@carrieros/cli 0.3.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.
- package/README.md +34 -13
- package/dist/commands/chat.js +3 -3
- package/dist/commands/context.js +40 -0
- package/dist/commands/doctor.js +27 -12
- package/dist/commands/logout.js +1 -0
- package/dist/commands/permissions.js +77 -0
- package/dist/commands/scope.js +9 -6
- package/dist/commands/sessions.js +5 -0
- package/dist/commands/settings.js +8 -1
- package/dist/commands/update.js +79 -9
- package/dist/commands/usage.js +5 -5
- package/dist/commands/whoami.js +12 -9
- package/dist/ide/editor-context.js +115 -12
- package/dist/ide/ide-session.js +274 -13
- package/dist/ide/tool-host.js +2 -2
- package/dist/main.js +0 -0
- package/dist/services/api.js +178 -12
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/chat-stream.js +26 -3
- package/dist/services/checkpoints.js +176 -14
- package/dist/services/client-tools.js +113 -21
- package/dist/services/code-intel.js +243 -0
- package/dist/services/code-symbols.js +94 -0
- package/dist/services/coding-workflow.js +554 -0
- package/dist/services/command-coordinator.js +85 -12
- package/dist/services/command-policy.js +34 -4
- package/dist/services/config.js +67 -5
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +45 -17
- package/dist/services/device-auth.js +30 -5
- package/dist/services/execution-platform.js +30 -0
- package/dist/services/file-resolver.js +1 -1
- package/dist/services/folder-key.js +22 -0
- package/dist/services/git-tools.js +181 -0
- package/dist/services/helper-bin.js +56 -35
- package/dist/services/instruction-resolver.js +54 -0
- package/dist/services/job-helper.js +31 -10
- package/dist/services/local-files.js +148 -26
- package/dist/services/local-tools.js +540 -35
- package/dist/services/login-flow.js +43 -12
- package/dist/services/mutation-coordinator.js +186 -20
- package/dist/services/mutation-groups.js +309 -0
- package/dist/services/mutation-recovery.js +159 -0
- package/dist/services/mutations.js +264 -78
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +15 -0
- package/dist/services/permission-mode.js +60 -0
- package/dist/services/process-runner.js +7 -1
- package/dist/services/project-context.js +4 -4
- package/dist/services/result-reconciliation.js +49 -0
- package/dist/services/secure-store.js +21 -1
- package/dist/services/session-resolver.js +5 -0
- package/dist/services/supported-runtime.js +59 -0
- package/dist/services/task-context.js +212 -0
- package/dist/services/task-snapshot.js +38 -0
- package/dist/services/tool-result-outbox.js +195 -0
- package/dist/services/update.js +37 -12
- package/dist/services/workspace-registry.js +4 -3
- package/dist/services/workspace.js +8 -1
- package/dist/shell/shell-chat.js +299 -32
- package/dist/shell/shell-commands.js +46 -4
- package/dist/shell/shell-prompt.js +21 -11
- package/dist/shell/shell-renderer.js +1 -1
- package/dist/shell/shell.js +69 -7
- package/dist/shell/task-context-view.js +40 -0
- package/dist/ui/agent-cards.js +111 -0
- package/dist/ui/agent-presentation.js +131 -0
- package/dist/ui/approval.js +46 -16
- package/dist/ui/banner.js +31 -87
- package/dist/ui/change-review.js +293 -46
- package/dist/ui/chat-renderer.js +6 -6
- package/dist/ui/colors.js +9 -9
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-palette.js +27 -10
- package/dist/ui/command-registry.js +9 -2
- package/dist/ui/command-review.js +77 -28
- package/dist/ui/composer-layout.js +26 -20
- package/dist/ui/conversation.js +77 -25
- package/dist/ui/live.js +1 -1
- package/dist/ui/screen.js +19 -11
- package/dist/ui/select.js +6 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/trust.js +7 -12
- package/dist/ui/ui.js +23 -0
- package/package.json +8 -5
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import crypto from "node:crypto";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import { appendEntry, latestRevertible, repositoryKey, loadCheckpoint, newCheckpointId, saveCheckpoint, sha256, updateEntry } from "./checkpoints.js";
|
|
5
|
-
import { diffLines, formatUnified } from "./diff.js";
|
|
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";
|
|
6
7
|
import { LocalFileError, isInside, isPathIgnored, resolveInside } from "./local-files.js";
|
|
7
8
|
import { isSensitiveName } from "./local-tools.js";
|
|
8
9
|
import { activeRepository, isWildcardSelector, listRepositories, resolveOperableRepository } from "./workspace-registry.js";
|
|
@@ -38,9 +39,11 @@ export const APPROVAL_TIMEOUT_MS = 4 * 60 * 1000;
|
|
|
38
39
|
const EXTRA_PROTECTED = [/^secrets?(\..+)?$/i, /^\.git-credentials$/i, /^\.htpasswd$/i, /^authorized_keys$/i, /^known_hosts$/i];
|
|
39
40
|
export class MutationError extends Error {
|
|
40
41
|
code;
|
|
41
|
-
|
|
42
|
+
recovery;
|
|
43
|
+
constructor(code, message, recovery) {
|
|
42
44
|
super(message);
|
|
43
45
|
this.code = code;
|
|
46
|
+
this.recovery = recovery;
|
|
44
47
|
this.name = "MutationError";
|
|
45
48
|
}
|
|
46
49
|
}
|
|
@@ -61,7 +64,7 @@ function isBinary(buf) {
|
|
|
61
64
|
* is proven on the deepest ancestor that DOES exist — otherwise a junction
|
|
62
65
|
* directory inside the project would let a "new file" land outside it.
|
|
63
66
|
*/
|
|
64
|
-
function
|
|
67
|
+
export function resolveMutationTarget(input, root) {
|
|
65
68
|
const raw = str(input)?.trim();
|
|
66
69
|
if (!raw)
|
|
67
70
|
throw new MutationError("INVALID_TOOL_ARGUMENTS", '"path" is required.');
|
|
@@ -139,6 +142,16 @@ function countOccurrences(haystack, needle) {
|
|
|
139
142
|
from = i + needle.length;
|
|
140
143
|
}
|
|
141
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
|
+
}
|
|
142
155
|
/**
|
|
143
156
|
* Apply an edit's replacement deterministically, or refuse.
|
|
144
157
|
*
|
|
@@ -157,7 +170,8 @@ function applyEdit(original, oldStr, newStr, replaceAll, rel) {
|
|
|
157
170
|
}
|
|
158
171
|
return replaceAll ? original.split(o).join(n) : original.replace(o, () => n);
|
|
159
172
|
};
|
|
160
|
-
|
|
173
|
+
// A direct match in a CRLF file still writes its new lines as CRLF.
|
|
174
|
+
const direct = attempt(oldStr, matchLineEndings(original, newStr));
|
|
161
175
|
if (direct !== null)
|
|
162
176
|
return direct;
|
|
163
177
|
if (original.includes("\r\n") && !oldStr.includes("\r\n")) {
|
|
@@ -195,14 +209,52 @@ function finishPlan(p) {
|
|
|
195
209
|
const before = p.beforeBuf?.toString("utf8") ?? "";
|
|
196
210
|
const after = p.afterBuf?.toString("utf8") ?? "";
|
|
197
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 } : {};
|
|
198
216
|
return {
|
|
199
217
|
...p,
|
|
200
218
|
beforeSha: p.beforeBuf ? sha256(p.beforeBuf) : null,
|
|
201
219
|
afterSha: p.afterBuf ? sha256(p.afterBuf) : null,
|
|
202
220
|
diff,
|
|
203
|
-
unified: formatUnified(p.rel, diff, { oldExists: p.beforeExists, newExists: p.afterExists })
|
|
221
|
+
unified: formatUnified(p.rel, diff, { oldExists: p.beforeExists, newExists: p.afterExists }),
|
|
222
|
+
...where,
|
|
223
|
+
...lineEndings
|
|
204
224
|
};
|
|
205
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
|
+
}
|
|
206
258
|
/**
|
|
207
259
|
* Turn one proposal into a reviewable plan. Reads, never writes. Throws a
|
|
208
260
|
* MutationError with a code the model can act on for anything it refuses.
|
|
@@ -218,7 +270,7 @@ export function planMutation(call) {
|
|
|
218
270
|
// root every containment check runs against is a registry handle's root and
|
|
219
271
|
// never something derived from the path itself.
|
|
220
272
|
const repo = repositoryForChange(args.repository);
|
|
221
|
-
const root = repo.root;
|
|
273
|
+
const root = fs.realpathSync.native(repo.root);
|
|
222
274
|
const operationId = call.tool_call_id;
|
|
223
275
|
if (name === "revert_change") {
|
|
224
276
|
// Scoped to this repository's own journal: an operation id belonging to a
|
|
@@ -230,7 +282,7 @@ export function planMutation(call) {
|
|
|
230
282
|
? `No applied change with that id in ${repo.name}. A change is undone in the repository it was made in.`
|
|
231
283
|
: `There is no applied change to undo in ${repo.name}.`);
|
|
232
284
|
}
|
|
233
|
-
const { abs, rel } =
|
|
285
|
+
const { abs, rel } = resolveMutationTarget(target.path, root);
|
|
234
286
|
// Undo restores what was there BEFORE the change — but only if the file is
|
|
235
287
|
// still exactly what the change left. Anything else would clobber later work.
|
|
236
288
|
const nowExists = fs.existsSync(abs);
|
|
@@ -263,7 +315,7 @@ export function planMutation(call) {
|
|
|
263
315
|
beforeMode: target.mode
|
|
264
316
|
});
|
|
265
317
|
}
|
|
266
|
-
const { abs, rel } =
|
|
318
|
+
const { abs, rel } = resolveMutationTarget(args.path, root);
|
|
267
319
|
const exists = fs.existsSync(abs);
|
|
268
320
|
switch (name) {
|
|
269
321
|
case "create_file": {
|
|
@@ -283,7 +335,8 @@ export function planMutation(call) {
|
|
|
283
335
|
throw new MutationError("FILE_NOT_FOUND", `${rel} does not exist. Use create_file for a new file.`);
|
|
284
336
|
checkWriteSize(content);
|
|
285
337
|
const { buf, mode } = readExisting(abs, rel);
|
|
286
|
-
|
|
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") });
|
|
287
340
|
}
|
|
288
341
|
case "edit_file": {
|
|
289
342
|
const oldStr = str(args.old_string);
|
|
@@ -304,12 +357,12 @@ export function planMutation(call) {
|
|
|
304
357
|
throw new MutationError("UNKNOWN_CLIENT_TOOL", `No local tool named "${call.name}".`);
|
|
305
358
|
}
|
|
306
359
|
/** Write bytes via a temp file in the same directory, then rename over the target. */
|
|
307
|
-
function atomicWrite(abs, buf, mode) {
|
|
360
|
+
function atomicWrite(abs, buf, mode, signal) {
|
|
308
361
|
const dir = path.dirname(abs);
|
|
309
362
|
const tmp = path.join(dir, `.${path.basename(abs)}.cos-${crypto.randomBytes(4).toString("hex")}.tmp`);
|
|
310
363
|
fs.writeFileSync(tmp, buf, mode ? { mode: mode & 0o777 } : undefined);
|
|
311
364
|
try {
|
|
312
|
-
|
|
365
|
+
renameWithRetry(tmp, abs, { signal });
|
|
313
366
|
}
|
|
314
367
|
catch (err) {
|
|
315
368
|
try {
|
|
@@ -321,29 +374,98 @@ function atomicWrite(abs, buf, mode) {
|
|
|
321
374
|
throw err;
|
|
322
375
|
}
|
|
323
376
|
}
|
|
324
|
-
/**
|
|
325
|
-
*
|
|
326
|
-
|
|
327
|
-
* verifies the result. On a failure after the write began, the original is put
|
|
328
|
-
* back before the error propagates.
|
|
329
|
-
*/
|
|
330
|
-
export function applyPlan(plan) {
|
|
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) {
|
|
331
380
|
const root = plan.repositoryRoot;
|
|
332
|
-
//
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
if (
|
|
338
|
-
throw new MutationError("
|
|
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.");
|
|
339
388
|
}
|
|
389
|
+
// A corrupt journal is not an empty history. Fail before touching the file.
|
|
390
|
+
readJournal(root);
|
|
340
391
|
const checkpointId = newCheckpointId();
|
|
341
392
|
try {
|
|
342
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
|
+
});
|
|
343
402
|
}
|
|
344
403
|
catch {
|
|
345
404
|
throw new MutationError("CHECKPOINT_FAILED", `Could not save a checkpoint for ${plan.rel}. Nothing was written.`);
|
|
346
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
|
+
};
|
|
347
469
|
try {
|
|
348
470
|
if (plan.afterExists && plan.afterBuf) {
|
|
349
471
|
if (!plan.beforeExists) {
|
|
@@ -354,21 +476,20 @@ export function applyPlan(plan) {
|
|
|
354
476
|
throw new MutationError("OUTSIDE_WORKSPACE", `${plan.rel} resolved outside the project.`);
|
|
355
477
|
}
|
|
356
478
|
}
|
|
357
|
-
atomicWrite(plan.abs, plan.afterBuf, plan.beforeMode);
|
|
479
|
+
atomicWrite(plan.abs, plan.afterBuf, plan.beforeMode, signal);
|
|
358
480
|
}
|
|
359
481
|
else {
|
|
360
482
|
fs.unlinkSync(plan.abs);
|
|
361
483
|
}
|
|
484
|
+
updateRecoveryReceipt(root, checkpointId, { phase: "applied" });
|
|
362
485
|
const verifySha = fs.existsSync(plan.abs) ? sha256(fs.readFileSync(plan.abs)) : null;
|
|
363
486
|
if (verifySha !== plan.afterSha) {
|
|
364
487
|
throw new MutationError("WRITE_FAILED", `${plan.rel} did not end up with the approved content.`);
|
|
365
488
|
}
|
|
489
|
+
updateRecoveryReceipt(root, checkpointId, { phase: "verified" });
|
|
366
490
|
}
|
|
367
491
|
catch (err) {
|
|
368
|
-
|
|
369
|
-
if (err instanceof MutationError)
|
|
370
|
-
throw err;
|
|
371
|
-
throw new MutationError("WRITE_FAILED", `Could not write ${plan.rel}: ${err.message}`);
|
|
492
|
+
return recoverFailure(err instanceof MutationError ? err.code : "WRITE_FAILED");
|
|
372
493
|
}
|
|
373
494
|
const applied = {
|
|
374
495
|
operationId: plan.operationId,
|
|
@@ -385,48 +506,64 @@ export function applyPlan(plan) {
|
|
|
385
506
|
afterBytes: plan.afterBuf?.length ?? 0,
|
|
386
507
|
added: plan.diff.added,
|
|
387
508
|
removed: plan.diff.removed,
|
|
509
|
+
...(plan.symbol ? { symbol: plan.symbol } : {}),
|
|
510
|
+
review: reviewedDiffMetadata(plan),
|
|
388
511
|
...(plan.reverts ? { reverts: plan.reverts } : {})
|
|
389
512
|
};
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
updateEntry(root, plan.reverts, {
|
|
414
|
-
status: "ROLLED_BACK",
|
|
415
|
-
reverted_by: plan.operationId,
|
|
416
|
-
rolled_back_at: new Date().toISOString()
|
|
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 } : {})
|
|
417
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");
|
|
418
553
|
}
|
|
419
554
|
return applied;
|
|
420
555
|
}
|
|
421
556
|
function restoreOriginal(abs, existed, buf, mode) {
|
|
422
|
-
|
|
423
|
-
if (
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
fs.unlinkSync(abs);
|
|
557
|
+
if (existed) {
|
|
558
|
+
if (buf === null)
|
|
559
|
+
throw new Error("Missing original checkpoint");
|
|
560
|
+
atomicWrite(abs, buf, mode);
|
|
427
561
|
}
|
|
428
|
-
|
|
429
|
-
|
|
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");
|
|
430
567
|
}
|
|
431
568
|
}
|
|
432
569
|
/**
|
|
@@ -440,21 +577,37 @@ export function rollbackApplied(applied) {
|
|
|
440
577
|
// restore into, and guessing one would write another repository's file.
|
|
441
578
|
if (!root)
|
|
442
579
|
return false;
|
|
443
|
-
const
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
const original = applied.beforeExists ? loadCheckpoint(root, applied.checkpointId) : null;
|
|
449
|
-
if (applied.beforeExists && !original)
|
|
580
|
+
const unresolved = () => {
|
|
581
|
+
try {
|
|
582
|
+
updateRecoveryReceipt(root, applied.checkpointId, { phase: "unresolved" });
|
|
583
|
+
}
|
|
584
|
+
catch { /* retain existing evidence when the receipt cannot be updated */ }
|
|
450
585
|
return false;
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
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;
|
|
456
607
|
}
|
|
457
|
-
|
|
608
|
+
catch {
|
|
609
|
+
return unresolved();
|
|
610
|
+
} // A failed restore or bookkeeping update is never success.
|
|
458
611
|
}
|
|
459
612
|
/**
|
|
460
613
|
* The root of the repository an earlier change belonged to, or null.
|
|
@@ -466,6 +619,37 @@ export function rollbackApplied(applied) {
|
|
|
466
619
|
function repositoryRootById(id) {
|
|
467
620
|
return listRepositories().find((r) => r.id === id)?.root ?? null;
|
|
468
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
|
+
}
|
|
469
653
|
/** Metadata posted back to the server for an applied change — never content. */
|
|
470
654
|
export function appliedResult(a) {
|
|
471
655
|
return {
|
|
@@ -484,6 +668,8 @@ export function appliedResult(a) {
|
|
|
484
668
|
sha_after: a.afterSha,
|
|
485
669
|
lines_added: a.added,
|
|
486
670
|
lines_removed: a.removed,
|
|
671
|
+
...(a.symbol ? { symbol: a.symbol } : {}),
|
|
672
|
+
...(a.review ? { reviewed_diff: a.review } : {}),
|
|
487
673
|
...(a.reverts ? { reverted_operation_id: a.reverts } : {})
|
|
488
674
|
};
|
|
489
675
|
}
|