toolroll 0.9.126 → 0.9.127

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.
@@ -0,0 +1,138 @@
1
+ import { LAND_DESTINATION, LAND_HANDOFF, LAND_HANDOFF_SETTLED, LAND_INTENT, LAND_SETTLED, landableBranch, revertedOnBranch } from "./local-landing.js";
2
+ import { recentGitReads } from "./task-base.js";
3
+ const listReads = recentGitReads();
4
+ export const LANDED_GIT_READS = 24;
5
+ class GitBudgetSpent extends Error {
6
+ }
7
+ const OID = /^[0-9a-f]{40}$/;
8
+ const short = (oid) => oid.slice(0, 7);
9
+ function intentOf(id, d) {
10
+ if (d["v"] !== 1 || typeof d["ref"] !== "string" || typeof d["old"] !== "string" || typeof d["commit"] !== "string" || !OID.test(d["old"]) || !OID.test(d["commit"])
11
+ || (d["mode"] !== "files" && d["mode"] !== "ref") || typeof d["key"] !== "string" || (d["kind"] !== "land" && d["kind"] !== "undo"))
12
+ return null;
13
+ return { id, kind: d["kind"], ref: d["ref"], old: d["old"], commit: d["commit"], candidate: typeof d["candidate"] === "string" && OID.test(d["candidate"]) ? d["candidate"] : d["commit"],
14
+ reverts: typeof d["reverts"] === "number" || typeof d["reverts"] === "string" ? d["reverts"] : null, fromHandoff: typeof d["fromHandoff"] === "number" ? d["fromHandoff"] : null };
15
+ }
16
+ function handoffOf(id, d) {
17
+ const ok = d["v"] === 1 && typeof d["key"] === "string" && typeof d["ref"] === "string" && typeof d["old"] === "string" && OID.test(d["old"]) && typeof d["commit"] === "string" && OID.test(d["commit"])
18
+ && typeof d["keep"] === "string" && typeof d["folder"] === "string" && typeof d["candidate"] === "string" && OID.test(d["candidate"]);
19
+ return ok ? { id, ref: d["ref"], old: d["old"], commit: d["commit"], candidate: d["candidate"] } : null;
20
+ }
21
+ const parsed = (text) => {
22
+ try {
23
+ const value = JSON.parse(String(text ?? "null"));
24
+ return value !== null && typeof value === "object" ? value : null;
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ };
30
+ export function landedRowsOf(store, rows, read = listReads) {
31
+ const out = new Map();
32
+ const done = rows.filter(one => one.assignmentState === "complete" && one.repo !== null && one.resultRunId !== null);
33
+ if (done.length === 0)
34
+ return out;
35
+ const ids = [...new Set(done.map(one => one.rootId))], repos = [...new Set(done.map(one => one.repo))], runs = [...new Set(done.map(one => one.resultRunId))];
36
+ const marks = (n) => Array.from({ length: n }, () => "?").join(",");
37
+ const found = store.handle.prepare(`
38
+ WITH heads AS (SELECT id, head_revision FROM run WHERE id IN (${marks(runs.length)})),
39
+ handed AS (SELECT id, task_id, repo, action, outcome, detail FROM action_ledger WHERE task_id IN (${marks(ids.length)}) AND action = ?
40
+ AND (CASE WHEN json_valid(detail) THEN json_extract(detail, '$.candidate') END) IN (SELECT head_revision FROM heads))
41
+ SELECT 'ledger' AS kind, id, task_id, repo, action, outcome, detail FROM action_ledger WHERE task_id IN (${marks(ids.length)}) AND action IN (?, ?)
42
+ UNION ALL SELECT 'ledger', id, task_id, repo, action, outcome, detail FROM handed
43
+ UNION ALL SELECT 'ledger', id, task_id, repo, action, outcome, NULL FROM action_ledger WHERE task_id IN (${marks(ids.length)}) AND action = ? AND outcome IN (SELECT id || ':kept' FROM handed)
44
+ UNION ALL SELECT 'destination', id, NULL, repo, action, NULL, detail FROM action_ledger
45
+ WHERE id IN (SELECT max(id) FROM action_ledger WHERE repo IN (${marks(repos.length)}) AND action = ? AND source = 'request' GROUP BY repo)
46
+ UNION ALL SELECT 'grant', NULL, NULL, repo, NULL, NULL, NULL FROM publication_grant WHERE repo IN (${marks(repos.length)}) AND revoked_at IS NULL
47
+ UNION ALL SELECT 'run', id, NULL, NULL, NULL, head_revision, NULL FROM heads`)
48
+ .all(...runs, ...ids, LAND_HANDOFF, ...ids, LAND_INTENT, LAND_SETTLED, ...ids, LAND_HANDOFF_SETTLED, ...repos, LAND_DESTINATION, ...repos);
49
+ const heads = new Map(), granted = new Set(), destinations = new Map();
50
+ const intents = new Map(), handoffs = new Map();
51
+ const settled = new Map(), kept = new Set();
52
+ for (const row of found) {
53
+ const kind = String(row["kind"]), id = Number(row["id"]);
54
+ if (kind === "run") {
55
+ heads.set(id, row["outcome"] == null ? null : String(row["outcome"]));
56
+ continue;
57
+ }
58
+ if (kind === "grant") {
59
+ granted.add(String(row["repo"]));
60
+ continue;
61
+ }
62
+ if (kind === "destination") {
63
+ const ref = parsed(row["detail"])?.["ref"], repo = String(row["repo"]);
64
+ if ((destinations.get(repo)?.id ?? -1) < id)
65
+ destinations.set(repo, { id, ref: typeof ref === "string" && typeof parsed(row["detail"])?.["common"] === "string" ? ref : "" });
66
+ continue;
67
+ }
68
+ const action = String(row["action"]), outcome = String(row["outcome"] ?? ""), task = String(row["task_id"]);
69
+ if (action === LAND_SETTLED) {
70
+ const intent = Number(outcome.slice(0, outcome.indexOf(":")));
71
+ if (outcome.includes(":") && (settled.get(intent)?.id ?? -1) < id)
72
+ settled.set(intent, { id, outcome: outcome.slice(outcome.indexOf(":") + 1) });
73
+ }
74
+ else if (action === LAND_HANDOFF_SETTLED) {
75
+ if (/^\d+:kept$/.test(outcome))
76
+ kept.add(Number(outcome.slice(0, outcome.indexOf(":"))));
77
+ }
78
+ else if (action === LAND_INTENT) {
79
+ const one = intentOf(id, parsed(row["detail"]) ?? {});
80
+ if (one !== null)
81
+ intents.set(task, [...(intents.get(task) ?? []), one]);
82
+ }
83
+ else if (action === LAND_HANDOFF) {
84
+ const one = handoffOf(id, parsed(row["detail"]) ?? {});
85
+ if (one !== null)
86
+ handoffs.set(task, [...(handoffs.get(task) ?? []), { repo: String(row["repo"]), one }]);
87
+ }
88
+ }
89
+ const landedOutcome = (intent) => settled.get(intent)?.outcome.startsWith("landed") === true;
90
+ let left = LANDED_GIT_READS;
91
+ const budgeted = (cwd, args) => {
92
+ if (left <= 0)
93
+ throw new GitBudgetSpent();
94
+ left -= 1;
95
+ return read(cwd, args);
96
+ };
97
+ for (const row of done) {
98
+ try {
99
+ const words = landedWordsOf(row);
100
+ if (words !== null)
101
+ out.set(row.rootId, words);
102
+ }
103
+ catch (error) {
104
+ if (error instanceof GitBudgetSpent)
105
+ break;
106
+ throw error;
107
+ }
108
+ }
109
+ return out;
110
+ function landedWordsOf(row) {
111
+ const repo = row.repo, head = heads.get(row.resultRunId) ?? null;
112
+ if (granted.has(repo) || (!intents.has(row.rootId) && !handoffs.has(row.rootId)))
113
+ return null;
114
+ const all = [...(intents.get(row.rootId) ?? [])].sort((a, b) => b.id - a.id);
115
+ const record = all.find(one => one.kind === "land" && landedOutcome(one.id)) ?? null;
116
+ const name = record === null ? null : record.fromHandoff !== null ? `handoff:${record.fromHandoff}` : `intent:${record.id}`;
117
+ const undone = record !== null && all.some(one => one.kind === "undo" && (one.reverts === name || one.reverts === record.id) && landedOutcome(one.id));
118
+ if (record === null || undone) {
119
+ if (head === null || !OID.test(head))
120
+ return null;
121
+ const destination = destinations.get(repo)?.ref ?? null;
122
+ const ref = destination !== null && destination !== "" ? destination : (() => { const named = budgeted(repo, ["symbolic-ref", "-q", "HEAD"]); return named !== null && named.startsWith("refs/heads/") ? named : null; })();
123
+ if (ref === null || !landableBranch(ref.slice("refs/heads/".length)))
124
+ return null;
125
+ const handed = (handoffs.get(row.rootId) ?? []).filter(one => one.repo === repo && kept.has(one.one.id) && one.one.candidate === head && one.one.ref === ref)
126
+ .sort((a, b) => b.one.id - a.one.id).map(one => ({ commit: one.one.commit, old: one.one.old }));
127
+ const on = [{ commit: head, old: null }, ...handed].find(one => budgeted(repo, ["merge-base", "--is-ancestor", one.commit, ref]) !== null);
128
+ if (on === undefined)
129
+ return null;
130
+ const reverted = on.old !== null && revertedOnBranch(repo, ref, { old: on.old, commit: on.commit }, budgeted);
131
+ return `Landed on ${ref.slice("refs/heads/".length)} (${short(on.commit)})${reverted ? " · a later commit reverted it" : ""}`;
132
+ }
133
+ if (head === null || record.candidate !== head)
134
+ return null;
135
+ const reverted = revertedOnBranch(repo, record.ref, record, budgeted);
136
+ return `Landed on ${record.ref.replace(/^refs\/heads\//, "")} (${short(record.commit)})${reverted ? " · a later commit reverted it" : ""}`;
137
+ }
138
+ }
@@ -11,6 +11,7 @@ import { reproveApprover, verifyApproverStanding } from "./principal.js";
11
11
  import { localActNow, LOCAL_OWNER_LAPSED } from "./local-owner.js";
12
12
  import { publishingOf } from "./pull-request-flow.js";
13
13
  import { readGit, wholeChangeBaseOf } from "./task-base.js";
14
+ import { catchUpConflictOf } from "./revision-catch-up.js";
14
15
  export const LAND_DESTINATION = "land destination";
15
16
  export const LAND_INTENT = "land intent";
16
17
  export const LAND_SETTLED = "land settled";
@@ -188,6 +189,17 @@ export function publishesThroughPullRequests(store, repo) {
188
189
  }
189
190
  export const PULL_REQUESTS_INSTEAD = "This project publishes through pull requests; open one from the task instead.";
190
191
  const ALREADY_MSG = (ref, commit) => `Already on ${ref.replace(/^refs\/heads\//, "")} (${short(commit)}).`;
192
+ const MOVED_MSG = (branch, old) => `${branch} moved on since this work started (it's at ${short(old)} now). `
193
+ + `Send it back: Toolroll builds it again on the current ${branch} with this work merged in, and its checks run on both together.`;
194
+ const CONFLICT_MSG = (branch, old, files, candidate) => {
195
+ const named = files.slice(0, 3).map(one => shownName(one)).join(", ");
196
+ return `${branch} moved on since this work started (it's at ${short(old)} now), and its newer changes conflict with this work${named === "" ? "" : ` in ${named}${files.length > 3 ? ", …" : ""}`}. `
197
+ + `Toolroll can't merge them by itself. To land it, merge ${short(candidate)} into ${branch} yourself and resolve the conflicts, or file a new task on the current ${branch}.`;
198
+ };
199
+ export function landingBranchOf(store, repo, fallback) {
200
+ const recorded = recordedDestination(store, repo);
201
+ return recorded !== null && recorded.common === commonDirOf(repo) ? recorded.ref.slice("refs/heads/".length) : fallback;
202
+ }
191
203
  export async function readLanding(store, taskId, access, now, options) {
192
204
  const assignment = assignmentOf(store, taskId, now, { principal: "operator", repos: access.repos, includeUnplaced: false }, options.root);
193
205
  if (assignment === null)
@@ -236,6 +248,13 @@ export async function readLanding(store, taskId, access, now, options) {
236
248
  if (seen !== null && seen.reverted)
237
249
  return refuse("nothing", `${seen.words}.`);
238
250
  }
251
+ if (!read.ok && read.reason === "moved") {
252
+ const now = await git(["rev-parse", "--verify", "-q", `${destination.ref}^{commit}`]);
253
+ const old = now.stdout.trim();
254
+ const files = now.code === 0 && OID.test(old) ? catchUpConflictOf(store, receipt.taskId, old) : null;
255
+ if (files !== null)
256
+ return refuse("moved", CONFLICT_MSG(destination.ref.slice("refs/heads/".length), old, files, candidate));
257
+ }
239
258
  return read;
240
259
  }
241
260
  export function landedLine(landed) {
@@ -299,8 +318,7 @@ async function planFor(git, project, destination, fixed, squashing = null) {
299
318
  }
300
319
  const ancestor = await git(["merge-base", "--is-ancestor", old, fixed.candidate]);
301
320
  if (ancestor.code === 1) {
302
- return refuse("moved", `${branch} moved on since this work started (it's at ${short(old)} now): bring this task up to date first. `
303
- + `Send it back to build on the current ${branch}; landing it as it is would drop or mix in changes nobody checked together.`);
321
+ return refuse("moved", MOVED_MSG(branch, old));
304
322
  }
305
323
  if (ancestor.code !== 0)
306
324
  return refuse("git", "Toolroll couldn't compare the commits.");
@@ -4,10 +4,11 @@ import { releaseCiHoldOf, releaseCiRunningOf } from "./release-ci-hold.js";
4
4
  import { isRevisionFeedback } from "./result-review.js";
5
5
  import { approvalOf, deployGateScope } from "./scope.js";
6
6
  import { shipChecksForTask } from "./store.js";
7
- import { approvedCheckStateOf, requirementWordOf } from "./task-status.js";
7
+ import { approvedCheckStateOf, completedByOf, requirementWordOf } from "./task-status.js";
8
8
  import { projectCheckSet } from "./check-levels.js";
9
9
  import { projectName } from "./project.js";
10
- import { landingHistoryOf, publishesThroughPullRequests } from "./local-landing.js";
10
+ import { landingBranchOf, landingHistoryOf, publishesThroughPullRequests, shownName } from "./local-landing.js";
11
+ import { catchUpConflictOf } from "./revision-catch-up.js";
11
12
  import { recentGitReads } from "./task-base.js";
12
13
  const landingReads = recentGitReads();
13
14
  export function landedNowOf(store, assignment, read = landingReads) {
@@ -52,6 +53,8 @@ export function checklistFromAssignment(store, taskId, assignment, landed = null
52
53
  const head = receipt?.head ?? null;
53
54
  const rows = [];
54
55
  const row = (key, mark, say, act = null) => rows.push({ key, label: CHECKLIST_LABELS[key], mark, say, act });
56
+ const accepted = assignment.state === "complete" && assignment.completion !== null;
57
+ const acceptedByPerson = accepted && assignment.completion.person !== undefined;
55
58
  if (scope === null)
56
59
  row("plan", "no", "There's no plan yet.");
57
60
  else if (approvalOf(scope).approved)
@@ -78,13 +81,17 @@ export function checklistFromAssignment(store, taskId, assignment, landed = null
78
81
  else if (check === "off")
79
82
  row("checks", "waiting", "Checks are off for this project; they run at release.");
80
83
  else if (check === "not-run" && assignment.repo !== null && !projectCheckSet(store, assignment.repo)) {
81
- row("checks", "no", noCheckSetWords(assignment.repo));
84
+ row("checks", "note", noCheckSetWords(assignment.repo));
82
85
  }
83
86
  else
84
87
  row("checks", "no", check === "unreadable" ? "The check result couldn't be read." : check === "stale" ? "The check command changed since they ran on this commit." : "No check ran on this commit.", { kind: "run-checks", run: receipt.runId });
85
88
  const criteria = assignment.readiness?.blockers.filter(one => one.key === "criteria" || one.key === "high") ?? [];
86
89
  if (receipt === null)
87
90
  row("requirements", "waiting", "Waits for a build.");
91
+ else if (acceptedByPerson) {
92
+ const by = completedByOf(assignment.completion);
93
+ row("requirements", "yes", by === null ? "Accepted." : `Accepted by ${by}.`);
94
+ }
88
95
  else if (criteria.length > 0)
89
96
  row("requirements", "no", criteria[0].message, { kind: "fix", run: receipt.runId, note: criteria.map(one => one.message).join("\n") });
90
97
  else if (assignment.readiness?.verdict === "refuted")
@@ -144,15 +151,20 @@ export function checklistFromAssignment(store, taskId, assignment, landed = null
144
151
  row("pr-ci", view.state === "failed" || view.state === "closed" ? "skip" : "waiting", view.state === "failed" || view.state === "closed" ? "No open pull request." : "No CI has reported yet.");
145
152
  }
146
153
  const notRecorded = publishing.on ? NOT_RECORDED : NOT_RECORDED_LOCAL;
147
- const standing = merged || publishing.on || receipt === null || assignment.repo === null ? null : resultBehindMain(assignment.repo, head, base === undefined ? undefined : base?.main ?? null, read);
154
+ const standing = merged || publishing.on || receipt === null || assignment.repo === null ? null : behindMainOf(store, assignment, base === undefined ? undefined : base?.main ?? null, read);
148
155
  if (merged)
149
156
  row("up-to-date", "yes", "Merged.");
150
157
  else if (standing == null || standing.main === null || standing.behind === null)
151
158
  row("up-to-date", "unknown", notRecorded);
152
159
  else if (standing.behind === 0)
153
160
  row("up-to-date", "yes", `Up to date with ${standing.main}.`);
154
- else
155
- row("up-to-date", "no", `${standing.main} has ${standing.behind === 1 ? "1 commit" : `${standing.behind} commits`} this work doesn't. Send it back to build on the current ${standing.main}.`, { kind: "fix", run: receipt.runId, note: `${standing.main} moved on since this work started. Build it again on the current ${standing.main}.` });
161
+ else {
162
+ const missing = `${standing.main} has ${standing.behind === 1 ? "1 commit" : `${standing.behind} commits`} this work doesn't`;
163
+ if (standing.conflict !== null)
164
+ row("up-to-date", "no", `${missing}, and they conflict with it${conflictNames(standing.conflict)}. Merge it into ${standing.main} yourself and resolve the conflicts, or file a new task on the current ${standing.main}.`);
165
+ else
166
+ row("up-to-date", "no", `${missing}. Send it back: Toolroll builds it again on the current ${standing.main} with this work merged in.`, { kind: "fix", run: receipt.runId, note: upToDateNote(standing.main) });
167
+ }
156
168
  if (merged)
157
169
  row("conflicts", "yes", "Merged.");
158
170
  else if (receipt?.checks.batch?.state === "conflict")
@@ -165,7 +177,7 @@ export function checklistFromAssignment(store, taskId, assignment, landed = null
165
177
  else if (notes.length === 0)
166
178
  row("comments", "yes", "None open.");
167
179
  else
168
- row("comments", "no", `${notes.length} note${notes.length === 1 ? "" : "s"} not sent back yet.`, { kind: "fix", run, note: "" });
180
+ row("comments", accepted ? "note" : "no", `${notes.length} note${notes.length === 1 ? "" : "s"} not sent back yet.`, { kind: "fix", run, note: "" });
169
181
  if (scope !== null && deployGateScope(scope)) {
170
182
  if (releaseCiHoldOf(store, active) !== null || releaseCiRunningOf(store, active) !== null)
171
183
  row("release", "waiting", "GitHub's checks are still running.");
@@ -187,6 +199,19 @@ export function checklistFromAssignment(store, taskId, assignment, landed = null
187
199
  : `Yes, as far as Toolroll records.${unknown.length === 0 ? "" : ` Check ${unknown.join(" and ")} ${publishing.on ? "on GitHub" : "in your repository"}.`}`;
188
200
  return { taskId, activeTaskId: active, run, head, answer, sentence, rows };
189
201
  }
202
+ export const upToDateNote = (main) => `${main} moved on since this work started. Make sure the work still fits with ${main}'s newer changes.`;
203
+ const conflictNames = (files) => files.length === 0 ? "" : ` in ${files.slice(0, 3).map(one => shownName(one)).join(", ")}${files.length > 3 ? ", …" : ""}`;
204
+ export function behindMainOf(store, assignment, main, read = landingReads) {
205
+ const receipt = assignment.receipt;
206
+ if (receipt === null || assignment.repo === null)
207
+ return null;
208
+ const checkedOut = main === undefined ? read(assignment.repo, ["symbolic-ref", "--short", "-q", "HEAD"]) || null : main;
209
+ const standing = resultBehindMain(assignment.repo, receipt.head, landingBranchOf(store, assignment.repo, checkedOut), read);
210
+ if (standing.main === null || standing.behind === null || standing.behind === 0)
211
+ return { ...standing, conflict: null };
212
+ const tip = read(assignment.repo, ["rev-parse", "--verify", "-q", `refs/heads/${standing.main}^{commit}`]);
213
+ return { ...standing, conflict: tip === null ? null : catchUpConflictOf(store, receipt.taskId, tip) };
214
+ }
190
215
  function resultBehindMain(repo, head, main, read) {
191
216
  const branch = main === undefined ? read(repo, ["symbolic-ref", "--short", "-q", "HEAD"]) || null : main;
192
217
  if (branch === null || head === null || !/^[0-9a-f]{40}$/.test(head))
@@ -197,7 +222,7 @@ function resultBehindMain(repo, head, main, read) {
197
222
  export function checklistLines(list) {
198
223
  if (list.answer === "landed")
199
224
  return [list.sentence];
200
- const MARK = { yes: "✓", no: "✗", waiting: "…", unknown: "?", skip: "–" };
225
+ const MARK = { yes: "✓", no: "✗", waiting: "…", unknown: "?", note: "–", skip: "–" };
201
226
  return [`Can I merge ${list.activeTaskId}? ${list.sentence}`,
202
227
  ...list.rows.filter(one => one.mark !== "skip").map(one => ` ${MARK[one.mark]} ${one.label}: ${one.say}${one.act === null ? "" : ` Next: ${CHECKLIST_ACT_LABELS[one.act.kind]}, on the task's page.`}`)];
203
228
  }
package/dist/operate.js CHANGED
@@ -4,7 +4,7 @@ import { readStoredGeminiStatus, refreshSubscriptions } from "./subscription-usa
4
4
  import { liveCommandsShown } from "./live-detail.js";
5
5
  import { flexibleArmedPass } from "./flexible-ship.js";
6
6
  import { directChatArmedPass } from "./direct-chat-ship.js";
7
- import { saveFlexibleBranch } from "./flexible-save.js";
7
+ import { flexibleSavedWords, flexibleUncommittedFiles, saveFlexibleBranch } from "./flexible-save.js";
8
8
  import { closeFlexibleThread, flexibleShipNeedsFor, flexibleThreadRecords, flexibleThreadShipTerms, flexibleThreadTitleOf, latestFlexibleShip, removeFlexibleThreadCopy, shipFlexibleThread, stopFlexibleThreadsEverywhere } from "./flexible-session.js";
9
9
  import { runCardCommand } from "./card-cli.js";
10
10
  import { mintSecret } from "./secret-mint.js";
@@ -102,6 +102,7 @@ import { passwordFreeOwner, passwordFreeShell, passwordFreeShellWords, proveTask
102
102
  import { applyPendingAgentChanges, planAgainAsLocalOwner, requestPlanAsLocalOwner, retryAsLocalOwner } from "./local-owner-acts.js";
103
103
  import { withTaskAlias } from "./task-aliases.js";
104
104
  import { checklistLines, landedNowOf, mergeChecklistOf } from "./merge-checklist.js";
105
+ import { landedRowsOf } from "./landed-rows.js";
105
106
  import { taskReviewBrief, renderReviewBrief } from "./task-review-brief.js";
106
107
  import { homedir, hostname } from "node:os";
107
108
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
@@ -127,7 +128,8 @@ import { isWritesMode, writesWords } from "./writes-mode.js";
127
128
  import { linuxFenceAvailable, macosFenceAvailable } from "./agent-fence.js";
128
129
  import { parseMachLookup, parseReadDeny, readDenyWords } from "./project-sandbox.js";
129
130
  import { LOCAL_POLICY } from "./surface.js";
130
- import { handoffWords, land, landedLine, landingWords, publishesThroughPullRequests, PULL_REQUESTS_INSTEAD, readLanding } from "./local-landing.js";
131
+ import { handoffWords, land, landedLine, landingBranchOf, landingWords, publishesThroughPullRequests, PULL_REQUESTS_INSTEAD, readLanding } from "./local-landing.js";
132
+ import { catchUpMergeOf, catchUpRevision, recordCatchUp } from "./revision-catch-up.js";
131
133
  import { asLocalOwner, currentLocalOwner, localActNow, LOCAL_MODE_CONFINES, localModeOn, localOwnerRefusal, localOwnerRequested } from "./local-owner.js";
132
134
  import { CHECK_ACCESS_WARNINGS, checkAccessRunsAs, checkAccessWords, isCheckAccess, signInHostsMissing, signInsUnavailableWords, widerThan } from "./check-access.js";
133
135
  import { CLI_PASSWORD_SOURCE, withPasswordSource } from "./sign-in-guard.js";
@@ -223,6 +225,7 @@ import { readExecutorOf } from "./read-executor.js";
223
225
  import { parseWorkView } from "./workspace-ui.js";
224
226
  import { taskWorkSummaryOf } from "./work-summary.js";
225
227
  import { assignmentOf, assignmentBrief, syncAssignmentHandoffs } from "./assignment.js";
228
+ import { completedByOf } from "./task-status.js";
226
229
  import { createScheduledFlow, describeSchedule, parseSchedule } from "./flow-schedule.js";
227
230
  import { fileTaskProposal, validateTaskText } from "./proposal.js";
228
231
  import { TEMPLATES, templateByName } from "./templates.js";
@@ -2771,17 +2774,32 @@ async function tickCommand(flags, context) {
2771
2774
  const branch = await existingOrFirst(taskBranches(id), async (one) => (await git("git", ["rev-parse", "--verify", "--quiet", `refs/heads/${one}`], { cwd: repo })).code === 0);
2772
2775
  const exists = await git("git", ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`], { cwd: repo });
2773
2776
  let buildBase = base;
2777
+ let caughtUp = null;
2774
2778
  if (ref.revisionOf !== null) {
2775
2779
  const source = revisionSourceHead(store, context.evidenceRoot, ref.id, ref.revisionOf);
2776
2780
  let problem = source.ok ? null : source.problem;
2777
2781
  if (source.ok) {
2778
- if (exists.code !== 0 && text(flags, "base") === undefined)
2782
+ if (exists.code !== 0 && text(flags, "base") === undefined) {
2779
2783
  buildBase = source.head;
2784
+ if (!publishesThroughPullRequests(store, repo)) {
2785
+ const onto = landingBranchOf(store, repo, base);
2786
+ const result = await catchUpRevision(hardenedGit(git, "build", { repo }), repo, source.head, onto, id, clock());
2787
+ caughtUp = { head: source.head, onto, result };
2788
+ if (result.kind === "merged")
2789
+ buildBase = result.commit;
2790
+ }
2791
+ }
2780
2792
  else {
2781
2793
  const descendant = exists.code === 0 ? branch : base;
2782
2794
  const ancestry = await lazyFetchSafeGit(git)("git", [...noLazyFetch(), "-c", "protocol.allow=never", "--no-replace-objects", "merge-base", "--is-ancestor", source.head, descendant], { cwd: repo });
2783
2795
  if (ancestry.code !== 0)
2784
2796
  problem = ancestry.stderr.includes(PARTIAL_CLONE_REFUSAL) ? PARTIAL_CLONE_REFUSAL : "the requested revision base does not contain its source head";
2797
+ else if (exists.code === 0 && store.latestBranchBaseMove(ref.id, branch) === null && store.firstBuilderBase(ref.id, branch) === null && !publishesThroughPullRequests(store, repo)) {
2798
+ const tip = exists.stdout.trim();
2799
+ const main = await catchUpMergeOf(hardenedGit(git, "build", { repo }), repo, tip, source.head, landingBranchOf(store, repo, base));
2800
+ if (main !== null)
2801
+ store.recordBranchBaseMove(ref.id, branch, tip, main, clock());
2802
+ }
2785
2803
  }
2786
2804
  }
2787
2805
  if (problem !== null) {
@@ -2800,6 +2818,21 @@ async function tickCommand(flags, context) {
2800
2818
  reclaim: { evidenceRoot: context.evidenceRoot },
2801
2819
  ...(exists.code === 0 ? freshBaseFor(store, id, branch, base) : {}),
2802
2820
  });
2821
+ if (caughtUp !== null && caughtUp.result.kind === "merged") {
2822
+ const merged = caughtUp.result;
2823
+ const at = leased.ok && leased.created ? await hardenedGit(git, "build", { repo })("git", ["rev-parse", "--verify", "-q", `refs/heads/${branch}^{commit}`], { cwd: repo }) : null;
2824
+ if (at !== null && at.code === 0 && at.stdout.trim() === merged.commit)
2825
+ store.recordBranchBaseMove(ref.id, branch, merged.commit, merged.main, clock());
2826
+ else if (leased.ok && leased.created) {
2827
+ await worktrees.release(leased.worktree.path, clock());
2828
+ release(store, lease, clock());
2829
+ dispatched.push({ id, outcome: "failed", reason: "git", detail: "Toolroll couldn't confirm the new branch stands at its merge of main; it tries again." });
2830
+ broke++;
2831
+ continue;
2832
+ }
2833
+ else
2834
+ caughtUp = { ...caughtUp, result: { kind: "unavailable" } };
2835
+ }
2803
2836
  if (!leased.ok) {
2804
2837
  release(store, lease, clock());
2805
2838
  dispatched.push({ id, outcome: "failed", reason: leased.reason });
@@ -2849,6 +2882,8 @@ async function tickCommand(flags, context) {
2849
2882
  continue;
2850
2883
  }
2851
2884
  noteBaseStanding(store, runId, leased.base, base, clock());
2885
+ if (caughtUp !== null && leased.created)
2886
+ recordCatchUp(store, { repo, taskId: id, runId, branch, head: caughtUp.head, onto: caughtUp.onto }, caughtUp.result, clock());
2852
2887
  if (leased.resumedFromRun !== undefined) {
2853
2888
  store.addRunNote(runId, "Toolroll", `Recovered the ${leased.recoveryKind === "completed" ? "completed source draft" : "work-in-progress draft"} from interrupted attempt #${leased.resumedFromRun}. This fresh attempt is reviewing and verifying it; the safety patch is retained.`, clock());
2854
2889
  }
@@ -4704,6 +4739,8 @@ async function verifyCommand(positional, flags, context) {
4704
4739
  const wanted = positional[1];
4705
4740
  if (!isCheckLevel(wanted))
4706
4741
  return fail(write, json, "verify level", "usage", "`toolroll verify level quick|full|off --repo <path> --as <you> --token <t>`", EXIT.usage);
4742
+ if (passwordFreeInstall(store, flags, context.principal !== undefined))
4743
+ return fail(write, json, "verify level", "local-owner", "Changing a check needs a password. Run `toolroll password set` first.", EXIT.refused);
4707
4744
  const acting = await askCredentials(flags, context);
4708
4745
  if (acting === null)
4709
4746
  return fail(write, json, "verify level", "usage", "changing a project's checks takes `--as <you> --token <t>`", EXIT.usage);
@@ -4725,6 +4762,8 @@ async function verifyCommand(positional, flags, context) {
4725
4762
  const grantKey = repo === undefined ? undefined : quickValue !== undefined || quickClear ? quickVerifyKey(repo) : repo;
4726
4763
  if (repo === undefined)
4727
4764
  return fail(write, json, `verify ${action}`, "usage", "which repo? --repo <path>", EXIT.usage);
4765
+ if (passwordFreeInstall(store, flags, context.principal !== undefined))
4766
+ return fail(write, json, `verify ${action}`, "local-owner", `${action === "set" ? "Setting" : "Clearing"} a check needs a password. Run \`toolroll password set\` first.`, EXIT.refused);
4728
4767
  const acting = await askCredentials(flags, context);
4729
4768
  const verified = acting === null ? null : authenticateApprover(store, acting.name, acting.token);
4730
4769
  if (acting === null || !verified?.ok)
@@ -8072,7 +8111,8 @@ function listTasks(flags, context) {
8072
8111
  return fail(write, json, 'task list', 'usage', 'Invalid page cursor. Start again without --cursor.', EXIT.usage);
8073
8112
  };
8074
8113
  const show = (page) => {
8075
- const tasks = page.items.map(item => ({ ...item, id: item.rootId }));
8114
+ const landed = landedRowsOf(store, page.items);
8115
+ const tasks = page.items.map(item => ({ ...item, id: item.rootId, ...(landed.has(item.rootId) ? { landed: landed.get(item.rootId) } : {}) }));
8076
8116
  if (json) {
8077
8117
  write(envelopeJson({ ok: true, command: 'task list', count: tasks.length, tasks,
8078
8118
  totals: page.totals, nextCursor: page.nextCursor, limit: page.limit, view: page.view, evidence: 'recorded' }));
@@ -8081,8 +8121,13 @@ function listTasks(flags, context) {
8081
8121
  if (tasks.length === 0)
8082
8122
  write(wanted === undefined ? 'The task list is empty.' : `Nothing is ${wanted}.`);
8083
8123
  const width = Math.max(0, ...tasks.map(task => task.id.length));
8124
+ const AFTER = { failed: 'checks failed after acceptance', stale: 'checks out of date', unreadable: "checks couldn't be read" };
8125
+ const marks = (task) => {
8126
+ const said = [...('landed' in task ? [`${task.landed.charAt(0).toLowerCase()}${task.landed.slice(1)}`] : []), ...(task.check === undefined ? [] : [AFTER[task.check]])];
8127
+ return said.length === 0 ? '' : ` · ${said.join(' · ')}`;
8128
+ };
8084
8129
  for (const task of tasks)
8085
- write(task.archived === undefined ? ` ${task.id.padEnd(width)} ${task.status.label.padEnd(16)} ${task.title}`
8130
+ write(task.archived === undefined ? ` ${task.id.padEnd(width)} ${task.status.label.padEnd(16)} ${task.title}${marks(task)}`
8086
8131
  : ` ${task.id.padEnd(width)} ${'Archived'.padEnd(16)} ${task.title} — by ${task.archived.byKind === 'tidy' ? 'tidy' : task.archived.by}: ${task.archived.reason}`);
8087
8132
  if (page.nextCursor !== null)
8088
8133
  write(`Next page: --cursor ${page.nextCursor}`);
@@ -8172,6 +8217,7 @@ function showTask(positional, context) {
8172
8217
  return succeed(write, json, "task show", detail, () => [
8173
8218
  `${task.id} ${shared?.headline ?? detail.work?.status.label ?? task.state}${ref.deliverable === "report" ? " (scout — delivers a report)" : ""}`,
8174
8219
  ` ${task.title}`,
8220
+ ...(landedNow === null ? [] : [` landing: ${landedNow}`]),
8175
8221
  ...(detail.work === null ? [] : [
8176
8222
  ` status: ${shared?.headline ?? detail.work.status.label}${shared === null ? "" : `${shared.headline === "On hold" ? " · " : " — "}${shared.sentence}`}`,
8177
8223
  ...(primaryAction === null || (checkedByPerson && (primaryAction.code === "open-result" || primaryAction.code === "inspect-run")) ? []
@@ -8179,12 +8225,17 @@ function showTask(positional, context) {
8179
8225
  ]),
8180
8226
  ...(task.state !== "done" || detail.proofVerdict === null
8181
8227
  ? []
8182
- : [
8183
- ` checked: ${proofVerdictWords(current?.receipt?.runId === latestFinished?.id ? current?.readiness?.verdict ?? detail.proofVerdict : detail.proofVerdict, detail.proofReasons).word}${detail.proofAccepted ? " (accepted)" : ""}`,
8184
- ...(shownReasons.length > 0 ? [` ${shownReasons.map(plainReasonWords).join(" ")}`] : []),
8228
+ : shared?.headline === "Complete" && current?.completion?.person !== undefined ? [
8229
+ ` checked: ${acceptedWords(current?.completion ?? null)}`,
8185
8230
  ...matrixWords(shownMatrix),
8186
8231
  ...(detail.semanticCoverage === null ? [] : coverageWords(detail.semanticCoverage).map(line => ` ${line}`)),
8187
- ]),
8232
+ ]
8233
+ : [
8234
+ ` checked: ${proofVerdictWords(current?.receipt?.runId === latestFinished?.id ? current?.readiness?.verdict ?? detail.proofVerdict : detail.proofVerdict, detail.proofReasons).word}${detail.proofAccepted ? " (accepted)" : ""}`,
8235
+ ...(shownReasons.length > 0 ? [` ${shownReasons.map(plainReasonWords).join(" ")}`] : []),
8236
+ ...matrixWords(shownMatrix),
8237
+ ...(detail.semanticCoverage === null ? [] : coverageWords(detail.semanticCoverage).map(line => ` ${line}`)),
8238
+ ]),
8188
8239
  ...(detail.report === null
8189
8240
  ? []
8190
8241
  : detail.report.ok
@@ -8195,7 +8246,6 @@ function showTask(positional, context) {
8195
8246
  ]
8196
8247
  : [` report: ${detail.report.problem} (build #${detail.report.run})`]),
8197
8248
  ...pullRequestLines(detail.pullRequest),
8198
- ...(landedNow === null ? [] : [` landing: ${landedNow}`]),
8199
8249
  ...(base === null ? [] : [` base: ${baseStandingWords(base, landedNow !== null)}`]),
8200
8250
  ...(detail.blockedBy.length > 0 ? [` waits for ${detail.blockedBy.join(", ")}`] : []),
8201
8251
  ...(detail.position === null
@@ -13083,10 +13133,7 @@ async function flexibleSignInConfig(action, extra, repoGiven, flags, context) {
13083
13133
  return succeed(write, json, command, { saved: true, replaced: saved.replaced, check: checked.outcome, signIn: statusData(flexibleSignInStatus(store, acting.name)) }, () => [`${saved.replaced ? "Replaced" : "Saved"}. ${signInCheckWords(checked)} It powers only threads you start; a password reset ends it.`]);
13084
13134
  }
13085
13135
  function passwordFreeRefusal(store, flags, key, remote) {
13086
- if (remote || ["as", "token", "token-file", "token-env"].some(name => flags.has(name)) || localOwnerRequested() || envValue(process.env, "LEAD_TOKEN") !== undefined)
13087
- return null;
13088
- const binding = localOwnerBinding(store);
13089
- if (binding === null || store.accountOf(binding.account)?.passwordSet === true)
13136
+ if (!passwordFreeInstall(store, flags, remote))
13090
13137
  return null;
13091
13138
  return `This Toolroll has no password yet, so this runs from Toolroll itself: run \`toolroll\`, select the task and press ${key}, or open it in the browser.`;
13092
13139
  }
@@ -13220,13 +13267,16 @@ async function threadCommand(positional, flags, context) {
13220
13267
  if (done.stopPending)
13221
13268
  await stopFlexibleThreadsEverywhere(store, { reason: "its owner ended the thread", thread, clock });
13222
13269
  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)}\`)`;
13223
- 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.`]);
13270
+ const left = done.already ? 0 : (await flexibleUncommittedFiles(store, { thread })).length;
13271
+ const leftWords = `Ended. Its agent left uncommitted edits in ${left} file${left === 1 ? "" : "s"}: \`toolroll thread save ${thread.slice(0, 8)}\` saves them with its work as a branch. Its copy is kept for a week.`;
13272
+ return succeed(write, json, command, { thread, already: done.already }, () => [done.already ? "This thread had already ended." : left > 0 ? leftWords : `Ended. You can still ${keeps} for a week; then its copy is tidied.`]);
13224
13273
  }
13225
13274
  if (verb === "save") {
13226
13275
  const saved = await saveFlexibleBranch(store, { thread, by: { name: who.name, generation: account.generation }, now: clock(), prove: proveNow });
13227
13276
  if (!saved.ok)
13228
13277
  return fail(write, json, command, saved.reason, saved.message, EXIT.refused);
13229
- return succeed(write, json, command, { thread, branch: saved.branch, commit: saved.candidate, already: saved.already, files: saved.changedPaths, next: saved.next }, () => [saved.already ? `Already saved as ${saved.branch} (commit ${saved.candidate.slice(0, 12)}).` : `Saved as ${saved.branch} (commit ${saved.candidate.slice(0, 12)}, ${saved.changedPaths.length} file${saved.changedPaths.length === 1 ? "" : "s"}).`, saved.next]);
13278
+ return succeed(write, json, command, { thread, branch: saved.branch, commit: saved.candidate, already: saved.already, files: saved.changedPaths, next: saved.next,
13279
+ leftover: saved.leftover, uncommitted: saved.uncommitted }, () => [flexibleSavedWords(saved), saved.next]);
13230
13280
  }
13231
13281
  const removed = await removeFlexibleThreadCopy(store, { thread, by: who.name, now: clock(), prove: proveNow });
13232
13282
  return removed.ok ? succeed(write, json, command, { thread }, () => ["Removed its working copy. Its record stays."]) : fail(write, json, command, removed.reason, removed.message, EXIT.refused);
@@ -13504,3 +13554,13 @@ function verifyRepoOf(store, raw) {
13504
13554
  return absolute;
13505
13555
  }
13506
13556
  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`).";
13557
+ function passwordFreeInstall(store, flags, remote) {
13558
+ if (remote || ["as", "token", "token-file", "token-env"].some(name => flags.has(name)) || localOwnerRequested() || envValue(process.env, "LEAD_TOKEN") !== undefined)
13559
+ return false;
13560
+ const binding = localOwnerBinding(store);
13561
+ return binding !== null && store.accountOf(binding.account)?.passwordSet !== true;
13562
+ }
13563
+ function acceptedWords(completion) {
13564
+ const by = completedByOf(completion);
13565
+ return by === null ? "accepted" : `accepted by ${by}`;
13566
+ }
@@ -87,7 +87,14 @@ export function followUpChecksOf(store, runId, now = new Date(), root, asOf) {
87
87
  return { ...base, state: "not-run", note: "The saved check result could not be verified." };
88
88
  }
89
89
  const exit = /exit (\d+)/.exec(finished.detail ?? "");
90
- return { ...base, state: status === "passed" ? "passed" : status === "failed" ? "failed" : "not-run",
90
+ const outdated = status === "failed" && root !== undefined && asOf === undefined && repo !== null && !stillApproved(base.level, digest)
91
+ && (() => { try {
92
+ return checkCommandFor(store, repo, base.level).command !== null;
93
+ }
94
+ catch {
95
+ return false;
96
+ } })();
97
+ return { ...base, ...(outdated ? { outdated: true } : {}), state: status === "passed" ? "passed" : status === "failed" ? "failed" : "not-run",
91
98
  exitCode: exit === null ? sealed?.exitCode ?? null : Number(exit[1]), logArtifactId: sealed?.log ?? null, note: status === "not-run" ? finished.detail : null,
92
99
  ...(sealed === null ? {} : { tested: sealed.ran ? sealed.tested : null, batch: sealed.batch }) };
93
100
  }