@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,168 @@
1
+ /** Thrown for every way a stream can end other than `complete`. */
2
+ /**
3
+ * The server's structured provider-failure reasons (`reason` on a stream
4
+ * `error`), so a surface can tell them apart without reading the message.
5
+ * Anything else the server sends is dropped, never shown.
6
+ */
7
+ export const PROVIDER_ERROR_REASONS = {
8
+ rate_limited: "Rate limited",
9
+ quota_daily: "Quota exhausted",
10
+ provider_credits: "Credits exhausted",
11
+ provider_request_failed: "Provider error",
12
+ provider_config: "Configuration error",
13
+ provider_auth: "Authentication error"
14
+ };
15
+ export function providerErrorReason(value) {
16
+ return typeof value === "string" && Object.hasOwn(PROVIDER_ERROR_REASONS, value) ? value : undefined;
17
+ }
18
+ export class StreamError extends Error {
19
+ code;
20
+ status;
21
+ reason;
22
+ constructor(code, message, status = 0, reason) {
23
+ super(message);
24
+ this.code = code;
25
+ this.status = status;
26
+ this.reason = reason;
27
+ this.name = "StreamError";
28
+ }
29
+ }
30
+ /** Map the server's `complete` payload onto the synchronous endpoint's shape. */
31
+ export function completeToResult(d) {
32
+ return {
33
+ id: d.message_id ?? null,
34
+ response: typeof d.content === "string" ? d.content : "",
35
+ session_id: d.session_id,
36
+ tokens_used: Number(d.tokens_used ?? 0) || 0,
37
+ cost_usd: typeof d.cost_usd === "number" ? d.cost_usd : undefined,
38
+ credits_remaining: typeof d.credits_remaining === "number" ? d.credits_remaining : null,
39
+ credits_unlimited: typeof d.credits_unlimited === "boolean" ? d.credits_unlimited : null,
40
+ credits_spent: typeof d.credits_spent === "number" ? d.credits_spent : null,
41
+ sources: Array.isArray(d.sources) ? d.sources : [],
42
+ web_search_used: d.web_search_used === true,
43
+ high_power_used: d.high_power_used === true,
44
+ speed: d.speed === "fast" ? "fast" : d.speed === "standard" ? "standard" : undefined,
45
+ model: typeof d.model === "string" ? d.model : undefined
46
+ };
47
+ }
48
+ /**
49
+ * Consume an SSE body until `complete`, `error`, `interrupted` or the socket
50
+ * ends. Frames are `data: {"type":…,"data":…}` separated by a blank line;
51
+ * `: ping` comments and the `[DONE]` sentinel carry nothing.
52
+ */
53
+ export function consumeChatStream(body, handlers = {}, signal) {
54
+ return new Promise((resolve, reject) => {
55
+ let buffer = "";
56
+ let settled = false;
57
+ const finish = (fn) => {
58
+ if (settled)
59
+ return;
60
+ settled = true;
61
+ signal?.removeEventListener?.("abort", onAbort);
62
+ fn();
63
+ };
64
+ function onAbort() {
65
+ finish(() => reject(new StreamError("ABORTED", "Interrupted.")));
66
+ try {
67
+ body.destroy?.();
68
+ }
69
+ catch {
70
+ /* already closed */
71
+ }
72
+ }
73
+ if (signal?.aborted) {
74
+ onAbort();
75
+ return;
76
+ }
77
+ signal?.addEventListener?.("abort", onAbort, { once: true });
78
+ const dispatch = (type, data) => {
79
+ switch (type) {
80
+ case "message_created":
81
+ handlers.onMessageCreated?.(data);
82
+ return;
83
+ case "chunk":
84
+ if (typeof data.delta === "string" && data.delta)
85
+ handlers.onDelta?.(data.delta);
86
+ return;
87
+ case "status":
88
+ case "tool_status":
89
+ if (typeof data.message === "string")
90
+ handlers.onStatus?.(type, data.message);
91
+ return;
92
+ case "client_tool_call": {
93
+ if (!handlers.onClientToolCall)
94
+ return;
95
+ // Never let a tool handler's failure — or its duration — stall the
96
+ // parser: the server keeps streaming while it waits for the result.
97
+ void Promise.resolve()
98
+ .then(() => handlers.onClientToolCall(data))
99
+ .catch((error) => {
100
+ if (error?.code === "TOOL_RESULT_DELIVERY_FAILED") {
101
+ finish(() => reject(new StreamError("TOOL_RESULT_DELIVERY_FAILED", "Tool result delivery failed. Saved results will be retried before the next chat; tools are not rerun.")));
102
+ body.destroy?.();
103
+ }
104
+ });
105
+ return;
106
+ }
107
+ case "complete":
108
+ finish(() => resolve(completeToResult(data)));
109
+ return;
110
+ case "interrupted":
111
+ finish(() => reject(signal?.aborted
112
+ ? new StreamError("ABORTED", "Interrupted.")
113
+ : new StreamError("INTERRUPTED", "The response was interrupted before it finished.")));
114
+ return;
115
+ case "error":
116
+ finish(() => reject(new StreamError(typeof data.code === "string" ? data.code : "STREAM_ERROR", typeof data.message === "string" ? data.message : "The response failed.", 0, providerErrorReason(data.reason))));
117
+ return;
118
+ default:
119
+ return; // generation_type and anything newer: nothing to do
120
+ }
121
+ };
122
+ const drain = () => {
123
+ buffer = buffer.replace(/\r\n/g, "\n");
124
+ let sep = buffer.indexOf("\n\n");
125
+ while (sep !== -1) {
126
+ const block = buffer.slice(0, sep);
127
+ buffer = buffer.slice(sep + 2);
128
+ const payload = block
129
+ .split("\n")
130
+ .filter((l) => l.startsWith("data:"))
131
+ .map((l) => l.slice(5).replace(/^ /, ""))
132
+ .join("\n");
133
+ if (payload && payload !== "[DONE]") {
134
+ try {
135
+ const frame = JSON.parse(payload);
136
+ if (frame?.type)
137
+ dispatch(frame.type, frame.data ?? {});
138
+ }
139
+ catch {
140
+ /* a malformed frame is skipped, never fatal */
141
+ }
142
+ }
143
+ if (settled)
144
+ return;
145
+ sep = buffer.indexOf("\n\n");
146
+ }
147
+ };
148
+ body.setEncoding?.("utf8");
149
+ body.on("data", (chunk) => {
150
+ if (settled)
151
+ return;
152
+ buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
153
+ drain();
154
+ });
155
+ body.on("end", () => {
156
+ if (settled)
157
+ return;
158
+ buffer += "\n\n";
159
+ drain();
160
+ finish(() => reject(new StreamError("STREAM_ENDED", "The connection closed before the response finished.")));
161
+ });
162
+ body.on("error", () => {
163
+ finish(() => reject(signal?.aborted
164
+ ? new StreamError("ABORTED", "Interrupted.")
165
+ : new StreamError("NETWORK_ERROR", "The connection to the API dropped mid-response.")));
166
+ });
167
+ });
168
+ }
@@ -0,0 +1,278 @@
1
+ import { folderKey } from "./folder-key.js";
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { ConfigStore } from "./config.js";
6
+ /**
7
+ * Checkpoints and the change journal for supervised file edits.
8
+ *
9
+ * Kept in the CLI's own app-data folder, per workspace — never inside the
10
+ * repository. A change can be undone whether or not the file was ever committed,
11
+ * nothing ends up in `git status`, and Git is not a dependency of the safety
12
+ * net. This is not a version-control system: it keeps enough to restore the
13
+ * last few approved changes, and prunes the rest.
14
+ *
15
+ * What a checkpoint holds is the ORIGINAL bytes of one file, plus whether it
16
+ * existed and its mode. That is the only file content the CLI ever retains, it
17
+ * stays on the machine, and credential files never get one because they are
18
+ * refused before a change is planned.
19
+ */
20
+ /** Changes remembered per workspace; older checkpoints are deleted. */
21
+ const MAX_ENTRIES = 50;
22
+ export const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("hex");
23
+ /**
24
+ * The identity of a repository's checkpoint store: a hash of its normalized
25
+ * root. Exported so a journal entry can record which store it was written to,
26
+ * and an undo can prove it is reading the right one.
27
+ */
28
+ export function repositoryKey(root) {
29
+ // Canonical (real path, case-folded on Windows): a repository opened through a
30
+ // symlink must find the same evidence its changes wrote. Unchanged for any
31
+ // root whose resolved path is already its real path.
32
+ return sha256(folderKey(root)).slice(0, 16);
33
+ }
34
+ /** One directory per repository root, keyed by a hash of its normalized path. */
35
+ export function workspaceDir(root) {
36
+ const dir = path.join(ConfigStore.resolveDir(), "checkpoints", repositoryKey(root));
37
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
38
+ return dir;
39
+ }
40
+ const journalFile = (root) => path.join(workspaceDir(root), "journal.json");
41
+ export class RecoveryStateError extends Error {
42
+ constructor(message = "Recovery state is unreadable or inconsistent. Existing evidence was preserved.") {
43
+ super(message);
44
+ this.name = "RecoveryStateError";
45
+ }
46
+ }
47
+ /** Waits between rename attempts while a Windows scanner or editor holds the target. */
48
+ export const RENAME_RETRY_DELAYS_MS = [10, 20, 40, 80];
49
+ const LOCKED = new Set(["EPERM", "EBUSY", "EACCES"]);
50
+ /**
51
+ * renameSync that tolerates a transient Windows sharing lock (antivirus, the
52
+ * search indexer, an editor): EPERM/EBUSY/EACCES are retried a bounded number
53
+ * of times with a short backoff — on Windows only, where those codes mean a
54
+ * lock rather than a permission. Cancellation stops the retries. When they run
55
+ * out, the ORIGINAL error is thrown, so callers fail exactly as before.
56
+ */
57
+ export function renameWithRetry(from, to, opts = {}) {
58
+ const rename = opts.rename ?? fs.renameSync;
59
+ const wait = opts.wait ?? ((ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms));
60
+ const retries = (opts.platform ?? process.platform) === "win32" ? RENAME_RETRY_DELAYS_MS : [];
61
+ for (let attempt = 0;; attempt++) {
62
+ try {
63
+ rename(from, to);
64
+ return;
65
+ }
66
+ catch (err) {
67
+ const code = err.code ?? "";
68
+ if (!LOCKED.has(code) || attempt >= retries.length || opts.signal?.aborted)
69
+ throw err;
70
+ wait(retries[attempt]);
71
+ }
72
+ }
73
+ }
74
+ /** Atomic publication with file fsync; directory fsync where supported. */
75
+ export function durableWrite(file, data) {
76
+ const tmp = `${file}.${crypto.randomBytes(8).toString("hex")}.tmp`;
77
+ try {
78
+ const fd = fs.openSync(tmp, "wx", 0o600);
79
+ try {
80
+ fs.writeFileSync(fd, data);
81
+ fs.fsyncSync(fd);
82
+ }
83
+ finally {
84
+ fs.closeSync(fd);
85
+ }
86
+ renameWithRetry(tmp, file);
87
+ if (process.platform !== "win32") {
88
+ const dir = fs.openSync(path.dirname(file), "r");
89
+ try {
90
+ fs.fsyncSync(dir);
91
+ }
92
+ finally {
93
+ fs.closeSync(dir);
94
+ }
95
+ }
96
+ }
97
+ finally {
98
+ try {
99
+ fs.unlinkSync(tmp);
100
+ }
101
+ catch { /* absent after publication */ }
102
+ }
103
+ }
104
+ export function readJournal(root) {
105
+ try {
106
+ const file = journalFile(root);
107
+ if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 2 * 1024 * 1024)
108
+ throw new RecoveryStateError();
109
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
110
+ if (!Array.isArray(parsed) || parsed.some(e => !e || typeof e.operation_id !== "string" ||
111
+ typeof e.path !== "string" || typeof e.checkpoint_id !== "string" ||
112
+ !["EXECUTED", "ROLLED_BACK", "FAILED"].includes(e.status)) ||
113
+ new Set(parsed.map(e => e.operation_id)).size !== parsed.length)
114
+ throw new RecoveryStateError();
115
+ return parsed;
116
+ }
117
+ catch (err) {
118
+ if (err.code === "ENOENT")
119
+ return [];
120
+ throw new RecoveryStateError("Mutation journal is unreadable. It was preserved; history cannot be replaced or assumed empty.");
121
+ }
122
+ }
123
+ function writeJournal(root, entries) {
124
+ durableWrite(journalFile(root), JSON.stringify(entries, null, 2));
125
+ }
126
+ export function newCheckpointId() {
127
+ return `cp_${Date.now().toString(36)}_${crypto.randomBytes(6).toString("hex")}`;
128
+ }
129
+ /** Save a file's original bytes before it is changed. */
130
+ export function saveCheckpoint(root, checkpointId, original) {
131
+ if (original === null)
132
+ return; // nothing existed — undo means delete
133
+ const file = path.join(workspaceDir(root), `${checkpointId}.before`);
134
+ durableWrite(file, original);
135
+ }
136
+ export function loadCheckpoint(root, checkpointId) {
137
+ try {
138
+ if (!/^cp_[a-z0-9]+_[a-f0-9]+$/.test(checkpointId))
139
+ return null;
140
+ const file = path.join(workspaceDir(root), `${checkpointId}.before`);
141
+ if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 1024 * 1024)
142
+ return null;
143
+ return fs.readFileSync(file);
144
+ }
145
+ catch {
146
+ return null;
147
+ }
148
+ }
149
+ export function saveRecoveryReceipt(root, checkpointId, metadata) {
150
+ const file = path.join(workspaceDir(root), `${checkpointId}.recovery.json`);
151
+ if (fs.existsSync(file))
152
+ throw new RecoveryStateError();
153
+ durableWrite(file, JSON.stringify({ ...metadata, checkpoint_id: checkpointId, repository_key: repositoryKey(root) }));
154
+ }
155
+ export const MAX_RECOVERY_SCAN = 100;
156
+ export function recoveryReceipts(root) {
157
+ const receipts = [];
158
+ let problems = 0;
159
+ const dir = workspaceDir(root);
160
+ const names = [];
161
+ // Bound directory traversal, not only the number of parsed JSON records.
162
+ let visited = 0, bounded = false;
163
+ const directory = fs.opendirSync(dir);
164
+ try {
165
+ let entry;
166
+ while ((entry = directory.readSync()) !== null) {
167
+ if (++visited > MAX_RECOVERY_SCAN * 4) {
168
+ bounded = true;
169
+ break;
170
+ }
171
+ if (entry.name.endsWith(".recovery.json"))
172
+ names.push(entry.name);
173
+ }
174
+ }
175
+ finally {
176
+ directory.closeSync();
177
+ }
178
+ if (names.length > MAX_RECOVERY_SCAN)
179
+ bounded = true;
180
+ for (const name of names.slice(0, MAX_RECOVERY_SCAN)) {
181
+ try {
182
+ const file = path.join(dir, name);
183
+ if (fs.lstatSync(file).isSymbolicLink() || fs.statSync(file).size > 64 * 1024)
184
+ throw new RecoveryStateError();
185
+ const r = JSON.parse(fs.readFileSync(file, "utf8"));
186
+ const hashValid = (exists, hash) => typeof exists === "boolean" &&
187
+ (exists ? typeof hash === "string" && /^[a-f0-9]{64}$/.test(hash) : hash === null);
188
+ if ((r.group_id !== undefined && !/^grp_[a-f0-9]{32}$/.test(r.group_id)) ||
189
+ r.version !== 2 || r.approved !== true || r.repository_key !== repositoryKey(root) ||
190
+ typeof r.operation_id !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(r.operation_id) || typeof r.repository_id !== "string" ||
191
+ typeof r.repository_name !== "string" || typeof r.path !== "string" ||
192
+ !/^cp_[a-z0-9]+_[a-f0-9]+$/.test(r.checkpoint_id) || name !== `${r.checkpoint_id}.recovery.json` ||
193
+ !["create_file", "write_file", "edit_file", "delete_file", "revert_change"].includes(r.action) ||
194
+ !["prepared", "applied", "verified", "rolled_back", "unresolved"].includes(r.phase) ||
195
+ !["none", "ready", "queued", "acknowledged", "rejected"].includes(r.delivery) ||
196
+ typeof r.journal_persisted !== "boolean" || !Number.isFinite(Date.parse(r.created_at)) ||
197
+ !hashValid(r.before_exists, r.before_sha) || !hashValid(r.after_exists, r.after_sha) ||
198
+ (r.scope !== undefined && !/^[a-f0-9]{64}$/.test(r.scope)) ||
199
+ (r.result && (r.result.tool_call_id !== r.operation_id || typeof r.result.ok !== "boolean")) ||
200
+ (r.delivery !== "none" && !r.result))
201
+ throw new RecoveryStateError();
202
+ receipts.push(r);
203
+ }
204
+ catch {
205
+ problems++;
206
+ } // No content, malformed paths or credentials in diagnostics.
207
+ }
208
+ const counts = new Map();
209
+ for (const r of receipts)
210
+ counts.set(r.operation_id, (counts.get(r.operation_id) ?? 0) + 1);
211
+ return { receipts: receipts.filter(r => {
212
+ if (counts.get(r.operation_id) > 1) {
213
+ problems++;
214
+ return false;
215
+ }
216
+ return true;
217
+ }), problems, bounded };
218
+ }
219
+ export function updateRecoveryReceipt(root, checkpointId, patch) {
220
+ const scan = recoveryReceipts(root);
221
+ const r = scan.receipts.find(e => e.checkpoint_id === checkpointId);
222
+ if (!r)
223
+ throw new RecoveryStateError();
224
+ if (r.result && patch.result && JSON.stringify(r.result) !== JSON.stringify(patch.result))
225
+ throw new RecoveryStateError();
226
+ durableWrite(path.join(workspaceDir(root), `${checkpointId}.recovery.json`), JSON.stringify({ ...r, ...patch }));
227
+ }
228
+ /** Append an entry and prune the oldest beyond MAX_ENTRIES, deleting their checkpoints. */
229
+ export function appendEntry(root, entry) {
230
+ const entries = [...readJournal(root), entry];
231
+ const dropped = entries.length > MAX_ENTRIES ? entries.splice(0, entries.length - MAX_ENTRIES) : [];
232
+ writeJournal(root, entries);
233
+ for (const d of dropped) {
234
+ try {
235
+ const receipt = recoveryReceipts(root).receipts.find(r => r.checkpoint_id === d.checkpoint_id);
236
+ if (!receipt || receipt.group_id || !receipt.journal_persisted || !["verified", "rolled_back"].includes(receipt.phase) ||
237
+ (receipt.scope && !["acknowledged", "rejected"].includes(receipt.delivery)))
238
+ continue;
239
+ fs.rmSync(path.join(workspaceDir(root), `${d.checkpoint_id}.before`), { force: true });
240
+ fs.rmSync(path.join(workspaceDir(root), `${d.checkpoint_id}.recovery.json`), { force: true });
241
+ }
242
+ catch {
243
+ /* already gone */
244
+ }
245
+ }
246
+ }
247
+ export function updateEntry(root, operationId, patch) {
248
+ const entries = readJournal(root);
249
+ const i = entries.findIndex((e) => e.operation_id === operationId);
250
+ if (i === -1)
251
+ return;
252
+ entries[i] = { ...entries[i], ...patch };
253
+ writeJournal(root, entries);
254
+ }
255
+ /**
256
+ * The change `/undo` (or `revert_change` without an id) should undo: the most
257
+ * recent applied change that has not already been undone. Reverts are skipped,
258
+ * so undoing twice walks back two changes rather than toggling one.
259
+ */
260
+ export function latestRevertible(root, operationId, repositoryId) {
261
+ const key = repositoryKey(root);
262
+ // An entry has to belong to THIS repository's store. Entries written before
263
+ // repository identity existed carry neither field and are accepted on the
264
+ // strength of the directory they were found in; anything that names a
265
+ // different repository is refused rather than restored.
266
+ const mine = (e) => (e.repository_key === undefined || e.repository_key === key) &&
267
+ (repositoryId === undefined || e.repository_id === undefined || e.repository_id === repositoryId);
268
+ const entries = readJournal(root).filter(mine);
269
+ if (operationId) {
270
+ return entries.find((e) => e.operation_id === operationId && e.status === "EXECUTED" && !e.reverts) ?? null;
271
+ }
272
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
273
+ const e = entries[i];
274
+ if (e.status === "EXECUTED" && !e.reverts)
275
+ return e;
276
+ }
277
+ return null;
278
+ }