@cotal-ai/cli 0.171.4 → 0.172.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 (85) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +54 -21
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/down.d.ts.map +1 -1
  5. package/dist/commands/down.js +19 -6
  6. package/dist/commands/down.js.map +1 -1
  7. package/dist/commands/ext.d.ts +1 -1
  8. package/dist/commands/ext.d.ts.map +1 -1
  9. package/dist/commands/ext.js +70 -13
  10. package/dist/commands/ext.js.map +1 -1
  11. package/dist/commands/help.js +2 -2
  12. package/dist/commands/help.js.map +1 -1
  13. package/dist/commands/service-actions.d.ts.map +1 -1
  14. package/dist/commands/service-actions.js +22 -12
  15. package/dist/commands/service-actions.js.map +1 -1
  16. package/dist/commands/space-registration.d.ts.map +1 -1
  17. package/dist/commands/space-registration.js +9 -3
  18. package/dist/commands/space-registration.js.map +1 -1
  19. package/dist/commands/space.d.ts.map +1 -1
  20. package/dist/commands/space.js +40 -29
  21. package/dist/commands/space.js.map +1 -1
  22. package/dist/commands/spawn.js +1 -1
  23. package/dist/commands/spawn.js.map +1 -1
  24. package/dist/commands/stack-down.d.ts.map +1 -1
  25. package/dist/commands/stack-down.js +5 -4
  26. package/dist/commands/stack-down.js.map +1 -1
  27. package/dist/commands/stack-up.d.ts +5 -0
  28. package/dist/commands/stack-up.d.ts.map +1 -1
  29. package/dist/commands/stack-up.js +46 -20
  30. package/dist/commands/stack-up.js.map +1 -1
  31. package/dist/commands/status.d.ts +2 -1
  32. package/dist/commands/status.d.ts.map +1 -1
  33. package/dist/commands/status.js +50 -28
  34. package/dist/commands/status.js.map +1 -1
  35. package/dist/commands/up.d.ts +1 -1
  36. package/dist/commands/up.d.ts.map +1 -1
  37. package/dist/commands/up.js +34 -22
  38. package/dist/commands/up.js.map +1 -1
  39. package/dist/commands/update.d.ts +6 -5
  40. package/dist/commands/update.d.ts.map +1 -1
  41. package/dist/commands/update.js +281 -39
  42. package/dist/commands/update.js.map +1 -1
  43. package/dist/commands/whoami.d.ts.map +1 -1
  44. package/dist/commands/whoami.js +2 -1
  45. package/dist/commands/whoami.js.map +1 -1
  46. package/dist/lib/broker-service.d.ts +6 -4
  47. package/dist/lib/broker-service.d.ts.map +1 -1
  48. package/dist/lib/broker-service.js +36 -6
  49. package/dist/lib/broker-service.js.map +1 -1
  50. package/dist/lib/extension-stage.d.ts +1 -1
  51. package/dist/lib/extension-stage.d.ts.map +1 -1
  52. package/dist/lib/extension-stage.js +26 -11
  53. package/dist/lib/extension-stage.js.map +1 -1
  54. package/dist/lib/restore.d.ts +3 -2
  55. package/dist/lib/restore.d.ts.map +1 -1
  56. package/dist/lib/restore.js +12 -10
  57. package/dist/lib/restore.js.map +1 -1
  58. package/dist/lib/self-exec.d.ts +2 -0
  59. package/dist/lib/self-exec.d.ts.map +1 -1
  60. package/dist/lib/self-exec.js +5 -1
  61. package/dist/lib/self-exec.js.map +1 -1
  62. package/dist/lib/service-preset-target.d.ts +2 -1
  63. package/dist/lib/service-preset-target.d.ts.map +1 -1
  64. package/dist/lib/service-preset-target.js +11 -2
  65. package/dist/lib/service-preset-target.js.map +1 -1
  66. package/dist/lib/service-systemd.d.ts +3 -3
  67. package/dist/lib/service-systemd.d.ts.map +1 -1
  68. package/dist/lib/service-systemd.js +6 -6
  69. package/dist/lib/service-systemd.js.map +1 -1
  70. package/dist/lib/up-report.d.ts.map +1 -1
  71. package/dist/lib/up-report.js +9 -6
  72. package/dist/lib/up-report.js.map +1 -1
  73. package/dist/lib/update-pending.d.ts +1 -0
  74. package/dist/lib/update-pending.d.ts.map +1 -1
  75. package/dist/lib/update-pending.js +4 -3
  76. package/dist/lib/update-pending.js.map +1 -1
  77. package/dist/lib/version.d.ts +1 -0
  78. package/dist/lib/version.d.ts.map +1 -1
  79. package/dist/lib/version.js +2 -2
  80. package/dist/lib/version.js.map +1 -1
  81. package/dist/seed/reconcile.d.ts +2 -0
  82. package/dist/seed/reconcile.d.ts.map +1 -1
  83. package/dist/seed/reconcile.js +30 -11
  84. package/dist/seed/reconcile.js.map +1 -1
  85. package/package.json +4 -4
@@ -1,28 +1,29 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { lookup } from "node:dns/promises";
3
- import { existsSync, lstatSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { existsSync, lstatSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import { isIP, SocketAddress } from "node:net";
6
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
+ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
7
7
  import { globalConfigDir } from "@cotal-ai/core";
8
- import { CommandFailure, isCommandFailure, jsonFlag, plainFlag, presentationOf, protectedLocalDirectory, renderReport, writeResult, cmdSpawnSpec, beginGlobalUpdateChild, processGroupMembers, processStartToken, claimUpdateClosureAccess, updateClosureOwner, homeCotalDir, readUpdateRecovery, clearUpdateRecovery, writeUpdateRecovery, readUpdateSettings, recordUpdateCompletion, recordUpdateDeferral, recordUpdateRefusal, recordUpdateReplacement, setUpdateSetting, bindExtensionPeers, claimGlobalNpmUpdateLock, launcherInstallRoot, logicalExecutionEntry, loadExtensionsManifest, provenance, SEEDED_EXTENSIONS, targetFlags, resolveControlTarget, recoveryDisposition, liveUpdateClosureOwner, recoveryProcessStartToken, observeUnownedRecovery, } from "@cotal-ai/workspace";
8
+ import { CommandFailure, isCommandFailure, jsonFlag, plainFlag, presentationOf, protectedLocalDirectory, renderReport, writeResult, cmdSpawnSpec, oneLine, beginGlobalUpdateChild, processGroupMembers, processStartToken, claimUpdateClosureAccess, updateClosureOwner, homeCotalDir, isMeshRegistryError, preparedRecordSkipped, preparedRecordSpace, preparedSpacesDir, readPreparedSpaces, recordOperationWarning, readUpdateRecovery, clearUpdateRecovery, writeUpdateRecovery, readUpdateSettings, observeUpdateVersion, UPDATE_HOUR_MS, recordUpdateCompletion, recordUpdateDeferral, recordUpdateReleaseHold, recordUpdateRefusal, recordUpdateReplacement, prepareConnectorConfigForUpdate, setUpdateSetting, bindExtensionPeers, claimGlobalNpmUpdateLock, launcherInstallRoot, logicalExecutionEntry, loadExtensionsManifest, provenance, SEEDED_EXTENSIONS, targetFlags, resolveControlTarget, recoveryDisposition, liveUpdateClosureOwner, recoveryProcessStartToken, observeUnownedRecovery, UnreadableConnectorSelection, } from "@cotal-ai/workspace";
9
9
  import { retainUnusableRecovery } from "../lib/update-recovery-state.js";
10
10
  import { readUpdatePending } from "../lib/update-pending.js";
11
11
  import { snapshotUpdateClosure } from "../lib/update-snapshot.js";
12
12
  import { EXT_UPDATE_PARENT_ENV } from "./ext.js";
13
13
  import { claimExtensionUpdatePass } from "../lib/ext-mutation.js";
14
+ import { recoverExtensionPromotion } from "../lib/extension-stage.js";
14
15
  import { selfArgv } from "../lib/self-exec.js";
15
16
  import { repairInstallModes, withInstallUmask } from "../lib/install-umask.js";
16
17
  import { cliVersion, installedCliVersion } from "../lib/version.js";
17
- import { runSeed, compareSemver, seedInstallationCurrent, assertReadableSeedState } from "../seed/reconcile.js";
18
+ import { runSeed, compareSemver, seedInstallationCurrent, assertReadableSeedState, readSeedRepairRefusal } from "../seed/reconcile.js";
18
19
  import { operatorInstallDiffers } from "../seed/verify.js";
19
20
  import { cliPackageRoot, entryScript, seedWriterKind } from "../seed/paths.js";
20
21
  import { refreshConnectorInstalls } from "./setup.js";
21
22
  import { c } from "../ui.js";
22
23
  import { assertEndpointUnreachable } from "../lib/endpoint-cut.js";
23
- import { supervisorMayServe } from "../lib/manager-proc.js";
24
+ import { isCliEntry, supervisorMayServe } from "../lib/manager-proc.js";
24
25
  import { processGone, readStackJournal, stackScopeRefusals } from "../lib/stack-journal.js";
25
- import { observeServiceProcess, serviceInstances } from "../lib/service-instances.js";
26
+ import { observeServiceProcess, serviceInstances, serviceInstanceStore } from "../lib/service-instances.js";
26
27
  import { ConnectRefusal, isConnectRefusal, isWorkspaceTargetError, localMeshesForRoot, preparedNeverStarted, pruneStaleMeshes, renderWorkspaceError, resolveMeshTarget, } from "@cotal-ai/workspace";
27
28
  import { refreshOwnedCompletions } from "../lib/completion-install.js";
28
29
  import { legacyManagerReport, legacySeatLabel } from "../lib/legacy-manager-report.js";
@@ -50,6 +51,7 @@ export const updateFlags = [
50
51
  ...targetFlags,
51
52
  onFlag,
52
53
  ];
54
+ const MISSING_NPM_REMEDY = "Install npm or add it to this command's PATH, then retry.";
53
55
  export { installedCliVersion, repairInstallModes };
54
56
  export const updateRuntime = {
55
57
  env: process.env,
@@ -212,6 +214,7 @@ async function updateInstallation(args, rt) {
212
214
  remedy: "update the desktop app with its signed platform installer; no npm self-update was attempted",
213
215
  });
214
216
  }
217
+ let connectorSelection;
215
218
  if (args.values.self === true) {
216
219
  try {
217
220
  rt.preflightExecution?.();
@@ -226,6 +229,40 @@ async function updateInstallation(args, rt) {
226
229
  native: { outcome: "not-executed" },
227
230
  });
228
231
  }
232
+ try {
233
+ if (rt.prepareExecution) {
234
+ prepareConnectorConfigForUpdate();
235
+ if (recoverExtensionPromotion(true))
236
+ prepareConnectorConfigForUpdate();
237
+ }
238
+ else
239
+ recoverExtensionPromotion();
240
+ }
241
+ catch (error) {
242
+ if (error instanceof UnreadableConnectorSelection)
243
+ connectorSelection = error;
244
+ else {
245
+ const failure = isCommandFailure(error) ? error : new CommandFailure("refused", "PERMISSION_DENIED", `Cannot prepare the Cotal connector configuration: ${message(error)}. No CLI update was staged.`, {
246
+ native: { outcome: "not-executed" }, remedy: "Correct the reported connector configuration problem, then run `cotal update --self` again.",
247
+ });
248
+ recordUpdateDeferral(rt.version(), `connector configuration preflight: ${preflightDetail(failure)}`);
249
+ throw failure;
250
+ }
251
+ }
252
+ // Built-in self-update skips the extension overlay. Validate its inventory after recovery.
253
+ if (!connectorSelection)
254
+ try {
255
+ loadExtensionsManifest();
256
+ }
257
+ catch (error) {
258
+ if (error instanceof UnreadableConnectorSelection)
259
+ connectorSelection = error;
260
+ else {
261
+ rt.err(c.red(`✗ ${message(error)}`));
262
+ process.exitCode = 1;
263
+ return;
264
+ }
265
+ }
229
266
  }
230
267
  const restored = await recoverInterruptedUpdate(rt);
231
268
  if (restored) {
@@ -254,7 +291,7 @@ async function updateInstallation(args, rt) {
254
291
  if (repaired)
255
292
  rt.out(c.green(`✓ removed group and other write from ${repaired} ${repaired === 1 ? "entry" : "entries"} in Cotal's ${what} at ${root}`));
256
293
  }
257
- const code = await executeUpdate(Boolean(args.values.self), rt, args.values);
294
+ const code = await executeUpdate(Boolean(args.values.self), rt, args.values, restored ? undefined : connectorSelection);
258
295
  if (code !== 0)
259
296
  process.exitCode = code;
260
297
  else if (args.values.self !== true && childBinding(rt).kind !== "bound") {
@@ -428,34 +465,53 @@ function checkUpdate(args, rt) {
428
465
  warnings.push({ code: "EXTENSION_INVENTORY_UNREADABLE", target: null, message: "The extension inventory could not be read. It was not repaired or treated as empty." });
429
466
  }
430
467
  const latest = latestVersion(rt);
468
+ const missingNpm = !latest.ok && latest.missingNpm;
431
469
  if (!latest.ok)
432
- warnings.push({ code: "LATEST_VERSION_UNAVAILABLE", target: null, message: "The registry did not return a valid latest version. Update availability is unknown." });
470
+ warnings.push(missingNpm
471
+ ? { code: "NPM_UNAVAILABLE", target: null, message: "npm is not on PATH. Update availability is unknown." }
472
+ : { code: "LATEST_VERSION_UNAVAILABLE", target: null, message: "The registry did not return a valid latest version. Update availability is unknown." });
433
473
  const comparison = latest.ok ? compareSemver(latest.version, current) : null;
434
- const pending = readUpdatePending(current);
435
- if (pending.kind === "unreadable")
436
- warnings.push({ code: "RECONCILIATION_UNREADABLE", target: null, message: `Reconciliation state could not be read: ${pending.error}` });
437
- const result = { kind: "update-check", reconciliation: pending, current, latest: latest.ok ? latest.version : null, updateAvailable: comparison === null ? null : comparison > 0, extensions, scope: "registry version and recorded installation versions", installationChanged: false, processesRestarted: false };
474
+ let reconciliation = readUpdatePending(current);
475
+ if (reconciliation.kind === "none" || reconciliation.kind === "version-mismatch") {
476
+ try {
477
+ const refusal = readSeedRepairRefusal(current);
478
+ if (refusal)
479
+ reconciliation = { kind: "seed", instruction: refusal.message };
480
+ }
481
+ catch (error) {
482
+ reconciliation = { kind: "unreadable", source: "seed", error: refusal(error), instruction: "Run `cotal ext seed --repair` to reconcile the connectors." };
483
+ }
484
+ }
485
+ if (reconciliation.kind === "unreadable")
486
+ warnings.push({ code: "RECONCILIATION_UNREADABLE", target: null, message: `Reconciliation state could not be read: ${reconciliation.error}` });
487
+ if (reconciliation.kind === "seed")
488
+ warnings.push({ code: "OPERATION_PARTIAL", target: null, message: reconciliation.instruction });
489
+ const manifestUnreadable = reconciliation.kind === "unreadable" && reconciliation.source === "manifest";
490
+ const result = { kind: "update-check", reconciliation, current, latest: latest.ok ? latest.version : null, updateAvailable: comparison === null ? null : comparison > 0, extensions, scope: "registry version and recorded installation versions", installationChanged: false, processesRestarted: false };
438
491
  writeResult(presentationOf(args.values), {
439
492
  command: "update", target: null, result, warnings,
440
- ...(warnings.length ? { completeness: "partial", partial: { message: "Some update information could not be established.", remedy: "Check registry access or the unreadable inventory and repeat update --check." } } : {}),
493
+ ...(warnings.length ? { completeness: "partial", partial: {
494
+ message: reconciliation.kind === "seed" ? "Connector seeding needs reconciliation." : "Some update information could not be established.",
495
+ remedy: reconciliation.kind === "seed" || reconciliation.kind === "unreadable" && reconciliation.source !== "receipt" ? reconciliation.instruction : missingNpm ? MISSING_NPM_REMEDY : "Check registry access or the unreadable inventory and repeat update --check.",
496
+ } } : {}),
441
497
  }, (r) => ({ sections: [
442
- ...(pending.kind === "none" ? [] : [{ title: "Reconciliation", blocks: [{ kind: "lines", lines: [pending.instruction] }] }]),
498
+ ...(r.reconciliation.kind === "none" ? [] : [{ title: "Reconciliation", blocks: [{ kind: "lines", lines: [r.reconciliation.instruction] }] }]),
443
499
  { title: "Update availability", blocks: [{ kind: "fields", rows: [["Running CLI", r.current], ["Registry latest", r.latest ?? "not established"], ["CLI update", r.updateAvailable === null ? { text: "unknown", tone: "waiting" } : r.updateAvailable ? { text: "available", tone: "waiting" } : comparison === 0 ? "matches latest tag" : "running version is ahead of latest tag"]] }] },
444
500
  { title: "Recorded extensions", blocks: [r.extensions === null ? { kind: "lines", lines: [{ text: "Inventory unavailable. No repair was attempted.", tone: "waiting" }] } : r.extensions.length ? { kind: "table", columns: [{ key: "package", label: "Package" }, { key: "version", label: "Recorded version" }, { key: "state", label: "Generation" }], rows: r.extensions.map((entry) => ({ package: entry.package, version: entry.version, state: !entry.firstParty ? { text: "third party", tone: "hint" } : entry.matchesCli ? { text: "matches running CLI", tone: "ok" } : { text: "differs from running CLI", tone: "waiting" } })) } : { kind: "lines", lines: ["No extensions in the recorded inventory."] }, { kind: "lines", lines: [{ text: "Version records only. Package contents, signatures and running processes were not checked. No installation was reconciled or restarted.", tone: "hint" }] }] },
445
- { title: "Next", blocks: [{ kind: "commands", items: [{ command: "cotal update", description: "Reconcile the current generation through the existing guarded updater" }, ...(r.updateAvailable ? [{ command: "cotal update --self", description: rt.checkout() ? "Install the verified latest CLI as a separate global copy and reconcile through it; this checkout does not change" : "Install the verified latest CLI and reconcile its generation" }] : []), { command: "cotal status", description: "Inspect this machine and its selected space" }] }] },
501
+ ...(manifestUnreadable ? [] : [{ title: "Next", blocks: [{ kind: "commands", items: [{ command: "cotal update", description: "Reconcile the current generation through the existing guarded updater" }, ...(r.updateAvailable ? [{ command: "cotal update --self", description: rt.checkout() ? "Install the verified latest CLI as a separate global copy and reconcile through it; this checkout does not change" : "Install the verified latest CLI and reconcile its generation" }] : []), { command: "cotal status", description: "Inspect this machine and its selected space" }] }] }]),
446
502
  ] }));
447
503
  }
448
504
  /** Injectable command body: production keeps one process seam; the smoke covers every decision branch. */
449
- export async function executeUpdate(self, rt = updateRuntime, target = {}) {
505
+ export async function executeUpdate(self, rt = updateRuntime, target = {}, unreadableSelection) {
450
506
  const current = rt.version();
451
- if (self && rt.env.COTAL_AUTO_UPDATE === "1")
452
- recordUpdateDeferral(current, "waiting for update preflight");
453
507
  const child = childBinding(rt);
454
508
  if (child.kind === "invalid") {
455
509
  rt.err(c.red(`✗ invalid global update child binding: ${child.reason}; refusing to mutate extensions`));
456
510
  return 1;
457
511
  }
458
512
  if (child.kind === "bound") {
513
+ if (self && rt.env.COTAL_AUTO_UPDATE === "1")
514
+ recordUpdateDeferral(current, "waiting for update preflight");
459
515
  if (current !== child.target) {
460
516
  rt.err(c.red(`✗ global update child is cotal-ai ${current}, expected ${child.target}; refusing to mutate extensions`));
461
517
  return 1;
@@ -496,22 +552,52 @@ export async function executeUpdate(self, rt = updateRuntime, target = {}) {
496
552
  if (self) {
497
553
  const latest = latestVersion(rt);
498
554
  if (!latest.ok) {
555
+ if (latest.missingNpm) {
556
+ if (rt.env.COTAL_AUTO_UPDATE === "1")
557
+ recordUpdateDeferral(current, "waiting for npm availability", true);
558
+ rt.err(c.red(`✗ cotal-ai version check failed: ${latest.error}. ${MISSING_NPM_REMEDY}`));
559
+ return 1;
560
+ }
561
+ if (!latest.npmResult || !(releaseReadError(latest.npmResult, "cotal-ai version check failed") instanceof RegistryUnavailable)) {
562
+ rt.err(c.red(`✗ cotal-ai version check failed: ${oneLine(latest.error.split(/\r?\n/, 1)[0])}`));
563
+ return 1;
564
+ }
499
565
  if (rt.env.COTAL_AUTO_UPDATE === "1")
500
566
  recordUpdateDeferral(current, "waiting for registry availability", true);
501
- else if (latest.npmResult && await npmProxyRefused(latest.npmResult, rt.env)) {
567
+ else if (await npmProxyRefused(latest.npmResult, rt.env)) {
502
568
  rt.err("The npm proxy refused the connection (ECONNREFUSED). The update did not start. Check HTTP_PROXY and HTTPS_PROXY, then retry.");
503
569
  return 1;
504
570
  }
505
571
  rt.out("The registry cannot be reached; nothing was changed.");
506
572
  return 0;
507
573
  }
508
- if (compareSemver(latest.version, current) > 0) {
574
+ const upgrading = compareSemver(latest.version, current) > 0;
575
+ if (rt.env.COTAL_AUTO_UPDATE === "1") {
576
+ // The live npm lookup can select a different version from the one the daemon held.
577
+ const next = await observeUpdateVersion(latest.version) + UPDATE_HOUR_MS;
578
+ if (upgrading && Date.now() < next) {
579
+ recordUpdateReleaseHold(latest.version, next);
580
+ return 0;
581
+ }
582
+ recordUpdateDeferral(current, "waiting for update preflight");
583
+ }
584
+ if (upgrading) {
585
+ // Replacing packages still requires an identifiable graph for dependency checks and rollback.
586
+ if (unreadableSelection)
587
+ throw unreadableSelection;
509
588
  const code = await upgradeAndReconcile(latest.version, current, rt, target);
510
589
  if (code === 0 && rt.env.COTAL_AUTO_UPDATE !== "1")
511
590
  rt.generationWaited = true;
512
591
  return code;
513
592
  }
593
+ if (unreadableSelection) {
594
+ rt.err(unreadableSelection.message);
595
+ rt.out("No newer CLI version. No connector reconciliation was run.");
596
+ reportVersion(current, latest.version, rt, false);
597
+ return 0;
598
+ }
514
599
  if (rt.isCurrent?.()) {
600
+ reportUncheckedPreparedRecords(rt, target);
515
601
  rt.out("No newer CLI version; installed package closure is current. No connector reconciliation was run.");
516
602
  if (rt.env.COTAL_AUTO_UPDATE === "1")
517
603
  recordUpdateCompletion(current, "up to date", true);
@@ -544,6 +630,25 @@ export async function executeUpdate(self, rt = updateRuntime, target = {}) {
544
630
  return reconciled ? 0 : 1;
545
631
  });
546
632
  }
633
+ function reportUncheckedPreparedRecords(rt, target) {
634
+ if (["server", "creds", "on"].some(key => typeof target[key] === "string"))
635
+ return;
636
+ // The installed child may carry a daemon admission receipt and never resolve the project.
637
+ // Report read failures separately from the Manager custody verdict and package reconciliation.
638
+ try {
639
+ for (const error of readPreparedSpaces().unusable) {
640
+ if (error.refusal !== "PERMISSION_DENIED")
641
+ continue;
642
+ if (typeof target.space === "string" && target.space !== preparedRecordSpace(error.file))
643
+ continue;
644
+ recordOperationWarning(preparedRecordSkipped(error));
645
+ rt.out(c.dim(` ${error.file}: leaving its records and processes untouched, continuity not checked`));
646
+ }
647
+ }
648
+ catch (error) {
649
+ rt.err(`Could not check prepared space records: ${message(error)}; continuity not checked`);
650
+ }
651
+ }
547
652
  async function reconcileCurrent(current, rt, target, finish) {
548
653
  try {
549
654
  await rt.prepareReconciliation?.(target);
@@ -571,6 +676,7 @@ async function reconcileCurrent(current, rt, target, finish) {
571
676
  rt.err(c.red(`✗ running manager continuity check: ${refusal(e)}`));
572
677
  return finish(false, true);
573
678
  }
679
+ reportUncheckedPreparedRecords(rt, target);
574
680
  try {
575
681
  await rt.preflightReplacement?.();
576
682
  }
@@ -854,6 +960,38 @@ export async function readUpdateManagerContinuity(manager, flags, readOne = read
854
960
  return "none";
855
961
  }
856
962
  }
963
+ /** Link the answering Manager to the controller's live process before excluding its installation. */
964
+ function isForeignStackManager(target, status, installedEntry) {
965
+ if (process.platform !== "linux" || !target.root || !status || typeof status.instanceId !== "string" || typeof status.lifecycleUid !== "string")
966
+ return false;
967
+ try {
968
+ const journal = readStackJournal(target.root)?.journal;
969
+ if (!journal || journal.operation.kind !== "up" || journal.operation.phase !== "completed" || journal.space !== target.space || brokerAddressKey(journal.server) !== brokerAddressKey(target.server))
970
+ return false;
971
+ const member = journal.members.find(row => row.role === "manager");
972
+ if (!member?.instanceId || !member.process)
973
+ return false;
974
+ const instance = serviceInstanceStore(target.space).read(member.instanceId)?.record.value;
975
+ const native = instance?.adapterReadiness?.native;
976
+ if (!instance?.process || instance.definition !== member.definition || instance.state !== "running" ||
977
+ instance.process.pid !== member.process.pid || instance.process.token !== member.process.token ||
978
+ native?.instanceId !== status.instanceId || native.lifecycleUid !== status.lifecycleUid || observeServiceProcess(instance) !== "running")
979
+ return false;
980
+ const argv = readFileSync(`/proc/${instance.process.pid}/cmdline`, "utf8").split("\0");
981
+ // The controller places only the optional global color flag after its Node entry.
982
+ const verb = argv.indexOf("__service-manager");
983
+ const launch = argv[verb - (argv[verb - 1] === "--no-color" ? 2 : 1)];
984
+ if (!launch || !isAbsolute(launch))
985
+ return false;
986
+ const entry = realpathSync(launch);
987
+ const own = realpathSync(installedEntry ?? logicalExecutionEntry() ?? entryScript());
988
+ return entry !== own && isCliEntry(entry) && assertRecordIdentity(instance.process).kind === "match";
989
+ }
990
+ catch {
991
+ // An unreadable record or launch entry cannot prove a different installation.
992
+ return false;
993
+ }
994
+ }
857
995
  export async function readManagerContinuity(flags, options = {}) {
858
996
  const { readMeshRegistry } = await import("@cotal-ai/workspace");
859
997
  const registry = readMeshRegistry();
@@ -900,6 +1038,16 @@ export async function readManagerContinuity(flags, options = {}) {
900
1038
  peek = resolveMeshTarget(process.cwd(), { server, space, offline });
901
1039
  }
902
1040
  catch (e) {
1041
+ // An unreadable prepared record is not evidence about Manager custody. The updater can
1042
+ // leave it alone only if it was not asked for a broker or instance and has no potentially
1043
+ // running registration or supervisor to check for the affected target.
1044
+ if (isMeshRegistryError(e) && e.refusal === "PERMISSION_DENIED" && dirname(e.file) === preparedSpacesDir()) {
1045
+ const name = preparedRecordSpace(e.file);
1046
+ if (name !== undefined && server === undefined && on === undefined &&
1047
+ !registry.entries.some(entry => space === undefined ? !offline?.includes(entry.space) : entry.space === space) &&
1048
+ !supervisorMayServe(name, options.installedEntry))
1049
+ return "none";
1050
+ }
903
1051
  if (!isWorkspaceTargetError(e))
904
1052
  throw e;
905
1053
  // Sudo can inspect another account's project without owning its controller records.
@@ -1021,6 +1169,8 @@ export async function readManagerContinuity(flags, options = {}) {
1021
1169
  return "none";
1022
1170
  throw new Error(status.error ?? "manager status request failed");
1023
1171
  }
1172
+ if (typeof flags.creds !== "string" && isForeignStackManager(target, status.data, options.installedEntry))
1173
+ return "none";
1024
1174
  const seats = await askManager(cliControl, target.space, target.server, "ps", undefined, target.auth, "owner", undefined, pin);
1025
1175
  if (!seats.ok)
1026
1176
  throw new Error(seats.error ?? "manager seat inventory request failed");
@@ -1068,6 +1218,8 @@ function latestVersion(rt) {
1068
1218
  const cache = mkdtempSync(join(tmpdir(), "cotal-npm-view-"));
1069
1219
  try {
1070
1220
  const result = rt.npm(["view", "cotal-ai@latest", "version", "--json", "--cache", cache, "--logs-max=0", "--update-notifier=false", "--fetch-retries=0", "--fetch-timeout=15000"]);
1221
+ if (result.errorCode === "ENOENT")
1222
+ return { ok: false, error: "npm is not on PATH", missingNpm: true };
1071
1223
  if (result.status !== 0)
1072
1224
  return { ok: false, error: failure(result), npmResult: result };
1073
1225
  try {
@@ -1125,12 +1277,17 @@ async function npmProxyRefused(result, env) {
1125
1277
  }
1126
1278
  }
1127
1279
  /** Resolve installed first-party surfaces in a disposable prefix, including their npm dependencies. */
1128
- function checkInstalledClosure(version, rt) {
1280
+ function checkInstalledClosure(version, releasePackages, rt) {
1129
1281
  const names = [...new Set(rt.extensions().filter(entry => entry.pkg.startsWith("@cotal-ai/")).map(entry => entry.pkg))];
1130
1282
  if (!names.length)
1131
1283
  return;
1132
1284
  const staging = mkdtempSync(join(tmpdir(), "cotal-closure-check-"));
1133
1285
  try {
1286
+ // Reconciliation supplies first-party peers from the target CLI, not the registry's latest tag.
1287
+ // Constrain npm to that verified release graph without skipping third-party peers.
1288
+ writeFileSync(join(staging, "package.json"), JSON.stringify({
1289
+ overrides: Object.fromEntries([...releasePackages, ...names].map(name => [name, version])),
1290
+ }));
1134
1291
  const result = rt.npm(["install", "--prefix", staging, "--cache", join(staging, ".npm-cache"), "--logs-max=0", "--update-notifier=false", "--ignore-scripts", "--package-lock=false", "--no-audit", "--no-fund", "--fetch-retries=2", "--fetch-retry-mintimeout=1000", "--fetch-retry-maxtimeout=2000", "--fetch-timeout=15000", "--prefer-online", ...names.map(name => `${name}@${version}`)]);
1135
1292
  if (result.signal)
1136
1293
  throw new DependencyCheckInterrupted(`npm dependency check was terminated by ${result.signal}`);
@@ -1217,6 +1374,7 @@ async function checkReleaseArchives(version, rt) {
1217
1374
  if (archive.status !== 0)
1218
1375
  throw releaseReadError(archive, `archives for ${specs.join(", ")} could not be downloaded and verified`);
1219
1376
  }
1377
+ return pending;
1220
1378
  }
1221
1379
  finally {
1222
1380
  rmSync(cache, { recursive: true, force: true, maxRetries: 3 });
@@ -1307,7 +1465,7 @@ class DependencyCheckNoSpace extends Error {
1307
1465
  }
1308
1466
  class RegistryUnavailable extends Error {
1309
1467
  }
1310
- const NETWORK_ERROR_CODE = /^(?:ENETUNREACH|EHOSTUNREACH|ENETDOWN|EHOSTDOWN|ECONNRESET|ECONNREFUSED|ECONNABORTED|ETIMEDOUT|ESOCKETTIMEDOUT|EAI_AGAIN|ENOTFOUND)$/;
1468
+ const NETWORK_ERROR_CODE = /^(?:ENETUNREACH|EHOSTUNREACH|ENETDOWN|EHOSTDOWN|ECONNRESET|ECONNREFUSED|ECONNABORTED|ETIMEDOUT|EIDLETIMEOUT|ESOCKETTIMEDOUT|EAI_AGAIN|ENOTFOUND)$/;
1311
1469
  function registryNetworkFailure(error) {
1312
1470
  if (error instanceof RegistryUnavailable)
1313
1471
  return true;
@@ -1339,8 +1497,7 @@ async function waitForReleaseArchives(version, current, rt) {
1339
1497
  const deadline = now() + 10 * 60_000;
1340
1498
  for (;;) {
1341
1499
  try {
1342
- await checkReleaseArchives(version, rt);
1343
- return true;
1500
+ return await checkReleaseArchives(version, rt);
1344
1501
  }
1345
1502
  catch (error) {
1346
1503
  if (!(error instanceof ReleaseNotAvailable))
@@ -1349,7 +1506,7 @@ async function waitForReleaseArchives(version, current, rt) {
1349
1506
  if (remaining <= 0) {
1350
1507
  recordUpdateDeferral(version, "waiting for registry or extension closure availability", true);
1351
1508
  rt.out(`cotal-ai@${version} is still reaching the registry. Keeping cotal-ai@${current}; no global install was attempted. A later update check will try again.`);
1352
- return false;
1509
+ return undefined;
1353
1510
  }
1354
1511
  rt.out(`Waiting for cotal-ai@${version} release archives to reach the registry (${Math.ceil(remaining / 1000)} s remaining); cotal-ai@${current} stays installed.`);
1355
1512
  await (rt.sleep ?? (milliseconds => new Promise(resolveSleep => setTimeout(resolveSleep, milliseconds))))(Math.min(15_000, remaining));
@@ -1405,10 +1562,11 @@ async function upgradeAndReconcile(targetVersion, current, rt, target) {
1405
1562
  const releaseChecksStarted = Date.now();
1406
1563
  try {
1407
1564
  rt.out(`Checking cotal-ai@${targetVersion} release archives`);
1408
- if (!await waitForReleaseArchives(targetVersion, current, rt))
1565
+ const releasePackages = await waitForReleaseArchives(targetVersion, current, rt);
1566
+ if (!releasePackages)
1409
1567
  return 0;
1410
1568
  rt.out(`Checking installed extension dependencies for ${targetVersion}`);
1411
- checkInstalledClosure(targetVersion, rt);
1569
+ checkInstalledClosure(targetVersion, releasePackages, rt);
1412
1570
  // In-place rollback downloads the previous release. Staged rollback retains its complete graph.
1413
1571
  if (!rt.prepareExecution) {
1414
1572
  rt.out(`Checking cotal-ai@${current} recovery archives`);
@@ -1536,7 +1694,7 @@ async function upgradeAndReconcile(targetVersion, current, rt, target) {
1536
1694
  }
1537
1695
  catch { /* an unpublished copy left behind selects nothing */ }
1538
1696
  releaseGlobal();
1539
- if (!execution && message(error).startsWith("target staging failed: ") && registryNetworkFailure(error)) {
1697
+ if (!execution && (error instanceof RegistryUnavailable || message(error).startsWith("target staging failed: ") && registryNetworkFailure(error))) {
1540
1698
  recordUpdateDeferral(targetVersion, "waiting for registry access", true);
1541
1699
  rt.out("The registry cannot be reached; nothing was changed.");
1542
1700
  return 0;
@@ -1663,12 +1821,13 @@ async function upgradeAndReconcile(targetVersion, current, rt, target) {
1663
1821
  rt.err(c.red(`✗ cotal-ai@${targetVersion} installed globally, but its reconcile failed: ${failure(child)}`));
1664
1822
  return await repairReplacement(`reconcile failed: ${failure(child)}`, child.status ?? 1, readUpdateRecovery()?.phase === "verified-ready");
1665
1823
  }
1824
+ let activationDeferred = undefined;
1666
1825
  if (rt.env.COTAL_AUTO_UPDATE !== "1" || rt.automaticGenerationWait) {
1667
1826
  try {
1668
1827
  const recovery = readUpdateRecovery();
1669
1828
  if (recovery && recovery.phase !== "verified-ready")
1670
1829
  writeUpdateRecovery({ ...recovery, installed: targetVersion, phase: "verified-ready" });
1671
- await rt.waitForInstalledGeneration?.(targetVersion);
1830
+ activationDeferred = await rt.waitForInstalledGeneration?.(targetVersion);
1672
1831
  }
1673
1832
  catch (error) {
1674
1833
  rt.err(c.red(`✗ installed daemon generation: ${refusal(error)}`));
@@ -1684,8 +1843,12 @@ async function upgradeAndReconcile(targetVersion, current, rt, target) {
1684
1843
  rt.out("Removing completed update recovery snapshot");
1685
1844
  snapshot.discard();
1686
1845
  clearUpdateRecovery();
1687
- recordUpdateCompletion(targetVersion, `updated to ${targetVersion}`, true);
1846
+ recordUpdateCompletion(targetVersion, activationDeferred || `updated to ${targetVersion}`, !activationDeferred);
1688
1847
  execution?.complete?.();
1848
+ if (activationDeferred) {
1849
+ rt.err(activationDeferred);
1850
+ return interrupted || 1;
1851
+ }
1689
1852
  if (stagedExecution)
1690
1853
  rt.out(c.green(`✓ cotal-ai@${targetVersion} in use and reconciled`));
1691
1854
  else
@@ -1874,7 +2037,7 @@ async function runNpmAsync(args, archiveCache) {
1874
2037
  const gated = archiveCache !== undefined && (process.platform === "linux" || process.platform === "darwin");
1875
2038
  const gate = 'IFS= read -r permit <&3 && [ "$permit" = run ] || exit 1; exec 3<&-; exec "$@"';
1876
2039
  const child = spawn(gated ? "/bin/sh" : file, gated ? ["-c", gate, "cotal-release-check", file, ...spawnArgs] : spawnArgs, {
1877
- windowsVerbatimArguments, windowsHide: true,
2040
+ cwd: parse(homedir()).root, windowsVerbatimArguments, windowsHide: true,
1878
2041
  ...(gated ? { detached: true, stdio: ["ignore", "pipe", "pipe", "pipe"] } : {}),
1879
2042
  });
1880
2043
  let stdout = "", stderr = "", error;
@@ -1907,19 +2070,21 @@ async function runNpmAsync(args, archiveCache) {
1907
2070
  function runNpm(args, inherit = false) {
1908
2071
  try {
1909
2072
  const { file, args: spawnArgs, windowsVerbatimArguments } = cmdSpawnSpec("npm", args);
1910
- const result = spawnSync(file, spawnArgs, inherit
1911
- ? { stdio: "inherit", windowsVerbatimArguments }
1912
- : { encoding: "utf8", windowsVerbatimArguments });
2073
+ const result = spawnSync(file, spawnArgs, {
2074
+ cwd: parse(homedir()).root, windowsVerbatimArguments,
2075
+ ...(inherit ? { stdio: "inherit" } : { encoding: "utf8" }),
2076
+ });
1913
2077
  return {
1914
2078
  status: result.status,
1915
2079
  signal: result.signal,
1916
2080
  stdout: `${result.stdout ?? ""}`,
1917
2081
  stderr: `${result.stderr ?? ""}`,
1918
2082
  error: result.error?.message,
2083
+ errorCode: result.error?.code,
1919
2084
  };
1920
2085
  }
1921
2086
  catch (e) {
1922
- return { status: null, stdout: "", stderr: "", error: message(e) };
2087
+ return { status: null, stdout: "", stderr: "", error: message(e), errorCode: e?.code };
1923
2088
  }
1924
2089
  }
1925
2090
  function runProcess(file, args, env, inherit = false) {
@@ -1931,18 +2096,33 @@ function runProcess(file, args, env, inherit = false) {
1931
2096
  error: result.error?.message,
1932
2097
  };
1933
2098
  }
1934
- async function runGlobalProcess(root, operation, file, args, env, inherit = false, windowsVerbatimArguments = false) {
2099
+ async function runGlobalProcess(root, operation, file, args, env, inherit = false, windowsVerbatimArguments = false, staging) {
1935
2100
  const gated = process.platform === "linux";
1936
2101
  const mutation = beginGlobalUpdateChild(root, operation, gated);
1937
2102
  let cache;
1938
2103
  let published = false;
1939
2104
  let preservePending = false;
2105
+ const watchers = [];
2106
+ let elapsed;
2107
+ let idle;
2108
+ let stopping;
1940
2109
  try {
1941
2110
  cache = mkdtempSync(join(tmpdir(), "cotal-update-npm-"));
2111
+ if (staging !== undefined) {
2112
+ // npm is quiet during a download. Its private cache receives the archive bytes and
2113
+ // the private prefix changes as packages unpack. Neither depends on terminal output.
2114
+ for (const path of [cache, staging]) {
2115
+ const watcher = watch(path, { recursive: true }, () => idle?.refresh());
2116
+ watcher.on("error", () => { clearTimeout(idle); idle = undefined; watcher.close(); });
2117
+ watchers.push(watcher);
2118
+ }
2119
+ }
1942
2120
  // The pipe closes without permission if the parent dies before publishing the PID.
1943
2121
  // exec keeps the published PID and the real child keeps its original argv and stdin.
1944
2122
  const gate = 'IFS= read -r permit <&3 && [ "$permit" = run ] || exit 1; exec 3<&-; exec "$@"';
1945
2123
  const child = withInstallUmask(() => spawn(gated ? "/bin/sh" : file, gated ? ["-c", gate, "cotal-update", file, ...args] : args, {
2124
+ // Corepack searches ancestors for a package manager. Keep only npm at the filesystem root.
2125
+ ...(operation === "install" ? { cwd: parse(homedir()).root } : {}),
1946
2126
  env: { ...env, npm_config_cache: cache, npm_config_logs_max: "0", npm_config_update_notifier: "false" },
1947
2127
  // A separate process group keeps terminal interrupts out of npm's live replacement.
1948
2128
  // Keep the ChildProcess referenced and await close; this is not a background update.
@@ -1970,17 +2150,79 @@ async function runGlobalProcess(root, operation, file, args, env, inherit = fals
1970
2150
  }
1971
2151
  }
1972
2152
  permit?.end(published ? "run\n" : undefined);
1973
- const closed = await new Promise((resolveClose) => child.once("close", (status, signal) => resolveClose({ status, signal })));
2153
+ let rejectClose;
2154
+ const close = new Promise((resolveClose, reject) => {
2155
+ rejectClose = reject;
2156
+ child.once("close", (status, signal) => resolveClose({ status, signal }));
2157
+ });
2158
+ if (staging !== undefined && child.pid !== undefined) {
2159
+ const pgid = child.pid;
2160
+ const signalGroup = (signal) => {
2161
+ try {
2162
+ process.kill(-pgid, signal);
2163
+ }
2164
+ catch (error) {
2165
+ if (error.code !== "ESRCH")
2166
+ throw error;
2167
+ }
2168
+ };
2169
+ const grace = 2000;
2170
+ const reap = 1000;
2171
+ const stop = () => {
2172
+ if (stopping)
2173
+ return;
2174
+ clearTimeout(elapsed);
2175
+ clearTimeout(idle);
2176
+ stopping = (async () => {
2177
+ signalGroup("SIGTERM");
2178
+ await new Promise(resolve => setTimeout(resolve, grace));
2179
+ if (processGroupMembers(pgid).length)
2180
+ signalGroup("SIGKILL");
2181
+ const deadline = performance.now() + reap;
2182
+ while (processGroupMembers(pgid).length) {
2183
+ if (performance.now() >= deadline)
2184
+ throw new Error(`could not stop staging npm process group ${pgid}`);
2185
+ await new Promise(resolve => setTimeout(resolve, 25));
2186
+ }
2187
+ })();
2188
+ void stopping.catch(error => {
2189
+ child.stdin?.destroy();
2190
+ child.stdout?.destroy();
2191
+ child.stderr?.destroy();
2192
+ child.unref();
2193
+ rejectClose(error);
2194
+ });
2195
+ };
2196
+ // Leave room for TERM and KILL within the five-minute staging budget. Idle time
2197
+ // covers three 15-second fetch attempts plus their one- and two-second backoffs.
2198
+ elapsed = setTimeout(stop, 300_000 - grace - reap);
2199
+ idle = setTimeout(stop, 50_000);
2200
+ }
2201
+ const closed = await close;
2202
+ clearTimeout(elapsed);
2203
+ clearTimeout(idle);
2204
+ if (stopping) {
2205
+ await stopping;
2206
+ if (published)
2207
+ mutation.clear();
2208
+ throw new RegistryUnavailable("target staging could not reach the registry");
2209
+ }
1974
2210
  if (published)
1975
2211
  mutation.complete(closed.status, closed.signal, closed.signal !== null
1976
2212
  ? `${operation} child terminated by ${closed.signal}`
1977
2213
  : `Windows npm intermediary exited ${closed.status}; descendant completion is unproved`);
1978
- return { status: error ? null : closed.status, stdout, stderr, ...(error ? { error } : {}) };
2214
+ return { status: error ? null : closed.status, signal: closed.signal, stdout, stderr, ...(error ? { error } : {}) };
1979
2215
  }
1980
2216
  catch (e) {
2217
+ if (e instanceof RegistryUnavailable)
2218
+ throw e;
1981
2219
  return { status: null, stdout: "", stderr: "", error: message(e) };
1982
2220
  }
1983
2221
  finally {
2222
+ for (const watcher of watchers)
2223
+ watcher.close();
2224
+ clearTimeout(elapsed);
2225
+ clearTimeout(idle);
1984
2226
  if (!published && !preservePending)
1985
2227
  mutation.clear();
1986
2228
  if (cache)
@@ -2000,7 +2242,7 @@ function latestNotAvailable(result, version) {
2000
2242
  }
2001
2243
  }
2002
2244
  function failure(result) {
2003
- return [result.error, result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n") || `process exited ${result.status}`;
2245
+ return [result.signal && `process terminated by ${result.signal}`, result.error, result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n") || `process exited ${result.status}`;
2004
2246
  }
2005
2247
  function message(value) {
2006
2248
  return value instanceof Error ? value.message : String(value);