@cotal-ai/cli 0.111.1 → 0.113.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.
@@ -5,7 +5,7 @@ import { createConnection, createServer, isIP } from "node:net";
5
5
  import { homedir, hostname } from "node:os";
6
6
  import { accessSync, constants, mkdirSync, readFileSync, existsSync, statSync, closeSync, lstatSync, realpathSync, readdirSync, rmdirSync, unlinkSync, } from "node:fs";
7
7
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
8
- import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, reconcileSpaceTtls, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, MEMBERSHIP_MAX_BYTES, spaceDeletionStreams, isJetStreamMissing, seedChannelRegistry, ensureDefaultDeliveryClass, assertValidChannel, isConcreteChannel, validateChannelConfig, validateChannelDefaults, LEASE_TTL_MS, mkSecretDir, openPrivateAppend, realDirNoSymlink, writeSecretFile, writeSecretFileAtomic, utf16Problem, } from "@cotal-ai/core";
8
+ import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, removeIssuedStoresBeforeRetention, IssuedStoreBeforeRetentionError, IssuedStoreRecreateRefusal, reconcileSpaceTtls, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, MEMBERSHIP_MAX_BYTES, spaceDeletionStreams, isJetStreamMissing, seedChannelRegistry, ensureDefaultDeliveryClass, assertValidChannel, isConcreteChannel, validateChannelConfig, validateChannelDefaults, LEASE_TTL_MS, mkSecretDir, openPrivateAppend, realDirNoSymlink, writeSecretFile, writeSecretFileAtomic, utf16Problem, } from "@cotal-ai/core";
9
9
  import { JetStreamApiCodes, jetstreamManager, StorageType } from "@nats-io/jetstream";
10
10
  import { Kvm } from "@nats-io/kv";
11
11
  import { assertManagerName, readManagerName, readManagerSeatCap, recordManagerName, recordManagerSeatCap, parseSeatCapFlag, seatCapText, assertRecordIdentity, formatRecord, identityRecord, parseRecord, CommandFailure, commandFailureReport, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, terminalWidth, 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, MIN_FILE_STORE, NATS_PIDFILE, exitCode, } from "@cotal-ai/workspace";
@@ -104,6 +104,7 @@ export const upFlags = [
104
104
  { name: "service-endpoints", type: "boolean", description: "with --user-auth: the auth service also hosts service endpoints (the registration door and the owner-decision host route)" },
105
105
  { name: "agent-provisioning-url", type: "string", value: "<https://…>", description: "with --exchange-public-port: the deployment's remote agent-provisioning endpoint the public bundle advertises" },
106
106
  { name: "rotate-sys", type: "boolean", description: "renew the expired/expiring $SYS creds by rotating the system account (agents, data and creds survive; needs a stopped mesh)" },
107
+ { name: "recreate-issued-stores", type: "string", value: "<backup-dir>", description: "back up this space's issued-authority stores created before 0.111.0 into a new <backup-dir>, delete them and create them again (needs a stopped stack and every other issuer of the space stopped)" },
107
108
  { name: "detach", type: "boolean", short: "d", description: "run in the background (the default; stop with cotal down)" },
108
109
  { name: "foreground", type: "boolean", description: "keep a non-manifest native stack in this terminal; -f currently refuses" },
109
110
  { name: "runtime", type: "string", value: "<name>", description: "agent runtime for the mesh manager (default pty; extension runtimes are explicit-only, see `cotal runtimes`); with -f overrides the manifest's runtime" },
@@ -127,13 +128,21 @@ export function upComplete(argv) {
127
128
  return { items: ["pty", ...extensionNames("runtime")].filter((v, i, a) => a.indexOf(v) === i).map((value) => ({ value })), directive: "nofiles" };
128
129
  if (flag?.name === "restore-only")
129
130
  return { items: [{ value: "registry" }], directive: "nofiles" };
130
- if (flag && ["root", "restore", "file", "channels", "tls-cert", "tls-key", "store-dir"].includes(flag.name))
131
+ if (flag && ["root", "restore", "recreate-issued-stores", "file", "channels", "tls-cert", "tls-key", "store-dir"].includes(flag.name))
131
132
  return { items: [], directive: "default" };
132
133
  if (flag)
133
134
  return { items: [], directive: "nofiles" };
134
135
  const items = upFlags.map((f) => ({ value: `--${f.name}`, description: f.description }));
135
136
  return { items, directive: items.length ? "nofiles" : "default" };
136
137
  }
138
+ /** `--recreate-issued-stores <backup-dir>` names a directory the step creates, so it must not exist
139
+ * and its parent must. Checked before anything starts; the step checks again when it creates it. */
140
+ function assertIssuedBackupDirArgument(raw) {
141
+ const dir = resolve(raw);
142
+ const problem = !raw.trim() ? "is empty" : existsSync(dir) ? `${dir} already exists` : !existsSync(dirname(dir)) ? `${dirname(dir)} does not exist` : undefined;
143
+ if (problem)
144
+ throw new CommandFailure("refused", "USAGE_INVALID", `--recreate-issued-stores names a new backup directory, and ${problem}; nothing was started`, { target: { backupDir: dir }, remedy: "name a directory that does not exist yet, inside one that does" });
145
+ }
137
146
  /** Launch intent is checked by the kernel before seed or effect preparation. A recovery
138
147
  * re-entry supplies its recorded mode explicitly rather than inheriting the new public default. */
139
148
  export function validateUpArguments(args) {
@@ -208,6 +217,11 @@ export function validateUpArguments(args) {
208
217
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --file/-f or --channels");
209
218
  if (args.values.restore && args.values["rotate-sys"] === true)
210
219
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --rotate-sys", { remedy: "restore the space and verify it first, then rotate: cotal down, then cotal up --rotate-sys" });
220
+ if (args.values["recreate-issued-stores"] !== undefined) {
221
+ if (args.values.file !== undefined || args.values.restore !== undefined)
222
+ throw new CommandFailure("refused", "USAGE_INVALID", `--recreate-issued-stores cannot be combined with ${args.values.file !== undefined ? "--file/-f" : "--restore"}; nothing was started`, { remedy: "run cotal up --space <space> --recreate-issued-stores <backup-dir> on its own first" });
223
+ assertIssuedBackupDirArgument(String(args.values["recreate-issued-stores"]));
224
+ }
211
225
  if (args.values.root !== undefined)
212
226
  preparedUpRoot(String(args.values.root));
213
227
  else if (!(args.values.file && args.values["dry-run"] === true)) {
@@ -865,6 +879,8 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
865
879
  // `up` that has already begun adopting a maintenance attempt.
866
880
  if (values["rotate-sys"] && readMaintenanceJournal(root))
867
881
  throw new Error("--rotate-sys is refused while this root has a maintenance attempt to recover - finish or roll back that attempt (`cotal up` alone recovers it), then `cotal down` and `cotal up --rotate-sys`");
882
+ if (values["recreate-issued-stores"] !== undefined && readMaintenanceJournal(root))
883
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "--recreate-issued-stores needs a fresh broker start, and this root has a maintenance attempt to recover; nothing was started", { target: { root }, remedy: "finish or roll back that attempt first (cotal up alone recovers it)" });
868
884
  // Raised here for the stronger reason the journal itself carries: a pending maintenance attempt
869
885
  // means the store is mid-recovery, and a broker-only boot over it is wrong with or without the
870
886
  // manager half. The manager half is why the FLAG specifically cannot apply. A settled active
@@ -1354,7 +1370,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1354
1370
  const stackServer = values.server ?? readStackJournal(meshRoot)?.journal.server ?? localMeshesForRoot(meshRoot).find((m) => m.space === stackSpace)?.server ?? await unrecordedStackServer(meshRoot, stackSpace, values.host);
1355
1371
  if (values.foreground && presentation !== "json")
1356
1372
  stackUpForegroundNotice(presentation, stackSpace, takeover);
1357
- await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, ...(stackMode ? { mode: stackMode } : {}), ...(values.idp ? { idp: values.idp } : {}), ...(values.host ? { host: values.host } : {}), ...(values["store-dir"] ? { storeDir: values["store-dir"] } : {}), ...(values["rotate-sys"] ? { rotateSys: true } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(authTimeout !== undefined ? { authTimeout } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), ...(values.__invokedRoot ? { invokedRoot: values.__invokedRoot } : {}), foreground: values.foreground === true, presentation }, native);
1373
+ await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, ...(stackMode ? { mode: stackMode } : {}), ...(values.idp ? { idp: values.idp } : {}), ...(values.host ? { host: values.host } : {}), ...(values["store-dir"] ? { storeDir: values["store-dir"] } : {}), ...(values["rotate-sys"] ? { rotateSys: true } : {}), ...(values["recreate-issued-stores"] !== undefined ? { recreateIssuedStores: resolve(values["recreate-issued-stores"]) } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(authTimeout !== undefined ? { authTimeout } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), ...(values.__invokedRoot ? { invokedRoot: values.__invokedRoot } : {}), foreground: values.foreground === true, presentation }, native);
1358
1374
  }
1359
1375
  finally {
1360
1376
  releaseMaintenanceLock(stackLock);
@@ -1660,6 +1676,8 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1660
1676
  console.error(c.red(`✗ mesh "${held.space}" is already running at ${server} - a running broker can't rotate its system account (it would keep serving the retired one); \`cotal down\` it first, then \`cotal up --rotate-sys\``));
1661
1677
  process.exit(1);
1662
1678
  }
1679
+ if (values["recreate-issued-stores"] !== undefined)
1680
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `mesh "${held.space}" is already running at ${server}, and its issued-authority stores are recreated only on a fresh broker start, before any issuer runs; nothing was changed`, { target: { space: held.space }, remedy: "stop the stack first, then run cotal up --recreate-issued-stores <backup-dir> again" });
1663
1681
  // `--foreground` asks this terminal to hold the stack's lifetime, but this branch starts
1664
1682
  // nothing here: it used to print `✓ already running`, restart a missing manager detached and
1665
1683
  // exit 0. A service unit relying on `--foreground` read that exit as the stack ending, stopped
@@ -1940,6 +1958,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1940
1958
  open: values.open,
1941
1959
  userAuth: wantUser ? { idpUrl: values.idp } : undefined,
1942
1960
  rotateSys: values["rotate-sys"],
1961
+ ...(values["recreate-issued-stores"] !== undefined ? { recreateIssuedStores: resolve(values["recreate-issued-stores"]) } : {}),
1943
1962
  publicExchange,
1944
1963
  channels: values.channels,
1945
1964
  // The RAW flag, not the loopback-defaulted `host` above: `startMeshDetached` applies the same
@@ -2207,6 +2226,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2207
2226
  };
2208
2227
  const { authService, controlPlane } = await serveReadyListener({
2209
2228
  child, server, space, storeDir, setup, seedFile, transport,
2229
+ ...(values["recreate-issued-stores"] !== undefined ? { recreateIssuedStores: resolve(values["recreate-issued-stores"]) } : {}),
2210
2230
  host: values.host,
2211
2231
  maxSessions,
2212
2232
  maxFileStore,
@@ -3181,7 +3201,7 @@ export function controllerStackNative() {
3181
3201
  const prepared = await prepareBrokerStart({ transport: opts.transport, server: opts.server, space: opts.space, ...(opts.open ? { open: true } : {}), ...(opts.userAuth ? { userAuth: opts.userAuth } : {}), ...(opts.host ? { host: opts.host } : {}), ...(opts.storeDir ? { storeDir: opts.storeDir } : {}), ...(opts.existingStore ? { existingStore: opts.existingStore } : {}), ...(opts.maxFileStore !== undefined ? { maxFileStore: opts.maxFileStore } : {}), ...(opts.authTimeout !== undefined ? { authTimeout: opts.authTimeout } : {}), ...(opts.seed !== undefined ? { seed: opts.seed } : opts.channels ? { channels: opts.channels } : {}), quietBoot: true });
3182
3202
  return { root: prepared.root, server: prepared.server, space: prepared.space, storeDir: prepared.storeDir, transport: prepared.transport, ...(prepared.setup ? { setup: { creds: prepared.setup.creds, wsPort: prepared.setup.wsPort } } : {}), ...(prepared.setup?.prepared && prepared.setup.stateDir ? { user: { prepared: prepared.setup.prepared, stateDir: prepared.setup.stateDir } } : {}), confPath: prepared.confPath, bin: prepared.bin, source: prepared.source, version: prepared.version, seedFile: prepared.seedFile, ...(prepared.setup?.authTimeout !== undefined ? { authTimeout: prepared.setup.authTimeout } : {}) };
3183
3203
  },
3184
- initializeStreams: (server, space, setup, seedFile) => postStart(server, space, setup, seedFile),
3204
+ initializeStreams: (server, space, setup, seedFile, recreateIssuedStores) => postStart(server, space, setup, seedFile, recreateIssuedStores),
3185
3205
  recreateDeletedStreams: ({ seed, ...opts }) => recreateDeletedStreams({ ...opts, ...(seed !== undefined ? { seed: seed } : {}) }),
3186
3206
  recordMesh: (entry) => recordOurMesh({ ...entry, ts: new Date().toISOString() }, "started", true),
3187
3207
  commitTransport: (root, chosen, authTimeout) => commitTransportPolicy(root, chosen, true, undefined, authTimeout),
@@ -3646,7 +3666,7 @@ async function awaitSpawnedListener(l) {
3646
3666
  const { child, server, space } = l;
3647
3667
  let facts;
3648
3668
  try {
3649
- if (!(await waitReady(server, l.creds, l.tls)))
3669
+ if (!(await waitReady(server, l.creds, l.tls, l.log)))
3650
3670
  throw exitedBeforeReady(l) ?? new Error(`nats-server did not become reachable at ${server} - see ${l.log}`);
3651
3671
  facts = await brokerVersion(server, space, l.creds);
3652
3672
  }
@@ -3689,7 +3709,7 @@ async function serveReadyListener(l) {
3689
3709
  await recreateMemoryBuckets(server, space, setup);
3690
3710
  else {
3691
3711
  try {
3692
- await postStart(server, space, setup, l.seedFile);
3712
+ await postStart(server, space, setup, l.seedFile, l.recreateIssuedStores);
3693
3713
  }
3694
3714
  catch (e) {
3695
3715
  await stopFailedListener(child);
@@ -3836,6 +3856,7 @@ opts) {
3836
3856
  await awaitSpawnedListener({ child, executable: { path: bin, source, version }, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: logPath, boundListener: opts.boundListener });
3837
3857
  const { authService, controlPlane } = await serveReadyListener({
3838
3858
  child, server, space, storeDir, setup, seedFile, transport,
3859
+ ...(opts.recreateIssuedStores !== undefined ? { recreateIssuedStores: opts.recreateIssuedStores } : {}),
3839
3860
  host: opts.host,
3840
3861
  maxSessions: opts.maxSessions,
3841
3862
  maxFileStore: opts.maxFileStore,
@@ -4197,18 +4218,59 @@ function seedPersonaAfterUp(root, quiet = false) {
4197
4218
  if (written && !quiet)
4198
4219
  console.log(c.dim(` wrote ${written.what}: ${written.path}`));
4199
4220
  }
4200
- async function waitReady(server, creds, tls = false) {
4201
- for (let i = 0; i < 50; i++) {
4202
- // An open listener answers the plaintext probe before any handshake, so TLS is checked either way.
4221
+ async function waitReady(server, creds, tls = false, log) {
4222
+ // Fifty silent probes is the bound for a broker that is not advancing. A listener that is up, or a
4223
+ // broker log that keeps growing or recording a JetStream restore, is evidence the process is still
4224
+ // recovering, so the wait continues instead of stopping it at a fixed count.
4225
+ let evidence = 0;
4226
+ let silent = 0;
4227
+ for (let i = 0; silent < 50; i++) {
4203
4228
  const reachable = await isReachable(server, creds ? { creds } : undefined);
4204
4229
  if (tls)
4205
4230
  await refuseUntrustedListener(server, creds);
4206
4231
  if (reachable)
4207
4232
  return true;
4233
+ const { evidence: next, restoring } = brokerRecoveryEvidence(log);
4234
+ // Any restore evidence seen during the wait is progress, including evidence already present on
4235
+ // the first probe. A restore that has started and not finished is progress on every probe, since
4236
+ // the broker writes nothing to its log until it completes; the probe cap bounds that wait. Only a
4237
+ // probe with no new evidence and no restore in flight counts toward the silent bound.
4238
+ if (next > evidence || restoring) {
4239
+ evidence = Math.max(evidence, next);
4240
+ silent = 0;
4241
+ }
4242
+ else {
4243
+ silent++;
4244
+ }
4245
+ if (i >= 1_500)
4246
+ return false;
4208
4247
  await new Promise((r) => setTimeout(r, 200));
4209
4248
  }
4210
4249
  return false;
4211
4250
  }
4251
+ /** Bytes plus completed-restore lines in the broker log, and whether a restore is in flight. A
4252
+ * foreground launch inherits the terminal and has no file to read, so it contributes no evidence
4253
+ * and keeps the silent-probe bound. */
4254
+ function brokerRecoveryEvidence(log) {
4255
+ const none = { evidence: 0, restoring: false };
4256
+ if (!log || log.startsWith("the terminal"))
4257
+ return none;
4258
+ let text = "";
4259
+ let size = 0;
4260
+ try {
4261
+ const stat = statSync(log);
4262
+ if (!stat.isFile())
4263
+ return none;
4264
+ size = stat.size;
4265
+ text = readFileSync(log, "utf8");
4266
+ }
4267
+ catch {
4268
+ return none;
4269
+ }
4270
+ const started = text.match(/Starting restore/g)?.length ?? 0;
4271
+ const restored = text.match(/Restored \d/g)?.length ?? 0;
4272
+ return { evidence: size + restored, restoring: started > restored };
4273
+ }
4212
4274
  /** Node's codes for a certificate chain this client does not trust. */
4213
4275
  const UNTRUSTED_CERTIFICATE = new Set(["DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN", "UNABLE_TO_GET_ISSUER_CERT", "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "CERT_UNTRUSTED"]);
4214
4276
  /** Throw when the TLS listener at `server` answers and this client refuses its certificate in the
@@ -4451,8 +4513,18 @@ function freePort(host, requestedPort = 0) {
4451
4513
  * before an endpoint has joined (e.g. `cotal spawn`'s DM-inbox provisioning, `cotal_purge`,
4452
4514
  * `history clear`) finds the streams instead of failing with StreamNotFound. Open connects
4453
4515
  * without creds (no authenticator). */
4454
- async function postStart(server, space, setup, seedFile) {
4455
- await setupSpaceStreams({ servers: server, space, creds: setup?.creds });
4516
+ async function postStart(server, space, setup, seedFile, recreateIssuedStores) {
4517
+ if (recreateIssuedStores !== undefined)
4518
+ await recreateIssuedStoresBeforeSetup(server, space, setup !== undefined, recreateIssuedStores);
4519
+ try {
4520
+ await setupSpaceStreams({ servers: server, space, creds: setup?.creds });
4521
+ }
4522
+ catch (error) {
4523
+ // Nothing of the stack runs yet, and the caller stops this broker again, so this is a refusal.
4524
+ if (error instanceof IssuedStoreBeforeRetentionError)
4525
+ throw new CommandFailure("refused", "CONFLICT", error.message, { target: { space, store: error.bucket }, remedy: `stop every other issuer and resolver of space ${space}, then add --recreate-issued-stores <backup-dir> to the cotal up that starts it` });
4526
+ throw error;
4527
+ }
4456
4528
  if (seedFile) {
4457
4529
  await seedChannelRegistry({ servers: server, space, creds: setup?.creds, file: seedFile });
4458
4530
  }
@@ -4467,6 +4539,39 @@ async function postStart(server, space, setup, seedFile) {
4467
4539
  deliveryClass: setup ? "durable" : "live",
4468
4540
  });
4469
4541
  }
4542
+ /** `--recreate-issued-stores`: on the broker this boot just started, before any issuer or resolver
4543
+ * of the space runs, back up and delete the space's issued-authority stores created before bounded
4544
+ * retention, so the stream setup that follows creates them in the current shape. It runs the core
4545
+ * step an embedder runs, on a one-shot `issued-store-recreate` credential minted from the root's
4546
+ * trust; an open space uses its bare connection, as stream setup does. */
4547
+ async function recreateIssuedStoresBeforeSetup(server, space, authenticated, backupDir) {
4548
+ let creds;
4549
+ let inboxPrefix = "_INBOX";
4550
+ if (authenticated) {
4551
+ const auth = await getSpaceAuth(workspaceSecretStore(cotalRoot()), space);
4552
+ if (!auth)
4553
+ throw new Error(`space "${space}" has no trust material under ${authDir(cotalRoot())}; its issued-authority stores were not touched`);
4554
+ const identity = newIdentity();
4555
+ creds = await mintCreds(auth, identity, "issued-store-recreate");
4556
+ inboxPrefix = `_INBOX_${identity.id}`;
4557
+ }
4558
+ const nc = await dialerFor(server)({ servers: server, ...standaloneConnectOpts({ creds, tls: false }), inboxPrefix });
4559
+ let removed;
4560
+ try {
4561
+ removed = await removeIssuedStoresBeforeRetention(nc, { space, backupDir, inboxPrefix });
4562
+ }
4563
+ catch (error) {
4564
+ if (error instanceof IssuedStoreRecreateRefusal)
4565
+ throw new CommandFailure("refused", error.reason === "nothing-to-recreate" ? "CONFLICT" : "USAGE_INVALID", error.message, { target: { space, backupDir }, remedy: error.reason === "nothing-to-recreate" ? "start the space without --recreate-issued-stores" : "name a directory that does not exist yet, inside one that does" });
4566
+ throw error;
4567
+ }
4568
+ finally {
4569
+ await nc.drain().catch(() => nc.close());
4570
+ }
4571
+ for (const store of removed)
4572
+ console.log(`→ backed up ${store.stream} (${store.messages} messages) to ${store.backup}, then deleted it`);
4573
+ console.log(c.dim("• the issued-authority stores are created again in the current shape; every generation issued before the upgrade is refused from now on"));
4574
+ }
4470
4575
  /** A resume or restore skips `postStart` because the preserved store already holds every canonical
4471
4576
  * stream. A memory-backed bucket is the exception: the broker stop that preserved the store emptied
4472
4577
  * it, stream and all (#1356 made presence memory-backed). Recreate those, and only those, from the