@carrieros/cli 0.2.0 → 0.4.0

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 (124) hide show
  1. package/README.md +170 -64
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/btw.js +78 -0
  4. package/dist/commands/changes.js +167 -0
  5. package/dist/commands/chat.js +81 -15
  6. package/dist/commands/context.js +200 -0
  7. package/dist/commands/doctor.js +63 -3
  8. package/dist/commands/files.js +84 -23
  9. package/dist/commands/help.js +1 -0
  10. package/dist/commands/history.js +88 -23
  11. package/dist/commands/login.js +31 -7
  12. package/dist/commands/logout.js +1 -0
  13. package/dist/commands/memory.js +162 -0
  14. package/dist/commands/mode-model.js +39 -3
  15. package/dist/commands/modes.js +4 -1
  16. package/dist/commands/permissions.js +77 -0
  17. package/dist/commands/project.js +106 -0
  18. package/dist/commands/repo.js +146 -0
  19. package/dist/commands/repos.js +61 -0
  20. package/dist/commands/review.js +92 -0
  21. package/dist/commands/scope.js +9 -6
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +224 -65
  24. package/dist/commands/settings.js +94 -0
  25. package/dist/commands/update.js +229 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +213 -17
  28. package/dist/commands/whoami.js +12 -9
  29. package/dist/ide/editor-context.js +275 -0
  30. package/dist/ide/ide-session.js +355 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +26 -1
  33. package/dist/services/api.js +315 -15
  34. package/dist/services/auth-origin.js +20 -0
  35. package/dist/services/chat-stream.js +168 -0
  36. package/dist/services/checkpoints.js +278 -0
  37. package/dist/services/client-tools.js +352 -0
  38. package/dist/services/code-intel.js +243 -0
  39. package/dist/services/code-symbols.js +94 -0
  40. package/dist/services/coding-workflow.js +554 -0
  41. package/dist/services/command-coordinator.js +273 -0
  42. package/dist/services/command-policy.js +434 -0
  43. package/dist/services/config.js +311 -24
  44. package/dist/services/container-runner.js +254 -0
  45. package/dist/services/container-supervisor.js +38 -0
  46. package/dist/services/context.js +296 -23
  47. package/dist/services/device-auth.js +72 -35
  48. package/dist/services/diff.js +196 -0
  49. package/dist/services/env-policy.js +108 -0
  50. package/dist/services/execution-platform.js +30 -0
  51. package/dist/services/file-detect.js +104 -0
  52. package/dist/services/file-resolver.js +199 -0
  53. package/dist/services/file-upload.js +126 -0
  54. package/dist/services/folder-key.js +22 -0
  55. package/dist/services/git-tools.js +429 -0
  56. package/dist/services/glob-match.js +164 -0
  57. package/dist/services/helper-bin.js +85 -0
  58. package/dist/services/ignore-rules.js +189 -0
  59. package/dist/services/instruction-resolver.js +54 -0
  60. package/dist/services/job-helper.js +328 -0
  61. package/dist/services/local-files.js +639 -0
  62. package/dist/services/local-tools.js +937 -0
  63. package/dist/services/login-flow.js +55 -17
  64. package/dist/services/meta.js +3 -1
  65. package/dist/services/mutation-coordinator.js +327 -0
  66. package/dist/services/mutation-groups.js +309 -0
  67. package/dist/services/mutation-recovery.js +159 -0
  68. package/dist/services/mutations.js +679 -0
  69. package/dist/services/open-url.js +68 -0
  70. package/dist/services/output.js +5 -2
  71. package/dist/services/packaged-update.js +403 -0
  72. package/dist/services/packaged.js +39 -0
  73. package/dist/services/permission-mode.js +60 -0
  74. package/dist/services/process-runner.js +412 -0
  75. package/dist/services/project-context.js +298 -0
  76. package/dist/services/redaction.js +201 -0
  77. package/dist/services/result-reconciliation.js +49 -0
  78. package/dist/services/secure-store.js +217 -0
  79. package/dist/services/session-resolver.js +113 -0
  80. package/dist/services/sia.js +51 -0
  81. package/dist/services/supported-runtime.js +59 -0
  82. package/dist/services/task-context.js +212 -0
  83. package/dist/services/task-snapshot.js +38 -0
  84. package/dist/services/tool-result-outbox.js +195 -0
  85. package/dist/services/update.js +311 -0
  86. package/dist/services/workspace-registry.js +310 -0
  87. package/dist/services/workspace.js +580 -0
  88. package/dist/shell/shell-chat.js +1297 -59
  89. package/dist/shell/shell-commands.js +243 -12
  90. package/dist/shell/shell-prompt.js +94 -11
  91. package/dist/shell/shell-renderer.js +8 -20
  92. package/dist/shell/shell-router.js +19 -3
  93. package/dist/shell/shell.js +252 -22
  94. package/dist/shell/task-context-view.js +40 -0
  95. package/dist/types/index.js +3 -1
  96. package/dist/ui/agent-cards.js +111 -0
  97. package/dist/ui/agent-presentation.js +131 -0
  98. package/dist/ui/approval.js +111 -0
  99. package/dist/ui/banner.js +31 -48
  100. package/dist/ui/btw-overlay.js +230 -0
  101. package/dist/ui/change-review.js +334 -0
  102. package/dist/ui/chat-renderer.js +207 -14
  103. package/dist/ui/colors.js +12 -8
  104. package/dist/ui/command-details.js +11 -0
  105. package/dist/ui/command-filter.js +26 -5
  106. package/dist/ui/command-palette.js +44 -14
  107. package/dist/ui/command-registry.js +92 -10
  108. package/dist/ui/command-review.js +187 -0
  109. package/dist/ui/composer-layout.js +48 -1
  110. package/dist/ui/conversation.js +450 -0
  111. package/dist/ui/interrupt.js +35 -0
  112. package/dist/ui/live.js +4 -2
  113. package/dist/ui/markdown.js +63 -9
  114. package/dist/ui/message.js +14 -31
  115. package/dist/ui/screen-prompt.js +181 -0
  116. package/dist/ui/screen.js +19 -11
  117. package/dist/ui/select.js +191 -29
  118. package/dist/ui/sia-qa.js +213 -0
  119. package/dist/ui/task-context-card.js +99 -0
  120. package/dist/ui/text-prompt.js +74 -0
  121. package/dist/ui/trust.js +88 -0
  122. package/dist/ui/ui.js +27 -1
  123. package/package.json +18 -4
  124. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The function / class a line belongs to — deterministic, no parser, no index.
3
+ *
4
+ * Used to label search matches ("line 58, in Cart.subtotal") so an agent can go
5
+ * from a matching line to the symbol to its callers (by searching the name)
6
+ * without reading whole files first. Heuristic by design: it recognises common
7
+ * declaration shapes in JS/TS, Python, Go, Rust, Java/C#/Kotlin and Ruby, and
8
+ * uses indentation to find the enclosing one. When unsure it returns nothing
9
+ * rather than a guess.
10
+ */
11
+ /** How far above a line to look for its declaration. */
12
+ const MAX_SCAN = 400;
13
+ const KEYWORDS = new Set(["if", "for", "while", "switch", "catch", "return", "function", "else", "do", "try", "with", "new", "typeof", "await"]);
14
+ /** Declaration patterns; the first capture group that is a name wins. */
15
+ const PATTERNS = [
16
+ // class / interface / struct / enum / trait / impl / module (any language)
17
+ { re: /^\s*(?:export\s+)?(?:default\s+)?(?:public\s+|private\s+|protected\s+|internal\s+)?(?:abstract\s+|final\s+|sealed\s+|static\s+|data\s+|pub(?:\([^)]*\))?\s+)*(?:class|interface|struct|enum|trait|impl|module|object)\s+(?:<[^>]*>\s*)?([A-Za-z_$][\w$]*)/, container: true },
18
+ // JS/TS function declarations
19
+ { re: /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/ },
20
+ // JS/TS const x = (...) => / function
21
+ { re: /^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s+)?(?:function\b|\([^)]*\)\s*(?::[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)/ },
22
+ // Python / Ruby
23
+ { re: /^\s*(?:async\s+)?def\s+(?:self\.)?([A-Za-z_]\w*[!?]?)/ },
24
+ // Go (functions and methods)
25
+ { re: /^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)/ },
26
+ // Rust
27
+ { re: /^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z_]\w*)/ },
28
+ // Class members: JS/TS methods, Java/C#/Kotlin methods — `name(args) {` with optional modifiers/return type
29
+ { re: /^\s*(?:(?:public|private|protected|internal|static|async|override|virtual|final|readonly|get|set|fun)\s+)*(?:[\w<>\[\],.?]+\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\([^;]*\)\s*(?::\s*[^{=;]+)?(?:throws\s+[\w., ]+)?\s*\{\s*$/ }
30
+ ];
31
+ const indentOf = (line) => {
32
+ const m = /^[ \t]*/.exec(line);
33
+ return m ? m[0].replace(/\t/g, " ").length : 0;
34
+ };
35
+ export function declaration(line) {
36
+ for (const { re, container } of PATTERNS) {
37
+ const m = re.exec(line);
38
+ const name = m?.[1];
39
+ if (name && !KEYWORDS.has(name))
40
+ return { name, container: !!container };
41
+ }
42
+ return null;
43
+ }
44
+ /**
45
+ * The innermost declaration enclosing `lines[index]` (0-based), with its
46
+ * containing class/struct when there is one: "Cart.subtotal", "subtotal",
47
+ * "Cart". The line itself counts when it is the declaration.
48
+ */
49
+ export function enclosingSymbol(lines, index) {
50
+ if (index < 0 || index >= lines.length)
51
+ return undefined;
52
+ const own = declaration(lines[index]);
53
+ let inner = own ? { ...own, indent: indentOf(lines[index]) } : undefined;
54
+ let limit = inner ? inner.indent : indentOf(lines[index]);
55
+ // A top-level line that is not itself a declaration belongs to no symbol: the
56
+ // declarations above it are its siblings, not its parents.
57
+ if (!inner && limit === 0)
58
+ return undefined;
59
+ let outer;
60
+ for (let i = index - 1, scanned = 0; i >= 0 && scanned < MAX_SCAN; i -= 1, scanned += 1) {
61
+ const line = lines[i];
62
+ if (!line.trim())
63
+ continue;
64
+ const indent = indentOf(line);
65
+ if (indent >= limit)
66
+ continue;
67
+ const d = declaration(line);
68
+ if (!d) {
69
+ // A shallower non-declaration line (e.g. the closing brace of an earlier
70
+ // block at top level) means the enclosing scope is above it; keep looking,
71
+ // but only for something still shallower.
72
+ if (indent < limit)
73
+ limit = indent;
74
+ continue;
75
+ }
76
+ if (!inner) {
77
+ inner = { ...d, indent };
78
+ limit = indent;
79
+ if (indent === 0)
80
+ break;
81
+ continue;
82
+ }
83
+ if (d.container && !inner.container) {
84
+ outer = d.name;
85
+ break;
86
+ }
87
+ limit = indent;
88
+ if (indent === 0)
89
+ break;
90
+ }
91
+ if (!inner)
92
+ return undefined;
93
+ return outer ? `${outer}.${inner.name}` : inner.name;
94
+ }
@@ -0,0 +1,554 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { resolveInside } from "./local-files.js";
5
+ import { activeRepository, resolveOperableRepository } from "./workspace-registry.js";
6
+ import { evaluateCommand } from "./command-policy.js";
7
+ import { instructionPathsForDirectories } from "./instruction-resolver.js";
8
+ import { outline } from "./code-intel.js";
9
+ export const MAX_CORRECTIONS = 2;
10
+ const NEXT = {
11
+ TASK_RECEIVED: ["INSPECTING"], INSPECTING: ["PLANNING"], PLANNING: ["CAPABILITY_CHECK"], CAPABILITY_CHECK: ["READING"],
12
+ READING: ["PROPOSING", "CORRECTIVE_PROPOSAL"], PROPOSING: ["AWAITING_APPROVAL"],
13
+ AWAITING_APPROVAL: ["APPLYING"], APPLYING: ["PROPOSING", "TESTING"],
14
+ TESTING: ["ANALYZING_FAILURE", "COMPLETED"], ANALYZING_FAILURE: ["PLANNING"],
15
+ CORRECTIVE_PROPOSAL: ["CORRECTIVE_APPROVAL"], CORRECTIVE_APPROVAL: ["REAPPLYING"],
16
+ REAPPLYING: ["CORRECTIVE_PROPOSAL", "RETESTING"], RETESTING: ["ANALYZING_FAILURE", "COMPLETED"]
17
+ };
18
+ const TERMINAL = new Set(["COMPLETED", "FAILED", "CANCELLED", "UNRESOLVED"]);
19
+ export class WorkflowError extends Error {
20
+ code = "CODING_WORKFLOW_BLOCKED";
21
+ }
22
+ function fail(message) { throw new WorkflowError(message); }
23
+ const sha = (value) => createHash("sha256").update(value).digest("hex");
24
+ const text = (v, max = 2000, field = "explanation") => typeof v === "string" && v.trim() && v.length <= max ? v.trim() : fail(`A bounded nonempty ${field} is required (maximum ${max} characters).`);
25
+ const commandKey = (v) => JSON.stringify([v.program, v.args ?? [], v.cwd ?? "."]);
26
+ /** Deterministic gate only. Plans/analysis come from the backend; never chooses a tool. */
27
+ export class CodingWorkflow {
28
+ capability;
29
+ show;
30
+ options;
31
+ currentState = "TASK_RECEIVED";
32
+ get state() { return this.currentState; }
33
+ corrections = 0;
34
+ plan;
35
+ repo;
36
+ inspected = new Set();
37
+ reads = new Map();
38
+ evidence = new Set();
39
+ pending = new Set();
40
+ changed = new Set();
41
+ plannedApplied = new Set();
42
+ tests = new Map();
43
+ running = new Map();
44
+ analyzed = false;
45
+ active = false;
46
+ controlPending;
47
+ finishPending;
48
+ finishAcknowledged = false;
49
+ taskId = `task_${randomUUID()}`;
50
+ execution;
51
+ planOperationId;
52
+ planScope;
53
+ operations = new Set();
54
+ planOperations = new Set();
55
+ commandOperations = new Set();
56
+ candidate;
57
+ correctiveReads = new Set();
58
+ observedPaths = new Map();
59
+ /** Files inspected this turn in any form (ranged read, outline) — what "ruled out" may cite. */
60
+ inspectedFiles = new Set();
61
+ constructor(capability, show, options = {}) {
62
+ this.capability = capability;
63
+ this.show = show;
64
+ this.options = options;
65
+ }
66
+ transition(next) {
67
+ if (TERMINAL.has(this.state) || (!["FAILED", "CANCELLED", "UNRESOLVED"].includes(next) && !NEXT[this.state]?.includes(next)))
68
+ fail(`Invalid coding transition: ${this.state} → ${next}.`);
69
+ this.currentState = next;
70
+ }
71
+ checkBoundary() {
72
+ if (this.options.signal?.aborted) {
73
+ if (!TERMINAL.has(this.state))
74
+ this.transition("CANCELLED");
75
+ fail("The coding task was cancelled; no approval or execution may continue.");
76
+ }
77
+ if (this.plan && this.options.recoveryScope?.() !== this.planScope) {
78
+ if (!TERMINAL.has(this.state))
79
+ this.transition("UNRESOLVED");
80
+ fail("The coding task identity changed. Start a fresh task and approval under the current identity.");
81
+ }
82
+ }
83
+ approvalContext() {
84
+ return { task_id: this.taskId, plan_operation_id: this.planOperationId, recovery_scope: this.planScope,
85
+ plan_fingerprint: this.plan ? sha(JSON.stringify({ plan: this.plan, operation: this.planOperationId, scope: this.planScope })) : undefined };
86
+ }
87
+ requireNewOperation(id) {
88
+ if (this.operations.has(id) || this.planOperations.has(id) || this.commandOperations.has(id))
89
+ fail("A new operation identity is required; previous review identities cannot authorize new work.");
90
+ }
91
+ repository(selector) { return selector ? resolveOperableRepository(text(selector, 64)) : activeRepository(); }
92
+ key(root, rel) { return `${root}\0${rel}`; }
93
+ observeRead(call, payload) {
94
+ if (!payload.ok || TERMINAL.has(this.state))
95
+ return;
96
+ if (this.state === "TASK_RECEIVED")
97
+ this.transition("INSPECTING");
98
+ const args = call.arguments ?? {};
99
+ if (args.repository === "*")
100
+ return;
101
+ const repo = this.repository(args.repository);
102
+ if (["list_files", "git_status"].includes(call.name))
103
+ this.inspected.add(repo.id);
104
+ if (this.evidence.size < 200)
105
+ this.evidence.add(call.tool_call_id);
106
+ const result = payload.result;
107
+ if ((call.name === "read_file" || call.name === "code_outline") && typeof result?.path === "string" && this.inspectedFiles.size < 200) {
108
+ this.inspectedFiles.add(this.key(repo.root, path.normalize(result.path)));
109
+ }
110
+ if (call.name !== "read_file" || !result)
111
+ return;
112
+ // An "unchanged" answer is issued only when this turn's read cache proves the
113
+ // same complete bytes were already delivered since the last invalidation and
114
+ // still match disk — so it stands for the complete read it refers to. Ranged
115
+ // and truncated reads never do.
116
+ const unchanged = result.unchanged === true && typeof result.sha256 === "string";
117
+ if (!unchanged && (result.truncated !== false || typeof result.content !== "string"))
118
+ return;
119
+ const abs = resolveInside(text(args.path, 1024), repo.root);
120
+ const bytes = fs.readFileSync(abs);
121
+ if (sha(bytes) !== (unchanged ? result.sha256 : sha(result.content)))
122
+ return; // no snippets, truncation or stale reads
123
+ if (this.reads.size >= 100)
124
+ fail("Read-evidence limit reached; split this task.");
125
+ const rel = path.relative(repo.root, abs);
126
+ this.reads.set(this.key(repo.root, rel), sha(bytes));
127
+ if (this.observedPaths.size < 100)
128
+ this.observedPaths.set(call.tool_call_id, { repoId: repo.id, rel });
129
+ }
130
+ requiredReads(repo = this.candidate?.repo ?? this.repo, files = this.candidate?.files ?? this.plan?.files, tests = this.candidate?.tests ?? this.plan?.tests, contextFiles = this.candidate?.contextFiles ?? this.plan?.contextFiles) {
131
+ if (!files || !repo)
132
+ return [];
133
+ const required = new Set();
134
+ for (const file of contextFiles ?? [])
135
+ required.add(file.path);
136
+ for (const file of files) {
137
+ if (fs.existsSync(path.join(repo.root, file.path)))
138
+ required.add(file.path);
139
+ }
140
+ const configDirs = new Set(["."]);
141
+ for (const test of tests ?? []) {
142
+ let dir = String(test.cwd ?? ".");
143
+ for (;;) {
144
+ configDirs.add(dir);
145
+ if (dir === ".")
146
+ break;
147
+ dir = path.dirname(dir);
148
+ }
149
+ }
150
+ const instructionDirectories = [
151
+ ...files.map((file) => path.dirname(file.path)),
152
+ ...[...(tests ?? [])].map((test) => String(test.cwd ?? "."))
153
+ ];
154
+ for (const rel of instructionPathsForDirectories(repo.root, instructionDirectories))
155
+ required.add(rel);
156
+ for (const dir of configDirs) {
157
+ for (const name of ["package.json", "pyproject.toml", "pytest.ini", "go.mod", "Cargo.toml"]) {
158
+ const rel = path.join(dir, name);
159
+ if (fs.existsSync(path.join(repo.root, rel)))
160
+ required.add(rel);
161
+ }
162
+ }
163
+ for (const rel of this.correctiveReads)
164
+ required.add(rel);
165
+ return [...required];
166
+ }
167
+ verifyReads(repo = this.candidate?.repo ?? this.repo, files = this.candidate?.files ?? this.plan?.files, tests = this.candidate?.tests ?? this.plan?.tests, contextFiles = this.candidate?.contextFiles ?? this.plan?.contextFiles) {
168
+ if (!repo)
169
+ fail("Propose a plan first.");
170
+ for (const rel of this.requiredReads(repo, files, tests, contextFiles)) {
171
+ const abs = resolveInside(rel, repo.root);
172
+ if (this.reads.get(this.key(repo.root, path.relative(repo.root, abs))) !== sha(fs.readFileSync(abs))) {
173
+ fail(`Read the complete current file before proposing changes: ${rel}`);
174
+ }
175
+ }
176
+ }
177
+ continuation() {
178
+ if (this.options.signal?.aborted && !TERMINAL.has(this.state))
179
+ this.transition("CANCELLED");
180
+ if (TERMINAL.has(this.state) && this.state !== "COMPLETED")
181
+ return { required: false, state: this.state, next_actions: [], missing_reads: [] };
182
+ const repo = this.candidate?.repo ?? this.repo;
183
+ const needsReads = ["TASK_RECEIVED", "INSPECTING", "ANALYZING_FAILURE", "READING"].includes(this.state);
184
+ const missing = repo && needsReads ? this.requiredReads(repo, this.candidate?.files ?? this.plan?.files, this.candidate?.tests ?? this.plan?.tests, this.candidate?.contextFiles ?? this.plan?.contextFiles).filter(rel => {
185
+ try {
186
+ const abs = resolveInside(rel, repo.root);
187
+ return this.reads.get(this.key(repo.root, path.relative(repo.root, abs))) !== sha(fs.readFileSync(abs));
188
+ }
189
+ catch {
190
+ return true;
191
+ }
192
+ }) : [];
193
+ const actions = [];
194
+ if (this.state === "COMPLETED")
195
+ actions.push({ tool: "coding_workflow", arguments: { action: "finish" } });
196
+ else if (this.state === "ANALYZING_FAILURE" && !this.analyzed)
197
+ actions.push({ tool: "coding_workflow", arguments: { action: "analyze", test_ids: [...this.tests.values()].filter(t => !t.passed).map(t => t.id) } });
198
+ else if (["TASK_RECEIVED", "INSPECTING", "ANALYZING_FAILURE", "READING"].includes(this.state)) {
199
+ if (!repo || !this.inspected.has(repo.id))
200
+ actions.push({ tool: "list_files", arguments: repo ? { repository: repo.name } : {} });
201
+ for (const rel of missing)
202
+ actions.push({ tool: "read_file", arguments: { path: rel, ...(repo ? { repository: repo.name } : {}) } });
203
+ if (!actions.length) {
204
+ if (this.state === "READING")
205
+ for (const file of this.plan?.files ?? [])
206
+ actions.push({ tool: "edit_file", arguments: { repository: repo?.name, path: file.path } });
207
+ else
208
+ actions.push({ tool: "coding_workflow", arguments: { action: "plan" } });
209
+ }
210
+ }
211
+ else if (["APPLYING", "REAPPLYING", "TESTING", "RETESTING"].includes(this.state) && !this.pending.size && !this.running.size) {
212
+ if (this.plan?.files.every(f => this.plannedApplied.has(f.path))) {
213
+ const test = this.plan.tests.find(t => !this.tests.has(commandKey(t)));
214
+ if (test) {
215
+ const { purpose: _, ...command } = structuredClone(test);
216
+ actions.push({ tool: "run_command", arguments: { ...command, repository: this.repo?.name } });
217
+ }
218
+ }
219
+ else
220
+ for (const file of this.plan?.files.filter(f => !this.plannedApplied.has(f.path)) ?? [])
221
+ actions.push({ tool: "edit_file", arguments: { repository: this.repo?.name, path: file.path } });
222
+ }
223
+ const mutationApprovalComplete = Boolean(this.plan?.files.every(f => this.plannedApplied.has(f.path))) && !this.pending.size;
224
+ const approvalRequired = actions.some(a => a.tool === "edit_file" || a.tool === "run_command");
225
+ return { required: actions.length > 0, state: this.state, validation: this.validation(), missing_reads: missing, next_actions: actions, approval_required: approvalRequired,
226
+ mutation_approval_complete: mutationApprovalComplete,
227
+ ...(this.state === "ANALYZING_FAILURE" ? { guidance: this.analyzed ? "Read every listed missing_reads file completely in one parallel read batch where supported, then submit the corrective plan and invoke its mutation tool for a new diff review. Analysis invalidated earlier reads; do not ask for approval in prose." : "Invoke coding_workflow analyze now using the actual failed command evidence. Complete analysis before rereading files: analysis invalidates earlier reads. Then batch all listed fresh reads before corrective planning. Only the mutation tool opens correction approval; prose cannot request or grant it." } : {}),
228
+ ...(!this.plan && ["TASK_RECEIVED", "INSPECTING"].includes(this.state) ? { guidance: "If the user asked for a code change: complete the listed reads, submit coding_workflow plan, then invoke the mutation tool — its diff review collects the user's approval, so never ask for permission or show a proposed diff in prose. If the user only asked a question, answer it directly without planning." } : {}),
229
+ ...(mutationApprovalComplete && actions.some(a => a.tool === "run_command") ? { guidance: "The mutations were already approved and verified applied. Invoke the listed run_command now; its existing command review collects command approval. Do not ask for the completed mutation approval again in prose." } : {}) };
230
+ }
231
+ async control(call) {
232
+ const a = call.arguments ?? {};
233
+ if (a.action === "status") {
234
+ const continuation = this.continuation();
235
+ return { ...this.snapshot(), required_reads: this.requiredReads(), continuation };
236
+ }
237
+ this.checkBoundary();
238
+ if (a.action === "plan") {
239
+ if (this.controlPending)
240
+ fail("Wait for the preceding workflow result acknowledgement.");
241
+ this.requireNewOperation(call.tool_call_id);
242
+ if (!["TASK_RECEIVED", "INSPECTING", "ANALYZING_FAILURE"].includes(this.state))
243
+ fail("Inspect the repository first; a new plan requires completed failure analysis.");
244
+ const corrective = this.state === "ANALYZING_FAILURE";
245
+ if (corrective && !this.analyzed)
246
+ fail("Analyze the actual failing test and cite evidence before a correction.");
247
+ if (corrective && this.corrections >= MAX_CORRECTIONS) {
248
+ this.transition("UNRESOLVED");
249
+ fail("Correction limit reached. No further changes are allowed.");
250
+ }
251
+ const repo = this.repository(a.repository);
252
+ if (this.repo && this.repo.id !== repo.id)
253
+ fail("A coding task cannot switch repositories.");
254
+ if (!Array.isArray(a.files) || a.files.length < 1 || a.files.length > 5 || !Array.isArray(a.context_files) || a.context_files.length < 1 || a.context_files.length > 12 || !Array.isArray(a.tests) || a.tests.length < 1 || a.tests.length > 3)
255
+ fail("A plan needs 1–5 changed files, 1–12 contextual files, and 1–3 verification commands.");
256
+ const files = a.files.map(f => {
257
+ const rel = text(f.path, 1024);
258
+ if (path.isAbsolute(rel) || /[:\\\0]/.test(rel) || rel.split("/").includes("..") || rel === ".")
259
+ fail("Plan paths must stay relative to the repository.");
260
+ return { path: path.normalize(rel), reason: text(f.reason) };
261
+ });
262
+ if (new Set(files.map(f => f.path)).size !== files.length)
263
+ fail("Plan paths must be unique.");
264
+ const contextFiles = a.context_files.map(f => {
265
+ const rel = text(f.path, 1024, "context file path");
266
+ if (path.isAbsolute(rel) || /[:\\\0]/.test(rel) || rel.split("/").includes("..") || rel === ".")
267
+ fail("Context file paths must stay relative to the repository.");
268
+ const normalized = path.normalize(rel);
269
+ const abs = resolveInside(normalized, repo.root);
270
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile())
271
+ fail(`Context file does not exist or is not a file: ${normalized}`);
272
+ return { path: normalized, reason: text(f.reason, 2000, "context-file reason") };
273
+ });
274
+ if (new Set(contextFiles.map(f => f.path)).size !== contextFiles.length)
275
+ fail("Context file paths must be unique.");
276
+ const tests = a.tests.map(t => {
277
+ const d = evaluateCommand({ program: t.program, args: t.args, cwd: t.cwd }, repo.root);
278
+ return { program: d.program, args: d.args, cwd: d.cwdRelative || ".", purpose: text(t.purpose, 2000, "validation purpose") };
279
+ });
280
+ if (new Set(tests.map(commandKey)).size !== tests.length)
281
+ fail("Verification commands must be unique.");
282
+ const plan = { repository: repo.name, files, tests, summary: text(a.summary, 2000, "summary"), expected: text(a.expected, 2000, "expected"), risks: text(a.risks, 2000, "risks"), dependencies: text(a.dependencies, 2000, "dependencies") };
283
+ this.candidate = { repo, files, contextFiles, tests };
284
+ if (!this.inspected.has(repo.id))
285
+ fail("Inspect this repository using list_files or git_status first. coding_workflow status lists the required next actions.");
286
+ this.verifyReads(repo, files, tests, contextFiles);
287
+ const investigation = this.investigation(a.investigation, repo, files, contextFiles, corrective);
288
+ this.transition("PLANNING");
289
+ this.planOperations.add(call.tool_call_id);
290
+ if (corrective)
291
+ this.corrections++;
292
+ this.repo = repo;
293
+ this.plan = structuredClone({ ...plan, contextFiles, ...(investigation ? { investigation } : {}) });
294
+ this.planOperationId = call.tool_call_id;
295
+ this.planScope = this.options.recoveryScope?.();
296
+ this.active = true;
297
+ this.analyzed = false;
298
+ this.plannedApplied.clear();
299
+ this.tests.clear();
300
+ const traced = investigation ? [`Symptom: ${investigation.symptom}`, `Root cause: ${investigation.root_cause}`,
301
+ `Change location: ${investigation.change_location.path}${investigation.change_location.symbol ? ` · ${investigation.change_location.symbol}` : ""}`,
302
+ `Execution path: ${investigation.execution_path.map(s => s.symbol ? `${s.path} · ${s.symbol}` : s.path).join(" → ")}`,
303
+ ...investigation.evidence.map(e => `Evidence: ${e.path}${e.lines ? `:${e.lines}` : ""} — ${e.note}`),
304
+ ...investigation.ruled_out.map(r => `Ruled out: ${r.path} — ${r.reason}`)] : [];
305
+ this.show([`Plan: ${plan.summary}`, `Expected: ${plan.expected}`, ...traced, ...files.map(f => `${f.path}: ${f.reason}`), `Context files (${contextFiles.length}): ${contextFiles.map(f => f.path.length > 120 ? `${f.path.slice(0, 117)}...` : f.path).join(", ")}`, `Dependencies: ${plan.dependencies}`, `Validation:`, ...tests.map(t => ` ${t.program} ${t.args.join(" ")} (cwd: ${t.cwd}) — ${t.purpose}`), `Risks: ${plan.risks}`]);
306
+ this.show([`Plan operation: ${this.planOperationId}`, ...(this.planScope ? [`Recovery scope: ${this.planScope}`] : [])]);
307
+ this.transition("CAPABILITY_CHECK");
308
+ try {
309
+ const contract = await this.capability();
310
+ this.checkBoundary();
311
+ if (contract?.capability === "UNSUPPORTED")
312
+ fail(contract.prerequisite);
313
+ this.execution = contract || undefined;
314
+ }
315
+ catch (error) {
316
+ if (!TERMINAL.has(this.state))
317
+ this.transition("UNRESOLVED");
318
+ throw error;
319
+ }
320
+ this.controlPending = call.tool_call_id;
321
+ this.transition("READING");
322
+ return { ...this.snapshot(), required_reads: this.requiredReads(), continuation: this.continuation() };
323
+ }
324
+ if (a.action === "analyze") {
325
+ if (this.state !== "ANALYZING_FAILURE")
326
+ fail("There is no failed verification to analyze.");
327
+ const failures = [...this.tests.values()].filter(t => !t.passed).map(t => t.id);
328
+ if (!Array.isArray(a.test_ids) || !a.test_ids.length || a.test_ids.some(id => !failures.includes(String(id))))
329
+ fail("Analysis must cite actual failed verification operations.");
330
+ if (!Array.isArray(a.evidence_ids) || !a.evidence_ids.length || a.evidence_ids.some(id => !this.evidence.has(String(id)) && !failures.includes(String(id))))
331
+ fail("Analysis must cite recorded read/test evidence.");
332
+ const classification = text(a.classification, 40);
333
+ if (!["implementation", "pre_existing", "environment", "dependency", "infrastructure", "test_defect", "configuration", "unrelated", "unknown"].includes(classification))
334
+ fail("Invalid failure classification.");
335
+ const explanation = text(a.explanation);
336
+ this.controlPending = call.tool_call_id;
337
+ this.show([`Failure analysis (${classification}): ${explanation}`]);
338
+ this.analyzed = classification === "implementation";
339
+ // Retain only this task's already-selected read set in this repository.
340
+ // Test filenames need not follow a convention; never scan the whole repo.
341
+ for (const { repoId, rel } of this.observedPaths.values())
342
+ if (repoId === this.repo?.id)
343
+ this.correctiveReads.add(rel);
344
+ this.reads.clear(); // correction needs new complete reads, not pre-change evidence
345
+ this.options.onReadsInvalidated?.();
346
+ if (!this.analyzed)
347
+ this.transition("UNRESOLVED");
348
+ return { ...this.snapshot(), continuation: this.continuation(), analysis: { classification, explanation, test_ids: a.test_ids, evidence_ids: a.evidence_ids } };
349
+ }
350
+ if (a.action === "finish") {
351
+ if (this.state !== "COMPLETED" || this.pending.size || this.running.size || this.controlPending || !this.plan?.files.every(f => this.plannedApplied.has(f.path)) || !this.plan.tests.every(t => this.tests.get(commandKey(t))?.passed))
352
+ fail("Completion requires applied changes and every planned verification passing.");
353
+ this.controlPending = call.tool_call_id;
354
+ this.finishPending = call.tool_call_id;
355
+ return this.snapshot();
356
+ }
357
+ fail("Unknown coding workflow action.");
358
+ }
359
+ /** Validate a plan's investigation against what was actually read (see Investigation). */
360
+ investigation(raw, repo, files, contextFiles, corrective) {
361
+ if (raw === undefined && corrective)
362
+ return undefined; // a correction's evidence is its failure analysis
363
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
364
+ fail("A first plan needs an investigation: symptom, execution_path, evidence, root_cause and change_location, citing the files you read.");
365
+ const inv = raw;
366
+ const read = new Set([...files.map(f => f.path), ...contextFiles.map(f => f.path)]);
367
+ const cited = (value, what) => {
368
+ const rel = path.normalize(text(value, 1024, `${what} path`));
369
+ if (!read.has(rel))
370
+ fail(`${what} cites ${rel}, which is not one of this plan's files or context files. Cite only files you read completely.`);
371
+ return rel;
372
+ };
373
+ const symbolsOf = (rel) => {
374
+ const abs = resolveInside(rel, repo.root);
375
+ const symbols = fs.existsSync(abs) ? outline(fs.readFileSync(abs, "utf8"), rel).symbols : [];
376
+ return { names: symbols.flatMap(s => s.container ? [s.name, `${s.container}.${s.name}`] : [s.name]),
377
+ callable: symbols.some(s => s.kind !== "constant" && s.kind !== "type" && s.kind !== "interface") };
378
+ };
379
+ // A symbol is required wherever the file declares a function, method, class or
380
+ // component; module-level code (or only values and types) has nothing to name.
381
+ const symbolFor = (rel, raw, what) => {
382
+ const { names, callable } = symbolsOf(rel);
383
+ const symbol = raw === undefined || raw === null || raw === "" ? null : text(raw, 200, `${what} symbol`);
384
+ if (!symbol) {
385
+ if (callable)
386
+ fail(`${what} for ${rel} must name the function, method, class or component involved (code_outline lists them).`);
387
+ return null;
388
+ }
389
+ if (!names.includes(symbol))
390
+ fail(`${what} names ${symbol}, which is not declared in ${rel}. Name a function, method, class or component that exists there (code_outline lists them).`);
391
+ return symbol;
392
+ };
393
+ const list = (value, min, max, what) => {
394
+ if (!Array.isArray(value) || value.length < min || value.length > max)
395
+ fail(`investigation.${what} needs ${min}–${max} entries.`);
396
+ return value;
397
+ };
398
+ const location = (inv.change_location ?? {});
399
+ const changePath = path.normalize(text(location.path, 1024, "change location path"));
400
+ if (!files.some(f => f.path === changePath))
401
+ fail(`change_location.path ${changePath} must be one of the plan's files to change.`);
402
+ // A file the plan creates has nothing to name yet.
403
+ const changeSymbol = fs.existsSync(resolveInside(changePath, repo.root)) ? symbolFor(changePath, location.symbol, "change_location") : null;
404
+ const executionPath = list(inv.execution_path, 1, 8, "execution_path").map(step => {
405
+ const rel = cited(step.path, "execution_path");
406
+ const symbol = symbolFor(rel, step.symbol, "execution_path");
407
+ return { path: rel, symbol, note: typeof step.note === "string" ? step.note.trim().slice(0, 300) : "" };
408
+ });
409
+ const evidence = list(inv.evidence, 1, 8, "evidence").map(e => {
410
+ const rel = cited(e.path, "evidence");
411
+ const lines = e.lines === undefined || e.lines === null ? null : text(e.lines, 20, "evidence lines");
412
+ if (lines && !/^\d+(-\d+)?$/.test(lines))
413
+ fail("evidence.lines must look like 42 or 42-58.");
414
+ if (lines) {
415
+ const total = fs.readFileSync(resolveInside(rel, repo.root), "utf8").split(/\r\n|\r|\n/).length;
416
+ const [from, to = from] = lines.split("-").map(Number);
417
+ if (from < 1 || to < from || to > total)
418
+ fail(`evidence.lines ${lines} is outside ${rel} (${total} lines).`);
419
+ }
420
+ return { path: rel, lines, note: text(e.note, 500, "evidence note") };
421
+ });
422
+ const ruledOut = (inv.ruled_out === undefined ? [] : list(inv.ruled_out, 0, 8, "ruled_out")).map(r => {
423
+ const rel = path.normalize(text(r.path, 1024, "ruled out path"));
424
+ if (!this.inspectedFiles.has(this.key(repo.root, rel)) && !read.has(rel))
425
+ fail(`ruled_out cites ${rel}, which was not inspected in this task.`);
426
+ return { path: rel, reason: text(r.reason, 300, "ruled out reason") };
427
+ });
428
+ return { symptom: text(inv.symptom, 500, "symptom"), root_cause: text(inv.root_cause, 1000, "root cause"),
429
+ change_location: { path: changePath, symbol: changeSymbol }, execution_path: executionPath, evidence, ruled_out: ruledOut };
430
+ }
431
+ confirmControl(id) {
432
+ if (this.controlPending === id)
433
+ this.controlPending = undefined;
434
+ if (this.finishPending === id) {
435
+ this.finishAcknowledged = true;
436
+ this.finishPending = undefined;
437
+ }
438
+ }
439
+ beforeMutation(plans) {
440
+ this.checkBoundary();
441
+ if (this.controlPending)
442
+ fail("Wait for the plan acknowledgement before proposing mutations.");
443
+ if (!this.plan || !this.repo || !["READING", "APPLYING", "REAPPLYING"].includes(this.state) || this.pending.size)
444
+ fail("A displayed plan and completed reads are required before mutation approval.");
445
+ this.verifyReads();
446
+ for (const p of plans) {
447
+ this.requireNewOperation(p.operationId);
448
+ if (p.repositoryId !== this.repo.id || !this.plan.files.some(f => f.path === p.rel) || this.plannedApplied.has(p.rel))
449
+ fail("The mutation must match the current plan and selected repository.");
450
+ if (p.beforeExists && this.reads.get(this.key(p.repositoryRoot, p.rel)) !== p.beforeSha)
451
+ fail(`Read current full bytes before changing ${p.rel}.`);
452
+ }
453
+ this.transition(this.corrections ? "CORRECTIVE_PROPOSAL" : "PROPOSING");
454
+ this.transition(this.corrections ? "CORRECTIVE_APPROVAL" : "AWAITING_APPROVAL");
455
+ for (const p of plans) {
456
+ this.pending.add(p.operationId);
457
+ this.operations.add(p.operationId);
458
+ }
459
+ }
460
+ approval(answer) {
461
+ if (this.options.signal?.aborted) {
462
+ if (!TERMINAL.has(this.state))
463
+ this.transition("CANCELLED");
464
+ return;
465
+ }
466
+ this.checkBoundary();
467
+ if (answer !== "approve") {
468
+ this.transition(answer === "cancel" ? "CANCELLED" : "FAILED");
469
+ return;
470
+ }
471
+ this.transition(this.corrections ? "REAPPLYING" : "APPLYING");
472
+ }
473
+ mutationResult(payload) {
474
+ if (!this.pending.delete(payload.tool_call_id))
475
+ return;
476
+ if (!payload.ok) {
477
+ if (!TERMINAL.has(this.state))
478
+ this.transition(payload.error?.code === "MUTATION_CANCELLED" ? "CANCELLED" : "UNRESOLVED");
479
+ return;
480
+ }
481
+ const rel = String(payload.result?.path ?? "");
482
+ this.changed.add(rel);
483
+ this.plannedApplied.add(rel);
484
+ }
485
+ beforeCommand(call) {
486
+ this.checkBoundary();
487
+ if (!this.plan)
488
+ return; // ordinary read-only command requests remain available
489
+ this.requireNewOperation(call.tool_call_id);
490
+ if (!this.plan || !this.repo || this.pending.size || !["APPLYING", "REAPPLYING", "TESTING", "RETESTING"].includes(this.state))
491
+ fail("Apply the approved plan before verification.");
492
+ if (this.plan.files.some(f => !this.plannedApplied.has(f.path)))
493
+ fail("All planned file operations must finish before verification.");
494
+ const a = call.arguments ?? {};
495
+ if (this.repository(a.repository).id !== this.repo.id)
496
+ fail("Verification must use the planned repository.");
497
+ const key = commandKey(a);
498
+ if (!this.plan.tests.some(t => commandKey(t) === key) || this.running.size || this.tests.has(key))
499
+ fail("Run each planned verification once and sequentially.");
500
+ const next = this.plan.tests.find(t => !this.tests.has(commandKey(t)));
501
+ if (!next || commandKey(next) !== key)
502
+ fail("Run verification commands in planned order, after the preceding result is acknowledged.");
503
+ if (this.state === "APPLYING" || this.state === "REAPPLYING")
504
+ this.transition(this.corrections ? "RETESTING" : "TESTING");
505
+ this.running.set(call.tool_call_id, key);
506
+ this.commandOperations.add(call.tool_call_id);
507
+ }
508
+ commandResult(payload) {
509
+ const key = this.running.get(payload.tool_call_id);
510
+ if (!key || TERMINAL.has(this.state))
511
+ return;
512
+ // An absent/malformed exit is not implementation-failure evidence. Explicit
513
+ // timeout/cancellation still describe an observed executor outcome.
514
+ const r = payload.result ?? {};
515
+ if (payload.ok && !Number.isSafeInteger(r.exit_code) && r.timed_out !== true && r.cancelled !== true) {
516
+ this.transition("UNRESOLVED");
517
+ return;
518
+ }
519
+ this.running.delete(payload.tool_call_id);
520
+ if (!payload.ok) {
521
+ this.transition(["COMMAND_REJECTED", "COMMAND_CANCELLED", "CANCELLED"].includes(payload.error?.code ?? "") ? "CANCELLED" : "UNRESOLVED");
522
+ return;
523
+ }
524
+ const passed = r.exit_code === 0 && !r.timed_out && !r.cancelled;
525
+ this.tests.set(key, { id: payload.tool_call_id, passed, exit: r.exit_code });
526
+ if (!passed)
527
+ this.transition(r.cancelled ? "CANCELLED" : "ANALYZING_FAILURE");
528
+ else if (this.tests.size === this.plan.tests.length)
529
+ this.transition("COMPLETED");
530
+ }
531
+ interrupt() {
532
+ // Passing verification makes finish available; a completed turn additionally
533
+ // requires the existing finish result ACK. Never restore this on restart.
534
+ if (this.active && this.state === "COMPLETED" && !this.finishAcknowledged) {
535
+ this.currentState = this.options.signal?.aborted ? "CANCELLED" : "UNRESOLVED";
536
+ }
537
+ else if (this.active && !TERMINAL.has(this.state))
538
+ this.transition(this.options.signal?.aborted ? "CANCELLED" : "UNRESOLVED");
539
+ }
540
+ validation() {
541
+ return (this.plan?.tests ?? []).map(command => {
542
+ const key = commandKey(command), result = this.tests.get(key);
543
+ const running = [...this.running.entries()].find(([, value]) => value === key);
544
+ const applied = this.plan.files.every(f => this.plannedApplied.has(f.path)) && !this.pending.size;
545
+ return { ...structuredClone(command), repository: this.repo?.name, task_id: this.taskId, plan_operation_id: this.planOperationId,
546
+ operation_id: result?.id ?? running?.[0] ?? null, reason: "Verify the approved plan", stage: this.corrections ? "RETEST" : "TEST",
547
+ status: result ? (result.passed ? "PASSED" : "FAILED") : running ? (this.state === "UNRESOLVED" ? "UNRESOLVED" : "REVIEW_OR_EXECUTION_PENDING") : applied ? "PENDING_REVIEW" : "PENDING_MUTATION",
548
+ approval: result ? "RECORDED_BY_COMMAND_RESULT" : "REQUIRED", execution: result ? "COMPLETED" : running ? "PENDING_RESULT" : "NOT_STARTED" };
549
+ });
550
+ }
551
+ snapshot() { return { validation: this.validation(), task_id: this.taskId, state: this.state, execution: this.execution, corrections: this.corrections, repository: this.repo?.name, files: [...this.changed], tests: [...this.tests.entries()].map(([command, r]) => ({ command, ...r })), plan: this.plan ? structuredClone(this.plan) : undefined, approval: this.approvalContext(), operation_ids: [...this.operations] }; }
552
+ summary() { if (!this.active)
553
+ return []; return [`Coding task: ${this.state}`, `Change: ${this.plan?.summary ?? "No plan"}`, `Files changed: ${[...this.changed].join(", ") || "none confirmed"}`, `Verification: ${[...this.tests.values()].filter(t => t.passed).length}/${this.plan?.tests.length ?? 0} passed; corrections: ${this.corrections}`, ...this.plan.tests.map(t => { const r = this.tests.get(commandKey(t)); return `${t.program} ${t.args.join(" ")} (${t.cwd}) — ${t.purpose}: ${r ? `${r.passed ? "passed" : "failed"}, exit ${r.exit ?? "unknown"}` : "not completed"}`; }), ...(this.state !== "COMPLETED" ? ["Task is incomplete; no approval, mutation or command will be resumed automatically."] : [])]; }
554
+ }