diff --git a/AGENTS.md b/AGENTS.md index a3fee23..c1661b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -70,7 +70,7 @@ One directory per test under `tests/`, each an ordinary `main()` linking the lib - the foundations: Crypto, Text, Platform and Process; - Goldens: the pure pipeline against the recorded answers in `tests/Goldens/fixture`; - Runs: full runs end to end on a claude stand-in; -- Commands: init, doc, stop, seats, browser; +- Commands: init, doc, stop, wait, seats, browser, --version; - LensTools: every allowlisted program on PATH, strict inside the Flatpak build. Conventions: @@ -137,7 +137,7 @@ Conventions: - `progress.json` is written atomically, through a temporary file and a rename. - The `seats` API report says the ledger counts what "the review drivers" spent: every driver writes it. - In the Flatpak, a pass's `SHELL` is `/bin/bash` (Platform). -- **Commands beyond the gates**: `init`, `doc`, `browser install`, `stop`, and `--version`, which prints the home and the charters' sha256s (Commands). +- **Commands beyond the gates**: `init`, `doc`, `browser install`, `stop`, `wait`, and `--version`, which prints the home and the charters' sha256s (Commands). - **Order, not value:** `estimate.cacheWrite`'s last digit depends on the order the passes ran, because it is a float sum. - **A mode is an artifact kind plus the lenses it runs and its effort** (2026-11-01: `modes.` in the config, `Config::ModeOf`, `ModeNames`, `LensesOff(config, mode)`). The three kinds (`Plan::Kinds`: reply, series, commits) are modes of their own name; a mode of another name states its `kind`. The kind decides the partition and hash, the common text and run layer, the schemas, the disposition and reuse-key rules and what the CLI requires (`Run::Arguments::kind`, `Plan::IsKernelKind`); the mode decides which of the kind's lenses run (`Plan::KindLenses`, in the kind's gate order, `Plan::Gates`) and the effort (`modes..effort`, else the kind's default). Every lens is off until a mode lists it (2026-10-31, Jorijn: "all lenses off by default and opt in only"): `Config::Defaults()` runs no lens, while the template lists every lens of each kind at the kind's effort, to trim (Jorijn, 2026-11-01, on the populated template as the example: "looks good"; `init` says to trim); `lenses..run` is retired with a warning that says so; a lens of another kind, a name that is no lens, a lens listed twice and an unknown effort are config problems; `--mode` names any configured mode, the dump records `mode` and `kind`, and a reuse key carries no mode name, so a clean read bought in one mode counts in another of the same kind. The run lock, the run numbers and the dump names are the kind's (`--run-N.json`): one full run per hash across the modes of a kind, their rounds counting on together; the dump's `mode` says which ran (Config, CommitsMode, KernelModes). - **The commit-truth lens** (`repo-facts.md`, 2026-10-31): Gate 4, after the proofs, so the messages and documents are read once the code they describe has settled. Its block kinds are text, doc and slot: the message units keyed on their text, the base and the code up to their commit (`MessageDeps`); a documentation unit on its file, its normalised text, the base and the code of the whole range (`DocKeyParts`); a diffstat on its text alone; `whole:order` and `whole:absent` in slot passes of its own (a lens with no whole pass asks the slots named in its row; never stored). A documentation file's diff header and a part the commit writes nothing in are mechanical n/a. Budgets 60/40 for a text or doc block, 50/35 for a slot; one read. The owner's gate is 5. The other lenses' prompts, keys and plans are untouched (CommitsMode, CodeKeys, Runs, the Goldens' series and gates). @@ -165,6 +165,10 @@ Conventions: - A stop is handled exactly like SIGTERM, and it stays in force across gates. - Claiming a scratch dir drops a stale `stop`. - A process-group SIGTERM to the `setsid` launch reaches the driver; `flatpak kill` is the hard stop. +- **Wait.** `wait --artifact --hash ` reads the hash's run lock and the run's dump, never writes them: stopping it leaves the run alone (Commands, Runs). It is started before the run, so the run takes the lock after it began. + - The run it waits for is one a poll sees holding the lock, or one that names itself there - or clears the last run's identity from it - after the wait began: a run can take and leave the lock between two polls. A full run takes the lock before anything slow, clears the last run's identity from it (`RunLock`) and names itself there once it has its run number (`RunLock::WriteInfo`). One killed between taking the lock and clearing it (two consecutive calls) leaves the last run's identity, which a wait that saw it hold the lock reads as that run's; one that takes and leaves the lock unnamed where no run was named before is not seen. A run a preflight check stops before it takes the lock never shows - the check that refuses a second full run of a live hash among them, whose wait follows the live run. A test or dry run takes no lock and is not waited for. + - The run has ended once nobody holds the lock. `wait` reads the identity only then, under its probe's own hold, so it never reads a holder's rewrite in flight (`RunLock::AddInfo`) or a new holder's first instant, before it clears the last run's identity; should another run have taken the lock between two polls, the identity is that newer run's. `wait` then prints `State::Summary` of the dump of the run the identity names and exits with the code its verdict maps to, as `run`'s does: 3 with the message of a preflight check that stopped the run after it took the lock (`Main` adds it to the lock's identity, `RunLock::AddInfo`), 2 when the dump is missing or IN PROGRESS (killed before its end, or stopped before Gate 0 has set up its seats - a stop then ends the driver at once, as SIGTERM does) or when the run ended before it named itself, and 3 when it sees no run within `--appear`, naming the run the lock names, with its dump, its preflight message or its log. + - Every probe of the run lock is `State::ProbeRunLock` - `LockHolder`, a test or dry run's, is built on it: it opens the lock file (one it cannot open counts as none), takes the lock shared for an instant (`/proc/locks` hides another pid namespace's locks), reads a failure to take it as a holder, and reads the identity under that hold when nobody holds the lock. Probers never see each other, and `RunLock` tries for 200 ms before it counts a holder. - **gpg.** Only `xdg-run/gnupg/S.keyboxd` is exposed, so `%G?` verifies against the public keys and the agent stays out of reach. **Process lifetime.** diff --git a/README.md b/README.md index 19a12bb..c398d75 100644 --- a/README.md +++ b/README.md @@ -52,11 +52,12 @@ crafter-review config # edit .review-gates/config.json until it prints no ## Run a review ```bash -crafter-review freeze --slug # Gate 0: the checks, the export, the hash - and the run line +crafter-review freeze --slug # Gate 0: the checks, the export, the hash - and the wait and run lines +crafter-review wait … # the wait line freeze printed, in the background, first crafter-review run … # the line freeze printed (run-line.txt), from a detached shell ``` -Exit codes: 0 SEND-READY, 1 FIX FIRST, 2 run the same line again (INCOMPLETE, PARTIAL or CONFIRMING), 3 preflight. Every finding, note and coverage entry is in the dump, `gate-state/commits--run-.json`. `crafter-review stop --hash ` kills a run's passes and writes its dump. +Exit codes: 0 SEND-READY, 1 FIX FIRST, 2 run the same line again (INCOMPLETE, PARTIAL or CONFIRMING), 3 preflight. Every finding, note and coverage entry is in the dump, `gate-state/commits--run-.json`. `crafter-review stop --hash ` stops a run. A directory can review other repositories: `freeze --repo --out --worktree`, then the printed run line. The config, the seats and the records are the reviewing directory's. @@ -98,9 +99,10 @@ Gates run in order, and each must pass before the next starts. The owner is the | Command | | |---|---| | `init`, `config`, `doc` | set a repository up; the merged config and its problems; the shipped texts | -| `freeze` | Gate 0: the checks, the export, the hash, the run line; `--verify` at push time | +| `freeze` | Gate 0: the checks, the export, the hash, the wait and run lines; `--verify` at push time | | `run` | the gates of a mode (`--mode`); `--dry-run` launches nothing | | `stop` | stop a run: its passes are killed, the dump written | +| `wait` | waits in the background beside a detached run (AGENTS.md: Wait) | | `seats`, `slots` | every seat probed; how many stacks fit in free memory | | `browser install` | the Chromium the Playwright MCP server drives | | `sql`, `totp`, `inventory` | the helpers a lens runs; the partition of an artifact into units | diff --git a/implementations/Crafter.Review-Driver.cpp b/implementations/Crafter.Review-Driver.cpp index d9de552..23ba5c9 100644 --- a/implementations/Crafter.Review-Driver.cpp +++ b/implementations/Crafter.Review-Driver.cpp @@ -21,6 +21,7 @@ import :Seats; import :SeatPool; import :OpenCode; import :Run; +import :State; import std; namespace fs = std::filesystem; @@ -29,7 +30,7 @@ namespace Crafter::Review { namespace { constexpr std::string_view Usage = R"(usage: crafter-review [--config FILE] {run,freeze,slots,config} ... - crafter-review {seats,inventory,sql,totp,init,doc,browser,stop} ... + crafter-review {seats,inventory,sql,totp,init,doc,browser,stop,wait} ... crafter-review --version The pre-push review pipeline: adversarial lenses, one claude process per @@ -714,6 +715,148 @@ inventory unit, against a frozen commit range.)"; return 0; } + // ---- wait: a run's end, for the background beside a detached run --------------- + constexpr std::array WaitOptions = {{ + {"--artifact", true, "ARTIFACT", "the artifact the run reviews, as the run line names it", Kind::String, {}, true}, + {"--hash", true, "HASH", "the artifact hash, as the run line names it (its first 8 characters decide)", Kind::String, {}, true}, + {"--appear", true, "SECONDS", "how long to wait for a run of the hash to take its run lock (default 120)", Kind::Float}, + }}; + + // The dump of the run a lock identity names. + fs::path DumpOf(const fs::path& gateDir, std::string_view kind, std::string_view h8, const Json& info) { + return gateDir / std::format("{}-{}-run-{}.json", kind, h8, Dyn::Str(Dyn::Get(info, "run_n"))); + } + + // That run's final dump: null while it has none (live, or killed). + Json FinalDump(const fs::path& gateDir, std::string_view kind, std::string_view h8, const Json& info) { + if (!Dyn::Truthy(Dyn::Get(info, "run_n"))) return nullptr; + Json dump; + try { + dump = Dyn::LoadJsonFile(DumpOf(gateDir, kind, h8, info)); + } catch (const std::exception&) { + return nullptr; + } + const std::string overall = dump.is_object() ? Dyn::StrOr(Dyn::Get(dump, "overall"), "") : ""; + return overall.empty() || overall.starts_with("IN PROGRESS") ? Json(nullptr) : dump; + } + + // A run's end, as its run lock's identity and its dump record it: the + // summary `run` printed at its end and the run's exit code; 3 with the + // message of a preflight check that stopped it, 2 when it left no final + // dump. + std::int32_t ReportRun(const fs::path& gateDir, std::string_view kind, std::string_view h8, const Json& info) { + if (Dyn::Get(info, "preflight").is_string()) { + std::println("preflight: {}", Dyn::Str(info.at("preflight"))); + return 3; + } + if (!Dyn::Truthy(Dyn::Get(info, "run_n"))) { + std::println("wait: a run of {} took its run lock and ended before it named itself (killed or crashed)", h8); + return 2; + } + const Json dump = FinalDump(gateDir, kind, h8, info); + if (dump.is_null()) { + std::println("wait: run {} of {} ended without its final dump (killed or crashed); its log is {}", Dyn::Str(Dyn::Get(info, "run_n")), h8, + (fs::path(Dyn::StrOr(Dyn::Get(info, "scratch"), "")) / "log.txt").string()); + return 2; + } + const std::string overall = Dyn::Str(dump.at("overall")); + std::string summary; + try { + summary = State::Summary(dump); + } catch (const std::exception&) { + summary = std::format("overall: {}\ndump: {}", overall, DumpOf(gateDir, kind, h8, info).string()); + } + std::println("{}", summary); + if (overall == "SEND-READY") return 0; + return overall == "FIX FIRST" ? 1 : 2; + } + + std::int32_t WaitCommand(std::span args) { + constexpr std::string_view Prog = "crafter-review wait"; + const Parsed parsed = ParseOptions(args, WaitOptions); + if (parsed.help) { + std::print("{}", Help(Prog, + "once a run of an artifact hash that it has seen hold or take the run lock lets it go, print the summary of the final dump of the run " + "the lock names and exit with the code its verdict maps to (2 without a final dump, 3 with the message of a preflight check that stopped " + "it after it took the lock, or when it sees no run) - in the background, started before a detached `run`; a wait that is stopped " + "changes nothing: run it again", + WaitOptions)); + return 0; + } + if (!parsed.error.empty()) return UsageError(UsageLine(Prog, WaitOptions), Prog, parsed.error); + const fs::path artifact = parsed.Value("artifact").value_or(""); + const std::string h8 = parsed.Value("hash").value_or("").substr(0, 8); + double appear = 120; + if (const std::optional given = parsed.Value("appear")) { + appear = Dyn::ParseFloat(*given).value_or(-1); + if (!std::isfinite(appear) || appear < 0) return UsageError(UsageLine(Prog, WaitOptions), Prog, std::format("argument --appear: invalid seconds: {}", Dyn::Repr(*given))); + } + // The gate-state dir as `run` takes it: a reply's beside its file. + const fs::path gateDir = (fs::is_regular_file(artifact) ? artifact.parent_path() : artifact) / "gate-state"; + // The hash's run lock, of whichever kind's is there: a full run + // takes it before anything slow, clears the last run's identity + // from it and names itself there once it has its run number; the + // kernel releases it when the run's driver ends. + auto lockOf = [&]() -> std::optional> { + for (const std::string_view kind : Plan::Kinds) { + const fs::path path = State::LockPath(gateDir, kind, h8); + if (fs::exists(path)) return std::pair(std::string(kind), path); + } + return std::nullopt; + }; + auto same = [](const Json& l, const Json& r) { + return Dyn::Get(l, "pid") == Dyn::Get(r, "pid") && Dyn::Get(l, "since") == Dyn::Get(r, "since") && Dyn::Get(l, "run_n") == Dyn::Get(r, "run_n"); + }; + // The run to wait for: one a poll sees holding the lock, or one that + // names itself there - or clears the last run's identity from it - + // after the wait began (it can take and leave the lock between two + // polls). It has ended once nobody holds the lock: the identity, + // read only then, under the probe's own hold, is its - never a + // rewrite in flight, never a new holder's first instant. + std::optional> lock = lockOf(); + const std::optional first = lock ? State::ProbeRunLock(lock->second) : std::nullopt; + bool heldSeen = first && first->held; + const Json start = first && !first->held ? first->info : Json::object(); + // An identity a run wrote there since the wait began: a new one, or + // the last one cleared. + auto changed = [&](const Json& info) { + if (Dyn::Truthy(Dyn::Get(info, "pid"))) return !same(info, start); + return Dyn::Truthy(Dyn::Get(start, "pid")); + }; + const double deadline = Platform::Now() + appear; + constexpr auto Poll = std::chrono::seconds(2); + while (true) { + if (!lock) lock = lockOf(); + if (const std::optional now = lock ? State::ProbeRunLock(lock->second) : std::nullopt) { + if (now->held) { + heldSeen = true; + } else if (heldSeen || changed(now->info)) { + return ReportRun(gateDir, lock->first, h8, now->info); + } + } + if (!heldSeen && Platform::Now() > deadline) { + // The run the lock names ended before the wait began. + std::string late; + if (lock && Dyn::Truthy(Dyn::Get(start, "run_n"))) { + const std::string n = Dyn::Str(start.at("run_n")); + const fs::path dump = DumpOf(gateDir, lock->first, h8, start); + if (Dyn::Get(start, "preflight").is_string()) { + late = std::format("; the lock names run {}, which a preflight check stopped before this wait began: {}", n, Dyn::Str(start.at("preflight"))); + } else if (fs::exists(dump)) { + late = std::format("; the lock names run {}, which ended before this wait began: {}", n, dump.string()); + } else { + late = std::format("; the lock names run {}, which ended before this wait began without a dump: its log is {}", n, + (fs::path(Dyn::StrOr(Dyn::Get(start, "scratch"), "")) / "log.txt").string()); + } + } + std::println(std::cerr, "wait: no full run of {} seen at its run lock in {} within {} s - a run that stops at its preflight before it takes the lock never shows: its own output says why{}", + h8, gateDir.string(), std::format("{:g}", appear), late); + return 3; + } + std::this_thread::sleep_for(Poll); + } + } + // ---- doc: the texts the Flatpak ships ------------------------------------------------- constexpr std::array DocNames = {"prepush", "manifest", "config"}; constexpr std::array DocOptions = {{ @@ -1046,6 +1189,7 @@ inventory unit, against a frozen commit range.)"; if (command == "slots") return SlotsCommand(after, configPath); if (command == "seats") return SeatsCommand(after); if (command == "stop") return StopCommand(after); + if (command == "wait") return WaitCommand(after); if (command == "doc") return DocCommand(after); if (command == "browser") return BrowserCommand(after); if (command == "init") return InitCommand(after); diff --git a/implementations/Crafter.Review-Freeze.cpp b/implementations/Crafter.Review-Freeze.cpp index a1dc4b5..bea6961 100644 --- a/implementations/Crafter.Review-Freeze.cpp +++ b/implementations/Crafter.Review-Freeze.cpp @@ -422,6 +422,10 @@ namespace Crafter::Review::Freeze { Dyn::Str(Dyn::At(report, "base")), trees, Dyn::JoinPath(Dyn::JoinPath(outRel, "gate-state"), "dispositions.json"), Dyn::Str(Dyn::At(report, "date"))); } + std::string WaitLine(const Json& report, std::string_view outRel) { + return std::format("{} wait --artifact {} --hash {}", Invocation(), outRel, Dyn::Slice(Dyn::Str(Dyn::At(report, "hash")), 0, 8)); + } + std::string TreeOf(const Json& record, const fs::path& cwd) { const Json& worktree = Dyn::Get(record, "worktree"); if (Dyn::Truthy(worktree)) return Dyn::Str(worktree); @@ -492,7 +496,8 @@ namespace Crafter::Review::Freeze { std::println("hash: {}", report.at("hash").get()); const std::string line = RunLine(report, rel, TreeOf(report, cwd)); std::ofstream(fs::path(report.at("out").get()) / "run-line.txt", std::ios::binary) << line << "\n"; - std::println("run (from the repository root, in a detached background shell; also in {}):\n {}", Dyn::JoinPath(rel, "run-line.txt"), line); + std::println("first the wait, in the background:\n {}", WaitLine(report, rel)); + std::println("then the run, from the repository root, detached - `setsid nohup > 2>&1 < /dev/null &` (also in {}):\n {}", Dyn::JoinPath(rel, "run-line.txt"), line); return 0; } } diff --git a/implementations/Crafter.Review-Run.cpp b/implementations/Crafter.Review-Run.cpp index 62b28c5..a050fc9 100644 --- a/implementations/Crafter.Review-Run.cpp +++ b/implementations/Crafter.Review-Run.cpp @@ -2466,6 +2466,8 @@ namespace Crafter::Review::Run { } catch (const Preflight& e) { std::println(std::cerr, "preflight: {}", e.what()); code = 3; + // Once the run lock names this run, `wait` reads the stop there. + if (run.runLock) run.runLock->AddInfo("preflight", e.what()); } watcher.request_stop(); watcher.join(); diff --git a/implementations/Crafter.Review-State.cpp b/implementations/Crafter.Review-State.cpp index a2fff19..355fe8b 100644 --- a/implementations/Crafter.Review-State.cpp +++ b/implementations/Crafter.Review-State.cpp @@ -155,12 +155,25 @@ namespace Crafter::Review::State { const fs::path path = LockPath(gateDir, mode, hash8); fd = open(path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644); if (fd < 0) throw std::runtime_error(std::format("{}: {}", Dyn::ErrnoText(errno), Dyn::Repr(std::string_view(path.string())))); - if (flock(fd, LOCK_EX | LOCK_NB) != 0) { + bool locked = flock(fd, LOCK_EX | LOCK_NB) == 0; + for (std::int32_t attempt = 0; !locked && attempt < 20; ++attempt) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + locked = flock(fd, LOCK_EX | LOCK_NB) == 0; + } + if (!locked) { const Json info = ReadLockInfo(path); close(fd); fd = -1; throw RunLocked(Describe(info)); } + // The last run's identity is not this run's: until it names itself, + // the holder reads as one that has just started. + if (ftruncate(fd, 0) != 0) { + const std::int32_t failure = errno; + close(fd); + fd = -1; + throw std::runtime_error(std::format("{}: {}", Dyn::ErrnoText(failure), Dyn::Repr(std::string_view(path.string())))); + } } RunLock::~RunLock() { @@ -168,6 +181,7 @@ namespace Crafter::Review::State { } void RunLock::WriteInfo(const Json& info) { + written = info; const std::string text = DumpSpaced(info); if (lseek(fd, 0, SEEK_SET) < 0 || ftruncate(fd, 0) != 0) return; std::size_t written = 0; @@ -181,18 +195,34 @@ namespace Crafter::Review::State { } } - std::optional LockHolder(const fs::path& gateDir, std::string_view mode, std::string_view hash8) { - const fs::path path = LockPath(gateDir, mode, hash8); + void RunLock::AddInfo(std::string_view key, const Json& value) { + if (!written.is_object()) return; + Json info = written; + info[std::string(key)] = value; + WriteInfo(info); + } + + std::optional ProbeRunLock(const fs::path& path) { const std::int32_t handle = open(path.c_str(), O_RDONLY | O_CLOEXEC); if (handle < 0) return std::nullopt; - std::optional holder; - if (flock(handle, LOCK_EX | LOCK_NB) == 0) { + // Shared, for an instant: two probers never see each other, and a + // starting run tries its exclusive lock for 200 ms (RunLock). + LockState state; + if (flock(handle, LOCK_SH | LOCK_NB) == 0) { + state.info = ReadLockInfo(path); flock(handle, LOCK_UN); } else { - holder = ReadLockInfo(path); + state.held = true; + state.info = ReadLockInfo(path); } close(handle); - return holder; + return state; + } + + std::optional LockHolder(const fs::path& gateDir, std::string_view mode, std::string_view hash8) { + const std::optional state = ProbeRunLock(LockPath(gateDir, mode, hash8)); + if (!state || !state->held) return std::nullopt; + return state->info; } std::int64_t NextRunNumber(const fs::path& gateDir, std::string_view mode, std::string_view hash8) { diff --git a/interfaces/Crafter.Review-Freeze.cppm b/interfaces/Crafter.Review-Freeze.cppm index f4f5faa..9666a78 100644 --- a/interfaces/Crafter.Review-Freeze.cppm +++ b/interfaces/Crafter.Review-Freeze.cppm @@ -77,6 +77,8 @@ export namespace Crafter::Review::Freeze { // The exact `run` command for a freeze report: built from its fields, never // retyped (2026-09-29). std::string RunLine(const Json& report, std::string_view outRel, std::string_view trees); + // The `wait` command beside it, from the same fields. + std::string WaitLine(const Json& report, std::string_view outRel); // The tree the lenses read for a frozen artifact, as its record says: the // worktree (relative to the directory freeze ran from), else the // repository when it is not `cwd`, else `.`. diff --git a/interfaces/Crafter.Review-State.cppm b/interfaces/Crafter.Review-State.cppm index 4b457da..25e6886 100644 --- a/interfaces/Crafter.Review-State.cppm +++ b/interfaces/Crafter.Review-State.cppm @@ -49,7 +49,9 @@ export namespace Crafter::Review::State { // unlink and re-create would hand two drivers one hash. class RunLock { public: - // Throws RunLocked naming the holder. + // Throws RunLocked naming the holder. A probe holds the lock shared + // for an instant (LockHolder): it is tried for 200 ms first. Taken, + // it clears the last run's identity. RunLock(const std::filesystem::path& gateDir, std::string_view mode, std::string_view hash8); ~RunLock(); RunLock(const RunLock&) = delete; @@ -57,13 +59,27 @@ export namespace Crafter::Review::State { // The holder's identity, once it knows its run number: one JSON // document, truncated and rewritten. void WriteInfo(const Json& info); + // One more field in the identity last written (a preflight check's + // message, for `wait`); nothing before the identity is written. + void AddInfo(std::string_view key, const Json& value); private: std::int32_t fd = -1; + Json written; }; - // Who holds this hash's run lock ({} while the holder has not written - // itself yet), nullopt when nobody does: a test or dry run takes no lock - // but numbers its scratch dir past a live holder. + // The run lock at `path` as one probe sees it, nullopt when the file + // cannot be opened (there is none): taken shared for an instant (a failure + // to take it reads as held), and the identity - read under that hold when + // nobody holds the lock, so no holder can be rewriting it then. + struct LockState { + bool held = false; + Json info = Json::object(); + }; + std::optional ProbeRunLock(const std::filesystem::path& path); + // Who holds this hash's run lock - its identity, {} from its clearing of + // the last run's until it names itself - nullopt when nobody does + // (ProbeRunLock): a test or dry run takes no lock but numbers its scratch + // dir past a live holder. std::optional LockHolder(const std::filesystem::path& gateDir, std::string_view mode, std::string_view hash8); std::int64_t NextRunNumber(const std::filesystem::path& gateDir, std::string_view mode, std::string_view hash8); diff --git a/packaging/flatpak/net.catcrafts.CrafterReview.metainfo.xml b/packaging/flatpak/net.catcrafts.CrafterReview.metainfo.xml index d423f8a..ebebc79 100644 --- a/packaging/flatpak/net.catcrafts.CrafterReview.metainfo.xml +++ b/packaging/flatpak/net.catcrafts.CrafterReview.metainfo.xml @@ -27,6 +27,14 @@ + + +

New

+
    +
  • crafter-review wait waits in the background beside a detached review run. The /prepush skill runs it there, so the session hears when a review ends. Run crafter-review init again to refresh a repository's skill.
  • +
+
+

New

diff --git a/process/prepush.md b/process/prepush.md index f571fad..c649246 100644 --- a/process/prepush.md +++ b/process/prepush.md @@ -285,11 +285,20 @@ under the 99 % cutoff — at most 128 passes per account, every driver's counted (`REVIEW_GATES_OAUTH_CONCURRENCY`), and a pass launches only when its environment's instrument is free and it fits in free memory (How the passes share the stacks): the driver logs per gate -how many passes of each environment memory and the stacks allow. Run -from the repository root in a detached background shell (`setsid nohup … &` — -a launch bound to a tool call's timeout dies with it) and poll -`~/.cache/review-gates/-run-/progress.json`; `freeze` prints the -exact line and writes it to `run-line.txt` — launch from that file verbatim, +how many passes of each environment memory and the stacks allow. Start +the `wait` line freeze prints first, in Claude Code's background mode +(`run_in_background`), then run the run line from the repository root in a +detached background shell (`setsid nohup … > 2>&1 < /dev/null &` — a +launch bound to a tool call's timeout dies with it). Once a run it has seen +hold or take the hash's run lock lets it go, the wait prints the summary of +the final dump of the run the lock names, so the harness reports the end. A +run a preflight check stops before it takes the lock - the check that refuses +a second full run of a live hash among them - never shows: the wait then +follows the live run, or exits 3 after `--appear` (120 s), and the launch's +`` says why. A wait that is stopped can run again without touching the +run; `~/.cache/review-gates/-run-/progress.json` shows a run in +progress. `freeze` prints both lines and writes the run's to +`run-line.txt` — launch from that file verbatim, never retyped (2026-09-29: a hand-copied base cut at 120 columns did not resolve and nobody noticed for a round). @@ -328,8 +337,12 @@ even though the driver calls it full: say so in the manifest. Exit 0 SEND-READY = **push-ready**; 1 FIX FIRST; 2 INCOMPLETE / PARTIAL / CONFIRMING (gates clean, code units still owe clean reads — run the same line -again, see "Three clean reads"); 3 preflight. A whole pass gates its block -passes; coverage is fail-closed per inventory unit (`inventory commits`: +again, see "Three clean reads"); 3 preflight. `wait`'s exit code maps the +reported run's verdict as `run`'s does: 2 for one that left no final dump, 3 +for one a preflight check stopped after it took the run lock, and 3 when it +sees no run. A +whole pass gates its block passes; coverage is fail-closed per inventory +unit (`inventory commits`: `pK:subject`, `pK:msg`, `pK:diffstat`, `pK:#hdr`, `pK:#H`, `pK:outside`, `pK:absent`, `whole:order`, `whole:absent`, `whole:behaviour`); per-unit reuse across hashes, salvage of finished diff --git a/process/skill/prepush/SKILL.md b/process/skill/prepush/SKILL.md index 84d28b7..5114a3d 100644 --- a/process/skill/prepush/SKILL.md +++ b/process/skill/prepush/SKILL.md @@ -24,8 +24,8 @@ of running it: ``` It refuses on any failed check — fix the commits, never the check. It - prints the hash and the exact run command, also in - `.review-gates/push//run-line.txt`. + prints the hash, the wait line and the exact run command, the run command + also in `.review-gates/push//run-line.txt`. 3. **The application and the database under test** (when a lens that runs has the browser — `browser`, `browser+supabase`; the functional lens by default — or the database — `supabase`, `browser+supabase`; nothing to @@ -47,9 +47,19 @@ of running it: `supabase.dbUrl` does not answer or its applied migrations are not HEAD's: reset the stack from the frozen tree, after every `freeze --replace` too. Do not edit that tree while the run is on. -4. **Gates 1–4**: run the printed command from the repository root in a - detached background shell (`setsid nohup … > 2>&1 < /dev/null &`); - poll `~/.cache/review-gates/-run-/progress.json` and `log.txt`. +4. **Gates 1–4**: first run the wait line freeze printed + (`flatpak run net.catcrafts.CrafterReview wait --artifact … --hash …`) in + the background (the Bash tool's `run_in_background`), then launch the run + line from the repository root detached, so no tool call's timeout ends it + (`setsid nohup … > 2>&1 < /dev/null &`). Once a run it has seen hold + or take the hash's run lock lets it go, the wait prints the summary of the + final dump of the run the lock names, so the harness's notice of its end + is a run's. A run a preflight check stops before it takes the lock (a + `--context-paths` that does not exist, a second run of a live hash) never + shows: the wait then exits 3 after `--appear` (120 s), or follows the live + run, and the launch's `` says why. A wait that is stopped leaves the + run alone: run it again; one started after the run's end exits 3 naming + the run the lock names. Add `--context-paths` for the evidence dirs the messages' claims rest on. To stop a run: `flatpak run net.catcrafts.CrafterReview stop ` (the last word of its gate-0 log), never a kill of a pid — inside @@ -57,7 +67,9 @@ of running it: FIRST / 2 INCOMPLETE, PARTIAL or CONFIRMING (gates clean, static code units still owe clean reads of 3 — run the SAME command again on the same hash, it is the next round, until SEND-READY) / 3 preflight; the dump path is - the last stdout line. + the last stdout line. The wait's exit code maps the reported run's verdict + as `run`'s does: 2 for one that left no final dump, 3 for one a preflight + check stopped after it took the run lock, and 3 when it sees no run. 5. **On FIX FIRST** — per undischarged finding exactly one disposition (prepush.md §Verdicts): FIX it (amend/rebase the commit in another worktree, `freeze --replace` into the same dir, restart the application diff --git a/tests/Commands/main.cpp b/tests/Commands/main.cpp index b3577a1..8101690 100644 --- a/tests/Commands/main.cpp +++ b/tests/Commands/main.cpp @@ -5,8 +5,12 @@ // refreshes, keeps what it did not write, replaces the old link into the // submodule, refuses a foreign link, a subdirectory and the home directory // before it writes anything), doc, stop (a scratch dir, --hash on the -// board), seats on a claude stand-in, and browser's usage. +// board), --version, wait (a run's end at the hash's run lock), seats on a +// claude stand-in, and browser's usage. +#include +#include +#include #include import std; import Crafter.Review; @@ -66,7 +70,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"ok","total } std::int32_t Checks() { - std::println("commands: init, doc, stop, seats on a claude stand-in, browser's usage"); + std::println("commands: init, doc, stop, --version, wait, seats on a claude stand-in, browser's usage"); Platform::SetMode(Platform::Mode::Native); const fs::path checkout = fs::current_path(); SetHome(checkout); @@ -316,6 +320,265 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"ok","total Check("stop --hash: every live run of the hash on the board gets its stop file (the first 8 characters decide); another hash finds none (exit 1); the board is read, never written", byHash.returnCode == 0 && wroteHash && otherHash.returnCode == 1 && otherHash.err.contains("no live run of 00000000 on the board") && Read(base / "board.json") == boardBefore, byHash.out + byHash.err + otherHash.err); + // --version: the driver, the home, every charter's sha256. + const Process::Captured version = Self({"--version"}, base); + std::int64_t charters = 0; + bool chartersHashed = true; + for (const fs::directory_entry& entry : fs::directory_iterator(checkout / "process" / "lenses")) { + if (entry.path().extension() != ".md") continue; + ++charters; + chartersHashed = chartersHashed && version.out.contains(std::format("charter {} {}\n", entry.path().filename().string(), Sha256Hex(Read(entry.path())))); + } + Check("--version: the home and every charter's sha256", version.returnCode == 0 && version.out.contains(std::format("home {}\n", checkout.string())) && charters > 0 && chartersHashed, + version.out); + // wait (1.2.0): a run's end, for the background beside a detached + // run, read from the hash's run lock and the run's dump. This process + // stands in for the run's driver on a thread while the wait runs: it + // holds the lock, names a run in it, writes the dump, lets the lock go. + auto artifactOf = [&](std::string_view name) { + const fs::path art = base / "waits" / name; + fs::create_directories(art / "gate-state"); + return art; + }; + auto dumpOf = [](std::string_view h8, std::int64_t n, std::string_view overall) { + return Json {{"overall", overall}, {"results", Json::array()}, {"dumpPath", std::format("gate-state/commits-{}-run-{}.json", h8, n)}}; + }; + auto identity = [&](std::int64_t n) { + return Json {{"pid", 4242}, {"since", std::format("2026-11-02T22:00:0{}", n)}, {"scratch", (base / "scratch" / std::format("x-run-{}", n)).string()}, {"run_n", n}}; + }; + auto waitOn = [&](const fs::path& art, std::string_view hash, std::vector extra = {}) { + std::vector argv = {"wait", "--artifact", art.string(), "--hash", std::string(hash)}; + std::ranges::move(extra, std::back_inserter(argv)); + return Self(argv, base); + }; + // A run live when the wait begins, ending with its final dump. + const fs::path artA = artifactOf("a"); + const Json dumpA = dumpOf("beefa001", 1, "SEND-READY"); + auto lockA = std::make_unique(artA / "gate-state", "commits", "beefa001"); + lockA->WriteInfo(identity(1)); + std::jthread endA([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(2500)); + Write(artA / "gate-state" / "commits-beefa001-run-1.json", DumpFile(dumpA)); + lockA.reset(); + }); + const double startA = Platform::Now(); + const Process::Captured ended = waitOn(artA, "beefa001ffff"); + const double waitedA = Platform::Now() - startA; + endA.join(); + // A run whose lock goes without its final dump (killed). + const fs::path artB = artifactOf("b"); + Write(artB / "gate-state" / "commits-beefb002-run-1.json", DumpFile(dumpOf("beefb002", 1, "IN PROGRESS - after Gate 1 — Approach"))); + auto lockB = std::make_unique(artB / "gate-state", "commits", "beefb002"); + lockB->WriteInfo(identity(1)); + std::jthread endB([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(1500)); + lockB.reset(); + }); + const Process::Captured killed = waitOn(artB, "beefb002"); + endB.join(); + // A run a preflight check stops after it took the lock. + const fs::path artC = artifactOf("c"); + auto lockC = std::make_unique(artC / "gate-state", "commits", "beefc003"); + lockC->WriteInfo(identity(1)); + std::jthread endC([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(1500)); + lockC->AddInfo("preflight", "no lens runs: --without drops all"); + lockC.reset(); + }); + const Process::Captured stopped = waitOn(artC, "beefc003"); + endC.join(); + // Run 1 ended before the wait began; a new holder takes the lock and + // names itself only a poll later - the wait follows run 2, not run 1. + const fs::path artD = artifactOf("d"); + { + State::RunLock first(artD / "gate-state", "commits", "beefd004"); + first.WriteInfo(identity(1)); + } + Write(artD / "gate-state" / "commits-beefd004-run-1.json", DumpFile(dumpOf("beefd004", 1, "FIX FIRST"))); + const Json dumpD2 = dumpOf("beefd004", 2, "SEND-READY"); + std::jthread runD([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + State::RunLock second(artD / "gate-state", "commits", "beefd004"); + std::this_thread::sleep_for(std::chrono::milliseconds(2500)); + second.WriteInfo(identity(2)); + std::this_thread::sleep_for(std::chrono::milliseconds(2500)); + Write(artD / "gate-state" / "commits-beefd004-run-2.json", DumpFile(dumpD2)); + }); + const Process::Captured newer = waitOn(artD, "beefd004", {"--appear", "10"}); + runD.join(); + // A wait that begins just after a new holder took the lock, before it + // names itself: the lock no longer names the last run (killed, its dump + // IN PROGRESS), and the new run is followed. + const fs::path artE = artifactOf("e"); + { + State::RunLock first(artE / "gate-state", "commits", "beefe005"); + first.WriteInfo(identity(1)); + } + Write(artE / "gate-state" / "commits-beefe005-run-1.json", DumpFile(dumpOf("beefe005", 1, "IN PROGRESS - after Gate 1 — Approach"))); + auto lockE = std::make_unique(artE / "gate-state", "commits", "beefe005"); + const Json dumpE2 = dumpOf("beefe005", 2, "SEND-READY"); + std::jthread runE([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(2500)); + lockE->WriteInfo(identity(2)); + std::this_thread::sleep_for(std::chrono::milliseconds(2500)); + Write(artE / "gate-state" / "commits-beefe005-run-2.json", DumpFile(dumpE2)); + lockE.reset(); + }); + const Process::Captured fresh = waitOn(artE, "beefe005", {"--appear", "10"}); + runE.join(); + // The instant before a new holder clears the identity, held by a bare + // flock: the lock still names the last run, killed (its dump IN + // PROGRESS) - not that run; the new one is reported once it ends. + const fs::path artG = artifactOf("g"); + { + State::RunLock first(artG / "gate-state", "commits", "beef9006"); + first.WriteInfo(identity(1)); + } + Write(artG / "gate-state" / "commits-beef9006-run-1.json", DumpFile(dumpOf("beef9006", 1, "IN PROGRESS - after Gate 1 — Approach"))); + const fs::path lockG = State::LockPath(artG / "gate-state", "commits", "beef9006"); + const std::int32_t bare = open(lockG.c_str(), O_RDWR | O_CLOEXEC); + const bool bareHeld = bare >= 0 && flock(bare, LOCK_EX | LOCK_NB) == 0; + const Json dumpG2 = dumpOf("beef9006", 2, "SEND-READY"); + std::jthread runG([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(2500)); + Write(lockG, DumpFile(identity(2))); + std::this_thread::sleep_for(std::chrono::milliseconds(2500)); + Write(artG / "gate-state" / "commits-beef9006-run-2.json", DumpFile(dumpG2)); + close(bare); + }); + const Process::Captured notLast = waitOn(artG, "beef9006", {"--appear", "10"}); + runG.join(); + Check("wait: begun just after a new holder took the lock, it follows the new run - the lock no longer names the last one (killed)", + fresh.returnCode == 0 && fresh.out == std::format("{}\n", State::Summary(dumpE2)), fresh.out + fresh.err); + Check("wait: a held lock still naming the last run, killed - a new holder's instant before it clears the identity - is not that run: the new one is reported once it ends", + bareHeld && notLast.returnCode == 0 && notLast.out == std::format("{}\n", State::Summary(dumpG2)), notLast.out + notLast.err); + // A run rewriting its identity while it holds the lock - here held + // empty across a poll, as in the instant inside AddInfo's rewrite - is + // read only once nobody holds the lock: its preflight message, exit 3. + const fs::path artT = artifactOf("t"); + auto lockT = std::make_unique(artT / "gate-state", "commits", "beef7007"); + lockT->WriteInfo(identity(1)); + const fs::path lockPathT = State::LockPath(artT / "gate-state", "commits", "beef7007"); + std::jthread endT([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + Write(lockPathT, ""); + std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + lockT->AddInfo("preflight", "the application does not answer"); + lockT.reset(); + }); + const Process::Captured rewritten = waitOn(artT, "beef7007"); + endT.join(); + Check("wait: a run whose identity is mid-rewrite while it holds the lock (here empty across a poll) is read once nobody holds it - its preflight message, exit 3", + rewritten.returnCode == 3 && rewritten.out == "preflight: the application does not answer\n", rewritten.out + rewritten.err); + // A run that takes the lock after the wait began and leaves it between + // two polls without naming itself: seen by the identity it cleared, + // exit 2. + const fs::path artU = artifactOf("u"); + { + State::RunLock first(artU / "gate-state", "commits", "beef8008"); + first.WriteInfo(identity(1)); + } + Write(artU / "gate-state" / "commits-beef8008-run-1.json", DumpFile(dumpOf("beef8008", 1, "FIX FIRST"))); + std::jthread runU([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(1500)); + const State::RunLock unnamed(artU / "gate-state", "commits", "beef8008"); + }); + const Process::Captured unnamedRun = waitOn(artU, "beef8008", {"--appear", "10"}); + runU.join(); + Check("wait: a run that takes the lock after the wait began and leaves it between two polls unnamed is seen by the identity it cleared - exit 2", + unnamedRun.returnCode == 2 && unnamedRun.out.contains("took its run lock and ended before it named itself"), unnamedRun.out + unnamedRun.err); + // A wait started after a run a preflight check stopped: the lock names + // that run and the check's message. + const fs::path artV = artifactOf("v"); + { + State::RunLock stopped(artV / "gate-state", "commits", "beef9009"); + stopped.WriteInfo(identity(1)); + stopped.AddInfo("preflight", "no lens runs: --without drops all"); + } + const Process::Captured latePreflight = waitOn(artV, "beef9009", {"--appear", "0"}); + Check("wait: started after a run a preflight check stopped, it exits 3 naming that run and the check's message", + latePreflight.returnCode == 3 + && latePreflight.err.contains("the lock names run 1, which a preflight check stopped before this wait began: no lens runs: --without drops all"), + latePreflight.err); + // A wait started after a run that ended without a dump: the lock names + // that run and its log. + const fs::path artW = artifactOf("w"); + { + State::RunLock nodump(artW / "gate-state", "commits", "beefa010"); + nodump.WriteInfo(identity(1)); + } + const Process::Captured lateNoDump = waitOn(artW, "beefa010", {"--appear", "0"}); + Check("wait: started after a run that ended without a dump, it exits 3 naming that run and its log", + lateNoDump.returnCode == 3 + && lateNoDump.err.contains(std::format("the lock names run 1, which ended before this wait began without a dump: its log is {}", + (base / "scratch" / "x-run-1" / "log.txt").string())), + lateNoDump.err); + // A run that ends CONFIRMING: its summary, exit 2 - a round to run + // again, as run's code says. + const fs::path artY = artifactOf("y"); + const Json dumpY = dumpOf("beefc012", 1, "CONFIRMING - NOT SEND-READY (gates clean; 2 code unit(s) owe 3 clean read(s) to reach 3: run the same line again)"); + auto lockY = std::make_unique(artY / "gate-state", "commits", "beefc012"); + lockY->WriteInfo(identity(1)); + std::jthread endY([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(1500)); + Write(artY / "gate-state" / "commits-beefc012-run-1.json", DumpFile(dumpY)); + lockY.reset(); + }); + const Process::Captured confirming = waitOn(artY, "beefc012"); + endY.join(); + Check("wait: a run whose final dump is CONFIRMING - its summary, exit 2, the code run gives it", + confirming.returnCode == 2 && confirming.out == std::format("{}\n", State::Summary(dumpY)), confirming.out + confirming.err); + // A wait only reads: stopped while its run is live, it leaves the lock + // and its identity as they were, a wait started again reports the run, + // and a wait leaves the lock file and the dump byte for byte as found. + const fs::path artK = artifactOf("k"); + auto lockK = std::make_unique(artK / "gate-state", "commits", "beefb011"); + lockK->WriteInfo(identity(1)); + const fs::path lockPathK = State::LockPath(artK / "gate-state", "commits", "beefb011"); + const std::string identityK = Read(lockPathK); + const Process::Child stoppedWait = Process::Start({.argv = {Platform::SelfExe().string(), "wait", "--artifact", artK.string(), "--hash", "beefb011"}, + .environment = Env, + .cwd = base, + .input = {.kind = Process::Stream::Kind::Null}, + .output = {.kind = Process::Stream::Kind::File, .file = base / "stopped-wait.out"}, + .error = {.kind = Process::Stream::Kind::File, .file = base / "stopped-wait.err"}}); + std::this_thread::sleep_for(std::chrono::milliseconds(2500)); + Process::Signal(stoppedWait.pid, SIGKILL); + const std::optional stoppedCode = Process::Wait(stoppedWait.pid, std::chrono::seconds(10)); + const bool untouched = Read(lockPathK) == identityK && State::LockHolder(artK / "gate-state", "commits", "beefb011").has_value(); + const Json dumpK = dumpOf("beefb011", 1, "SEND-READY"); + std::jthread endK([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(1500)); + Write(artK / "gate-state" / "commits-beefb011-run-1.json", DumpFile(dumpK)); + lockK.reset(); + }); + const Process::Captured restarted = waitOn(artK, "beefb011"); + endK.join(); + const std::string lockBytes = Read(lockPathK); + const std::string dumpBytes = Read(artK / "gate-state" / "commits-beefb011-run-1.json"); + const Process::Captured readsOnly = waitOn(artK, "beefb011", {"--appear", "0"}); + Check("wait: stopped while its run is live, it leaves the lock and its identity as they were; one started again reports the run; a wait writes neither the lock file nor the dump", + stoppedCode.has_value() && untouched && restarted.returnCode == 0 && restarted.out == std::format("{}\n", State::Summary(dumpK)) && readsOnly.returnCode == 3 + && Read(lockPathK) == lockBytes && Read(artK / "gate-state" / "commits-beefb011-run-1.json") == dumpBytes, + restarted.out + restarted.err + readsOnly.err); + // A wait started after its run's end, and one no run ever shows for. + const Process::Captured late = waitOn(artD, "beefd004", {"--appear", "0"}); + const Process::Captured noRun = waitOn(artifactOf("f"), "00000000", {"--appear", "0"}); + const Process::Captured noArtifact = Self({"wait", "--hash", "00000000"}, base); + const Process::Captured badAppear = waitOn(artifactOf("f"), "00000000", {"--appear=-1"}); + Check("wait: a run live when it begins - its summary as `run` prints it from the dump, its exit code, once the lock goes", + ended.returnCode == 0 && ended.out == std::format("{}\n", State::Summary(dumpA)) && waitedA > 2.0, std::format("{} {:.1f}s", ended.out + ended.err, waitedA)); + Check("wait: a run whose lock goes without its final dump (killed) exits 2 naming its log; one a preflight check stopped after the lock, 3 with the message", + killed.returnCode == 2 && killed.out.contains("ended without its final dump") && killed.out.contains((base / "scratch" / "x-run-1" / "log.txt").string()) + && stopped.returnCode == 3 && stopped.out == "preflight: no lens runs: --without drops all\n", + killed.out + killed.err + stopped.out + stopped.err); + Check("wait: a new holder that has not named itself is not the run the lock still names - the run it then names is followed", + newer.returnCode == 0 && newer.out == std::format("{}\n", State::Summary(dumpD2)), newer.out + newer.err); + Check("wait: started after its run's end it exits 3 naming that run's dump; no run, exit 3; no --artifact or a negative --appear is a usage error (3)", + late.returnCode == 3 && late.err.contains(std::format("ended before this wait began: {}", (artD / "gate-state" / "commits-beefd004-run-2.json").string())) && noRun.returnCode == 3 + && noRun.err.contains("no full run of 00000000 seen at its run lock") && noArtifact.returnCode == 3 && noArtifact.err.contains("the following arguments are required: --artifact") + && badAppear.returnCode == 3 && badAppear.err.contains("invalid seconds"), + late.err + noRun.err + noArtifact.err + badAppear.err); // Only `run` and `seats` read the seats file, and its lines reach the // placement readers alone (rounds 8 and 11 of the self-review): a // `stop` with the board path only in the working directory's .env diff --git a/tests/Drivers/main.cpp b/tests/Drivers/main.cpp index e2696af..976bc80 100644 --- a/tests/Drivers/main.cpp +++ b/tests/Drivers/main.cpp @@ -10,8 +10,10 @@ // stand until it dies; two drivers recording into one memory file are two // runs of this binary (`--record`). +#include #include #include +#include #include import std; import Crafter.Review; @@ -436,6 +438,27 @@ namespace { Check("run lock: another hash is free; nobody holds an untaken one", takes("ffff0000") && !State::LockHolder(gd, "commits", "00000000")); f.reset(); Check("run lock: released on close (the kernel releases it on death the same way)", !State::LockHolder(gd, "commits", "abcd1234") && takes("abcd1234")); + { + // Taken again, the lock no longer names the last run. + const State::RunLock again(gd, "commits", "abcd1234"); + const std::optional holder = State::LockHolder(gd, "commits", "abcd1234"); + Check("run lock: taken again, it clears the last run's identity - its holder reads as not named yet", holder && *holder == Json::object(), + holder ? holder->dump() : std::string("no holder")); + } + { + // A probe takes the lock shared for an instant: another prober's + // is no holder, and a starting run waits it out. + const std::int32_t probe = open(State::LockPath(gd, "commits", "abcd1234").c_str(), O_RDONLY | O_CLOEXEC); + const bool shared = probe >= 0 && flock(probe, LOCK_SH | LOCK_NB) == 0; + const bool seenFree = !State::LockHolder(gd, "commits", "abcd1234"); + std::jthread release([probe] { + std::this_thread::sleep_for(50ms); + close(probe); + }); + const bool started = takes("abcd1234"); + release.join(); + Check("run lock: a probe's instant shared lock is no holder to another probe, and a starting run waits it out", shared && seenFree && started); + } // unit-state merge-on-write const fs::path sp = td / "unit-state.json"; diff --git a/tests/Freeze/main.cpp b/tests/Freeze/main.cpp index 930b959..38f5950 100644 --- a/tests/Freeze/main.cpp +++ b/tests/Freeze/main.cpp @@ -123,6 +123,8 @@ int main() { const std::string line = Freeze::RunLine(r1, "out", "."); Check("run line: built from the report, names the hash, the base, the tree and the register", line.starts_with(std::format("{} run --artifact out --hash {}", Invocation(), r1.at("hash").get())) && line.contains(std::format("--base {}", base)) && line.contains("--trees .") && line.contains("out/gate-state/dispositions.json")); + Check("wait line: built from the report, the invocation's, names the artifact and the hash's first 8 characters", + Freeze::WaitLine(r1, "out") == std::format("{} wait --artifact out --hash {}", Invocation(), r1.at("hash").get().substr(0, 8)), Freeze::WaitLine(r1, "out")); const Json r2 = freeze({.base = base, .replace = true, .worktree = true}); const fs::path wt = td / Dyn::Str(Dyn::Get(r2, "worktree")); Check("--worktree checks out HEAD detached under .review-gates/trees", r2.at("ok").get() && r2.at("worktree").get().starts_with(std::format("{}/r-", Freeze::Worktrees)) diff --git a/tests/Runs/main.cpp b/tests/Runs/main.cpp index 622cc35..34b4df1 100644 --- a/tests/Runs/main.cpp +++ b/tests/Runs/main.cpp @@ -229,6 +229,20 @@ echo "{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"result\" } const std::string hash = freezeJson.at("hash").get(); const std::string h8 = hash.substr(0, 8); + // The wait line freeze prints, before the run line: Freeze::WaitLine's, + // the invocation this binary's path (main() runs every child native). + // Every wait below starts from it, as the skill does. + const std::string waitMark = "first the wait, in the background:\n "; + const std::size_t waitAt = frozen.out.find(waitMark); + const std::size_t runAt = frozen.out.find("then the run,"); + std::string printedWait; + if (waitAt != std::string::npos) { + const std::size_t from = waitAt + waitMark.size(); + printedWait = frozen.out.substr(from, frozen.out.find('\n', from) - from); + } + Check("freeze prints the wait line, Freeze::WaitLine's, before the run line", + waitAt != std::string::npos && runAt != std::string::npos && waitAt < runAt && printedWait == Freeze::WaitLine(freezeJson, ".review-gates/push/x"), frozen.out); + const std::vector waitLine = Dyn::Split(printedWait); auto runArgs = [&](std::vector extra) { std::vector args = {Platform::SelfExe().string(), "run", "--artifact", ".review-gates/push/x", "--hash", hash, "--base", baseSha, "--trees", ".", "--dispositions", ".review-gates/push/x/gate-state/dispositions.json", "--date", Text(freezeJson.at("date")), @@ -284,6 +298,18 @@ echo "{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"result\" // driver is SIGKILLed once every other pass has. const fs::path scratchA = scratchRoot / std::format("{}-run-1", h8); const Process::Child a = start({}, {{"FAKE_SLEEP", "571"}, {"FAKE_SLEEP_ON", std::format("repo-security:{}", securityUnit)}}, "a"); + // `wait` beside it, as the skill runs it: the line freeze printed. + auto waitBeside = [&](std::string_view name) { + std::vector argv = waitLine; + argv.insert(argv.end(), {"--appear", "30"}); + return Process::Start({.argv = argv, + .environment = Env, + .cwd = repo, + .input = {.kind = Process::Stream::Kind::Null}, + .output = {.kind = Process::Stream::Kind::File, .file = base / std::format("{}.out", name)}, + .error = {.kind = Process::Stream::Kind::File, .file = base / std::format("{}.err", name)}}); + }; + const Process::Child waitA = waitBeside("wait-a"); auto answered = [&] { std::int64_t n = 0; std::error_code error; @@ -295,6 +321,9 @@ echo "{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"result\" const bool settled = WaitFor([&] { return calls() == all && answered() == all - 1; }, std::chrono::seconds(30)); Process::Signal(a.pid, SIGKILL); const std::optional aCode = Process::Wait(a.pid, std::chrono::seconds(10)); + const std::optional waitACode = Process::Wait(waitA.pid, std::chrono::seconds(30)); + Check("...and a wait beside it reports a run that left no final dump: exit 2", waitACode == 2 && Read(base / "wait-a.out").contains("ended without its final dump"), + Read(base / "wait-a.out") + Read(base / "wait-a.err")); const std::vector aLeft = LeftoversAfter(fakeDir); Json resumeA; try { @@ -310,7 +339,9 @@ echo "{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"result\" // The next run: the first gate resumed, the outputs of the killed run // salvaged, the one pass that never answered bought again. std::int64_t before = calls(); + const Process::Child waitB = waitBeside("wait-b"); const Process::Captured b = run({}); + const std::optional waitBCode = Process::Wait(waitB.pid, std::chrono::seconds(30)); const Json dumpB = LatestDump(gateDir, h8); const Json& processesB = dumpB.is_object() ? dumpB.at("processes") : Json::array(); Check("the next run resumes the first gate from the checkpoint, salvages every output the killed run finished and buys only the pass that never answered - SEND-READY, exit 0", @@ -318,6 +349,9 @@ echo "{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"result\" && std::ranges::count_if(processesB, [](const Json& r) { return Dyn::Truthy(Dyn::Get(r, "salvaged")); }) == all - gate1 - 1 && Count(processesB, "status", "ok") == all - gate1, std::format("exit {}, {} call(s), {}", b.returnCode, calls() - before, dumpB.is_object() ? Text(dumpB.at("overall")) : b.out + b.err)); + const std::string waitBOut = Read(base / "wait-b.out"); + Check("a wait beside the next run ends with it, printing the summary the run printed at its end, with its exit code", waitBCode == 0 && !waitBOut.empty() && b.out.ends_with(waitBOut), + waitBOut + Read(base / "wait-b.err")); const Json stored = State::LoadState(gateDir / "unit-state.json").at("entries"); Check("...and stores the clean block results of the range for reuse", static_cast(stored.size()) >= all - gate1, std::to_string(stored.size())); @@ -329,14 +363,28 @@ echo "{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"result\" c.returnCode == 0 && calls() == before && dumpC.is_object() && dumpC.at("overall") == "SEND-READY" && dumpC.at("resumedLenses").size() == 3, std::format("exit {}, {} call(s)", c.returnCode, calls() - before)); + // A full run a preflight check stops after it took the run lock: the + // wait beside it prints the check's message, exit 3. + const Process::Child waitP = waitBeside("wait-p"); + const Process::Captured p = run({"--without", "repo-better-solution.md,repo-bug-prover.md,repo-security.md"}); + const std::optional waitPCode = Process::Wait(waitP.pid, std::chrono::seconds(30)); + Check("a wait beside a full run that a preflight check stops after its run lock prints the check's message, exit 3", p.returnCode == 3 && waitPCode == 3 + && Read(base / "wait-p.out").starts_with("preflight: no lens runs") && p.err.contains(Dyn::Strip(Read(base / "wait-p.out"))), + Read(base / "wait-p.out") + Read(base / "wait-p.err") + p.err); + // A defect, on a run that reuses nothing; the scratch dir it claims // holds a stop file from before, which is not this run's. const std::string nextRun = std::format("{}-run-{}", h8, RunNumber(dumpC) + 1); const fs::path stale = scratchRoot / nextRun / "stop"; Write(stale, ""); before = calls(); + const Process::Child waitD = waitBeside("wait-d"); const Process::Captured d = run({"--no-reuse", "--no-salvage"}, {{"FAKE_FIX", std::format("repo-bug-prover:{}", proverUnit)}, {"FAKE_SLEEP", "3"}, {"FAKE_SLEEP_ON", "repo-better-solution:whole:order"}}); + const std::optional waitDCode = Process::Wait(waitD.pid, std::chrono::seconds(30)); + const std::string waitDOut = Read(base / "wait-d.out"); + Check("a wait beside a FIX FIRST run prints the summary the run printed at its end, exit 1", waitDCode == 1 && !waitDOut.empty() && d.out.ends_with(waitDOut), + waitDOut + Read(base / "wait-d.err")); const Json dumpD = LatestDump(gateDir, h8); Check("FIX FIRST: a defect in the last gate stops the run there, exit 1 - every pass bought again with --no-reuse --no-salvage", d.returnCode == 1 && calls() - before == all && dumpD.is_object() && dumpD.at("overall") == "FIX FIRST" && dumpD.at("stoppedAt") == "Gate 3 — Proof",