@cotal-ai/cli 0.132.3 → 0.132.5

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.
@@ -6,7 +6,7 @@ import { createConnection, createServer, isIP } from "node:net";
6
6
  import { homedir, hostname } from "node:os";
7
7
  import { accessSync, constants, mkdirSync, readFileSync, existsSync, statSync, closeSync, lstatSync, realpathSync, readdirSync, rmdirSync, unlinkSync, } from "node:fs";
8
8
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
9
- import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, SERVICE_AUTHORITY_MAX_BYTES, SERVICE_CALLER_PAYLOAD_FLOOR, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, removeIssuedStoresBeforeRetention, IssuedStoreBeforeRetentionError, IssuedStoreRecreateRefusal, reconcileSpaceTtls, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, spaceDeletionStreams, isJetStreamMissing, seedChannelRegistry, ensureDefaultDeliveryClass, UndecodableRegistryEntry, assertValidChannel, isConcreteChannel, validateChannelConfig, validateChannelDefaults, LEASE_TTL_MS, mkSecretDir, openPrivateAppend, realDirNoSymlink, writeSecretFile, writeSecretFileAtomic, utf16Problem, } from "@cotal-ai/core";
9
+ import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, SERVICE_AUTHORITY_MAX_BYTES, SERVICE_CALLER_PAYLOAD_FLOOR, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, removeIssuedStoresBeforeRetention, IssuedStoreBeforeRetentionError, IssuedStoreRecreateRefusal, reconcileSpaceTtls, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, spaceDeletionStreams, isJetStreamMissing, seedChannelRegistry, ensureDefaultDeliveryClass, UndecodableRegistryEntry, assertValidChannel, isConcreteChannel, validateChannelConfig, validateChannelDefaults, LEASE_TTL_MS, EpEnvelopeError, mkSecretDir, openPrivateAppend, realDirNoSymlink, writeSecretFile, writeSecretFileAtomic, utf16Problem, } from "@cotal-ai/core";
10
10
  import { JetStreamApiCodes, jetstreamManager, StorageType } from "@nats-io/jetstream";
11
11
  import { Kvm } from "@nats-io/kv";
12
12
  import { assertManagerName, readManagerName, readManagerSeatCap, recordManagerName, recordManagerSeatCap, parseSeatCapFlag, seatCapText, assertRecordIdentity, formatRecord, identityRecord, parseRecord, CommandFailure, codeSpan, commandFailureReport, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, brokerPolicyPath, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, brokerAddressKey, canonicalRoot, rootPathProblem, rootControlProblem, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, keepsRegistration, oneLine, presentationOf, writeResult, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, parsePositiveIntegerFlag, recordMesh, retainedLegacyBroker, meshesForRoot, removeMesh, rotateSystemCreds, setCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessMaintenanceClaim, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, rootNamesNoSpace, readMaintenanceResumeDocument, seatCheckpointDir, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, writeBrokerPolicy, removePidPair, writePidPair, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, recordsElsewhereError, recordOperationWarning, retainSystemSigningSeed, restoreLeftOut, SPACE_NAME_MAX, spaceNameTooLong, NATS_PIDFILE, UNTRUSTED_CERTIFICATE, exitCode, canonicalLocalProcessPath, DELIVERY_LOGFILE, terminalWidth, } from "@cotal-ai/workspace";
@@ -61,7 +61,7 @@ import { extensionNames, preflightRuntime } from "../ext-loader.js";
61
61
  import { completingFlagValue } from "../lib/completion.js";
62
62
  import { metadataPositionals } from "../lib/command-path.js";
63
63
  import { askManager } from "../lib/control.js";
64
- import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, heldClaim, movedFolderRefusal, prepareRestore, preservedSourceState, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, journaledRestoredStreams, leftOutNotes, replacePreparedDeadRestoreListener, restoreComposition, restoreNextStep, restoreOnlyCopy, } from "../lib/restore.js";
64
+ import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, heldClaim, movedFolderRefusal, prepareRestore, preservedSourceState, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, journaledMaxFileStore, journaledRestoredStreams, leftOutNotes, replacePreparedDeadRestoreListener, restoreComposition, restoreNextStep, restoreOnlyCopy, } from "../lib/restore.js";
65
65
  import { attemptProcessesGone } from "../lib/isolated-broker.js";
66
66
  import { assertEndpointUnreachable } from "../lib/endpoint-cut.js";
67
67
  import { addressHolder, brokerListenAddress, listenerBindError } from "../lib/broker-service.js";
@@ -1691,7 +1691,8 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1691
1691
  throw new Error(`restore attempt ${resumeAttempt} re-entry has no bound listener proof; preserving recovery state`);
1692
1692
  const ownerStatus = localProcessOwnerStatus(restoredAttempt.listenerProof.processOwner);
1693
1693
  if (ownerStatus === "alive") {
1694
- await resumeProvenRestoreListener(restoredAttempt, startupLock);
1694
+ await provePreparedRestoreListener(restoredAttempt);
1695
+ await adoptProvenListener(restoredAttempt, restoredAttempt.targetPath, "proven restore listener", startupLock);
1695
1696
  return;
1696
1697
  }
1697
1698
  if (ownerStatus === "unknown")
@@ -1706,7 +1707,8 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1706
1707
  if (ordinaryAttempt?.adoptProof) {
1707
1708
  // The recovered attempt's exact bound listener is alive: prove it over the wire and adopt it
1708
1709
  // instead of spawning a competitor over the same store.
1709
- await resumeProvenOrdinaryListener(ordinaryAttempt, startupLock);
1710
+ await proveOrdinaryResumeListener(ordinaryAttempt);
1711
+ await adoptProvenListener(ordinaryAttempt, ordinaryAttempt.storeDir, "adopted resume listener", startupLock);
1710
1712
  return;
1711
1713
  }
1712
1714
  if (ordinaryAttempt?.journalState === "resume-committed")
@@ -1888,6 +1890,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1888
1890
  // never just reprint "already running" over a dead callout. No broker config is (re)written
1889
1891
  // here, so healing on a bare `cotal up` is safe: the mode can't drift, only the daemon heals.
1890
1892
  let userAuth;
1893
+ let startAuth;
1891
1894
  if (held.mode === "user") {
1892
1895
  const auth = await getSpaceAuth(workspaceSecretStore(root), held.space);
1893
1896
  if (!auth) {
@@ -1910,11 +1913,13 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1910
1913
  stderrLine("✗ ", `${e.message}`, c.red);
1911
1914
  process.exit(1);
1912
1915
  }
1913
- const svc = await startUserAuthService(held.space, server, { prepared, stateDir }, [...publicExchange, ...authTimeoutArgs(runningTimeout)]);
1914
- userAuth = svc.userAuth;
1915
- // The refresh IS the recovery command — a heal that didn't heal must not exit 0.
1916
- if (!svc.ok)
1917
- process.exitCode = 1;
1916
+ startAuth = async () => {
1917
+ const svc = await startUserAuthService(held.space, server, { prepared, stateDir }, [...publicExchange, ...authTimeoutArgs(runningTimeout)]);
1918
+ userAuth = svc.userAuth;
1919
+ // The refresh IS the recovery command — a heal that didn't heal must not exit 0.
1920
+ if (!svc.ok)
1921
+ process.exitCode = 1;
1922
+ };
1918
1923
  }
1919
1924
  // Re-ensure the control plane on a refresh, in every mode, under the decision the first boot
1920
1925
  // follows: the mesh owes a manager unless `--no-manager` was asked for, and a delivery daemon
@@ -1946,7 +1951,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1946
1951
  attachHost: attachHostFor(held.space, values.host),
1947
1952
  maxSessions: maxSessionsFor(held.space, maxSessions),
1948
1953
  noManager,
1949
- });
1954
+ }, startAuth);
1950
1955
  if (!controlPlane)
1951
1956
  process.exitCode = 1;
1952
1957
  // #883: a refresh that HEALED a missing manager must say so — the summary line otherwise reads
@@ -2858,37 +2863,40 @@ async function verifySpawnedOrdinaryListener(pending) {
2858
2863
  if (info.server_name !== pending.serverName)
2859
2864
  throw new Error(`resume attempt ${pending.attemptId} spawned listener reports a foreign NATS server name`);
2860
2865
  }
2861
- async function resumeProvenOrdinaryListener(pending, heldLock) {
2862
- await proveOrdinaryResumeListener(pending);
2863
- await recreateAdoptedMemoryBuckets(pending.root, pending.space, pending.server, pending.mode);
2864
- const svc = await ensureRecoveredUserAuth(pending);
2866
+ /** Adopts a listener its resume or restore attempt has proved over the wire: records the mesh,
2867
+ * starts delivery and completes the attempt. `storeDir` is the store that listener runs on, and
2868
+ * `listener` names it in a degraded reason. */
2869
+ async function adoptProvenListener(attempt, storeDir, listener, heldLock) {
2870
+ await recreateAdoptedMemoryBuckets(attempt.root, attempt.space, attempt.server, attempt.mode);
2871
+ const svc = await ensureRecoveredUserAuth(attempt);
2865
2872
  // Read the recorded exposure BEFORE re-recording: `recordOurMesh` writes the entry whole, so a
2866
2873
  // record built without this field would erase the operator's decision, and the adopted manager
2867
2874
  // below would then be launched loopback-only from an entry that no longer remembers otherwise.
2868
- const adoptAttachHost = attachHostFor(pending.space);
2869
- const adoptMaxSessions = maxSessionsFor(pending.space);
2875
+ const attachHost = attachHostFor(attempt.space);
2876
+ const maxSessions = maxSessionsFor(attempt.space);
2877
+ // Adopted from the recorded policy: an adopted listener was started from it, never from a default.
2878
+ const tlsRequired = adoptedTlsRequired(attempt.root);
2870
2879
  recordOurMesh({
2871
- space: pending.space,
2872
- server: pending.server,
2873
- root: pending.root,
2874
- mode: pending.mode,
2875
- // Adopted from the recorded policy: this path proves and re-adopts a listener it did not start.
2876
- tlsRequired: adoptedTlsRequired(pending.root),
2880
+ space: attempt.space,
2881
+ server: attempt.server,
2882
+ root: attempt.root,
2883
+ mode: attempt.mode,
2884
+ tlsRequired,
2877
2885
  ...(svc.userAuth ? { userAuth: svc.userAuth } : {}),
2878
- ...(adoptAttachHost ? { attachHost: adoptAttachHost } : {}),
2879
- ...(adoptMaxSessions !== undefined ? { maxSessions: adoptMaxSessions } : {}),
2880
- ...(pending.maxFileStore !== undefined ? { maxFileStore: pending.maxFileStore } : {}),
2881
- storeDir: resolve(pending.storeDir),
2886
+ ...(attachHost ? { attachHost } : {}),
2887
+ ...(maxSessions !== undefined ? { maxSessions } : {}),
2888
+ ...(attempt.maxFileStore !== undefined ? { maxFileStore: attempt.maxFileStore } : {}),
2889
+ storeDir: resolve(storeDir),
2882
2890
  ts: new Date().toISOString(),
2883
2891
  }, "started");
2884
- const controlPlane = await startDeliveryWithBroker(pending.space, pending.server, adoptedTlsRequired(pending.root), {
2885
- runtime: pending.runtime,
2886
- attachHost: adoptAttachHost,
2887
- maxSessions: adoptMaxSessions,
2888
- resumeAttempt: pending.attemptId,
2889
- resumeCommit: commitTokenHandoff(pending.root, pending.managerCommit !== undefined, heldLock),
2892
+ const controlPlane = await startDeliveryWithBroker(attempt.space, attempt.server, tlsRequired, {
2893
+ runtime: attempt.runtime,
2894
+ attachHost,
2895
+ maxSessions,
2896
+ resumeAttempt: attempt.attemptId,
2897
+ resumeCommit: commitTokenHandoff(attempt.root, attempt.managerCommit !== undefined, heldLock),
2890
2898
  });
2891
- await completeResumeActivation(pending.attemptId, controlPlane !== undefined && svc.ok, !svc.ok ? "adopted resume listener has no user-auth service" : "adopted resume listener has a degraded control plane", pending.server, heldLock);
2899
+ await completeResumeActivation(attempt.attemptId, controlPlane !== undefined && svc.ok, !svc.ok ? `${listener} has no user-auth service` : `${listener} has a degraded control plane`, attempt.server, heldLock);
2892
2900
  }
2893
2901
  async function ensureRecoveredUserAuth(prepared) {
2894
2902
  if (prepared.mode !== "user")
@@ -2906,37 +2914,6 @@ async function ensureRecoveredUserAuth(prepared) {
2906
2914
  });
2907
2915
  return startUserAuthService(prepared.space, prepared.server, { prepared: provider, stateDir });
2908
2916
  }
2909
- async function resumeProvenRestoreListener(prepared, heldLock) {
2910
- await provePreparedRestoreListener(prepared);
2911
- await recreateAdoptedMemoryBuckets(prepared.root, prepared.space, prepared.server, prepared.mode);
2912
- const svc = await ensureRecoveredUserAuth(prepared);
2913
- // Same ordering constraint as the pending-adopt path above: capture the recorded exposure before
2914
- // `recordOurMesh` rewrites the entry, or a restore silently demotes the mesh to loopback attach.
2915
- const restoreAttachHost = attachHostFor(prepared.space);
2916
- const restoreMaxSessions = maxSessionsFor(prepared.space);
2917
- recordOurMesh({
2918
- space: prepared.space,
2919
- server: prepared.server,
2920
- root: prepared.root,
2921
- mode: prepared.mode,
2922
- // Same as the ordinary-resume path: a restore adopts an existing listener, so the requirement
2923
- // comes from the policy that listener was started from, never from a default.
2924
- tlsRequired: adoptedTlsRequired(prepared.root),
2925
- ...(svc.userAuth ? { userAuth: svc.userAuth } : {}),
2926
- ...(restoreAttachHost ? { attachHost: restoreAttachHost } : {}),
2927
- ...(restoreMaxSessions !== undefined ? { maxSessions: restoreMaxSessions } : {}),
2928
- storeDir: resolve(prepared.targetPath),
2929
- ts: new Date().toISOString(),
2930
- }, "started");
2931
- const controlPlane = await startDeliveryWithBroker(prepared.space, prepared.server, adoptedTlsRequired(prepared.root), {
2932
- runtime: prepared.runtime,
2933
- attachHost: restoreAttachHost,
2934
- maxSessions: restoreMaxSessions,
2935
- resumeAttempt: prepared.attemptId,
2936
- resumeCommit: commitTokenHandoff(prepared.root, prepared.managerCommit !== undefined, heldLock),
2937
- });
2938
- await completeResumeActivation(prepared.attemptId, controlPlane !== undefined && svc.ok, !svc.ok ? "proven restore listener has no user-auth service" : "proven restore listener has a degraded control plane", prepared.server, heldLock);
2939
- }
2940
2917
  async function completeResumeActivation(attemptId, healthy, reason, server, heldLock, retireBroker) {
2941
2918
  if (!attemptId)
2942
2919
  return;
@@ -3190,7 +3167,12 @@ async function startUserAuthService(space, server, setup, publicExchange, quietB
3190
3167
  return { userAuth: info, ok: true };
3191
3168
  }
3192
3169
  catch (e) {
3193
- stderrLine("✗ ", `user-auth service did not come up (${e.message}) - user connects to "${space}" will fail until a re-\`cotal up\` succeeds`, c.red);
3170
+ // A typed refusal leads with its code and each detail's reason, e.g. a plane claim's
3171
+ // `unknown` liveness against its `live-peer` contention, so no caller parses the copy.
3172
+ const typed = e instanceof EpEnvelopeError
3173
+ ? ` [${[e.code, ...(e.details ?? []).map((d) => typeof d.reason === "string" ? `${d.kind}: ${d.reason}` : d.kind)].join("; ")}]`
3174
+ : "";
3175
+ stderrLine("✗ ", `user-auth service did not come up${typed} (${e.message}) - user connects to "${space}" will fail until a re-\`cotal up\` succeeds`, c.red);
3194
3176
  return { userAuth: assertUserAuthInfo(setup.prepared.publicAuth), ok: false };
3195
3177
  }
3196
3178
  }
@@ -3735,9 +3717,9 @@ async function startDeliveryWithBroker(space, server,
3735
3717
  * A second durable record consulted in the callee is how the caller's copy went silently unused.
3736
3718
  * One decision, and it arrives as an argument.
3737
3719
  */
3738
- tlsRequired, mgr) {
3720
+ tlsRequired, mgr, afterDelivery) {
3739
3721
  try {
3740
- const plane = await ensureControlPlane({ space, server, tls: tlsRequired, ...(mgr ?? {}) });
3722
+ const plane = await ensureControlPlane({ space, server, tls: tlsRequired, ...(mgr ?? {}) }, afterDelivery);
3741
3723
  // #1576: `up` either BINDS the responder or SAYS SO HERE. The delivery daemon is a hard
3742
3724
  // dependency of spawn, retirement and the durable backstop, and this function used to return `true` for a boot
3743
3725
  // that started a daemon whose responder never bound — so `cotal up` printed its success banner
@@ -3863,10 +3845,12 @@ async function serveReadyListener(l) {
3863
3845
  throw e;
3864
3846
  }
3865
3847
  }
3866
- // USER MODE: the auth service comes up FIRST among the daemons — until its callout answers,
3867
- // every user-mode connect to this broker is denied, so `up` must not report a usable user mesh
3868
- // (nor let agents race it) on a half-started auth plane.
3869
- const svc = await startUserAuthService(space, server, setup, [...(l.publicExchange ?? []), ...authTimeoutArgs(setup?.authTimeout)], l.quietBoot);
3848
+ // Register the prepared trust before delivery starts. Auth follows delivery's liveness oracle,
3849
+ // then the manager: a crashed auth claim cannot be reclaimed while that oracle is absent.
3850
+ let svc = {
3851
+ ok: setup?.prepared === undefined,
3852
+ ...(setup?.prepared ? { userAuth: assertUserAuthInfo(setup.prepared.publicAuth) } : {}),
3853
+ };
3870
3854
  // Record BEFORE the control plane comes up: the manager's fail-closed mode detection requires
3871
3855
  // an authoritative registry entry (marker-without-registry is a refused start, not a guess),
3872
3856
  // so the record must exist by the time it boots. A manager/delivery failure after this leaves
@@ -3916,6 +3900,10 @@ async function serveReadyListener(l) {
3916
3900
  resumeAttempt: l.resumeAttempt,
3917
3901
  resumeCommit: l.resumeCommit,
3918
3902
  wsPort: setup?.wsPort, // P2 item 6: the console session client's broker ws port
3903
+ }, async () => {
3904
+ svc = await startUserAuthService(space, server, setup, [...(l.publicExchange ?? []), ...authTimeoutArgs(setup?.authTimeout)], l.quietBoot);
3905
+ if (svc.userAuth)
3906
+ recordOurMesh({ space, server, root: cotalRoot(), mode: "user", userAuth: svc.userAuth, ts: new Date().toISOString() }, "refresh", true);
3919
3907
  });
3920
3908
  seedPersonaAfterUp(cotalRoot(), l.quietBoot);
3921
3909
  return { authService: svc.ok, controlPlane };
@@ -4333,15 +4321,6 @@ export function attachHostFor(space, explicit) {
4333
4321
  export function maxSessionsFor(space, explicit) {
4334
4322
  return explicit ?? findMesh(space)?.maxSessions;
4335
4323
  }
4336
- /** The store cap a preserved launch recorded: absent, or a positive integer byte count. Anything
4337
- * else is a damaged journal, refused rather than rendered as the dynamic default. */
4338
- function journaledMaxFileStore(value) {
4339
- if (value === undefined)
4340
- return undefined;
4341
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
4342
- throw new Error(`the preserved launch records an invalid maxFileStore (${JSON.stringify(value)}); refusing to guess the broker's store cap`);
4343
- return value;
4344
- }
4345
4324
  /** {@link recordOurMesh} under a name that says it is a test seam: the origin rule it enforces is
4346
4325
  * asserted directly by the registry smoke, since reaching each branch through a full `up` would
4347
4326
  * need a live broker per case. */