@carrieros/cli-staging 0.0.0-stage → 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 (136) hide show
  1. package/README.md +6 -2
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/auth.js +60 -0
  4. package/dist/commands/btw.js +78 -0
  5. package/dist/commands/changes.js +167 -0
  6. package/dist/commands/chat.js +182 -0
  7. package/dist/commands/context.js +200 -0
  8. package/dist/commands/doctor.js +119 -0
  9. package/dist/commands/files.js +94 -0
  10. package/dist/commands/help.js +37 -0
  11. package/dist/commands/history.js +112 -0
  12. package/dist/commands/login.js +62 -0
  13. package/dist/commands/logout.js +25 -0
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +64 -0
  16. package/dist/commands/models.js +28 -0
  17. package/dist/commands/modes.js +30 -0
  18. package/dist/commands/permissions.js +77 -0
  19. package/dist/commands/project.js +106 -0
  20. package/dist/commands/repo.js +146 -0
  21. package/dist/commands/repos.js +61 -0
  22. package/dist/commands/review.js +92 -0
  23. package/dist/commands/scope.js +155 -0
  24. package/dist/commands/search.js +92 -0
  25. package/dist/commands/sessions.js +282 -0
  26. package/dist/commands/settings.js +100 -0
  27. package/dist/commands/update.js +229 -0
  28. package/dist/commands/upload.js +223 -0
  29. package/dist/commands/usage.js +227 -0
  30. package/dist/commands/version.js +26 -0
  31. package/dist/commands/whoami.js +44 -0
  32. package/dist/ide/editor-context.js +275 -0
  33. package/dist/ide/ide-session.js +360 -0
  34. package/dist/ide/tool-host.js +109 -0
  35. package/dist/main.js +126 -0
  36. package/dist/services/api.js +439 -0
  37. package/dist/services/auth-origin.js +20 -0
  38. package/dist/services/chat-stream.js +168 -0
  39. package/dist/services/checkpoints.js +278 -0
  40. package/dist/services/client-tools.js +356 -0
  41. package/dist/services/code-intel.js +243 -0
  42. package/dist/services/code-symbols.js +94 -0
  43. package/dist/services/coding-workflow.js +554 -0
  44. package/dist/services/command-coordinator.js +273 -0
  45. package/dist/services/command-policy.js +434 -0
  46. package/dist/services/config.js +383 -0
  47. package/dist/services/container-runner.js +254 -0
  48. package/dist/services/container-supervisor.js +38 -0
  49. package/dist/services/context.js +371 -0
  50. package/dist/services/device-auth.js +286 -0
  51. package/dist/services/diff.js +196 -0
  52. package/dist/services/env-policy.js +108 -0
  53. package/dist/services/execution-platform.js +30 -0
  54. package/dist/services/file-detect.js +104 -0
  55. package/dist/services/file-resolver.js +199 -0
  56. package/dist/services/file-upload.js +126 -0
  57. package/dist/services/folder-key.js +22 -0
  58. package/dist/services/git-tools.js +429 -0
  59. package/dist/services/glob-match.js +164 -0
  60. package/dist/services/helper-bin.js +85 -0
  61. package/dist/services/ignore-rules.js +189 -0
  62. package/dist/services/instruction-resolver.js +54 -0
  63. package/dist/services/job-helper.js +328 -0
  64. package/dist/services/local-files.js +639 -0
  65. package/dist/services/local-tools.js +937 -0
  66. package/dist/services/login-flow.js +156 -0
  67. package/dist/services/meta.js +15 -0
  68. package/dist/services/mutation-coordinator.js +327 -0
  69. package/dist/services/mutation-groups.js +309 -0
  70. package/dist/services/mutation-recovery.js +159 -0
  71. package/dist/services/mutations.js +679 -0
  72. package/dist/services/open-url.js +68 -0
  73. package/dist/services/output.js +62 -0
  74. package/dist/services/packaged-update.js +403 -0
  75. package/dist/services/packaged.js +39 -0
  76. package/dist/services/permission-mode.js +78 -0
  77. package/dist/services/process-runner.js +412 -0
  78. package/dist/services/project-context.js +298 -0
  79. package/dist/services/redaction.js +201 -0
  80. package/dist/services/result-reconciliation.js +49 -0
  81. package/dist/services/secure-store.js +217 -0
  82. package/dist/services/session-resolver.js +113 -0
  83. package/dist/services/sia.js +51 -0
  84. package/dist/services/spinner.js +40 -0
  85. package/dist/services/supported-runtime.js +59 -0
  86. package/dist/services/task-context.js +212 -0
  87. package/dist/services/task-snapshot.js +38 -0
  88. package/dist/services/tool-result-outbox.js +195 -0
  89. package/dist/services/update.js +311 -0
  90. package/dist/services/workspace-registry.js +310 -0
  91. package/dist/services/workspace.js +580 -0
  92. package/dist/shell/shell-chat.js +1619 -0
  93. package/dist/shell/shell-commands.js +411 -0
  94. package/dist/shell/shell-prompt.js +110 -0
  95. package/dist/shell/shell-renderer.js +51 -0
  96. package/dist/shell/shell-router.js +37 -0
  97. package/dist/shell/shell.js +389 -0
  98. package/dist/shell/task-context-view.js +40 -0
  99. package/dist/staging.js +5 -0
  100. package/dist/types/index.js +6 -0
  101. package/dist/ui/agent-cards.js +111 -0
  102. package/dist/ui/agent-presentation.js +131 -0
  103. package/dist/ui/approval.js +111 -0
  104. package/dist/ui/banner.js +56 -0
  105. package/dist/ui/btw-overlay.js +230 -0
  106. package/dist/ui/change-review.js +334 -0
  107. package/dist/ui/chat-renderer.js +463 -0
  108. package/dist/ui/code-block.js +52 -0
  109. package/dist/ui/color-picker.js +100 -0
  110. package/dist/ui/colors.js +55 -0
  111. package/dist/ui/command-details.js +11 -0
  112. package/dist/ui/command-filter.js +92 -0
  113. package/dist/ui/command-item.js +6 -0
  114. package/dist/ui/command-palette.js +383 -0
  115. package/dist/ui/command-registry.js +128 -0
  116. package/dist/ui/command-renderer.js +55 -0
  117. package/dist/ui/command-review.js +187 -0
  118. package/dist/ui/composer-layout.js +74 -0
  119. package/dist/ui/conversation.js +450 -0
  120. package/dist/ui/interrupt.js +35 -0
  121. package/dist/ui/live.js +141 -0
  122. package/dist/ui/logo.js +58 -0
  123. package/dist/ui/markdown.js +205 -0
  124. package/dist/ui/message.js +21 -0
  125. package/dist/ui/screen-prompt.js +181 -0
  126. package/dist/ui/screen.js +297 -0
  127. package/dist/ui/select.js +284 -0
  128. package/dist/ui/sia-qa.js +213 -0
  129. package/dist/ui/spinner.js +23 -0
  130. package/dist/ui/sticky-stream.js +64 -0
  131. package/dist/ui/task-context-card.js +99 -0
  132. package/dist/ui/text-prompt.js +74 -0
  133. package/dist/ui/theme.js +80 -0
  134. package/dist/ui/trust.js +88 -0
  135. package/dist/ui/ui.js +101 -0
  136. package/package.json +33 -4
@@ -0,0 +1,679 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { appendEntry, latestRevertible, repositoryKey, readJournal, loadCheckpoint, newCheckpointId, saveCheckpoint, saveRecoveryReceipt, recoveryReceipts, renameWithRetry, updateRecoveryReceipt, sha256, updateEntry } from "./checkpoints.js";
5
+ import { diffLines, formatUnified, toLines } from "./diff.js";
6
+ import { enclosingSymbol } from "./code-symbols.js";
7
+ import { LocalFileError, isInside, isPathIgnored, resolveInside } from "./local-files.js";
8
+ import { isSensitiveName } from "./local-tools.js";
9
+ import { activeRepository, isWildcardSelector, listRepositories, resolveOperableRepository } from "./workspace-registry.js";
10
+ /**
11
+ * Supervised file changes: plan, show, approve, apply, undo.
12
+ *
13
+ * This module never decides that a change is wanted. It turns a proposal into a
14
+ * PLAN — validated, diffed, touching nothing on disk — and applies a plan only
15
+ * when the caller has an explicit approval for that exact plan. Between the two
16
+ * the file is read again, and if it changed at all the apply refuses: the user
17
+ * approved a diff against a specific file, not whatever is there now.
18
+ *
19
+ * Every boundary the read tools enforce applies here too, and more strictly:
20
+ * the workspace root, realpath containment for the file AND every existing
21
+ * parent directory, ignored paths (which include .git and node_modules), and
22
+ * credential-shaped files, which are refused outright rather than confirmed.
23
+ */
24
+ export const MUTATION_TOOL_NAMES = ["create_file", "write_file", "edit_file", "delete_file", "revert_change"];
25
+ /** Largest content a create/write may carry, and largest file an edit reads. */
26
+ export const MAX_WRITE_BYTES = 512 * 1024;
27
+ export const MAX_EDIT_SOURCE_BYTES = 1024 * 1024;
28
+ /** Most files in one approval, and in one turn. Intentionally small. */
29
+ export const MAX_FILES_PER_APPROVAL = 5;
30
+ export const MAX_MUTATIONS_PER_TURN = 8;
31
+ /** A diff longer than this cannot be reviewed on a terminal and is refused. */
32
+ export const MAX_REVIEW_LINES = 800;
33
+ /** Unanswered approvals close as rejected — inside the server's 5 minute hold. */
34
+ export const APPROVAL_TIMEOUT_MS = 4 * 60 * 1000;
35
+ /**
36
+ * Names refused for changes beyond the read tools' credential list: anything
37
+ * called "secrets", git credential stores, and SSH material by directory.
38
+ */
39
+ const EXTRA_PROTECTED = [/^secrets?(\..+)?$/i, /^\.git-credentials$/i, /^\.htpasswd$/i, /^authorized_keys$/i, /^known_hosts$/i];
40
+ export class MutationError extends Error {
41
+ code;
42
+ recovery;
43
+ constructor(code, message, recovery) {
44
+ super(message);
45
+ this.code = code;
46
+ this.recovery = recovery;
47
+ this.name = "MutationError";
48
+ }
49
+ }
50
+ const str = (v) => (typeof v === "string" ? v : undefined);
51
+ const posix = (p) => p.split(path.sep).join("/");
52
+ /** Text with a NUL byte in its first 8 KB is not something we edit as text. */
53
+ function isBinary(buf) {
54
+ const end = Math.min(buf.length, 8192);
55
+ for (let i = 0; i < end; i += 1)
56
+ if (buf[i] === 0)
57
+ return true;
58
+ return false;
59
+ }
60
+ /**
61
+ * Resolve a proposed path and prove it may be changed.
62
+ *
63
+ * For a file that does not exist yet, realpath cannot run on it, so containment
64
+ * is proven on the deepest ancestor that DOES exist — otherwise a junction
65
+ * directory inside the project would let a "new file" land outside it.
66
+ */
67
+ export function resolveMutationTarget(input, root) {
68
+ const raw = str(input)?.trim();
69
+ if (!raw)
70
+ throw new MutationError("INVALID_TOOL_ARGUMENTS", '"path" is required.');
71
+ if (path.isAbsolute(raw) || /^[a-zA-Z]:/.test(raw)) {
72
+ throw new MutationError("OUTSIDE_WORKSPACE", "Paths must be relative to the project root.");
73
+ }
74
+ if (raw.split(/[\\/]+/).includes("..")) {
75
+ throw new MutationError("OUTSIDE_WORKSPACE", "Paths must stay inside the project.");
76
+ }
77
+ let abs;
78
+ try {
79
+ abs = resolveInside(raw, root);
80
+ }
81
+ catch (err) {
82
+ if (err instanceof LocalFileError)
83
+ throw new MutationError(err.code, err.message);
84
+ throw err;
85
+ }
86
+ let probe = path.dirname(abs);
87
+ while (!fs.existsSync(probe) && isInside(root, path.dirname(probe)) && path.dirname(probe) !== probe) {
88
+ probe = path.dirname(probe);
89
+ }
90
+ try {
91
+ if (!isInside(root, fs.realpathSync.native(probe))) {
92
+ throw new MutationError("OUTSIDE_WORKSPACE", `${raw} is inside a link that leaves the project.`);
93
+ }
94
+ }
95
+ catch (err) {
96
+ if (err instanceof MutationError)
97
+ throw err;
98
+ }
99
+ const rel = posix(path.relative(root, abs));
100
+ if (!rel || rel.startsWith(".."))
101
+ throw new MutationError("OUTSIDE_WORKSPACE", "Paths must stay inside the project.");
102
+ if (isPathIgnored(rel, root)) {
103
+ throw new MutationError("IGNORED_PATH", `${rel} is excluded by the project's ignore rules and will not be changed.`);
104
+ }
105
+ const base = path.basename(abs);
106
+ if (isSensitiveName(base) || EXTRA_PROTECTED.some((re) => re.test(base)) || rel.split("/").includes(".ssh")) {
107
+ throw new MutationError("SENSITIVE_FILE", `${rel} looks like a credentials file. Carrier OS will not change it.`);
108
+ }
109
+ return { abs, rel };
110
+ }
111
+ function readExisting(abs, rel) {
112
+ let st;
113
+ try {
114
+ st = fs.statSync(abs);
115
+ }
116
+ catch {
117
+ throw new MutationError("FILE_NOT_FOUND", `${rel} does not exist.`);
118
+ }
119
+ if (!st.isFile())
120
+ throw new MutationError("NOT_A_FILE", `${rel} is not a file.`);
121
+ if (st.size > MAX_EDIT_SOURCE_BYTES) {
122
+ throw new MutationError("FILE_TOO_LARGE", `${rel} is larger than ${MAX_EDIT_SOURCE_BYTES} bytes.`);
123
+ }
124
+ const buf = fs.readFileSync(abs);
125
+ if (isBinary(buf))
126
+ throw new MutationError("BINARY_FILE", `${rel} is not a text file.`);
127
+ return { buf, mode: st.mode };
128
+ }
129
+ function checkWriteSize(content) {
130
+ if (Buffer.byteLength(content, "utf8") > MAX_WRITE_BYTES) {
131
+ throw new MutationError("FILE_TOO_LARGE", `The new content exceeds ${MAX_WRITE_BYTES} bytes.`);
132
+ }
133
+ }
134
+ function countOccurrences(haystack, needle) {
135
+ let count = 0;
136
+ let from = 0;
137
+ for (;;) {
138
+ const i = haystack.indexOf(needle, from);
139
+ if (i === -1)
140
+ return count;
141
+ count += 1;
142
+ from = i + needle.length;
143
+ }
144
+ }
145
+ /** A text's line-ending style: consistently LF, consistently CRLF, mixed, or no line breaks. */
146
+ export function lineEndingStyle(text) {
147
+ const crlf = (text.match(/\r\n/g) ?? []).length, lf = (text.match(/\n/g) ?? []).length - crlf;
148
+ return crlf && lf ? "mixed" : crlf ? "CRLF" : lf ? "LF" : "none";
149
+ }
150
+ /** New text for a consistently-CRLF file, written with CRLF when it carries no CR
151
+ * of its own. A mixed or LF file, or text that already has CRs, is left exactly as given. */
152
+ function matchLineEndings(original, text) {
153
+ return lineEndingStyle(original) === "CRLF" && !text.includes("\r") ? text.replace(/\n/g, "\r\n") : text;
154
+ }
155
+ /**
156
+ * Apply an edit's replacement deterministically, or refuse.
157
+ *
158
+ * Exact match only — no fuzzy matching, no whitespace normalisation beyond one
159
+ * well-defined case: a Windows file with CRLF line endings, where a model that
160
+ * read the file copies `old_string` with LF. That is retried ONCE with CRLF
161
+ * applied to both strings, and still has to match exactly and uniquely.
162
+ */
163
+ function applyEdit(original, oldStr, newStr, replaceAll, rel) {
164
+ const attempt = (o, n) => {
165
+ const count = countOccurrences(original, o);
166
+ if (count === 0)
167
+ return null;
168
+ if (count > 1 && !replaceAll) {
169
+ throw new MutationError("EDIT_AMBIGUOUS", `old_string occurs ${count} times in ${rel}. Include more surrounding lines so it matches exactly once.`);
170
+ }
171
+ return replaceAll ? original.split(o).join(n) : original.replace(o, () => n);
172
+ };
173
+ // A direct match in a CRLF file still writes its new lines as CRLF.
174
+ const direct = attempt(oldStr, matchLineEndings(original, newStr));
175
+ if (direct !== null)
176
+ return direct;
177
+ if (original.includes("\r\n") && !oldStr.includes("\r\n")) {
178
+ const crlf = (s) => s.replace(/\r?\n/g, "\r\n");
179
+ const converted = attempt(crlf(oldStr), crlf(newStr));
180
+ if (converted !== null)
181
+ return converted;
182
+ }
183
+ throw new MutationError("EDIT_TARGET_NOT_FOUND", `old_string was not found in ${rel}. Read the file again and copy the text exactly.`);
184
+ }
185
+ /**
186
+ * The repository a change will touch.
187
+ *
188
+ * Omitted means the ACTIVE repository — the behaviour every earlier call
189
+ * depends on. A named repository may be any registered, TRUSTED one, whether or
190
+ * not it is active: the user still reads that name on the approval card and
191
+ * still says yes to that specific change, and the active repository is left
192
+ * exactly where it was. What is never accepted is a wildcard, an unknown name,
193
+ * anything path-shaped, or a repository the user has not trusted.
194
+ */
195
+ function repositoryForChange(selector) {
196
+ if (selector === undefined || selector === null || selector === "")
197
+ return activeRepository();
198
+ if (isWildcardSelector(selector)) {
199
+ throw new MutationError("REPOSITORY_WILDCARD_NOT_ALLOWED", 'A change must name one repository; "*" is not accepted.');
200
+ }
201
+ try {
202
+ return resolveOperableRepository(selector);
203
+ }
204
+ catch (err) {
205
+ throw new MutationError(err.code ?? "INVALID_REPOSITORY", err.message);
206
+ }
207
+ }
208
+ function finishPlan(p) {
209
+ const before = p.beforeBuf?.toString("utf8") ?? "";
210
+ const after = p.afterBuf?.toString("utf8") ?? "";
211
+ const diff = diffLines(before, after);
212
+ const where = changeLocation(diff, p.afterExists ? after : before, p.afterExists ? "new" : "old");
213
+ const styles = { before: lineEndingStyle(before), after: lineEndingStyle(after) };
214
+ const lineEndings = p.beforeExists && p.afterExists && styles.before !== styles.after &&
215
+ styles.before !== "none" && styles.after !== "none" ? { lineEndings: styles } : {};
216
+ return {
217
+ ...p,
218
+ beforeSha: p.beforeBuf ? sha256(p.beforeBuf) : null,
219
+ afterSha: p.afterBuf ? sha256(p.afterBuf) : null,
220
+ diff,
221
+ unified: formatUnified(p.rel, diff, { oldExists: p.beforeExists, newExists: p.afterExists }),
222
+ ...where,
223
+ ...lineEndings
224
+ };
225
+ }
226
+ /**
227
+ * The changed line range (context excluded) and the symbol around its first
228
+ * line, from the diff itself — so the numbers and names a reviewer sees are the
229
+ * diff's, not the model's.
230
+ */
231
+ export function changeLocation(diff, text, side) {
232
+ let first = 0, last = 0;
233
+ for (const h of diff.hunks) {
234
+ let oldNo = h.oldStart, newNo = h.newStart;
235
+ for (const l of h.lines) {
236
+ const changed = side === "new" ? l.op === "+" : l.op === "-";
237
+ const lineNo = side === "new" ? newNo : oldNo;
238
+ if (changed) {
239
+ if (!first)
240
+ first = lineNo;
241
+ last = lineNo;
242
+ }
243
+ if (l.op !== "+")
244
+ oldNo += 1;
245
+ if (l.op !== "-")
246
+ newNo += 1;
247
+ }
248
+ }
249
+ // A pure deletion inside an edit changes no new line: point at where it was.
250
+ if (!first && diff.hunks.length) {
251
+ first = last = Math.max(1, side === "new" ? diff.hunks[0].newStart : diff.hunks[0].oldStart);
252
+ }
253
+ if (!first)
254
+ return {};
255
+ const symbol = enclosingSymbol(toLines(text), first - 1);
256
+ return { range: { startLine: first, endLine: last, side }, ...(symbol ? { symbol } : {}) };
257
+ }
258
+ /**
259
+ * Turn one proposal into a reviewable plan. Reads, never writes. Throws a
260
+ * MutationError with a code the model can act on for anything it refuses.
261
+ */
262
+ export function planMutation(call) {
263
+ const name = call.name;
264
+ if (!MUTATION_TOOL_NAMES.includes(name)) {
265
+ throw new MutationError("UNKNOWN_CLIENT_TOOL", `No local tool named "${call.name}".`);
266
+ }
267
+ const args = (call.arguments ?? {});
268
+ const reason = str(args.reason)?.trim() || "No reason given.";
269
+ // One change, one repository — resolved BEFORE any path is touched, so the
270
+ // root every containment check runs against is a registry handle's root and
271
+ // never something derived from the path itself.
272
+ const repo = repositoryForChange(args.repository);
273
+ const root = fs.realpathSync.native(repo.root);
274
+ const operationId = call.tool_call_id;
275
+ if (name === "revert_change") {
276
+ // Scoped to this repository's own journal: an operation id belonging to a
277
+ // different repository is simply not found here, which is the behaviour we
278
+ // want — a change is undone where it was made, or not at all.
279
+ const target = latestRevertible(root, str(args.operation_id), repo.id);
280
+ if (!target) {
281
+ throw new MutationError("NOTHING_TO_REVERT", str(args.operation_id)
282
+ ? `No applied change with that id in ${repo.name}. A change is undone in the repository it was made in.`
283
+ : `There is no applied change to undo in ${repo.name}.`);
284
+ }
285
+ const { abs, rel } = resolveMutationTarget(target.path, root);
286
+ // Undo restores what was there BEFORE the change — but only if the file is
287
+ // still exactly what the change left. Anything else would clobber later work.
288
+ const nowExists = fs.existsSync(abs);
289
+ const nowBuf = nowExists ? fs.readFileSync(abs) : null;
290
+ const nowSha = nowBuf ? sha256(nowBuf) : null;
291
+ if (nowExists !== target.after_exists || nowSha !== target.after_sha) {
292
+ throw new MutationError("STALE_FILE", `${rel} has changed since that change was applied, so it will not be reverted.`);
293
+ }
294
+ let restored = null;
295
+ if (target.before_exists) {
296
+ restored = loadCheckpoint(root, target.checkpoint_id);
297
+ if (!restored)
298
+ throw new MutationError("CHECKPOINT_MISSING", `The checkpoint for ${rel} is no longer available.`);
299
+ }
300
+ return finishPlan({
301
+ operationId,
302
+ repositoryId: repo.id,
303
+ repositoryName: repo.name,
304
+ repositoryRoot: root,
305
+ name,
306
+ rel,
307
+ abs,
308
+ reason,
309
+ beforeExists: nowExists,
310
+ beforeBuf: nowBuf,
311
+ afterExists: target.before_exists,
312
+ afterBuf: restored,
313
+ reverts: target.operation_id,
314
+ revertEntry: target,
315
+ beforeMode: target.mode
316
+ });
317
+ }
318
+ const { abs, rel } = resolveMutationTarget(args.path, root);
319
+ const exists = fs.existsSync(abs);
320
+ switch (name) {
321
+ case "create_file": {
322
+ const content = str(args.content);
323
+ if (content === undefined)
324
+ throw new MutationError("INVALID_TOOL_ARGUMENTS", '"content" must be a string.');
325
+ if (exists)
326
+ throw new MutationError("FILE_EXISTS", `${rel} already exists. Use edit_file or write_file to change it.`);
327
+ checkWriteSize(content);
328
+ return finishPlan({ operationId, repositoryId: repo.id, repositoryName: repo.name, repositoryRoot: root, name, rel, abs, reason, beforeExists: false, beforeBuf: null, afterExists: true, afterBuf: Buffer.from(content, "utf8") });
329
+ }
330
+ case "write_file": {
331
+ const content = str(args.content);
332
+ if (content === undefined)
333
+ throw new MutationError("INVALID_TOOL_ARGUMENTS", '"content" must be a string.');
334
+ if (!exists)
335
+ throw new MutationError("FILE_NOT_FOUND", `${rel} does not exist. Use create_file for a new file.`);
336
+ checkWriteSize(content);
337
+ const { buf, mode } = readExisting(abs, rel);
338
+ const written = matchLineEndings(buf.toString("utf8"), content);
339
+ return finishPlan({ operationId, repositoryId: repo.id, repositoryName: repo.name, repositoryRoot: root, name, rel, abs, reason, beforeExists: true, beforeBuf: buf, beforeMode: mode, afterExists: true, afterBuf: Buffer.from(written, "utf8") });
340
+ }
341
+ case "edit_file": {
342
+ const oldStr = str(args.old_string);
343
+ const newStr = str(args.new_string);
344
+ if (!oldStr || newStr === undefined) {
345
+ throw new MutationError("INVALID_TOOL_ARGUMENTS", '"old_string" and "new_string" are required.');
346
+ }
347
+ const { buf, mode } = readExisting(abs, rel);
348
+ const updated = applyEdit(buf.toString("utf8"), oldStr, newStr, args.replace_all === true, rel);
349
+ checkWriteSize(updated);
350
+ return finishPlan({ operationId, repositoryId: repo.id, repositoryName: repo.name, repositoryRoot: root, name, rel, abs, reason, beforeExists: true, beforeBuf: buf, beforeMode: mode, afterExists: true, afterBuf: Buffer.from(updated, "utf8") });
351
+ }
352
+ case "delete_file": {
353
+ const { buf, mode } = readExisting(abs, rel);
354
+ return finishPlan({ operationId, repositoryId: repo.id, repositoryName: repo.name, repositoryRoot: root, name, rel, abs, reason, beforeExists: true, beforeBuf: buf, beforeMode: mode, afterExists: false, afterBuf: null });
355
+ }
356
+ }
357
+ throw new MutationError("UNKNOWN_CLIENT_TOOL", `No local tool named "${call.name}".`);
358
+ }
359
+ /** Write bytes via a temp file in the same directory, then rename over the target. */
360
+ function atomicWrite(abs, buf, mode, signal) {
361
+ const dir = path.dirname(abs);
362
+ const tmp = path.join(dir, `.${path.basename(abs)}.cos-${crypto.randomBytes(4).toString("hex")}.tmp`);
363
+ fs.writeFileSync(tmp, buf, mode ? { mode: mode & 0o777 } : undefined);
364
+ try {
365
+ renameWithRetry(tmp, abs, { signal });
366
+ }
367
+ catch (err) {
368
+ try {
369
+ fs.unlinkSync(tmp);
370
+ }
371
+ catch {
372
+ /* ignore */
373
+ }
374
+ throw err;
375
+ }
376
+ }
377
+ /** Prepare existing per-file evidence without changing the target. Group creation uses
378
+ * this after approval so even not-started members have a checkpoint and hashes. */
379
+ export function prepareMutation(plan, recoveryScope, groupId) {
380
+ const root = plan.repositoryRoot;
381
+ // Stable IDs are evidence, never permission to repeat a mutation.
382
+ const existing = recoveryReceipts(root);
383
+ if (existing.problems || existing.bounded || existing.receipts.length >= 90) {
384
+ throw new MutationError("RECOVERY_STATE_BLOCKED", "Recovery evidence needs review before more changes can be applied. Nothing was written.");
385
+ }
386
+ if (existing.receipts.some(r => r.operation_id === plan.operationId)) {
387
+ throw new MutationError("MUTATION_ALREADY_RECORDED", "This operation already has recovery evidence. It will not be executed again.");
388
+ }
389
+ // A corrupt journal is not an empty history. Fail before touching the file.
390
+ readJournal(root);
391
+ const checkpointId = newCheckpointId();
392
+ try {
393
+ saveCheckpoint(root, checkpointId, plan.beforeBuf);
394
+ saveRecoveryReceipt(root, checkpointId, {
395
+ version: 2, action: plan.name, approved: true, phase: "prepared", journal_persisted: false,
396
+ delivery: "none", scope: recoveryScope, group_id: groupId, created_at: new Date().toISOString(),
397
+ repository_id: plan.repositoryId, repository_name: plan.repositoryName,
398
+ operation_id: plan.operationId, path: plan.rel, before_exists: plan.beforeExists,
399
+ before_sha: plan.beforeSha, after_exists: plan.afterExists, after_sha: plan.afterSha,
400
+ mode: plan.beforeMode
401
+ });
402
+ }
403
+ catch {
404
+ throw new MutationError("CHECKPOINT_FAILED", `Could not save a checkpoint for ${plan.rel}. Nothing was written.`);
405
+ }
406
+ return checkpointId;
407
+ }
408
+ /**
409
+ * Apply an APPROVED plan. Re-reads the file first and refuses if anything
410
+ * changed since the plan was made; checkpoints the original; writes atomically;
411
+ * verifies the result. On failure, restores and verifies the original where
412
+ * possible; otherwise reports an unresolved mutation with checkpoint identity.
413
+ */
414
+ export function applyPlan(plan, recoveryScope, prepared, signal) {
415
+ const checkCancellation = () => { if (signal?.aborted)
416
+ throw new MutationError("MUTATION_CANCELLED", "The turn was cancelled before target mutation. Prepared recovery evidence was retained."); };
417
+ checkCancellation();
418
+ const root = plan.repositoryRoot;
419
+ assertPlanCurrent(plan);
420
+ let checkpointId;
421
+ if (prepared) {
422
+ const receipt = recoveryReceipts(root).receipts.find(r => r.checkpoint_id === prepared.checkpointId);
423
+ const original = receipt && plan.beforeExists ? loadCheckpoint(root, receipt.checkpoint_id) : null;
424
+ if (!receipt || receipt.group_id !== prepared.groupId || receipt.phase !== "prepared" ||
425
+ receipt.scope !== recoveryScope || receipt.operation_id !== plan.operationId ||
426
+ receipt.repository_id !== plan.repositoryId || receipt.path !== plan.rel || receipt.action !== plan.name ||
427
+ receipt.before_exists !== plan.beforeExists || receipt.after_exists !== plan.afterExists ||
428
+ receipt.before_sha !== plan.beforeSha || receipt.after_sha !== plan.afterSha ||
429
+ (plan.beforeExists && (!original || sha256(original) !== plan.beforeSha))) {
430
+ throw new MutationError("RECOVERY_STATE_BLOCKED", "Prepared mutation evidence does not match the approved plan. Nothing was written.");
431
+ }
432
+ checkpointId = receipt.checkpoint_id;
433
+ readJournal(root);
434
+ }
435
+ else
436
+ checkpointId = prepareMutation(plan, recoveryScope);
437
+ checkCancellation();
438
+ const recoverFailure = (code) => {
439
+ try {
440
+ resolveMutationTarget(plan.rel, root);
441
+ const exists = fs.existsSync(plan.abs);
442
+ const hash = exists ? sha256(fs.readFileSync(plan.abs)) : null;
443
+ // Never overwrite a concurrent edit while trying to repair our failure.
444
+ if (exists !== plan.beforeExists || hash !== plan.beforeSha) {
445
+ if (exists !== plan.afterExists || hash !== plan.afterSha)
446
+ throw new Error("intervening edit");
447
+ restoreOriginal(plan.abs, plan.beforeExists, plan.beforeBuf, plan.beforeMode);
448
+ }
449
+ }
450
+ catch {
451
+ try {
452
+ updateRecoveryReceipt(root, checkpointId, { phase: "unresolved" });
453
+ }
454
+ catch { /* preserve prepared evidence */ }
455
+ throw new MutationError("MUTATION_UNRESOLVED", `${plan.repositoryName}/${plan.rel} may still be modified; restoration could not be verified. Recovery checkpoint ${checkpointId} (operation ${plan.operationId}) was preserved.`, { operationId: plan.operationId, checkpointId, path: plan.rel, repositoryId: plan.repositoryId, unresolved: true });
456
+ }
457
+ try {
458
+ updateRecoveryReceipt(root, checkpointId, { phase: "rolled_back" });
459
+ }
460
+ catch { /* scan compares actual bytes */ }
461
+ // If an entry was published before a later journal update failed, do not
462
+ // leave it claiming successful execution when we have restored the bytes.
463
+ try {
464
+ updateEntry(root, plan.operationId, { status: "FAILED" });
465
+ }
466
+ catch { /* receipt remains available */ }
467
+ throw new MutationError(code, `${plan.rel}: ${code === "JOURNAL_FAILED" ? "journal persistence" : "file write"} failed; original file state was verified/restored. Recovery checkpoint ${checkpointId} was preserved.`);
468
+ };
469
+ try {
470
+ if (plan.afterExists && plan.afterBuf) {
471
+ if (!plan.beforeExists) {
472
+ fs.mkdirSync(path.dirname(plan.abs), { recursive: true });
473
+ // mkdir may have created directories; the file's final location must
474
+ // still be inside the project.
475
+ if (!isInside(root, fs.realpathSync.native(path.dirname(plan.abs)))) {
476
+ throw new MutationError("OUTSIDE_WORKSPACE", `${plan.rel} resolved outside the project.`);
477
+ }
478
+ }
479
+ atomicWrite(plan.abs, plan.afterBuf, plan.beforeMode, signal);
480
+ }
481
+ else {
482
+ fs.unlinkSync(plan.abs);
483
+ }
484
+ updateRecoveryReceipt(root, checkpointId, { phase: "applied" });
485
+ const verifySha = fs.existsSync(plan.abs) ? sha256(fs.readFileSync(plan.abs)) : null;
486
+ if (verifySha !== plan.afterSha) {
487
+ throw new MutationError("WRITE_FAILED", `${plan.rel} did not end up with the approved content.`);
488
+ }
489
+ updateRecoveryReceipt(root, checkpointId, { phase: "verified" });
490
+ }
491
+ catch (err) {
492
+ return recoverFailure(err instanceof MutationError ? err.code : "WRITE_FAILED");
493
+ }
494
+ const applied = {
495
+ operationId: plan.operationId,
496
+ repositoryId: plan.repositoryId,
497
+ repositoryName: plan.repositoryName,
498
+ checkpointId,
499
+ name: plan.name,
500
+ rel: plan.rel,
501
+ beforeExists: plan.beforeExists,
502
+ afterExists: plan.afterExists,
503
+ beforeSha: plan.beforeSha,
504
+ afterSha: plan.afterSha,
505
+ beforeBytes: plan.beforeBuf?.length ?? 0,
506
+ afterBytes: plan.afterBuf?.length ?? 0,
507
+ added: plan.diff.added,
508
+ removed: plan.diff.removed,
509
+ ...(plan.symbol ? { symbol: plan.symbol } : {}),
510
+ review: reviewedDiffMetadata(plan),
511
+ ...(plan.reverts ? { reverts: plan.reverts } : {})
512
+ };
513
+ try {
514
+ appendEntry(root, {
515
+ operation_id: plan.operationId,
516
+ repository_id: plan.repositoryId,
517
+ repository_name: plan.repositoryName,
518
+ repository_key: repositoryKey(root),
519
+ checkpoint_id: checkpointId,
520
+ action: plan.name,
521
+ path: plan.rel,
522
+ reason: plan.reason.slice(0, 300),
523
+ created_at: new Date().toISOString(),
524
+ status: "EXECUTED",
525
+ before_exists: plan.beforeExists,
526
+ after_exists: plan.afterExists,
527
+ before_sha: plan.beforeSha,
528
+ after_sha: plan.afterSha,
529
+ before_bytes: applied.beforeBytes,
530
+ after_bytes: applied.afterBytes,
531
+ added: plan.diff.added,
532
+ removed: plan.diff.removed,
533
+ mode: plan.beforeMode,
534
+ reviewed_diff: applied.review,
535
+ ...(plan.reverts ? { reverts: plan.reverts } : {})
536
+ });
537
+ if (plan.reverts) {
538
+ updateEntry(root, plan.reverts, {
539
+ status: "ROLLED_BACK",
540
+ reverted_by: plan.operationId,
541
+ rolled_back_at: new Date().toISOString()
542
+ });
543
+ }
544
+ }
545
+ catch {
546
+ return recoverFailure("JOURNAL_FAILED");
547
+ }
548
+ try {
549
+ updateRecoveryReceipt(root, checkpointId, { journal_persisted: true });
550
+ }
551
+ catch {
552
+ return recoverFailure("JOURNAL_FAILED");
553
+ }
554
+ return applied;
555
+ }
556
+ function restoreOriginal(abs, existed, buf, mode) {
557
+ if (existed) {
558
+ if (buf === null)
559
+ throw new Error("Missing original checkpoint");
560
+ atomicWrite(abs, buf, mode);
561
+ }
562
+ else if (fs.existsSync(abs))
563
+ fs.unlinkSync(abs);
564
+ const exists = fs.existsSync(abs);
565
+ if (exists !== existed || (exists && !fs.readFileSync(abs).equals(buf))) {
566
+ throw new Error("Restored bytes could not be verified");
567
+ }
568
+ }
569
+ /**
570
+ * Undo a change applied earlier in the SAME approval group, used when a later
571
+ * change in the group fails. Only restores if the file is still exactly what
572
+ * this change wrote.
573
+ */
574
+ export function rollbackApplied(applied) {
575
+ const root = repositoryRootById(applied.repositoryId);
576
+ // The repository is no longer registered: there is no root we can honestly
577
+ // restore into, and guessing one would write another repository's file.
578
+ if (!root)
579
+ return false;
580
+ const unresolved = () => {
581
+ try {
582
+ updateRecoveryReceipt(root, applied.checkpointId, { phase: "unresolved" });
583
+ }
584
+ catch { /* retain existing evidence when the receipt cannot be updated */ }
585
+ return false;
586
+ };
587
+ try {
588
+ const { abs } = resolveMutationTarget(applied.rel, root);
589
+ const nowExists = fs.existsSync(abs);
590
+ const nowSha = nowExists ? sha256(fs.readFileSync(abs)) : null;
591
+ if (nowExists !== applied.afterExists || nowSha !== applied.afterSha)
592
+ return unresolved();
593
+ const original = applied.beforeExists ? loadCheckpoint(root, applied.checkpointId) : null;
594
+ if (applied.beforeExists && !original)
595
+ return unresolved();
596
+ if (original && sha256(original) !== applied.beforeSha)
597
+ return unresolved();
598
+ const entry = readJournal(root).find(e => e.operation_id === applied.operationId);
599
+ restoreOriginal(abs, applied.beforeExists, original, entry?.mode);
600
+ updateRecoveryReceipt(root, applied.checkpointId, { phase: "rolled_back" });
601
+ updateEntry(root, applied.operationId, { status: "ROLLED_BACK", rolled_back_at: new Date().toISOString() });
602
+ if (applied.reverts) {
603
+ // Rolling back a revert puts the reverted change back in force.
604
+ updateEntry(root, applied.reverts, { status: "EXECUTED", reverted_by: undefined, rolled_back_at: undefined });
605
+ }
606
+ return true;
607
+ }
608
+ catch {
609
+ return unresolved();
610
+ } // A failed restore or bookkeeping update is never success.
611
+ }
612
+ /**
613
+ * The root of the repository an earlier change belonged to, or null.
614
+ *
615
+ * Null rather than a fallback on purpose: a checkpoint whose repository has
616
+ * left the registry must fail safely. Falling back to "wherever we are now"
617
+ * would restore one repository's bytes into another.
618
+ */
619
+ function repositoryRootById(id) {
620
+ return listRepositories().find((r) => r.id === id)?.root ?? null;
621
+ }
622
+ /**
623
+ * Is the reviewed diff still based on what is on disk?
624
+ *
625
+ * Re-validates the path (the workspace or a link could have changed while the
626
+ * user was reading the diff) and compares existence and full-byte hash with the
627
+ * bytes the diff was computed from. Throws STALE_FILE otherwise. applyPlan runs
628
+ * this immediately before writing; the coordinator also runs it for every member
629
+ * of an approved group before the first write, so a group whose files moved on
630
+ * is refused whole rather than partly applied and rolled back.
631
+ */
632
+ export function assertPlanCurrent(plan) {
633
+ resolveMutationTarget(plan.rel, plan.repositoryRoot);
634
+ const nowExists = fs.existsSync(plan.abs);
635
+ const nowSha = nowExists ? sha256(fs.readFileSync(plan.abs)) : null;
636
+ if (nowExists !== plan.beforeExists || nowSha !== plan.beforeSha) {
637
+ throw new MutationError("STALE_FILE", `${plan.rel} changed after the proposal was made. Nothing was written.`);
638
+ }
639
+ }
640
+ /**
641
+ * Safe, content-free description of the diff a person approved: the hunk
642
+ * ranges, counts and a hash of the exact unified text shown. Lets the audit
643
+ * record (which stores the applied result) correlate with the reviewed diff
644
+ * without duplicating source code.
645
+ */
646
+ export function reviewedDiffMetadata(plan) {
647
+ return {
648
+ diff_sha256: sha256(Buffer.from(plan.unified, "utf8")),
649
+ hunks: plan.diff.hunks.map((h) => ({ old_start: h.oldStart, old_lines: h.oldLines, new_start: h.newStart, new_lines: h.newLines })).slice(0, 50),
650
+ hunk_count: plan.diff.hunks.length
651
+ };
652
+ }
653
+ /** Metadata posted back to the server for an applied change — never content. */
654
+ export function appliedResult(a) {
655
+ return {
656
+ operation_id: a.operationId,
657
+ repository: a.repositoryName,
658
+ repository_id: a.repositoryId,
659
+ status: "EXECUTED",
660
+ action: a.name,
661
+ path: a.rel,
662
+ checkpoint_id: a.checkpointId,
663
+ before_exists: a.beforeExists,
664
+ after_exists: a.afterExists,
665
+ bytes_before: a.beforeBytes,
666
+ bytes_after: a.afterBytes,
667
+ sha_before: a.beforeSha,
668
+ sha_after: a.afterSha,
669
+ lines_added: a.added,
670
+ lines_removed: a.removed,
671
+ ...(a.symbol ? { symbol: a.symbol } : {}),
672
+ ...(a.review ? { reviewed_diff: a.review } : {}),
673
+ ...(a.reverts ? { reverted_operation_id: a.reverts } : {})
674
+ };
675
+ }
676
+ /** Diff lines a plan asks a person to read. */
677
+ export function reviewLineCount(plan) {
678
+ return plan.diff.hunks.reduce((n, h) => n + h.lines.length + 1, 0);
679
+ }