diff --git a/.agents/skills/implement-issue/SKILL.md b/.agents/skills/implement-issue/SKILL.md index db4b091..e184053 100644 --- a/.agents/skills/implement-issue/SKILL.md +++ b/.agents/skills/implement-issue/SKILL.md @@ -130,7 +130,7 @@ git push gh pr create -R --title ": " --body "" [--label ] gh pr edit -R --add-label # when set gh pr edit -R --add-label # when set, and a person sees the change in the UI -$RS park ... # every pull request of the issue; then its waiter, below +$RS park ... # every pull request of the issue; then end the turn as it says ``` The body: what changed and why, how it was verified (the commands, and what @@ -151,8 +151,8 @@ that fails, is one line there, and a later round tries again. Then `Fixes #` `Written by this agent — ` from `bash "$HOME/scripts/session-link.sh"`. With `label_mine` set it carries that label from the start: without it, no later run finds the pull request, and `finish` refuses `pr-opened`. -Then **babysit it in this session** until it is merged: park it, start -`$RS wait --park` as a background task and end the turn; when the waiter wakes +Then **babysit it in this session** until it is merged: park it and end the +turn as `park` says; when the precheck (or, without a tick, the waiter) wakes the session, `start` the item, handle what landed, push, park again — [`docs/babysit.md`](../../../docs/babysit.md). The run ends `released` once it is merged or closed, and `blocked` when it cannot get green. diff --git a/CHANGELOG.md b/CHANGELOG.md index 5895b6b..2f568f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,21 @@ Applying the kit never touches an agent already created from it, so an instance crosses a version only when its operator walks it through these steps, in the direct session. +## 6.17.0 — 2026-11-10 + +**The precheck watches a parked item; nothing waits in the sandbox.** `park` +ends the turn with nothing running: the tick's precheck, which reads the pull +requests anyway, messages the parked session when a review, a person's comment, +a failed check, a conflict or the merge lands after its last round — and +nothing else wakes it. The two-hour waiter, and its wake every two hours to +start it again, is left only where no tick runs: a person's session, or +`schedules` without `tick`. A session not back within fifteen minutes is handed +to a fresh run, as before. + +**Upgrade:** nothing. An item parked before this version moves over by itself: +its running waiter hands it to the precheck when it next ends, and one lost to a +restart is watched instead of messaged. + ## 6.16.2 — 2026-11-10 **An item with work pushed past its merged pull requests is not done.** `start` diff --git a/CLAUDE.md b/CLAUDE.md index 822b126..a835c52 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -126,15 +126,15 @@ requests, comments. Every step below goes through `scripts/run-state.sh`: pass|fail|skipped [cause]`. A check that did not pass is never only a line in a pull request body: `checked` says what to post, and park and finish hold a change on `verify_required_paths` back from review until it passes. -- **Waiting on a person** — a review, a merge: `park` it, with its waiter - running ([`docs/babysit.md`](docs/babysit.md) → **Held, then parked**). +- **Waiting on a person** — a review, a merge: `park` it, and end the turn as + it says ([`docs/babysit.md`](docs/babysit.md) → **Held, then parked**). - **Last, on every way out:** push everything, report on GitHub, then `run-state.sh finish [pr]` — `nothing`, `pr-opened`, `pr-updated`, `released`, `blocked`, `waiting-lock`, `waiting-env` or `needs-info`. It refuses until the slot is pushed and this run's report is on the issue or its pull request ([`docs/runs.md`](docs/runs.md) → **Reports**); then it frees the item and the slot, and backs `work/` up. A `Stop` hook keeps an unattended run's turn - from ending before it, or before it is parked with its waiter running. A run that ends without it anyway is found dead by the next precheck, and + from ending before it, or before it is parked. A run that ends without it anyway is found dead by the next precheck, and its item handed on as half-done — say so in your report when you resume one. - **Resumed after a restart** (``): `start` your item again. @@ -161,7 +161,7 @@ Nothing to do is a normal outcome. Say so, finish `nothing`, end the turn. Never end a turn asking, summarizing or promising to continue. - **Never leave work running behind you**: a build detached with `nohup`, `setsid` or `&` outlives its locks. - **Long commands run in the background, and you work meanwhile**: `verify`, - `verify_exclusive`, a build, a test suite, `run-state.sh wait`, its waiter — start each as + `verify_exclusive`, a build, a test suite, `run-state.sh wait` — start each as the harness's own background task (Claude Code: `run_in_background`), then review the diff, draft the pull request body, read what comes next, and act on its result when it arrives. Never change what it is testing while it runs, diff --git a/README.md b/README.md index 87f513c..66e2207 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,7 @@ through review. - `work-backup.sh` backs `work/` up to a private repository of its own, and restores it on a fresh volume; - `harness/claude-code/` holds the `Stop` hook that keeps an unattended run - from ending its turn until it is at rest — finished, or parked with its - waiter running — and the installer that registers it and links the skills; + from ending its turn until it is at rest — finished, or parked — and the installer that registers it and links the skills; - `verify-onboarding.sh` checks an instance has the shape onboarding promises, and every failure names its fix; - `audit.sh` is the deterministic half of the weekly audit; @@ -58,8 +57,8 @@ run the weekly audit. One session carries an issue from its claim to the merge. While it works, it holds the issue and a slot, and the Stop hook keeps its turn going. While a person moves — a review, a merge — it **parks**: the slot and the exclusive -lock go back, the issue stays its own, and a waiter wakes that same session -when a review, a comment, a red check or the merge lands +lock go back, the issue stays its own, nothing runs, and the precheck wakes +that same session when a review, a comment, a red check or the merge lands ([`docs/babysit.md`](docs/babysit.md)). ```mermaid @@ -71,13 +70,13 @@ stateDiagram-v2 Working --> Verifying: lock · takes exclusive Verifying --> Working: unlock } - state "PARKED · the turn ends, a waiter watches" as Parked { + state "PARKED · the turn ends, the precheck watches" as Parked { InReview --> AwaitingMerge: approved AwaitingMerge --> InReview: approval dismissed } Held --> Parked: park · frees slot + exclusive Parked --> Held: a review, a comment, a red check · same session - Parked --> Held: waiter lost to a restart · a fresh run + Parked --> Held: session not back in time · a fresh run Parked --> Released: merged or closed · frees item Released --> [*] Held --> Aside: finish · frees item + slot diff --git a/VERSION b/VERSION index cd8864f..1980a78 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -6.16.2 +6.17.0 diff --git a/app/control-room/machine.json b/app/control-room/machine.json index 61e0fcf..30b707c 100644 --- a/app/control-room/machine.json +++ b/app/control-room/machine.json @@ -49,7 +49,7 @@ "id": "in-review", "label": "In review", "zone": "outflow", - "holds": "item · waiter", + "holds": "item · watched", "stages": [ "in-review" ] @@ -58,7 +58,7 @@ "id": "awaiting-merge", "label": "Awaiting merge", "zone": "outflow", - "holds": "item · waiter", + "holds": "item · watched", "stages": [ "awaiting-merge" ] @@ -147,7 +147,7 @@ "from": "in-review", "to": "working", "by": "start · review or failed check", - "who": "waiter · booking · tick" + "who": "precheck · waiter · tick" }, { "from": "in-review", @@ -159,7 +159,7 @@ "from": "awaiting-merge", "to": "working", "by": "start · maintainer comment or red", - "who": "waiter · booking · tick" + "who": "precheck · waiter · tick" }, { "from": "awaiting-merge", diff --git a/app/control-room/page.html b/app/control-room/page.html index 34d192f..074ab39 100644 --- a/app/control-room/page.html +++ b/app/control-room/page.html @@ -708,7 +708,7 @@

Event log · TICK.log —

: changes ? `changes requested on ${p.map((q) => q.ref).join(" ")}: the next round answers it` : p.length ? `in review: ${p.map((q) => q.ref).join(" ")}` : x.stage === "orphan" ? "claimed, no pull request and no run on it" : x.stage; const held = x.lock && x.lock.parked_at - ? (x.watched === "waiter" ? " · parked, its waiter watching" : x.watched === "booking" ? ` · parked, no waiter: a wake-up at ${(x.lock.wake_at || "").slice(11, 16)} UTC` : x.watched === "message" ? " · parked, its waiter lost: its session was messaged to come back" : " · parked, nothing watching: the next tick takes it over") + ? (x.watched === "precheck" ? " · parked, the precheck watching" : x.watched === "waiter" ? " · parked, its waiter watching" : x.watched === "booking" ? ` · parked, no waiter: a wake-up at ${(x.lock.wake_at || "").slice(11, 16)} UTC` : x.watched === "message" ? " · parked, its session messaged to come back" : " · parked, nothing watching: the next tick takes it over") : x.lock && !x.slot ? ` · item lock held by session ${x.lock.session.slice(0, 8)}, no slot` : ""; wait.push(row(red || changes ? "adv" : x.stage === "orphan" ? "adv" : "park", lbl(x.item), x.url, x.title || x.branch, why + held, p.length && (changes || red) ? askBtn("Round", `Start a review round on PR ${p[0].ref}: docs/direct-session.md → review round. Read its reviews, comments and checks first and tell me the plan before you push.`, true) : "")); @@ -762,10 +762,10 @@

Event log · TICK.log —

$("s-flight-sub").textContent = `${f.filter((x) => x.slot).length} working · ${parkedN} parked`; $("s-flight-sub").title = `${f.filter((x) => x.slot).length} in a slot · ${parkedN} parked, waiting on a person · ${by("in-review")} in review · ${by("awaiting-merge")} approved, awaiting merge`; const rz = S.resumes || {}; - const cont = (rz.waiter || 0) + (rz.booking || 0) + (rz.operator || 0); + const cont = (rz.precheck || 0) + (rz.waiter || 0) + (rz.booking || 0) + (rz.operator || 0); $("s-res").textContent = rz.total ? `${cont}/${rz.total}` : "—"; $("s-res-sub").textContent = rz.total ? `continued · ${rz.fresh || 0} fresh` : "none this week"; - $("s-res-sub").title = `last 7 days: ${rz.waiter || 0} woken by the waiter, ${rz.booking || 0} by a booked wake-up, ${rz.operator || 0} by a person typing in the session; ${rz.messaged || 0} asked to restart a waiter a restart killed; ${rz.fresh || 0} taken over by a fresh session without the context`; + $("s-res-sub").title = `last 7 days: ${rz.precheck || 0} woken by the precheck, ${rz.waiter || 0} by the waiter, ${rz.booking || 0} by a booked wake-up, ${rz.operator || 0} by a person typing in the session; ${rz.messaged || 0} messages sent to parked sessions; ${rz.fresh || 0} taken over by a fresh session without the context`; const r = S.gh?.rate; if (r && r.remaining != null) { const lim = r.limit || 5000, pct = Math.max(0, Math.min(100, Math.round(100 * r.remaining / lim))); diff --git a/app/src/developer/audit.ts b/app/src/developer/audit.ts index 6becad6..f99974d 100644 --- a/app/src/developer/audit.ts +++ b/app/src/developer/audit.ts @@ -58,17 +58,17 @@ export const audit: Command = async (deps) => { ); // How often the session that wrote a change was the one woken to answer what // landed on it, and how often a fresh run had to take it over without that - // context. A fresh one after a parked item is a waiter lost to a restart - // whose session the sweep's message did not bring back. + // context. A fresh one after a parked item is a session the precheck's or + // the sweep's message did not bring back. const resumed = week.filter((l) => l.split(" ")[1] === "resumed"); if (resumed.length > 0) { const by = (c: string) => resumed.filter((l) => new RegExp(`cause=${c}( |$)`).test(l)).length; const continued = resumed.length - by("fresh"); o( - `resumes: ${continued} continued in their own session (waiter ${by("waiter")}, booked wake-up ${by("booking")}, a person ${by("operator")}), ${by("fresh")} taken over by a fresh one`, + `resumes: ${continued} continued in their own session (precheck ${by("precheck")}, waiter ${by("waiter")}, booked wake-up ${by("booking")}, a person ${by("operator")}), ${by("fresh")} taken over by a fresh one`, ); const messaged = week.filter((l) => l.split(" ")[1] === "messaged").length; - if (messaged > 0) o(`waiters lost to a restart: ${messaged}, each session messaged to start its own again`); + if (messaged > 0) o(`parked sessions messaged: ${messaged}, for what landed or a waiter lost to a restart`); if (by("fresh") > continued) o(`warn runs.resumed — most resumes lost their context: ${by("fresh")} of ${resumed.length} started fresh`); } diff --git a/app/src/developer/control-room.ts b/app/src/developer/control-room.ts index 2807eb9..7dc6f2c 100644 --- a/app/src/developer/control-room.ts +++ b/app/src/developer/control-room.ts @@ -22,7 +22,7 @@ import { join } from "node:path"; import type { Command, Deps } from "../factory/context.ts"; import { issueRefs, login } from "../factory/github.ts"; import { parseKv, readText } from "../factory/kv.ts"; -import type { Held } from "../factory/locks.ts"; +import type { Held, ParkedHolder } from "../factory/locks.ts"; import { run } from "../factory/proc.ts"; import type { SessionInfo } from "../factory/runtime.ts"; import { epoch, iso, nowSeconds } from "../factory/time.ts"; @@ -84,9 +84,9 @@ export interface LockView { readonly silent_min: number | null; readonly stop_blocks: number; readonly holder: Holder; - /** A parked item lock: when, and what keeps it — its waiter, a booked wake-up, a message asking its session back, or nothing. */ + /** A parked item lock: when, and what keeps it — the precheck, its waiter, a booked wake-up, a message asking its session back, or nothing. */ readonly parked_at: string; - readonly kept_by: "waiter" | "booking" | "message" | ""; + readonly kept_by: ParkedHolder; readonly wake_at: string; } @@ -227,6 +227,7 @@ export function resumeCounts(text: string, sinceIso: string) { const by = (c: string) => lines.filter((l) => new RegExp(`cause=${c}( |$)`).test(l)).length; return { total: lines.length, + precheck: by("precheck"), waiter: by("waiter"), booking: by("booking"), messaged: text.split("\n").filter((l) => l.split(" ")[1] === "messaged" && (l.split(" ")[0] ?? "") > sinceIso) diff --git a/app/src/developer/harness.ts b/app/src/developer/harness.ts index 0a8d0c0..e8a9dfd 100644 --- a/app/src/developer/harness.ts +++ b/app/src/developer/harness.ts @@ -32,12 +32,13 @@ const WAITER = /run-state(\.sh)?["']?\s+wait\s+--park/; * hook asks. Nobody watches a scheduled run, so a turn that ends mid-work — * a summary, a question, "I'll continue next time" — is work nobody hears * about until a later run finds it dead. A run whose pull request waits on a - * person is at rest once it is parked and something will wake it: then the - * turn ends, and the waiter brings it back. Exit 2 keeps the turn going and - * shows the model stderr: what is left, and how. + * person is at rest once it is parked and something will wake it — the + * precheck, which watches it, or else its waiter: then the turn ends with + * nothing running, and a message brings it back. Exit 2 keeps the turn going + * and shows the model stderr: what is left, and how. * - * A waiter the harness lists as a running background task counts as one even - * before it has written its pid: the model may end the turn the moment it + * A waiter, where one is still started, the harness lists as a running + * background task counts as one even before it has written its pid: the model may end the turn the moment it * starts it. The hook counts its own blocks on the item's lock; after * MAX_BLOCKS it lets the stop through — the harness ends a turn after eight * blocks anyway — and the next precheck finds the run dead and hands its item @@ -88,8 +89,7 @@ export const enforceFinish: Command = async (deps) => { e("- Waiting on a person — a review, a merge? Push, comment the pull request"); e(" with this run's session link, then:"); e(' bash "$HOME/scripts/run-state.sh" park ...'); - e(' bash "$HOME/scripts/run-state.sh" wait --park (a background task)'); - e(" and end the turn: the waiter wakes this session when something lands."); + e(" and end the turn as it says: this session is woken when something lands."); e("- Done, or cannot go on: push, report on the issue or its pull request with"); e(' the session link (bash "$HOME/scripts/session-link.sh"), then'); e(' bash "$HOME/scripts/run-state.sh" finish [pr]'); diff --git a/app/src/developer/kit.ts b/app/src/developer/kit.ts index 14875cc..b0e9b35 100644 --- a/app/src/developer/kit.ts +++ b/app/src/developer/kit.ts @@ -121,6 +121,12 @@ export class Kit { get stuckMin(): number { return this.cfg.int("stuck_after_min", 120); } + /** Whether the tick's precheck runs, and so watches a parked item: autonomous, with the tick among `schedules`. */ + get precheckWatches(): boolean { + if (this.cfg.mode() !== "autonomous") return false; + const on = this.cfg.list("schedules"); + return on.length === 0 || on.includes("tick"); + } get babysitMaxHours(): number { return this.cfg.int("babysit_max_hours", 4); } diff --git a/app/src/developer/precheck.ts b/app/src/developer/precheck.ts index 53c45df..dcd836b 100644 --- a/app/src/developer/precheck.ts +++ b/app/src/developer/precheck.ts @@ -208,6 +208,8 @@ async function readRest(gh: GitHub, kit: Kit, author: string, mine: string, also interface ItemCache { readonly seen: string; + /** When the session that parked it came back from its last round: what lands after it wakes that session. */ + readonly round: string; readonly state: string; readonly abandoned: number; readonly branch: string; @@ -230,6 +232,7 @@ export function readItems(dir: string): Map { const m = parseKv(readText(join(dir, f))); out.set(f.slice(0, -3), { seen: m.get("seen_at") ?? "", + round: m.get("round_at") ?? "", state: m.get("state") ?? "", abandoned: Number(m.get("abandoned") ?? 0) || 0, branch: m.get("branch") ?? "", @@ -238,6 +241,16 @@ export function readItems(dir: string): Map { return out; } +/** A parked item the precheck watches, and what landed on its pull requests: its session is messaged. */ +export interface Wake { + readonly item: string; + readonly what: string; + /** The worklist line a fresh run gets when the session cannot be reached. */ + readonly line: string; + /** Every pull request of it merged or closed, as far as the open ones show: `start` reads GitHub again. */ + readonly done?: boolean; +} + /** The worklist, by section, from what GitHub and the cache say. */ export function worklist( kit: Kit, @@ -248,24 +261,32 @@ export function worklist( author: string, lockFree: boolean, envFree = false, + watched: ReadonlySet = new Set(), ) { const root = kit.slug; // A pull request is babysat until it is merged (docs/babysit.md). It wakes // a run for what happened to it since a run last looked: a review, a // person's comment — on an approved one, a maintainer's — or a check that // failed, once, so what the agent could not fix is not reported every tick. - // Its item is the issue of `repo` its body names, and an item held — by a - // live run, or parked with its session's waiter or wake-up still to come — - // is left out: that session answers it, with the context that wrote it. One - // in another repository that names none is not this instance's work. + // Its item is the issue of `repo` its body names, and an item held by a + // live run, or parked with its session's waiter or wake-up still to come, + // is left out. One parked with the precheck watching it (`watched`) is a + // wake instead: its session is messaged, so the context that wrote the + // change answers it — from its last round on, and a conflict in review too, + // as a waiter would. One in another repository that names none is not this + // instance's work. const prWork: string[] = []; + const wakes = new Map(); for (const p of snap.prs) { const repo = p.repo || root; const other = repo.toLowerCase() !== root.toLowerCase(); const item = issueRefs(p.body, root, repo)[0] ?? (other ? undefined : `pr${String(p.number)}`); - if (item === undefined || held.has(item)) continue; + if (item === undefined) continue; + const wake = watched.has(item); + if (held.has(item) && !wake) continue; const ref = other ? `${repo}#${String(p.number)}` : `#${String(p.number)}`; - const s = items.get(item)?.seen || since; + const cached = items.get(item); + const s = (wake ? cached?.round || cached?.seen : cached?.seen) || since; const approved = p.reviewDecision === "APPROVED"; const latest = reviewsSince(p, "", author) .filter((r) => !approved || r.state !== "APPROVED") @@ -274,18 +295,24 @@ export function worklist( .at(-1); const reviewed = (latest ?? "") > s; const commented = commentsSince(p.comments ?? [], s, approved).length > 0; - const failed = failedSince(p, s); - const conflict = p.mergeable === "CONFLICTING" && items.get(item)?.state === "awaiting-merge"; + const failed = failedSince(p, s, wake); + const conflict = p.mergeable === "CONFLICTING" && (wake || cached?.state === "awaiting-merge"); if (!reviewed && !commented && failed.length === 0 && !conflict) continue; const what = [ ...(reviewed ? ["reviewed; resolve every finding and re-request review"] : []), ...(commented ? [`commented${approved ? " after approval" : ""}; answer every comment`] : []), ...(failed.length > 0 ? [`checks failed: ${failed.join(", ")}`] : []), - ...(conflict ? ["approved, now conflicting: rebase"] : []), + ...(conflict ? [`${approved ? "approved, now " : ""}conflicting: rebase`] : []), ].join("; "); - prWork.push( - `- ${item.startsWith("pr") ? item : `#${item}`} — PR ${ref} ${p.title ?? ""} — ${what} — docs/babysit.md\n ${p.url ?? ""}`, - ); + const line = `- ${item.startsWith("pr") ? item : `#${item}`} — PR ${ref} ${p.title ?? ""} — ${what} — docs/babysit.md\n ${p.url ?? ""}`; + if (!wake) { + prWork.push(line); + continue; + } + const w = wakes.get(item) ?? { what: [], lines: [] }; + w.what.push(`PR ${ref} ${what}`); + w.lines.push(line); + wakes.set(item, w); } // Items a run parked because the exclusive lock was taken: due again once // it is free. `waiting-cluster` is the same state as written before 3.0.0. @@ -322,12 +349,20 @@ export function worklist( issueRefs(p.body, root, p.repo || root).concat(p.repo && p.repo !== root ? [] : [`pr${String(p.number)}`]), ), ); + const releaseLine = (k: string) => + `- ${k.startsWith("pr") ? k : `#${k}`} — its pull request is merged or closed: release the issue — docs/babysit.md`; const releaseWork = [...items.entries()] .filter(([k, v]) => (v.state === "in-review" || v.state === "awaiting-merge") && !held.has(k) && !openNamed.has(k)) - .map( - ([k]) => - `- ${k.startsWith("pr") ? k : `#${k}`} — its pull request is merged or closed: release the issue — docs/babysit.md`, - ); + .map(([k]) => releaseLine(k)); + // a watched item with no open pull request left: merged or closed, its session woken to release it + const wakeWork: Wake[] = [...wakes.entries()].map(([item, w]) => ({ + item, + what: w.what.join("; "), + line: w.lines.join("\n"), + })); + for (const k of watched) + if (!openNamed.has(k) && !wakes.has(k)) + wakeWork.push({ item: k, what: "merged or closed: release the issue", line: releaseLine(k), done: true }); const resumeWork = snap.claimed .filter((i) => mine === "" || i.labels.includes(mine)) .filter((i) => !named.has(String(i.number))) @@ -342,7 +377,7 @@ export function worklist( const a = items.get(String(i.number))?.abandoned ?? 0; return `- #${i.number} ${i.title}${a > 0 ? ` — a run died on it ${a} time(s)` : ""}\n ${i.url}`; }); - return { prWork, lockWork, envWork, issueWork, resumeWork, releaseWork }; + return { prWork, lockWork, envWork, issueWork, resumeWork, releaseWork, wakeWork }; } export const precheck: Command = async (deps, _args) => { @@ -366,6 +401,15 @@ export const precheck: Command = async (deps, _args) => { lockFree = kit.locks.read("exclusive") === undefined; } const held = new Set(kit.locks.ofKind("item-").map((h) => h.name.slice("item-".length))); + // parked items the precheck watches, their sessions not yet messaged: what lands on them is a message, not a run + const watched = new Set( + probe + ? [] + : kit.locks + .ofKind("item-") + .filter((h) => h.owner.parked_at !== "" && kit.locks.parkedHolder(h.owner) === "precheck") + .map((h) => h.name.slice("item-".length)), + ); if (!kit.repo) { // Nothing to work on — CONFIG.md lost or never written. Letting a run // through to say so would repeat every ten minutes into a chat nobody @@ -398,7 +442,26 @@ export const precheck: Command = async (deps, _args) => { const envs = await deps.runtime.environments(); envFree = envs !== undefined && envs.length < kit.environmentsMax; } - const w = worklist(kit, snap, cached, held, deps.env.PLATFORM_LAST_RUN_AT ?? "", author, lockFree, envFree); + const w = worklist(kit, snap, cached, held, deps.env.PLATFORM_LAST_RUN_AT ?? "", author, lockFree, envFree, watched); + // Each watched item something landed on: its session is messaged, a turn + // there and none here. Not reached, the item is handed on, and its line + // joins the list for a fresh run. A pull request missing from the open ones + // is read once more, so a search that lags never wakes a session for a + // merge that did not happen. + if (w.wakeWork.length > 0) { + const rs = new RunState(silenced(deps)); + const handedOn: string[] = []; + for (const x of w.wakeWork) { + if (x.done && !(await rs.prsClosed(x.item))) continue; + if (await rs.wakeParked(x.item, x.what)) continue; + handedOn.push(`#${x.item.replace(/^pr/, "")}`); + (x.done ? w.releaseWork : w.prWork).push(x.line); + } + if (handedOn.length > 0) + notes.push( + `${handedOn.join(" ")} parked, and its session could not be reached to answer what landed: take it over from its branch and pull request.`, + ); + } const n = w.prWork.length + w.lockWork.length + w.envWork.length + w.issueWork.length; if (n + w.resumeWork.length + w.releaseWork.length === 0) return 1; const o = (s: string) => deps.io.out(s); diff --git a/app/src/developer/run-state.ts b/app/src/developer/run-state.ts index fa4f7c3..172f2e2 100644 --- a/app/src/developer/run-state.ts +++ b/app/src/developer/run-state.ts @@ -21,11 +21,14 @@ // # elsewhere // park ... the run's part is done and a person moves next: // frees the slot and the exclusive lock, keeps the -// item, so the session may end its turn -// wait --park the parked item's waiter, a background task: blocks -// up to ~2 hours until a pull request needs the run -// (0, and the harness wakes the session), it merged -// (0), or nothing came (3: start it again) +// item, so the session may end its turn; the +// precheck watches it, and messages the session +// when something lands +// wait --park in a person's session, or with no tick to watch: +// the parked item's waiter, a background task, +// blocks up to ~2 hours until a pull request needs +// the run (0, and the harness wakes the session), +// it merged (0), or nothing came (3: start it again) // booked [id] a wake-up booked on the platform for the parked item // may-stop whether this session may end its turn now (0), or // what is left first (1, on stderr): the Stop hook @@ -145,13 +148,14 @@ class RunState { } } - /** Back from parked: the item lock is the turn's again, its waiter and booking spent. */ + /** Back from parked: the item lock is the turn's again, its watch, waiter and booking spent. */ resume(item: string, slot: string, phase: string): void { this.locks.update(`item-${item}`, { slot, phase, phase_at: this.now(), parked_at: "-", + watched: "-", waiter: "-", waiter_boot: "-", wake_at: "-", @@ -165,6 +169,15 @@ class RunState { return this.itemKey(item, "pr").split(/\s+/).filter(Boolean); } + /** + * Whether the precheck watches this session's parked item, so nothing need + * run in its sandbox while it waits: the tick runs, and the session is not + * a person's — a script never messages a person's chat. + */ + async precheckWatches(session: string): Promise { + return this.kit.precheckWatches && !ATTENDED.has(await this.deps.runtime.sessionType(session)); + } + /** * Every pull request on the item's record is merged or closed, and the * branch the run starts on holds nothing the default branch lacks; one @@ -173,11 +186,17 @@ class RunState { * work is not done because the earlier ones merged. */ async allDone(item: string, branch: string): Promise { - const refs = this.prsOf(item).flatMap((a) => parsePrRef(a, this.kit.slug) ?? []); - if (refs.length === 0) return false; + if (this.prsOf(item).length === 0) return false; const co = this.kit.checkout; for (const ref of [this.kit.git.defaultBranch(co), branch]) this.kit.git.run(co, ["fetch", "-q", "origin", ref]); if (this.kit.git.remoteAhead(co, branch)) return false; + return this.prsClosed(item); + } + + /** Every pull request on the item's record is merged or closed; one unread is not. The precheck's check: no fetch. */ + async prsClosed(item: string): Promise { + const refs = this.prsOf(item).flatMap((a) => parsePrRef(a, this.kit.slug) ?? []); + if (refs.length === 0) return false; for (const ref of refs) { const view = (await this.deps.github.prView(this.kit.host, ref.slug, ref.number, "state")) as | { state?: string } @@ -262,13 +281,19 @@ class RunState { } } if (!k) { - // a parked item stays parked, its waiter and booking untouched: dropping - // its lock here would hand it to whichever run comes next + // a parked item stays parked, its watch, waiter and booking untouched: + // dropping its lock here would hand it to whichever run comes next. One + // the precheck messaged is watched again, and messaged again once a + // slot is free: the precheck lets nothing through while every one is held if (!parked) this.locks.drop(`item-${item}`); + const watched = held?.owner.watched === "precheck"; + if (watched) this.locks.update(`item-${item}`, { messaged_at: "-", woke: "-" }); this.say( - parked - ? `all ${open.length} open slots of ${n} are in use — #${item} stays parked; start it again once a slot is free (its waiter, started again, wakes you).` - : `all ${open.length} open slots of ${n} are in use — nothing can start now.`, + !parked + ? `all ${open.length} open slots of ${n} are in use — nothing can start now.` + : watched + ? `all ${open.length} open slots of ${n} are in use — #${item} stays parked, and the precheck wakes this session again once a slot is free. End the turn.` + : `all ${open.length} open slots of ${n} are in use — #${item} stays parked; start it again once a slot is free (its waiter, started again, wakes you).`, ); return 1; } @@ -708,7 +733,14 @@ class RunState { } const now = this.now(); const state = approved ? "awaiting-merge" : "in-review"; - this.locks.update(`item-${item}`, { slot: "-", parked_at: now, phase: `parked: ${state}`, phase_at: now }); + const watched = await this.precheckWatches(this.kit.me); + this.locks.update(`item-${item}`, { + slot: "-", + parked_at: now, + phase: `parked: ${state}`, + phase_at: now, + watched: watched ? "precheck" : "-", + }); this.writeItem(item, { state, pr: prs, session: this.kit.me, round_at: now, updated_at: now }); this.logLine("parked", this.kit.me, item, slot, prs.split(" ").join(","), since, `state=${state}`); const labels = refs.map((x) => labelRef(x, this.kit.slug)).join(" "); @@ -731,6 +763,13 @@ class RunState { this.writeItem(item, { ui_notified: uiPrs }); } this.out(`parked #${item} (${state}): the slot and the exclusive lock are free; the item stays yours.`); + if (watched) { + this.out("Now end the turn, with nothing left running: the precheck watches it."); + this.out( + `It messages this session for a review, a comment, a red check or a conflict on ${labels}, and when it merges.`, + ); + return 0; + } this.out( `Now start its waiter as a background task — bash "$HOME/scripts/run-state.sh" wait --park — and end the turn.`, ); @@ -741,12 +780,16 @@ class RunState { } /** - * The parked item's waiter: what wakes the session. Started as a harness + * The parked item's waiter, where the precheck does not watch it — a + * person's session, or no tick: what wakes the session. Started as a harness * background task, it records its pid on the item lock — the lock's holder * while the turn is over — then looks at the pull requests once a minute, * an unchanged one at no cost, for up to PARK_FOR_SECONDS. It exits when * one needs the run, and the harness hands the session its output as a new - * turn; or with 3 when nothing came, and the session starts it again. + * turn; or with 3 when nothing came, and the session starts it again. One + * the precheck may watch instead — an item parked before it did — is handed + * to it, at once or when the waiter runs out, so nothing wakes the session + * every two hours for nothing. */ async waitParked(): Promise { this.needSession(); @@ -764,6 +807,15 @@ class RunState { this.say(`#${item} is parked with no pull request on record: start it again and park `); return 1; } + const watch = await this.precheckWatches(this.kit.me); + if ( + watch && + (lock.owner.watched === "precheck" || !waiterAlive(lock.owner, this.locks.boot, this.locks.livePids)) + ) { + this.watchParked(lock.name); + this.out(`#${item}: the precheck watches it, and messages this session when something lands. End the turn.`); + return 5; + } const pid = this.deps.env.SD_WAITER_PID || String(process.pid); if ( lock.owner.waiter && @@ -820,6 +872,11 @@ class RunState { const o = this.locks.read(lock.name)?.owner; if (o?.waiter === pid && o.parked_at !== "") this.locks.update(lock.name, { waiter: "-", waiter_boot: "-" }); } + if (watch) { + this.watchParked(lock.name); + this.out(`nothing yet on ${labels.join(" ")} — ${last}. The precheck watches it from now on: end the turn.`); + return 3; + } this.out( `nothing yet on ${labels.join(" ")} — ${last}. Start the waiter again: bash "$HOME/scripts/run-state.sh" wait --park`, ); @@ -859,8 +916,13 @@ class RunState { const item = mine.find((h) => h.name.startsWith("item-")); const holds = mine.filter((h) => !h.name.startsWith("item-")).map((h) => h.name); if (item && item.owner.parked_at !== "" && holds.length === 0) { - // a message asking for its waiter is no reason to stop: it is what woke this turn + // a message is no reason to stop: it is what woke this turn if (!["", "message"].includes(this.locks.parkedHolder(item.owner))) return 0; + if (item.owner.watched === "precheck") { + this.say(`#${item.owner.item} is parked, and the precheck woke this session for what landed on it:`); + this.say(`take it back — bash "$HOME/scripts/run-state.sh" start ${item.owner.item} — and handle it.`); + return 1; + } this.say(`#${item.owner.item} is parked, but nothing will wake this session:`); this.say( 'start its waiter as a background task — bash "$HOME/scripts/run-state.sh" wait --park — then end the turn.', @@ -1215,6 +1277,10 @@ class RunState { // most likely: its session is asked back once, so the context that // wrote the change answers it; asked already, or not reachable, the // next tick picks it up as a run that stopped + if (item && h.owner.messaged_at === "" && (await this.precheckWatches(h.owner.session))) { + this.watchParked(h.name); + continue; + } if (item && h.owner.messaged_at === "" && (await this.callBack(h))) continue; if (item) { this.writeItem(item, { state: "abandoned", updated_at: this.now() }); @@ -1257,6 +1323,51 @@ class RunState { return abandoned; } + /** The precheck watches a parked item from now on: its waiter and booking are spent. */ + watchParked(name: string): void { + this.locks.update(name, { watched: "precheck", waiter: "-", waiter_boot: "-", messaged_at: "-" }); + } + + /** + * Something landed on a parked item the precheck watches: its session is + * messaged to take it back, a turn there, and the lock is held for it + * MESSAGE_GRACE_MIN; not taken back by then, it is dead, and a fresh run + * takes the item over. False when the platform did not queue the message: + * the item is handed on at once. + */ + async wakeParked(item: string, what: string): Promise { + const name = `item-${item}`; + const h = this.locks.read(name); + if (!h || h.owner.parked_at === "" || this.locks.parkedHolder(h.owner) !== "precheck") return true; + const { session, parked_at } = h.owner; + const prs = this.prsOf(item).join(","); + const said = what.replaceAll('"', "'"); + const text = [ + `#${item} is parked in this session, and something landed on it: ${what}.`, + `Take it back — bash "$HOME/scripts/run-state.sh" start ${item} — and handle it (docs/babysit.md).`, + `Sent by the precheck. Not taken back within ${MESSAGE_GRACE_MIN} minutes, and a fresh run takes the item over.`, + ].join("\n\n"); + // stamped first, so a precheck beside this one does not send it twice + const now = this.now(); + this.locks.update(name, { messaged_at: now, woke: "precheck", phase: `woken: ${said}`, phase_at: now }); + if (await this.deps.runtime.message(session, text)) { + this.logLine("messaged", session, item, "-", prs, parked_at, `reason="landed: ${said}"`); + return true; + } + this.writeItem(item, { state: "abandoned", updated_at: now }); + this.logLine( + "abandoned", + session, + item, + "-", + prs, + parked_at, + `reason="parked, its session not reached for what landed"`, + ); + this.locks.drop(name); + return false; + } + /** Asks a parked item's session to take it back: true once the platform queued the message, and the lock is held for it. */ private async callBack(h: { name: string; diff --git a/app/src/factory/locks.ts b/app/src/factory/locks.ts index 487aaa3..a7a5a4c 100644 --- a/app/src/factory/locks.ts +++ b/app/src/factory/locks.ts @@ -9,10 +9,12 @@ // messages, so its lock goes stale only `attendedStaleMin` after it was taken. // // A parked lock (`parked_at`) has outlived its turn on purpose: the session -// ended it to wait for a person, and its holder is now whatever wakes it — a -// waiter process on this boot, or a wake-up booked on the platform. Neither -// left, the sweep messages the session once to come back (`messaged_at`), and -// the lock is held for that a while; it is dead once nothing is left. A runtime that does not answer frees nothing: a guess +// ended it to wait for a person, and its holder is now whatever wakes it — the +// precheck (`watched`), which messages the session when something lands on its +// pull requests; in a person's session a waiter process on this boot, or a +// wake-up booked on the platform. A session messaged to come back +// (`messaged_at`) has a while to take it; then, and with nothing else left, +// the lock is dead. A runtime that does not answer frees nothing: a guess // could hand a live run's work to another. import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs"; import { join } from "node:path"; @@ -28,8 +30,9 @@ export const OWNER_KEYS = [ "slot", "phase", "phase_at", - // a parked item lock: when it was parked, its waiter, its booked wake-up, and what woke it last + // a parked item lock: when it was parked, who watches it, its waiter, its booked wake-up, and what woke it last "parked_at", + "watched", "waiter", "waiter_boot", "wake_at", @@ -47,6 +50,7 @@ export interface Owner { readonly phase: string; readonly phase_at: string; readonly parked_at: string; + readonly watched: string; readonly waiter: string; readonly waiter_boot: string; readonly wake_at: string; @@ -61,6 +65,9 @@ export const BOOKING_GRACE_MIN = 30; /** How long a session messaged to come back to its parked item has to take it before the lock reads dead. */ export const MESSAGE_GRACE_MIN = 15; +/** What keeps a parked lock alive, "" when nothing does. */ +export type ParkedHolder = "waiter" | "booking" | "message" | "precheck" | ""; + export interface Held { readonly name: string; readonly dir: string; @@ -94,6 +101,7 @@ function owner(file: string): Owner { phase: g("phase"), phase_at: g("phase_at"), parked_at: g("parked_at"), + watched: g("watched"), waiter: g("waiter"), waiter_boot: g("waiter_boot"), wake_at: g("wake_at"), @@ -217,16 +225,18 @@ export class Locks { /** * What keeps a parked lock alive: its waiter, a wake-up booked and not yet - * overdue, or a message asking its session back, sent a moment ago. "" when - * nothing does. + * overdue, a message asking its session back, sent a moment ago, or the + * precheck watching it. "" when nothing does — a message whose grace ran + * out included: the session did not come, and the item goes to a fresh run. */ - parkedHolder(o: Owner): "waiter" | "booking" | "message" | "" { + parkedHolder(o: Owner): ParkedHolder { if (waiterAlive(o, this.opts.boot, this.opts.livePids)) return "waiter"; const now = nowSeconds(this.opts.clock); const t = epoch(o.wake_at); if (t !== undefined && now < t + BOOKING_GRACE_MIN * 60) return "booking"; const m = epoch(o.messaged_at); - if (m !== undefined && now < m + MESSAGE_GRACE_MIN * 60) return "message"; + if (m !== undefined) return now < m + MESSAGE_GRACE_MIN * 60 ? "message" : ""; + if (o.watched === "precheck") return "precheck"; return ""; } diff --git a/app/test/audit.test.ts b/app/test/audit.test.ts index 348907d..159f245 100644 --- a/app/test/audit.test.ts +++ b/app/test/audit.test.ts @@ -83,7 +83,7 @@ test("a busy week, counted", () => assert.match(r.out, /median 1, longest 40/); assert.match( r.out, - /resumes: 2 continued in their own session \(waiter 1, booked wake-up 0, a person 1\), 1 taken over by a fresh one/, + /resumes: 2 continued in their own session \(precheck 0, waiter 1, booked wake-up 0, a person 1\), 1 taken over by a fresh one/, ); assert.doesNotMatch(r.out, /warn runs\.resumed/, "most kept their context"); assert.match(r.out, /warn runs\.abandoned — 1 run\(s\)/); diff --git a/app/test/control-room.test.ts b/app/test/control-room.test.ts index 0e292c7..8560376 100644 --- a/app/test/control-room.test.ts +++ b/app/test/control-room.test.ts @@ -191,6 +191,7 @@ test("the resume counts and the log come from TICK.log", () => { ].join("\n"); assert.deepEqual(resumeCounts(log, "2026-09-21T00:00:00Z"), { total: 2, + precheck: 0, waiter: 0, messaged: 0, booking: 0, diff --git a/app/test/harness.test.ts b/app/test/harness.test.ts index 6a33dea..74a5217 100644 --- a/app/test/harness.test.ts +++ b/app/test/harness.test.ts @@ -77,6 +77,17 @@ test("a parked item with its waiter running stops; parked with nothing to wake i assert.equal((await stop(s, "sess-a", [], { SD_LIVE_PIDS: "" })).rc, 0, "a wake-up is booked"); })); +test("parked with the precheck watching stops with nothing running; woken by it, it does not", () => + inSandbox(async (s) => { + s.runtime.running.add("sess-a"); + s.lock("item-7", { session: "sess-a", item: "7", parked_at: s.clock.ago(1), watched: "precheck" }); + assert.equal((await stop(s, "sess-a")).rc, 0, "no waiter, no booking: the precheck watches it"); + s.write("locks/item-7/owner", `${s.read("locks/item-7/owner")}- messaged_at: ${s.clock.ago(1)}\n`); + const r = await stop(s, "sess-a"); + assert.equal(r.rc, 2, "the message is what woke this turn"); + assert.match(r.err, /the precheck woke this session .* start 7/s); + })); + test("parked does not excuse a slot or the exclusive lock still held", () => inSandbox(async (s) => { s.runtime.running.add("sess-a"); diff --git a/app/test/precheck.test.ts b/app/test/precheck.test.ts index 4ce33cf..39ad6b4 100644 --- a/app/test/precheck.test.ts +++ b/app/test/precheck.test.ts @@ -319,6 +319,141 @@ test("a parked item is its session's: the precheck leaves it while something wil ); })); +/** #4 parked by sess-a, its last round `roundMin` ago, the precheck watching it. */ +function watched(s: Sandbox, roundMin = 60, state = "in-review"): void { + s.item("4", { state, pr: "40", session: "sess-a", round_at: s.clock.ago(roundMin), seen_at: s.clock.ago(roundMin) }); + s.lock("item-4", { + session: "sess-a", + item: "4", + since: s.clock.ago(roundMin + 10), + parked_at: s.clock.ago(roundMin), + watched: "precheck", + }); +} +const pr40 = (s: Sandbox, extra: Record = {}) => ({ + number: 40, + title: "Forty", + url: "https://gh/pr/40", + reviewDecision: "REVIEW_REQUIRED", + mergeable: "MERGEABLE", + body: "Fixes #4", + latestReviews: [], + statusCheckRollup: [{ name: "test", conclusion: "SUCCESS", completedAt: s.clock.ago(90) }], + ...extra, +}); + +test("a parked item the precheck watches: quiet costs nothing, what lands messages its session", () => + inSandbox(async (s) => { + watched(s); + gql(s, [pr40(s)]); + assert.equal((await pc(s)).rc, 1, "nothing landed: no run, no message"); + assert.equal(s.runtime.messages.length, 0); + for (const [why, extra, said] of [ + [ + "a review", + { latestReviews: [{ author: { login: "guardian" }, state: "CHANGES_REQUESTED", submittedAt: s.clock.ago(2) }] }, + /PR #40 reviewed; resolve every finding/, + ], + [ + "a person's comment", + { + comments: { + nodes: [ + { + author: { __typename: "User", login: "alice" }, + authorAssociation: "NONE", + body: "why?", + updatedAt: s.clock.ago(2), + }, + ], + }, + }, + /PR #40 commented; answer every comment/, + ], + [ + "a red check", + { statusCheckRollup: [{ name: "test", conclusion: "FAILURE", completedAt: s.clock.ago(2) }] }, + /PR #40 checks failed: test/, + ], + ["a conflict in review", { mergeable: "CONFLICTING" }, /PR #40 conflicting: rebase/], + ] as const) { + s.runtime.messages.length = 0; + rmSync(join(s.locks, "item-4"), { recursive: true, force: true }); + watched(s); + gql(s, [pr40(s, extra)]); + const r = await pc(s); + assert.equal(r.rc, 1, `${why}: a message, no run here`); + assert.equal(s.runtime.messages.length, 1, why); + assert.equal(s.runtime.messages[0]?.id, "sess-a"); + assert.match(s.runtime.messages[0]?.text ?? "", said); + assert.match(s.runtime.messages[0]?.text ?? "", /run-state\.sh" start 4/); + assert.match(s.read("locks/item-4/owner"), /^- messaged_at: /m); + // asked once: the next tick, still in its grace, sends nothing + assert.equal((await pc(s)).rc, 1); + assert.equal(s.runtime.messages.length, 1, `${why}: asked once`); + } + assert.match(s.read("work/TICK.log"), /messaged session=sess-a issue=4 slot=- pr=40 .*reason="landed: PR #40/); + })); + +test("what landed before the last round wakes nothing", () => + inSandbox(async (s) => { + watched(s, 30); + gql(s, [ + pr40(s, { + latestReviews: [{ author: { login: "guardian" }, state: "CHANGES_REQUESTED", submittedAt: s.clock.ago(40) }], + }), + ]); + assert.equal((await pc(s)).rc, 1); + assert.equal(s.runtime.messages.length, 0, "the round that parked it answered that review"); + })); + +test("a watched session that does not come back in time is handed to a fresh run", () => + inSandbox(async (s) => { + watched(s); + gql(s, [ + pr40(s, { latestReviews: [{ author: { login: "guardian" }, state: "COMMENTED", submittedAt: s.clock.ago(2) }] }), + ]); + assert.equal((await pc(s)).rc, 1); + assert.equal(s.runtime.messages.length, 1); + s.clock.advance(16 * 60); + const r = await pc(s); + assert.equal(r.rc, 0, "its grace is over: a fresh run takes the review"); + assert.match(r.out, /stopped without finishing/); + assert.match(r.out, /#4 — PR #40 Forty — reviewed/); + assert.equal(s.runtime.messages.length, 1, "not asked twice"); + })); + +test("a message the platform does not queue hands the watched item to a fresh run at once", () => + inSandbox(async (s) => { + watched(s); + s.runtime.queues = false; + gql(s, [pr40(s, { statusCheckRollup: [{ name: "test", conclusion: "FAILURE", completedAt: s.clock.ago(2) }] })]); + const r = await pc(s); + assert.equal(r.rc, 0); + assert.match(r.out, /#4 parked, and its session could not be reached/); + assert.match(r.out, /#4 — PR #40 Forty — checks failed: test/); + assert.ok(!existsSync(join(s.locks, "item-4")), "handed on"); + assert.match(s.read("work/TICK.log"), /abandoned session=sess-a issue=4 .*its session not reached/); + })); + +test("a watched item whose pull request merged wakes its session to release it", () => + inSandbox(async (s) => { + watched(s, 60, "awaiting-merge"); + gql(s, []); + s.github.prViews = [{ state: "OPEN" }]; + assert.equal((await pc(s)).rc, 1, "the search lags, the pull request is still open: nothing"); + assert.equal(s.runtime.messages.length, 0); + s.github.prViews = [{ state: "MERGED" }]; + assert.equal((await pc(s)).rc, 1); + assert.match(s.runtime.messages[0]?.text ?? "", /merged or closed: release the issue/); + s.runtime.queues = false; + rmSync(join(s.locks, "item-4"), { recursive: true, force: true }); + watched(s, 60, "awaiting-merge"); + const r = await pc(s); + assert.equal(r.rc, 0, "not reached: listed to release"); + assert.match(r.out, /Merged or closed while parked — release:\n- #4 — its pull request is merged or closed/); + })); + test("merged while parked with nothing to see it: the precheck lists it to release", () => inSandbox(async (s) => { s.item("4", { state: "awaiting-merge", pr: "40" }); diff --git a/app/test/run-state.test.ts b/app/test/run-state.test.ts index 8f82053..b6e4e69 100644 --- a/app/test/run-state.test.ts +++ b/app/test/run-state.test.ts @@ -26,6 +26,9 @@ function world(s: Sandbox): void { } const as = (s: Sandbox, session: string, ...args: string[]) => s.run(runState, args, { CLAUDE_CODE_SESSION_ID: session, SD_WAIT_FOR: "3", SD_WAIT_POLL: "1" }); +/** No tick runs, so nothing but a waiter watches a parked item. */ +const noTick = (s: Sandbox) => + s.write("work/CONFIG.md", s.read("work/CONFIG.md").replace("\n## Bounds", "- schedules: audit\n\n## Bounds")); const locks = (s: Sandbox) => (existsSync(s.locks) ? readdirSync(s.locks) : []); test("start takes the item and a slot, on a new branch", () => @@ -722,6 +725,7 @@ const COMMENTS21 = /^repos\/[^/]+\/[^/]+\/issues\/21\/comments/; test("park frees the slot and the exclusive lock, keeps the item, and needs the round reported", () => inSandbox(async (s) => { world(s); + noTick(s); s.originCheckout(); s.github.on(PULL, PULL21); s.github.prViews = [view("OPEN", "REVIEW_REQUIRED", "MERGEABLE", GREEN)]; @@ -779,6 +783,7 @@ test("approved, it parks awaiting the merge", () => test("the waiter wakes its session for a comment after approval, and for the merge", () => inSandbox(async (s) => { world(s); + noTick(s); s.originCheckout(); s.github.on(PULL, PULL21); s.github.prViews = [view("OPEN", "APPROVED", "MERGEABLE", GREEN)]; @@ -828,6 +833,7 @@ test("the waiter wakes its session for a comment after approval, and for the mer test("a second waiter steps aside, and a waiter whose session took its item back stops", () => inSandbox(async (s) => { world(s); + noTick(s); s.originCheckout(); s.github.on(PULL, PULL21); s.github.prViews = [view("OPEN", "REVIEW_REQUIRED", "MERGEABLE", GREEN)]; @@ -846,9 +852,80 @@ test("a second waiter steps aside, and a waiter whose session took its item back assert.equal(w.rc, 1, "nothing parked any more"); })); +test("with the tick on, park leaves the precheck watching: no waiter, and a restart frees nothing", () => + inSandbox(async (s) => { + world(s); + s.originCheckout(); + s.github.on(PULL, PULL21); + s.github.prViews = [view("OPEN", "REVIEW_REQUIRED", "MERGEABLE", GREEN)]; + await as(s, "sess-a", "start", "7", "feat/7"); + const r = await as(s, "sess-a", "park", "21"); + assert.equal(r.rc, 0, r.err); + assert.match(r.out, /end the turn, with nothing left running: the precheck watches it/); + assert.doesNotMatch(r.out, /wait --park/); + assert.match(s.read("locks/item-7/owner"), /^- watched: precheck$/m); + assert.equal((await as(s, "sess-a", "may-stop")).rc, 0, "at rest with nothing running"); + s.runtime.running.delete("sess-a"); + s.clock.advance(6 * 3600); + await as(s, "sess-b", "sweep"); + assert.ok(existsSync(join(s.locks, "item-7")), "the precheck holds it: not abandoned"); + assert.equal(s.runtime.messages.length, 0, "nobody is asked to restart anything"); + assert.equal((await as(s, "sess-b", "start", "7", "feat/7")).rc, 1, "no other run takes it"); + })); + +test("an item parked with a waiter is handed to the precheck: its lost waiter, or wait --park", () => + inSandbox(async (s) => { + world(s); + s.originCheckout(); + s.github.on(PULL, PULL21); + s.github.prViews = [view("OPEN", "REVIEW_REQUIRED", "MERGEABLE", GREEN)]; + await as(s, "sess-a", "start", "7", "feat/7"); + await as(s, "sess-a", "park", "21"); + // as a version before this one parked it: a waiter and no watch + s.write("locks/item-7/owner", s.read("locks/item-7/owner").replace(/^- watched: .*\n/m, "")); + s.runtime.running.delete("sess-a"); + await as(s, "sess-b", "sweep"); + assert.ok(existsSync(join(s.locks, "item-7")), "its waiter lost to a restart: watched, not abandoned"); + assert.equal(s.runtime.messages.length, 0, "no message to start a waiter"); + assert.match(s.read("locks/item-7/owner"), /^- watched: precheck$/m); + // one that starts its waiter anyway hands it over at once + s.write("locks/item-7/owner", s.read("locks/item-7/owner").replace(/^- watched: .*\n/m, "")); + s.runtime.running.add("sess-a"); + const r = await s.run(runState, ["wait", "--park"], { CLAUDE_CODE_SESSION_ID: "sess-a", SD_WAITER_PID: "777" }); + assert.equal(r.rc, 5); + assert.match(r.out, /the precheck watches it/); + assert.match(s.read("locks/item-7/owner"), /^- watched: precheck$/m); + assert.doesNotMatch(s.read("locks/item-7/owner"), /^- waiter:/m); + })); + +test("woken by the precheck while every slot is busy, it stays parked and watched", () => + inSandbox(async (s) => { + world(s); + s.originCheckout(); + s.github.on(PULL, PULL21); + s.github.prViews = [view("OPEN", "REVIEW_REQUIRED", "MERGEABLE", GREEN)]; + await as(s, "sess-a", "start", "7", "feat/7"); + await as(s, "sess-a", "park", "21"); + s.write("locks/item-7/owner", `${s.read("locks/item-7/owner")}- messaged_at: ${s.clock.ago(1)}\n`); + for (const [sess, n] of [ + ["sess-b", "8"], + ["sess-c", "9"], + ["sess-d", "10"], + ] as const) { + s.runtime.running.add(sess); + assert.equal((await as(s, sess, "start", n, `feat/${n}`)).rc, 0); + } + const r = await as(s, "sess-a", "start", "7"); + assert.equal(r.rc, 1); + assert.match(r.err, /the precheck wakes this session again once a slot is free/); + assert.doesNotMatch(s.read("locks/item-7/owner"), /^- messaged_at:/m, "watched again, not waiting out a grace"); + assert.equal((await as(s, "sess-a", "may-stop")).rc, 0); + })); + test("a booked wake-up holds a parked item across a restart, and resumes the same session", () => inSandbox(async (s) => { world(s); + noTick(s); s.originCheckout(); s.github.on(PULL, PULL21); s.github.prViews = [view("OPEN", "REVIEW_REQUIRED", "MERGEABLE", GREEN)]; @@ -869,6 +946,7 @@ test("a booked wake-up holds a parked item across a restart, and resumes the sam test("a parked item with nothing left to wake it is handed on, and its next run says so", () => inSandbox(async (s) => { world(s); + noTick(s); s.originCheckout(); s.github.on(PULL, PULL21); s.github.prViews = [view("OPEN", "REVIEW_REQUIRED", "MERGEABLE", GREEN)]; @@ -889,6 +967,7 @@ test("a parked item with nothing left to wake it is handed on, and its next run test("a parked item whose waiter a restart killed asks its own session to start it again, once", () => inSandbox(async (s) => { world(s); + noTick(s); s.originCheckout(); s.github.on(PULL, PULL21); s.github.prViews = [view("OPEN", "REVIEW_REQUIRED", "MERGEABLE", GREEN)]; @@ -919,6 +998,7 @@ test("a parked item whose waiter a restart killed asks its own session to start test("a session messaged that starts no waiter in time is handed on to a fresh run", () => inSandbox(async (s) => { world(s); + noTick(s); s.originCheckout(); s.github.on(PULL, PULL21); s.github.prViews = [view("OPEN", "REVIEW_REQUIRED", "MERGEABLE", GREEN)]; @@ -937,6 +1017,7 @@ test("a session messaged that starts no waiter in time is handed on to a fresh r test("a message the platform does not queue, or a person's session, hands the item on at once", () => inSandbox(async (s) => { world(s); + noTick(s); s.originCheckout(); s.github.on(PULL, PULL21); s.github.prViews = [view("OPEN", "REVIEW_REQUIRED", "MERGEABLE", GREEN)]; @@ -963,6 +1044,7 @@ test("a message the platform does not queue, or a person's session, hands the it test("a parked item woken while every slot is busy stays parked, not freed", () => inSandbox(async (s) => { world(s); + noTick(s); s.originCheckout(); s.github.on(PULL, PULL21); s.github.prViews = [view("OPEN", "REVIEW_REQUIRED", "MERGEABLE", GREEN)]; @@ -1071,6 +1153,7 @@ test("wait refuses while the exclusive lock is held", () => test("may-stop: a held run may not; at rest it may", () => inSandbox(async (s) => { world(s); + noTick(s); s.originCheckout(); s.github.on(PULL, PULL21); s.github.prViews = [view("OPEN", "REVIEW_REQUIRED", "MERGEABLE", GREEN)]; diff --git a/docs/babysit.md b/docs/babysit.md index ed6ecba..d185cae 100644 --- a/docs/babysit.md +++ b/docs/babysit.md @@ -13,56 +13,57 @@ what it holds besides changes with whose move it is: | | Whose move | Holds | The turn | | --- | --- | --- | --- | | **Held** | yours: writing, checking, a review round | the item, a slot, the exclusive lock while you use it | runs; the Stop hook keeps it going | -| **Parked** | a person's: a review, a merge | the item alone | ends; a waiter wakes the session | +| **Parked** | a person's: a review, a merge | the item alone | ends, nothing running; the precheck wakes the session | **Park** once the round is pushed and reported and a person moves next: ```sh bash "$HOME/scripts/run-state.sh" park ... -bash "$HOME/scripts/run-state.sh" wait --park # as a background task ``` `park` refuses until the slot is pushed and this round's comment is on the pull request, like `finish`. Then it gives the slot and the exclusive lock back — nothing shared waits on a person — and marks the item `in-review`, or -`awaiting-merge` once every pull request is approved. Start its waiter as the -harness's own background task (Claude Code: `run_in_background`) and end the -turn: the Stop hook lets a parked turn end once its waiter runs. - -**The waiter** looks at the pull requests once a minute — an unchanged one -costs nothing (`app/src/factory/github.ts`) — for up to two hours. It exits -when one needs you: a review, **a person's comment** in the conversation or on -a line, a failed check, a conflict, or the merge. The harness hands its output -to the session as a new turn: `start` the item again — it takes a slot, back -to Held — and handle what woke you, in the next section. Exit `3` is two hours -of nothing: start it again, and end the turn. **A person typing in the -session** wakes it the same way: `start` the item. +`awaiting-merge` once every pull request is approved. End the turn with +nothing left running: the Stop hook lets a parked turn end. + +**The precheck watches it.** Every tick it reads your open pull requests anyway, +at no model cost; for a parked item it looks for what came after your last +round: a review, **a person's comment** in the conversation, a failed check, a +conflict, or the merge. One of them **messages the session** — a turn there, none in the +tick — with what landed: `start` the item again — it takes a slot, back to +Held — and handle it, in the next section. Asked once: not back within fifteen +minutes, or the message not queued, **a later run takes it over** — the +precheck lists it like a run that stopped, and a fresh session babysits it from +the branch and the pull request. Every slot in use, `start` says so and the item +stays parked, watched: end the turn, and the precheck asks again once a slot +frees. A restart loses nothing: no process waits in the sandbox. **A person +typing in the session** wakes it the same way: `start` the item. `TICK.log` +says which happened — `messaged`, then `resumed … cause=precheck|operator`, or +`cause=fresh prev=` — and the weekly audit counts them. + +**Without a tick to watch it** — the direct session, a Slack session, or +`schedules` without `tick` — `park` says to start its **waiter**, `run-state.sh +wait --park`, as the harness's own background task (Claude Code: +`run_in_background`, `timeout` two hours), then end the turn. It looks at the +pull requests once a minute — an unchanged one costs nothing +(`app/src/factory/github.ts`) — for up to two hours, wakes the session for the +same events, and exits `3` after two hours of nothing: start it again. A +restart kills it: in the direct session book a wake-up too — +`schedule_once` with `inSession: "continue"`, a little over two hours ahead, +then `run-state.sh booked ` — and delete the booking when +the waiter wakes you first (`start` reminds you). An item parked by a version +before the precheck watched hands itself over: the sweep finds its waiter gone, +and `wait --park` ends at once where the precheck watches. **A short wait** — checks that finish in minutes — needs no parking: `run-state.sh wait ...` blocks up to nine minutes in the turn, the slot kept. Exit `3` is nothing yet: call it again. `wait` refuses while you hold the exclusive lock: `unlock` first. -An item with pull requests in more than one repository parks and waits on them -all ([runs.md](runs.md) → **Other repositories**), and is merged only once -every one is. - -**A restart kills the waiter.** In the direct session, book a wake-up too, so -the same session comes back: `schedule_once` with `inSession: "continue"`, a -little over two hours ahead, then `run-state.sh booked `. -Woken by the waiter first, delete the booking (`start` reminds you). A -scheduled run may not change the platform's schedules (`CLAUDE.md` → **Hard -invariants**): its waiter alone holds the item. After a restart, **the sweep -asks the session to start it again**: it finds the parked item with nothing -left to wake it, sends its session a message (`send_session_message`), and -holds the item fifteen minutes for it. The message is a turn there: start the -waiter again, as it says, and end the turn — it looks from your last round on, -so what landed meanwhile wakes you at once. The message not queued, or no -waiter in time, **a later run takes it over** — the precheck lists it like a -run that stopped, and a fresh session babysits it from the top, from the branch -and the pull request. `TICK.log` says which happened — `messaged`, then -`resumed … cause=waiter|booking|operator`, or `cause=fresh prev=` — -and the weekly audit counts them. +An item with pull requests in more than one repository parks on them all +([runs.md](runs.md) → **Other repositories**), and is merged only once every +one is. ## The required check @@ -104,8 +105,8 @@ one round, so one push answers everything: (`CLAUDE.md` → **Trust boundary**). **A person's comment is findings too**, in the conversation or on a line. **After approval**, a review with findings or a comment from a maintainer — `OWNER`, `MEMBER` or - `COLLABORATOR` — is still a round; anyone else's is not, and the waiter - does not wake for it. A push may dismiss the approval: then re-request it. + `COLLABORATOR` — is still a round; anyone else's is not, and nothing + wakes you for it. A push may dismiss the approval: then re-request it. 3. **Conflicts.** Rebase on the default branch, run `verify` again. 4. **Push**, move its Environment's expiry on when it has one, and, with `demo_environment`, install the push there and retake the demo's @@ -139,7 +140,7 @@ skill, `CONTRIBUTING` — follow it, within the **Hard invariants**, for what one round does: how to mark it ready, whom to ask, how to answer findings. **Its waiting goes through `park` and `wait`.** Where it says to watch, poll or loop until a review or a check arrives, park instead (**Held, then parked**, -above): it frees what other runs need, and the waiter brings the session back. +above): it frees what other runs need, and the precheck brings the session back. **When you cannot get it green**, say so on the pull request — what fails, what you tried — and finish the run `blocked`. The precheck does not wake for the diff --git a/docs/direct-session.md b/docs/direct-session.md index 923e28a..a5c5751 100644 --- a/docs/direct-session.md +++ b/docs/direct-session.md @@ -26,6 +26,7 @@ precheck wakes nothing. What changes for a run: - **The session carries its pull request to the merge.** Open it, give the operator its link, then park it with its waiter running and a wake-up booked + — nothing watches it but the waiter ([babysit.md](babysit.md) → **Held, then parked**): a review, a comment — after approval too — a red check or the merge wakes this same session, and so does the operator typing here. No tick takes it over. `finish pr-opened ` diff --git a/docs/runs.md b/docs/runs.md index f69c1d1..58126e8 100644 --- a/docs/runs.md +++ b/docs/runs.md @@ -25,12 +25,12 @@ run takes it and every slot stays free for other work. **A lock never outlives its holder, nor dies before it.** A holder is the turn that took the lock, dead when the runtime says its session is not running a -turn. A parked item lock's holder is what wakes its session: its waiter, a -process on this boot, or a wake-up booked on the platform not yet past half an -hour overdue. With neither, the sweep messages the session once to start its -waiter again, and holds the item fifteen minutes for it ([babysit.md](babysit.md) → **Held, -then parked**); then it is dead like any other, and the next tick takes the -item over. A restart is +turn. A parked item lock's holder is what wakes its session: the precheck, +which watches it (`watched`); without a tick, its waiter, a process on this +boot, or a wake-up booked on the platform not yet past half an hour overdue. +Once the precheck messages the session for what landed, the item is held +fifteen minutes for it ([babysit.md](babysit.md) → **Held, then parked**); then +it is dead like any other, and the next tick takes the item over. A restart is no proof: the locks live on the home volume and survive it, and the platform resumes the interrupted turn, which still holds them. The direct session is the one exception: it ends its turns between the operator's messages and to wait diff --git a/docs/self-modification.md b/docs/self-modification.md index 7f137c5..93ac323 100644 --- a/docs/self-modification.md +++ b/docs/self-modification.md @@ -60,7 +60,8 @@ so to the operator. `work/.claude/skills` links. The one exception is `work-backup.sh`, which commits and pushes `work/`'s files to `work_repo` and touches nothing else. Its one message is to a session of this agent: - the sweep asks a parked item's session to start its lost waiter again + the precheck asks a parked item's session to take it back when something + landed on it, and the sweep one whose waiter was lost ([babysit.md](babysit.md) → **Held, then parked**), never a person's. - `CLAUDE.md` stays slim: run types, contracts, configuration, the trust boundary, invariants. Procedures live in `docs/`, each with its row in