@andorra-labs/code 0.1.6 → 0.1.7

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 (108) hide show
  1. package/dist/src/agent-execution.js +404 -25
  2. package/dist/src/agent-mcp-catalog.d.ts +21 -0
  3. package/dist/src/agent-mcp-catalog.js +40 -0
  4. package/dist/src/agent-mcp.d.ts +19 -3
  5. package/dist/src/agent-mcp.js +18 -44
  6. package/dist/src/app-server/protocol.d.ts +25 -3
  7. package/dist/src/app-server/protocol.js +5 -1
  8. package/dist/src/app-server/workspace.d.ts +8 -1
  9. package/dist/src/app-server/workspace.js +43 -2
  10. package/dist/src/app-server.js +88 -3
  11. package/dist/src/auth/AuthManager.d.ts +33 -1
  12. package/dist/src/auth/AuthManager.js +138 -10
  13. package/dist/src/auth/callback-page.d.ts +4 -0
  14. package/dist/src/auth/callback-page.js +70 -0
  15. package/dist/src/auth/callback.d.ts +39 -0
  16. package/dist/src/auth/callback.js +146 -22
  17. package/dist/src/auth/index.d.ts +10 -6
  18. package/dist/src/auth/index.js +2 -2
  19. package/dist/src/auth/store.d.ts +142 -3
  20. package/dist/src/auth/store.js +334 -13
  21. package/dist/src/auth/types.d.ts +17 -1
  22. package/dist/src/auth-commands.d.ts +11 -2
  23. package/dist/src/auth-commands.js +14 -7
  24. package/dist/src/automation-tool.js +10 -2
  25. package/dist/src/automations.d.ts +5 -0
  26. package/dist/src/automations.js +10 -0
  27. package/dist/src/capabilities.d.ts +9 -3
  28. package/dist/src/capabilities.js +7 -3
  29. package/dist/src/cli.js +31 -4
  30. package/dist/src/codex-provider.js +12 -0
  31. package/dist/src/coding-tools.d.ts +5 -0
  32. package/dist/src/coding-tools.js +54 -48
  33. package/dist/src/commands.d.ts +5 -1
  34. package/dist/src/commands.js +7 -6
  35. package/dist/src/completion.js +46 -0
  36. package/dist/src/config.d.ts +48 -0
  37. package/dist/src/config.js +248 -10
  38. package/dist/src/context-budget.d.ts +7 -0
  39. package/dist/src/context-budget.js +18 -1
  40. package/dist/src/decision/FactContinuations.d.ts +41 -6
  41. package/dist/src/decision/FactContinuations.js +211 -64
  42. package/dist/src/decision/PreparedSteps.js +3 -1
  43. package/dist/src/decision/checks.d.ts +25 -0
  44. package/dist/src/decision/checks.js +77 -6
  45. package/dist/src/delegation-changes.d.ts +109 -0
  46. package/dist/src/delegation-changes.js +431 -0
  47. package/dist/src/graph-server.d.ts +1 -0
  48. package/dist/src/graph-server.js +15 -3
  49. package/dist/src/graph-sync.d.ts +15 -0
  50. package/dist/src/graph-sync.js +50 -1
  51. package/dist/src/graph-tool.d.ts +52 -0
  52. package/dist/src/graph-tool.js +136 -0
  53. package/dist/src/graph-ui/app.js +212 -43
  54. package/dist/src/graph-ui/controls.js +6 -0
  55. package/dist/src/graph-ui/drafts.js +39 -0
  56. package/dist/src/graph-ui/embed.js +1 -1
  57. package/dist/src/graph-ui/index.html +2 -2
  58. package/dist/src/graph-ui/studio.css +7 -5
  59. package/dist/src/graph-ui/style.css +46 -12
  60. package/dist/src/graphs.d.ts +15 -2
  61. package/dist/src/graphs.js +42 -13
  62. package/dist/src/hardened-runtime.d.ts +4 -4
  63. package/dist/src/hardened-runtime.js +109 -9
  64. package/dist/src/powershell-pool.d.ts +9 -0
  65. package/dist/src/powershell-pool.js +16 -0
  66. package/dist/src/provider-keys.d.ts +48 -0
  67. package/dist/src/provider-keys.js +121 -0
  68. package/dist/src/pull-requests.d.ts +14 -5
  69. package/dist/src/pull-requests.js +28 -10
  70. package/dist/src/qa/runtime/ProcessManager.d.ts +6 -0
  71. package/dist/src/qa/runtime/ProcessManager.js +16 -0
  72. package/dist/src/react-runtime.js +30 -2
  73. package/dist/src/read-image.d.ts +30 -0
  74. package/dist/src/read-image.js +97 -0
  75. package/dist/src/secret-redaction.d.ts +13 -0
  76. package/dist/src/secret-redaction.js +71 -0
  77. package/dist/src/session-summary.d.ts +10 -4
  78. package/dist/src/session-summary.js +14 -7
  79. package/dist/src/sessions.js +4 -1
  80. package/dist/src/skills/bundled/graph-manager/SKILL.md +14 -11
  81. package/dist/src/skills/bundled/provenance.json +1 -1
  82. package/dist/src/telemetry/schema.d.ts +1 -1
  83. package/dist/src/telemetry/schema.js +1 -1
  84. package/dist/src/terminal-ui.d.ts +9 -0
  85. package/dist/src/terminal-ui.js +14 -0
  86. package/dist/src/tool-dependencies.js +4 -0
  87. package/dist/src/tools.d.ts +9 -0
  88. package/dist/src/tools.js +116 -11
  89. package/dist/src/transcript.js +5 -0
  90. package/dist/src/types.d.ts +13 -0
  91. package/dist/src/web-search.d.ts +59 -0
  92. package/dist/src/web-search.js +216 -0
  93. package/docs/agents/README.md +2 -2
  94. package/docs/agents/mcp-server.md +15 -2
  95. package/docs/concepts/README.md +1 -1
  96. package/docs/concepts/security.md +2 -2
  97. package/docs/getting-started/accounts.md +15 -4
  98. package/docs/getting-started/configure-providers.md +1 -1
  99. package/docs/guides/README.md +1 -0
  100. package/docs/guides/desktop-app.md +1 -1
  101. package/docs/guides/graph-builder.md +1 -1
  102. package/docs/guides/web-search.md +47 -0
  103. package/docs/reference/cli.md +4 -3
  104. package/docs/reference/config.md +3 -3
  105. package/docs/reference/slash-commands.md +2 -1
  106. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +295 -0
  107. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +291 -0
  108. package/package.json +1 -1
@@ -1,39 +1,72 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { checkRunners, commandLine, isCheckCall, isReplaySafeCheck, isVerificationCheck } from './checks.js';
2
+ import { commandLine, declaredCheckKind, isCheckCall, isReplaySafeCheck, isVerificationCheck, replayableCheck, stripOutputFilter } from './checks.js';
3
3
  export const PREPARE_FINISH = 'prepare_finish';
4
- export const FACT_CONTINUATION_GUIDANCE = 'Minimize model turns: batch independent reads and related file writes. Do not spend a turn only announcing a plan. When prepare_finish is available, implementation is finished and the verification is test, build, lint or typecheck commands, call prepare_finish LAST in the final edit batch (its description says how); for any other verification, finish normally. Do not add discretionary QA after the requested verification is sufficient. User instructions, workspace requirements and graph completion contracts still apply.';
4
+ export const FACT_CONTINUATION_GUIDANCE = 'Minimize model turns: batch independent reads and related file writes. Do not spend a turn only announcing a plan. When prepare_finish is available, finish through it: put it LAST in the batch that makes your final edits, with the commands that verify the work and your final summary. The runtime runs them and completes the task without another model call, so do not run those commands yourself first, do not call complete_agent afterwards and do not add discretionary QA: one passing run of the checks the project already has is sufficient, so do not write throwaway scripts to prove the same thing again. If the verification is not a command, verify first, then call prepare_finish alone with checks []. After you edit files the runtime runs your latest check again by itself, so do not spend a turn rerunning it or marking todos done. Keep the final summary short, whatever other formatting guidance says: one or two sentences with the outcome, then at most five short bullets on what changed and how it was verified, about 100 words in all, with no headings, no code blocks, no restated diff and no remarks on things the task did not ask about (such as a pull request that was never requested), unless the user asked for that content. User instructions, workspace requirements and graph completion contracts still apply.';
5
+ /** What the model writes once as its final answer; a retry reuses it instead of sending it again. */
6
+ export const FINISH_SUMMARY_DESCRIPTION = 'Final answer shown to the user, as Markdown with \\n line breaks: one or two sentences with the outcome, then at most five short bullets on what changed and how it was verified. About 100 words, no headings. Omit it on a retry to reuse the one already saved.';
5
7
  /** The tool description, naming the shell the model actually has. */
6
8
  export function prepareFinishDescription(shell = 'PowerShell') {
7
- return `After finishing implementation, call LAST in your final edit batch with the checks to run and your complete final result. The runtime runs the checks through normal approvals, completes the verification todos you name and submits the result without another coding-model call; a failed or unclear check returns control to you. Each check is one standalone test, build, lint or typecheck command with the timeout you would give it yourself, e.g. {"name": "${shell}", "arguments": {"command": "npm run build", "timeout": 300000}}: one entry per command, no ;, &&, ||, pipes, redirects or conditionals. Do not add optional QA. completion.tests must be [] (the runtime records what ran).`;
9
+ return `Finish the task. Call LAST in the batch that makes your final edits. checks: the commands that verify the work (tests, build, lint, typecheck), one command per entry, written exactly as you would run them with ${shell}, e.g. ["npm run build", "npm test"]; chain steps with && if needed, but no pipes, ";" or "||" (output is already bounded). summary: your final answer. The runtime runs the checks through normal approvals and, when all pass, closes the open todos and submits the summary without another coding-model call. If a check fails you receive its output: fix the problem and call prepare_finish again with the checks only, and the saved summary is reused unless you send a new one. After verifying some other way, call it alone with checks [] to submit.`;
8
10
  }
11
+ const DEFAULT_CHECK_TIMEOUT_MS = 300_000;
9
12
  /**
10
- * Repairs shape slips that would otherwise cost a whole coding-model turn, without changing what
11
- * runs: a note beside a check (`justification`, `description`), a check whose arguments were written
12
- * beside its name, a bare command given as the tool name, and evidence lines in completion.tests,
13
- * which the runtime fills in itself. Everything else is left for validation to reject.
13
+ * Brings what a model sends into the one shape `stage` validates, repairing slips that would
14
+ * otherwise cost a whole coding-model turn without changing what is verified: a check written as a
15
+ * command line (the advertised form), as `{command}`, with its arguments beside its name or with a
16
+ * note beside it; an output filter that would hide the exit status; the final answer written flat
17
+ * (`summary`) or as a JSON string; and evidence lines in `tests`, which the runtime fills in itself.
18
+ * Everything else is left for validation to reject.
14
19
  */
15
20
  export function prepareFinishArguments(args, tools) {
16
21
  if (!object(args))
17
22
  return args;
18
- const next = { ...args };
19
- if (Array.isArray(args.checks))
20
- next.checks = args.checks.map((raw) => {
21
- if (!object(raw) || typeof raw.name !== 'string')
22
- return raw;
23
- const { justification: _justification, description: _description, ...item } = raw;
24
- let { name, arguments: given, ...fields } = item;
25
- if (given === undefined) {
26
- given = fields;
27
- fields = {};
28
- }
29
- if (!tools.has(name) && tools.shell && object(given) && !Object.keys(given).length && /\s/.test(name.trim())) {
30
- given = { command: name.trim() };
31
- name = tools.shell;
32
- }
33
- return { name, arguments: given, ...fields };
34
- });
35
- if (object(args.completion) && Array.isArray(args.completion.tests) && args.completion.tests.length)
36
- next.completion = { ...args.completion, tests: [] };
23
+ const { checks: rawChecks, completion: nested, summary, outcome, output, artifacts, tests: _tests, timeoutMs, ...rest } = args;
24
+ const next = { ...rest };
25
+ const timeout = typeof timeoutMs === 'number' && Number.isInteger(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_CHECK_TIMEOUT_MS;
26
+ const shellCall = (command) => !tools.shell || !command.trim() ? command : tools.shell === 'shell'
27
+ ? { name: 'shell', arguments: { command: stripOutputFilter(command), timeout_ms: Math.min(timeout, 120_000) } }
28
+ : { name: tools.shell, arguments: { command: stripOutputFilter(command), timeout: Math.min(timeout, 600_000) } };
29
+ const list = typeof rawChecks === 'string' ? [rawChecks] : rawChecks ?? [];
30
+ next.checks = !Array.isArray(list) ? list : list.map((raw) => {
31
+ if (typeof raw === 'string')
32
+ return shellCall(raw);
33
+ if (!object(raw))
34
+ return raw;
35
+ if (typeof raw.name !== 'string')
36
+ return typeof raw.command === 'string' && Object.keys(raw).every(k => ['command', 'timeout', 'description', 'justification'].includes(k)) ? shellCall(raw.command) : raw;
37
+ const { justification: _justification, description: _description, ...item } = raw;
38
+ let { name, arguments: given, ...fields } = item;
39
+ if (given === undefined) {
40
+ given = fields;
41
+ fields = {};
42
+ }
43
+ if (!tools.has(name) && tools.shell && object(given) && !Object.keys(given).length && /\s/.test(name.trim())) {
44
+ given = { command: name.trim() };
45
+ name = tools.shell;
46
+ }
47
+ // A label where the tool name belongs, with the command beside it: the shell is what was meant.
48
+ if (!tools.has(name) && tools.shell && object(given) && typeof given.command === 'string')
49
+ name = tools.shell;
50
+ if (name === tools.shell && object(given) && typeof given.command === 'string')
51
+ given = { ...given, command: stripOutputFilter(given.command) };
52
+ return { name, arguments: given, ...fields };
53
+ });
54
+ let completion = nested;
55
+ if (typeof completion === 'string') {
56
+ const text = completion;
57
+ try {
58
+ const parsed = JSON.parse(text);
59
+ completion = object(parsed) ? parsed : { summary: text };
60
+ }
61
+ catch {
62
+ completion = { summary: text };
63
+ }
64
+ }
65
+ const flat = Object.fromEntries(Object.entries({ summary, outcome, output, artifacts }).filter(([, value]) => value !== undefined));
66
+ if (object(completion) || Object.keys(flat).length)
67
+ next.completion = { ...(object(completion) ? completion : {}), ...flat, tests: [] };
68
+ else if (completion !== undefined)
69
+ next.completion = completion;
37
70
  return next;
38
71
  }
39
72
  const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
@@ -47,6 +80,8 @@ const metadata = new Set([PREPARE_FINISH, 'update_todos', 'update_widget']);
47
80
  const probability = (value, bar) => value === undefined || !Number.isFinite(value) || value < 0 || value > 1 ? undefined : value >= bar - 1e-9 ? true : value <= 1 - bar + 1e-9 ? false : undefined;
48
81
  const concrete = (o) => ({ name: o.call.name, arguments: structuredClone(o.args) });
49
82
  const description = (call) => commandLine(call.arguments) ?? call.name;
83
+ /** What a failure looks like in the output of a command no runner pattern recognizes, even when it exits 0. */
84
+ const OPAQUE_FAILURE_TEXT = /Traceback \(most recent call last\)|\b(?:AssertionError|assertion failed|Segmentation fault|core dumped|panicked at|Unhandled(?:Promise)?Rejection|not ok)\b|(?:^|\n)\s*(?:error|fatal)\b[:\s]|\b[1-9]\d* (?:errors?|failures?)\b/i;
50
85
  const FAILURE_TEXT = /(?:^|\n)\s*(?:Exit code: [1-9]\d*|[ℹ#]\s*fail\s+[1-9]\d*|Test Suites:\s*[1-9]\d* failed)|\b[1-9]\d* failed\b|\b(?:FAIL|FAILED)\b|error TS\d+/m;
51
86
  /** A JSON report's own verdict; null when the output is not a report that decides one. */
52
87
  function structuredVerdict(text) {
@@ -145,6 +180,10 @@ export function taskConstraints(task, nodeInstruction = '') {
145
180
  kinds.add('typecheck');
146
181
  return { noTests, noChecks, commands: noChecks ? [] : commands.filter(c => !noTests || checkKind(c) !== 'test'), kinds };
147
182
  }
183
+ /** A follow-up check is worth a turn only while it is cheap: at most this often, and only a quick one. */
184
+ const FOLLOW_UP_LIMIT = 8;
185
+ const FOLLOW_UP_MAX_MS = 60_000;
186
+ const VERIFICATION_TODO = /^(?:run|rerun|re-run|verify|test|check|lint|build|typecheck|smoke)(?:[ :\-]|$)/i;
148
187
  function checkKind(line) {
149
188
  if (/\b(?:tsc|typecheck|type-check|mypy)\b/.test(line))
150
189
  return 'typecheck';
@@ -175,6 +214,15 @@ export class FactContinuations {
175
214
  constraints;
176
215
  syntheticCount = 0;
177
216
  finishHint = false;
217
+ /** The model's own most recent check, in the form the runtime may run again after an edit. */
218
+ lastCheck;
219
+ followUps = 0;
220
+ followUpPassed;
221
+ nextNudge;
222
+ /** The final answer the model already wrote; a later plan may omit it instead of sending it again. */
223
+ draft;
224
+ /** Commands the model named as its verification that no runner pattern recognizes, by check key. */
225
+ declared = new Map();
178
226
  constructor(options) {
179
227
  this.options = options;
180
228
  this.task = options.task;
@@ -182,6 +230,16 @@ export class FactContinuations {
182
230
  }
183
231
  get finishing() { return this.finishHint; }
184
232
  get proposed() { return !!this.plan || !!this.staged; }
233
+ /**
234
+ * Where the model stands when nothing was run for it: it just edited files and has not checked
235
+ * them, or its own check just failed. In both places the cheapest next move is one plan that
236
+ * carries the checks and the answer, and a reminder there is what makes the model take it.
237
+ */
238
+ get nudge() { return this.nextNudge; }
239
+ /** The check the runtime ran after the latest edits, when it passed on the current workspace. */
240
+ get followUp() { return this.followUpPassed; }
241
+ /** The model already wrote its final answer in an earlier plan. */
242
+ get hasDraft() { return !!this.draft; }
185
243
  async emit(action, data = {}) {
186
244
  await this.options.emit('efficiency.facts.action', { action, ...data });
187
245
  }
@@ -197,6 +255,10 @@ export class FactContinuations {
197
255
  this.taskNeedsChecksSource = 'deterministic';
198
256
  this.checks.clear();
199
257
  this.revision++;
258
+ this.draft = undefined;
259
+ this.declared.clear();
260
+ this.lastCheck = undefined;
261
+ this.followUpPassed = undefined;
200
262
  if (update)
201
263
  this.task += `\nLatest task update:\n${update}`;
202
264
  this.constraints = taskConstraints(this.task, [this.options.nodeInstruction, this.options.workspaceInstructions].filter(Boolean).join('\n'));
@@ -209,7 +271,7 @@ export class FactContinuations {
209
271
  this.pendingAutomatic = undefined;
210
272
  this.syntheticCount = 0;
211
273
  }
212
- stage(args, lastInBatch) {
274
+ stage(args, lastInBatch, alone = false) {
213
275
  this.plan = this.staged = undefined;
214
276
  this.queued = undefined;
215
277
  if (this.taskUpdated)
@@ -222,26 +284,46 @@ export class FactContinuations {
222
284
  if (!lastInBatch)
223
285
  throw new Error('prepare_finish must be the final call in the batch.');
224
286
  if (Object.keys(args).some(k => !['checks', 'completion', 'verificationTodoIds'].includes(k)) || !Array.isArray(args.checks)
225
- || args.checks.length > 8 || !object(args.completion) || Buffer.byteLength(JSON.stringify(args)) > 16_384)
287
+ || args.checks.length > 8 || (args.completion !== undefined && !object(args.completion)) || Buffer.byteLength(JSON.stringify(args)) > 16_384)
226
288
  throw new Error('Invalid finish plan (maximum 8 checks and 16 KiB).');
227
- const value = args.completion;
228
- if (Object.keys(value).some(k => !['summary', 'tests', 'outcome', 'output', 'artifacts'].includes(k)))
289
+ const given = args.completion;
290
+ if (given && Object.keys(given).some(k => !['summary', 'tests', 'outcome', 'output', 'artifacts'].includes(k)))
229
291
  throw new Error('Unknown completion field.');
292
+ // A retry sends only what changed: the saved answer supplies the rest.
293
+ const value = { ...this.draft, ...given, tests: given?.tests ?? [] };
230
294
  if (typeof value.summary !== 'string' || !value.summary.trim() || !Array.isArray(value.tests) || value.tests.length) {
231
295
  throw new Error('Provide the complete proposed summary and tests: []; observed check evidence is filled in by the runtime.');
232
296
  }
297
+ this.draft = structuredClone(value);
298
+ try {
299
+ this.stagePlan(args, value, alone);
300
+ }
301
+ catch (error) {
302
+ // The answer is already written and kept, so the retry costs a few tokens, not the answer again.
303
+ throw new Error(`${error instanceof Error ? error.message : String(error)} Your summary is saved: call prepare_finish again with only the corrected checks.`);
304
+ }
305
+ }
306
+ stagePlan(args, value, alone) {
307
+ const declared = new Map();
233
308
  const checks = args.checks.map((input) => {
234
309
  if (!object(input) || Object.keys(input).some(k => !['name', 'arguments'].includes(k)) || typeof input.name !== 'string' || !object(input.arguments))
235
310
  throw new Error('A check needs a name and exact arguments.');
236
311
  const tool = this.options.catalog(input.name);
237
312
  if (!tool)
238
313
  throw new Error(`Unknown or unavailable tool "${input.name.slice(0, 80)}": a check is the shell tool's name with its arguments, e.g. {"name": "<shell>", "arguments": {"command": "npm test"}}.`);
314
+ const call = { name: input.name, arguments: structuredClone(input.arguments) };
239
315
  if (!isVerificationCheck(input.name, tool.family, input.arguments)) {
240
- // Say which check and what to do instead: a retried plan costs a whole coding-model turn.
241
- const shown = (commandLine(input.arguments) ?? input.name).replace(/\s+/g, ' ').slice(0, 160);
242
- throw new Error(`"${shown}" is not a standalone test, build, lint or typecheck command, so it cannot be prepared. Give each such command its own check, without ;, &&, ||, pipes, redirects or conditionals. If your verification is anything else, such as running your own script, do not call prepare_finish; finish normally.`);
316
+ // A command the model names as its verification can still be prepared when its exit status
317
+ // is faithful; what an exit 0 then proves depends on whether a known runner is in the line.
318
+ const line = commandLine(input.arguments);
319
+ const kind = tool.family === 'shell' && line && !('action' in input.arguments) ? declaredCheckKind(line) : undefined;
320
+ if (!kind) {
321
+ // Say which check and what to do instead: a retried plan costs a whole coding-model turn.
322
+ const shown = (line ?? input.name).replace(/\s+/g, ' ').slice(0, 160);
323
+ throw new Error(`"${shown}" is not a standalone command whose exit status reports the result, so it cannot be prepared. Give each command its own check and chain steps with && only: no ;, ||, pipes, redirects or substitutions, and no mode that changes files (--fix, --write, -u); run such a command yourself before preparing.`);
324
+ }
325
+ declared.set(checkKey(call), kind);
243
326
  }
244
- const call = { name: input.name, arguments: structuredClone(input.arguments) };
245
327
  if (this.constraints.noChecks || this.constraints.noTests && (checkKind(description(call)) === 'test' || /^qa\.(?:fast|test|deep)$/.test(call.name))) {
246
328
  throw new Error('This check conflicts with the user\'s explicit verification opt-out.');
247
329
  }
@@ -253,46 +335,53 @@ export class FactContinuations {
253
335
  if (!Array.isArray(ids) || ids.length > 32 || ids.some(id => typeof id !== 'string') || new Set(ids).size !== ids.length)
254
336
  throw new Error('Invalid verification todo ids.');
255
337
  const todos = this.options.todos();
256
- if (ids.some(id => { const todo = todos.find(t => t.id === id); return todo && !/^(?:run|rerun|re-run|verify|test|check|lint|build|typecheck|smoke)[ :\-]/i.test(todo.text); }))
257
- throw new Error('Only explicitly verification-only todos may be completed automatically.');
258
338
  if (ids.some(id => !todos.some(todo => todo.id === id)))
259
339
  throw new Error('Verification todo does not exist.');
260
- if (todos.some(todo => todo.status !== 'completed' && !ids.includes(todo.id)))
261
- throw new Error('Finish implementation and other non-verification todos before preparing completion.');
262
- if (ids.length && !checks.length)
263
- throw new Error('Verification todos require declared checks.');
340
+ // Calling prepare_finish says the work is done, so the item in progress closes with it. An item
341
+ // that was never started is unfinished work unless it only names the verification itself.
342
+ if (todos.some(todo => todo.status === 'pending' && !VERIFICATION_TODO.test(todo.text)))
343
+ throw new Error('A todo was never started. Finish it, or update the todo list, before preparing completion.');
344
+ const closing = todos.filter(todo => todo.status !== 'completed').map(todo => todo.id);
345
+ const direct = alone && !checks.length;
264
346
  const alreadyPassed = [...this.checks.values()].filter(e => e.passed && e.pure && e.revision === this.revision).map(e => e.call);
265
- if (!this.coversRequirements([...alreadyPassed, ...checks]))
347
+ if (!direct && !this.coversRequirements([...alreadyPassed, ...checks]))
266
348
  throw new Error('The plan omits verification explicitly required by the task or node.');
267
- this.staged = { checks, completion: structuredClone(value), verificationTodoIds: ids, permission: this.options.permission(), revision: this.revision };
349
+ for (const [key, kind] of declared)
350
+ this.declared.set(key, kind);
351
+ this.staged = { checks, completion: structuredClone(value), verificationTodoIds: closing, permission: this.options.permission(), revision: this.revision, direct };
268
352
  }
269
353
  coversRequirements(calls) {
270
354
  const commands = new Set(calls.map(description));
271
355
  const kinds = new Set(calls.map(c => checkKind(description(c))));
272
356
  return this.constraints.commands.every(command => commands.has(command)) && [...this.constraints.kinds].every(kind => kinds.has(kind));
273
357
  }
358
+ /**
359
+ * The current workspace is verified: a check passed on it, and no earlier failure is left
360
+ * unanswered. A failed test, lint or typecheck is answered by a later pass of the same kind on the
361
+ * current workspace; a failed build or other command by any later pass, since a check that ran
362
+ * built what it needed. A command whose result is unknown proves nothing either way: the model
363
+ * saw its output and named the checks that decide.
364
+ */
274
365
  verified() {
275
366
  const rows = [...this.checks.values()];
276
- const current = (e) => e.passed === true && e.pure && e.revision === this.revision;
277
- // A compound command (`npm run build; node --test`) can never prove a pass itself. It stops
278
- // blocking once every runner it contains, including one nested in a conditional, has passed
279
- // later, on its own, on the current workspace. Anything else in the line keeps it blocking (checkRunners).
280
- const superseded = (e) => {
281
- const runners = checkRunners(commandLine(e.call.arguments) ?? '');
282
- return !!runners?.length && runners.every(command => rows.some(r => current(r) && r.seq > e.seq
283
- && r.call.name === e.call.name && description(r.call) === command));
284
- };
285
- return rows.length > 0 && rows.every(e => current(e) || !e.pure && superseded(e)) && this.coversRequirements(rows.map(e => e.call));
367
+ const passing = rows.filter(e => e.passed === true && e.pure && e.revision === this.revision);
368
+ const kind = (e) => checkKind(description(e.call));
369
+ const answered = (e) => passing.some(p => p.seq > e.seq && (kind(p) === kind(e) || ['check', 'build'].includes(kind(e))));
370
+ return passing.length > 0 && rows.every(e => e.passed !== false || answered(e)) && this.coversRequirements(passing.map(e => e.call));
286
371
  }
287
372
  async ask(input, signal) {
373
+ return (await this.consult(input, signal)).value;
374
+ }
375
+ /** `answered` is false when the service gave no answer at all, as opposed to an unsure one. */
376
+ async consult(input, signal) {
288
377
  signal.throwIfAborted();
289
378
  if (this.options.remoteFactsEnabled === false)
290
- return undefined;
379
+ return { answered: false, value: undefined };
291
380
  const start = performance.now();
292
381
  const value = await this.options.fact(input, signal);
293
382
  signal.throwIfAborted();
294
383
  await this.options.emit('efficiency.facts.answered', { waitMs: Math.round(performance.now() - start), asked: [input.id], answered: value === undefined ? 0 : 1 });
295
- return probability(value, input.id === 'checks_passed' ? .95 : .9);
384
+ return { answered: value !== undefined, value: probability(value, input.id === 'checks_passed' ? .95 : .9) };
296
385
  }
297
386
  async needsChecks(signal) {
298
387
  if (this.constraints.noChecks) {
@@ -316,42 +405,72 @@ export class FactContinuations {
316
405
  async observe(batch, signal) {
317
406
  signal.throwIfAborted();
318
407
  this.finishHint = false;
408
+ this.followUpPassed = undefined;
409
+ this.nextNudge = undefined;
319
410
  const automatic = this.pendingAutomatic;
320
411
  this.pendingAutomatic = undefined;
321
412
  const failed = batch.filter(o => o.isError || !o.executionSucceeded);
322
413
  if (failed.some(o => o.readOnly || metadata.has(o.call.name)))
323
414
  this.revision++;
324
415
  const work = batch.filter(o => !metadata.has(o.call.name));
325
- let wrote = false;
416
+ let wrote = false, modelChecked = false;
326
417
  for (const observation of work) {
327
418
  const call = concrete(observation);
328
- const check = isCheckCall(call.name, observation.family, call.arguments);
329
- const pure = isVerificationCheck(call.name, observation.family, call.arguments);
419
+ const key = checkKey(call);
420
+ const declared = this.declared.get(key);
421
+ const check = !!declared || isCheckCall(call.name, observation.family, call.arguments);
422
+ const pure = !!declared || isVerificationCheck(call.name, observation.family, call.arguments);
330
423
  if (!observation.readOnly && !pure) {
331
424
  this.revision++; // Failed writes/commands may have partially mutated the workspace too.
332
425
  wrote ||= observation.family === 'filesystem-write' && !observation.isError && observation.executionSucceeded;
333
426
  }
334
427
  if (!check)
335
428
  continue;
429
+ if (!automatic) {
430
+ modelChecked = true;
431
+ // What a later edit is followed by: the model's own latest check, never one the runtime chose.
432
+ const line = observation.family === 'shell' && typeof call.arguments.command === 'string' ? call.arguments.command : undefined;
433
+ const replay = line ? replayableCheck(line) : undefined;
434
+ if (replay)
435
+ this.lastCheck = { call: { name: call.name, arguments: { ...call.arguments, command: replay } }, durationMs: observation.durationMs };
436
+ }
336
437
  let passed = pure ? localCheckResult(observation) : undefined;
438
+ // Exit 0 of a command nothing recognizes does not settle it: its output has to say it passed.
439
+ // Only a clean exit qualifies at all; a report that leaves its own verdict open (every check
440
+ // skipped) or names a failure never reaches this point as a pass.
441
+ const cleanExit = declared === 'opaque' && passed === true;
442
+ if (cleanExit)
443
+ passed = undefined;
337
444
  let source = 'deterministic';
338
445
  // Only a result that can enable a continuation merits an external interpretation. A failed
339
446
  // execution is known false; a compound command never proves the final workspace verified.
340
447
  if (pure && passed === undefined && !observation.truncated && !failed.length && (this.plan || this.staged || this.options.todos().length > 0)) {
341
- passed = await this.ask({ id: 'checks_passed', state: { tool_results: [{ tool: call.name, command: description(call), succeeded: observation.executionSucceeded && !observation.isError, output: observation.output }] } }, signal);
448
+ const answer = await this.consult({ id: 'checks_passed', state: { tool_results: [{ tool: call.name, command: description(call), succeeded: observation.executionSucceeded && !observation.isError, output: observation.output }] } }, signal);
449
+ passed = answer.value;
342
450
  if (passed !== undefined)
343
451
  source = 'jev';
452
+ // No answer at all (the service is off, unreachable or does not speak this protocol) is not
453
+ // an unsure answer. What remains is what the model itself would go by: the command it named
454
+ // as its check exited 0 and nothing in its output reads as a failure.
455
+ else if (!answer.answered && cleanExit && !OPAQUE_FAILURE_TEXT.test(observation.output))
456
+ passed = true;
344
457
  }
345
- const key = checkKey(call);
346
458
  this.checks.delete(key); // Re-inserted last, so the map's order is the order checks ran.
347
- this.checks.set(key, { call, passed, pure, source, revision: this.revision, seq: ++this.checkSeq, evidence: `${description(call)}: ${passed === true ? 'passed' : passed === false ? 'failed' : 'unconfirmed'}` });
459
+ this.checks.set(key, { call, passed, pure, source, revision: this.revision, seq: ++this.checkSeq, evidence: `${description(call).split('\n')[0].slice(0, 200)}: ${passed === true ? 'passed' : passed === false ? 'failed' : 'unconfirmed'}` });
460
+ }
461
+ if (automatic?.kind === 'recheck' && automatic.tool && !failed.length) {
462
+ const evidence = this.checks.get(checkKey(automatic.tool));
463
+ if (evidence?.passed === true && evidence.revision === this.revision)
464
+ this.followUpPassed = description(automatic.tool).split('\n')[0].slice(0, 160);
348
465
  }
349
466
  if (failed.length)
350
467
  this.plan = this.staged = undefined;
351
468
  if (this.staged) {
352
469
  const declaration = batch.findIndex(o => o.call.name === PREPARE_FINISH);
470
+ // The answer was written before these results existed, so the batch may only write files and
471
+ // run checks: a read or another command in it is something the model has not seen yet.
353
472
  if (declaration < 0 || declaration !== batch.length - 1 || failed.length
354
- || work.some(o => o.family !== 'filesystem-write' && !isVerificationCheck(o.call.name, o.family, o.args)))
473
+ || work.some(o => o.family !== 'filesystem-write' && !this.declared.has(checkKey(concrete(o))) && !isVerificationCheck(o.call.name, o.family, o.args)))
355
474
  this.staged = undefined;
356
475
  else {
357
476
  this.staged.revision = this.revision;
@@ -384,9 +503,10 @@ export class FactContinuations {
384
503
  this.queue('check', next, this.verificationSource());
385
504
  return;
386
505
  }
387
- const noChecks = !this.checks.size && await this.needsChecks(signal) === false
506
+ const direct = this.plan.direct;
507
+ const noChecks = !direct && !this.checks.size && await this.needsChecks(signal) === false
388
508
  && (!this.options.workspaceInstructions?.trim() || this.constraints.noChecks);
389
- if (this.verified() || noChecks) {
509
+ if (direct || this.verified() || noChecks) {
390
510
  const ids = this.plan.verificationTodoIds;
391
511
  if (todos.some(t => ids.includes(t.id) && t.status !== 'completed')) {
392
512
  this.queue('todos', { name: 'update_todos', arguments: { todos: todos.map(t => ids.includes(t.id) ? { ...t, status: 'completed' } : t) } }, noChecks ? this.taskNeedsChecksSource : this.verificationSource());
@@ -413,6 +533,33 @@ export class FactContinuations {
413
533
  }
414
534
  }
415
535
  }
536
+ const unstarted = this.options.todos().some(t => t.status === 'pending' && !VERIFICATION_TODO.test(t.text));
537
+ if (!this.taskUpdated && !this.plan && !this.staged && !unstarted && !this.constraints.noChecks) {
538
+ if (!automatic && [...this.checks.values()].some(e => e.passed === false && e.revision === this.revision && e.seq > this.checkSeq - work.length) && modelChecked)
539
+ this.nextNudge = 'after_failed_check';
540
+ else if (!failed.length && wrote && !modelChecked)
541
+ this.nextNudge = 'after_write';
542
+ }
543
+ // After edits the model's next move is most often its own check again. Running it here costs
544
+ // the check; having the model ask for it costs a whole turn. Only a check that was quick, in a
545
+ // batch where the model did not already check, never twice for one state of the workspace, and
546
+ // not while a todo was never started: the edit is then one step of several, and on real runs the
547
+ // model went on writing twice as often as it checked.
548
+ const follow = this.lastCheck;
549
+ if (follow && !this.options.todos().some(t => t.status === 'pending' && !VERIFICATION_TODO.test(t.text)) && !this.taskUpdated && !failed.length && wrote && !modelChecked && !this.plan && !this.staged
550
+ && this.syntheticCount < 3 && this.followUps < FOLLOW_UP_LIMIT && (follow.durationMs ?? 0) <= FOLLOW_UP_MAX_MS
551
+ && !this.constraints.noChecks && !(this.constraints.noTests && checkKind(description(follow.call)) === 'test')) {
552
+ const key = `${this.revision}:${checkKey(follow.call)}`;
553
+ if (!this.rechecked.has(key)) {
554
+ this.rechecked.add(key);
555
+ this.followUps++;
556
+ if (!isVerificationCheck(follow.call.name, this.options.catalog(follow.call.name)?.family, follow.call.arguments))
557
+ this.declared.set(checkKey(follow.call), 'chain');
558
+ this.nextNudge = undefined;
559
+ this.queue('recheck', follow.call);
560
+ return;
561
+ }
562
+ }
416
563
  const open = this.options.todos().filter(t => t.status !== 'completed');
417
564
  const implementationOpen = open.some(t => !/^(?:run|rerun|re-run|verify|test|check|lint|build|typecheck|smoke)(?:[ :\-]|$)/i.test(t.text));
418
565
  if (!this.taskUpdated && !failed.length && wrote && !implementationOpen && this.syntheticCount < 3) {
@@ -468,5 +615,5 @@ export class FactContinuations {
468
615
  this.pendingAutomatic = next;
469
616
  return next;
470
617
  }
471
- completionAccepted() { this.plan = this.staged = undefined; this.finishHint = false; }
618
+ completionAccepted() { this.plan = this.staged = undefined; this.finishHint = false; this.draft = undefined; }
472
619
  }
@@ -5,7 +5,9 @@ export const PREPARE_STEPS = 'prepare_steps';
5
5
  export const PREPARED_TRIGGERS = ['success', 'failure', 'always'];
6
6
  const kinds = ['investigate', 'retry', 'change_strategy', 'verify', 'complete'];
7
7
  const triggerKinds = new Set(['investigate', 'verify']);
8
- const forbidden = new Set([PREPARE_STEPS, 'complete_agent', 'update_todos', 'ask_user', 'spawn_subagent']);
8
+ // Landing or dropping a delegated change is a decision taken after reviewing it, so neither can be
9
+ // prepared ahead and run before the review.
10
+ const forbidden = new Set([PREPARE_STEPS, 'complete_agent', 'update_todos', 'ask_user', 'spawn_subagent', 'accept_change', 'discard_change']);
9
11
  const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
10
12
  export function boundedDecisionText(text, bytes) {
11
13
  const value = redactSecrets(text).text;
@@ -11,3 +11,28 @@ export declare function isCheckCall(name: string, family: string | undefined, ar
11
11
  export declare function isReplaySafeCheck(name: string, family: string | undefined, args: unknown): boolean;
12
12
  /** A check that can establish a pass on the final workspace, not merely contain a check. */
13
13
  export declare function isVerificationCheck(name: string, family: string | undefined, args: unknown): boolean;
14
+ /**
15
+ * A declared check without the output filter that would hide its exit status: `pytest -q 2>&1 |
16
+ * tail -20` verifies exactly what `pytest -q 2>&1` verifies, and only the second reports it.
17
+ */
18
+ export declare function stripOutputFilter(line: string): string;
19
+ /**
20
+ * What a command the model named as its own verification can prove by exiting 0.
21
+ *
22
+ * `chain`: every step runs only if the one before succeeded (`&&`) and at least one step is a
23
+ * recognized check runner, so exit 0 means that runner passed (`cd build && ctest`,
24
+ * `PYTHONPATH=. python -m pytest -q`, `gcc -o t t.c && ./t`). `opaque`: the exit status is
25
+ * faithful but nothing in the line is a known runner (`./run_tests.sh`), so exit 0 alone does not
26
+ * settle it and the output has to be interpreted. One command fed by a here-document (`python3 -
27
+ * <<'PY' ... PY`) is opaque too: the script is its input, not more shell. Undefined when the line
28
+ * can hide a failure: a pipe, `;`, `||`, a background job, a substitution or a redirect.
29
+ */
30
+ export declare function declaredCheckKind(line: string): 'chain' | 'opaque' | undefined;
31
+ /**
32
+ * The form of a check the model ran in which the runtime may run it again after an edit, or
33
+ * undefined when it may not. Every step is a known runner or a `cd`, chained with `&&` only, so
34
+ * running it twice does what running it once did and its exit status reports the result. An output
35
+ * filter and the no-op `cd "$(pwd)" &&` are dropped; a mutating mode (`--fix`, `-u`) or anything
36
+ * else in the line (setup, cleanup, a script) leaves the next run to the model.
37
+ */
38
+ export declare function replayableCheck(line: string): string | undefined;
@@ -1,6 +1,13 @@
1
1
  /** Recognition is deliberately broader than replay/verification authority. */
2
- const RUNNER = String.raw `(?:node\s+--test\b|(?:python3?\s+-m\s+)?(?:pytest|unittest|mypy)\b|(?:npx\s+)?(?:jest|vitest|tsc|eslint|mocha|ava|ruff|ctest)\b|npx\s+playwright\s+test\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|build|lint|typecheck|type-check|check|verify)\b|cargo\s+(?:test|build|check|clippy)\b|go\s+(?:test|build|vet)\b|dotnet\s+(?:test|build)\b|mvn\s+(?:test|verify)\b|\.?[\\/]?gradlew?(?:\.bat)?\s+(?:test|build|check)\b|make\s+(?:test|check)\b)`;
3
- const AT_START = new RegExp(`^${RUNNER}`, 'i');
2
+ /** A directory in front of an executable: `.venv/bin/`, `/tmp/qa-venv/bin/`, `./node_modules/.bin/`. */
3
+ const BIN = String.raw `(?:[\w.~@+\-\\/:]*[\\/])?`;
4
+ /** Wrappers that run the same check under a deadline or inside a project environment (`timeout 120 uv run --with pytest ...`). */
5
+ const LAUNCH = String.raw `(?:time\s+)?(?:timeout\s+(?:-[\w-]+\s+)*\d+[smh]?\s+)?(?:(?:uv|poetry|pipenv|pdm|hatch|rye)\s+run\s+(?:(?:--with(?:-[\w-]+)?|--python|-p|--extra|--group|--project|--directory)[=\s]\S+\s+|--(?:frozen|locked|no-sync|no-project|isolated|quiet|offline|all-extras|no-dev|dev)\s+|-q\s+)*(?:--\s+)?)?`;
6
+ const PYTHON = String.raw `(?:${BIN}python[\d.]*\s+(?:-[BEIOsSuX]+\s+)*-m\s+)?`;
7
+ const RUNNER = String.raw `${LAUNCH}(?:${BIN}node\s+--test\b|${PYTHON}${BIN}(?:pytest|py\.test|unittest|mypy|compileall|py_compile)\b|(?:(?:npx|bunx)\s+(?:--no-install\s+|--yes\s+|-y\s+)?|pnpm\s+exec\s+)?${BIN}(?:jest|vitest|tsc|eslint|mocha|ava|ruff|ctest)\b|npx\s+playwright\s+test\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|build|lint|typecheck|type-check|check|verify)\b|cargo\s+(?:\+[\w.-]+\s+)?(?:test|build|check|clippy)\b|go\s+(?:test|build|vet)\b|dotnet\s+(?:test|build)\b|mvn\s+(?:test|verify)\b|\.?[\\/]?gradlew?(?:\.bat)?\s+(?:test|build|check)\b|make\s+(?:test|check)\b|make(?:\s+-C\s+\S+|\s+-j\s*\d*)*\s*$|cmake\s+--build\b|${BIN}(?:gcc|g\+\+|cc|c\+\+|clang|clang\+\+)\s)`;
8
+ const RUNNER_AT_START = new RegExp(`^${RUNNER}`, 'i');
9
+ /** A known check runner at the start of a command. `pytest --version` or `tsc --help` starts like one and checks nothing. */
10
+ const runner = (part) => RUNNER_AT_START.test(part) && !/(?:^|\s)(?:--version|-V|--help)(?:\s|$)/.test(part);
4
11
  /**
5
12
  * Glue that can sit between runners without changing what they verify: messages, exit, block ends,
6
13
  * output filters, and a test only as the condition of if/elif/while/until. On its own a test is an
@@ -34,7 +41,7 @@ export function checkRunners(line) {
34
41
  const negated = /^!\s*/.test(part);
35
42
  part = part.replace(/^!\s*/, '');
36
43
  // `! npm run build` expects a failure: a standalone pass of the same command cannot stand in for it.
37
- if (AT_START.test(part)) {
44
+ if (runner(part)) {
38
45
  if (negated)
39
46
  return undefined;
40
47
  runners.push(part);
@@ -64,7 +71,7 @@ export function isCheckCall(name, family, args) {
64
71
  if (family !== 'shell' || !object(args) || 'action' in args)
65
72
  return false;
66
73
  const line = commandLine(args);
67
- return !!line && line.split(/&&|\|\||[;|\n\r]/).some(part => AT_START.test(part.trim()));
74
+ return !!line && line.split(/&&|\|\||[;|\n\r]/).some(part => runner(part.trim()));
68
75
  }
69
76
  /** Closed, argument-aware output filters. In particular, sort -o and sort /O write files. */
70
77
  function outputFilter(stage) {
@@ -82,13 +89,13 @@ export function isReplaySafeCheck(name, family, args) {
82
89
  if (/(?:^|\s)(?:--(?:fix|write|update(?:-snapshots?)?|eval|require|import)(?:[=\s]|$)|-u(?:\s|$))/.test(line))
83
90
  return false;
84
91
  if (typeof args.program === 'string' && args.command === undefined && args.cmd === undefined) {
85
- return Array.isArray(args.args) && args.args.every(a => typeof a === 'string') && AT_START.test(line.trim());
92
+ return Array.isArray(args.args) && args.args.every(a => typeof a === 'string') && runner(line.trim());
86
93
  }
87
94
  const folded = line.replace(/2>&1/g, ' ').trim();
88
95
  if (/[;\n\r`<>$&(){}]|\|\|/.test(folded))
89
96
  return false;
90
97
  const [check, ...stages] = folded.split('|').map(s => s.trim());
91
- return AT_START.test(check) && stages.every(outputFilter);
98
+ return runner(check) && stages.every(outputFilter);
92
99
  }
93
100
  /** A check that can establish a pass on the final workspace, not merely contain a check. */
94
101
  export function isVerificationCheck(name, family, args) {
@@ -102,3 +109,67 @@ export function isVerificationCheck(name, family, args) {
102
109
  // automatic completion; let the model inspect it or use a plain/native check instead.
103
110
  return !commandLine(args)?.replace(/2>&1/g, '').includes('|');
104
111
  }
112
+ const ENV_PREFIX = /^(?:env\s+)?(?:[A-Za-z_]\w*=(?:"[^"]*"|'[^']*'|[^\s"'`$;&|<>()]*)\s+)+/;
113
+ /** Output-only suffixes the shell tool makes redundant (its output is already tail-bounded). */
114
+ const OUTPUT_FILTER = /\s*(?:2>&1\s*)?\|\s*(?:tail|head)(?:\s+-n\s*\d+|\s+-\d+)?\s*$|\s*(?:2>&1\s*)?\|\s*cat\s*$/i;
115
+ /**
116
+ * A declared check without the output filter that would hide its exit status: `pytest -q 2>&1 |
117
+ * tail -20` verifies exactly what `pytest -q 2>&1` verifies, and only the second reports it.
118
+ */
119
+ export function stripOutputFilter(line) {
120
+ let next = line.trim();
121
+ for (let i = 0; i < 2 && OUTPUT_FILTER.test(next); i++)
122
+ next = next.replace(OUTPUT_FILTER, '').trim();
123
+ return next;
124
+ }
125
+ /**
126
+ * What a command the model named as its own verification can prove by exiting 0.
127
+ *
128
+ * `chain`: every step runs only if the one before succeeded (`&&`) and at least one step is a
129
+ * recognized check runner, so exit 0 means that runner passed (`cd build && ctest`,
130
+ * `PYTHONPATH=. python -m pytest -q`, `gcc -o t t.c && ./t`). `opaque`: the exit status is
131
+ * faithful but nothing in the line is a known runner (`./run_tests.sh`), so exit 0 alone does not
132
+ * settle it and the output has to be interpreted. One command fed by a here-document (`python3 -
133
+ * <<'PY' ... PY`) is opaque too: the script is its input, not more shell. Undefined when the line
134
+ * can hide a failure: a pipe, `;`, `||`, a background job, a substitution or a redirect.
135
+ */
136
+ export function declaredCheckKind(line) {
137
+ // A mode that rewrites files (`eslint --fix`, `jest -u`) is an edit, not a check: admitting it
138
+ // would leave the passes recorded before it standing for a workspace it then changed.
139
+ if (MUTATING_FLAG.test(line))
140
+ return undefined;
141
+ const heredoc = /^([^\n]*?)<<-?\s*(['"]?)([A-Za-z_]\w*)\2([^\n]*)\n[\s\S]*\n\3\s*$/.exec(line.trim());
142
+ if (heredoc)
143
+ return declaredCheckKind(`${heredoc[1]} ${heredoc[4]}`) ? 'opaque' : undefined;
144
+ // Quoted text is an argument, not shell syntax: `python3 -c "import m; m.run()"` is one command.
145
+ // A double-quoted string that can expand (`$`, a backtick) is left in place and judged as written.
146
+ const folded = line.replace(/'[^']*'/g, "''").replace(/"(?:[^"\\$`]|\\.)*"/g, '""')
147
+ .replace(/\d?>&\d|(?:\d|&)?>\s*\/dev\/null/g, ' ').trim();
148
+ if (!folded || /[;\n\r`<>|]|\$\(/.test(folded) || /&/.test(folded.replace(/&&/g, ' ')))
149
+ return undefined;
150
+ const parts = folded.split('&&').map(part => part.trim().replace(ENV_PREFIX, ''));
151
+ if (parts.some(part => !part))
152
+ return undefined;
153
+ return parts.some(part => runner(part)) ? 'chain' : 'opaque';
154
+ }
155
+ const MUTATING_FLAG = /(?:^|\s)(?:--(?:fix|write|update(?:-snapshots?)?|eval|require|import)(?:[=\s]|$)|-u(?:\s|$))/;
156
+ /**
157
+ * The form of a check the model ran in which the runtime may run it again after an edit, or
158
+ * undefined when it may not. Every step is a known runner or a `cd`, chained with `&&` only, so
159
+ * running it twice does what running it once did and its exit status reports the result. An output
160
+ * filter and the no-op `cd "$(pwd)" &&` are dropped; a mutating mode (`--fix`, `-u`) or anything
161
+ * else in the line (setup, cleanup, a script) leaves the next run to the model.
162
+ */
163
+ export function replayableCheck(line) {
164
+ const next = stripOutputFilter(line.trim().replace(/^cd\s+"?\$\(pwd\)"?\s*&&\s*/, ''));
165
+ if (MUTATING_FLAG.test(next) || next.includes('<<'))
166
+ return undefined;
167
+ const folded = next.replace(/'[^']*'/g, "''").replace(/"(?:[^"\\$`]|\\.)*"/g, '""')
168
+ .replace(/\d?>&\d|(?:\d|&)?>\s*\/dev\/null/g, ' ').trim();
169
+ if (!folded || /[;\n\r`<>|]|\$\(/.test(folded) || /&/.test(folded.replace(/&&/g, ' ')))
170
+ return undefined;
171
+ const parts = folded.split('&&').map(part => part.trim().replace(ENV_PREFIX, ''));
172
+ if (parts.some(part => !part) || !parts.some(part => runner(part)))
173
+ return undefined;
174
+ return parts.every(part => runner(part) || /^cd\s+\S+$/.test(part)) ? next : undefined;
175
+ }