toolroll 0.9.125 → 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.
Files changed (69) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +1 -1
  3. package/dist/agent-detect.js +23 -3
  4. package/dist/assignment.js +14 -4
  5. package/dist/bounded-spawn.js +5 -36
  6. package/dist/browser/workspace.css +1 -1
  7. package/dist/browser/workspace.js +29 -29
  8. package/dist/browser-open.js +49 -0
  9. package/dist/chat-acceptance.js +1 -1
  10. package/dist/check-only.js +1 -1
  11. package/dist/cli.js +2 -2
  12. package/dist/connect-cli.js +2 -8
  13. package/dist/contracts/engine-api.js +8 -0
  14. package/dist/direct-chat.js +26 -18
  15. package/dist/doctor.js +30 -3
  16. package/dist/easy-start.js +44 -17
  17. package/dist/engine-reads.js +34 -1
  18. package/dist/evals.js +17 -19
  19. package/dist/first-run.js +5 -1
  20. package/dist/flexible-conversation.js +79 -1
  21. package/dist/flexible-import.js +162 -4
  22. package/dist/flexible-save.js +51 -4
  23. package/dist/flexible-session.js +34 -8
  24. package/dist/flexible-start.js +2 -1
  25. package/dist/flow-code.js +2 -2
  26. package/dist/invoke.js +4 -4
  27. package/dist/landed-rows.js +138 -0
  28. package/dist/laptop-background.js +2 -11
  29. package/dist/linux-packages.js +46 -0
  30. package/dist/local-landing.js +46 -7
  31. package/dist/merge-checklist.js +62 -8
  32. package/dist/operate.js +90 -33
  33. package/dist/preflight.js +14 -0
  34. package/dist/process-identity.js +155 -0
  35. package/dist/quick-start.js +6 -1
  36. package/dist/release.js +8 -0
  37. package/dist/result-follow-ups.js +8 -1
  38. package/dist/revision-catch-up.js +98 -0
  39. package/dist/runner-process.js +9 -25
  40. package/dist/sandbox-launch.js +3 -2
  41. package/dist/sandbox-runtime.js +115 -15
  42. package/dist/sandbox-tools.js +91 -6
  43. package/dist/server/direct-chat.js +4 -3
  44. package/dist/server/engine-api.js +13 -8
  45. package/dist/server/merge-ready-view.js +4 -2
  46. package/dist/server/pages.js +5 -2
  47. package/dist/server/render-pages.js +1 -0
  48. package/dist/server/render-results.js +9 -7
  49. package/dist/server/render-tasks.js +2 -2
  50. package/dist/server/task-views.js +16 -9
  51. package/dist/server/tasks.js +2 -2
  52. package/dist/shown-text.js +14 -0
  53. package/dist/skill-library.js +2 -12
  54. package/dist/status-probe.js +32 -0
  55. package/dist/task-base.js +13 -2
  56. package/dist/task-status.js +18 -8
  57. package/dist/teardown-git.js +6 -0
  58. package/dist/telegram-status.js +1 -1
  59. package/dist/toolroll-update-cli.js +2 -1
  60. package/dist/toolroll-update.js +4 -0
  61. package/dist/trust-repair.js +187 -0
  62. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  63. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  64. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  65. package/dist/tui/linux-x64/toolroll-tui +0 -0
  66. package/dist/unreachable.js +15 -0
  67. package/dist/work-index.js +51 -3
  68. package/dist/workspace-ui.js +4 -2
  69. package/package.json +1 -1
@@ -2,6 +2,9 @@ import { accessSync, constants as fsConstants, existsSync, lstatSync, realpathSy
2
2
  import { createRequire } from "node:module";
3
3
  import { dirname, join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
+ import { installLine, reinstallLine } from "./linux-packages.js";
6
+ import { hasUnsafeText, shownText } from "./shown-text.js";
7
+ import { mergeRepairs, toolrollPackageRoot, trustFaults, trustFaultWords, trustRepair } from "./trust-repair.js";
5
8
  import { platformAcl, rootOwnedBinary, rootOwnedFolders } from "./trusted-path.js";
6
9
  export const SANDBOX_TOOL_FOLDERS = ["/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin", "/run/current-system/sw/bin"];
7
10
  const SYSTEM_TOOLS = [
@@ -49,7 +52,7 @@ export function sandboxToolExclusions(terms, cwd) {
49
52
  return { all: roots([cwd, ...write.allowOnly, ...write.literalAllowOnly ?? [], ...write.denyWithinAllow, ...terms.readConfig.denyOnly]), writes: { allow, deny } };
50
53
  }
51
54
  const mayWrite = (writes, path) => writes.allow.some(root => insideOrAt(path, root)) && !writes.deny.some(root => insideOrAt(path, root));
52
- const installWords = (pkg) => `install ${pkg} from your system package manager (sudo apt install ${pkg}; Fedora: sudo dnf install ${pkg})`;
55
+ const installWords = (pkg) => `install ${pkg} from your system package manager (${installLine([pkg])})`;
53
56
  function identify(real) {
54
57
  try {
55
58
  accessSync(real, fsConstants.X_OK);
@@ -92,6 +95,7 @@ export function resolveLinuxSandboxTools(options = {}) {
92
95
  let whichFolder = null;
93
96
  for (const tool of SYSTEM_TOOLS) {
94
97
  const passedOver = [];
98
+ const rejected = [];
95
99
  for (const folder of folders) {
96
100
  const candidate = join(folder, tool.command);
97
101
  if (!existsSync(candidate))
@@ -99,12 +103,14 @@ export function resolveLinuxSandboxTools(options = {}) {
99
103
  const checked = checkSystem(candidate, trust, exclusions);
100
104
  if (!checked.ok) {
101
105
  passedOver.push(`${candidate}: ${checked.why}`);
106
+ rejected.push(candidate);
102
107
  continue;
103
108
  }
104
109
  if (tool.key === "which") {
105
110
  const dir = rootOwnedFolders(folder, trust.acl, trust.root);
106
111
  if (!dir.ok) {
107
112
  passedOver.push(`${candidate}: ${dir.why}`);
113
+ rejected.push(candidate);
108
114
  continue;
109
115
  }
110
116
  whichFolder = dir.real;
@@ -112,20 +118,28 @@ export function resolveLinuxSandboxTools(options = {}) {
112
118
  found[tool.key] = checked.tool;
113
119
  break;
114
120
  }
121
+ if (found[tool.key] === undefined && rejected.length === 0) {
122
+ return { ok: false, failure: "missing", why: shownText(`${tool.words} has no copy owned by root in ${folders.join(", ")}: ${installWords(tool.install)}`) };
123
+ }
115
124
  if (found[tool.key] === undefined) {
116
- return { ok: false, why: `${tool.words} has no copy owned by root in ${folders.join(", ")}${passedOver.length === 0 ? "" : ` (${passedOver.join("; ")})`}: ${installWords(tool.install)}` };
125
+ return { ok: false, failure: "untrusted", rejected,
126
+ why: shownText(`${tool.words} has no copy Toolroll can trust in ${folders.join(", ")} (${passedOver.join("; ")}): remove a copy your package manager didn't install, or reinstall ${tool.install} (${reinstallLine([tool.install])}); \`toolroll doctor\` says which`) };
117
127
  }
118
128
  }
119
129
  const helper = "seccomp" in options ? options.seccomp ?? null : seccompHelperPath();
120
130
  if (helper === null)
121
- return { ok: false, why: `the sandbox runtime's seccomp helper isn't available for this processor (${process.arch})` };
131
+ return { ok: false, failure: "unsupported-arch", why: `the sandbox runtime's seccomp helper isn't available for this processor (${process.arch})` };
122
132
  const checked = checkSeccompHelper(helper, exclusions, options);
123
133
  if (!checked.ok)
124
- return { ok: false, why: `the sandbox runtime's seccomp helper (${helper}) can't be trusted: ${checked.why}` };
134
+ return { ok: false, failure: "seccomp-untrusted", rejected: [helper], why: shownText(`the sandbox runtime's seccomp helper (${helper}) can't be trusted: ${checked.why}`) };
125
135
  found.seccomp = checked.tool;
126
136
  return { ok: true, tools: { ...found, whichFolder: whichFolder } };
127
137
  }
128
138
  export function verifyLinuxSandboxTools(tools, options = {}) {
139
+ const why = verifyNow(tools, options);
140
+ return why === null ? null : shownText(why);
141
+ }
142
+ function verifyNow(tools, options) {
129
143
  const trust = trustOf(options);
130
144
  const exclusions = options.exclusions ?? NO_EXCLUSIONS;
131
145
  for (const key of KEYS) {
@@ -150,7 +164,7 @@ export function isLinuxSandboxTools(value) {
150
164
  if (value === null || typeof value !== "object")
151
165
  return false;
152
166
  const record = value;
153
- const path = (one) => typeof one === "string" && one.startsWith("/") && !/[\u0000-\u001f\u007f]/.test(one);
167
+ const path = (one) => typeof one === "string" && one.startsWith("/") && !hasUnsafeText(one);
154
168
  if (!path(record["whichFolder"]))
155
169
  return false;
156
170
  return KEYS.every(key => {
@@ -170,7 +184,78 @@ export function linuxSandboxTools(exclusions = NO_EXCLUSIONS) {
170
184
  const why = verifyLinuxSandboxTools(tools, { exclusions });
171
185
  if (why !== null) {
172
186
  discovered = null;
173
- return { ok: false, why: `a sandbox program failed its check right before the launch: ${why}` };
187
+ return { ok: false, failure: "changed", why: shownText(`a sandbox program failed its check right before the launch: ${why}`) };
174
188
  }
175
189
  return { ok: true, tools };
176
190
  }
191
+ export function seccompHelperRepair(options = {}, packageRoot = toolrollPackageRoot()) {
192
+ const helper = "seccomp" in options ? options.seccomp ?? null : seccompHelperPath();
193
+ if (helper === null || checkSeccompHelper(helper, NO_EXCLUSIONS, options).ok)
194
+ return null;
195
+ const t = trustOf(options);
196
+ const owners = t.codeOwner === undefined ? t.root : [...t.root, t.codeOwner];
197
+ const root = packageRoot;
198
+ const real = realOrSelf(helper);
199
+ let mine = false;
200
+ try {
201
+ mine = root !== null && lstatSync(root).uid === (process.geteuid?.() ?? -1);
202
+ }
203
+ catch {
204
+ mine = false;
205
+ }
206
+ return trustRepair(helper, { owners, ownTree: root !== null && mine && insideOrAt(real, root) ? root : null });
207
+ }
208
+ export function sandboxToolsRepair(options = {}, packageRoot = toolrollPackageRoot()) {
209
+ const folders = options.folders ?? SANDBOX_TOOL_FOLDERS;
210
+ const trust = trustOf(options);
211
+ const managed = options.managed ?? fromPackageManager;
212
+ const faults = [];
213
+ const notes = [];
214
+ for (const tool of SYSTEM_TOOLS) {
215
+ const candidates = folders.map(folder => join(folder, tool.command)).filter(candidate => existsSync(candidate));
216
+ const passing = candidates.filter(candidate => checkSystem(candidate, trust, NO_EXCLUSIONS).ok
217
+ && (tool.key !== "which" || rootOwnedFolders(dirname(candidate), trust.acl, trust.root).ok));
218
+ for (const copy of candidates.filter(candidate => !passing.includes(candidate))) {
219
+ const found = trustFaults(copy, { owners: trust.root }) ?? [];
220
+ faults.push(...found);
221
+ const why = `${shownText(copy)} can't be trusted${found.length === 0 ? "" : ` (${shownText(found.map(trustFaultWords).join("; "))})`}`;
222
+ if (!managed(copy)) {
223
+ notes.push(`${why}: remove it (it isn't from your system package manager, and Toolroll won't run it)${passing.length > 0 ? "." : `, then install ${tool.install}: ${installLine([tool.install])}.`}`);
224
+ }
225
+ else {
226
+ notes.push(`${why}: reinstall ${tool.install} so its own files come back (${reinstallLine([tool.install])}), and don't change its permissions by hand.`);
227
+ }
228
+ }
229
+ }
230
+ const system = faults.length === 0 && notes.length === 0 ? null : { faults, commands: [], notes };
231
+ const protectedPaths = new Set();
232
+ for (const tool of SYSTEM_TOOLS) {
233
+ for (const folder of folders) {
234
+ const copy = join(folder, tool.command);
235
+ if (!existsSync(copy))
236
+ continue;
237
+ for (const start of new Set([copy, realOrSelf(copy)]))
238
+ for (let at = start;; at = dirname(at)) {
239
+ protectedPaths.add(at);
240
+ if (dirname(at) === at)
241
+ break;
242
+ }
243
+ }
244
+ }
245
+ const helper = seccompHelperRepair(options, packageRoot);
246
+ const kept = helper === null ? null : { ...helper, commands: helper.commands.filter(command => !touchesProtected(command, protectedPaths)) };
247
+ return mergeRepairs(system, kept);
248
+ }
249
+ function touchesProtected(command, protectedPaths) {
250
+ const quoted = / '((?:[^']|'\\'')*)'$/.exec(command);
251
+ if (quoted === null)
252
+ return true;
253
+ const target = quoted[1].replace(/'\\''/g, "'");
254
+ if (protectedPaths.has(target))
255
+ return true;
256
+ return / -R /.test(command) && [...protectedPaths].some(path => insideOrAt(path, target));
257
+ }
258
+ const PACKAGE_FOLDERS = new Set(["/usr/bin", "/bin", "/usr/sbin", "/sbin", "/run/current-system/sw/bin"]);
259
+ function fromPackageManager(copy) {
260
+ return PACKAGE_FOLDERS.has(dirname(realOrSelf(copy)));
261
+ }
@@ -232,7 +232,7 @@ export function createDirectChatHandlers(runtime, deps) {
232
232
  })),
233
233
  attachments: found.attachments.map(toArtifactView),
234
234
  ships,
235
- diff: responseDiff,
235
+ diff: { changedFiles: responseDiff.changedFiles, diffText: responseDiff.diffText, dirty: responseDiff.dirty, ...(responseDiff.unread === true ? { unread: true } : {}) },
236
236
  });
237
237
  }
238
238
  async function start(ctx) {
@@ -595,8 +595,9 @@ export function createDirectChatHandlers(runtime, deps) {
595
595
  const { thread, turns, diff, running } = found;
596
596
  const turnHtml = turns.map(turn => html `<section class="card" data-turn="${turn.id}"><p><b>You</b> · <span class="k-note">${STATUS_WORDS[turn.status] ?? turn.status}</span></p><p class="pre-wrap">${turn.userPrompt}</p>${turn.assistantText.trim() === "" ? "" : html `<p><b>${thread.provider === "claude" ? "Claude" : thread.provider === "codex" ? "Codex" : "Gemini"}</b></p><p class="pre-wrap">${turn.assistantText}</p>`}${turn.errorText === null ? "" : html `<p class="problem">${turn.errorText}</p>`}</section>`);
597
597
  const shownDiff = diff.diffText.length > DIFF_SHOWN ? `${diff.diffText.slice(0, DIFF_SHOWN)}\n… (shortened)` : diff.diffText;
598
- const changes = diff.changedFiles.length === 0 ? html `<p class="k-note">No changes in its copy of the project.</p>`
599
- : html `<p class="k-note">${diff.changedFiles.length} ${diff.changedFiles.length === 1 ? "file" : "files"} changed in its own copy of the project, as of its last turn${running ? " (it's still working)" : ""}.</p><ul>${diff.changedFiles.map(file => html `<li class="k-mono">${file}</li>`)}</ul>${shownDiff === "" ? "" : html `<details><summary>The changes</summary><pre class="k-mono" data-direct-chat-diff>${shownDiff}</pre></details>`}`;
598
+ const unread = diff.unread === true ? html `<p class="k-note" data-direct-chat-diff-unread>Toolroll couldn't read its copy of the project after its last turn${diff.changedFiles.length === 0 ? "" : ", so these are the changes it saw before"}.</p>` : "";
599
+ const changes = diff.changedFiles.length === 0 ? unread !== "" ? unread : html `<p class="k-note">No changes in its copy of the project.</p>`
600
+ : html `${unread}<p class="k-note">${diff.changedFiles.length} ${diff.changedFiles.length === 1 ? "file" : "files"} changed in its own copy of the project, as of its last turn${running ? " (it's still working)" : ""}.</p><ul>${diff.changedFiles.map(file => html `<li class="k-mono">${file}</li>`)}</ul>${shownDiff === "" ? "" : html `<details><summary>The changes</summary><pre class="k-mono" data-direct-chat-diff>${shownDiff}</pre></details>`}`;
600
601
  const ships = listDirectChatShips(store, thread.id);
601
602
  const bringIn = (one) => {
602
603
  if (one.mode !== "keep-branch" || one.state !== "kept" || !/^[0-9a-f]{40}$/.test(one.candidateSha))
@@ -10,7 +10,7 @@ import { flexibleAvailable } from "../flexible-available.js";
10
10
  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
- import { saveFlexibleBranch } from "../flexible-save.js";
13
+ import { flexibleSavedWords, flexibleUncommittedFiles, saveFlexibleBranch } from "../flexible-save.js";
14
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";
@@ -22,7 +22,7 @@ import { defaultChainOf, installModeNow } from "../install-mode.js";
22
22
  import { packageVersion } from "../monitoring.js";
23
23
  import { readChildWindow } from "../live-children-read.js";
24
24
  import { readMainWindow } from "../live-main-read.js";
25
- import { runLiveCommands } from "../store.js";
25
+ import { runLiveCommands, typedNotesFor } from "../store.js";
26
26
  import { agentsReadOf, resultDiffContextOf, resultDiffFileOf, resultDiffOf, resultRunsOf, stepCardsOf, taskResultOf, threadDiffFileOf, threadDiffOf } from "../engine-reads.js";
27
27
  import { leadChatOf } from "../engine-chat.js";
28
28
  import { remoteAllows } from "../operate-remote.js";
@@ -370,6 +370,8 @@ export function createEngineHandlers(runtime) {
370
370
  const taskId = family.current.id;
371
371
  const none = (problem) => sendChecked(response, 200, "approvalCard", { version: ENGINE_API_VERSION, task: taskId, key: null, digest: null, nonce: null, terms: [], problem });
372
372
  const waits = (view) => view.nonce !== "" && view.approvalDigest != null && view.approvalSummary != null;
373
+ const sentBackTyped = (view) => view.revision == null || "problem" in view.revision ? []
374
+ : typedNotesFor(runtime.store, taskId, 100).filter(one => one.kind === "sent-back");
373
375
  const view = runtime.taskViewData(taskId, who, null, { mintNonce: false });
374
376
  if (view === null)
375
377
  return refusal(response, 404, "task");
@@ -391,12 +393,12 @@ export function createEngineHandlers(runtime) {
391
393
  key: view.approvalSummary.key,
392
394
  digest: view.approvalDigest,
393
395
  nonce: runtime.heldApprovalNonce(who.name, taskId, view.approvalDigest),
394
- terms: approvalTermsOf(view.approvalSummary, view.planContract ?? null, view.revision ?? null),
396
+ terms: approvalTermsOf(view.approvalSummary, view.planContract ?? null, view.revision ?? null, sentBackTyped(view)),
395
397
  problem,
396
398
  });
397
399
  }
398
400
  return sendChecked(response, 200, "approvalCard", { version: ENGINE_API_VERSION, task: taskId, key: view.approvalSummary.key, digest: view.approvalDigest,
399
- nonce: runtime.heldApprovalNonce(who.name, taskId, view.approvalDigest), terms: approvalTermsOf(view.approvalSummary, view.planContract ?? null, view.revision ?? null), problem: null });
401
+ nonce: runtime.heldApprovalNonce(who.name, taskId, view.approvalDigest), terms: approvalTermsOf(view.approvalSummary, view.planContract ?? null, view.revision ?? null, sentBackTyped(view)), problem: null });
400
402
  }
401
403
  async function taskDiff(ctx) {
402
404
  const { url, request, response, who } = ctx;
@@ -576,9 +578,11 @@ export function createEngineHandlers(runtime) {
576
578
  const done = await closeFlexibleThread(store, flexible, { thread: id, by: { name: who.name, generation: who.session.generation }, act });
577
579
  if (!done.ok)
578
580
  return acted(response, 409, "refused", done.message);
581
+ const left = act === "end" && !done.already && !done.stopPending ? (await flexibleUncommittedFiles(store, { thread: id })).length : 0;
579
582
  const words = act === "end"
580
583
  ? 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)."
584
+ : left > 0 ? `Ended. Its agent left uncommitted edits in ${left} file${left === 1 ? "" : "s"}: save its work as a branch (S on the thread) to keep them.`
585
+ : 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)."
582
586
  : done.stopPending ? "Stopping its agent…" : "Stopped. Reply to go on.";
583
587
  return acted(response, 200, "done", words);
584
588
  };
@@ -678,7 +682,7 @@ export function createEngineHandlers(runtime) {
678
682
  const saved = await saveFlexibleBranch(store, { thread: id, by: { name: who.name, generation: who.session.generation }, now: new Date(), prove: held });
679
683
  if (!saved.ok)
680
684
  return acted(response, 409, "refused", saved.message);
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);
685
+ return acted(response, 200, "done", `${flexibleSavedWords(saved)} ${saved.next}`, undefined, saved.command);
682
686
  }
683
687
  async function leadChat(ctx) {
684
688
  const { url, who, request, response, now } = ctx;
@@ -844,7 +848,7 @@ function bodyOf(request, cap) {
844
848
  }
845
849
  export const NOTHING_TO_APPROVE = "Nothing on this task is waiting for your approval.";
846
850
  export const APPROVE_IN_BROWSER = "Press w to open it in your browser.";
847
- export function approvalTermsOf(summary, contract, revision) {
851
+ export function approvalTermsOf(summary, contract, revision, typed = []) {
848
852
  const terms = termsOfLines(summaryLines(summary));
849
853
  if (contract !== null && "problem" in contract)
850
854
  terms.push({ label: "Plan record", words: contract.problem });
@@ -856,7 +860,8 @@ export function approvalTermsOf(summary, contract, revision) {
856
860
  if (revision !== null && "problem" in revision)
857
861
  terms.push({ label: "Sent back", words: revision.problem });
858
862
  else if (revision !== null && revision.comments.length > 0) {
859
- terms.push({ label: "Sent back", words: revision.comments.map(one => `${one.path === null ? "" : `${one.path}${one.line === null ? "" : `:${one.line}`} — `}${one.note} (${one.author})`).join("\n") });
863
+ const said = (one) => typed.find(words => one.id != null && words.id === one.id && words.author === one.author && words.note !== "" && one.note.includes(words.note))?.note ?? one.note;
864
+ terms.push({ label: "Sent back", words: revision.comments.map(one => `${one.path === null ? "" : `${one.path}${one.line === null ? "" : `:${one.line}`} — `}${said(one)} (${one.author})`).join("\n") });
860
865
  }
861
866
  return terms;
862
867
  }
@@ -1,10 +1,12 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { checklistFromAssignment } from "../merge-checklist.js";
3
3
  import { isRevisionFeedback, revisionBatchOf, revisionSourceOf } from "../result-review.js";
4
- export function mergeReadyViewOf(store, taskId, assignment, who, runChecks, returnTo) {
4
+ export function mergeReadyViewOf(store, taskId, assignment, who, runChecks, returnTo, landed = null, base = null) {
5
5
  if (assignment == null || assignment.receipt === null)
6
6
  return null;
7
- const list = checklistFromAssignment(store, taskId, assignment);
7
+ const list = checklistFromAssignment(store, taskId, assignment, landed, base);
8
+ if (list.answer === "landed")
9
+ return null;
8
10
  const person = who.via === "cookie" && who.role === "approver" && !store.isDemo();
9
11
  const receipt = assignment.receipt;
10
12
  const notes = store.liveDiffComments(receipt.runId).filter(one => isRevisionFeedback(one));
@@ -81,6 +81,7 @@ import { workIndexPage } from "../work-index.js";
81
81
  import { checkEngineResponse, ENGINE_API_VERSION } from "../contracts/engine-api.js";
82
82
  import { readRunLive } from "./engine-api.js";
83
83
  import { waitingForTasks } from "../engine-reads.js";
84
+ import { landedRowsOf } from "../landed-rows.js";
84
85
  import { FOUND_PLACES_MAX, FOUND_REPOS_MAX, foundReposCache } from "./found-repos.js";
85
86
  const PICKER_PLACES = ["Developer", "Documents", "code", "Projects"];
86
87
  export function createPagesHandlers(runtime, work) {
@@ -1267,7 +1268,7 @@ export function createPagesHandlers(runtime, work) {
1267
1268
  setup: firstRunStepsNow(now) !== null ? "/welcome" : null,
1268
1269
  empty: needs.any || needs.total > 0 ? null : { title: "No tasks yet", text: "Describe a change in a sentence; an agent writes a plan for you to approve." },
1269
1270
  };
1270
- return { view, needs, listed, chrome };
1271
+ return { view, needs, listed, chrome, work: found.work };
1271
1272
  }
1272
1273
  async function workRows(ctx) {
1273
1274
  const { request, response, who, now } = ctx;
@@ -1305,10 +1306,12 @@ export function createPagesHandlers(runtime, work) {
1305
1306
  const needOf = (row) => ({ id: row.id, title: row.title, href: row.href, project: row.project, age: row.age, state: row.state, ask: row.ask,
1306
1307
  ...(row.group === undefined ? {} : { group: row.group }), reason: row.reason, line: row.line, action: row.action, question: row.question });
1307
1308
  const waiting = waitingForTasks(store, list.rows.map(row => row.id), now);
1309
+ const landed = landedRowsOf(store, built.work.items);
1308
1310
  const body = {
1309
1311
  version: ENGINE_API_VERSION, project: view.project, projectName: view.projectName, needsCount: view.needsCount, groups: list.groups,
1310
1312
  rows: list.rows.map(row => ({ id: row.id, title: row.title, href: row.href, project: row.project, age: row.age, status: row.status, word: row.word, ask: row.ask,
1311
- chip: row.chip, group: row.group, rank: row.rank, detail: row.detail, problem: row.problem, need: row.need === undefined ? null : needOf(row.need),
1313
+ chip: row.chip, group: row.group, rank: row.rank, ...(row.check === undefined ? {} : { check: row.check }),
1314
+ ...(landed.has(row.id) ? { landed: landed.get(row.id) } : {}), detail: row.detail, problem: row.problem, need: row.need === undefined ? null : needOf(row.need),
1312
1315
  waiting: waiting.get(row.id) ?? null })),
1313
1316
  needs: view.needs.map(group => ({ key: group.key, label: group.label, count: group.count, rows: group.rows.map(needOf) })),
1314
1317
  next: list.pages.next, room: "workspace", spend, limits,
@@ -344,6 +344,7 @@ export function workPage(chrome, data) {
344
344
  id: row.rootId, title: row.title, href: taskHref(row.rootId), project: projectOf(row), age: relativeAge(row.updatedAt, data.now),
345
345
  status: { label: row.status.label, tone: row.status.tone, token: row.status.token }, chip: row.chip, word: chip,
346
346
  ask: row.ask, group: row.ask ?? (row.status.rank === 1 ? 'building' : 'rest'), rank: row.status.rank,
347
+ ...(row.check === undefined ? {} : { check: row.check }),
347
348
  action: actionHref === null || row.primaryAction === null || row.ask === null ? null : { label: row.primaryAction.label, href: actionHref },
348
349
  detail: needsYouDetail ? row.status.detail : row.progress ?? (row.ask === null && row.status.detail !== row.status.label ? row.status.detail : null),
349
350
  problem: row.familyProblem,
@@ -583,7 +583,9 @@ export function reviewCockpitDetailParts(view, csrf, noted, canRetryReview, tab,
583
583
  const shared = accepted || assignment?.receipt == null ? null : owedAcceptance(assignment.receipt, assignment.readiness?.blockers ?? []);
584
584
  const owed = accepted ? null : youCheck?.accept != null || shared === "person-check" ? { note: null }
585
585
  : shared === "exception" || blocked === ACCEPT_NEEDS_REASON ? { note: "Why is this safe to accept?" } : null;
586
- const complete = hardStop === null && assignment?.state === "ready-to-check" && assignment.receipt !== null && canRetryReview && csrf !== ""
586
+ const confirm = assignment?.state === "complete" && assignment.completion !== null && assignment.completion.person === undefined && assignment.completion.historical !== true
587
+ && assignment.completion.landed === undefined && assignment.receipt !== null && assignment.completion.digest === assignment.receipt.digest && youCheck != null;
588
+ const complete = hardStop === null && (assignment?.state === "ready-to-check" || confirm) && assignment?.receipt != null && canRetryReview && csrf !== ""
587
589
  ? { action: `${taskHref(view.taskId)}/complete`, receipt: assignment.receipt.digest, run: run.id, accept: owed, ...(host.kind === "task" ? { returnTo: at() } : {}) } : null;
588
590
  if (complete !== null)
589
591
  parts.push(completionForm(view.taskId, run.id, complete.receipt, view.detail?.pullRequestTo ?? null, owed));
@@ -591,7 +593,7 @@ export function reviewCockpitDetailParts(view, csrf, noted, canRetryReview, tab,
591
593
  const matrix = proof === null || proof.proofProblem !== null ? [] : proof.matrix;
592
594
  const unanswered = accepted || youCheck == null ? [] : youCheck.items.length > 0 ? youCheck.items.map(one => one.statement === "" ? one.words : one.statement) : youCheck.lines;
593
595
  const base = !acceptsHere ? null : acceptWordsOf({
594
- checks: checks === undefined ? null : { passed: "passed", failed: "failed", running: "running", "not-run": "not-run", off: "off", unreadable: "unavailable" }[approvedCheckStateOf(checks)],
596
+ checks: checks === undefined ? null : { passed: "passed", failed: "failed", running: "running", "not-run": "not-run", off: "off", stale: "unavailable", unreadable: "unavailable" }[approvedCheckStateOf(checks)],
595
597
  unmet: matrix.filter(row => !["Met", "You check", CHECKED_AT_RELEASE].includes(requirementWordOf(row, null, checks === undefined ? undefined : checkBackingOf(checks)))).length,
596
598
  action: complete !== null ? "complete" : "accept",
597
599
  publishing: view.detail?.publishing ?? "other",
@@ -603,7 +605,7 @@ export function reviewCockpitDetailParts(view, csrf, noted, canRetryReview, tab,
603
605
  const followUps = view.detail.followUps ?? null;
604
606
  const checksRunning = checks?.running != null || (followUps?.checks.some(one => one.state === "waiting" || one.state === "running") ?? false);
605
607
  const runChecks = canRetryReview && csrf !== "" && followUps !== null && (followUps.full || followUps.quick) && !checksRunning &&
606
- (checks === undefined || ((checks.status === "not-run" || checks.status === "unavailable") && checks.release == null))
608
+ (checks === undefined || ((checks.status === "not-run" || checks.status === "unavailable" || (checks.status === "failed" && assignment?.state === "complete")) && checks.release == null))
607
609
  ? { action: `/r/${run.id}/checks`, level: followUps.full ? "full" : "quick", returnTo: at("checks") } : null;
608
610
  const need = panel.panel.need;
609
611
  const nextKind = selected.next?.kind;
@@ -1378,7 +1380,7 @@ export function resultPanelParts(detail, o) {
1378
1380
  }
1379
1381
  if (detail.ciFailing && publication !== null && taskStatus === null)
1380
1382
  attention.push(`CI is failing on PR #${publication.prNumber} at the last check.`);
1381
- const personChecks = proof === null || proof.accepted !== null ? [] : [
1383
+ const personChecks = proof === null || proof.accepted !== null || detail.landed === true || (detail.assignment?.state === "complete" && detail.assignment.completion?.person !== undefined) ? [] : [
1382
1384
  ...proof.matrix.filter(row => row.state === "manual-review").map(row => personCheckWords(row.statement)),
1383
1385
  ...(proof.matrix.length > 0 ? [] : proof.reasons.filter(reason => manualReviewCriterionOf(reason) !== null).map(() => personCheckWords(null))),
1384
1386
  ];
@@ -1657,9 +1659,9 @@ export function resultPanelParts(detail, o) {
1657
1659
  views: [{ key: "summary", html: htmlString(joinHtml(summaryParts, "\n")) }, { key: "changes", html: htmlString(joinHtml(changeParts, "\n")) }, { key: "checks", html: htmlString(joinHtml(checkParts, "\n")) }],
1658
1660
  history: detail.history === undefined ? "" : htmlString(detail.history),
1659
1661
  learning: detail.learning === undefined ? "" : htmlString(detail.learning),
1660
- request: detail.skillTest ? null : htmlString(joinHtml(requestParts, "\n")),
1661
- canRequest: detail.canAnnotate && o.csrf !== "",
1662
- sendBack: detail.skillTest || !detail.canAnnotate || o.csrf === "" ? null
1662
+ request: detail.skillTest || detail.landed === true ? null : htmlString(joinHtml(requestParts, "\n")),
1663
+ canRequest: detail.canAnnotate && o.csrf !== "" && detail.landed !== true,
1664
+ sendBack: detail.skillTest || !detail.canAnnotate || o.csrf === "" || detail.landed === true ? null
1663
1665
  : { action: `/r/${runId}/comment`, batch: revisionBatchOf(detail.comments), source: revisionSourceOf(detail.sourceDigest), request: o.requestToken },
1664
1666
  need,
1665
1667
  requestQuiet: detail.canAnnotate && o.csrf !== "" && detail.comments.length === 0 && (detail.pastComments?.length ?? 0) === 0 && detail.revisions.length === 0,
@@ -1979,7 +1979,7 @@ export function taskBodyParts(data) {
1979
1979
  if (data.repo !== null)
1980
1980
  work.push({ label: "Project", parts: [projectName(data.repo)] });
1981
1981
  if (data.base != null)
1982
- work.push({ label: "Base", parts: [baseStandingWords(data.base)] });
1982
+ work.push({ label: "Base", parts: [baseStandingWords(data.base, data.landing?.onBranch === true)] });
1983
1983
  work.push({ label: "Agent", parts: [lastRunForAgent !== undefined ? `${lastRunForAgent.provider}${lastRunForAgent.model === null ? "" : ` · ${lastRunForAgent.model}`} on ${lastRunForAgent.runner}`
1984
1984
  : data.route?.legacy != null ? `${data.route.legacy.provider} · ${data.route.legacy.model}` : "The project's default"] });
1985
1985
  if (scope !== null)
@@ -2150,7 +2150,7 @@ export function taskBodyParts(data) {
2150
2150
  { key: "route-change", html: data.routeChange == null ? "" : htmlString(html `<div class="card"><p>${data.routeChange}</p></div>`) },
2151
2151
  { key: "fast-grown", html: data.fastGrown == null || data.csrf === "" ? "" : htmlString(html `<div class="card"><p>${data.fastGrown}</p>${postForm(`${taskHref(task.id)}/keep-grown`, btn("Approve it", { variant: "primary", type: "submit" }))}</div>`) },
2152
2152
  { key: "pull-request", html: fragmentString(pullRequestCard) },
2153
- { key: "landing", html: data.landing == null ? "" : htmlString(landingCardHtml(data.landing, data.csrf)) },
2153
+ { key: data.landing?.onBranch === true ? "landed" : "landing", html: data.landing == null ? "" : htmlString(landingCardHtml(data.landing, data.csrf)) },
2154
2154
  { key: "needs-scope", html: fragmentString(needsScopeCard) },
2155
2155
  { key: "mirror", html: fragmentString(mirrorCard) }, { key: "attempt", html: fragmentString(attemptPanel), ...(liveRunId === null ? {} : { instance: String(liveRunId) }) },
2156
2156
  ].filter(one => one.html !== ""),
@@ -1,5 +1,5 @@
1
1
  import { localOwnerRefusal } from "../local-owner.js";
2
- import { broughtInOnBranch, keptHandoffOf, landedStanding, landingOf, publishesThroughPullRequests, recognisedOnBranch } from "../local-landing.js";
2
+ import { broughtInOnBranch, keptHandoffOf, landingHistoryOf, landingOf, publishesThroughPullRequests } 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";
@@ -21,6 +21,7 @@ import { routeChangeOf } from "../route-change.js";
21
21
  import { liveAttemptOf, steerControlsFor } from "../steer-controls.js";
22
22
  import { originOf } from "../task-source.js";
23
23
  import { recentGitReads, taskBaseOf } from "../task-base.js";
24
+ import { landedNowOf } from "../merge-checklist.js";
24
25
  import { assignmentPresentationOf, historicalAssessmentReason } from '../assignment-presentation.js';
25
26
  import { html, htmlString, joinHtml } from "../html.js";
26
27
  import { assignmentStatusOf, assignmentWithEvidence } from '../assignment-ui.js';
@@ -222,6 +223,7 @@ export function createTaskViews(runtime) {
222
223
  kind: parsed.kind === "ci-repair" ? "ci-repair" : parsed.kind === "criterion-repair" ? "criterion-repair" : "annotations",
223
224
  lineage: runtime.store.revisionLineageOf(ref.externalId, runtime.clock()),
224
225
  comments: (parsed.comments ?? []).slice(0, 100).map(one => ({
226
+ id: typeof one.id === "number" && Number.isSafeInteger(one.id) ? one.id : null,
225
227
  path: one.path === null || one.path === undefined ? null : String(one.path),
226
228
  line: one.line === null || one.line === undefined ? null : Number(one.line),
227
229
  note: String(one.note ?? ""),
@@ -618,12 +620,12 @@ export function createTaskViews(runtime) {
618
620
  if (!complete && record === null)
619
621
  return null;
620
622
  const person = who.via === "cookie" && who.role === "approver";
621
- const onBranch = record === null || record.undone ? recognisedOnBranch(runtime.store, repo, rootId, complete ? assignment?.receipt?.head ?? null : null, baseGit) : null;
622
- if (onBranch !== null)
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);
623
+ const history = landingHistoryOf(runtime.store, repo, rootId, complete ? assignment?.receipt?.head ?? null : null, baseGit);
624
+ if (history !== null && !history.recorded)
625
+ return { taskId: rootId, landed: history.words, onBranch: true, canLand: false, canUndo: person && !history.reverted && broughtInOnBranch(runtime.store, repo, rootId, baseGit) };
626
+ const standing = history;
625
627
  const kept = complete && (record === null || record.undone) ? keptHandoffOf(runtime.store, repo, rootId, assignment?.receipt?.head ?? null) : null;
626
- return { taskId: rootId, landed: standing?.words ?? null, canLand: person && complete && (record === null || record.undone), canUndo: person && record !== null && !record.undone && standing?.reverted !== true,
628
+ return { taskId: rootId, landed: standing?.words ?? null, onBranch: standing?.landed === true, canLand: person && complete && (record === null || record.undone), canUndo: person && record !== null && !record.undone && standing?.reverted !== true,
627
629
  ...(kept === null ? {} : { kept }) };
628
630
  }
629
631
  function failureOf(runs, assignment, readLog = true) {
@@ -713,10 +715,12 @@ export function createTaskViews(runtime) {
713
715
  const status = view.status === null ? null : { ...view.status, action: view.status.action === null ? null : link(view.status.action),
714
716
  status: { ...view.status.status, details: view.status.status.details.map(one => ({ ...one, href: one.href === null ? null : toTab(one.href), action: one.action === null ? null : link(one.action) })) } };
715
717
  const selected = extras.result?.selected ?? null;
718
+ const builds = runs.filter(run => run.role === "builder" || run.role === "scout" || run.role === "repair").map(run => run.id).sort((a, b) => a - b);
716
719
  const attempts = [...results.entries()].sort((a, b) => b[0] - a[0]).map(([id, taskId]) => {
717
720
  const run = runs.find(one => one.id === id);
718
721
  const outcome = run.outcome === "built" ? "result" : run.outcome === "no-change" ? "no change" : run.outcome === null ? "never finished" : run.outcome;
719
- return { label: `${run.role === "scout" ? "Report" : "Build"} #${id} · ${outcome}`, href: tabHref(taskId, id, null, ""), current: selected?.build === id };
722
+ const at = builds.indexOf(id);
723
+ return { label: `${at < 0 ? `Build #${id}` : `Attempt ${at + 1}`} · ${outcome}`, href: tabHref(taskId, id, null, ""), current: selected?.build === id };
720
724
  });
721
725
  return {
722
726
  ...view,
@@ -787,7 +791,7 @@ export function createTaskViews(runtime) {
787
791
  const rootId = family?.root.id ?? taskId;
788
792
  const oneTaskView = onePage?.kind === "task" ? { ...onePage, ship: shipViewOf(shipChecksForTask(runtime.store, rootId), runtime.clock()),
789
793
  release: releaseStepsViewOf(releaseProgressFor(runtime.store, rootId), runtime.clock()),
790
- mergeReady: mergeReadyViewOf(runtime.store, taskId, data.assignment, who, presentedData.runChecks ?? null, taskHref(taskId)) } : onePage;
794
+ mergeReady: mergeReadyViewOf(runtime.store, taskId, data.assignment, who, presentedData.runChecks ?? null, taskHref(taskId), landedOf(presentedData), data.base ?? null) } : onePage;
791
795
  if (oneTaskView?.kind === "task" && machineChecked(runtime.store, taskId)) {
792
796
  const words = machineCheckWords(runtime.store, taskId, data.liveRunId ?? null, oneTaskView.release ?? null, runtime.clock());
793
797
  const card = oneTaskView.status;
@@ -1053,7 +1057,7 @@ export function createTaskViews(runtime) {
1053
1057
  const assignment = value?.receipt?.runId === run.id && value.activeTaskId === taskId ? freshAssignment(value, receipt) : null;
1054
1058
  const completeRefusal = assignment?.state !== "ready-to-check" || assignment.receipt === null ? null
1055
1059
  : personCompletionRefusal(runtime.store, assignment.receipt.taskId, run.id, who.via === "cookie" ? who.name : null, runtime.evidenceRoot, who.via === "cookie" && who.authority === "local-owner" ? { rootId: assignment.rootId } : null);
1056
- return { assignment, completeRefusal };
1060
+ return { assignment, completeRefusal, landed: assignment !== null && landedNowOf(runtime.store, assignment) !== null };
1057
1061
  })(),
1058
1062
  handoff,
1059
1063
  proof,
@@ -1174,3 +1178,6 @@ export function releaseStepsViewOf(progress, now) {
1174
1178
  startedAt: progress.startedAt,
1175
1179
  };
1176
1180
  }
1181
+ function landedOf(data) {
1182
+ return data.landing?.onBranch === true ? data.landing.landed : null;
1183
+ }
@@ -94,7 +94,7 @@ import {} from "./session.js";
94
94
  import { approveReleaseCard, releaseApprovalCard, releaseSheetHref, releaseTaskOf } from "../release-approval.js";
95
95
  import { releaseSheetPage } from "./render-release.js";
96
96
  import { approvalFactsNow, btn } from "./kit.js";
97
- import { handoffWords, land, landingWords, publishesThroughPullRequests, PULL_REQUESTS_INSTEAD, readLanding } from "../local-landing.js";
97
+ import { handoffWords, land, landedLine, landingWords, publishesThroughPullRequests, PULL_REQUESTS_INSTEAD, readLanding } from "../local-landing.js";
98
98
  import { localActNow, localOwnerRefusal, withLocalAct } from "../local-owner.js";
99
99
  import { localChecksRefusal } from "../local-checks.js";
100
100
  import { sessionYesPossible } from "./send-back-build.js";
@@ -2831,7 +2831,7 @@ export function createTasksHandlers(runtime) {
2831
2831
  return taskScreen(response, who, shown, read.message, 409);
2832
2832
  if (!("plan" in read)) {
2833
2833
  if (answersInPlace(ctx.request))
2834
- return answerActInPlace(response, "done", `Already on ${read.landed.ref.replace(/^refs\/heads\//, "")} (${read.landed.commit.slice(0, 7)}).`, 200);
2834
+ return answerActInPlace(response, "done", read.landed.reverted === true ? landedLine(read.landed) : `Already on ${read.landed.ref.replace(/^refs\/heads\//, "")} (${read.landed.commit.slice(0, 7)}).`, 200);
2835
2835
  return redirect(response, taskHref(shown));
2836
2836
  }
2837
2837
  const plan = read.plan;
@@ -0,0 +1,14 @@
1
+ const UNSAFE = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029\\p{Cf}]", "gu");
2
+ const NAMED = { "\n": "\\n", "\r": "\\r", "\t": "\\t" };
3
+ export function shownText(text) {
4
+ return text.replace(UNSAFE, char => {
5
+ const named = NAMED[char];
6
+ if (named !== undefined)
7
+ return named;
8
+ const code = char.codePointAt(0);
9
+ return code <= 0xff ? `\\x${code.toString(16).padStart(2, "0")}` : `\\u${code.toString(16).padStart(4, "0")}`;
10
+ });
11
+ }
12
+ export function hasUnsafeText(text) {
13
+ return new RegExp(UNSAFE.source, "u").test(text);
14
+ }
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { unreachableWhy } from "./unreachable.js";
2
3
  import { scanForSecrets } from "./evidence.js";
3
4
  import { learningSha } from "./project-learning.js";
4
5
  import { PROJECT_SKILLS_GUIDANCE, PROJECT_SKILLS_READ, validateSkill, } from "./project-skills.js";
@@ -310,17 +311,6 @@ export function parseGithubBundleUrl(rawUrl) {
310
311
  : `https://github.com/${owner}/${repoName}`;
311
312
  return { id, repoUrl, owner: owner, repoName: repoName, ref: ref ?? null, subpath };
312
313
  }
313
- function unreachableWhy(error) {
314
- const cause = error?.cause;
315
- const code = typeof cause?.code === "string" ? cause.code : "";
316
- if (error?.name === "TimeoutError")
317
- return "it didn't answer within 20 seconds";
318
- if (code === "ENOTFOUND" || code === "EAI_AGAIN")
319
- return "its address couldn't be looked up (this computer may be offline)";
320
- if (code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EPERM" || code === "EACCES")
321
- return "the connection was refused or blocked";
322
- return "the connection failed (this computer may be offline, or a firewall blocks it)";
323
- }
324
314
  async function githubJson(owner, repoName, path, fetcher, budget) {
325
315
  let response;
326
316
  try {
@@ -331,7 +321,7 @@ async function githubJson(owner, repoName, path, fetcher, budget) {
331
321
  });
332
322
  }
333
323
  catch (error) {
334
- throw Error(`Couldn't reach GitHub: ${unreachableWhy(error)}.`);
324
+ throw Error(`Couldn't reach GitHub: ${unreachableWhy(error, 20)}.`);
335
325
  }
336
326
  if (!response.ok) {
337
327
  throw Error(`GitHub returned ${response.status} for ${owner}/${repoName}${path.split("?")[0]}.`);
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { accessSync, closeSync, constants, existsSync, lstatSync, mkdtempSync, openSync, readSync, realpathSync, rmSync } from "node:fs";
3
3
  import { homedir, tmpdir } from "node:os";
4
4
  import { delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
5
+ import { trustRepair } from "./trust-repair.js";
5
6
  import { boundedAcl, trustedBinary, trustedFolders } from "./trusted-path.js";
6
7
  export const STATUS_TIMEOUT_MS = 800;
7
8
  export const BACKGROUND_STATUS_TIMEOUT_MS = 3_000;
@@ -341,3 +342,34 @@ export function statusProbe(options = {}) {
341
342
  }
342
343
  };
343
344
  }
345
+ export function statusBinaryDiagnosis(binary, trust) {
346
+ const found = resolveLaunch(binary, trust);
347
+ if (found.ok || found.missing)
348
+ return null;
349
+ const firstMatch = (name) => {
350
+ for (const entry of trust.path.split(delimiter)) {
351
+ if (entry === "" || !isAbsolute(entry))
352
+ continue;
353
+ try {
354
+ accessSync(join(entry, name), constants.X_OK);
355
+ return { folder: entry, file: join(entry, name) };
356
+ }
357
+ catch { }
358
+ }
359
+ return null;
360
+ };
361
+ const paths = [];
362
+ const first = firstMatch(binary);
363
+ if (first !== null) {
364
+ paths.push(first.folder, first.file);
365
+ const real = realOrNull(first.file);
366
+ if (real !== null && isScript(real)) {
367
+ paths.push(packageFolderOf(real));
368
+ const bang = shebangOf(real);
369
+ const interpreter = bang === null ? null : bang.kind === "absolute" ? { folder: dirname(bang.path), file: bang.path } : firstMatch(bang.name);
370
+ if (interpreter !== null)
371
+ paths.push(interpreter.folder, interpreter.file);
372
+ }
373
+ }
374
+ return { why: found.why, repair: trust.uid === undefined || paths.length === 0 ? null : trustRepair(paths, { owners: [trust.uid, 0], stickyAbove: true }) };
375
+ }