@cotal-ai/cli 0.164.7 → 0.164.9

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.
@@ -3,7 +3,8 @@ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync }
3
3
  import { tmpdir } from "node:os";
4
4
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
5
  import { globalConfigDir } from "@cotal-ai/core";
6
- import { CommandFailure, jsonFlag, plainFlag, presentationOf, protectedLocalDirectory, renderReport, writeResult, cmdSpawnSpec, beginGlobalUpdateChild, processStartToken, claimUpdateClosureAccess, updateClosureOwner, readUpdateRecovery, clearUpdateRecovery, writeUpdateRecovery, readUpdateSettings, recordUpdateCompletion, recordUpdateDeferral, recordUpdateReplacement, setUpdateSetting, bindExtensionPeers, claimGlobalNpmUpdateLock, launcherInstallRoot, loadExtensionsManifest, provenance, SEEDED_EXTENSIONS, targetFlags, resolveControlTarget, } from "@cotal-ai/workspace";
6
+ import { CommandFailure, jsonFlag, plainFlag, presentationOf, protectedLocalDirectory, renderReport, writeResult, cmdSpawnSpec, beginGlobalUpdateChild, processStartToken, claimUpdateClosureAccess, updateClosureOwner, readUpdateRecovery, clearUpdateRecovery, writeUpdateRecovery, readUpdateSettings, recordUpdateCompletion, recordUpdateDeferral, recordUpdateReplacement, setUpdateSetting, bindExtensionPeers, claimGlobalNpmUpdateLock, launcherInstallRoot, loadExtensionsManifest, provenance, SEEDED_EXTENSIONS, targetFlags, resolveControlTarget, recoveryDisposition, liveUpdateClosureOwner, recoveryProcessStartToken, observeUnownedRecovery, } from "@cotal-ai/workspace";
7
+ import { retainUnusableRecovery } from "../lib/update-recovery-state.js";
7
8
  import { readUpdatePending } from "../lib/update-pending.js";
8
9
  import { snapshotUpdateClosure } from "../lib/update-snapshot.js";
9
10
  import { EXT_UPDATE_PARENT_ENV } from "./ext.js";
@@ -23,6 +24,7 @@ import { observeServiceProcess, serviceInstances } from "../lib/service-instance
23
24
  import { ConnectRefusal, isWorkspaceTargetError, localMeshesForRoot, preparedNeverStarted, pruneStaleMeshes, renderWorkspaceError, resolveMeshTarget, } from "@cotal-ai/workspace";
24
25
  import { refreshOwnedCompletions } from "../lib/completion-install.js";
25
26
  import { legacyManagerReport, legacySeatLabel } from "../lib/legacy-manager-report.js";
27
+ import { recordedStackRemedy } from "../lib/recorded-stack-remedy.js";
26
28
  import { askManager } from "@cotal-ai/workspace/control";
27
29
  import { cliControl, onFlag } from "../lib/control.js";
28
30
  import { managerPin } from "../lib/manager-choice.js";
@@ -85,6 +87,7 @@ export const updateRuntime = {
85
87
  checkout: () => seedWriterKind() === "checkout",
86
88
  installPrefix: () => installedUpdatePrefix(cliPackageRoot(), entryScript()),
87
89
  npm: runNpm,
90
+ npmAsync: runNpmAsync,
88
91
  spawn: runProcess,
89
92
  spawnGlobal: runGlobalProcess,
90
93
  verifyGlobalEntry,
@@ -153,50 +156,109 @@ export async function update(args, rt = updateRuntime) {
153
156
  }
154
157
  }
155
158
  /** Resume an abandoned replacement before a command or daemon can activate its closure. */
156
- export async function recoverInterruptedUpdate(rt = updateRuntime) {
157
- const record = readUpdateRecovery();
158
- if (!record?.owner || childBinding(rt).kind === "bound")
159
+ export async function recoverInterruptedUpdate(rt = updateRuntime, startup = false) {
160
+ if (childBinding(rt).kind === "bound")
159
161
  return false;
160
- const start = processStartToken(record.owner.pid);
161
- if (start !== undefined && start === record.owner.start)
162
+ const observed = readUpdateRecovery();
163
+ if (!observed)
162
164
  return false;
165
+ if (startup) {
166
+ // A restarted daemon must answer the updater that still owns the closure. It may only
167
+ // observe that live transaction here, never compete with it for restoration authority.
168
+ if (liveUpdateClosureOwner(observed, rt.recoveryOwnerStart ?? recoveryProcessStartToken))
169
+ return false;
170
+ }
163
171
  const release = claimUpdateClosureAccess(true);
164
172
  try {
165
- if (!record.snapshot)
166
- throw new Error("interrupted update has no closure snapshot");
167
- writeUpdateRecovery({ ...record, owner: updateClosureOwner(), phase: "restoring" });
168
- const snapshot = snapshotUpdateClosure(record.snapshot);
169
- const prefix = rt.installPrefix();
170
- const selected = rt.npm(["root", "-g", ...(prefix ? ["--prefix", prefix] : [])]);
171
- const root = selected.stdout.trim();
172
- if (selected.status !== 0 || !isAbsolute(root) || /[\r\n]/.test(root))
173
- throw new Error("cannot identify interrupted update installation");
174
- const releaseGlobal = rt.claimGlobalUpdate(root);
173
+ const record = readUpdateRecovery();
174
+ if (!record)
175
+ return false;
176
+ const now = rt.now?.() ?? Date.now();
177
+ let decision = recoveryDisposition(record, now, rt.recoveryOwnerStart ?? recoveryProcessStartToken);
178
+ if (decision.action === "wait") {
179
+ try {
180
+ observeUnownedRecovery(now);
181
+ }
182
+ catch (error) {
183
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `${decision.instruction} Cannot save the first observation: ${message(error)}`, { remedy: "correct access to the Cotal home, then run `cotal update --self`" });
184
+ }
185
+ decision = recoveryDisposition(record, now, rt.recoveryOwnerStart ?? recoveryProcessStartToken);
186
+ }
187
+ if (decision.action === "retire") {
188
+ let retained;
189
+ try {
190
+ retained = retainUnusableRecovery(record, now);
191
+ }
192
+ catch (error) {
193
+ throw new CommandFailure("refused", "CONFLICT", `${decision.instruction} Retention could not complete: ${message(error)}`, { remedy: "inspect the recovery records and retained folders in the Cotal home, correct access, then run `cotal update --self`" });
194
+ }
195
+ rt.out(`Retained unusable interrupted-update records in ${retained}; continuing the update.`);
196
+ return false;
197
+ }
198
+ if (startup && (decision.action === "wait" || decision.action === "active" || decision.action === "restore" && record.phase === "paused"))
199
+ return false;
200
+ if (decision.action !== "restore")
201
+ throw new CommandFailure("refused", decision.action === "active" ? "LIFECYCLE_BLOCKED" : decision.action === "wait" ? "CONFLICT" : "DEPENDENCY_UNAVAILABLE", decision.instruction, { native: { code: decision.action === "active" ? "UPDATE_RECOVERY_OWNER_ACTIVE" : decision.action === "wait" ? "UPDATE_RECOVERY_OBSERVATION_WAIT" : "UPDATE_RECOVERY_INSPECTION_FAILED" }, remedy: "follow the recovery instruction above, then run `cotal update --self`" });
202
+ if (!record.owner)
203
+ return false;
204
+ const start = processStartToken(record.owner.pid);
205
+ if (start !== undefined && start === record.owner.start)
206
+ return false;
175
207
  try {
176
- checkReleaseArchives(record.previous, rt);
177
- const command = cmdSpawnSpec("npm", ["install", "-g", ...(prefix ? ["--prefix", prefix] : []), `cotal-ai@${record.previous}`]);
178
- const installed = await rt.spawnGlobal(root, "install", command.file, command.args, rt.env, true, command.windowsVerbatimArguments);
179
- if (installed.status !== 0)
180
- throw new Error(failure(installed));
181
- const entry = rt.verifyGlobalEntry(root, record.previous);
182
- snapshot.restore();
183
- const env = { ...rt.env, [UPDATE_TARGET_ENV]: record.previous, [UPDATE_PARENT_ENV]: String(rt.pid) };
184
- const reconciled = await rt.spawnGlobal(root, "reconcile", rt.nodePath, [entry, "update"], env, true);
185
- if (reconciled.status !== 0)
186
- throw new Error(failure(reconciled));
187
- snapshot.discard();
188
- clearUpdateRecovery();
189
- rt.out(`Restored cotal-ai@${record.previous} after an interrupted update.`);
190
- return true;
208
+ if (!record.snapshot)
209
+ throw new Error("interrupted update has no closure snapshot");
210
+ writeUpdateRecovery({ ...record, owner: updateClosureOwner(), phase: "restoring" });
211
+ const snapshot = snapshotUpdateClosure(record.snapshot);
212
+ const completedRollback = !startup && record.phase === "paused" && record.installed === record.previous
213
+ && record.renames !== undefined && record.renames.length > 0 && record.renames.every(entry => entry.done);
214
+ const prefix = rt.installPrefix();
215
+ const selected = rt.npm(["root", "-g", ...(prefix ? ["--prefix", prefix] : [])]);
216
+ const root = selected.stdout.trim();
217
+ if (selected.status !== 0 || !isAbsolute(root) || /[\r\n]/.test(root))
218
+ throw new Error("cannot identify interrupted update installation");
219
+ const releaseGlobal = rt.claimGlobalUpdate(root);
220
+ try {
221
+ if (completedRollback) {
222
+ const version = rt.version();
223
+ const entry = rt.verifyGlobalEntry(root, version);
224
+ if (realpathSync(entry) !== realpathSync(entryScript()))
225
+ throw new Error("paused repair must run from the verified installed CLI");
226
+ snapshot.restore();
227
+ const env = { ...rt.env, [UPDATE_TARGET_ENV]: version, [UPDATE_PARENT_ENV]: String(rt.pid) };
228
+ const reconciled = await rt.spawnGlobal(root, "reconcile", rt.nodePath, [entry, "update"], env, true);
229
+ if (reconciled.status !== 0)
230
+ throw new Error(failure(reconciled));
231
+ snapshot.discard();
232
+ clearUpdateRecovery();
233
+ recordUpdateCompletion(version, `repaired paused installation at ${version}`, true);
234
+ rt.out(`Repaired the paused installation with cotal-ai@${version}; the machine service and its hosted Managers were verified.`);
235
+ return true;
236
+ }
237
+ checkReleaseArchives(record.previous, rt);
238
+ const command = cmdSpawnSpec("npm", ["install", "-g", ...(prefix ? ["--prefix", prefix] : []), `cotal-ai@${record.previous}`]);
239
+ const installed = await rt.spawnGlobal(root, "install", command.file, command.args, rt.env, true, command.windowsVerbatimArguments);
240
+ if (installed.status !== 0)
241
+ throw new Error(failure(installed));
242
+ const entry = rt.verifyGlobalEntry(root, record.previous);
243
+ snapshot.restore();
244
+ const env = { ...rt.env, [UPDATE_TARGET_ENV]: record.previous, [UPDATE_PARENT_ENV]: String(rt.pid) };
245
+ const reconciled = await rt.spawnGlobal(root, "reconcile", rt.nodePath, [entry, "update"], env, true);
246
+ if (reconciled.status !== 0)
247
+ throw new Error(failure(reconciled));
248
+ snapshot.discard();
249
+ clearUpdateRecovery();
250
+ rt.out(`Restored cotal-ai@${record.previous} after an interrupted update.`);
251
+ return true;
252
+ }
253
+ finally {
254
+ releaseGlobal();
255
+ }
191
256
  }
192
- finally {
193
- releaseGlobal();
257
+ catch (error) {
258
+ writeUpdateRecovery({ ...readUpdateRecovery(), phase: "paused", reason: `interrupted update restore failed: ${message(error)}` });
259
+ throw error;
194
260
  }
195
261
  }
196
- catch (error) {
197
- writeUpdateRecovery({ ...readUpdateRecovery(), phase: "paused", reason: `interrupted update restore failed: ${message(error)}` });
198
- throw error;
199
- }
200
262
  finally {
201
263
  release();
202
264
  }
@@ -313,7 +375,6 @@ export async function executeUpdate(self, rt = updateRuntime, target = {}) {
313
375
  rt.out("No newer CLI version; installed package closure is current. No connector reconciliation was run.");
314
376
  if (custody === "legacy")
315
377
  rt.out("A later update will require stopping the agents listed above before replacing packages.");
316
- rt.out("Run `cotal update` to repair connector integrations.");
317
378
  reportVersion(current, latest.version, rt, false);
318
379
  return 0;
319
380
  }
@@ -372,8 +433,11 @@ async function reconcileCurrent(current, rt, target, finish) {
372
433
  return finish(false);
373
434
  }
374
435
  try {
436
+ rt.out("Refreshing connector integrations");
437
+ const refreshStarted = Date.now();
375
438
  for (const line of await rt.refreshConnectors())
376
439
  rt.out(c.green(`✓ ${line}`));
440
+ rt.out(`✓ connector integrations refreshed (${((Date.now() - refreshStarted) / 1000).toFixed(1)} s)`);
377
441
  }
378
442
  catch (e) {
379
443
  rt.err(c.red(`✗ connector installs: ${message(e)}`));
@@ -434,7 +498,9 @@ async function reconcileCurrent(current, rt, target, finish) {
434
498
  };
435
499
  delete env[UPDATE_TARGET_ENV];
436
500
  delete env[UPDATE_PARENT_ENV];
501
+ const extensionStarted = Date.now();
437
502
  const result = rt.spawn(bin, [...argv, "ext", "__update-add", entry.pkg, spec], env);
503
+ rt.out(`✓ extension ${entry.pkg} install finished (${((Date.now() - extensionStarted) / 1000).toFixed(1)} s)`);
438
504
  writeChildOutput(result);
439
505
  if (result.status !== 0) {
440
506
  rt.err(c.red(`✗ ${entry.pkg}: ${failure(result)}`));
@@ -696,17 +762,26 @@ export async function readManagerContinuity(flags) {
696
762
  : []);
697
763
  if (!report)
698
764
  return "none";
699
- printLegacyReport(report, target.space, undefined, console.log, on);
765
+ const remedy = typeof flags.creds === "string" ? undefined : recordedStackRemedy(target.root, target.space, target.server, (status.data ?? {}));
766
+ printLegacyReport(report, target.space, undefined, console.log, on, remedy);
700
767
  return "legacy";
701
768
  }
702
769
  /** Name legacy custody and the cold update sequence without guessing its hosting lifecycle.
703
770
  * An endpoint identity is not a saved service instance or proof of its original starter.
704
771
  * The third argument is retained for callers, but an unverified stop command is not a remedy. */
705
- export function printLegacyReport(report, space, _stop = undefined, out = console.log, manager) {
772
+ export function printLegacyReport(report, space, _stop = undefined, out = console.log, manager, recorded) {
706
773
  out(c.yellow("! legacy manager custody: PTY continuity is impossible; this update is not a hot update"));
707
774
  out(` Manager ${manager ?? "(instance unavailable)"} in space ${JSON.stringify(space)}: ${report.seats.length} seats`);
708
775
  for (const seat of report.seats)
709
776
  out(c.dim(` ${legacySeatLabel(seat)}: ${seat.continuity}`));
777
+ if (recorded) {
778
+ out(` Recorded stack root: ${recorded.root}`);
779
+ out(" This is a manual cold update. The listed seats end and are not restarted. Nothing was stopped by this command.");
780
+ out(" Run these commands in order:");
781
+ for (const command of recorded.commands)
782
+ out(` ${command}`);
783
+ return;
784
+ }
710
785
  out(" Cannot determine this Manager's original hosting command. Obtain its exact stop and start commands before stopping it; do not infer a service instance from its Manager identity.");
711
786
  out(" Next: stop this Manager through its original host, ending any seats listed above; run `cotal update --self`, then restart through that host with the original start command. This is a cold update, including for a Manager with 0 seats.");
712
787
  }
@@ -746,51 +821,68 @@ function checkInstalledClosure(version, rt) {
746
821
  }
747
822
  /** Fetch the target's first-party install closure through npm, including integrity verification.
748
823
  * A private cache forces a registry read without changing the installed packages or running scripts. */
749
- function checkReleaseArchives(version, rt) {
824
+ async function checkReleaseArchives(version, rt) {
750
825
  const cache = mkdtempSync(join(tmpdir(), "cotal-release-check-"));
751
826
  const options = ["--cache", cache, "--logs-max=0", "--update-notifier=false", "--fetch-retries=0", "--fetch-timeout=15000", "--prefer-online"];
752
827
  const pending = new Set(["cotal-ai"]);
828
+ const names = ["cotal-ai"];
753
829
  try {
754
- for (const name of pending) {
755
- const spec = `${name}@${version}`;
756
- const manifest = rt.npm(["view", spec, "--json", ...options]);
757
- if (manifest.status !== 0)
758
- throw new Error(`metadata for ${spec} is unavailable`);
759
- let meta;
760
- try {
761
- const parsed = JSON.parse(manifest.stdout);
762
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
763
- throw new Error();
764
- meta = parsed;
765
- if (meta.name !== name || meta.version !== version)
766
- throw new Error();
767
- const dist = meta.dist;
768
- if (typeof dist?.tarball !== "string" || !dist.tarball || typeof dist.integrity !== "string" || !dist.integrity)
769
- throw new Error();
770
- }
771
- catch {
772
- throw new Error(`metadata for ${spec} is incomplete or invalid`);
773
- }
774
- for (const field of ["dependencies", "optionalDependencies", "peerDependencies"]) {
775
- const deps = meta[field];
776
- if (deps === undefined)
777
- continue;
778
- if (!deps || typeof deps !== "object" || Array.isArray(deps))
779
- throw new Error(`invalid ${field} for ${spec}`);
780
- for (const [dependency, range] of Object.entries(deps)) {
781
- if (!dependency.startsWith("@cotal-ai/"))
830
+ for (let offset = 0; offset < names.length;) {
831
+ const batch = names.slice(offset, offset + 3);
832
+ // Settle every read before validating or removing its shared private cache. Validation below
833
+ // stays in discovery order, including when independent registry requests finish out of order.
834
+ const manifests = await Promise.allSettled(batch.map(name => rt.npmAsync(["view", `${name}@${version}`, "--json", ...options])));
835
+ offset += batch.length;
836
+ for (const [index, name] of batch.entries()) {
837
+ const spec = `${name}@${version}`;
838
+ const result = manifests[index];
839
+ if (result.status === "rejected")
840
+ throw new Error(`metadata for ${spec} is unavailable`);
841
+ const manifest = result.value;
842
+ if (manifest.status !== 0)
843
+ throw new Error(`metadata for ${spec} is unavailable`);
844
+ let meta;
845
+ try {
846
+ const parsed = JSON.parse(manifest.stdout);
847
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
848
+ throw new Error();
849
+ meta = parsed;
850
+ if (meta.name !== name || meta.version !== version)
851
+ throw new Error();
852
+ const dist = meta.dist;
853
+ if (typeof dist?.tarball !== "string" || !dist.tarball || typeof dist.integrity !== "string" || !dist.integrity)
854
+ throw new Error();
855
+ }
856
+ catch {
857
+ throw new Error(`metadata for ${spec} is incomplete or invalid`);
858
+ }
859
+ for (const field of ["dependencies", "optionalDependencies", "peerDependencies"]) {
860
+ const deps = meta[field];
861
+ if (deps === undefined)
782
862
  continue;
783
- if (!/^@cotal-ai\/[a-z0-9][a-z0-9._-]*$/.test(dependency) || typeof range !== "string" ||
784
- (field !== "peerDependencies" && range !== version))
785
- throw new Error(`invalid first-party dependency in ${spec}`);
786
- pending.add(dependency);
863
+ if (!deps || typeof deps !== "object" || Array.isArray(deps))
864
+ throw new Error(`invalid ${field} for ${spec}`);
865
+ for (const [dependency, range] of Object.entries(deps)) {
866
+ if (!dependency.startsWith("@cotal-ai/"))
867
+ continue;
868
+ if (!/^@cotal-ai\/[a-z0-9][a-z0-9._-]*$/.test(dependency) || typeof range !== "string" ||
869
+ (field !== "peerDependencies" && range !== version))
870
+ throw new Error(`invalid first-party dependency in ${spec}`);
871
+ if (!pending.has(dependency)) {
872
+ pending.add(dependency);
873
+ names.push(dependency);
874
+ }
875
+ }
787
876
  }
788
877
  }
789
- // npm applies the configured registry, scoped authentication, proxy/TLS policy and SRI checks.
790
- // cache add downloads only this archive, so enumerate the dependency closure above as well.
791
- const archive = rt.npm(["cache", "add", spec, "--ignore-scripts", ...options]);
878
+ }
879
+ // npm verifies each archive's integrity and applies registry, scoped auth and proxy/TLS policy.
880
+ // Its cache add accepts multiple specs. Bound each group rather than starting npm per archive.
881
+ for (let offset = 0; offset < names.length; offset += 6) {
882
+ const specs = names.slice(offset, offset + 6).map(name => `${name}@${version}`);
883
+ const archive = await rt.npmAsync(["cache", "add", ...specs, "--ignore-scripts", ...options]);
792
884
  if (archive.status !== 0)
793
- throw new Error(`archive for ${spec} could not be downloaded and verified`);
885
+ throw new Error(`archives for ${specs.join(", ")} could not be downloaded and verified`);
794
886
  }
795
887
  }
796
888
  finally {
@@ -843,11 +935,16 @@ async function upgradeAndReconcile(targetVersion, current, rt, target) {
843
935
  rt.err(c.red(`✗ running manager continuity check: ${refusal(e)}`));
844
936
  return 1;
845
937
  }
938
+ const releaseChecksStarted = Date.now();
846
939
  try {
847
- checkReleaseArchives(targetVersion, rt);
940
+ rt.out(`Checking cotal-ai@${targetVersion} release archives`);
941
+ await checkReleaseArchives(targetVersion, rt);
942
+ rt.out(`Checking installed extension dependencies for ${targetVersion}`);
848
943
  checkInstalledClosure(targetVersion, rt);
849
944
  // A previous generation must remain downloadable and verified before replacement begins.
850
- checkReleaseArchives(current, rt);
945
+ rt.out(`Checking cotal-ai@${current} recovery archives`);
946
+ await checkReleaseArchives(current, rt);
947
+ rt.out(`✓ release archives checked (${((Date.now() - releaseChecksStarted) / 1000).toFixed(1)} s)`);
851
948
  }
852
949
  catch (e) {
853
950
  recordUpdateDeferral(targetVersion, "waiting for registry or extension closure availability", true);
@@ -920,9 +1017,12 @@ async function upgradeAndReconcile(targetVersion, current, rt, target) {
920
1017
  }
921
1018
  let releaseClosure;
922
1019
  let snapshot;
1020
+ const snapshotStarted = Date.now();
923
1021
  try {
924
1022
  releaseClosure = claimUpdateClosureAccess();
1023
+ rt.out("Saving update recovery snapshot");
925
1024
  snapshot = snapshotUpdateClosure();
1025
+ rt.out(`✓ recovery snapshot saved (${((Date.now() - snapshotStarted) / 1000).toFixed(1)} s)`);
926
1026
  }
927
1027
  catch (error) {
928
1028
  releaseClosure?.();
@@ -952,7 +1052,9 @@ async function upgradeAndReconcile(targetVersion, current, rt, target) {
952
1052
  recordUpdateReplacement(targetVersion);
953
1053
  writeUpdateRecovery({ previous: current, target: targetVersion, installed: current, phase: "replacing", reason: "global replacement in progress", owner: updateClosureOwner(), preparedRestart: rt.preparedRestart?.() ?? false, snapshot: snapshot.path });
954
1054
  const npmInstall = cmdSpawnSpec("npm", ["install", "-g", ...prefixArgs, `cotal-ai@${targetVersion}`, "--json"]);
1055
+ const installStarted = Date.now();
955
1056
  const installed = await rt.spawnGlobal(root, "install", npmInstall.file, npmInstall.args, rt.env, false, npmInstall.windowsVerbatimArguments);
1057
+ rt.out(`✓ global package install finished (${((Date.now() - installStarted) / 1000).toFixed(1)} s)`);
956
1058
  if (latestNotAvailable(installed, targetVersion)) {
957
1059
  // npm resolves the requested version before reifying the global tree. This refusal
958
1060
  // did not replace packages, so neither rollback nor a failed-attempt charge applies.
@@ -969,6 +1071,7 @@ async function upgradeAndReconcile(targetVersion, current, rt, target) {
969
1071
  rt.err(c.red(`✗ global cotal-ai@${targetVersion} install failed: ${failure(installed)}`));
970
1072
  return await repairReplacement(`global install failed: ${failure(installed)}`);
971
1073
  }
1074
+ rt.out("Verifying installed global entry");
972
1075
  let entry;
973
1076
  try {
974
1077
  entry = rt.verifyGlobalEntry(root, targetVersion);
@@ -984,7 +1087,10 @@ async function upgradeAndReconcile(targetVersion, current, rt, target) {
984
1087
  [UPDATE_PARENT_ENV]: String(rt.pid),
985
1088
  };
986
1089
  delete env[EXT_UPDATE_PARENT_ENV];
1090
+ rt.out(`Reconciling installed cotal-ai@${targetVersion}`);
1091
+ const reconcileStarted = Date.now();
987
1092
  const child = await rt.spawnGlobal(root, "reconcile", rt.nodePath, [entry, "update", ...targetArgv(target)], env, true);
1093
+ rt.out(`✓ installed reconciliation finished (${((Date.now() - reconcileStarted) / 1000).toFixed(1)} s)`);
988
1094
  if (child.stderr)
989
1095
  rt.stderr(child.stderr);
990
1096
  if (child.stdout)
@@ -993,6 +1099,7 @@ async function upgradeAndReconcile(targetVersion, current, rt, target) {
993
1099
  rt.err(c.red(`✗ cotal-ai@${targetVersion} installed globally, but its reconcile failed: ${failure(child)}`));
994
1100
  return await repairReplacement(`reconcile failed: ${failure(child)}`, child.status ?? 1);
995
1101
  }
1102
+ rt.out("Removing completed update recovery snapshot");
996
1103
  snapshot.discard();
997
1104
  clearUpdateRecovery();
998
1105
  recordUpdateCompletion(targetVersion, `updated to ${targetVersion}`, true);
@@ -1029,7 +1136,7 @@ async function upgradeAndReconcile(targetVersion, current, rt, target) {
1029
1136
  if (!recovery)
1030
1137
  throw new Error("update recovery journal is missing");
1031
1138
  writeUpdateRecovery({ ...recovery, phase: "restoring" });
1032
- checkReleaseArchives(current, rt);
1139
+ await checkReleaseArchives(current, rt);
1033
1140
  const command = cmdSpawnSpec("npm", ["install", "-g", ...prefixArgs, `cotal-ai@${current}`]);
1034
1141
  const restored = await rt.spawnGlobal(root, "install", command.file, command.args, rt.env, true, command.windowsVerbatimArguments);
1035
1142
  if (restored.status !== 0)
@@ -1154,6 +1261,21 @@ export function verifyGlobalEntry(root, expectedVersion) {
1154
1261
  throw new Error(`the installed cotal executable escapes its package: ${entry}`);
1155
1262
  return entry;
1156
1263
  }
1264
+ async function runNpmAsync(args) {
1265
+ try {
1266
+ const { file, args: spawnArgs, windowsVerbatimArguments } = cmdSpawnSpec("npm", args);
1267
+ const child = spawn(file, spawnArgs, { windowsVerbatimArguments, windowsHide: true });
1268
+ let stdout = "", stderr = "", error;
1269
+ child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); });
1270
+ child.stderr?.on("data", (chunk) => { stderr += chunk.toString(); });
1271
+ child.once("error", cause => { error = cause.message; });
1272
+ const status = await new Promise(resolveClose => child.once("close", resolveClose));
1273
+ return { status, stdout, stderr, ...(error ? { error } : {}) };
1274
+ }
1275
+ catch (error) {
1276
+ return { status: null, stdout: "", stderr: "", error: message(error) };
1277
+ }
1278
+ }
1157
1279
  function runNpm(args, inherit = false) {
1158
1280
  try {
1159
1281
  const { file, args: spawnArgs, windowsVerbatimArguments } = cmdSpawnSpec("npm", args);