@carrieros/cli 0.3.0 → 0.4.1
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 +89 -15
- package/dist/commands/chat.js +6 -6
- package/dist/commands/context.js +40 -0
- package/dist/commands/doctor.js +34 -14
- package/dist/commands/logout.js +2 -0
- package/dist/commands/permissions.js +78 -0
- package/dist/commands/scope.js +9 -6
- package/dist/commands/sessions.js +5 -0
- package/dist/commands/settings.js +83 -10
- package/dist/commands/update.js +177 -51
- package/dist/commands/usage.js +10 -8
- package/dist/commands/version.js +1 -3
- package/dist/commands/whoami.js +12 -9
- package/dist/ide/editor-context.js +115 -12
- package/dist/ide/ide-session.js +288 -18
- package/dist/ide/tool-host.js +6 -6
- package/dist/main.js +10 -1
- package/dist/services/api.js +183 -15
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/auto-update.js +221 -0
- package/dist/services/chat-stream.js +26 -3
- package/dist/services/checkpoints.js +176 -14
- package/dist/services/client-tools.js +123 -27
- 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 +96 -11
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +98 -25
- package/dist/services/device-auth.js +33 -6
- 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 +44 -13
- package/dist/services/meta.js +27 -0
- 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 +78 -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 +7 -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 +457 -13
- package/dist/services/workspace-registry.js +4 -3
- package/dist/services/workspace.js +8 -1
- package/dist/shell/shell-chat.js +320 -34
- package/dist/shell/shell-commands.js +47 -5
- package/dist/shell/shell-prompt.js +21 -11
- package/dist/shell/shell-renderer.js +1 -1
- package/dist/shell/shell.js +107 -20
- 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 +11 -4
- 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 +9 -5
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { durableWrite, readJournal, recoveryReceipts, repositoryKey, workspaceDir } from "./checkpoints.js";
|
|
5
|
+
import { MAX_FILES_PER_APPROVAL, MUTATION_TOOL_NAMES, prepareMutation } from "./mutations.js";
|
|
6
|
+
import { reconcileMutations } from "./mutation-recovery.js";
|
|
7
|
+
import { listRepositories, repositoryTrust } from "./workspace-registry.js";
|
|
8
|
+
import { folderKey } from "./folder-key.js";
|
|
9
|
+
const GROUP_STATES = ["CREATED", "APPLYING", "PARTIALLY_APPLIED", "COMPLETED", "FAILED", "CONFLICT", "ROLLED_BACK", "UNRESOLVED"];
|
|
10
|
+
const MEMBER_STATES = ["NOT_STARTED", "APPLYING", "NOT_APPLIED", "APPLIED", "COMPLETED", "FAILED", "CONFLICT", "ROLLED_BACK", "UNRESOLVED"];
|
|
11
|
+
const MAX_GROUPS = 50;
|
|
12
|
+
const validId = (id) => typeof id === "string" && /^grp_[a-f0-9]{32}$/.test(id);
|
|
13
|
+
export class GroupStateError extends Error {
|
|
14
|
+
constructor() { super("Group recovery state could not be verified or persisted. Existing evidence was preserved."); }
|
|
15
|
+
}
|
|
16
|
+
function directory(root) {
|
|
17
|
+
const dir = path.join(workspaceDir(root), "groups");
|
|
18
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
19
|
+
if (fs.lstatSync(dir).isSymbolicLink())
|
|
20
|
+
throw new GroupStateError();
|
|
21
|
+
return dir;
|
|
22
|
+
}
|
|
23
|
+
function file(root, id) {
|
|
24
|
+
if (!validId(id))
|
|
25
|
+
throw new GroupStateError();
|
|
26
|
+
return path.join(directory(root), `${id}.json`);
|
|
27
|
+
}
|
|
28
|
+
function read(root, id) {
|
|
29
|
+
try {
|
|
30
|
+
const name = file(root, id), stat = fs.lstatSync(name);
|
|
31
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024)
|
|
32
|
+
throw new GroupStateError();
|
|
33
|
+
const g = JSON.parse(fs.readFileSync(name, "utf8"));
|
|
34
|
+
if (g.version !== 1 || g.group_id !== id || g.repository_key !== repositoryKey(root) ||
|
|
35
|
+
typeof g.repository_id !== "string" || !g.repository_id || !GROUP_STATES.includes(g.state) ||
|
|
36
|
+
!Number.isFinite(Date.parse(g.created_at)) || !Number.isFinite(Date.parse(g.updated_at)) ||
|
|
37
|
+
(g.scope !== undefined && !/^[a-f0-9]{64}$/.test(g.scope)) ||
|
|
38
|
+
!Array.isArray(g.members) || g.members.length < 2 || g.members.length > MAX_FILES_PER_APPROVAL ||
|
|
39
|
+
g.members.some(m => !m || typeof m.operation_id !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(m.operation_id) ||
|
|
40
|
+
!/^cp_[a-z0-9]+_[a-f0-9]+$/.test(m.checkpoint_id) || typeof m.path !== "string" ||
|
|
41
|
+
!m.path || m.path.length > 4096 || !MUTATION_TOOL_NAMES.includes(m.action) ||
|
|
42
|
+
typeof m.started !== "boolean" || typeof m.failed !== "boolean" || !MEMBER_STATES.includes(m.state)) ||
|
|
43
|
+
new Set(g.members.map(m => m.operation_id)).size !== g.members.length ||
|
|
44
|
+
new Set(g.members.map(m => m.checkpoint_id)).size !== g.members.length ||
|
|
45
|
+
new Set(g.members.map(m => m.path.toLowerCase())).size !== g.members.length)
|
|
46
|
+
throw new GroupStateError();
|
|
47
|
+
return g;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
throw new GroupStateError();
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export function readMutationGroups(root) {
|
|
54
|
+
const groups = [];
|
|
55
|
+
let problems = 0, bounded = false, visited = 0;
|
|
56
|
+
const dir = directory(root), handle = fs.opendirSync(dir);
|
|
57
|
+
try {
|
|
58
|
+
let entry;
|
|
59
|
+
while ((entry = handle.readSync()) !== null) {
|
|
60
|
+
if (++visited > MAX_GROUPS * 4) {
|
|
61
|
+
bounded = true;
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
if (!entry.name.endsWith(".json"))
|
|
65
|
+
continue;
|
|
66
|
+
if (groups.length >= MAX_GROUPS) {
|
|
67
|
+
bounded = true;
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
groups.push(read(root, entry.name.slice(0, -5)));
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
problems++;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
handle.closeSync();
|
|
80
|
+
}
|
|
81
|
+
return { groups, problems, bounded };
|
|
82
|
+
}
|
|
83
|
+
function publish(root, group) {
|
|
84
|
+
try {
|
|
85
|
+
durableWrite(file(root, group.group_id), JSON.stringify(group));
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
throw new GroupStateError();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** Called only for the exact approved batch, before any target file is changed. */
|
|
92
|
+
export function createMutationGroup(plans, scope) {
|
|
93
|
+
if (plans.length < 2 || plans.length > MAX_FILES_PER_APPROVAL ||
|
|
94
|
+
plans.some(p => p.repositoryId !== plans[0].repositoryId || p.repositoryRoot !== plans[0].repositoryRoot) ||
|
|
95
|
+
new Set(plans.map(p => p.operationId)).size !== plans.length ||
|
|
96
|
+
new Set(plans.map(p => p.rel.toLowerCase())).size !== plans.length)
|
|
97
|
+
throw new GroupStateError();
|
|
98
|
+
const root = plans[0].repositoryRoot;
|
|
99
|
+
// Same repository id AND the same folder on disk: a plan records its root's
|
|
100
|
+
// real path, the registry keeps the spelling it was opened with (/var vs /private/var).
|
|
101
|
+
const repo = listRepositories().find(r => r.id === plans[0].repositoryId && folderKey(r.root) === folderKey(root));
|
|
102
|
+
if (!repo || repositoryTrust(repo) !== "trusted")
|
|
103
|
+
throw new GroupStateError();
|
|
104
|
+
const prior = readMutationGroups(root);
|
|
105
|
+
if (prior.problems || prior.bounded || prior.groups.length >= MAX_GROUPS)
|
|
106
|
+
throw new GroupStateError();
|
|
107
|
+
const id = `grp_${crypto.randomBytes(16).toString("hex")}`;
|
|
108
|
+
const members = plans.map(p => ({ operation_id: p.operationId, checkpoint_id: prepareMutation(p, scope, id),
|
|
109
|
+
path: p.rel, action: p.name, started: false, failed: false, state: "NOT_STARTED" }));
|
|
110
|
+
const timestamp = new Date().toISOString();
|
|
111
|
+
const group = { version: 1, group_id: id, repository_id: repo.id,
|
|
112
|
+
repository_key: repositoryKey(root), scope, created_at: timestamp, updated_at: timestamp, state: "CREATED", members };
|
|
113
|
+
publish(root, group);
|
|
114
|
+
return group;
|
|
115
|
+
}
|
|
116
|
+
export function startGroupMember(root, groupId, operationId) {
|
|
117
|
+
const g = read(root, groupId), member = g.members.find(m => m.operation_id === operationId);
|
|
118
|
+
if (!member || member.started || !["CREATED", "APPLYING", "PARTIALLY_APPLIED"].includes(g.state))
|
|
119
|
+
throw new GroupStateError();
|
|
120
|
+
member.started = true;
|
|
121
|
+
member.state = "APPLYING";
|
|
122
|
+
g.state = "APPLYING";
|
|
123
|
+
g.updated_at = new Date().toISOString();
|
|
124
|
+
publish(root, g);
|
|
125
|
+
return { groupId, checkpointId: member.checkpoint_id };
|
|
126
|
+
}
|
|
127
|
+
export function appliedGroupMember(root, groupId, operationId) {
|
|
128
|
+
const g = read(root, groupId), member = g.members.find(m => m.operation_id === operationId);
|
|
129
|
+
const r = member && recoveryReceipts(root).receipts.find(r => r.checkpoint_id === member.checkpoint_id);
|
|
130
|
+
if (!member?.started || !r || r.group_id !== groupId || r.phase !== "verified" || !r.journal_persisted)
|
|
131
|
+
throw new GroupStateError();
|
|
132
|
+
member.state = "COMPLETED";
|
|
133
|
+
g.state = "PARTIALLY_APPLIED";
|
|
134
|
+
g.updated_at = new Date().toISOString();
|
|
135
|
+
publish(root, g);
|
|
136
|
+
}
|
|
137
|
+
export function failGroupMember(root, groupId, operationId) {
|
|
138
|
+
const g = read(root, groupId), member = g.members.find(m => m.operation_id === operationId);
|
|
139
|
+
if (!member)
|
|
140
|
+
throw new GroupStateError();
|
|
141
|
+
member.failed = true;
|
|
142
|
+
member.state = "FAILED";
|
|
143
|
+
g.state = "UNRESOLVED";
|
|
144
|
+
g.updated_at = new Date().toISOString();
|
|
145
|
+
publish(root, g);
|
|
146
|
+
}
|
|
147
|
+
function memberState(g, m, r, report) {
|
|
148
|
+
if (!r || r.group_id !== g.group_id || r.operation_id !== m.operation_id || r.checkpoint_id !== m.checkpoint_id ||
|
|
149
|
+
r.repository_id !== g.repository_id || r.repository_key !== g.repository_key || r.scope !== g.scope ||
|
|
150
|
+
r.path !== m.path || r.action !== m.action || !report)
|
|
151
|
+
return "UNRESOLVED";
|
|
152
|
+
if (report.classification === "unresolved") {
|
|
153
|
+
return report.fileState === "UNEXPECTED_CHANGED" ||
|
|
154
|
+
(report.fileState === "MISSING" && r.before_exists && r.after_exists) ? "CONFLICT" : "UNRESOLVED";
|
|
155
|
+
}
|
|
156
|
+
const original = report.fileState === "ORIGINAL" || (report.fileState === "MISSING" && !r.before_exists);
|
|
157
|
+
const expected = report.fileState === "EXPECTED_APPLIED" || (report.fileState === "MISSING" && !r.after_exists) ||
|
|
158
|
+
(original && r.before_sha === r.after_sha && r.before_exists === r.after_exists);
|
|
159
|
+
if (original && (!expected || r.phase === "prepared" || r.phase === "rolled_back")) {
|
|
160
|
+
if (m.failed)
|
|
161
|
+
return "FAILED";
|
|
162
|
+
if (!m.started && r.phase === "prepared")
|
|
163
|
+
return "NOT_STARTED";
|
|
164
|
+
if (m.started && r.phase === "rolled_back")
|
|
165
|
+
return "ROLLED_BACK";
|
|
166
|
+
return m.started ? "NOT_APPLIED" : "UNRESOLVED";
|
|
167
|
+
}
|
|
168
|
+
if (!m.started || !expected)
|
|
169
|
+
return "UNRESOLVED";
|
|
170
|
+
return r.phase === "verified" && r.journal_persisted && report.journalStatus === "EXECUTED" ? "COMPLETED" : "APPLIED";
|
|
171
|
+
}
|
|
172
|
+
function groupState(members) {
|
|
173
|
+
const states = members.map(m => m.state);
|
|
174
|
+
if (states.includes("CONFLICT"))
|
|
175
|
+
return "CONFLICT";
|
|
176
|
+
if (states.includes("UNRESOLVED"))
|
|
177
|
+
return "UNRESOLVED";
|
|
178
|
+
if (states.every(s => s === "COMPLETED"))
|
|
179
|
+
return "COMPLETED";
|
|
180
|
+
if (states.some(s => s === "COMPLETED" || s === "APPLIED"))
|
|
181
|
+
return "PARTIALLY_APPLIED";
|
|
182
|
+
if (states.includes("ROLLED_BACK"))
|
|
183
|
+
return "ROLLED_BACK";
|
|
184
|
+
if (states.includes("FAILED") || states.includes("NOT_APPLIED"))
|
|
185
|
+
return "FAILED";
|
|
186
|
+
return "CREATED";
|
|
187
|
+
}
|
|
188
|
+
/** A verified terminal group whose results are settled: history, not an
|
|
189
|
+
* interrupted transaction. Shared by reconciliation and pruning. */
|
|
190
|
+
function groupIsHistory(g, receipts) {
|
|
191
|
+
return ["COMPLETED", "ROLLED_BACK", "FAILED"].includes(g.state) && g.members.every(m => {
|
|
192
|
+
const r = receipts.find(r => r.checkpoint_id === m.checkpoint_id);
|
|
193
|
+
return r && r.group_id === g.group_id && r.operation_id === m.operation_id &&
|
|
194
|
+
r.repository_id === g.repository_id && r.path === m.path && r.action === m.action &&
|
|
195
|
+
r.scope === g.scope && r.journal_persisted && m.started &&
|
|
196
|
+
(g.state === "COMPLETED" ? m.state === "COMPLETED" && r.phase === "verified" :
|
|
197
|
+
m.state === "ROLLED_BACK" && r.phase === "rolled_back") &&
|
|
198
|
+
(!g.scope || ["acknowledged", "rejected"].includes(r.delivery));
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
/** Settled receipts kept for local history after pruning; the server's audit log is authoritative. */
|
|
202
|
+
export const RETAINED_SETTLED_RECEIPTS = 40;
|
|
203
|
+
/**
|
|
204
|
+
* Remove settled recovery evidence so a long-lived repository never reaches the
|
|
205
|
+
* RECOVERY_STATE_BLOCKED receipt bound or the group bound with nothing to
|
|
206
|
+
* review. Removed — oldest first, down to RETAINED_SETTLED_RECEIPTS — only when
|
|
207
|
+
* ALL hold: the change finished (verified or rolled back), its journal write
|
|
208
|
+
* and result delivery are done, no journal entry still refers to its
|
|
209
|
+
* checkpoint (undo keeps working), and, for a group member, the whole group is
|
|
210
|
+
* verified history (its file is removed with its members, never before them).
|
|
211
|
+
* Unresolved, prepared, applied or undelivered evidence is never touched, and
|
|
212
|
+
* unreadable evidence stops pruning entirely: it needs review, not cleanup.
|
|
213
|
+
*
|
|
214
|
+
* @returns the number of receipts removed
|
|
215
|
+
*/
|
|
216
|
+
export function pruneSettledEvidence(root) {
|
|
217
|
+
let journal, scan, groups;
|
|
218
|
+
try {
|
|
219
|
+
journal = readJournal(root);
|
|
220
|
+
scan = recoveryReceipts(root);
|
|
221
|
+
groups = readMutationGroups(root);
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
return 0;
|
|
225
|
+
}
|
|
226
|
+
if (scan.problems || scan.bounded || groups.problems || groups.bounded)
|
|
227
|
+
return 0;
|
|
228
|
+
const linked = new Set(journal.map(e => e.checkpoint_id));
|
|
229
|
+
const settled = (r) => ["verified", "rolled_back"].includes(r.phase) && r.journal_persisted &&
|
|
230
|
+
(!r.scope || ["acknowledged", "rejected"].includes(r.delivery)) && !linked.has(r.checkpoint_id);
|
|
231
|
+
const byGroup = new Map(groups.groups.map(g => [g.group_id, g]));
|
|
232
|
+
// A group is one unit: removable only when every member is.
|
|
233
|
+
const removableGroup = (g) => !!g && groupIsHistory(g, scan.receipts) &&
|
|
234
|
+
g.members.every(m => { const r = scan.receipts.find(r => r.checkpoint_id === m.checkpoint_id); return !!r && settled(r); });
|
|
235
|
+
const units = new Map();
|
|
236
|
+
for (const r of scan.receipts) {
|
|
237
|
+
if (!settled(r) || (r.group_id && !removableGroup(byGroup.get(r.group_id))))
|
|
238
|
+
continue;
|
|
239
|
+
const key = r.group_id ?? r.checkpoint_id;
|
|
240
|
+
units.set(key, [...(units.get(key) ?? []), r]);
|
|
241
|
+
}
|
|
242
|
+
// Deterministic: oldest unit first, ties broken by id.
|
|
243
|
+
const ordered = [...units.entries()].sort(([a, x], [b, y]) => Math.max(...x.map(r => Date.parse(r.created_at))) - Math.max(...y.map(r => Date.parse(r.created_at))) || (a < b ? -1 : a > b ? 1 : 0));
|
|
244
|
+
let remaining = scan.receipts.length, removed = 0;
|
|
245
|
+
const dir = workspaceDir(root);
|
|
246
|
+
for (const [key, receipts] of ordered) {
|
|
247
|
+
if (remaining <= RETAINED_SETTLED_RECEIPTS)
|
|
248
|
+
break;
|
|
249
|
+
try {
|
|
250
|
+
if (byGroup.has(key))
|
|
251
|
+
fs.rmSync(file(root, key), { force: true });
|
|
252
|
+
for (const r of receipts) {
|
|
253
|
+
fs.rmSync(path.join(dir, `${r.checkpoint_id}.recovery.json`), { force: true });
|
|
254
|
+
fs.rmSync(path.join(dir, `${r.checkpoint_id}.before`), { force: true });
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
remaining -= receipts.length;
|
|
261
|
+
removed += receipts.length;
|
|
262
|
+
}
|
|
263
|
+
return removed;
|
|
264
|
+
}
|
|
265
|
+
/** The Phase 2 scanner owns every target-file read. This layer only joins its
|
|
266
|
+
* verified reports to manifest/receipt identities and writes group metadata. */
|
|
267
|
+
export function reconcileMutationGroups(scope) {
|
|
268
|
+
const loaded = [], groups = [];
|
|
269
|
+
for (const repo of listRepositories().slice(0, 20)) {
|
|
270
|
+
try {
|
|
271
|
+
const scan = readMutationGroups(repo.root);
|
|
272
|
+
if (scan.problems || scan.bounded)
|
|
273
|
+
groups.push({ state: "UNRESOLVED", message: "Group evidence is unreadable or exceeds the scan limit; it was preserved." });
|
|
274
|
+
const receipts = recoveryReceipts(repo.root).receipts;
|
|
275
|
+
for (const g of scan.groups) {
|
|
276
|
+
if (g.repository_id !== repo.id || repositoryTrust(repo) !== "trusted" || (g.scope && g.scope !== scope)) {
|
|
277
|
+
groups.push({ groupId: g.group_id, state: "UNRESOLVED", message: `Group ${g.group_id}: repository trust, identity or session scope is not verified.` });
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
// Verified terminal groups whose results are settled are history. Do not
|
|
281
|
+
// reinterpret later normal user edits as an interrupted transaction.
|
|
282
|
+
if (groupIsHistory(g, receipts))
|
|
283
|
+
continue;
|
|
284
|
+
loaded.push({ root: repo.root, group: g });
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
groups.push({ state: "UNRESOLVED", message: "Group evidence could not be read; it was preserved." });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const operations = new Set(loaded.flatMap(({ group }) => group.members.map(m => m.operation_id)));
|
|
292
|
+
const recovery = reconcileMutations(scope, operations);
|
|
293
|
+
for (const { root, group: g } of loaded) {
|
|
294
|
+
try {
|
|
295
|
+
const receipts = recoveryReceipts(root).receipts;
|
|
296
|
+
const members = g.members.map(m => ({ ...m, state: memberState(g, m, receipts.find(r => r.checkpoint_id === m.checkpoint_id), recovery.reports.find(r => r.operationId === m.operation_id && r.repositoryId === g.repository_id)) }));
|
|
297
|
+
const state = groupState(members);
|
|
298
|
+
if (state !== g.state || JSON.stringify(members) !== JSON.stringify(g.members)) {
|
|
299
|
+
publish(root, { ...g, members, state, updated_at: new Date().toISOString() });
|
|
300
|
+
}
|
|
301
|
+
groups.push({ groupId: g.group_id, state, members, message: `Group ${g.group_id}: ${state}. ` +
|
|
302
|
+
members.map(m => `${m.operation_id}: ${m.state}`).join("; ") + ". Recovery changed no target files." });
|
|
303
|
+
}
|
|
304
|
+
catch {
|
|
305
|
+
groups.push({ groupId: g.group_id, state: "UNRESOLVED", message: `Group ${g.group_id}: reconciliation could not be persisted or verified; evidence was preserved.` });
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return { ...recovery, groups };
|
|
309
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { loadCheckpoint, readJournal, recoveryReceipts, sha256, updateRecoveryReceipt } from "./checkpoints.js";
|
|
3
|
+
import { resolveMutationTarget, MAX_EDIT_SOURCE_BYTES } from "./mutations.js";
|
|
4
|
+
import { listRepositories, repositoryTrust } from "./workspace-registry.js";
|
|
5
|
+
/** Inspect bytes through the mutation boundary and retain unresolved receipt state.
|
|
6
|
+
* Never executes or restores a target file. */
|
|
7
|
+
export function reconcileMutations(scope, inspectOperations) {
|
|
8
|
+
const reports = [], replay = [];
|
|
9
|
+
const repositories = listRepositories();
|
|
10
|
+
if (repositories.length > 20)
|
|
11
|
+
reports.push({ classification: "unresolved", message: "Recovery scan limited to 20 repositories; remaining evidence was preserved." });
|
|
12
|
+
for (const repo of repositories.slice(0, 20)) {
|
|
13
|
+
try {
|
|
14
|
+
const scan = recoveryReceipts(repo.root);
|
|
15
|
+
if (scan.problems || scan.bounded)
|
|
16
|
+
reports.push({ classification: "unresolved",
|
|
17
|
+
message: "Recovery evidence is unreadable, inconsistent, legacy, or exceeds the scan limit. It was preserved for review." });
|
|
18
|
+
for (const r of scan.receipts) {
|
|
19
|
+
// Delivery already settled is history, not an interrupted operation. So is a
|
|
20
|
+
// finished LOCAL operation (an undo or rewind: no session scope, nothing was
|
|
21
|
+
// ever to be delivered) — it is not reported as pending on every start, even
|
|
22
|
+
// if an earlier scan marked it unresolved because the file was edited later.
|
|
23
|
+
if (!inspectOperations?.has(r.operation_id) && r.journal_persisted &&
|
|
24
|
+
((r.phase !== "unresolved" && (r.delivery === "acknowledged" || r.delivery === "rejected")) ||
|
|
25
|
+
(!r.scope && r.delivery === "none")))
|
|
26
|
+
continue;
|
|
27
|
+
let fileState;
|
|
28
|
+
let journalStatus;
|
|
29
|
+
const emit = (classification, detail, reason) => reports.push({
|
|
30
|
+
reason, operationId: r.operation_id, repositoryId: repo.id, classification, ...(fileState ? { fileState } : {}), ...(journalStatus ? { journalStatus } : {}),
|
|
31
|
+
message: `Recovery ${r.operation_id}: ${detail} Checkpoint ${r.checkpoint_id} retained; recovery changed no target files.`
|
|
32
|
+
});
|
|
33
|
+
if (r.repository_id !== repo.id || repositoryTrust(repo) !== "trusted") {
|
|
34
|
+
emit("unresolved", "Repository identity/trust could not be verified.");
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (r.scope && r.scope !== scope) {
|
|
38
|
+
emit("unresolved", "Saved operation belongs to a different authenticated session scope; no result was sent.");
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const unresolved = (detail) => {
|
|
42
|
+
if (r.phase !== "unresolved") {
|
|
43
|
+
try {
|
|
44
|
+
updateRecoveryReceipt(repo.root, r.checkpoint_id, { phase: "unresolved" });
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
detail += " The unresolved marker could not be saved; prior recovery evidence remains.";
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
emit("unresolved", detail);
|
|
51
|
+
};
|
|
52
|
+
try {
|
|
53
|
+
const { abs } = resolveMutationTarget(r.path, repo.root);
|
|
54
|
+
let stat;
|
|
55
|
+
try {
|
|
56
|
+
stat = fs.statSync(abs);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
if (error.code !== "ENOENT")
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
const exists = stat !== undefined;
|
|
63
|
+
if (stat && (!stat.isFile() || stat.size > MAX_EDIT_SOURCE_BYTES))
|
|
64
|
+
throw new Error();
|
|
65
|
+
const hash = exists ? sha256(fs.readFileSync(abs)) : null;
|
|
66
|
+
const before = exists === r.before_exists && hash === r.before_sha;
|
|
67
|
+
const after = exists === r.after_exists && hash === r.after_sha;
|
|
68
|
+
fileState = !exists ? "MISSING" : before ? "ORIGINAL" : after ? "EXPECTED_APPLIED" : "UNEXPECTED_CHANGED";
|
|
69
|
+
if (!before && !after) {
|
|
70
|
+
unresolved("File conflicts with both recorded states; newer edits were preserved.");
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (r.before_exists) {
|
|
74
|
+
const checkpoint = loadCheckpoint(repo.root, r.checkpoint_id);
|
|
75
|
+
if (!checkpoint || sha256(checkpoint) !== r.before_sha) {
|
|
76
|
+
emit("unresolved", "Original checkpoint is missing, unreadable or inconsistent.");
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
let journal;
|
|
81
|
+
try {
|
|
82
|
+
journal = readJournal(repo.root);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
emit("unresolved", "Journal is unreadable; receipt/checkpoint evidence was preserved.");
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const entry = journal.find(e => e.operation_id === r.operation_id);
|
|
89
|
+
if (entry && (entry.checkpoint_id !== r.checkpoint_id || entry.path !== r.path ||
|
|
90
|
+
entry.before_sha !== r.before_sha || entry.after_sha !== r.after_sha ||
|
|
91
|
+
entry.before_exists !== r.before_exists || entry.after_exists !== r.after_exists ||
|
|
92
|
+
entry.action !== r.action || entry.repository_key !== r.repository_key ||
|
|
93
|
+
entry.repository_id !== repo.id)) {
|
|
94
|
+
unresolved("Journal and receipt identities disagree.");
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
journalStatus = entry?.status;
|
|
98
|
+
// No-op writes are ambiguous if the process died before verification.
|
|
99
|
+
if (before && after && r.phase === "prepared") {
|
|
100
|
+
emit("unresolved", "Identical pre/post states cannot prove this operation ran.");
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (before && (!after || r.phase === "rolled_back")) {
|
|
104
|
+
emit("not_applied", "File matches the original state; no applied change remains.");
|
|
105
|
+
if (r.result?.ok)
|
|
106
|
+
continue; // Never replay success when current recovery evidence disagrees.
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
if (r.phase === "unresolved" || r.phase === "rolled_back") {
|
|
110
|
+
emit("unresolved", "Applied bytes remain while this operation is unresolved or marked rolled back; review is required.");
|
|
111
|
+
if (r.result?.ok !== false)
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
const consistent = entry?.status === "EXECUTED";
|
|
116
|
+
emit(consistent && r.journal_persisted && (r.result || !r.scope) ? "completed" : "safely_recoverable", consistent ? "Applied bytes and history verified; result delivery may still be pending."
|
|
117
|
+
: "Applied bytes verified; history or final result is incomplete and needs review.");
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (r.result && ["ready", "queued"].includes(r.delivery) &&
|
|
121
|
+
Date.now() - Date.parse(r.created_at) >= 16 * 60 * 1000) {
|
|
122
|
+
emit("unresolved", "Saved result exceeded its recovery lifetime; it was not requeued.", "delivery_expired");
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (r.result && r.scope === scope && ["ready", "queued"].includes(r.delivery) &&
|
|
126
|
+
Date.now() - Date.parse(r.created_at) < 16 * 60 * 1000) {
|
|
127
|
+
// Backend still decides ownership, expiry and duplicate acknowledgement.
|
|
128
|
+
// Never synthesize a missing result: a group may have failed later.
|
|
129
|
+
replay.push({ payload: r.result, createdAt: Date.parse(r.created_at) });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
fileState = "UNREADABLE";
|
|
134
|
+
unresolved("File access was denied or state could not be verified.");
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
reports.push({ classification: "unresolved", message: "Recovery scan could not read repository evidence. It was preserved; no file was changed." });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return { reports, replay };
|
|
143
|
+
}
|
|
144
|
+
/** Bind transport progress to existing receipts, without duplicating the outbox. */
|
|
145
|
+
export function recordMutationDelivery(payload, scope, delivery) {
|
|
146
|
+
for (const repo of listRepositories().slice(0, 20)) {
|
|
147
|
+
const scan = recoveryReceipts(repo.root);
|
|
148
|
+
const receipt = scan.receipts.find(r => r.operation_id === payload.tool_call_id && r.scope === scope && r.repository_id === repo.id);
|
|
149
|
+
if (!receipt)
|
|
150
|
+
continue;
|
|
151
|
+
// A replay must not downgrade acknowledged state before local outbox cleanup.
|
|
152
|
+
if (["acknowledged", "rejected"].includes(receipt.delivery))
|
|
153
|
+
return;
|
|
154
|
+
if (receipt.result && JSON.stringify(receipt.result) !== JSON.stringify(payload))
|
|
155
|
+
throw new Error("Conflicting saved mutation result; original evidence was preserved.");
|
|
156
|
+
updateRecoveryReceipt(repo.root, receipt.checkpoint_id, { result: payload, delivery });
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
}
|