@cotal-ai/cli 0.168.0 → 0.170.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 (193) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +21 -8
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +70 -19
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/app-identity.d.ts.map +1 -1
  8. package/dist/commands/app-identity.js +14 -5
  9. package/dist/commands/app-identity.js.map +1 -1
  10. package/dist/commands/channels.js +2 -2
  11. package/dist/commands/channels.js.map +1 -1
  12. package/dist/commands/clean.d.ts.map +1 -1
  13. package/dist/commands/clean.js +30 -5
  14. package/dist/commands/clean.js.map +1 -1
  15. package/dist/commands/config.d.ts +1 -0
  16. package/dist/commands/config.d.ts.map +1 -1
  17. package/dist/commands/config.js +15 -7
  18. package/dist/commands/config.js.map +1 -1
  19. package/dist/commands/describe.js +4 -4
  20. package/dist/commands/describe.js.map +1 -1
  21. package/dist/commands/doctor.d.ts.map +1 -1
  22. package/dist/commands/doctor.js +49 -18
  23. package/dist/commands/doctor.js.map +1 -1
  24. package/dist/commands/down.d.ts.map +1 -1
  25. package/dist/commands/down.js +81 -10
  26. package/dist/commands/down.js.map +1 -1
  27. package/dist/commands/endpoint.d.ts +1 -1
  28. package/dist/commands/endpoint.d.ts.map +1 -1
  29. package/dist/commands/endpoint.js +3 -4
  30. package/dist/commands/endpoint.js.map +1 -1
  31. package/dist/commands/ext.d.ts +1 -0
  32. package/dist/commands/ext.d.ts.map +1 -1
  33. package/dist/commands/ext.js +24 -0
  34. package/dist/commands/ext.js.map +1 -1
  35. package/dist/commands/help.d.ts.map +1 -1
  36. package/dist/commands/help.js +5 -0
  37. package/dist/commands/help.js.map +1 -1
  38. package/dist/commands/history-clear.js +2 -2
  39. package/dist/commands/history-clear.js.map +1 -1
  40. package/dist/commands/history.d.ts +1 -1
  41. package/dist/commands/history.d.ts.map +1 -1
  42. package/dist/commands/history.js +21 -10
  43. package/dist/commands/history.js.map +1 -1
  44. package/dist/commands/join.d.ts.map +1 -1
  45. package/dist/commands/join.js +113 -28
  46. package/dist/commands/join.js.map +1 -1
  47. package/dist/commands/manager-service.d.ts.map +1 -1
  48. package/dist/commands/manager-service.js +7 -14
  49. package/dist/commands/manager-service.js.map +1 -1
  50. package/dist/commands/meshes-add.d.ts.map +1 -1
  51. package/dist/commands/meshes-add.js +6 -0
  52. package/dist/commands/meshes-add.js.map +1 -1
  53. package/dist/commands/meshes.d.ts.map +1 -1
  54. package/dist/commands/meshes.js +17 -2
  55. package/dist/commands/meshes.js.map +1 -1
  56. package/dist/commands/mint.d.ts.map +1 -1
  57. package/dist/commands/mint.js +19 -4
  58. package/dist/commands/mint.js.map +1 -1
  59. package/dist/commands/models.d.ts +1 -0
  60. package/dist/commands/models.d.ts.map +1 -1
  61. package/dist/commands/models.js +11 -3
  62. package/dist/commands/models.js.map +1 -1
  63. package/dist/commands/persona.d.ts +1 -0
  64. package/dist/commands/persona.d.ts.map +1 -1
  65. package/dist/commands/persona.js +15 -15
  66. package/dist/commands/persona.js.map +1 -1
  67. package/dist/commands/personas.js +3 -1
  68. package/dist/commands/personas.js.map +1 -1
  69. package/dist/commands/send.d.ts.map +1 -1
  70. package/dist/commands/send.js +47 -20
  71. package/dist/commands/send.js.map +1 -1
  72. package/dist/commands/service-actions.d.ts.map +1 -1
  73. package/dist/commands/service-actions.js +15 -8
  74. package/dist/commands/service-actions.js.map +1 -1
  75. package/dist/commands/service-registry.d.ts.map +1 -1
  76. package/dist/commands/service-registry.js +20 -11
  77. package/dist/commands/service-registry.js.map +1 -1
  78. package/dist/commands/setup.d.ts +4 -4
  79. package/dist/commands/setup.d.ts.map +1 -1
  80. package/dist/commands/setup.js +18 -15
  81. package/dist/commands/setup.js.map +1 -1
  82. package/dist/commands/space-registration.d.ts.map +1 -1
  83. package/dist/commands/space-registration.js +37 -12
  84. package/dist/commands/space-registration.js.map +1 -1
  85. package/dist/commands/space.d.ts +1 -0
  86. package/dist/commands/space.d.ts.map +1 -1
  87. package/dist/commands/space.js +13 -2
  88. package/dist/commands/space.js.map +1 -1
  89. package/dist/commands/spawn-preview.d.ts.map +1 -1
  90. package/dist/commands/spawn-preview.js +11 -4
  91. package/dist/commands/spawn-preview.js.map +1 -1
  92. package/dist/commands/spawn.d.ts.map +1 -1
  93. package/dist/commands/spawn.js +103 -44
  94. package/dist/commands/spawn.js.map +1 -1
  95. package/dist/commands/stack-gone.d.ts +10 -0
  96. package/dist/commands/stack-gone.d.ts.map +1 -1
  97. package/dist/commands/stack-gone.js +169 -7
  98. package/dist/commands/stack-gone.js.map +1 -1
  99. package/dist/commands/stack-lost-records.js +1 -1
  100. package/dist/commands/stack-lost-records.js.map +1 -1
  101. package/dist/commands/stack-up.d.ts.map +1 -1
  102. package/dist/commands/stack-up.js +13 -6
  103. package/dist/commands/stack-up.js.map +1 -1
  104. package/dist/commands/status.d.ts +2 -2
  105. package/dist/commands/status.d.ts.map +1 -1
  106. package/dist/commands/status.js +244 -93
  107. package/dist/commands/status.js.map +1 -1
  108. package/dist/commands/sync.d.ts +1 -0
  109. package/dist/commands/sync.d.ts.map +1 -1
  110. package/dist/commands/sync.js +8 -1
  111. package/dist/commands/sync.js.map +1 -1
  112. package/dist/commands/team.d.ts.map +1 -1
  113. package/dist/commands/team.js +4 -1
  114. package/dist/commands/team.js.map +1 -1
  115. package/dist/commands/up.d.ts.map +1 -1
  116. package/dist/commands/up.js +35 -10
  117. package/dist/commands/up.js.map +1 -1
  118. package/dist/commands/update.d.ts +3 -1
  119. package/dist/commands/update.d.ts.map +1 -1
  120. package/dist/commands/update.js +117 -25
  121. package/dist/commands/update.js.map +1 -1
  122. package/dist/commands/use.d.ts +1 -0
  123. package/dist/commands/use.d.ts.map +1 -1
  124. package/dist/commands/use.js +6 -0
  125. package/dist/commands/use.js.map +1 -1
  126. package/dist/commands/whoami.js +3 -3
  127. package/dist/commands/whoami.js.map +1 -1
  128. package/dist/help.d.ts.map +1 -1
  129. package/dist/help.js +29 -27
  130. package/dist/help.js.map +1 -1
  131. package/dist/index.d.ts.map +1 -1
  132. package/dist/index.js +25 -8
  133. package/dist/index.js.map +1 -1
  134. package/dist/lib/completion-install.d.ts.map +1 -1
  135. package/dist/lib/completion-install.js +6 -3
  136. package/dist/lib/completion-install.js.map +1 -1
  137. package/dist/lib/confirmation-required.d.ts +14 -0
  138. package/dist/lib/confirmation-required.d.ts.map +1 -1
  139. package/dist/lib/confirmation-required.js +13 -0
  140. package/dist/lib/confirmation-required.js.map +1 -1
  141. package/dist/lib/connect.d.ts +2 -2
  142. package/dist/lib/connect.d.ts.map +1 -1
  143. package/dist/lib/connect.js +6 -4
  144. package/dist/lib/connect.js.map +1 -1
  145. package/dist/lib/control.d.ts +8 -0
  146. package/dist/lib/control.d.ts.map +1 -1
  147. package/dist/lib/control.js +23 -1
  148. package/dist/lib/control.js.map +1 -1
  149. package/dist/lib/controller-restore.d.ts.map +1 -1
  150. package/dist/lib/controller-restore.js +5 -1
  151. package/dist/lib/controller-restore.js.map +1 -1
  152. package/dist/lib/credential-exports.d.ts +1 -0
  153. package/dist/lib/credential-exports.d.ts.map +1 -1
  154. package/dist/lib/credential-exports.js +3 -3
  155. package/dist/lib/credential-exports.js.map +1 -1
  156. package/dist/lib/delivery-proc.d.ts +2 -0
  157. package/dist/lib/delivery-proc.d.ts.map +1 -1
  158. package/dist/lib/delivery-proc.js +12 -2
  159. package/dist/lib/delivery-proc.js.map +1 -1
  160. package/dist/lib/local-process-stop.d.ts.map +1 -1
  161. package/dist/lib/local-process-stop.js +49 -18
  162. package/dist/lib/local-process-stop.js.map +1 -1
  163. package/dist/lib/persona-files.d.ts.map +1 -1
  164. package/dist/lib/persona-files.js +10 -20
  165. package/dist/lib/persona-files.js.map +1 -1
  166. package/dist/lib/restore.js +1 -1
  167. package/dist/lib/restore.js.map +1 -1
  168. package/dist/lib/self-exec.d.ts +4 -2
  169. package/dist/lib/self-exec.d.ts.map +1 -1
  170. package/dist/lib/self-exec.js +22 -11
  171. package/dist/lib/self-exec.js.map +1 -1
  172. package/dist/lib/service-preset-target.d.ts.map +1 -1
  173. package/dist/lib/service-preset-target.js +15 -5
  174. package/dist/lib/service-preset-target.js.map +1 -1
  175. package/dist/lib/service-presets.d.ts.map +1 -1
  176. package/dist/lib/service-presets.js +38 -18
  177. package/dist/lib/service-presets.js.map +1 -1
  178. package/dist/lib/service-process.d.ts +10 -0
  179. package/dist/lib/service-process.d.ts.map +1 -1
  180. package/dist/lib/service-process.js +108 -3
  181. package/dist/lib/service-process.js.map +1 -1
  182. package/dist/lib/stack-journal.d.ts +12 -6
  183. package/dist/lib/stack-journal.d.ts.map +1 -1
  184. package/dist/lib/stack-journal.js +73 -18
  185. package/dist/lib/stack-journal.js.map +1 -1
  186. package/dist/lib/store-dir.d.ts +4 -2
  187. package/dist/lib/store-dir.d.ts.map +1 -1
  188. package/dist/lib/store-dir.js +28 -3
  189. package/dist/lib/store-dir.js.map +1 -1
  190. package/dist/lib/update-snapshot.d.ts.map +1 -1
  191. package/dist/lib/update-snapshot.js +4 -3
  192. package/dist/lib/update-snapshot.js.map +1 -1
  193. package/package.json +4 -4
@@ -1,13 +1,14 @@
1
- import { accessSync, constants, existsSync, lstatSync } from "node:fs";
1
+ import { accessSync, constants, existsSync, lstatSync, statSync } from "node:fs";
2
2
  import { drainAndClose } from "@cotal-ai/core";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { CotalEndpoint, agentFilePath, dialerFor, EpEnvelopeError, formatAge, isReachable, isStreamNotFound, mintCreds, mintLifecycleUid, resolveService, realDirNoSymlink, invokeRepairingSplit, standaloneConnectOpts, newIdentity, idFromCreds, principalKey, DEV_OWNER, unansweredRequest, resolveAuthProvider, personaDir, } from "@cotal-ai/core";
6
- import { stoppedLoopbackListener, accountInventory, authDir, isCommandFailure, readMaintenanceJournal, recordsElsewhereError, recordsElsewhereText, restoreRolledBackRuns, targetErrorSpace, brokerAddressForDisplay, brokerCheck, canonicalRoot, CLI_USER_ACTOR, codeSpan, CommandFailure, deliveryCredsKey, DELIVERY_PIDFILE, extensionsDir, findCotalRoot, folderSpaceOverSelection, meshesForRoot, resolveReadsLiveness, stoppedStack, unsettledStackOperation, withdrawOperationNote, hasUserAuthState, homeCotalDir, installationWriter, cachedPreferences, loadLaunchPersonaFile, resolvePreference, isMeshRegistryError, isWorkspaceTargetError, jsonFlag, loadManagerInstanceIdentity, loadSoleSpaceAuth, localProcessPath, localProcessVisible, MANAGER_PIDFILE, oneLine, PREFERENCE_KEYS, parsePid, plainFlag, preflightTarget, presentationOf, principalFromBearer, probeLiveness, probeWebReadiness, readCurrent, readMeshRegistry, readPidfile, preparedRecordSkipped, readPreparedSpaces, stackJournalPath, readRenewalRecord, renderWorkspaceError, resolveMeshTarget, serverFlag, spaceFlag, userAuthStateDir, WEB_PIDFILE, workspaceSecretStore, displayWidth, terminalWidth, wrapWords, writeResult, workspaceErrorParts, preferencesPath, preferencesFolderWarning, cotalDirLink, movedProject, spaceStreamsAbsent, spaceStreamsExpected, resolveControlTarget, } from "@cotal-ai/workspace";
6
+ import { stoppedLoopbackListener, stackRunsUnderOtherHome, accountInventory, authDir, isCommandFailure, readMaintenanceJournal, recordsElsewhereError, recordsElsewhereText, restoreRolledBackRuns, targetErrorSpace, brokerAddressForDisplay, brokerCheck, canonicalRoot, CLI_USER_ACTOR, codeSpan, credentialFileExposure, CommandFailure, deliveryCredsKey, DELIVERY_PIDFILE, extensionsDir, findCotalRoot, folderSpaceOverSelection, meshesForRoot, resolveReadsLiveness, stoppedStack, unsettledStackOperation, withdrawOperationNote, hasUserAuthState, homeCotalDir, installationWriter, cachedPreferences, loadLaunchPersonaFile, resolvePreference, isMeshRegistryError, isWorkspaceTargetError, jsonFlag, loadManagerInstanceIdentity, loadSoleSpaceAuth, localProcessPath, localProcessVisible, MANAGER_PIDFILE, NATS_PIDFILE, oneLine, spaceKey, PREFERENCE_KEYS, plainFlag, preflightTarget, presentationOf, principalFromBearer, verifyIdentityPin, probeWebReadiness, readCurrent, readMeshRegistry, readPidfile, preparedRecordSkipped, readPreparedSpaces, stackJournalPath, readRenewalRecord, recordOperationSpace, renderWorkspaceError, resolveMeshTarget, serverFlag, spaceFlag, userAuthStateDir, WEB_PIDFILE, workspaceSecretStore, displayWidth, terminalWidth, wrapWords, writeResult, workspaceErrorParts, preferencesPath, preferencesFolderWarning, cotalDirLink, movedProject, spaceStreamsAbsent, spaceStreamsExpected, resolveControlTarget, } from "@cotal-ai/workspace";
7
7
  import { localProcessSurface } from "../ext-loader.js";
8
8
  import { cliVersion, cliProvenance, readExtensionVersions } from "../lib/version.js";
9
9
  import { agentSkillsSkew } from "../lib/agent-skills.js";
10
- import { managerHasDeliveryMarker } from "../lib/manager-proc.js";
10
+ import { managerHasDeliveryMarker, managerLogPath } from "../lib/manager-proc.js";
11
+ import { MANAGER_OMITTED } from "../lib/delivery-proc.js";
11
12
  import { signedInSpace } from "../lib/conversation-identity.js";
12
13
  import { connectorHarnesses, connectorStatusRows, machineStatus, recordedWebUrl, resolveRuntimeSpace, webBoundAddress, webInstalled, webSessionSource } from "../lib/status.js";
13
14
  import { deliveryResponderFromLease, deliveryResponderState, deliveryRowSuffix, RESPONDER_STALE_TEXT, RESPONDER_UNBOUND_CONSEQUENCE } from "../lib/delivery-responder.js";
@@ -22,7 +23,7 @@ import { c } from "../ui.js";
22
23
  import { preparedCatalogDiagnostics } from "./sync.js";
23
24
  import { agentStatus } from "./agents.js";
24
25
  import { invalidEnvironmentValues } from "./config.js";
25
- import { cliControl, onInstance } from "../lib/control.js";
26
+ import { cliControl, onInstance, onRerun } from "../lib/control.js";
26
27
  import { serviceDefinitionProjection, serviceDefinitionStore } from "../lib/service-definitions.js";
27
28
  import { instanceProjection, serviceInstances } from "../lib/service-instances.js";
28
29
  import { readinessAddressSurvivors } from "../lib/service-process.js";
@@ -31,7 +32,7 @@ import { additiveTeamRecordedState, listAdditiveTeamAttempts } from "../lib/team
31
32
  import { maintenanceNextStep, rolledBackNotes } from "../lib/restore.js";
32
33
  import { journalRecordedElsewhere, readStackJournal, serviceHeldRecords, STACK_ADAPTER, STACK_DEFINITION, stackStartedWithoutManager, stackOperationBlock, stackRootGone, unfinishedStackOperation, } from "../lib/stack-journal.js";
33
34
  import { cotalLinkHere, homeHoldsStack, linkedCotalRemedy } from "../lib/paths.js";
34
- import { storeWriteProblem } from "../lib/store-dir.js";
35
+ import { rootStoreProblem } from "../lib/store-dir.js";
35
36
  import { stackStoreWarnings } from "../lib/store-identity.js";
36
37
  import { natsServerLabel } from "../lib/nats-bin.js";
37
38
  import { askManager } from "@cotal-ai/workspace/control";
@@ -51,11 +52,11 @@ export const statusFlags = [
51
52
  spaceFlag,
52
53
  serverFlag,
53
54
  { name: "on", type: "string", value: "<manager-instance>", description: "named agent: inspect one manager instance" },
54
- { name: "creds", type: "string", value: "<file>", description: "named agent: use an explicit connection credential" },
55
+ { name: "creds", type: "string", value: "<file>", description: "explicit credential file (unsupported for status)" },
55
56
  { name: "all", type: "boolean", description: "check every recorded mesh, not only the selected one, and report every row in full" },
56
57
  { name: "wide", type: "boolean", description: "report every row in full: each known agent application, each extension, and the spaces under their broker addresses" },
57
58
  { name: "verbose", short: "v", type: "boolean", description: "include installation paths, local records and detailed diagnostics" },
58
- { name: "components", type: "boolean", description: "probe manager, delivery, web, and registered broker component health (exit: 0 serving, or the optional dashboard not installed or not started; 1 absent; 2 present but not serving; 3 probe refused)" },
59
+ { name: "components", type: "boolean", description: "probe manager, delivery, web, and registered broker component health (exit: 0 serving, an intentionally omitted manager, or the optional dashboard not installed or not started; 1 absent; 2 present but not serving; 3 probe refused)" },
59
60
  jsonFlag,
60
61
  plainFlag,
61
62
  ];
@@ -120,14 +121,24 @@ function displayStatusBroker(server, space, gaps) {
120
121
  }
121
122
  /** Named-agent and infrastructure inputs choose different reads. */
122
123
  export function validateStatusArguments(args) {
124
+ presentationOf(args.values);
123
125
  if (args.positionals.length > 1 || args.positionals.length && !args.positionals[0]?.trim())
124
126
  throw new CommandFailure("refused", "USAGE_INVALID", "status takes at most one agent name");
125
- if (args.positionals.length && (args.values.all || args.values.components))
126
- throw new CommandFailure("refused", "USAGE_INVALID", "a named agent status takes no --all or --components");
127
+ if (args.positionals.length && (args.values.all || args.values.components || args.values.wide || args.values.verbose))
128
+ throw new CommandFailure("refused", "USAGE_INVALID", "a named agent status takes no --all, --components, --wide or --verbose");
127
129
  if (typeof args.values.on === "string")
128
- onInstance(args.values.on, "cotal status");
129
- if (!args.positionals.length && (args.values.on !== undefined || args.values.creds !== undefined))
130
- throw new CommandFailure("refused", "USAGE_INVALID", "--on and --creds select a named agent read, not infrastructure status");
130
+ onInstance(args.values.on, onRerun("cotal status", args.values, args.positionals));
131
+ if (!args.positionals.length && args.values.on !== undefined)
132
+ throw new CommandFailure("refused", "USAGE_INVALID", "--on selects a named agent read, not infrastructure status");
133
+ if (!args.positionals.length && args.values.creds !== undefined) {
134
+ const space = typeof args.values.space === "string" && args.values.space.trim() ? args.values.space : undefined;
135
+ if (space !== undefined)
136
+ recordOperationSpace(space);
137
+ throw new CommandFailure("refused", "UNSUPPORTED", "status does not accept --creds: infrastructure status reads local and registered meshes, and named agent status mints its own control caller", {
138
+ ...(space !== undefined ? { target: { space } } : {}),
139
+ remedy: "run `cotal status` or `cotal status <agent>` without --creds",
140
+ });
141
+ }
131
142
  }
132
143
  /** `cotal status` — detailed, read-only diagnostics for the local machine + selected mesh. */
133
144
  export async function status(args) {
@@ -170,8 +181,22 @@ export async function status(args) {
170
181
  // health they never checked. It is read before the folder section because that section renders
171
182
  // the delivery process row, and a live pid means nothing without it.
172
183
  const preflight = selected.ok && selected.target.mode !== "user" ? await preflightTarget(selected.target) : undefined;
173
- const responder = await readResponderAxis(selected, preflight);
184
+ const responder = await readResponderAxis(selected, preflight, gaps);
174
185
  const folder = blocked ? unreadFolder(root, blocked) : await readFolder(root, selected, values, responder.state, gaps, hints);
186
+ if (selected.ok) {
187
+ try {
188
+ const renewal = readRenewalRecord(selected.target.root, selected.target.space);
189
+ if (renewal?.adoption?.ok === false) {
190
+ gaps.add("RENEWAL_ADOPTION_REFUSED", "the recorded renewal adoption was refused; a bound delivery responder does not clear that finding", { root: selected.target.root, space: selected.target.space });
191
+ hints.push("start or repair this space's manager, the renewal owner, so it re-signs the daemon credentials and the broker accepts them; do not respawn agents for this finding");
192
+ }
193
+ }
194
+ catch (error) {
195
+ gaps.add("RENEWAL_RECORD_UNREADABLE", error.message, { root: selected.target.root, space: selected.target.space });
196
+ if (isCommandFailure(error) && error.remedy)
197
+ hints.push(error.remedy);
198
+ }
199
+ }
175
200
  const meshes = await readMeshes(cwd, selected, Boolean(values.all), gaps, offline, preflight);
176
201
  const maintenance = blocked ? { root, space: null, state: "unreadable", attemptId: null, next: null } : readMaintenance(root, gaps);
177
202
  const recovery = backupRecovery(maintenance);
@@ -230,7 +255,7 @@ export async function status(args) {
230
255
  ...(parts ? { partial: { message: `status could not read ${parts === 1 ? "one part" : `${parts} parts`} of what it reports; the warnings name ${parts === 1 ? "it" : "each"}` } } : {}),
231
256
  }, (result) => statusView(result, Boolean(values.verbose), Boolean(values.all) || Boolean(values.wide)));
232
257
  if (values.components)
233
- await printComponentHealth(cwd, values);
258
+ await printComponentHealth(selected, store);
234
259
  }
235
260
  /** Why this account cannot list or search `root`, or undefined when it can. */
236
261
  function folderReadProblem(root) {
@@ -472,21 +497,22 @@ function readExtensions(gaps) {
472
497
  *
473
498
  * READ-ONLY AND BEST EFFORT. A workspace that never launched a daemon locally (an adopted or remote
474
499
  * one) has no creds file, and that is not an error: the caller then does not check the holder, the
475
- * same concession `waitForDeliveryLease` makes for an adopted daemon. Any failure yields `undefined`
476
- * rather than a wrong id, because a WRONG expected holder is worse than an unchecked one. */
500
+ * same concession `waitForDeliveryLease` makes for an adopted daemon. An existing credential that
501
+ * cannot be read privately refuses the check rather than silently disabling holder attribution. */
477
502
  async function expectedDeliveryHolder(target) {
478
- try {
479
- const creds = await workspaceSecretStore(target.root).get(deliveryCredsKey(target.space, { injected: false, root: target.root }));
480
- if (!creds)
481
- return undefined;
482
- // The daemon declares no owner/actor, so the endpoint falls back to DEV_OWNER for the owner and
483
- // to the connection id for the actor: `local.<idFromCreds>`. Built through `principalKey` rather
484
- // than string concatenation so this tracks the one definition of the dot-form.
485
- return principalKey(DEV_OWNER, idFromCreds(creds)).key;
486
- }
487
- catch {
503
+ const key = deliveryCredsKey(target.space, { injected: false, root: target.root });
504
+ const path = join(target.root, ".cotal", key);
505
+ const stat = lstatSync(path, { throwIfNoEntry: false });
506
+ const exposure = stat?.isFile() ? credentialFileExposure(path, stat) : undefined;
507
+ if (exposure)
508
+ throw new CommandFailure("refused", "PERMISSION_DENIED", `${path}: ${exposure.reason}`, { remedy: exposure.remedy, target: { path, space: target.space } });
509
+ const creds = await workspaceSecretStore(target.root).get(key);
510
+ if (!creds)
488
511
  return undefined;
489
- }
512
+ // The daemon declares no owner/actor, so the endpoint falls back to DEV_OWNER for the owner and
513
+ // to the connection id for the actor: `local.<idFromCreds>`. Built through `principalKey` rather
514
+ // than string concatenation so this tracks the one definition of the dot-form.
515
+ return principalKey(DEV_OWNER, idFromCreds(creds)).key;
490
516
  }
491
517
  /** Read the delivery responder axis for the bare-status rows (#1576).
492
518
  *
@@ -503,13 +529,22 @@ async function expectedDeliveryHolder(target) {
503
529
  *
504
530
  * `leased` says whether the read found a delivery lease record. An open mesh runs no delivery
505
531
  * daemon, so there a missing lease is the normal state rather than an unbound responder. */
506
- async function readResponderAxis(selected, preflight) {
532
+ async function readResponderAxis(selected, preflight, gaps) {
507
533
  let leased = false;
508
534
  if (!selected.ok)
509
535
  return { state: "unknown", leased };
510
536
  const target = selected.target;
511
537
  if (target.mode === "user")
512
538
  return { state: "unknown", leased };
539
+ let holder;
540
+ try {
541
+ holder = await expectedDeliveryHolder(target);
542
+ }
543
+ catch (error) {
544
+ const message = error instanceof Error ? error.message : String(error);
545
+ gaps.add("DELIVERY_CREDENTIAL_UNREADABLE", isCommandFailure(error) && error.remedy ? `${message}; ${error.remedy}` : message, { root: target.root, space: target.space });
546
+ return { state: "unknown", leased };
547
+ }
513
548
  try {
514
549
  if (!preflight?.ok)
515
550
  return { state: "unknown", leased };
@@ -546,12 +581,16 @@ async function readResponderAxis(selected, preflight) {
546
581
  // `--components` surface deliberately does NOT use it: that surface must tell a missing lease
547
582
  // stream apart from a refused read, and flattening both to `unknown` would erase a
548
583
  // distinction it reports.
549
- const holder = await expectedDeliveryHolder(target);
550
584
  const state = await deliveryResponderState(async () => { const lease = await ep.readDeliveryLease(0); leased = lease !== undefined; return lease; }, holder);
551
585
  // A daemon killed before it could release shard 0 leaves its ready row, which names this
552
586
  // folder's credential, until the bucket TTL removes it. When this folder's delivery pidfile
553
587
  // names a process that is gone, that row is the dead daemon's, the same rule `up` waits on.
554
- return { state: state === "bound" && holder !== undefined && processRecord(DELIVERY_PIDFILE, { root: target.root, space: target.space }).kind === "dead" ? "stale" : state, leased };
588
+ const deadLocal = processRecord(DELIVERY_PIDFILE, { root: target.root, space: target.space }).kind === "dead";
589
+ const journal = readStackJournal(target.root)?.journal;
590
+ const member = journal?.space === target.space ? journal.members.find((row) => row.role === "delivery") : undefined;
591
+ const instance = member?.instanceId && serviceInstances(target.space, STACK_DEFINITION.delivery).find((row) => row.name === member.instanceId);
592
+ const deadInstance = instance && ["gone", "foreign-pid", "previous-boot"].includes(instanceProjection(instance).observedProcess);
593
+ return { state: state === "bound" && holder !== undefined && (deadLocal || deadInstance) ? "stale" : state, leased };
555
594
  }
556
595
  finally {
557
596
  await ep.stop().catch(() => { });
@@ -652,6 +691,11 @@ async function readFolder(root, selected, values, responder, gaps, hints) {
652
691
  processes.push({ name: component.name, state: "unreadable", pid: null, detail: `pidfile unreadable · ${e.message}` });
653
692
  continue;
654
693
  }
694
+ if (state.liveness === "unknown") {
695
+ const path = localProcessPath(component.pidFile, context);
696
+ gaps.add("PIDFILE_UNATTRIBUTABLE", `the ${component.name} pidfile ${path} cannot establish process state: ${state.note ?? "pid liveness unknown"}`, { root, space, process: component.name });
697
+ hints.push(`inspect ${path} and its process before restoring or removing that pidfile; no stopped state was inferred`);
698
+ }
655
699
  if (component.name === "nats")
656
700
  nats = state;
657
701
  // #2073: a live manager pid used to print green `running` on the pidfile alone, which is how
@@ -682,6 +726,7 @@ async function readFolder(root, selected, values, responder, gaps, hints) {
682
726
  // rest of the report still stands.
683
727
  if (isCommandFailure(error) && (error.code === "SCHEMA_INVALID" || error.code === "PERMISSION_DENIED")) {
684
728
  unusable = true;
729
+ stackJournal = "unreadable";
685
730
  gaps.add(error.code === "PERMISSION_DENIED" ? "STACK_JOURNAL_UNREADABLE" : "STACK_JOURNAL_INVALID", error.remedy ? `${error.message}; ${error.remedy}` : error.message, { root });
686
731
  if (error.remedy)
687
732
  hints.push(error.remedy);
@@ -691,7 +736,14 @@ async function readFolder(root, selected, values, responder, gaps, hints) {
691
736
  }
692
737
  const brokerIndex = processes.findIndex((row) => row.name === "nats");
693
738
  if (brokerIndex !== -1)
694
- processes[brokerIndex] = brokerProcess(processes[brokerIndex], controllerStack ? journal : undefined, gaps);
739
+ processes[brokerIndex] = unusable
740
+ ? { name: "nats", state: "unreadable", pid: null, detail: "stack journal unreadable; no broker stopped state was inferred" }
741
+ : brokerProcess(processes[brokerIndex], controllerStack ? journal : undefined, gaps);
742
+ const managerIndex = !unusable && !controllerStack && (nats?.liveness === "alive" || nats?.liveness === "dead")
743
+ ? processes.findIndex((row) => row.name === "manager" && row.state === "stopped" && row.pid === null)
744
+ : -1;
745
+ if (managerIndex !== -1 && legacyManagerStopped(root, space))
746
+ processes[managerIndex] = { ...processes[managerIndex], detail: "stopped" };
695
747
  const noManager = journal !== undefined && controllerStack && stackStartedWithoutManager(journal);
696
748
  // An operation cut off with no recorded outcome can keep up and down from settling it; status names
697
749
  // why and the way out their refusal names. A refusal of another kind is left to them.
@@ -731,7 +783,7 @@ async function readFolder(root, selected, values, responder, gaps, hints) {
731
783
  catch {
732
784
  legacyElsewhere = false;
733
785
  }
734
- const storedState = !controllerStack && !elsewhere && !copiedStack && !legacyElsewhere && nats?.liveness !== "alive" && existsSync(join(root, ".cotal", "nats"));
786
+ const storedState = !unusable && !controllerStack && !elsewhere && !copiedStack && !legacyElsewhere && nats?.liveness !== "alive" && existsSync(join(root, ".cotal", "nats"));
735
787
  // While a maintenance journal holds the store, clean store refuses, so it is not offered.
736
788
  let maintained = false;
737
789
  try {
@@ -741,7 +793,7 @@ async function readFolder(root, selected, values, responder, gaps, hints) {
741
793
  maintained = true;
742
794
  }
743
795
  // Its next step is the unusable journal's, which every stack command refuses until it is fixed.
744
- if (storedState && !maintained && !unusable) {
796
+ if (storedState && !maintained && !unusable && !rootStoreProblem(root)) {
745
797
  const resetSpace = storeResetSpace(root, space);
746
798
  hints.push(resetSpace !== undefined
747
799
  ? `if the stored JetStream state is stale: \`${cmd} reset store ${resetSpace}\`, then \`up\` with your usual flags`
@@ -855,6 +907,8 @@ function brokerProcess(legacy, journal, gaps) {
855
907
  const row = { ...legacy, source: journal ? "owned-service" : "legacy-pidfile", legacyPidfile: { state, pid, detail }, ownedService: null };
856
908
  if (!journal)
857
909
  return row;
910
+ if (stackRunsUnderOtherHome(journal.root, journal) && journal.recovery?.home !== homeCotalDir())
911
+ return { ...row, state: "unknown", pid: null, detail: `stack member records belong to ${journal.recovery?.home ?? "another Cotal home"}` };
858
912
  try {
859
913
  const instances = serviceInstances(journal.space, STACK_DEFINITION.broker);
860
914
  if (instances.length === 0) {
@@ -940,6 +994,28 @@ function localManagerInstanceId(root, space) {
940
994
  return undefined;
941
995
  }
942
996
  }
997
+ /** Whether the legacy stack whose broker pidfile is in `root` started a manager that has since
998
+ * exited and removed its pidfile (as SIGTERM does), rather than running with `--no-manager`. */
999
+ function legacyManagerStopped(root, space) {
1000
+ const id = localManagerInstanceId(root, space);
1001
+ if (id === undefined)
1002
+ return false;
1003
+ let brokerMtime;
1004
+ try {
1005
+ brokerMtime = statSync(join(root, ".cotal", NATS_PIDFILE), { bigint: true }).mtimeNs;
1006
+ }
1007
+ catch {
1008
+ return false;
1009
+ }
1010
+ for (const path of [managerLogPath(space, root), join(root, ".cotal", `manager-execution.${spaceKey(space)}.${id}.json`)]) {
1011
+ try {
1012
+ if (statSync(path, { bigint: true }).mtimeNs >= brokerMtime)
1013
+ return true;
1014
+ }
1015
+ catch { /* absent or unreadable candidate */ }
1016
+ }
1017
+ return false;
1018
+ }
943
1019
  /** User-mode manager status goes through the same control call `cotal spawn` uses. `instanceId`
944
1020
  * pins that call to this machine's manager. Without it, the exchange may select another live
945
1021
  * manager of the same owner. */
@@ -1060,7 +1136,7 @@ async function readMeshes(cwd, selected, all, gaps, offline, preflight) {
1060
1136
  return "reachable";
1061
1137
  if (preflight.kind === "slow-link" || preflight.kind === "broker-stopped" || preflight.kind === "unreachable")
1062
1138
  return preflight.kind;
1063
- return preflight.kind === "tls-trust" || preflight.kind === "tls-unsupported" ? "unreachable" : "reachable";
1139
+ return preflight.kind === "tls-trust" || preflight.kind === "tls-unsupported" || preflight.kind === "auth-unsupported" || preflight.kind === "jetstream-unsupported" || preflight.kind === "non-nats-listener" ? "unreachable" : "reachable";
1064
1140
  }
1065
1141
  return brokerCheck(m.server, m.tlsRequired);
1066
1142
  };
@@ -1150,23 +1226,6 @@ function unusableServiceInstances(space) {
1150
1226
  return isCommandFailure(error) && error.code === "SCHEMA_INVALID" ? error : undefined;
1151
1227
  }
1152
1228
  }
1153
- /** Why the broker of the stack at `root` cannot start on its store: the one its stack journal recorded,
1154
- * or `.cotal/nats`. */
1155
- function rootStoreProblem(root) {
1156
- let recorded;
1157
- try {
1158
- recorded = readStackJournal(root)?.journal.broker?.storeDir;
1159
- }
1160
- catch {
1161
- recorded = undefined;
1162
- }
1163
- try {
1164
- return storeWriteProblem(recorded ?? join(root, ".cotal", "nats"));
1165
- }
1166
- catch {
1167
- return undefined;
1168
- }
1169
- }
1170
1229
  async function readSelected(selected, responder, folder, gaps, hints, preflight) {
1171
1230
  const cmd = displayCmd();
1172
1231
  if (!selected.ok) {
@@ -1228,8 +1287,10 @@ async function readSelected(selected, responder, folder, gaps, hints, preflight)
1228
1287
  hints.push(instances.remedy ?? instances.message);
1229
1288
  else if (store)
1230
1289
  hints.push(`${store.message}; ${store.remedy}`);
1231
- else if (!d.unsettled || !servedStack(folder, result))
1232
- hints.push(remedy ?? message);
1290
+ else if (!d.unsettled || !servedStack(folder, result)) {
1291
+ const step = remedy ?? message;
1292
+ hints.push(e.code === "no-meshes" && d.root === undefined ? step.replaceAll("`cotal ", () => `\`${cmd} `) : step);
1293
+ }
1233
1294
  else if (!folder.stackBlock && !folder.stackUnfinished)
1234
1295
  hints.push(`start it with \`cotal up\` in ${d.root}`);
1235
1296
  return result;
@@ -1306,9 +1367,14 @@ async function readSelected(selected, responder, folder, gaps, hints, preflight)
1306
1367
  // starts it again rather than a registration to repair.
1307
1368
  const flagged = (target.source === "flag-server" || target.source === "flag-space-override") && target.recordedServer !== target.server;
1308
1369
  const offline = preflight.kind === "unreachable" && !flagged && target.origin === "up";
1370
+ const store = offline ? rootStoreProblem(target.root) : undefined;
1309
1371
  // A blocked stack refuses that `up`, and Next names the step that clears the block instead.
1310
1372
  if (preflight.kind === "unreachable" && (flagged || offline) && !(servedStack(folder, base) && folder.stackBlock)) {
1311
1373
  const { message, remedy } = workspaceErrorParts({ kind: "preflight", failure: "unreachable", target, pruned: !offline && preflight.prune });
1374
+ hints.push(store ? `${store.message}; ${store.remedy}` : remedy === undefined ? message : `${message}; ${remedy}`);
1375
+ }
1376
+ if (preflight.kind === "non-nats-listener" || preflight.kind === "auth-unsupported" || preflight.kind === "jetstream-unsupported") {
1377
+ const { message, remedy } = workspaceErrorParts({ kind: "preflight", failure: preflight.kind, target, pruned: false });
1312
1378
  hints.push(remedy === undefined ? message : `${message}; ${remedy}`);
1313
1379
  }
1314
1380
  return { ...base, connection: preflight.kind, ...(preflight.pid === undefined ? {} : { brokerPid: preflight.pid }), staleRecord: preflight.prune && !offline, snapshot: { state: "skipped", reason: "broker not connected" } };
@@ -1430,8 +1496,8 @@ function personaCell(p, dim = false) {
1430
1496
  }
1431
1497
  function processCell(p) {
1432
1498
  const detail = p.detail ? ` · ${p.detail}` : "";
1433
- if (p.state === "unreadable")
1434
- return cell(p.detail ?? "pidfile unreadable", "failed");
1499
+ if (p.state === "unreadable" || p.state === "unknown")
1500
+ return cell(p.detail ?? "process state unknown", "failed");
1435
1501
  if (p.state === "not-serving")
1436
1502
  return cell(`not serving (pid ${p.pid})${detail}`, "failed");
1437
1503
  if (p.state === "running")
@@ -1741,6 +1807,9 @@ function connectionCell(s) {
1741
1807
  "broker-stopped": `broker process ${s.brokerPid} is stopped`,
1742
1808
  "tls-trust": "TLS could not be verified",
1743
1809
  "tls-unsupported": "listener does not offer required TLS",
1810
+ "auth-unsupported": "listener does not enforce Cotal authentication",
1811
+ "jetstream-unsupported": "listener does not offer JetStream",
1812
+ "non-nats-listener": "non-NATS listener holds the broker address",
1744
1813
  "stale-auth": "credentials need renewal",
1745
1814
  "auth-required": "authentication required",
1746
1815
  "open-wants-auth": "authentication required",
@@ -1797,7 +1866,7 @@ function spacesOverview(r, wide) {
1797
1866
  });
1798
1867
  const columns = [{ key: "space", label: "Space" }, { key: "state", label: "Connection" }, { key: "detail", label: "Signs in" }];
1799
1868
  if (!r.meshes.items.length && !r.meshes.unreadable.length)
1800
- blocks.push({ kind: "lines", lines: [cell("No spaces registered", "hint"), cell("Sign in to Cotal Cloud with `cotal login`.", "hint")] });
1869
+ blocks.push({ kind: "lines", lines: [cell("No spaces registered", "hint"), cell(`Sign in to Cotal Cloud with \`${displayCmd()} login\`.`, "hint")] });
1801
1870
  else if (wide) {
1802
1871
  const groups = new Map();
1803
1872
  for (const entry of r.meshes.items) {
@@ -1891,6 +1960,9 @@ function selectedOverview(r) {
1891
1960
  if (r.folder.root === s.root && r.folder.processSpace === s.space && r.folder.controllerStack) {
1892
1961
  blocks.push({ kind: "lines", lines: [cell("Controller stack · its members are the stack-* rows under Owned services", "hint")] }, ...stackLines(r.folder));
1893
1962
  }
1963
+ else if (r.folder.root === s.root && r.folder.stackJournal === "unreadable") {
1964
+ blocks.push({ kind: "lines", lines: [cell("Stack journal unreadable · no stack membership or stopped state was inferred; see Owned services and the journal warning", "failed")] });
1965
+ }
1894
1966
  else if (r.folder.root === s.root && r.folder.processSpace === s.space && r.folder.processes) {
1895
1967
  blocks.push({ kind: "lines", lines: [cell("Legacy local process records", "label")] });
1896
1968
  blocks.push({
@@ -1898,7 +1970,7 @@ function selectedOverview(r) {
1898
1970
  columns: [{ key: "name", label: "Service" }, { key: "state", label: "State" }],
1899
1971
  rows: r.folder.processes.map((item) => ({
1900
1972
  name: item.name === "nats" ? "Broker" : item.name === "manager" ? "Manager" : item.name === "delivery" ? "Delivery" : item.name === "web" ? "Web" : item.name,
1901
- state: item.state === "running" || item.state === "not-serving" || item.state === "unreadable" ? processCell(item) : stateCell(item.pid === null ? "not started" : item.detail ?? "stopped", "hint"),
1973
+ state: item.state !== "stopped" ? processCell(item) : stateCell(item.pid === null && item.detail !== "stopped" ? "not started" : item.detail ?? "stopped", "hint"),
1902
1974
  })),
1903
1975
  });
1904
1976
  }
@@ -1948,7 +2020,7 @@ function nextActions(r) {
1948
2020
  const cmd = displayCmd();
1949
2021
  const items = [];
1950
2022
  const extra = [];
1951
- const noApplication = !r.machine.connectors?.length;
2023
+ const noApplication = !setUpApplications(r.machine).length;
1952
2024
  if (!r.selected.resolved && !r.meshes.items.length && !r.meshes.unreadable.length) {
1953
2025
  items.push({ command: `${cmd} login`, description: "Sign in to Cotal Cloud" });
1954
2026
  }
@@ -1978,7 +2050,7 @@ function nextActions(r) {
1978
2050
  // own records. One whose last operation a member keeps unsettled is named the way out that
1979
2051
  // `up` and `down` name instead. A stack started with --no-manager leaves its manager out by choice,
1980
2052
  // so a manager record an earlier up left is not a stopped member, and the restart keeps the flag.
1981
- const memberGone = r.services?.instances?.some((row) => row.definition.startsWith("stack-") && row.observedProcess === "gone" && !(r.folder.noManager && row.definition === STACK_DEFINITION.manager)) === true;
2053
+ const memberGone = r.services?.instances?.some((row) => row.definition.startsWith("stack-") && ["gone", "foreign-pid", "previous-boot"].includes(row.observedProcess) && !(r.folder.noManager && row.definition === STACK_DEFINITION.manager)) === true;
1982
2054
  // A connection to a `--server` address other than the recorded one does not say whether the stack
1983
2055
  // answers; the hint `readSelected` adds names that address. A user-auth space is probed on its own path.
1984
2056
  const dialed = r.selected.resolved ? r.selected : undefined;
@@ -1993,7 +2065,8 @@ function nextActions(r) {
1993
2065
  // refresh restarts no manager, and an open or user-auth broker needs its mode flag again.
1994
2066
  const local = r.selected.resolved && r.selected.mode === "auth" && !r.folder.controllerStack && r.folder.root === r.selected.root && r.folder.processSpace === r.selected.space
1995
2067
  && !["manual", "catalog"].includes(r.meshes.items.find((m) => m.space === r.selected.space)?.origin ?? "up");
1996
- const exited = local ? (r.folder.processes ?? []).filter((row) => (row.name === "nats" || row.name === "manager") && row.state === "stopped" && row.pid !== null).map((row) => row.name) : [];
2068
+ const exited = local ? (r.folder.processes ?? []).filter((row) => (row.name === "nats" || row.name === "manager") && row.state === "stopped" && (row.pid !== null || row.detail === "stopped")).map((row) => row.name) : [];
2069
+ const storeBlocked = !elsewhere && r.selected.resolved && r.selected.connection === "unreachable" && rootStoreProblem(r.selected.root) !== undefined;
1997
2070
  if (r.selected.resolved && r.selected.connection === "broker-stopped")
1998
2071
  items.unshift({ command: `kill -CONT ${r.selected.brokerPid}`, description: "Resume the stopped broker process so it answers again" });
1999
2072
  else if (block && blocked) {
@@ -2024,17 +2097,22 @@ function nextActions(r) {
2024
2097
  extra.push(`${absent.message}; ${absent.remedy}`);
2025
2098
  }
2026
2099
  }
2027
- else if (own && r.selected.resolved && r.store?.state !== "full" && (memberGone || !elsewhere && r.selected.connection !== "ok" && r.selected.connection !== "reachable")) {
2100
+ else if (!storeBlocked && own && r.selected.resolved && r.store?.state !== "full" && (memberGone || !elsewhere && r.selected.connection !== "ok" && r.selected.connection !== "reachable")) {
2028
2101
  // `up` neither adopts nor replaces a service outside the stack that runs one of this root's
2029
2102
  // records, so each is stopped first, with the stop `up` names.
2030
2103
  const held = r.folder.heldServices ?? [], space = r.selected.space;
2031
2104
  items.unshift(...held.map((row) => ({ command: `${cmd} svc stop ${row.definition} --instance ${row.instanceId} --space ${space} --yes`, description: `Stop the ${row.definition} service, which runs this root's ${row.record} (pid ${row.pid}) outside the stack` })), { command: `${cmd} up --root ${shellWord(r.selected.root)}${r.folder.noManager ? " --no-manager" : ""}`, description: held.length ? "Then restart this stack's stopped members from its recorded inputs" : "Restart this stack's stopped members from its recorded inputs" });
2032
2105
  }
2033
- else if (exited.length) {
2106
+ else if (!storeBlocked && exited.length) {
2034
2107
  const broker = exited.includes("nats"), manager = exited.includes("manager");
2035
2108
  const notes = [...(broker ? ["up reopens the recorded store"] : []), ...(manager ? ["pass --runtime again if the manager ran on one"] : [])];
2036
2109
  items.unshift({ command: `${cmd} up`, description: `Restart this folder's ${broker && manager ? "broker and manager" : broker ? "broker" : "manager"}, which exited; ${notes.join("; ")}` });
2037
2110
  }
2111
+ else if (!storeBlocked && local && r.selected.resolved && r.selected.connection === "unreachable" && (r.folder.processes ?? []).every((row) => row.state === "stopped")) {
2112
+ // A clean down leaves every member stopped with no pidfile. Spawn and ps need the stack, so the
2113
+ // bare `up` that starts it again on its recorded address and store comes first.
2114
+ items.unshift({ command: `${cmd} up`, description: "Start this folder's stopped stack again; pass --runtime again if the manager ran on one" });
2115
+ }
2038
2116
  // A stack whose folder was deleted stops only from this machine's records.
2039
2117
  if (r.selected.resolved && r.selected.rootGone)
2040
2118
  items.unshift({ command: `${cmd} down --space ${r.selected.space} --yes`, description: "Stop the stack whose folder is gone and free its name" });
@@ -2184,21 +2262,17 @@ function componentExit(components) {
2184
2262
  return Math.max(...components.map((component) => COMPONENT_EXIT[component.verdict]));
2185
2263
  }
2186
2264
  function processRecord(template, context) {
2187
- let raw;
2188
2265
  try {
2189
- raw = readPidfile(localProcessPath(template, context));
2266
+ const path = localProcessPath(template, context);
2267
+ const state = pidfileState(path);
2268
+ if (state.pid === undefined)
2269
+ return state.liveness === "dead" ? { kind: "absent" } : { kind: "unattributable", raw: readPidfile(path) ?? "" };
2270
+ return { kind: state.liveness === "alive" ? "live" : state.liveness === "dead" ? "dead" : "unknown", pid: state.pid };
2190
2271
  }
2191
2272
  catch (e) {
2192
2273
  // An ambiguous record or any failed read refuses this component's row, never the whole pass.
2193
2274
  return { kind: "unreadable", error: e.message };
2194
2275
  }
2195
- if (!raw)
2196
- return { kind: "absent" };
2197
- const pid = parsePid(raw);
2198
- if (pid === undefined)
2199
- return { kind: "unattributable", raw };
2200
- const liveness = probeLiveness(pid);
2201
- return liveness === "alive" ? { kind: "live", pid } : liveness === "dead" ? { kind: "dead", pid } : { kind: "unknown", pid };
2202
2276
  }
2203
2277
  function pidFacts(record) {
2204
2278
  if (record.kind === "live" || record.kind === "dead" || record.kind === "unknown")
@@ -2350,7 +2424,7 @@ async function managerServiceHealth(target, auth) {
2350
2424
  await drainAndClose(nc);
2351
2425
  }
2352
2426
  }
2353
- async function managerHealth(target, context, credential) {
2427
+ async function managerHealth(target, context, credential, broker) {
2354
2428
  const record = processRecord(MANAGER_PIDFILE, context);
2355
2429
  const facts = pidFacts(record);
2356
2430
  // A corrupt or kernel-unreadable LOCAL record is neither evidence that the manager is absent nor
@@ -2446,10 +2520,26 @@ async function managerHealth(target, context, credential) {
2446
2520
  // lease still identifies an extant component; any other failed probe remains a refusal.
2447
2521
  const noService = managerNoService(e);
2448
2522
  facts.push(noService ? "serve no answer" : `serve probe refused: ${e.message}`);
2523
+ if (broker.verdict === "absent" && processVerdict(record) === "absent")
2524
+ return { name: "manager", verdict: "absent", facts };
2449
2525
  if (!noService)
2450
2526
  return { name: "manager", verdict: "refused", facts };
2451
2527
  const liveRecord = record.kind === "live";
2452
2528
  const hasLease = facts.some((fact) => fact.startsWith("lease holder "));
2529
+ if (!liveRecord && !hasLease) {
2530
+ try {
2531
+ const journal = readStackJournal(context.root)?.journal;
2532
+ const pin = verifyIdentityPin(localProcessPath(MANAGER_OMITTED, context));
2533
+ const brokerRecord = processRecord(NATS_PIDFILE, context);
2534
+ const omitted = journal?.space === context.space ? stackStartedWithoutManager(journal)
2535
+ : pin.kind === "match" && brokerRecord.kind === "live" && pin.record.pid === brokerRecord.pid;
2536
+ if (omitted)
2537
+ return { name: "manager", verdict: "not-started", facts: [...facts, "started with --no-manager"] };
2538
+ }
2539
+ catch (error) {
2540
+ return { name: "manager", verdict: "refused", facts: [...facts, `startup intent unreadable: ${error.message}`] };
2541
+ }
2542
+ }
2453
2543
  return { name: "manager", verdict: liveRecord || (record.kind !== "dead" && hasLease) ? "not-serving" : "absent", facts };
2454
2544
  }
2455
2545
  finally {
@@ -2482,6 +2572,26 @@ async function deliveryHealth(target, context, credential) {
2482
2572
  facts.push("renewal adoption not reported");
2483
2573
  else
2484
2574
  facts.push(renewal.adoption.ok ? "renewal adoption accepted" : `renewal adoption refused${renewal.adoption.error ? `: ${renewal.adoption.error}` : ""}`);
2575
+ const renewalRefused = renewal?.adoption?.ok === false;
2576
+ if (target.mode === "open" && record.kind === "absent" && !renewalRefused) {
2577
+ if (credential.kind === "unavailable")
2578
+ return { name: "delivery", verdict: "refused", facts: [credential.reason] };
2579
+ try {
2580
+ const component = await componentEp(target, credential);
2581
+ try {
2582
+ if (!await component.ep.readDeliveryLease(0))
2583
+ return { name: "delivery", verdict: "not-started", facts: ["not used on an open mesh"] };
2584
+ }
2585
+ finally {
2586
+ await component.close();
2587
+ }
2588
+ }
2589
+ catch (error) {
2590
+ if (deliveryLeaseAbsent(error))
2591
+ return { name: "delivery", verdict: "not-started", facts: ["not used on an open mesh"] };
2592
+ return { name: "delivery", verdict: "refused", facts: [`lease probe refused: ${error instanceof Error ? error.message : String(error)}`] };
2593
+ }
2594
+ }
2485
2595
  if (stopped) {
2486
2596
  if (record.kind === "dead")
2487
2597
  facts.push("stale pidfile");
@@ -2489,7 +2599,7 @@ async function deliveryHealth(target, context, credential) {
2489
2599
  facts.push("unattributable pidfile");
2490
2600
  if (record.kind === "unknown")
2491
2601
  facts.push("pid liveness unestablishable");
2492
- return { name: "delivery", verdict: stopped, facts };
2602
+ return { name: "delivery", verdict: renewalRefused ? "refused" : stopped, facts };
2493
2603
  }
2494
2604
  let close;
2495
2605
  try {
@@ -2514,7 +2624,7 @@ async function deliveryHealth(target, context, credential) {
2514
2624
  const state = deliveryResponderFromLease(lease, await expectedDeliveryHolder(target));
2515
2625
  if (!lease) {
2516
2626
  facts.push("ready lease absent", `responder not bound - ${RESPONDER_UNBOUND_CONSEQUENCE}`);
2517
- return { name: "delivery", verdict: "not-serving", facts };
2627
+ return { name: "delivery", verdict: renewalRefused ? "refused" : "not-serving", facts };
2518
2628
  }
2519
2629
  facts.push(`lease holder ${lease.holder}`);
2520
2630
  if (state === "stale") {
@@ -2522,12 +2632,12 @@ async function deliveryHealth(target, context, credential) {
2522
2632
  // operator cannot derive from the other facts on the line.
2523
2633
  facts.push("ready, but held by a DIFFERENT daemon than this workspace launched (a dead holder's record expires on its own)");
2524
2634
  facts.push(`responder not bound - ${RESPONDER_UNBOUND_CONSEQUENCE}`);
2525
- return { name: "delivery", verdict: "not-serving", facts };
2635
+ return { name: "delivery", verdict: renewalRefused ? "refused" : "not-serving", facts };
2526
2636
  }
2527
2637
  facts.push(state === "bound" ? "ready" : "starting (lease not ready)");
2528
2638
  if (state !== "bound")
2529
2639
  facts.push(`responder not bound - ${RESPONDER_UNBOUND_CONSEQUENCE}`);
2530
- return { name: "delivery", verdict: state === "bound" ? "serving" : "not-serving", facts };
2640
+ return { name: "delivery", verdict: renewalRefused ? "refused" : state === "bound" ? "serving" : "not-serving", facts };
2531
2641
  }
2532
2642
  catch (e) {
2533
2643
  // A live recorded daemon with no delivery lease bucket cannot be serving this build's delivery
@@ -2536,7 +2646,9 @@ async function deliveryHealth(target, context, credential) {
2536
2646
  const noLeaseSurface = deliveryLeaseAbsent(e);
2537
2647
  const msg = e instanceof Error ? e.message : String(e);
2538
2648
  facts.push(noLeaseSurface ? "ready lease absent" : `lease probe refused: ${msg}`);
2539
- return { name: "delivery", verdict: noLeaseSurface ? "not-serving" : "refused", facts };
2649
+ if (isCommandFailure(e) && e.remedy)
2650
+ facts.push(e.remedy);
2651
+ return { name: "delivery", verdict: renewalRefused || !noLeaseSurface ? "refused" : "not-serving", facts };
2540
2652
  }
2541
2653
  finally {
2542
2654
  await close?.();
@@ -2549,6 +2661,14 @@ async function webHealth(context) {
2549
2661
  const facts = pidFacts(record);
2550
2662
  const stopped = processVerdict(record);
2551
2663
  if (record.kind === "absent") {
2664
+ try {
2665
+ const unsettled = serviceInstances(context.space, "web").map(instanceProjection).find((row) => row.recordedState !== "stopped" && ["gone", "foreign-pid", "previous-boot"].includes(row.observedProcess));
2666
+ if (unsettled)
2667
+ return { name: "web", verdict: "absent", facts: [`service instance ${unsettled.instanceId}`, `recorded ${unsettled.recordedState}`, unsettled.observedProcess] };
2668
+ }
2669
+ catch (e) {
2670
+ return { name: "web", verdict: "refused", facts: [`service instance records unreadable: ${e.message}`] };
2671
+ }
2552
2672
  // An installation that cannot be read keeps the absent verdict rather than a clean zero.
2553
2673
  let installed;
2554
2674
  try {
@@ -2609,12 +2729,39 @@ async function webHealth(context) {
2609
2729
  }
2610
2730
  return { name: "web", verdict: "not-serving", facts: [...facts, `host ${bound.host}`, `port ${bound.port}`, "http not answered"] };
2611
2731
  }
2612
- async function brokerHealth(target) {
2732
+ async function brokerHealth(target, store) {
2613
2733
  const address = brokerAddressForDisplay(target.server);
2614
2734
  if (address === undefined)
2615
2735
  return { name: "broker", verdict: "refused", facts: ["registered address unavailable", "invalid broker address"] };
2616
2736
  try {
2737
+ const context = { root: target.root, space: target.space };
2738
+ const journal = readStackJournal(target.root)?.journal;
2739
+ if (journal?.space === target.space && journal.server === target.server) {
2740
+ const member = journal.members.find((row) => row.role === "broker");
2741
+ const instance = serviceInstances(target.space, STACK_DEFINITION.broker).find((row) => row.name === member?.instanceId);
2742
+ const observed = instance && instanceProjection(instance).observedProcess;
2743
+ if (!instance || observed && ["gone", "foreign-pid", "previous-boot"].includes(observed))
2744
+ return { name: "broker", verdict: "absent", facts: [`registered ${address}`, observed ?? "no local instance"] };
2745
+ if (observed !== "running")
2746
+ return { name: "broker", verdict: "refused", facts: [`registered ${address}`, `local process ${observed}`] };
2747
+ }
2748
+ else if (target.origin === "up" && target.mode !== "user" && (target.recordedServer === undefined || target.recordedServer === target.server)) {
2749
+ const record = processRecord(NATS_PIDFILE, context);
2750
+ const verdict = processVerdict(record);
2751
+ if (verdict)
2752
+ return { name: "broker", verdict, facts: [`registered ${address}`, ...pidFacts(record), ...(record.kind === "dead" ? ["stale pidfile"] : [])] };
2753
+ }
2754
+ const storeFailure = store?.state === "write-failed" ? `store write failed: ${store.cause}`
2755
+ : store?.state === "full" ? `store full: ${store.used} bytes exceeds ${store.cap} bytes at ${store.path}` : undefined;
2756
+ if (target.mode !== "user") {
2757
+ const preflight = await preflightTarget(target);
2758
+ if (!preflight.ok)
2759
+ return { name: "broker", verdict: "not-serving", facts: [`registered ${address}`, workspaceErrorParts({ kind: "preflight", failure: preflight.kind, target, pruned: false }).message] };
2760
+ return { name: "broker", verdict: storeFailure ? "not-serving" : "serving", facts: [`registered ${address}`, "reachable", ...(storeFailure ? [storeFailure] : [])] };
2761
+ }
2617
2762
  const reachable = await isReachable(target.server, target.tlsRequired ? { tls: true } : {});
2763
+ if (storeFailure)
2764
+ return { name: "broker", verdict: "not-serving", facts: [`registered ${address}`, reachable ? "reachable" : "unreachable", storeFailure] };
2618
2765
  return reachable
2619
2766
  ? { name: "broker", verdict: "serving", facts: [`registered ${address}`, "reachable"] }
2620
2767
  : { name: "broker", verdict: "not-serving", facts: [`registered ${address}`, "unreachable"] };
@@ -2623,36 +2770,40 @@ async function brokerHealth(target) {
2623
2770
  return { name: "broker", verdict: "refused", facts: [`registered ${address}`, `probe refused: ${e.message}`] };
2624
2771
  }
2625
2772
  }
2626
- async function printComponentHealth(cwd, values) {
2773
+ async function printComponentHealth(selected, store) {
2627
2774
  section("Component Health");
2628
- let target;
2629
- try {
2630
- target = resolveMeshTarget(cwd, { server: values.server, space: values.space });
2631
- }
2632
- catch (e) {
2775
+ if (!selected.ok) {
2776
+ const e = selected.error;
2777
+ if (isMeshRegistryError(e)) {
2778
+ printComponent({ name: "target", verdict: "refused", facts: ["SCHEMA_INVALID", e.message] });
2779
+ process.exitCode = COMPONENT_EXIT.refused;
2780
+ return;
2781
+ }
2633
2782
  if (isWorkspaceTargetError(e)) {
2634
- printComponent({ name: "target", verdict: "refused", facts: [e.code, renderWorkspaceError({ kind: "target", error: e }).replace(/^✗ /, "")] });
2783
+ const verdict = e.code === "not-started" ? "absent" : "refused";
2784
+ printComponent({ name: "target", verdict, facts: [e.code, renderWorkspaceError({ kind: "target", error: e }).replace(/^✗ /, "")] });
2785
+ process.exitCode = COMPONENT_EXIT[verdict];
2786
+ return;
2787
+ }
2788
+ if (e instanceof UnregisteredRoot) {
2789
+ printComponent({ name: "target", verdict: "refused", facts: ["unregistered-root", `no space is registered or prepared here for ${e.root}`] });
2635
2790
  process.exitCode = COMPONENT_EXIT.refused;
2636
2791
  return;
2637
2792
  }
2638
2793
  throw e;
2639
2794
  }
2640
- // The report's own rule: an unregistered project root is given no broker to probe.
2641
- if (target.source === "local-space") {
2642
- printComponent({ name: "target", verdict: "refused", facts: ["unregistered-root", `no space is registered or prepared here for ${target.root}`] });
2643
- process.exitCode = COMPONENT_EXIT.refused;
2644
- return;
2645
- }
2795
+ const target = selected.target;
2646
2796
  const context = { root: target.root, space: target.space, userAuth: target.mode === "user" };
2647
2797
  // ONE credential read for the whole pass (user mode resolves the signed-in login once; the
2648
2798
  // static shape is just the target's own auth material), shared by the manager and delivery
2649
2799
  // probes so the two rows cannot disagree about whose credential they probed with.
2650
2800
  const credential = await componentCredential(target);
2801
+ const broker = await brokerHealth(target, store);
2651
2802
  const components = await Promise.all([
2652
- managerHealth(target, context, credential),
2803
+ managerHealth(target, context, credential, broker),
2653
2804
  deliveryHealth(target, context, credential),
2654
2805
  webHealth(context),
2655
- brokerHealth(target),
2806
+ broker,
2656
2807
  ]);
2657
2808
  for (const component of components)
2658
2809
  printComponent(component);