@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.
Files changed (89) hide show
  1. package/README.md +89 -15
  2. package/dist/commands/chat.js +6 -6
  3. package/dist/commands/context.js +40 -0
  4. package/dist/commands/doctor.js +34 -14
  5. package/dist/commands/logout.js +2 -0
  6. package/dist/commands/permissions.js +78 -0
  7. package/dist/commands/scope.js +9 -6
  8. package/dist/commands/sessions.js +5 -0
  9. package/dist/commands/settings.js +83 -10
  10. package/dist/commands/update.js +177 -51
  11. package/dist/commands/usage.js +10 -8
  12. package/dist/commands/version.js +1 -3
  13. package/dist/commands/whoami.js +12 -9
  14. package/dist/ide/editor-context.js +115 -12
  15. package/dist/ide/ide-session.js +288 -18
  16. package/dist/ide/tool-host.js +6 -6
  17. package/dist/main.js +10 -1
  18. package/dist/services/api.js +183 -15
  19. package/dist/services/auth-origin.js +20 -0
  20. package/dist/services/auto-update.js +221 -0
  21. package/dist/services/chat-stream.js +26 -3
  22. package/dist/services/checkpoints.js +176 -14
  23. package/dist/services/client-tools.js +123 -27
  24. package/dist/services/code-intel.js +243 -0
  25. package/dist/services/code-symbols.js +94 -0
  26. package/dist/services/coding-workflow.js +554 -0
  27. package/dist/services/command-coordinator.js +85 -12
  28. package/dist/services/command-policy.js +34 -4
  29. package/dist/services/config.js +96 -11
  30. package/dist/services/container-runner.js +254 -0
  31. package/dist/services/container-supervisor.js +38 -0
  32. package/dist/services/context.js +98 -25
  33. package/dist/services/device-auth.js +33 -6
  34. package/dist/services/execution-platform.js +30 -0
  35. package/dist/services/file-resolver.js +1 -1
  36. package/dist/services/folder-key.js +22 -0
  37. package/dist/services/git-tools.js +181 -0
  38. package/dist/services/helper-bin.js +56 -35
  39. package/dist/services/instruction-resolver.js +54 -0
  40. package/dist/services/job-helper.js +31 -10
  41. package/dist/services/local-files.js +148 -26
  42. package/dist/services/local-tools.js +540 -35
  43. package/dist/services/login-flow.js +44 -13
  44. package/dist/services/meta.js +27 -0
  45. package/dist/services/mutation-coordinator.js +186 -20
  46. package/dist/services/mutation-groups.js +309 -0
  47. package/dist/services/mutation-recovery.js +159 -0
  48. package/dist/services/mutations.js +264 -78
  49. package/dist/services/packaged-update.js +403 -0
  50. package/dist/services/packaged.js +15 -0
  51. package/dist/services/permission-mode.js +78 -0
  52. package/dist/services/process-runner.js +7 -1
  53. package/dist/services/project-context.js +4 -4
  54. package/dist/services/result-reconciliation.js +49 -0
  55. package/dist/services/secure-store.js +21 -1
  56. package/dist/services/session-resolver.js +7 -0
  57. package/dist/services/supported-runtime.js +59 -0
  58. package/dist/services/task-context.js +212 -0
  59. package/dist/services/task-snapshot.js +38 -0
  60. package/dist/services/tool-result-outbox.js +195 -0
  61. package/dist/services/update.js +457 -13
  62. package/dist/services/workspace-registry.js +4 -3
  63. package/dist/services/workspace.js +8 -1
  64. package/dist/shell/shell-chat.js +320 -34
  65. package/dist/shell/shell-commands.js +47 -5
  66. package/dist/shell/shell-prompt.js +21 -11
  67. package/dist/shell/shell-renderer.js +1 -1
  68. package/dist/shell/shell.js +107 -20
  69. package/dist/shell/task-context-view.js +40 -0
  70. package/dist/ui/agent-cards.js +111 -0
  71. package/dist/ui/agent-presentation.js +131 -0
  72. package/dist/ui/approval.js +46 -16
  73. package/dist/ui/banner.js +31 -87
  74. package/dist/ui/change-review.js +293 -46
  75. package/dist/ui/chat-renderer.js +6 -6
  76. package/dist/ui/colors.js +9 -9
  77. package/dist/ui/command-details.js +11 -0
  78. package/dist/ui/command-palette.js +27 -10
  79. package/dist/ui/command-registry.js +11 -4
  80. package/dist/ui/command-review.js +77 -28
  81. package/dist/ui/composer-layout.js +26 -20
  82. package/dist/ui/conversation.js +77 -25
  83. package/dist/ui/live.js +1 -1
  84. package/dist/ui/screen.js +19 -11
  85. package/dist/ui/select.js +6 -0
  86. package/dist/ui/task-context-card.js +99 -0
  87. package/dist/ui/trust.js +7 -12
  88. package/dist/ui/ui.js +23 -0
  89. package/package.json +9 -5
@@ -1,7 +1,6 @@
1
1
  import chalk from "chalk";
2
2
  import { ApiError } from "./api.js";
3
- import { DEFAULT_API_URL } from "./config.js";
4
- import { deviceLabel, localAuthorizeDefault, openBrowser, platformAuthBase, pollForToken, startDeviceAuthorization, withPlatformOrigin } from "./device-auth.js";
3
+ import { deviceLabel, localAuthorizeDefault, openBrowser, userCliAuthBase, pollForToken, startDeviceAuthorization, withPlatformOrigin } from "./device-auth.js";
5
4
  import { info, line } from "./output.js";
6
5
  import { sleep, withSpinner } from "./spinner.js";
7
6
  import { c } from "../ui/colors.js";
@@ -15,10 +14,29 @@ import { c } from "../ui/colors.js";
15
14
  * Opening your browser…
16
15
  * ✓ Browser opened <verification url> Code XXXX-XXXX
17
16
  * ⠋ Waiting for approval… (in-place spinner)
18
- * ✓ Device authorized / Workspace / Project / Session / Authentication successful
17
+ * ✓ Device authorized / Session synchronized / Logged in as <account>
19
18
  */
19
+ /**
20
+ * The device-authorization flow without any terminal output: request a device
21
+ * code, compute where the browser should go, and — when `complete()` is called —
22
+ * poll for approval and persist the session exactly as the CLI does. Shared by
23
+ * `cos login` (which renders it in the terminal) and the IDE extension (which
24
+ * opens the URL with the editor's own browser API). One flow, one session store.
25
+ */
26
+ export async function beginDeviceLogin(ctx, apiUrl, label = deviceLabel()) {
27
+ const authBase = userCliAuthBase(apiUrl);
28
+ const start = await startDeviceAuthorization(authBase, label);
29
+ const apiUri = start.verification_uri_complete || start.verification_uri;
30
+ const override = ctx.config.get("platformUrl") || process.env.CARRIEROS_PLATFORM_URL || localAuthorizeDefault(apiUrl, apiUri);
31
+ return {
32
+ openUrl: withPlatformOrigin(apiUri, override),
33
+ userCode: start.user_code,
34
+ // A cancelled sign-in stops polling, so a late approval never signs anyone in.
35
+ complete: async (signal) => persistSession(ctx, await pollForToken(authBase, start, undefined, signal), apiUrl)
36
+ };
37
+ }
20
38
  export async function deviceLogin(ctx, apiUrl) {
21
- const authBase = platformAuthBase(apiUrl);
39
+ const authBase = userCliAuthBase(apiUrl);
22
40
  // Branding + intro first (shown for both `cos` first-run and `cos login`).
23
41
  line();
24
42
  line(" " + c.brand("Welcome to Carrier OS"));
@@ -49,16 +67,26 @@ export async function deviceLogin(ctx, apiUrl) {
49
67
  // Waiting state — a single in-place spinner (never scrolls). Polling is
50
68
  // unchanged; the spinner just animates until it resolves or throws.
51
69
  const tokens = await withSpinner(chalk.dim("Waiting for approval…"), () => pollForToken(authBase, start));
52
- return renderAuthorized(ctx, tokens);
70
+ return renderAuthorized(ctx, tokens, apiUrl);
71
+ }
72
+ /**
73
+ * The website's own "Not you? Use a different account" for this request: it signs
74
+ * that browser out of whoever is signed in there, shows the sign-in form, and
75
+ * returns to the same /cli/authorize request (code intact) for the account just
76
+ * signed in — which approves it there, as always.
77
+ */
78
+ export function switchAccountUrl(openUrl) {
79
+ const u = new URL(openUrl);
80
+ return `${u.origin}/sign-in?switch=1&redirectTo=${encodeURIComponent(u.pathname + u.search)}`;
53
81
  }
54
82
  /** The success sequence — a short animated checklist, then persist + verify,
55
83
  * ending on "Logged in as <email>" (the shell then pauses + shows the welcome). */
56
- async function renderAuthorized(ctx, tokens) {
84
+ async function renderAuthorized(ctx, tokens, apiUrl) {
57
85
  const ok = (msg) => line(" " + chalk.green("✓") + " " + msg);
58
86
  line();
59
87
  ok("Device authorized");
60
88
  await sleep(150);
61
- const scope = await persistSession(ctx, tokens);
89
+ const scope = await persistSession(ctx, tokens, apiUrl);
62
90
  ok("Session synchronized");
63
91
  await sleep(130);
64
92
  const email = scope.user?.email ?? tokens.account?.email;
@@ -68,21 +96,24 @@ async function renderAuthorized(ctx, tokens) {
68
96
  }
69
97
  return scope;
70
98
  }
71
- /** Save the issued tokens + a cached scope; land in Carrier Chat by default.
99
+ /** Save the issued tokens + a cached scope; land in Standard chat by default.
72
100
  * (Unchanged behaviour — persistence + a verify to confirm the token works.) */
73
- async function persistSession(ctx, tokens) {
101
+ export async function persistSession(ctx, tokens, issuer) {
74
102
  ctx.config.update({
75
103
  auth: {
76
104
  accessToken: tokens.access_token,
77
105
  refreshToken: tokens.refresh_token,
78
106
  // Which server issued this session. Only its refusal ends the session.
79
- apiUrl: ctx.config.get("apiUrl") ?? DEFAULT_API_URL,
107
+ apiUrl: issuer,
80
108
  account: tokens.account,
81
109
  workspace: tokens.workspace ?? null,
82
110
  project: tokens.project ?? null
83
111
  }
84
112
  });
85
- ctx.config.set("chatType", "carrier");
113
+ // A conversation keeps its type forever. Reset the saved session too: a
114
+ // previous conversation must not resume under a different account.
115
+ ctx.setChatType("standard");
116
+ ctx.config.set("sessionTitle", undefined);
86
117
  let scope;
87
118
  try {
88
119
  scope = await ctx.client().verify();
@@ -96,8 +127,8 @@ async function persistSession(ctx, tokens) {
96
127
  function scopeFromTokens(tokens) {
97
128
  return {
98
129
  apiKey: null,
99
- workspace: tokens.workspace ?? { id: "", name: "—", slug: "" },
100
- project: tokens.project ?? { id: "", name: "—", projectId: "", environment: "" },
130
+ workspace: tokens.workspace ?? null,
131
+ project: tokens.project ?? null,
101
132
  user: tokens.account ? { id: tokens.account.id, email: tokens.account.email } : null
102
133
  };
103
134
  }
@@ -13,3 +13,30 @@ export function cliVersion() {
13
13
  return "0.0.0";
14
14
  }
15
15
  }
16
+ /**
17
+ * Which client is talking to the API, sent on every request:
18
+ *
19
+ * X-CarrierOS-Client: cli/0.4.1 | cli-exe/0.4.1 | vscode/0.2.1
20
+ * X-CarrierOS-Channel: latest | beta | next | staging (when known)
21
+ *
22
+ * Only the client kind, its version and its release channel — never a path,
23
+ * user name, token or anything else from the machine. Servers that do not read
24
+ * these headers ignore them, so older APIs are unaffected.
25
+ */
26
+ let clientKind = "cli";
27
+ let clientVersionOverride = null;
28
+ let releaseChannel = null;
29
+ /** Set once at startup: "cli-exe" for the packaged build, "vscode" for the extension. */
30
+ export function setClientIdentity(kind, version) {
31
+ clientKind = kind;
32
+ clientVersionOverride = version && /^[0-9A-Za-z.+-]{1,64}$/.test(version) ? version : null;
33
+ }
34
+ export function setClientReleaseChannel(channel) {
35
+ releaseChannel = channel && /^(latest|beta|next|staging)$/.test(channel) ? channel : null;
36
+ }
37
+ export function clientHeaders() {
38
+ return {
39
+ "X-CarrierOS-Client": `${clientKind}/${clientVersionOverride ?? cliVersion()}`,
40
+ ...(releaseChannel ? { "X-CarrierOS-Channel": releaseChannel } : {})
41
+ };
42
+ }
@@ -1,4 +1,6 @@
1
- import { MAX_FILES_PER_APPROVAL, MAX_MUTATIONS_PER_TURN, MAX_REVIEW_LINES, MutationError, appliedResult, applyPlan, planMutation, reviewLineCount, rollbackApplied } from "./mutations.js";
1
+ import { createHash } from "node:crypto";
2
+ import { createMutationGroup, startGroupMember, appliedGroupMember, failGroupMember, pruneSettledEvidence, reconcileMutationGroups } from "./mutation-groups.js";
3
+ import { MAX_FILES_PER_APPROVAL, APPROVAL_TIMEOUT_MS, MAX_MUTATIONS_PER_TURN, MAX_REVIEW_LINES, MutationError, appliedResult, applyPlan, assertPlanCurrent, planMutation, reviewLineCount, rollbackApplied } from "./mutations.js";
2
4
  import { inWorkspaceMode } from "./workspace-registry.js";
3
5
  const VERB = {
4
6
  create_file: "Created",
@@ -16,23 +18,45 @@ export function createMutationCoordinator(opts) {
16
18
  let timer = null;
17
19
  let chain = Promise.resolve();
18
20
  let stopped = false;
19
- const fail = (p, code, message) => opts.submit({
21
+ const seen = new Set();
22
+ const submitOnce = (p, result) => {
23
+ // Transport owns retrying this exact result. A later batch error must never
24
+ // synthesize a contradictory second result for an already-finalized call.
25
+ if (p.result)
26
+ return Promise.resolve();
27
+ p.result = result;
28
+ // Recorded locally before the server can see it (see `record`). Bookkeeping
29
+ // never blocks delivery of a result that is already final.
30
+ try {
31
+ opts.record?.(result);
32
+ }
33
+ catch { /* the finalized result is still delivered */ }
34
+ return opts.submit(result);
35
+ };
36
+ const fail = (p, code, message) => submitOnce(p, {
20
37
  tool_call_id: p.call.tool_call_id,
21
38
  ok: false,
22
39
  error: { code, message },
23
40
  duration_ms: Date.now() - p.started
24
41
  });
25
- const succeed = (p, change) => opts.submit({
42
+ const succeed = (p, change) => submitOnce(p, {
26
43
  tool_call_id: p.call.tool_call_id,
27
44
  ok: true,
28
45
  result: appliedResult(change),
29
46
  duration_ms: Date.now() - p.started
30
47
  });
31
48
  async function review(batch) {
49
+ if (opts.signal?.aborted) {
50
+ stopped = true;
51
+ await Promise.all(batch.map(p => fail(p, "MUTATION_CANCELLED", "The turn was cancelled. Nothing was changed.")));
52
+ return;
53
+ }
32
54
  if (stopped) {
33
55
  // A "no" ends proposals for the turn. The model asks the user what they
34
56
  // want instead of offering variations until one is accepted.
35
- await Promise.all(batch.map((p) => fail(p, "MUTATION_REJECTED", "The user already declined a change in this turn. Nothing was changed; ask the user how to proceed.")));
57
+ const message = "Further changes are stopped for this turn. Review the earlier rejection or unresolved failure with the user before proceeding.";
58
+ ui.refused?.({ files: batch.map((p) => p.call.arguments?.path).filter((x) => typeof x === "string"), code: "MUTATIONS_STOPPED", message });
59
+ await Promise.all(batch.map((p) => fail(p, "MUTATION_REJECTED", message)));
36
60
  return;
37
61
  }
38
62
  // Plan everything first. A proposal that cannot be planned is answered
@@ -46,11 +70,15 @@ export function createMutationCoordinator(opts) {
46
70
  // the repository AND the path.
47
71
  const key = `${plan.repositoryId}:${plan.rel.toLowerCase()}`;
48
72
  if (seen.has(key)) {
49
- await fail(p, "CONFLICTING_CHANGE", `${plan.rel} is already changed by another proposal in this step. Propose one change per file.`);
73
+ const message = `${plan.rel} is already changed by another proposal in this step. Propose one change per file.`;
74
+ ui.refused?.({ files: [plan.rel], code: "CONFLICTING_CHANGE", message });
75
+ await fail(p, "CONFLICTING_CHANGE", message);
50
76
  continue;
51
77
  }
52
78
  if (reviewLineCount(plan) > MAX_REVIEW_LINES) {
53
- await fail(p, "DIFF_TOO_LARGE", `The change to ${plan.rel} is too large to review. Split it into smaller edits.`);
79
+ const message = `The change to ${plan.rel} is too large to review. Split it into smaller edits.`;
80
+ ui.refused?.({ files: [plan.rel], code: "DIFF_TOO_LARGE", message });
81
+ await fail(p, "DIFF_TOO_LARGE", message);
54
82
  continue;
55
83
  }
56
84
  seen.add(key);
@@ -58,6 +86,8 @@ export function createMutationCoordinator(opts) {
58
86
  }
59
87
  catch (err) {
60
88
  const e = err instanceof MutationError ? err : new MutationError("TOOL_FAILED", err.message);
89
+ const rel = p.call.arguments?.path;
90
+ ui.refused?.({ files: typeof rel === "string" ? [rel] : [], code: e.code, message: e.message });
61
91
  await fail(p, e.code, e.message);
62
92
  }
63
93
  }
@@ -65,7 +95,7 @@ export function createMutationCoordinator(opts) {
65
95
  return;
66
96
  // One approval, one repository.
67
97
  //
68
- // A group is approved as a unit and applied all-or-nothing, and "all" has to
98
+ // A group is approved as a unit, with verified rollback on failure. "All" has to
69
99
  // mean something a person can hold in their head: these files, in this
70
100
  // repository. A group spanning two repositories would ask for one yes
71
101
  // covering two boundaries, and a rollback would have to reach across both.
@@ -75,48 +105,177 @@ export function createMutationCoordinator(opts) {
75
105
  if (repositories.length > 1) {
76
106
  const names = [...new Set(ready.map((r) => r.plan.repositoryName))].join(", ");
77
107
  ui.note([` ⊘ One change group cannot span ${names} — nothing was changed.`]);
108
+ ui.refused?.({ files: ready.map((r) => r.plan.rel), code: "MULTI_REPOSITORY_MUTATION_NOT_ALLOWED",
109
+ message: `A single change cannot span more than one repository (${names}). Nothing was changed.` });
78
110
  await Promise.all(ready.map((r) => fail(r.p, "MULTI_REPOSITORY_MUTATION_NOT_ALLOWED", `A single change cannot span more than one repository (${names}). Nothing was changed. Propose the changes for each repository as a separate operation.`)));
79
111
  return;
80
112
  }
81
- const decision = await ui.review(ready.map((r) => r.plan));
113
+ const approvalScope = opts.recoveryScope?.();
114
+ const fingerprint = () => createHash("sha256").update(JSON.stringify({ plans: ready.map(r => ({ plan: r.plan, callId: r.p.call.tool_call_id })), workflow: opts.approvalContext?.() })).digest("hex");
115
+ const reviewedHash = fingerprint();
116
+ const approvalDeadline = Date.now() + APPROVAL_TIMEOUT_MS;
117
+ try {
118
+ opts.validatePlans?.(ready.map(r => r.plan));
119
+ }
120
+ catch (error) {
121
+ ui.refused?.({ files: ready.map((r) => r.plan.rel), code: "CODING_WORKFLOW_BLOCKED", message: error.message });
122
+ await Promise.all(ready.map(r => fail(r.p, "CODING_WORKFLOW_BLOCKED", error.message)));
123
+ return;
124
+ }
125
+ // The decision comes from the person, or from the session's Accept Edits
126
+ // policy — never from the model. Either way the checks after it (cancel,
127
+ // fingerprint, deadline, scope, freshness, checkpoint) still decide whether
128
+ // anything is written.
129
+ let decision;
130
+ if (opts.approveEditsByPolicy?.() === true) {
131
+ ui.approvedByPolicy?.(ready.map((r) => r.plan));
132
+ decision = "approve";
133
+ }
134
+ else
135
+ decision = await ui.review(ready.map((r) => r.plan));
136
+ if (opts.signal?.aborted) {
137
+ stopped = true;
138
+ await Promise.all(ready.map(r => fail(r.p, "MUTATION_CANCELLED", "The turn was cancelled during review. Nothing was changed.")));
139
+ return;
140
+ }
82
141
  if (decision !== "approve") {
83
- const code = decision === "timeout" ? "APPROVAL_TIMEOUT" : "MUTATION_REJECTED";
142
+ const code = decision === "timeout" ? "APPROVAL_TIMEOUT" : decision === "cancel" ? "MUTATION_CANCELLED" : "MUTATION_REJECTED";
84
143
  const message = decision === "timeout"
85
144
  ? "No one approved the change in time. Nothing was changed."
86
- : "The user rejected the change. Nothing was changed.";
87
- ui.note([decision === "timeout" ? " ⊘ Approval timed out — nothing changed." : " ⊘ Rejected — nothing changed."]);
145
+ : decision === "cancel"
146
+ ? "The turn was cancelled during review. Nothing was changed."
147
+ : "The user rejected the change. Nothing was changed.";
148
+ if (decision === "reject" && ui.rejected)
149
+ ui.rejected(ready.map((r) => r.plan));
150
+ else
151
+ ui.note([decision === "timeout" ? " ⊘ Approval timed out — nothing changed." : decision === "cancel" ? " ⊘ Cancelled — nothing changed." : " ⊘ Rejected — nothing changed."]);
88
152
  stopped = true;
89
153
  await Promise.all(ready.map((r) => fail(r.p, code, message)));
90
154
  if (decision === "cancel")
91
155
  ui.cancelTurn();
92
156
  return;
93
157
  }
94
- // Approved: apply in order, all or nothing.
158
+ if (Date.now() >= approvalDeadline || fingerprint() !== reviewedHash || opts.recoveryScope?.() !== approvalScope) {
159
+ stopped = true;
160
+ const message = "The proposal, identity or approval deadline changed during review. Nothing was written. Request a fresh review.";
161
+ // The person said yes; tell them why nothing happened.
162
+ ui.applyFailed?.({ code: "APPROVAL_INVALIDATED", message, rolledBack: [], unresolved: [], notApplied: ready.map((r) => r.plan.rel) });
163
+ await Promise.all(ready.map(r => fail(r.p, "APPROVAL_INVALIDATED", message)));
164
+ return;
165
+ }
166
+ // The approval was for diffs computed from specific bytes. Before the first
167
+ // write, every member must still be based on what is on disk — otherwise
168
+ // the whole group is refused (nothing written) and needs a fresh proposal
169
+ // and approval. applyPlan repeats the check per file immediately before its
170
+ // write, which still covers a change racing in between.
171
+ const stale = [];
172
+ for (const r of ready) {
173
+ try {
174
+ assertPlanCurrent(r.plan);
175
+ }
176
+ catch (err) {
177
+ stale.push({ ...r, error: err instanceof MutationError ? err : new MutationError("STALE_FILE", err.message) });
178
+ }
179
+ }
180
+ if (stale.length) {
181
+ const rels = stale.map((s) => s.plan.rel);
182
+ if (ui.noLongerValid)
183
+ ui.noLongerValid(rels);
184
+ else
185
+ ui.note([` ⊘ Change no longer valid: ${rels.join(", ")} changed after this review. Nothing was written.`]);
186
+ await Promise.all(ready.map((r) => {
187
+ const s = stale.find((x) => x.p === r.p);
188
+ return s
189
+ ? fail(r.p, s.error.code, `${r.plan.rel} changed after this review. The proposed diff is no longer based on the current file. Nothing was written; propose the change again from a fresh read for a new review.`)
190
+ : fail(r.p, "NOT_APPLIED", `Not applied because ${rels.join(", ")} changed after this review. Nothing was written.`);
191
+ }));
192
+ return;
193
+ }
194
+ let group;
195
+ const root = ready[0].plan.repositoryRoot;
196
+ const scope = opts.recoveryScope?.();
197
+ // Settled history only; never fails the batch (see pruneSettledEvidence).
198
+ pruneSettledEvidence(root);
199
+ if (ready.length > 1) {
200
+ try {
201
+ group = createMutationGroup(ready.map(r => r.plan), scope);
202
+ }
203
+ catch {
204
+ stopped = true;
205
+ ui.note([" ✗ Group intent could not be persisted. No target files were changed; available recovery evidence was preserved."]);
206
+ ui.applyFailed?.({ code: "GROUP_PERSISTENCE_FAILED", message: "Group intent could not be persisted. No target files were changed.",
207
+ rolledBack: [], unresolved: [], notApplied: ready.map(r => r.plan.rel) });
208
+ await Promise.all(ready.map(r => fail(r.p, "GROUP_PERSISTENCE_FAILED", "Group intent could not be persisted. No target files were changed.")));
209
+ return;
210
+ }
211
+ }
212
+ const reconcileGroup = () => {
213
+ if (!group)
214
+ return;
215
+ try {
216
+ const report = reconcileMutationGroups(scope).groups.find(g => g.groupId === group.group_id);
217
+ if (report)
218
+ ui.note([report.message]);
219
+ }
220
+ catch {
221
+ ui.note([`Group ${group.group_id}: recovery state is unresolved; evidence was preserved.`]);
222
+ }
223
+ };
224
+ // Approved: apply in order; verify each rollback and report unresolved files.
95
225
  const done = [];
96
226
  for (let i = 0; i < ready.length; i += 1) {
97
227
  const { p, plan } = ready[i];
98
228
  try {
99
- done.push({ p, change: applyPlan(plan) });
229
+ if (opts.signal?.aborted)
230
+ throw new MutationError("MUTATION_CANCELLED", "The turn was cancelled before mutation. Nothing further was applied.");
231
+ const prepared = group ? startGroupMember(root, group.group_id, plan.operationId) : undefined;
232
+ done.push({ p, change: applyPlan(plan, scope, prepared, opts.signal) });
233
+ if (group)
234
+ appliedGroupMember(root, group.group_id, plan.operationId);
100
235
  }
101
236
  catch (err) {
102
237
  const e = err instanceof MutationError ? err : new MutationError("WRITE_FAILED", err.message);
103
- for (const d of [...done].reverse())
104
- rollbackApplied(d.change);
105
- ui.note([` ✗ ${plan.rel}: ${e.message}`, ...(done.length ? [" ↺ Earlier changes in this group were rolled back."] : [])]);
238
+ if (group) {
239
+ try {
240
+ failGroupMember(root, group.group_id, plan.operationId);
241
+ }
242
+ catch {
243
+ ui.note([`Group ${group.group_id}: failure state could not be persisted; recovery evidence retained.`]);
244
+ }
245
+ }
246
+ const outcomes = [...done].reverse().map(d => ({ ...d, restored: rollbackApplied(d.change) }));
247
+ const unresolved = outcomes.filter(d => !d.restored);
248
+ if (unresolved.length || e.code === "MUTATION_UNRESOLVED" || e.code === "MUTATION_CANCELLED")
249
+ stopped = true;
250
+ ui.note([` ✗ ${plan.rel}: ${e.message}`,
251
+ ...outcomes.map(d => d.restored
252
+ ? ` ↺ ${d.change.repositoryName}/${d.change.rel}: rolled back.`
253
+ : ` ✗ ${d.change.repositoryName}/${d.change.rel}: rollback unresolved; file may remain modified. Recovery checkpoint ${d.change.checkpointId} preserved.`)]);
254
+ ui.applyFailed?.({
255
+ failed: plan.rel, code: e.code, message: e.message,
256
+ rolledBack: outcomes.filter(d => d.restored).map(d => d.change.rel),
257
+ // The failing file itself may also be left modified (its own recovery unresolved).
258
+ unresolved: [...unresolved.map(d => ({ rel: d.change.rel, checkpointId: d.change.checkpointId })),
259
+ ...(e.recovery?.unresolved ? [{ rel: plan.rel, checkpointId: e.recovery.checkpointId }] : [])],
260
+ notApplied: ready.slice(i + 1).map(r => r.plan.rel)
261
+ });
262
+ reconcileGroup();
106
263
  await Promise.all([
107
- ...done.map((d) => fail(d.p, "ROLLED_BACK", `Rolled back because the change to ${plan.rel} failed.`)),
108
- fail(p, e.code, e.message),
264
+ ...outcomes.map((d) => fail(d.p, d.restored ? "ROLLED_BACK" : "ROLLBACK_UNRESOLVED", d.restored ? `Rolled back because the change to ${plan.rel} failed.`
265
+ : `${d.change.repositoryName}/${d.change.rel}: rollback unresolved; file may remain modified. Recovery checkpoint ${d.change.checkpointId} (operation ${d.change.operationId}) preserved.`)),
266
+ ...(done.some(d => d.p === p) ? [] : [fail(p, e.code, e.message)]),
109
267
  ...ready.slice(i + 1).map((r) => fail(r.p, "NOT_APPLIED", `Not applied because the change to ${plan.rel} failed.`))
110
268
  ]);
111
269
  return;
112
270
  }
113
271
  }
272
+ reconcileGroup();
114
273
  applied.push(...done.map((d) => d.change));
115
274
  ui.note(done.map((d) => {
116
275
  // Say WHICH repository once the workspace has more than one; in a single
117
276
  // repository the name would be noise on every line.
118
277
  const where = inWorkspaceMode() ? `${d.change.repositoryName}/` : "";
119
- return ` ✓ ${VERB[d.change.name] ?? "Changed"} ${where}${d.change.rel} (+${d.change.added} −${d.change.removed})`;
278
+ return ` ✓ ${VERB[d.change.name] ?? "Changed"} ${where}${d.change.rel} (+${d.change.added} −${d.change.removed}) · Applied · ${d.change.operationId}`;
120
279
  }));
121
280
  await Promise.all(done.map((d) => succeed(d.p, d.change)));
122
281
  }
@@ -128,7 +287,10 @@ export function createMutationCoordinator(opts) {
128
287
  chain = chain
129
288
  .then(() => review(batch))
130
289
  .catch(async () => {
131
- // A failure here is a bug, not a decision — never leave a call unanswered.
290
+ // Preserve finalized payloads; outbox retry must not become a second,
291
+ // contradictory submission after one member's transport failed.
292
+ if (batch.some(p => p.result))
293
+ ui.note(["Result delivery did not complete. Any saved results can be retried without rerunning file changes."]);
132
294
  await Promise.all(batch.map((p) => fail(p, "TOOL_FAILED", "The change could not be processed.").catch(() => undefined)));
133
295
  })
134
296
  .finally(() => batch.forEach((p) => p.done()));
@@ -136,6 +298,10 @@ export function createMutationCoordinator(opts) {
136
298
  return {
137
299
  applied,
138
300
  handle(call) {
301
+ // A repeated id is the same call: it is reviewed and answered at most once.
302
+ if (seen.has(call.tool_call_id))
303
+ return Promise.resolve();
304
+ seen.add(call.tool_call_id);
139
305
  const started = Date.now();
140
306
  received += 1;
141
307
  if (received > MAX_MUTATIONS_PER_TURN) {