toolroll 0.9.122 → 0.9.123

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,30 @@ Each release opens with one line on its theme, then **New**, **Changed**, **Fixe
4
4
  the ones it has). Each item is at most two lines and says where to find it. Notes for maintainers (CI, the release
5
5
  tooling) go on the GitHub release, not here. Entries before 0.9.104 use the older format.
6
6
 
7
+ ## 0.9.123 — 2026-11-26
8
+
9
+ Accepted work stays accepted, every command Toolroll gives you can be copied whole, and Toolroll stays quiet while
10
+ nothing runs.
11
+
12
+ ### Changed
13
+
14
+ - **Accepted work stays accepted** when its checks run again, in the task list, the browser and the workbench; a
15
+ failed re-check shows next to it and blocks Land with the reason.
16
+ - **Commands you need to run open in a sheet** in the workbench (Land, Save as branch, a Ship that can't open a pull
17
+ request): the whole command on its own line, and `c` copies it exactly.
18
+ - **Plan-limit checks run only while an agent is working** (or for ten minutes after you open Spend), never while
19
+ tasks just wait.
20
+ - **`toolroll task new` with a password set** asks for it, shows the terms, then builds; a wrong password files
21
+ nothing.
22
+ - **Landing from a shell on an install without a password** says to land from the workbench (B) or the task page.
23
+
24
+ ### Fixed
25
+
26
+ - **After you revert landed work yourself**, the task says "Landed on main (abc1234) · a later commit reverted it"
27
+ instead of "On main".
28
+ - **The page after Land** shows the task's current version; **ending a thread** offers Save as branch where Ship
29
+ can't work.
30
+
7
31
  ## 0.9.122 — 2026-11-26
8
32
 
9
33
  Share one pinned skill library across every project and agent, approve releases on one clear screen, and enjoy a cleaner Mac titlebar.
@@ -136,14 +136,14 @@ export function scheduleLimitsLoop(store, seams, everyMs = 5 * 60_000) {
136
136
  if (stopped || busy)
137
137
  return;
138
138
  const now = clock();
139
- if (!planLimitsWanted(store, now))
139
+ if (!planLimitsWanted(store, now, seams.alive))
140
140
  return;
141
141
  if (viewed && now.getTime() - lastPass < VIEWED_PASS_GAP_MS)
142
142
  return;
143
143
  busy = true;
144
144
  lastPass = now.getTime();
145
145
  try {
146
- const stillWanted = () => !stopped && planLimitsWanted(store, clock());
146
+ const stillWanted = () => !stopped && planLimitsWanted(store, clock(), seams.alive);
147
147
  await codexLimitsPass(store, { signedIn: seams.signedIn, stopped: () => stopped, stillWanted, ...(seams.readCodex === undefined ? {} : { read: seams.readCodex }) });
148
148
  if (stillWanted()) {
149
149
  await refreshSubscriptions(store, store.databaseFile(), { skipCodex: true, now: clock(), stillWanted, ...(seams.readers === undefined ? {} : { readers: seams.readers }) });
package/dist/first-run.js CHANGED
@@ -166,7 +166,7 @@ export function taskRoad(read, approved, built, facts) {
166
166
  if (waitsAtReady)
167
167
  steps = steps.map(step => step.key === "ready" ? { ...step, state: "stuck" } : step);
168
168
  const at = steps.find(step => step.key === "checks");
169
- if (facts.report !== true && at !== undefined && at.state === "stuck") {
169
+ if (facts.report !== true && at !== undefined && at.state === "stuck" && !complete) {
170
170
  steps = steps.map(step => step.key === "ready" && step.state === "done" ? { ...step, state: "todo" } : step);
171
171
  }
172
172
  if (facts.report === true) {
@@ -5,6 +5,7 @@ import { flexibleImportRef, importFlexibleCandidate, projectMergeHint, projectTh
5
5
  import { branchHeld, nextSeq, turnRunning } from "./flexible-ship.js";
6
6
  import { flexibleThread, flexibleThreadBranch, withFlexibleThreadLock } from "./flexible-thread.js";
7
7
  import { machineActing } from "./scope.js";
8
+ import { gitCommand, UNSAFE_FOLDER } from "./local-landing.js";
8
9
  const WORDS = Object.freeze({
9
10
  "machine-proof": "Only a person can save a thread's work. Nothing was saved.",
10
11
  "thread-unknown": "There's no such thread.",
@@ -19,7 +20,6 @@ const WORDS = Object.freeze({
19
20
  });
20
21
  const refuse = (reason) => ({ ok: false, reason, message: WORDS[reason] });
21
22
  export const flexibleSaveDigestOf = (terms) => createHash("sha256").update(`standing-orders:flexible-save:${canonicalJson(terms)}`, "utf8").digest("hex").slice(0, 32);
22
- const shellWord = (text) => /^[A-Za-z0-9_./~+@%=:,-]+$/.test(text) ? text : `'${text.replace(/'/g, "'\\''")}'`;
23
23
  function saverStanding(store, thread, by) {
24
24
  if (thread.createdBy !== by.name)
25
25
  return refuse("not-owner");
@@ -33,13 +33,13 @@ function saverStanding(store, thread, by) {
33
33
  async function nextWords(store, thread, candidate, branch, runner) {
34
34
  const hint = await projectMergeHint(store, { thread, candidate, ...(runner === undefined ? {} : { runner }) });
35
35
  if (hint === null)
36
- return `To use it: merge ${branch} in your repository.`;
37
- const repo = shellWord(hint.repo);
36
+ return { next: `To use it: merge ${branch} in your repository.`, command: null };
37
+ const ff = gitCommand(hint.repo, ["merge", "--ff-only", branch]), merge = gitCommand(hint.repo, ["merge", branch]);
38
38
  if (hint.branch === null)
39
- return `To use it: check out the branch you want it on, then run \`git -C ${repo} merge --ff-only ${branch}\`.`;
39
+ return { next: `To use it: check out the branch you want it on, then ${ff === null ? UNSAFE_FOLDER(`git merge --ff-only ${branch}`) : `run \`${ff}\`.`}`, command: ff };
40
40
  if (hint.fastForward)
41
- return `To put it on ${hint.branch}: \`git -C ${repo} merge --ff-only ${branch}\`.`;
42
- return `${hint.branch} moved since the thread started, so it won't fast-forward. To merge it: \`git -C ${repo} merge ${branch}\`.`;
41
+ return { next: ff === null ? `To put it on ${hint.branch}: ${UNSAFE_FOLDER(`git merge --ff-only ${branch}`)}` : `To put it on ${hint.branch}: \`${ff}\`.`, command: ff };
42
+ return { next: `${hint.branch} moved since the thread started, so it won't fast-forward. ${merge === null ? UNSAFE_FOLDER(`git merge ${branch}`) : `To merge it: \`${merge}\`.`}`, command: merge };
43
43
  }
44
44
  export async function saveFlexibleBranch(store, input) {
45
45
  if (machineActing())
@@ -67,7 +67,7 @@ export async function saveFlexibleBranch(store, input) {
67
67
  return refuse("branch-gone");
68
68
  if (actual !== read.candidate)
69
69
  return refuse("branch-moved");
70
- return { ok: true, already: true, branch, candidate: read.candidate, seq: null, changedPaths: read.changedPaths, next: await nextWords(store, input.thread, read.candidate, branch, input.runner) };
70
+ return { ok: true, already: true, branch, candidate: read.candidate, seq: null, changedPaths: read.changedPaths, ...(await nextWords(store, input.thread, read.candidate, branch, input.runner)) };
71
71
  }
72
72
  const at = input.now.toISOString();
73
73
  const recorded = store.transact(() => {
@@ -105,7 +105,7 @@ export async function saveFlexibleBranch(store, input) {
105
105
  return imported;
106
106
  }
107
107
  store.transact(() => { store.handle.prepare("UPDATE flexible_ship SET state = 'imported', state_at = ? WHERE id = ? AND state = 'approved'").run(at, recorded.digest); });
108
- return { ok: true, already: false, branch, candidate: read.candidate, seq: recorded.seq, changedPaths: read.changedPaths, next: await nextWords(store, input.thread, read.candidate, branch, input.runner) };
108
+ return { ok: true, already: false, branch, candidate: read.candidate, seq: recorded.seq, changedPaths: read.changedPaths, ...(await nextWords(store, input.thread, read.candidate, branch, input.runner)) };
109
109
  });
110
110
  if (locked.ok === false && (locked.reason === "not-available" || locked.reason === "thread-unknown"))
111
111
  return refuse("thread-unknown");
@@ -215,7 +215,7 @@ export async function readLanding(store, taskId, access, now, options) {
215
215
  const checks = receipt.checks.status === "passed" ? "passed" : !projectCheckSet(store, project.repo) && receipt.checks.status === "not-run" ? "none" : null;
216
216
  if (checks === null) {
217
217
  if (receipt.checks.status === "failed")
218
- return refuse("checks", later ? `Its checks failed when they ran again after you accepted it (${receipt.checks.detail}). It stays Complete; it can't land until they pass on its exact commit.`
218
+ return refuse("checks", later ? `Its checks failed when they ran again after you accepted it (${receipt.checks.detail.replace(/\.$/, "")}). It stays Complete; it can't land until they pass on its exact commit.`
219
219
  : "Its checks failed. Only work whose checks passed on its exact commit lands.");
220
220
  return refuse("checks", later ? "Its checks changed since you accepted it and haven't run on its exact commit since. Run checks (it stays Complete), then land it."
221
221
  : "Its checks haven't passed on its exact commit. Run checks, then land it.");
@@ -636,13 +636,14 @@ function oidOrThrow(oid) {
636
636
  throw new Error("not a commit id");
637
637
  return oid;
638
638
  }
639
- const UNSAFE_IN_COMMAND = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/;
639
+ const UNSAFE_IN_COMMAND = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/;
640
+ export const unsafeInCommand = (text) => UNSAFE_IN_COMMAND.test(text);
640
641
  export function gitCommand(folder, args) {
641
642
  if (UNSAFE_IN_COMMAND.test(folder))
642
643
  return null;
643
644
  return ["git", "-C", `'${folder.replace(/'/g, "'\\''")}'`, ...args].join(" ");
644
645
  }
645
- const UNSAFE_FOLDER = (what) => `Toolroll can't write a safe command for this folder's name; run ${what} in your project folder.`;
646
+ export const UNSAFE_FOLDER = (what) => `Toolroll can't write a safe command for this folder's name; run ${what} in your project folder.`;
646
647
  function handoffCommand(folder, commit) {
647
648
  return gitCommand(folder, ["merge", "--ff-only", oidOrThrow(commit)]);
648
649
  }
@@ -735,12 +736,45 @@ async function revertCommit(git, plan, scratch) {
735
736
  await git(["worktree", "prune"]).catch(() => null);
736
737
  }
737
738
  }
738
- export function landedWords(store, rootId) {
739
+ export function landedWords(store, rootId, read) {
740
+ return landedStanding(store, rootId, read)?.words ?? null;
741
+ }
742
+ export function landedStanding(store, rootId, read) {
739
743
  const landed = landingOf(store, rootId);
740
744
  if (landed === null)
741
745
  return null;
742
- return landed.undone ? `Landed on ${landed.intent.ref.replace(/^refs\/heads\//, "")} (${short(landed.intent.commit)}), then undone.`
743
- : `Landed on ${landed.intent.ref.replace(/^refs\/heads\//, "")} (${short(landed.intent.commit)}).`;
746
+ const where = `Landed on ${landed.intent.ref.replace(/^refs\/heads\//, "")} (${short(landed.intent.commit)})`;
747
+ if (landed.undone)
748
+ return { words: `${where}, then undone.`, reverted: false };
749
+ const reverted = read !== undefined && revertedOnBranch(landed.intent.repo, landed.intent.ref, landed.intent, read);
750
+ return { words: reverted ? `${where} · a later commit reverted it` : `${where}.`, reverted };
751
+ }
752
+ export function revertedOnBranch(repo, ref, landing, read) {
753
+ if (!OID.test(landing.old) || !OID.test(landing.commit) || !ref.startsWith("refs/heads/"))
754
+ return false;
755
+ const parents = read(repo, ["rev-list", "--parents", "-n", "1", landing.commit])?.split(" ") ?? [];
756
+ if (parents.length !== 2 || parents[0] !== landing.commit || parents[1] !== landing.old)
757
+ return false;
758
+ const changes = (raw) => {
759
+ const lines = raw.split("\n").filter(line => line.startsWith(":"));
760
+ const keys = [];
761
+ for (const line of lines) {
762
+ const match = /^:(\d{6}) (\d{6}) ([0-9a-f]{40}|[0-9a-f]{64}) ([0-9a-f]{40}|[0-9a-f]{64}) [A-Z]\d*\t(.+)$/.exec(line);
763
+ if (match === null)
764
+ return null;
765
+ keys.push(`${match[1]} ${match[2]} ${match[3]} ${match[4]}\t${match[5]}`);
766
+ }
767
+ return keys.sort();
768
+ };
769
+ const own = read(repo, ["diff-tree", "-r", "--no-renames", "--no-abbrev", "--no-commit-id", "--no-ext-diff", "--no-textconv", landing.commit]);
770
+ const mine = own === null ? null : changes(own);
771
+ if (mine === null || mine.length === 0)
772
+ return false;
773
+ const inverse = mine.map(key => { const [modes, path] = key.split("\t"); const [m1, m2, s1, s2] = modes.split(" "); return `${m2} ${m1} ${s2} ${s1}\t${path}`; }).sort().join("\n");
774
+ const later = read(repo, ["log", "--no-show-signature", "--no-merges", "--ancestry-path", "-n", "50", "--format=%x01%H", "--raw", "--no-renames", "--no-abbrev", "--no-ext-diff", "--no-textconv", `${landing.commit}..${ref}`]);
775
+ if (later === null)
776
+ return false;
777
+ return later.split("\u0001").slice(1).some(entry => changes(entry.slice(entry.indexOf("\n") + 1))?.join("\n") === inverse);
744
778
  }
745
779
  export function recognisedOnBranch(store, repo, rootId, candidate, read) {
746
780
  if (candidate === null || !OID.test(candidate))
@@ -749,8 +783,14 @@ export function recognisedOnBranch(store, repo, rootId, candidate, read) {
749
783
  const ref = recorded ?? (() => { const head = read(repo, ["symbolic-ref", "-q", "HEAD"]); return head !== null && head.startsWith("refs/heads/") ? head : null; })();
750
784
  if (ref === null || !landableBranch(ref.slice("refs/heads/".length)))
751
785
  return null;
752
- const commits = [candidate, ...handoffsOf(store, repo, rootId).filter(one => one.candidate === candidate && one.ref === ref).map(one => one.commit)];
753
- return commits.some(commit => read(repo, ["merge-base", "--is-ancestor", commit, ref]) !== null) ? `On ${ref.slice("refs/heads/".length)}` : null;
786
+ const handed = handoffsOf(store, repo, rootId).filter(one => one.candidate === candidate && one.ref === ref);
787
+ const found = [{ commit: candidate, old: null }, ...handed.map(one => ({ commit: one.commit, old: one.old }))]
788
+ .find(one => read(repo, ["merge-base", "--is-ancestor", one.commit, ref]) !== null);
789
+ if (found === undefined)
790
+ return null;
791
+ const reverted = found.old !== null && revertedOnBranch(repo, ref, { old: found.old, commit: found.commit }, read);
792
+ const where = `Landed on ${ref.slice("refs/heads/".length)} (${short(found.commit)})`;
793
+ return { words: reverted ? `${where} · a later commit reverted it` : where, reverted };
754
794
  }
755
795
  export function broughtInOnBranch(store, repo, rootId, read) {
756
796
  const landed = landedCommits(store, rootId);
package/dist/operate.js CHANGED
@@ -367,7 +367,7 @@ export const OPERATE_HELP = `toolroll — operating the queue
367
367
  toolroll task complete <id> mark the current result complete (--digest for JSON/agents);
368
368
  [--pull-request] --pull-request also opens its pull request
369
369
  toolroll task land <id> put accepted work on the project's own branch (no pull requests): shows what lands
370
- where, then --yes --key <key> lands it as one commit; --undo reverts it
370
+ where, then --yes --key <preview-key> lands it as one commit; --undo reverts it
371
371
  toolroll task merge <id> --as <you> --token <t>
372
372
  merge the task's pull request once checks pass
373
373
  [--anyway] merge without waiting for the full check
@@ -7730,7 +7730,7 @@ function taskAction(action, rest, flags, context) {
7730
7730
  return fail(context.write, context.json, "task", "usage", `unknown \`task ${action ?? ""}\` — try ${TASK_ACTIONS.join(", ")}`, EXIT.usage);
7731
7731
  }
7732
7732
  }
7733
- async function addTask(positional, flags, context) {
7733
+ async function addTask(positional, flags, context, fromNew = false) {
7734
7734
  const { store, write, json, now } = context;
7735
7735
  const title = positional.join(" ").trim();
7736
7736
  if (title === "")
@@ -7838,7 +7838,7 @@ async function addTask(positional, flags, context) {
7838
7838
  }
7839
7839
  }
7840
7840
  const next = filedRef !== null && filedRef.repo !== null && filedRef.plan === null && !flags.has("report")
7841
- ? "Next: run `toolroll`, select it and press p to ask for a plan. To build without a plan, file it with `toolroll task new` instead." : null;
7841
+ ? `Next: run \`toolroll\`, select it and press p to ask for a plan.${fromNew ? "" : " To build without a plan, file it with `toolroll task new` instead."}` : null;
7842
7842
  return succeed(write, json, "task add", {
7843
7843
  task: outcome.task,
7844
7844
  ...(replaces === undefined ? {} : { replaces }),
@@ -7887,16 +7887,17 @@ async function runTaskChecks(positional, flags, context) {
7887
7887
  const state = done?.state ?? "waiting";
7888
7888
  const words = `${CHECK_LEVEL_WORDS[asked.level]} checks`;
7889
7889
  const payload = { task: taskId, run: result.runId, head: result.head, request: asked.request, level: asked.level, state, exitCode: done?.exitCode ?? null };
7890
+ const complete = assignmentOf(store, taskId, clock(), { principal: "operator", repos: null, includeUnplaced: true }, context.evidenceRoot)?.state === "complete";
7890
7891
  if (state === "failed") {
7891
7892
  if (json) {
7892
7893
  write(envelopeJson({ ok: false, command: "task checks", reason: "checks-failed", ...payload }));
7893
7894
  return EXIT.failed;
7894
7895
  }
7895
- write(`${words} failed on ${result.head.slice(0, 7)}${done?.exitCode == null ? "" : ` (exit ${done.exitCode})`}. The result shows the failure.`);
7896
+ write(`${words} failed on ${result.head.slice(0, 7)}${done?.exitCode == null ? "" : ` (exit ${done.exitCode})`}. ${complete ? "It stays Complete; it can't land until they pass on its exact commit." : "The result shows the failure."}`);
7896
7897
  return EXIT.failed;
7897
7898
  }
7898
7899
  return succeed(write, json, "task checks", payload, () => [
7899
- state === "passed" ? `${words} passed on ${result.head.slice(0, 7)}. The result's status is upgraded.`
7900
+ state === "passed" ? `${words} passed on ${result.head.slice(0, 7)}.${complete ? " It stays Complete." : ""}`
7900
7901
  : state === "running" ? `${words} are already running on ${result.head.slice(0, 7)}.`
7901
7902
  : state === "not-run" ? `${words} didn't run: ${done?.note ?? "see the result's log"}`
7902
7903
  : `${words} are queued on ${result.head.slice(0, 7)}.`,
@@ -8208,7 +8209,7 @@ function showTask(positional, context) {
8208
8209
  ...(detail.hold === null ? [] : [` held: ${detail.hold.reason}`]),
8209
8210
  ...detail.steering.slice(-5).map(one => ` note #${one.id} to the agent: ${one.words}`),
8210
8211
  ...(detail.claim === null ? [] : [` claimed by ${detail.claim.runner} until ${detail.claim.expiresAt}`]),
8211
- ...(detail.dispatch === null ? [] : [` dispatch: ${detail.dispatch.detail.startsWith(detail.dispatch.summary) ? detail.dispatch.detail : `${detail.dispatch.summary} — ${detail.dispatch.detail}`}`]),
8212
+ ...(detail.dispatch === null || shared?.headline === "Complete" ? [] : [` dispatch: ${detail.dispatch.detail.startsWith(detail.dispatch.summary) ? detail.dispatch.detail : `${detail.dispatch.summary} — ${detail.dispatch.detail}`}`]),
8212
8213
  ...(detail.control.kind === "none"
8213
8214
  ? []
8214
8215
  : detail.control.kind === "stop"
@@ -12056,7 +12057,7 @@ async function newTaskCommand(positional, flags, context) {
12056
12057
  return fail(write, json, command, "person-only", "Only a person starts a build this way. File it with `task add`.", EXIT.refused);
12057
12058
  if (local === null && (json || !personAtTerminal(context)))
12058
12059
  return fail(write, json, command, "person-only", "`task new` asks a person at a terminal. Use `task add` from a script or an agent.", EXIT.refused);
12059
- const { name, token } = credentialsFrom(flags, context);
12060
+ let { name, token } = credentialsFrom(flags, context);
12060
12061
  const passwordFree = token !== undefined && (local !== null || sessionStandsIn(store));
12061
12062
  const facts = { passwordless: local === null && passwordFree, localOwner: local !== null, freshAt: null, returnTo: "/" };
12062
12063
  const buildNow = (preview, digest) => fastStartBuild(store, { preview, digest, actor: name ?? "", via: local === null ? "cli" : "terminal-ui", password: facts,
@@ -12078,6 +12079,29 @@ async function newTaskCommand(positional, flags, context) {
12078
12079
  if (words === "" || repo === undefined)
12079
12080
  return fail(write, json, command, "usage", "`toolroll task new \"<what should change>\" --repo <project>`", EXIT.usage);
12080
12081
  const placed = canonicalProject(repo) ?? resolve(repo);
12082
+ if (local === null && (flags.has("token") || (!facts.passwordless && !passwordFreeOwner(store)))) {
12083
+ let given = flags.has("token") ? token : undefined;
12084
+ if (given === undefined) {
12085
+ const usual = name === undefined ? soloOperatorOf(store) : null;
12086
+ if (name === undefined) {
12087
+ const answered = await (context.easySeams?.ask ?? ask)(usual === null ? "username: " : `username [${usual}]: `);
12088
+ name = answered === "" && usual !== null ? usual : answered;
12089
+ }
12090
+ given = await (context.easySeams?.askHidden ?? askHidden)("password: ");
12091
+ }
12092
+ else if (name === undefined)
12093
+ name = soloOperatorOf(store) ?? undefined;
12094
+ if (name === undefined || name === "" || given === "") {
12095
+ write("Nothing was filed.");
12096
+ return EXIT.refused;
12097
+ }
12098
+ const person = name;
12099
+ const proved = verifyApproverByPassword(store, person, given, store.knownRepos().filter(one => store.accountCanAccess(person, one)));
12100
+ if (!proved.ok)
12101
+ return fail(write, json, command, "unauthenticated", "That username and password didn't work. Nothing was filed.", EXIT.refused);
12102
+ token = given;
12103
+ facts.freshAt = clock().getTime();
12104
+ }
12081
12105
  const prepared = name === undefined || token === undefined ? { eligible: false, reason: "password" }
12082
12106
  : await prepareFastStart(store, { actor: name, repo: placed, title: words, via: local === null ? "cli" : "terminal-ui", password: facts }, clock());
12083
12107
  const terms = prepared.eligible ? fastTermsLines(store, prepared.scope, placed) : [];
@@ -12088,7 +12112,7 @@ async function newTaskCommand(positional, flags, context) {
12088
12112
  }
12089
12113
  if (!prepared.eligible) {
12090
12114
  write(`${fastRefusalWords(prepared.reason)} Filing it for a plan.`);
12091
- return addTask([words], flags, context);
12115
+ return addTask([words], flags, context, true);
12092
12116
  }
12093
12117
  write("Build approves exactly this:");
12094
12118
  write("");
@@ -13196,7 +13220,8 @@ async function threadCommand(positional, flags, context) {
13196
13220
  return fail(write, json, command, done.reason, done.message, EXIT.refused);
13197
13221
  if (done.stopPending)
13198
13222
  await stopFlexibleThreadsEverywhere(store, { reason: "its owner ended the thread", thread, clock });
13199
- return succeed(write, json, command, { thread, already: done.already }, () => [done.already ? "This thread had already ended." : "Ended. You can still ship its work for a week; then its copy is tidied."]);
13223
+ const keeps = flexibleShipNeedsFor(store, thread) === null ? "ship its work, or save it as a branch," : `save its work as a branch (\`toolroll thread save ${thread.slice(0, 8)}\`)`;
13224
+ return succeed(write, json, command, { thread, already: done.already }, () => [done.already ? "This thread had already ended." : `Ended. You can still ${keeps} for a week; then its copy is tidied.`]);
13200
13225
  }
13201
13226
  if (verb === "save") {
13202
13227
  const saved = await saveFlexibleBranch(store, { thread, by: { name: who.name, generation: account.generation }, now: clock(), prove: proveNow });
@@ -13397,7 +13422,7 @@ async function landTaskCommand(positional, flags, context) {
13397
13422
  return fail(write, json, command, "usage", `--${key} is not a ${command} option.`, EXIT.usage);
13398
13423
  const id = positional[0] === undefined ? undefined : resolveTaskId(store, positional[0]);
13399
13424
  if (id === undefined || positional.length !== 1)
13400
- return fail(write, json, command, "usage", "Use `toolroll task land <id>` to see what landing does, then `--yes --key <key>` to land it.", EXIT.usage);
13425
+ return fail(write, json, command, "usage", "Use `toolroll task land <id>` to see what landing does, then `--yes --key <preview-key>` to land it.", EXIT.usage);
13401
13426
  const into = text(flags, "into"), undo = flags.get("undo") === true, yes = flags.get("yes") === true, key = text(flags, "key");
13402
13427
  if (flags.has("into") && into === undefined)
13403
13428
  return fail(write, json, command, "usage", "--into needs a branch name.", EXIT.usage);
@@ -13418,6 +13443,8 @@ async function landTaskCommand(positional, flags, context) {
13418
13443
  if (!("plan" in read))
13419
13444
  return succeed(write, json, command, { landed: read.landed }, () => [`${id} · Landed on ${read.landed.ref.replace(/^refs\/heads\//, "")} (${read.landed.commit.slice(0, 7)}).`]);
13420
13445
  const plan = read.plan;
13446
+ if (local === null && passwordFreeOwner(store))
13447
+ return succeed(write, json, command, { plan }, () => [...landingWords(plan), LAND_NEEDS_PASSWORD]);
13421
13448
  return succeed(write, json, command, { plan }, () => [...landingWords(plan),
13422
13449
  `To ${undo ? "undo it" : "land it"}: toolroll task land ${id}${into === undefined ? "" : ` --into ${into}`}${undo ? " --undo" : ""} --yes --key ${plan.key}${local === null ? " --as <you>" : ""}`,
13423
13450
  ...(local === null ? ["That asks for your Toolroll password."] : [])]);
@@ -13427,6 +13454,8 @@ async function landTaskCommand(positional, flags, context) {
13427
13454
  let authority;
13428
13455
  if (local !== null)
13429
13456
  authority = { kind: "local" };
13457
+ else if (passwordFreeOwner(store))
13458
+ return fail(write, json, command, "unauthenticated", LAND_NEEDS_PASSWORD, EXIT.refused);
13430
13459
  else {
13431
13460
  const acting = await askCredentials(flags, context);
13432
13461
  const ref = store.lookupRef(id);
@@ -13475,3 +13504,4 @@ function verifyRepoOf(store, raw) {
13475
13504
  }
13476
13505
  return absolute;
13477
13506
  }
13507
+ const LAND_NEEDS_PASSWORD = "Land it from the workbench (B) or the task page in the browser; from a shell it needs a Toolroll password (`toolroll password set`).";
@@ -1,5 +1,14 @@
1
+ import { realCustodyIO } from "./flexible-custody.js";
2
+ function processesNow() {
3
+ let table;
4
+ return (pid, start) => {
5
+ if (table === undefined)
6
+ table = realCustodyIO(() => null).table();
7
+ return table?.some(row => row.pid === pid && !row.zombie && row.start === start) ?? false;
8
+ };
9
+ }
10
+ const PROCESS_ROWS_AT_MOST = 500;
1
11
  export const PLAN_LIMITS_VIEW_WINDOW_MS = 10 * 60_000;
2
- const QUEUED_RECENTLY_MS = 60 * 60_000;
3
12
  const RUNNING_AT_MOST_MS = 6 * 3_600_000;
4
13
  const viewedAt = new WeakMap();
5
14
  const listeners = new WeakMap();
@@ -26,20 +35,33 @@ function any(store, sql, ...values) {
26
35
  return false;
27
36
  }
28
37
  }
29
- export function agentWorkActive(store, now) {
30
- const queuedSince = new Date(now.getTime() - QUEUED_RECENTLY_MS).toISOString();
38
+ function processesOf(store, sql, ...values) {
39
+ try {
40
+ return store.handle.prepare(sql).all(...values).flatMap(row => typeof row["pid"] === "number" && typeof row["start"] === "string" && row["start"] !== ""
41
+ ? [{ pid: row["pid"], start: row["start"] }] : []);
42
+ }
43
+ catch {
44
+ return [];
45
+ }
46
+ }
47
+ export function agentWorkActive(store, now, alive = processesNow()) {
48
+ const at = now.toISOString();
31
49
  const runningSince = new Date(now.getTime() - RUNNING_AT_MOST_MS).toISOString();
32
- return any(store, "SELECT 1 FROM task WHERE state = 'running' OR (state = 'queued' AND updated_at > ?) LIMIT 1", queuedSince)
33
- || any(store, "SELECT 1 FROM run WHERE outcome IS NULL AND started_at > ? LIMIT 1", runningSince)
34
- || any(store, "SELECT 1 FROM thread_turn WHERE status IN ('admitted', 'running') AND admitted_at > ? LIMIT 1", runningSince)
35
- || any(store, "SELECT 1 FROM direct_chat_turn WHERE status = 'running' AND created_at > ? LIMIT 1", runningSince)
36
- || any(store, "SELECT 1 FROM lead_queue WHERE status IN ('queued', 'running') LIMIT 1");
50
+ const living = (rows) => rows.some(one => alive(one.pid, one.start));
51
+ return any(store, `SELECT 1 FROM run r JOIN claim c ON c.lease_id = r.lease_id WHERE r.outcome IS NULL AND r.started_at > ?
52
+ AND c.released_at IS NULL AND c.expires_at > ? LIMIT 1`, runningSince, at)
53
+ || any(store, `SELECT 1 FROM lead_queue q JOIN mate_turn m ON m.id = q.turn_id WHERE q.status = 'running' AND q.claimed_at > ?
54
+ AND m.state = 'running' AND m.deadline_at > ? LIMIT 1`, runningSince, at)
55
+ || living(processesOf(store, `SELECT l.leader_pid AS pid, l.leader_start AS start FROM thread_turn t JOIN flexible_thread_launch l ON l.turn = t.id
56
+ WHERE t.status = 'running' AND t.started_at > ? AND l.state = 'live' LIMIT ${PROCESS_ROWS_AT_MOST}`, runningSince))
57
+ || living(processesOf(store, `SELECT pid, start_identity AS start FROM direct_chat_turn WHERE status = 'running' AND created_at > ?
58
+ LIMIT ${PROCESS_ROWS_AT_MOST}`, runningSince));
37
59
  }
38
- export function planLimitsWanted(store, now) {
60
+ export function planLimitsWanted(store, now, alive) {
39
61
  const viewed = viewedAt.get(store);
40
62
  if (viewed !== undefined && now.getTime() - viewed >= 0 && now.getTime() - viewed < PLAN_LIMITS_VIEW_WINDOW_MS)
41
63
  return true;
42
- return agentWorkActive(store, now);
64
+ return agentWorkActive(store, now, alive);
43
65
  }
44
66
  export function directChatRunning(store, provider, now) {
45
67
  const since = new Date(now.getTime() - RUNNING_AT_MOST_MS).toISOString();
@@ -11,7 +11,7 @@ import { laptopShipProblem } from "../flexible-laptop.js";
11
11
  import { threadsStatusNote, tidyFlexibleSignIns } from "../flexible-sign-in.js";
12
12
  import { FLEXIBLE_UNAVAILABLE } from "../flexible.js";
13
13
  import { saveFlexibleBranch } from "../flexible-save.js";
14
- import { admitFlexibleThreadOwner, answerFlexibleRequest, cancelFlexibleThreadShip, closeFlexibleSessions, closeFlexibleThread, continueFlexibleThread, flexibleThreadShipTerms, latestFlexibleShip, sendBackFlexibleThread, shipFlexibleThread, tidyEndedFlexibleThreads, flexibleThreadChangeOf, flexibleThreadEdited, flexibleThreadLiveOf, flexibleThreadsOf, FLEXIBLE_WAIT_MS, flexibleThreadsExist, flexibleWorkOpen, openFlexibleSessions, recoverFlexibleHolders, startFlexibleThread, settleFlexibleStops, tickFlexibleSessions, waitFlexibleThreadChange, flexibleThreadChanges, flexibleThreadTipOf } from "../flexible-session.js";
14
+ import { admitFlexibleThreadOwner, answerFlexibleRequest, cancelFlexibleThreadShip, closeFlexibleSessions, closeFlexibleThread, continueFlexibleThread, flexibleShipNeedsFor, flexibleThreadShipTerms, latestFlexibleShip, sendBackFlexibleThread, shipFlexibleThread, tidyEndedFlexibleThreads, flexibleThreadChangeOf, flexibleThreadEdited, flexibleThreadLiveOf, flexibleThreadsOf, FLEXIBLE_WAIT_MS, flexibleThreadsExist, flexibleWorkOpen, openFlexibleSessions, recoverFlexibleHolders, startFlexibleThread, settleFlexibleStops, tickFlexibleSessions, waitFlexibleThreadChange, flexibleThreadChanges, flexibleThreadTipOf } from "../flexible-session.js";
15
15
  import { createFlexibleLauncher } from "../flexible-launcher.js";
16
16
  import { FLEXIBLE_NEXT_WORDS, flexibleReadiness, flexibleStartCard } from "../flexible-start.js";
17
17
  import { summaryLines } from "../approval-summary.js";
@@ -171,7 +171,7 @@ export function createEngineHandlers(runtime) {
171
171
  const admitted = admitFlexibleThreadOwner(store, sessions, { thread, viewer: { name: who.name }, canAccess: repo => store.accountCanAccess(who.name, repo) });
172
172
  return admitted.ok ? admitted.repo : null;
173
173
  };
174
- const acted = (response, status, outcome, words, next) => json(response, status, next === undefined ? { outcome, words } : { outcome, words, next });
174
+ const acted = (response, status, outcome, words, next, command = null) => json(response, status, { outcome, words, ...(next === undefined ? {} : { next }), ...(command === null ? {} : { command }) });
175
175
  async function liveThread(ctx) {
176
176
  const { url, who, request, response } = ctx;
177
177
  if (who.via !== "cookie")
@@ -577,7 +577,8 @@ export function createEngineHandlers(runtime) {
577
577
  if (!done.ok)
578
578
  return acted(response, 409, "refused", done.message);
579
579
  const words = act === "end"
580
- ? done.already ? "This thread had already ended." : done.stopPending ? "Ended. Stopping its agent…" : "Ended. You can still ship its work."
580
+ ? done.already ? "This thread had already ended." : done.stopPending ? "Ended. Stopping its agent…"
581
+ : flexibleShipNeedsFor(store, id) === null ? "Ended. You can still ship its work, or save it as a branch." : "Ended. You can still save its work as a branch (S on the thread)."
581
582
  : done.stopPending ? "Stopping its agent…" : "Stopped. Reply to go on.";
582
583
  return acted(response, 200, "done", words);
583
584
  };
@@ -594,7 +595,7 @@ export function createEngineHandlers(runtime) {
594
595
  const by = { name: who.name, generation: who.session.generation };
595
596
  const shown = await flexibleThreadShipTerms(store, { thread: id, by });
596
597
  if (!shown.ok)
597
- return acted(response, 409, "refused", shown.message);
598
+ return acted(response, 409, "refused", shown.message, undefined, shown.reason === "no-check" || shown.reason === "no-publishing" ? `toolroll thread save ${id.slice(0, 8)}` : null);
598
599
  const laptop = who.authority === "local-owner" && who.session.localGeneration !== null
599
600
  && laptopShipProblem(store, { owner: who.name, localGeneration: who.session.localGeneration }) === null;
600
601
  const command = `toolroll thread ship ${id} --key ${shown.summary.key}`;
@@ -677,7 +678,7 @@ export function createEngineHandlers(runtime) {
677
678
  const saved = await saveFlexibleBranch(store, { thread: id, by: { name: who.name, generation: who.session.generation }, now: new Date(), prove: held });
678
679
  if (!saved.ok)
679
680
  return acted(response, 409, "refused", saved.message);
680
- return acted(response, 200, "done", `${saved.already ? `Already saved as ${saved.branch}.` : `Saved as ${saved.branch} (commit ${saved.candidate.slice(0, 12)}).`} ${saved.next}`);
681
+ return acted(response, 200, "done", `${saved.already ? `Already saved as ${saved.branch}.` : `Saved as ${saved.branch} (commit ${saved.candidate.slice(0, 12)}).`} ${saved.next}`, undefined, saved.command);
681
682
  }
682
683
  async function leadChat(ctx) {
683
684
  const { url, who, request, response, now } = ctx;
@@ -1,5 +1,5 @@
1
1
  import { localOwnerRefusal } from "../local-owner.js";
2
- import { broughtInOnBranch, landedWords, landingOf, publishesThroughPullRequests, recognisedOnBranch } from "../local-landing.js";
2
+ import { broughtInOnBranch, landedStanding, landingOf, publishesThroughPullRequests, recognisedOnBranch } from "../local-landing.js";
3
3
  import { requestContext } from "./request-context.js";
4
4
  import { heldFindingCount } from "../findings.js";
5
5
  import { familyInWebReach } from "../findings.js";
@@ -620,8 +620,9 @@ export function createTaskViews(runtime) {
620
620
  const person = who.via === "cookie" && who.role === "approver";
621
621
  const onBranch = record === null || record.undone ? recognisedOnBranch(runtime.store, repo, rootId, complete ? assignment?.receipt?.head ?? null : null, baseGit) : null;
622
622
  if (onBranch !== null)
623
- return { taskId: rootId, landed: onBranch, canLand: false, canUndo: person && broughtInOnBranch(runtime.store, repo, rootId, baseGit) };
624
- return { taskId: rootId, landed: landedWords(runtime.store, rootId), canLand: person && complete && (record === null || record.undone), canUndo: person && record !== null && !record.undone };
623
+ return { taskId: rootId, landed: onBranch.words, canLand: false, canUndo: person && !onBranch.reverted && broughtInOnBranch(runtime.store, repo, rootId, baseGit) };
624
+ const standing = landedStanding(runtime.store, rootId, baseGit);
625
+ return { taskId: rootId, landed: standing?.words ?? null, canLand: person && complete && (record === null || record.undone), canUndo: person && record !== null && !record.undone && standing?.reverted !== true };
625
626
  }
626
627
  function failureOf(runs, assignment, readLog = true) {
627
628
  const last = latestFinishedAttempt(runs);
@@ -2812,12 +2812,13 @@ export function createTasksHandlers(runtime) {
2812
2812
  const ref = store.lookupRef(act.taskId);
2813
2813
  if (ref === null || !visible(ref.repo) || who.via !== "cookie")
2814
2814
  return refuse(response, who, 404, "no such task", "/");
2815
+ const shown = store.taskFamilyOf(act.taskId, null, true)?.current.id ?? act.taskId;
2815
2816
  if (ref.repo !== null && publishesThroughPullRequests(store, ref.repo))
2816
- return taskScreen(response, who, act.taskId, PULL_REQUESTS_INSTEAD, 409);
2817
+ return taskScreen(response, who, shown, PULL_REQUESTS_INSTEAD, 409);
2817
2818
  const local = who.authority === "local-owner";
2818
2819
  const principal = local ? null : leadPrincipal(who);
2819
2820
  if (!local && principal === null)
2820
- return taskScreen(response, who, act.taskId, "Your access changed. Sign in again.", 403);
2821
+ return taskScreen(response, who, shown, "Your access changed. Sign in again.", 403);
2821
2822
  const access = { repos: principal !== null ? principal.repos : store.knownRepos().filter(repo => store.accountCanAccess(who.name, repo)) };
2822
2823
  const undo = body.get("undo") === "1";
2823
2824
  const into = (body.get("into") ?? "").trim();
@@ -2826,28 +2827,28 @@ export function createTasksHandlers(runtime) {
2826
2827
  if (key === "") {
2827
2828
  const read = await readLanding(store, act.taskId, access, now, options);
2828
2829
  if (!read.ok)
2829
- return taskScreen(response, who, act.taskId, read.message, 409);
2830
+ return taskScreen(response, who, shown, read.message, 409);
2830
2831
  if (!("plan" in read)) {
2831
2832
  if (answersInPlace(ctx.request))
2832
2833
  return answerActInPlace(response, "done", `Already on ${read.landed.ref.replace(/^refs\/heads\//, "")} (${read.landed.commit.slice(0, 7)}).`, 200);
2833
- return redirect(response, taskHref(act.taskId));
2834
+ return redirect(response, taskHref(shown));
2834
2835
  }
2835
2836
  const plan = read.plan;
2836
2837
  if (answersInPlace(ctx.request))
2837
2838
  return respond(response, 200, "application/json; charset=utf-8", JSON.stringify({ outcome: "land-terms", key: plan.key, lines: landingWords(plan) }));
2838
2839
  const title = undo ? "Undo landing" : `Land on ${plan.branch}`;
2839
- return sendScreen(response, 200, screen(title, html `<h1>${title}</h1>${landingWords(plan).map(line => html `<p>${line}</p>`)}${postForm(`${taskHref(act.taskId)}/land`, html `${btn(undo ? "Undo it" : "Land it", { variant: "primary", type: "submit" })} ${btn("Cancel", { variant: "ghost", href: taskHref(act.taskId) })}`, { hidden: { key: plan.key, ...(into === "" ? {} : { into }), ...(undo ? { undo: "1" } : {}) } })}`, { chrome: chromeFor(ref.repo, "tasks") }));
2840
+ return sendScreen(response, 200, screen(title, html `<h1>${title}</h1>${landingWords(plan).map(line => html `<p>${line}</p>`)}${postForm(`${taskHref(act.taskId)}/land`, html `${btn(undo ? "Undo it" : "Land it", { variant: "primary", type: "submit" })} ${btn("Cancel", { variant: "ghost", href: taskHref(shown) })}`, { hidden: { key: plan.key, ...(into === "" ? {} : { into }), ...(undo ? { undo: "1" } : {}) } })}`, { chrome: chromeFor(ref.repo, "tasks") }));
2840
2841
  }
2841
2842
  const done = await land(store, act.taskId, { key, ...(into === "" ? {} : { into }), ...(undo ? { undo: true } : {}) }, principal !== null ? { kind: "person", who: principal } : { kind: "local" }, access, now, { root: evidenceRoot });
2842
2843
  if (!done.ok)
2843
- return taskScreen(response, who, act.taskId, done.message, done.reason === "authority" ? 403 : 409);
2844
+ return taskScreen(response, who, shown, done.message, done.reason === "authority" ? 403 : 409);
2844
2845
  if (done.handoff !== null) {
2845
2846
  const words = `Landing commit ${done.commit.slice(0, 7)} is ready. Your project folder has ${done.branch} checked out, so Toolroll didn't touch it. ${handoffWords(done.handoff, done.commit)}`;
2846
- return answersInPlace(ctx.request) ? answerActInPlace(response, "done", words, 200) : taskScreen(response, who, act.taskId, words, 200);
2847
+ return answersInPlace(ctx.request) ? answerActInPlace(response, "done", words, 200, done.handoff.command) : taskScreen(response, who, shown, words, 200);
2847
2848
  }
2848
2849
  if (answersInPlace(ctx.request))
2849
2850
  return answerActInPlace(response, "done", `${done.kind === "undo" ? "Undone" : "Landed"} on ${done.branch} (${done.commit.slice(0, 7)}).`, 200);
2850
- return redirect(response, taskHref(act.taskId));
2851
+ return redirect(response, taskHref(shown));
2851
2852
  }
2852
2853
  return { registrations, workListFor, showOrder, runListPane, peekFragment, taskMutation, queueRegionFor, ciFailingFor, completedRowFor, attemptRowFor, resultRowOf, reviewCockpitViewOf, decisionEvidence, runEvidence, sendArtifact, peekGuards, liveRunIds };
2853
2854
  }
@@ -3027,8 +3028,8 @@ export function localOwnerRetry(store, taskId, run, digest, now) {
3027
3028
  const done = retryAsLocalOwner(store, taskId, { run: Number(run), digest }, now);
3028
3029
  return done.ok ? { ok: true, replayed: done.replayed } : { ok: false, status: done.reason === "local-owner" || done.reason === "refused" || done.reason === "limit" ? 403 : 409, message: done.message };
3029
3030
  }
3030
- export function answerActInPlace(response, outcome, words, status) {
3031
- respond(response, status, "application/json; charset=utf-8", JSON.stringify({ outcome, words }));
3031
+ export function answerActInPlace(response, outcome, words, status, command = null) {
3032
+ respond(response, status, "application/json; charset=utf-8", JSON.stringify(command === null ? { outcome, words } : { outcome, words, command }));
3032
3033
  }
3033
3034
  function typedSteer(store, who, file, now, words, question = null) {
3034
3035
  return store.transact(() => {
package/dist/surface.js CHANGED
@@ -309,7 +309,7 @@ const GUIDE_ROWS = [
309
309
  { name: "digest", takesValue: true, meaning: "the exact receipt from assignment show; accepts and finishes exactly that result" },
310
310
  { name: "despite", takesValue: true, meaning: "accept with this reason, without finishing; never combines with --finish or --digest (--note is its alias)" }],
311
311
  notableReasons: ["usage", "unknown-task", "no-run", "not-ready"] },
312
- { ...operator("task land", "put accepted work on the project's own branch when it has no pull requests: bare shows exactly what lands where; --yes --key <key> lands it as one new commit on top; --undo reverts that commit with a new one"),
312
+ { ...operator("task land", "put accepted work on the project's own branch when it has no pull requests: bare shows exactly what lands where; --yes --key <preview-key> lands it as one new commit on top; --undo reverts that commit with a new one"),
313
313
  positionals: [{ name: "id", required: true, meaning: "the task" }],
314
314
  flags: [jsonFlag, dbFlag, { name: "into", takesValue: true, meaning: "land on this branch instead of the recorded one (the yes records it)" },
315
315
  { name: "undo", takesValue: false, meaning: "revert the landing with a new commit on the branch" },
@@ -154,7 +154,8 @@ function sentenceOf(headline, facts) {
154
154
  return `Accepted automatically: ${facts.landed}.`;
155
155
  const by = facts.completedBy ? `Accepted by ${facts.completedBy}.` : "Accepted.";
156
156
  const pr = facts.pullRequest;
157
- return pr?.state === "merged" ? `${by} ${pr.number === null ? "Its pull request" : `Pull request #${pr.number}`} merged.` : by;
157
+ const again = facts.checks?.status === "failed" ? " Its checks failed when they ran again." : "";
158
+ return pr?.state === "merged" ? `${by} ${pr.number === null ? "Its pull request" : `Pull request #${pr.number}`} merged.${again}` : `${by}${again}`;
158
159
  }
159
160
  case "Failed":
160
161
  if (facts.checks?.status === "failed")
Binary file
Binary file
Binary file
Binary file
@@ -14,7 +14,7 @@ import { buildReviewOf } from './review-switch.js';
14
14
  import { shownVerdictOf } from './proof.js';
15
15
  import { isCheckLevel, repoClause, requiredCheckCommandFor, RUN_LEVEL_ACTION, TASK_LEVEL_ACTION } from './check-levels.js';
16
16
  import { MARKER } from './worktree.js';
17
- import { CHECKS_FINISHED, CHECKS_REQUESTED, CHECKS_STARTED, withFollowUps } from './result-follow-ups.js';
17
+ import { CHECKS_FINISHED, CHECKS_REQUESTED, CHECKS_STARTED, FOLLOW_UP_LOG, FOLLOW_UP_RECEIPT, withFollowUps } from './result-follow-ups.js';
18
18
  import { LANDED_ACTOR, landedReasonOf } from './result-completion.js';
19
19
  import { ASKS, CODE_READING, STORAGE_HOLD_PREFIX, NEED_ASK, NEEDS, askChipOf, failedAttemptSentence, isWaitCode, processNeedOf, resultHoldUpSentence } from './needs-you.js';
20
20
  import { agentlessCommand, NO_AGENT_TITLE, noAgentWords, retryWhenWords, signInAgainWords } from './dispatch.js';
@@ -212,7 +212,10 @@ const PROJECTION = `WITH RECURSIVE admitted AS MATERIALIZED (
212
212
  AND a.action IN ('task state changed','scope approved','task placed','run started','run finished')) END completion_changed,
213
213
  CASE WHEN f.ready AND EXISTS(SELECT 1 FROM action_ledger a
214
214
  WHERE a.task_id=f.root_id AND a.run_id=f.result_id AND a.action='assignment handoff checked' AND a.source='work')
215
- THEN (SELECT MAX(ar.created_at) FROM json_each(f.fam_refs) m JOIN run r ON r.task_ref=m.value JOIN artifact ar ON ar.run=r.id) END completion_artifact_at
215
+ THEN (SELECT MAX(ar.created_at) FROM json_each(f.fam_refs) m JOIN run r ON r.task_ref=m.value JOIN artifact ar ON ar.run=r.id
216
+ -- A follow-up check's own log and receipt (Run checks after accepting) are a separate check fact, never changed
217
+ -- work: assignment.ts reads the completion with the checks as they read then, so the list does too.
218
+ WHERE NOT (ar.kind='structured-output' AND ar.capture IN ('${FOLLOW_UP_LOG}','${FOLLOW_UP_RECEIPT}'))) END completion_artifact_at
216
219
  FROM ready f) f
217
220
  ), classified AS MATERIALIZED (
218
221
  SELECT f.*,CASE
@@ -1,9 +1,15 @@
1
1
  import { heldFindingCount } from "./findings.js";
2
2
  import { machineChecked } from "./machine-check.js";
3
- import { resultCheckLevel } from "./result-follow-ups.js";
3
+ import { FOLLOW_UP_LOG, FOLLOW_UP_RECEIPT, resultCheckLevel } from "./result-follow-ups.js";
4
+ import { COMPLETER_ACTOR, COMPLETION_ACTION } from "./result-completion.js";
5
+ import { approvalOf } from "./scope.js";
6
+ import { existsSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { MARKER } from "./worktree.js";
4
9
  import { projectCheckSet } from "./check-levels.js";
5
10
  import { diagnoseTaskDispatch } from "./dispatch.js";
6
11
  import { isAlive } from "./runner.js";
12
+ import { refArchived, stopFactOf } from "./store.js";
7
13
  import { taskControlOf } from "./task-control.js";
8
14
  import { buildReviewOf } from "./review-switch.js";
9
15
  import { reviewFactsOf, workStatusOf } from "./workspace-ui.js";
@@ -82,6 +88,7 @@ export function taskWorkSummaryOf(store, taskId, now, access) {
82
88
  const publication = result === null ? null : store.publicationForRun(result.id);
83
89
  const facts = {
84
90
  id: task.id, title: task.title, repo: ref.repo, state: task.state, updatedAt: task.updatedAt,
91
+ ...(task.state === "done" && result !== null && completionStands(store, task.id, now, result.id) ? { completed: true } : {}),
85
92
  ...(machineChecked(store, task.id) ? { machine: true } : {}),
86
93
  dispatch: diagnoseTaskDispatch(store, taskId, now, access.dependencyRepos ?? null), liveRunId: live?.id ?? null,
87
94
  unfinishedRunId: runs.find(one => one.outcome === null && one.role !== "reviewer")?.id ?? null,
@@ -107,3 +114,72 @@ export function taskWorkSummaryOf(store, taskId, now, access) {
107
114
  };
108
115
  return workSummaryOf(facts, access.principal);
109
116
  }
117
+ export function completionStands(store, taskId, now, resultRunId) {
118
+ try {
119
+ if (resultRunId !== undefined && store.handle.prepare("SELECT 1 AS hit FROM action_ledger WHERE run_id = ? AND action = ? AND source = 'work' LIMIT 1")
120
+ .get(resultRunId, COMPLETION_ACTION) === undefined)
121
+ return false;
122
+ const family = store.taskFamilyOf(taskId, null, true);
123
+ if (family === null || family.problem !== null || family.current.id !== taskId || family.current.state !== "done")
124
+ return false;
125
+ const current = family.current;
126
+ const runs = store.runsFor(current.refId);
127
+ const result = runs.find(run => run.finishedAt !== null && (run.role === "builder" || run.role === "scout"));
128
+ if (result === undefined || result.finishedAt === null)
129
+ return false;
130
+ const valid = result.role === "scout" ? result.outcome === "built"
131
+ : (result.outcome === "built" || result.outcome === "no-change") && /^[0-9a-f]{40}$/.test(result.headRevision ?? "");
132
+ if (!valid)
133
+ return false;
134
+ const scope = store.getScope(current.id);
135
+ if (scope === null || scope.termsProblem != null || !approvalOf(scope).approved || scope.digest !== result.scopeDigest)
136
+ return false;
137
+ const busy = (refId) => store.currentLiveLease(refId, now) !== null || store.runsFor(refId).some(run => run.outcome === null && run.role !== "reviewer");
138
+ if (family.versions.some(version => version.id !== current.id && ((version.state === "queued" && !refArchived(store, version.refId)) || version.state === "running" || busy(version.refId))))
139
+ return false;
140
+ if (busy(current.refId) || store.activeHolds(current.refId, now).length > 0 || store.applicableStopFor(result.id) !== null)
141
+ return false;
142
+ const counted = family.versions.filter(version => version.id === current.id || !refArchived(store, version.refId));
143
+ if (counted.some(version => openQuestionOn(store, version.refId) || custodyUnresolved(store, version.refId, version.state)))
144
+ return false;
145
+ const ids = JSON.stringify(family.versions.map(version => version.id));
146
+ const one = (sql, ...values) => store.handle.prepare(sql).get(...values);
147
+ const updated = String(one("SELECT MAX(updated_at) AS v FROM task WHERE id IN (SELECT value FROM json_each(?))", ids)?.["v"] ?? "");
148
+ const changed = Number(one(`SELECT MAX(id) AS v FROM action_ledger WHERE task_id IN (SELECT value FROM json_each(?))
149
+ AND action IN ('task state changed','scope approved','task placed','run started','run finished')`, ids)?.["v"] ?? 0);
150
+ const saved = String(one(`SELECT MAX(ar.created_at) AS v FROM artifact ar JOIN run r ON r.id = ar.run JOIN task_ref tr ON tr.id = r.task_ref
151
+ WHERE tr.backend = 'built-in' AND tr.external_id IN (SELECT value FROM json_each(?))
152
+ AND NOT (ar.kind = 'structured-output' AND ar.capture IN (?, ?))`, ids, FOLLOW_UP_LOG, FOLLOW_UP_RECEIPT)?.["v"] ?? "");
153
+ const after = [updated, result.finishedAt, scope.approvedAt ?? "", scope.proposedAt ?? ""];
154
+ const rows = store.handle.prepare(`SELECT id, at, actor FROM action_ledger WHERE task_id = ? AND run_id = ? AND action = ? AND source = 'work'
155
+ AND repo IS ? AND length(outcome) = 64 AND outcome NOT GLOB '*[^a-f0-9]*' ORDER BY id DESC`).all(family.root.id, result.id, COMPLETION_ACTION, current.repo);
156
+ return rows.some(row => {
157
+ const at = String(row["at"]);
158
+ if (!COMPLETER_ACTOR.test(String(row["actor"])) || Number(row["id"]) < changed || at < saved || after.some(one => at < one))
159
+ return false;
160
+ return one("SELECT 1 AS hit FROM proof_verdict WHERE run = ? AND decided_at > ?", result.id, at) === undefined
161
+ && one("SELECT 1 AS hit FROM proof_acceptance WHERE run = ? AND accepted_at > ?", result.id, at) === undefined;
162
+ });
163
+ }
164
+ catch {
165
+ return false;
166
+ }
167
+ }
168
+ function openQuestionOn(store, refId) {
169
+ return store.handle.prepare(`SELECT 1 AS hit FROM decision d JOIN run r ON r.id = d.run
170
+ WHERE r.task_ref = ? AND d.state <> 'answered' AND d.answered_at IS NULL LIMIT 1`).get(refId) !== undefined;
171
+ }
172
+ function custodyUnresolved(store, refId, state) {
173
+ const recorded = store.handle.prepare(`SELECT 1 AS hit FROM run r WHERE r.task_ref = ? AND r.provider_started_at IS NOT NULL
174
+ AND NOT EXISTS(SELECT 1 FROM run_process p WHERE p.run = r.id) AND NOT EXISTS(SELECT 1 FROM run_process_summary s WHERE s.run = r.id)
175
+ UNION SELECT 1 FROM run_process p JOIN run r ON r.id = p.run WHERE r.task_ref = ? AND p.exited_at IS NULL AND p.container_empty_at IS NULL
176
+ LIMIT 1`).get(refId, refId) !== undefined;
177
+ const noted = state === "done" && (() => {
178
+ const last = store.handle.prepare(`SELECT worktree FROM run WHERE task_ref = ? AND role IN ('builder','scout') AND finished_at IS NOT NULL
179
+ ORDER BY id DESC LIMIT 1`).get(refId)?.["worktree"];
180
+ return typeof last === "string" && existsSync(join(last, MARKER));
181
+ })();
182
+ if (!recorded && !noted)
183
+ return false;
184
+ return store.runsFor(refId).some(run => { const fact = stopFactOf(store, run.id); return fact !== null && fact.kind !== "open"; });
185
+ }
@@ -361,16 +361,22 @@ export function resultHeadlineOf(status) {
361
361
  : VERIFIED_RESULT.has(status.token) ? { status: "passed", exitCode: null, head: null } : null });
362
362
  return { ...status, label: shared.headline, tone: workToneOf(shared.headline) };
363
363
  }
364
+ const COMPLETION_YIELDS = new Set(["waiting-decision", "finding-held", "stopping", "stopped"]);
364
365
  export function workStatusOf(facts, resultDisplay) {
365
366
  const status = workStatusWordsOf(facts, resultDisplay);
366
367
  const done = facts.state === "done" && status.token !== "waiting-decision";
367
- const read = done ? RESULT_NEEDS_YOU.has(status.token) ? { stage: "needs-you", need: "other" } : stageOfCode(status.token, { needsPerson: false })
368
+ const read = done ? RESULT_NEEDS_YOU.has(status.token) ? { stage: "needs-you", need: "other" }
369
+ : status.token === "finding-held" ? { stage: "needs-you", need: "finding" } : stageOfCode(status.token, { needsPerson: false })
368
370
  : stageOfCode(status.token, { needsPerson: status.views.includes("needs-you"), planning: facts.dispatch?.code === "running" && facts.dispatch.role === "planner", operatorHold: facts.dispatch?.action === "unhold" });
369
- const stage = done && read.stage !== "needs-you" && read.stage !== "failed" ? "finished" : read.stage;
371
+ const complete = done && facts.completed === true && !COMPLETION_YIELDS.has(status.token) && (facts.control?.kind ?? "none") === "none"
372
+ && (facts.openDecision ?? null) === null && (facts.heldFindings ?? 0) === 0;
373
+ const stage = complete ? "complete" : done && read.stage !== "needs-you" && read.stage !== "failed" ? "finished" : read.stage;
370
374
  const level = facts.result?.checkLevel ?? null;
371
375
  const shared = taskStatusOf({ stage, ...(read.need === undefined ? {} : { need: read.need }), ...(read.wait === undefined ? {} : { wait: read.wait }), reason: plainReasonOf(stage, status.token, status.detail),
372
- report: facts.result?.role === "scout", ...(facts.machine === true ? { machine: true } : {}), checks: stage !== "finished" ? null : VERIFIED_RESULT.has(status.token) ? { status: "passed", exitCode: null, head: null, level }
376
+ report: facts.result?.role === "scout", ...(facts.machine === true ? { machine: true } : {}), checks: stage !== "finished" && stage !== "complete" ? null : VERIFIED_RESULT.has(status.token) ? { status: "passed", exitCode: null, head: null, level }
373
377
  : level === "off" ? { status: "not-run", exitCode: null, head: null, level } : null });
378
+ if (complete)
379
+ return { ...status, label: shared.headline, tone: workToneOf(shared.headline), detail: shared.sentence, action: null, views: status.views.filter(view => view !== "needs-you"), rank: 3 };
374
380
  return { ...status, label: shared.headline, tone: workToneOf(shared.headline), detail: stage === "finished" && level !== "off" ? status.detail : shared.sentence };
375
381
  }
376
382
  function workStatusWordsOf(facts, resultDisplay) {
@@ -409,12 +415,12 @@ function workStatusWordsOf(facts, resultDisplay) {
409
415
  return { token: "stopped", label: "Paused", detail: "The stopped attempt's work is preserved. Resuming requires confirmation and checks the current approval again.", tone: "attention", action: { label: "Review pause", kind: "open-task" }, views, rank: 0 };
410
416
  }
411
417
  if (facts.state === "done" && result !== null) {
412
- if (question !== null && result.tone !== "problem") {
418
+ if (question !== null && (result.tone !== "problem" || facts.completed === true)) {
413
419
  return { token: "waiting-decision", label: "Waiting on your answer", detail: question.question,
414
420
  tone: "attention", action: { label: "Answer question", kind: "open-task" }, views, rank: 0,
415
421
  diagnostics: [{ token: result.token, label: result.label, detail: result.detail, tone: result.tone }] };
416
422
  }
417
- if (held && result.tone !== "problem")
423
+ if (held && (result.tone !== "problem" || facts.completed === true))
418
424
  return findingWords({ token: result.token, label: result.label, detail: result.detail, tone: result.tone });
419
425
  return { ...result, views, rank: needs ? 0 : 3 };
420
426
  }
@@ -568,7 +574,7 @@ export function stepRowsOf(view) {
568
574
  if (step.state === "skipped")
569
575
  return { sentence: said === "Checks not run" ? "The checks didn't run" : said === "Checks at release" ? "Checks deferred to release" : "No checks were recorded", at: null };
570
576
  if (step.state === "stuck")
571
- return { sentence: step.needsYou && said === null ? "" : said === "Checks unreadable" ? "The checks couldn't be read" : said === "Checks failed" ? "The checks failed" : stoppedWord, at: null };
577
+ return { sentence: step.needsYou && said === null ? "" : said === "Checks unreadable" ? "The checks couldn't be read" : said === "Checks failed" ? headline === "Complete" ? "The checks failed when they ran again" : "The checks failed" : stoppedWord, at: null };
572
578
  if (step.state === "current")
573
579
  return { sentence: said === "Checks running" ? "The checks are running" : step.needsYou ? "" : "Waiting for the checks", at: null };
574
580
  return { sentence: "The project's checks run on the result", at: null };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toolroll",
3
- "version": "0.9.122",
3
+ "version": "0.9.123",
4
4
  "description": "Your agents build. You decide. A control plane for coding agents — Claude Code, Codex, Gemini: approve the exact scope once, get results back Ready with the diff, the passing check and screenshots. Runs on your machine.",
5
5
  "directories": {
6
6
  "doc": "docs"