@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
@@ -1,6 +1,6 @@
1
1
  import chalk from "chalk";
2
2
  import { ApiError } from "./api.js";
3
- import { deviceLabel, localPlatformDefault, openBrowser, platformAuthBase, pollForToken, startDeviceAuthorization, withPlatformOrigin } from "./device-auth.js";
3
+ import { deviceLabel, localAuthorizeDefault, openBrowser, userCliAuthBase, pollForToken, startDeviceAuthorization, withPlatformOrigin } from "./device-auth.js";
4
4
  import { info, line } from "./output.js";
5
5
  import { sleep, withSpinner } from "./spinner.js";
6
6
  import { c } from "../ui/colors.js";
@@ -14,25 +14,48 @@ import { c } from "../ui/colors.js";
14
14
  * Opening your browser…
15
15
  * ✓ Browser opened <verification url> Code XXXX-XXXX
16
16
  * ⠋ Waiting for approval… (in-place spinner)
17
- * ✓ Device authorized / Workspace / Project / Session / Authentication successful
17
+ * ✓ Device authorized / Session synchronized / Logged in as <account>
18
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
+ }
19
38
  export async function deviceLogin(ctx, apiUrl) {
20
- const authBase = platformAuthBase(apiUrl);
39
+ const authBase = userCliAuthBase(apiUrl);
21
40
  // Branding + intro first (shown for both `cos` first-run and `cos login`).
22
41
  line();
23
42
  line(" " + c.brand("Welcome to Carrier OS"));
24
- line(" " + c.dim("Sign in with your Carrier OS Developer account."));
43
+ line(" " + c.dim("Sign in with your Carrier OS account."));
25
44
  line();
26
45
  info("Opening your browser…");
27
46
  const start = await startDeviceAuthorization(authBase, deviceLabel());
28
- // Resolve the platform origin for the browser step. Precedence: explicit
29
- // config `platformUrl` → env CARRIEROS_PLATFORM_URL → a localhost default when
30
- // the API itself is local (so `cos` "just works" against a local stack) →
31
- // otherwise trust the URL the API returned.
47
+ // Where the browser goes to authorize this request.
48
+ //
49
+ // The API decides the PATH — /cli/authorize on the main Carrier OS site — and
50
+ // the overrides below only ever swap the origin, so a local override cannot
51
+ // send the browser to a page that does not exist. Precedence: explicit config
52
+ // `platformUrl` → env CARRIEROS_PLATFORM_URL → a localhost guess when the API
53
+ // is local but pointed at a production site → otherwise trust the API.
54
+ const apiUri = start.verification_uri_complete || start.verification_uri;
32
55
  const override = ctx.config.get("platformUrl") ||
33
56
  process.env.CARRIEROS_PLATFORM_URL ||
34
- localPlatformDefault(apiUrl);
35
- const openUrl = withPlatformOrigin(start.verification_uri_complete || start.verification_uri, override);
57
+ localAuthorizeDefault(apiUrl, apiUri);
58
+ const openUrl = withPlatformOrigin(apiUri, override);
36
59
  const opened = openBrowser(openUrl);
37
60
  line();
38
61
  line(" " + (opened ? chalk.green("✓") + " Browser opened." : chalk.yellow("!") + " Couldn't open your browser."));
@@ -44,16 +67,26 @@ export async function deviceLogin(ctx, apiUrl) {
44
67
  // Waiting state — a single in-place spinner (never scrolls). Polling is
45
68
  // unchanged; the spinner just animates until it resolves or throws.
46
69
  const tokens = await withSpinner(chalk.dim("Waiting for approval…"), () => pollForToken(authBase, start));
47
- 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)}`;
48
81
  }
49
82
  /** The success sequence — a short animated checklist, then persist + verify,
50
83
  * ending on "Logged in as <email>" (the shell then pauses + shows the welcome). */
51
- async function renderAuthorized(ctx, tokens) {
84
+ async function renderAuthorized(ctx, tokens, apiUrl) {
52
85
  const ok = (msg) => line(" " + chalk.green("✓") + " " + msg);
53
86
  line();
54
87
  ok("Device authorized");
55
88
  await sleep(150);
56
- const scope = await persistSession(ctx, tokens);
89
+ const scope = await persistSession(ctx, tokens, apiUrl);
57
90
  ok("Session synchronized");
58
91
  await sleep(130);
59
92
  const email = scope.user?.email ?? tokens.account?.email;
@@ -65,17 +98,22 @@ async function renderAuthorized(ctx, tokens) {
65
98
  }
66
99
  /** Save the issued tokens + a cached scope; land in Carrier Chat by default.
67
100
  * (Unchanged behaviour — persistence + a verify to confirm the token works.) */
68
- async function persistSession(ctx, tokens) {
101
+ export async function persistSession(ctx, tokens, issuer) {
69
102
  ctx.config.update({
70
103
  auth: {
71
104
  accessToken: tokens.access_token,
72
105
  refreshToken: tokens.refresh_token,
106
+ // Which server issued this session. Only its refusal ends the session.
107
+ apiUrl: issuer,
73
108
  account: tokens.account,
74
109
  workspace: tokens.workspace ?? null,
75
110
  project: tokens.project ?? null
76
111
  }
77
112
  });
78
- ctx.config.set("chatType", "carrier");
113
+ // A conversation keeps its type forever. Reset the saved session too: a
114
+ // previous Standard session must not resume under the new Carrier label.
115
+ ctx.setChatType("carrier");
116
+ ctx.config.set("sessionTitle", undefined);
79
117
  let scope;
80
118
  try {
81
119
  scope = await ctx.client().verify();
@@ -89,8 +127,8 @@ async function persistSession(ctx, tokens) {
89
127
  function scopeFromTokens(tokens) {
90
128
  return {
91
129
  apiKey: null,
92
- workspace: tokens.workspace ?? { id: "", name: "—", slug: "" },
93
- project: tokens.project ?? { id: "", name: "—", projectId: "", environment: "" },
130
+ workspace: tokens.workspace ?? null,
131
+ project: tokens.project ?? null,
94
132
  user: tokens.account ? { id: tokens.account.id, email: tokens.account.email } : null
95
133
  };
96
134
  }
@@ -1,7 +1,9 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { fileURLToPath } from "node:url";
3
- /** Read the CLI's own version from package.json (works in dev and after build). */
3
+ /** The CLI's own version — from the baked constant when packaged, else package.json. */
4
4
  export function cliVersion() {
5
+ if (typeof __CLI_VERSION__ === "string" && __CLI_VERSION__)
6
+ return __CLI_VERSION__;
5
7
  try {
6
8
  const pkgUrl = new URL("../../package.json", import.meta.url);
7
9
  const pkg = JSON.parse(readFileSync(fileURLToPath(pkgUrl), "utf8"));
@@ -0,0 +1,327 @@
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";
4
+ import { inWorkspaceMode } from "./workspace-registry.js";
5
+ const VERB = {
6
+ create_file: "Created",
7
+ write_file: "Overwrote",
8
+ edit_file: "Edited",
9
+ delete_file: "Deleted",
10
+ revert_change: "Reverted"
11
+ };
12
+ export function createMutationCoordinator(opts) {
13
+ const windowMs = opts.windowMs ?? 150;
14
+ const { ui } = opts;
15
+ const queue = [];
16
+ const applied = [];
17
+ let received = 0;
18
+ let timer = null;
19
+ let chain = Promise.resolve();
20
+ let stopped = false;
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, {
37
+ tool_call_id: p.call.tool_call_id,
38
+ ok: false,
39
+ error: { code, message },
40
+ duration_ms: Date.now() - p.started
41
+ });
42
+ const succeed = (p, change) => submitOnce(p, {
43
+ tool_call_id: p.call.tool_call_id,
44
+ ok: true,
45
+ result: appliedResult(change),
46
+ duration_ms: Date.now() - p.started
47
+ });
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
+ }
54
+ if (stopped) {
55
+ // A "no" ends proposals for the turn. The model asks the user what they
56
+ // want instead of offering variations until one is accepted.
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)));
60
+ return;
61
+ }
62
+ // Plan everything first. A proposal that cannot be planned is answered
63
+ // straight away — nothing touched disk, so there is nothing to approve.
64
+ const ready = [];
65
+ const seen = new Set();
66
+ for (const p of batch) {
67
+ try {
68
+ const plan = planMutation(p.call);
69
+ // Two repositories can hold the same relative path, so identity here is
70
+ // the repository AND the path.
71
+ const key = `${plan.repositoryId}:${plan.rel.toLowerCase()}`;
72
+ if (seen.has(key)) {
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);
76
+ continue;
77
+ }
78
+ if (reviewLineCount(plan) > MAX_REVIEW_LINES) {
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);
82
+ continue;
83
+ }
84
+ seen.add(key);
85
+ ready.push({ p, plan });
86
+ }
87
+ catch (err) {
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 });
91
+ await fail(p, e.code, e.message);
92
+ }
93
+ }
94
+ if (ready.length === 0)
95
+ return;
96
+ // One approval, one repository.
97
+ //
98
+ // A group is approved as a unit, with verified rollback on failure. "All" has to
99
+ // mean something a person can hold in their head: these files, in this
100
+ // repository. A group spanning two repositories would ask for one yes
101
+ // covering two boundaries, and a rollback would have to reach across both.
102
+ // It is refused rather than split, because splitting it would decide on the
103
+ // user's behalf which half they meant.
104
+ const repositories = [...new Set(ready.map((r) => r.plan.repositoryId))];
105
+ if (repositories.length > 1) {
106
+ const names = [...new Set(ready.map((r) => r.plan.repositoryName))].join(", ");
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.` });
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.`)));
111
+ return;
112
+ }
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
+ }
141
+ if (decision !== "approve") {
142
+ const code = decision === "timeout" ? "APPROVAL_TIMEOUT" : decision === "cancel" ? "MUTATION_CANCELLED" : "MUTATION_REJECTED";
143
+ const message = decision === "timeout"
144
+ ? "No one approved the change in time. Nothing was 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."]);
152
+ stopped = true;
153
+ await Promise.all(ready.map((r) => fail(r.p, code, message)));
154
+ if (decision === "cancel")
155
+ ui.cancelTurn();
156
+ return;
157
+ }
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.
225
+ const done = [];
226
+ for (let i = 0; i < ready.length; i += 1) {
227
+ const { p, plan } = ready[i];
228
+ try {
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);
235
+ }
236
+ catch (err) {
237
+ const e = err instanceof MutationError ? err : new MutationError("WRITE_FAILED", err.message);
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();
263
+ await Promise.all([
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)]),
267
+ ...ready.slice(i + 1).map((r) => fail(r.p, "NOT_APPLIED", `Not applied because the change to ${plan.rel} failed.`))
268
+ ]);
269
+ return;
270
+ }
271
+ }
272
+ reconcileGroup();
273
+ applied.push(...done.map((d) => d.change));
274
+ ui.note(done.map((d) => {
275
+ // Say WHICH repository once the workspace has more than one; in a single
276
+ // repository the name would be noise on every line.
277
+ const where = inWorkspaceMode() ? `${d.change.repositoryName}/` : "";
278
+ return ` ✓ ${VERB[d.change.name] ?? "Changed"} ${where}${d.change.rel} (+${d.change.added} −${d.change.removed}) · Applied · ${d.change.operationId}`;
279
+ }));
280
+ await Promise.all(done.map((d) => succeed(d.p, d.change)));
281
+ }
282
+ function flush() {
283
+ timer = null;
284
+ const batch = queue.splice(0, MAX_FILES_PER_APPROVAL);
285
+ if (queue.length)
286
+ timer = setTimeout(flush, 0);
287
+ chain = chain
288
+ .then(() => review(batch))
289
+ .catch(async () => {
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."]);
294
+ await Promise.all(batch.map((p) => fail(p, "TOOL_FAILED", "The change could not be processed.").catch(() => undefined)));
295
+ })
296
+ .finally(() => batch.forEach((p) => p.done()));
297
+ }
298
+ return {
299
+ applied,
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);
305
+ const started = Date.now();
306
+ received += 1;
307
+ if (received > MAX_MUTATIONS_PER_TURN) {
308
+ return opts
309
+ .submit({
310
+ tool_call_id: call.tool_call_id,
311
+ ok: false,
312
+ error: {
313
+ code: "MUTATION_LIMIT_REACHED",
314
+ message: `At most ${MAX_MUTATIONS_PER_TURN} file changes can be proposed in one turn.`
315
+ },
316
+ duration_ms: 0
317
+ })
318
+ .catch(() => undefined);
319
+ }
320
+ return new Promise((resolve) => {
321
+ queue.push({ call, started, done: resolve });
322
+ if (!timer)
323
+ timer = setTimeout(flush, windowMs);
324
+ });
325
+ }
326
+ };
327
+ }