@cotal-ai/cli 0.174.3 → 0.174.4

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 (205) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +8 -5
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +17 -10
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/channel-members.d.ts.map +1 -1
  8. package/dist/commands/channel-members.js +9 -7
  9. package/dist/commands/channel-members.js.map +1 -1
  10. package/dist/commands/channels.d.ts.map +1 -1
  11. package/dist/commands/channels.js +16 -7
  12. package/dist/commands/channels.js.map +1 -1
  13. package/dist/commands/chat.js +1 -1
  14. package/dist/commands/chat.js.map +1 -1
  15. package/dist/commands/clean.d.ts.map +1 -1
  16. package/dist/commands/clean.js +5 -3
  17. package/dist/commands/clean.js.map +1 -1
  18. package/dist/commands/config.d.ts.map +1 -1
  19. package/dist/commands/config.js +8 -1
  20. package/dist/commands/config.js.map +1 -1
  21. package/dist/commands/describe.d.ts.map +1 -1
  22. package/dist/commands/describe.js +11 -1
  23. package/dist/commands/describe.js.map +1 -1
  24. package/dist/commands/doctor.d.ts.map +1 -1
  25. package/dist/commands/doctor.js +21 -9
  26. package/dist/commands/doctor.js.map +1 -1
  27. package/dist/commands/down-preserve.d.ts.map +1 -1
  28. package/dist/commands/down-preserve.js +2 -1
  29. package/dist/commands/down-preserve.js.map +1 -1
  30. package/dist/commands/endpoint-authoring.d.ts.map +1 -1
  31. package/dist/commands/endpoint-authoring.js +20 -19
  32. package/dist/commands/endpoint-authoring.js.map +1 -1
  33. package/dist/commands/endpoint.d.ts.map +1 -1
  34. package/dist/commands/endpoint.js +7 -2
  35. package/dist/commands/endpoint.js.map +1 -1
  36. package/dist/commands/endpoints.d.ts.map +1 -1
  37. package/dist/commands/endpoints.js +12 -5
  38. package/dist/commands/endpoints.js.map +1 -1
  39. package/dist/commands/ext.d.ts +2 -6
  40. package/dist/commands/ext.d.ts.map +1 -1
  41. package/dist/commands/ext.js +19 -25
  42. package/dist/commands/ext.js.map +1 -1
  43. package/dist/commands/history-clear.d.ts.map +1 -1
  44. package/dist/commands/history-clear.js +5 -2
  45. package/dist/commands/history-clear.js.map +1 -1
  46. package/dist/commands/join.d.ts.map +1 -1
  47. package/dist/commands/join.js +23 -20
  48. package/dist/commands/join.js.map +1 -1
  49. package/dist/commands/meshes-add.d.ts.map +1 -1
  50. package/dist/commands/meshes-add.js +3 -2
  51. package/dist/commands/meshes-add.js.map +1 -1
  52. package/dist/commands/meshes.d.ts.map +1 -1
  53. package/dist/commands/meshes.js +17 -4
  54. package/dist/commands/meshes.js.map +1 -1
  55. package/dist/commands/persona-remote.d.ts.map +1 -1
  56. package/dist/commands/persona-remote.js +8 -4
  57. package/dist/commands/persona-remote.js.map +1 -1
  58. package/dist/commands/persona.d.ts.map +1 -1
  59. package/dist/commands/persona.js +38 -29
  60. package/dist/commands/persona.js.map +1 -1
  61. package/dist/commands/personas.js +1 -5
  62. package/dist/commands/personas.js.map +1 -1
  63. package/dist/commands/revoke-credential.d.ts.map +1 -1
  64. package/dist/commands/revoke-credential.js +5 -2
  65. package/dist/commands/revoke-credential.js.map +1 -1
  66. package/dist/commands/service-registry.js +1 -1
  67. package/dist/commands/service-registry.js.map +1 -1
  68. package/dist/commands/setup.d.ts.map +1 -1
  69. package/dist/commands/setup.js +2 -2
  70. package/dist/commands/setup.js.map +1 -1
  71. package/dist/commands/space-delete.d.ts.map +1 -1
  72. package/dist/commands/space-delete.js +17 -10
  73. package/dist/commands/space-delete.js.map +1 -1
  74. package/dist/commands/space-registration.d.ts.map +1 -1
  75. package/dist/commands/space-registration.js +11 -9
  76. package/dist/commands/space-registration.js.map +1 -1
  77. package/dist/commands/space.d.ts.map +1 -1
  78. package/dist/commands/space.js +39 -9
  79. package/dist/commands/space.js.map +1 -1
  80. package/dist/commands/spawn-flags.d.ts +5 -7
  81. package/dist/commands/spawn-flags.d.ts.map +1 -1
  82. package/dist/commands/spawn-flags.js +42 -6
  83. package/dist/commands/spawn-flags.js.map +1 -1
  84. package/dist/commands/spawn-preview.d.ts.map +1 -1
  85. package/dist/commands/spawn-preview.js +5 -3
  86. package/dist/commands/spawn-preview.js.map +1 -1
  87. package/dist/commands/spawn.d.ts.map +1 -1
  88. package/dist/commands/spawn.js +9 -2
  89. package/dist/commands/spawn.js.map +1 -1
  90. package/dist/commands/stack-up.d.ts.map +1 -1
  91. package/dist/commands/stack-up.js +12 -6
  92. package/dist/commands/stack-up.js.map +1 -1
  93. package/dist/commands/status-health.d.ts +139 -0
  94. package/dist/commands/status-health.d.ts.map +1 -0
  95. package/dist/commands/status-health.js +651 -0
  96. package/dist/commands/status-health.js.map +1 -0
  97. package/dist/commands/status-meshes.d.ts +26 -0
  98. package/dist/commands/status-meshes.d.ts.map +1 -0
  99. package/dist/commands/status-meshes.js +468 -0
  100. package/dist/commands/status-meshes.js.map +1 -0
  101. package/dist/commands/status-render.d.ts +30 -0
  102. package/dist/commands/status-render.d.ts.map +1 -0
  103. package/dist/commands/status-render.js +782 -0
  104. package/dist/commands/status-render.js.map +1 -0
  105. package/dist/commands/status.d.ts +2 -16
  106. package/dist/commands/status.d.ts.map +1 -1
  107. package/dist/commands/status.js +20 -1877
  108. package/dist/commands/status.js.map +1 -1
  109. package/dist/commands/topology.d.ts.map +1 -1
  110. package/dist/commands/topology.js +4 -0
  111. package/dist/commands/topology.js.map +1 -1
  112. package/dist/commands/up-host.d.ts +19 -0
  113. package/dist/commands/up-host.d.ts.map +1 -0
  114. package/dist/commands/up-host.js +105 -0
  115. package/dist/commands/up-host.js.map +1 -0
  116. package/dist/commands/up-stores.d.ts +42 -0
  117. package/dist/commands/up-stores.d.ts.map +1 -0
  118. package/dist/commands/up-stores.js +242 -0
  119. package/dist/commands/up-stores.js.map +1 -0
  120. package/dist/commands/up-target.d.ts +2 -0
  121. package/dist/commands/up-target.d.ts.map +1 -1
  122. package/dist/commands/up-target.js +9 -0
  123. package/dist/commands/up-target.js.map +1 -1
  124. package/dist/commands/up.d.ts.map +1 -1
  125. package/dist/commands/up.js +27 -363
  126. package/dist/commands/up.js.map +1 -1
  127. package/dist/commands/update-process.d.ts.map +1 -1
  128. package/dist/commands/update-process.js +3 -15
  129. package/dist/commands/update-process.js.map +1 -1
  130. package/dist/commands/update.js +1 -1
  131. package/dist/commands/update.js.map +1 -1
  132. package/dist/commands/use.js +2 -2
  133. package/dist/commands/use.js.map +1 -1
  134. package/dist/console/app.js +5 -5
  135. package/dist/console/app.js.map +1 -1
  136. package/dist/console/commands.d.ts +1 -1
  137. package/dist/console/commands.d.ts.map +1 -1
  138. package/dist/console/commands.js +1 -1
  139. package/dist/console/commands.js.map +1 -1
  140. package/dist/console/ui/Feed.d.ts +2 -2
  141. package/dist/console/ui/Feed.d.ts.map +1 -1
  142. package/dist/console/ui/Feed.js +2 -2
  143. package/dist/console/ui/Feed.js.map +1 -1
  144. package/dist/console/ui/StatusBar.d.ts +1 -1
  145. package/dist/console/ui/StatusBar.d.ts.map +1 -1
  146. package/dist/console/ui/StatusBar.js +1 -1
  147. package/dist/console/ui/StatusBar.js.map +1 -1
  148. package/dist/console/ui/Tabs.d.ts +2 -2
  149. package/dist/console/ui/Tabs.d.ts.map +1 -1
  150. package/dist/console/ui/Tabs.js +4 -4
  151. package/dist/console/ui/Tabs.js.map +1 -1
  152. package/dist/index.d.ts.map +1 -1
  153. package/dist/index.js +6 -1
  154. package/dist/index.js.map +1 -1
  155. package/dist/lib/backup-artifact.d.ts.map +1 -1
  156. package/dist/lib/backup-artifact.js +19 -7
  157. package/dist/lib/backup-artifact.js.map +1 -1
  158. package/dist/lib/choose-target.d.ts +1 -1
  159. package/dist/lib/choose-target.d.ts.map +1 -1
  160. package/dist/lib/choose-target.js +7 -4
  161. package/dist/lib/choose-target.js.map +1 -1
  162. package/dist/lib/completion-install.js +7 -8
  163. package/dist/lib/completion-install.js.map +1 -1
  164. package/dist/lib/control.d.ts +8 -2
  165. package/dist/lib/control.d.ts.map +1 -1
  166. package/dist/lib/control.js +11 -4
  167. package/dist/lib/control.js.map +1 -1
  168. package/dist/lib/manager-choice.d.ts +2 -1
  169. package/dist/lib/manager-choice.d.ts.map +1 -1
  170. package/dist/lib/manager-choice.js +2 -2
  171. package/dist/lib/manager-choice.js.map +1 -1
  172. package/dist/lib/manifest/index.d.ts +1 -1
  173. package/dist/lib/manifest/index.d.ts.map +1 -1
  174. package/dist/lib/manifest/index.js +2 -2
  175. package/dist/lib/manifest/index.js.map +1 -1
  176. package/dist/lib/manifest/resolve.d.ts +1 -1
  177. package/dist/lib/manifest/resolve.d.ts.map +1 -1
  178. package/dist/lib/manifest/resolve.js +4 -4
  179. package/dist/lib/manifest/resolve.js.map +1 -1
  180. package/dist/lib/npm-invocation.d.ts +6 -0
  181. package/dist/lib/npm-invocation.d.ts.map +1 -0
  182. package/dist/lib/npm-invocation.js +18 -0
  183. package/dist/lib/npm-invocation.js.map +1 -0
  184. package/dist/lib/persona-files.d.ts +1 -0
  185. package/dist/lib/persona-files.d.ts.map +1 -1
  186. package/dist/lib/persona-files.js +6 -2
  187. package/dist/lib/persona-files.js.map +1 -1
  188. package/dist/lib/personas.d.ts +1 -2
  189. package/dist/lib/personas.d.ts.map +1 -1
  190. package/dist/lib/personas.js +12 -3
  191. package/dist/lib/personas.js.map +1 -1
  192. package/dist/lib/private-directory.d.ts +3 -3
  193. package/dist/lib/private-directory.d.ts.map +1 -1
  194. package/dist/lib/private-directory.js +17 -7
  195. package/dist/lib/private-directory.js.map +1 -1
  196. package/dist/lib/service-presets.d.ts.map +1 -1
  197. package/dist/lib/service-presets.js +10 -5
  198. package/dist/lib/service-presets.js.map +1 -1
  199. package/dist/lib/stack-journal.d.ts.map +1 -1
  200. package/dist/lib/stack-journal.js +7 -4
  201. package/dist/lib/stack-journal.js.map +1 -1
  202. package/dist/telemetry.d.ts.map +1 -1
  203. package/dist/telemetry.js +3 -2
  204. package/dist/telemetry.js.map +1 -1
  205. package/package.json +4 -4
@@ -1,51 +1,42 @@
1
1
  import { accessSync, constants, existsSync, lstatSync } from "node:fs";
2
- import { drainAndClose } from "@cotal-ai/core";
3
- import { homedir } from "node:os";
4
2
  import { join } from "node:path";
5
- import { CotalEndpoint, agentFilePath, dialerFor, EpEnvelopeError, formatAge, globalConfigDir, isReachable, isStreamNotFound, mintCreds, mintLifecycleUid, resolveService, realDirNoSymlink, invokeRepairingSplit, standaloneConnectOpts, newIdentity, idFromCreds, principalKey, DEV_OWNER, unansweredRequest, resolveAuthProvider, personaDir, } from "@cotal-ai/core";
6
- import { stoppedLoopbackListener, UnreadableConnectorSelection, stackRunsUnderOtherHome, accountInventory, authDir, isCommandFailure, readMaintenanceJournal, recordsElsewhereError, recordsElsewhereText, restoreRolledBackRuns, targetErrorSpace, brokerAddressForDisplay, brokerCheck, brokerUrlKey, canonicalRoot, CLI_USER_ACTOR, codeSpan, credentialFileExposure, CommandFailure, deliveryCredsKey, DELIVERY_PIDFILE, extensionsDir, findCotalRoot, folderSpaceOverSelection, isGenuineSpace, meshesForRoot, resolveReadsLiveness, stoppedStack, unsettledStackOperation, withdrawOperationNote, hasUserAuthState, homeCotalDir, installationWriter, cachedPreferences, loadLaunchPersonaFile, resolvePreference, isMeshRegistryError, isWorkspaceTargetError, loadManagerInstanceIdentity, loadSoleSpaceAuth, localProcessPath, localProcessVisible, MANAGER_PIDFILE, NATS_PIDFILE, OFFICIAL_CONNECTORS, oneLine, PREFERENCE_KEYS, preflightTarget, preparedNeverStarted, presentationOf, principalFromBearer, verifyIdentityPin, probeWebReadiness, readCurrent, readMeshRegistry, readPidfile, preparedRecordSkipped, readPreparedSpaces, stackJournalPath, readRenewalRecord, recordOperationSpace, resolveMeshTarget, userAuthStateDir, WEB_PIDFILE, workspaceSecretStore, displayWidth, terminalWidth, wrapWords, writeResult, workspaceErrorParts, preferencesPath, preferencesFolderWarning, cotalDirLink, movedProject, spaceStreamsAbsent, spaceStreamsExpected, resolveControlTarget, } from "@cotal-ai/workspace";
3
+ import { CotalEndpoint, agentFilePath, globalConfigDir, isReachable, mintCreds, realDirNoSymlink, newIdentity, personaDir, } from "@cotal-ai/core";
4
+ import { UnreadableConnectorSelection, stackRunsUnderOtherHome, accountInventory, authDir, isCommandFailure, readMaintenanceJournal, recordsElsewhereError, restoreRolledBackRuns, brokerAddressForDisplay, brokerUrlKey, canonicalRoot, codeSpan, CommandFailure, DELIVERY_PIDFILE, extensionsDir, findCotalRoot, meshesForRoot, resolveReadsLiveness, unsettledStackOperation, withdrawOperationNote, hasUserAuthState, homeCotalDir, installationWriter, cachedPreferences, loadLaunchPersonaFile, resolvePreference, isWorkspaceTargetError, loadSoleSpaceAuth, localProcessPath, localProcessVisible, PREFERENCE_KEYS, preflightTarget, preparedNeverStarted, presentationOf, stackJournalPath, readRenewalRecord, recordOperationSpace, resolveMeshTarget, writeResult, preferencesPath, preferencesFolderWarning, cotalDirLink, } from "@cotal-ai/workspace";
7
5
  import { localProcessSurface } from "../ext-loader.js";
8
6
  import { cliVersion, cliProvenance, readExtensionVersions } from "../lib/version.js";
9
7
  import { agentSkillsSkew } from "../lib/agent-skills.js";
10
8
  import { managerHasDeliveryMarker } from "../lib/manager-proc.js";
11
- import { MANAGER_OMITTED } from "../lib/delivery-proc.js";
12
9
  import { signedInSpace } from "../lib/conversation-identity.js";
13
- import { connectorHarnesses, connectorStatusRows, machineStatus, recordedWebUrl, webBoundAddress, webInstalled, webSessionSource } from "../lib/status.js";
10
+ import { connectorHarnesses, connectorStatusRows, machineStatus, recordedWebUrl, webInstalled } from "../lib/status.js";
14
11
  import { legacyManagerStopped, statusRuntimeSpace } from "./status-legacy.js";
15
- import { deliveryResponderFromLease, deliveryResponderState, deliveryRowSuffix, RESPONDER_UNBOUND_CONSEQUENCE } from "../lib/delivery-responder.js";
16
- import { brokerStoreWrite, storeFull, storeWriteRepair } from "../lib/broker-store-health.js";
17
- import { chatStreamGone, stackState } from "../lib/space-streams.js";
12
+ import { deliveryResponderState, deliveryRowSuffix } from "../lib/delivery-responder.js";
13
+ import { brokerStoreWrite, storeFull } from "../lib/broker-store-health.js";
18
14
  import { pidfileState } from "./down.js";
19
- import { stoppedStackAddressProblem } from "./stack-up.js";
20
- import { legacyRestartAddressProblem } from "../lib/broker-service.js";
21
15
  import { selectResetTarget } from "./reset-store-apply.js";
22
- import { displayCmd, displayRemedy } from "../lib/self-exec.js";
16
+ import { displayCmd } from "../lib/self-exec.js";
23
17
  import { shellWord } from "../lib/endpoint-errors.js";
24
18
  import { readPersonas } from "../lib/personas.js";
25
- import { c } from "../ui.js";
26
- import { preparedCatalogDiagnostics } from "./sync.js";
27
19
  import { agentStatus } from "./agents.js";
28
20
  import { invalidEnvironmentValues } from "./config.js";
29
21
  import { canPrompt } from "./meshes-wizard.js";
30
- import { cliControl, onInstance, onRerun } from "../lib/control.js";
22
+ import { onInstance, onRerun } from "../lib/control.js";
31
23
  import { serviceDefinitionProjection, serviceDefinitionStore } from "../lib/service-definitions.js";
32
24
  import { instanceProjection, serviceInstances } from "../lib/service-instances.js";
33
25
  import { readinessAddressSurvivors } from "../lib/service-process.js";
34
26
  import { freshTeamAttemptSettled, listFreshTeamAttempts, listFreshTeamSummaries } from "../lib/team-fresh.js";
35
27
  import { additiveTeamRecordedState, listAdditiveTeamAttempts } from "../lib/team-additive-attempt.js";
36
- import { maintenanceNextStep, rolledBackNotes } from "../lib/restore.js";
37
- import { journalRecordedElsewhere, readStackJournal, serviceHeldRecords, STACK_ADAPTER, STACK_DEFINITION, stackStartedWithoutManager, stackOperationBlock, stackRootGone, unfinishedStackOperation, unusableStackJournal, } from "../lib/stack-journal.js";
38
- import { cotalLinkHere, homeHoldsStack, linkedCotalRemedy } from "../lib/paths.js";
39
- import { channelSeedRestartBlock } from "../lib/channel-seed.js";
28
+ import { maintenanceNextStep } from "../lib/restore.js";
29
+ import { journalRecordedElsewhere, readStackJournal, serviceHeldRecords, STACK_ADAPTER, STACK_DEFINITION, stackStartedWithoutManager, stackOperationBlock, unfinishedStackOperation, } from "../lib/stack-journal.js";
30
+ import { cotalLinkHere, linkedCotalRemedy } from "../lib/paths.js";
40
31
  import { rootStoreProblem } from "../lib/store-dir.js";
41
- import { stackStoreWarnings } from "../lib/store-identity.js";
42
- import { natsServerLabel } from "../lib/nats-bin.js";
43
- import { askManager } from "@cotal-ai/workspace/control";
44
32
  import { readCursor } from "../seed/lock.js";
45
33
  import { reconcileCursorPath } from "../seed/paths.js";
46
- import { managerStopImpactFacts } from "./status-stop-impact.js";
47
- import { responderText } from "./status-delivery.js";
48
- import { statusFlags, UnregisteredRoot, Gaps, displayStatusBroker, } from "./status-model.js";
34
+ import { statusFlags, UnregisteredRoot, Gaps, } from "./status-model.js";
35
+ import { servedStack, folderStack, backupRecovery, statusView } from "./status-render.js";
36
+ import { expectedDeliveryHolder, localManagerInstanceId, userManagerStatus, managerNoService, processRecord, componentCredential, staticServiceAuth, managerServiceHealth, printComponentHealth, } from "./status-health.js";
37
+ import { registryFallbackChecks, personaCatalog, readMeshes, readStackStoreWarnings, readSelected } from "./status-meshes.js";
38
+ export { managerNoService, deliveryLeaseAbsent } from "./status-health.js";
39
+ export { statusView } from "./status-render.js";
49
40
  export { statusFlags } from "./status-model.js";
50
41
  function resolveSelected(cwd, values, offline) {
51
42
  try {
@@ -76,21 +67,6 @@ async function folderSpacesOffline(cwd, values) {
76
67
  const probed = await Promise.all(entries.map(async (m) => ((await isReachable(m.server, m.tlsRequired ? { tls: true } : {})) ? undefined : m.space)));
77
68
  return probed.filter((space) => space !== undefined);
78
69
  }
79
- /** Outside a project, only the all-broker report has liveness evidence for the registry fallback. */
80
- async function registryFallbackChecks(root, values) {
81
- if (!values.all || values.space !== undefined || values.server !== undefined || isGenuineSpace(root))
82
- return undefined;
83
- let entries;
84
- try {
85
- if (readCurrent() !== undefined)
86
- return undefined;
87
- entries = readMeshRegistry().entries;
88
- }
89
- catch {
90
- return undefined;
91
- } // The reporting pass names unreadable records.
92
- return new Map(await Promise.all(entries.map(async (entry) => [entry.space, { entry, check: await brokerCheck(entry.server, entry.tlsRequired) }])));
93
- }
94
70
  /** Named-agent and infrastructure inputs choose different reads. */
95
71
  export function validateStatusArguments(args) {
96
72
  presentationOf(args.values);
@@ -194,9 +170,9 @@ export async function status(args) {
194
170
  const recovery = backupRecovery(maintenance, sourceMissing);
195
171
  const selectedHints = [];
196
172
  const target = await readSelected(selected, responder, folder, gaps, selectedHints, preflight, Boolean(values.all));
197
- // Do not offer the conditional store reset when this folder needs a channel seed repair first,
198
- // while a maintenance journal holds the store, or if the store is unwritable.
199
- if ((target.resolved || target.code !== "SCHEMA_INVALID") && folder.storedState && folder.processSpace !== null && maintenance === null && !(target.channelSeedBlocksRestart && target.root === root) && !rootStoreProblem(root)) {
173
+ const stoppedForeignListener = preflight?.ok === false && preflight.kind === "non-nats-listener" && preflight.pid !== undefined;
174
+ // Address, journal, channel seed, and store problems can block the conditional store reset.
175
+ if (!stoppedForeignListener && (target.resolved || target.code !== "SCHEMA_INVALID") && folder.storedState && folder.processSpace !== null && maintenance === null && !(target.channelSeedBlocksRestart && target.root === root) && !rootStoreProblem(root)) {
200
176
  const reset = storeResetTarget(root, folder.processSpace);
201
177
  // An explicit address is not evidence about a different broker's store.
202
178
  if (values.server === undefined || (reset && selected.ok && selected.target.space === reset.space
@@ -272,7 +248,7 @@ export async function status(args) {
272
248
  preparedHarness: !selected.ok && isWorkspaceTargetError(selected.error) && selected.error.code === "not-started" && preparedNeverStarted(selected.error.details)
273
249
  ? preferences.spaces[selected.error.details.space]?.harness : undefined,
274
250
  seed,
275
- recovery,
251
+ recovery, stoppedForeignListener,
276
252
  }));
277
253
  if (values.components)
278
254
  await printComponentHealth(selected, store, target.resolved && target.connection === "unreachable");
@@ -511,42 +487,6 @@ function readExtensions(gaps) {
511
487
  gaps.add("EXTENSIONS_UNREADABLE", `the extensions manifest could not be read: ${unreadable}`);
512
488
  return { root, items: unreadable === undefined ? versions.map((e) => ({ package: e.pkg, label: e.label, version: e.version })) : null };
513
489
  }
514
- /** The lease `holder` the delivery daemon THIS WORKSPACE launched would write, or `undefined` when it
515
- * cannot be known (#1576, and the reason is #837).
516
- *
517
- * THE HOLDER IS A PRINCIPAL DOT-FORM, NOT THE RAW CREDS ID, and getting that wrong is a live-caught
518
- * mistake rather than a hypothetical: the daemon builds its endpoint with
519
- * `card.id = idFromCreds(creds)`, and the endpoint then REWRITES `card.id` to
520
- * `principalKey(owner, actor).key` — `<owner>.<actor>` — which is what lands in the lease. Comparing
521
- * against the bare id therefore mismatches EVERY healthy daemon, which would turn this check into
522
- * the mirror of the bug it removes: a permanent false "stale" on a perfectly good mesh. A smoke cell
523
- * reads the record a real holder wrote and pins the exact shape, so this cannot regress silently.
524
- *
525
- * WHY IT MATTERS AT ALL. Without it, a `ready:true` record left by a daemon that has since died
526
- * reads as health for the rest of the bucket TTL — measured against a real broker, not theorised —
527
- * and a status command that exists to stop false green would print `responder bound` at a mesh that
528
- * cannot spawn, retire or join. Core demands a named holder in `waitForDeliveryLease` for exactly
529
- * this reason.
530
- *
531
- * READ-ONLY AND BEST EFFORT. A workspace that never launched a daemon locally (an adopted or remote
532
- * one) has no creds file, and that is not an error: the caller then does not check the holder, the
533
- * same concession `waitForDeliveryLease` makes for an adopted daemon. An existing credential that
534
- * cannot be read privately refuses the check rather than silently disabling holder attribution. */
535
- async function expectedDeliveryHolder(target) {
536
- const key = deliveryCredsKey(target.space, { injected: false, root: target.root });
537
- const path = join(target.root, ".cotal", key);
538
- const stat = lstatSync(path, { throwIfNoEntry: false });
539
- const exposure = stat?.isFile() ? credentialFileExposure(path, stat) : undefined;
540
- if (exposure)
541
- throw new CommandFailure("refused", "PERMISSION_DENIED", `${path}: ${exposure.reason}`, { remedy: exposure.remedy, target: { path, space: target.space } });
542
- const creds = await workspaceSecretStore(target.root).get(key);
543
- if (!creds)
544
- return undefined;
545
- // The daemon declares no owner/actor, so the endpoint falls back to DEV_OWNER for the owner and
546
- // to the connection id for the actor: `local.<idFromCreds>`. Built through `principalKey` rather
547
- // than string concatenation so this tracks the one definition of the dot-form.
548
- return principalKey(DEV_OWNER, idFromCreds(creds)).key;
549
- }
550
490
  /** Read the delivery responder axis for the bare-status rows (#1576).
551
491
  *
552
492
  * ONE SHORT-LIVED READ-ONLY CONNECTION, and it must never turn status into a command that fails.
@@ -864,28 +804,6 @@ function folderPersonas(root, selected, values, gaps, hints) {
864
804
  hints.push(`a bare \`${displayCmd()} spawn\` uses the selected mesh, NOT this folder - personas in ${personaDir(root)} will not launch until you run it from that mesh's root or select it (\`${displayCmd()} use <space>\`${values.space ? "" : ", or pass `--space`"})`);
865
805
  return { personas, launches: false };
866
806
  }
867
- /** Summarize the catalog through the shipped loader. A file is launchable only when
868
- * {@link readPersonas} parsed it with the same {@code loadAgentFile} path spawn uses. Only an absent
869
- * directory is an empty catalog: one that cannot be read is a gap, not `missing`. */
870
- function personaCatalog(root, gaps) {
871
- let personas;
872
- try {
873
- personas = readPersonas(root);
874
- }
875
- catch (e) {
876
- const error = e.message;
877
- gaps.add("PERSONAS_UNREADABLE", `the persona catalog ${personaDir(root)} could not be read: ${error}`, { root: personaDir(root) });
878
- return { root: personaDir(root), default: "unreadable", demo: null, error };
879
- }
880
- const byName = new Map(personas.map((persona) => [persona.name, persona]));
881
- const def = byName.get("default");
882
- return {
883
- root: personaDir(root),
884
- default: def?.def ? "valid" : def?.error ? "invalid" : "missing",
885
- demo: ["david", "sven", "me"].filter((name) => byName.get(name)?.def !== undefined).length,
886
- error: null,
887
- };
888
- }
889
807
  /** The one space whose `reset store <space>` selects this root's store: the folder's own, or one this
890
808
  * machine registered here, which a stopped folder no longer resolves to. A legacy root whose down
891
809
  * removed that registration has none, and the reset's refusal names clean instead. */
@@ -1007,41 +925,6 @@ async function managerProcess(target, state, space, gaps) {
1007
925
  return { name: "manager", state: "not-serving", pid: state.pid ?? null, detail: ["service endpoint not answering", ...details.filter((d) => d.startsWith("delivery-aware marker unreadable"))].join(" · ") };
1008
926
  return running(endpoint === "unchecked" ? "service unchecked" : undefined);
1009
927
  }
1010
- /** The instance id this workspace root persisted for `space`. That is the id the manager's
1011
- * own status reports. Absent when this root has never registered a manager. A malformed
1012
- * record is not an id: status must not invent one. */
1013
- function localManagerInstanceId(root, space) {
1014
- try {
1015
- const id = loadManagerInstanceIdentity(root, space)?.instanceId;
1016
- return typeof id === "string" && id.length > 0 ? id : undefined;
1017
- }
1018
- catch {
1019
- return undefined;
1020
- }
1021
- }
1022
- /** User-mode manager status goes through the same control call `cotal spawn` uses. `instanceId`
1023
- * pins that call to this machine's manager. Without it, the exchange may select another live
1024
- * manager of the same owner. */
1025
- async function userManagerStatus(target, instanceId) {
1026
- const control = await resolveControlTarget({ space: target.space, server: target.server }, "control-caller-privileged", instanceId, { onRefusal: "throw" });
1027
- const reply = await askManager(cliControl, control.space, control.server, "managerStatus", undefined, control.auth, "owner", 3_000);
1028
- if (reply.ok !== true) {
1029
- const message = "error" in reply && typeof reply.error === "string" ? reply.error : "manager status refused";
1030
- // `unavailable` stays a reachability failure, as the static probe does. Anything else, including
1031
- // a manager that answered and refused, is a precondition. The reply's details stay on the error:
1032
- // a real no-answer carries the unanswered marker, and dropping it would report silence as a refusal.
1033
- const code = reply.code === "unavailable" ? "unavailable" : "failed-precondition";
1034
- throw new EpEnvelopeError(code, message, reply.details);
1035
- }
1036
- if (reply.data === undefined)
1037
- throw new EpEnvelopeError("unavailable", "the manager status reply carried no data");
1038
- return reply.data;
1039
- }
1040
- /** A no-responder service rail or an absent manager registry: the definitive no-service evidence
1041
- * that both the manager row and the manager health check grade on, kept in one place (#3046). */
1042
- export function managerNoService(e) {
1043
- return e instanceof EpEnvelopeError && (unansweredRequest(e) || isStreamNotFound(e.cause));
1044
- }
1045
928
  /** One probe of the space's manager service endpoint. Only a definitive no-answer is
1046
929
  * `not-answering`; a refused probe or an `unavailable` user-mode credential is `unchecked`, so a
1047
930
  * failed probe never reads as a dead rail. The operator's credential calls the class rail, so with
@@ -1087,1744 +970,4 @@ async function readStackManager(target, services) {
1087
970
  function deliveryDetail(live, responder) {
1088
971
  return deliveryRowSuffix(live, responder, `${displayCmd()} status --components`).replace(/^ · /, "") || null;
1089
972
  }
1090
- /** The recorded meshes. Only the selected one is checked, and only when the command dials its
1091
- * recorded address, unless `--all` asks for every one; each check dials that record's own address
1092
- * with its own recorded TLS requirement. A bare TCP/INFO probe would green-light a plaintext broker
1093
- * that has substituted for a TLS-required mesh — the FAIL1 attack — so a list that only asks "is
1094
- * anything listening" cannot report on the one property the record claims. */
1095
- async function readMeshes(cwd, selected, all, gaps, offline, preflight, checks) {
1096
- // A registry file that cannot be read is named, and the readable records are still listed and
1097
- // checked. Only an absent directory or pointer is an empty registry or no current mesh.
1098
- const unreadable = [];
1099
- const unread = (file, error) => {
1100
- unreadable.push({ file, error });
1101
- gaps.add("MESH_REGISTRY_UNREADABLE", error, { file });
1102
- };
1103
- let entries = [];
1104
- try {
1105
- const registry = readMeshRegistry();
1106
- entries = registry.entries;
1107
- for (const e of registry.unusable)
1108
- unread(e.file, e.message);
1109
- }
1110
- catch (e) {
1111
- if (!isMeshRegistryError(e))
1112
- throw e;
1113
- unread(e.file, e.message);
1114
- }
1115
- let current = null;
1116
- try {
1117
- current = readCurrent() ?? null;
1118
- }
1119
- catch (e) {
1120
- if (!isMeshRegistryError(e))
1121
- throw e;
1122
- unread(e.file, e.message);
1123
- }
1124
- // A record this needs that cannot be read is already named above.
1125
- let folder = null;
1126
- // A folder space whose broker did not answer is not the target, so it is not this folder's here.
1127
- try {
1128
- folder = folderSpaceOverSelection(cwd, current, offline) ?? null;
1129
- }
1130
- catch (e) {
1131
- if (!isMeshRegistryError(e))
1132
- throw e;
1133
- }
1134
- const chosen = selected.ok ? selected.target : undefined;
1135
- const chosenServer = chosen && brokerUrlKey(chosen.server);
1136
- // A `--server` that names another address is the only broker dialed for the selected space.
1137
- const check = async (m) => {
1138
- const selectedAddress = m.space === chosen?.space && brokerUrlKey(m.server) === chosenServer;
1139
- if (!all && !selectedAddress)
1140
- return "not-checked";
1141
- if (preflight && selectedAddress) {
1142
- if (preflight.ok)
1143
- return "reachable";
1144
- if (preflight.kind === "slow-link" || preflight.kind === "broker-stopped" || preflight.kind === "unreachable")
1145
- return preflight.kind;
1146
- return preflight.kind === "tls-trust" || preflight.kind === "tls-unsupported" || preflight.kind === "auth-unsupported" || preflight.kind === "jetstream-unsupported" || preflight.kind === "non-nats-listener" ? "unreachable" : "reachable";
1147
- }
1148
- const prior = checks?.get(m.space);
1149
- if (prior?.entry.server === m.server && prior.entry.tlsRequired === m.tlsRequired)
1150
- return prior.check;
1151
- return brokerCheck(m.server, m.tlsRequired);
1152
- };
1153
- const items = await Promise.all(entries.map(async (m) => ({
1154
- space: m.space,
1155
- server: displayStatusBroker(m.server, m.space, gaps),
1156
- mode: m.mode,
1157
- root: m.root,
1158
- origin: m.origin ?? null,
1159
- tlsRequired: Boolean(m.tlsRequired),
1160
- eventsRequired: m.policy?.events === "required",
1161
- modeChecked: m.unchecked !== true,
1162
- current: m.space === current,
1163
- check: await check(m),
1164
- catalog: m.origin === "catalog" ? { name: m.catalogName && m.catalogName !== m.space ? m.catalogName : null, fetchedAt: m.catalogFetchedAt ?? null, error: m.catalogError ?? null } : null,
1165
- })));
1166
- // The prepared spaces folder, or a record in it, that cannot be read is named the same way.
1167
- let currentPrepared = false, currentStopped = false, hasPrepared = false;
1168
- try {
1169
- const prepared = readPreparedSpaces();
1170
- hasPrepared = prepared.spaces.length > 0;
1171
- // Named with the warning a command that skips it gives, so a run that also skipped it says it once.
1172
- for (const e of prepared.unusable) {
1173
- const skipped = preparedRecordSkipped(e);
1174
- unreadable.push({ file: e.file, error: e.message });
1175
- gaps.add(skipped.code, skipped.message, skipped.target);
1176
- }
1177
- const selected = current !== null && !entries.some((m) => m.space === current) ? prepared.spaces.find((p) => p.space === current) : undefined;
1178
- currentPrepared = selected !== undefined;
1179
- currentStopped = selected !== undefined && stoppedStack(selected.root, selected.space) !== undefined && unsettledStackOperation(selected.root, selected.space) === undefined;
1180
- }
1181
- catch (e) {
1182
- if (!isMeshRegistryError(e))
1183
- throw e;
1184
- unread(e.file, e.message);
1185
- }
1186
- return {
1187
- current,
1188
- currentRecorded: current === null || entries.some((m) => m.space === current),
1189
- currentPrepared,
1190
- hasPrepared,
1191
- currentStopped,
1192
- folder,
1193
- unreadable,
1194
- items,
1195
- catalogs: preparedCatalogDiagnostics().map((r) => ({ idp: r.account.idpUrl, account: r.account.sub, state: r.state, error: r.state === "failed" ? (r.error ?? "refresh failed") : null })),
1196
- };
1197
- }
1198
- /** Diagnose the current folder's store and a selected local stack independently of folder trust. */
1199
- function readStackStoreWarnings(root, gaps, hints, space) {
1200
- try {
1201
- const journal = readStackJournal(root)?.journal;
1202
- if (journal && (space === undefined || journal.space === space))
1203
- for (const warning of stackStoreWarnings(journal))
1204
- gaps.add(warning.code, warning.message, warning.target);
1205
- }
1206
- catch (error) {
1207
- if (isCommandFailure(error) && (error.code === "SCHEMA_INVALID" || error.code === "PERMISSION_DENIED")) {
1208
- gaps.add(error.code === "PERMISSION_DENIED" ? "STACK_JOURNAL_UNREADABLE" : "STACK_JOURNAL_INVALID", error.remedy ? `${error.message}; ${error.remedy}` : error.message, { root });
1209
- if (error.remedy)
1210
- hints.push(error.remedy);
1211
- }
1212
- else if (!isCommandFailure(error) || error.code !== "CONFLICT")
1213
- throw error;
1214
- // A copied or moved journal is diagnosed by the folder and selection readers.
1215
- }
1216
- }
1217
- /** The refusal of `space`'s service instance records when one is a record no command can use, as
1218
- * `up` and `down` refuse it. Undefined when they read. */
1219
- function unusableServiceInstances(space) {
1220
- try {
1221
- serviceInstances(space);
1222
- return undefined;
1223
- }
1224
- catch (error) {
1225
- return isCommandFailure(error) && error.code === "SCHEMA_INVALID" ? error : undefined;
1226
- }
1227
- }
1228
- async function readSelected(selected, responder, folder, gaps, hints, preflight, all) {
1229
- const cmd = displayCmd();
1230
- if (!selected.ok) {
1231
- const e = selected.error;
1232
- if (isCommandFailure(e) && e.code === "SCHEMA_INVALID") {
1233
- gaps.add(e.code, e.message, e.target);
1234
- if (e.remedy)
1235
- hints.push(e.remedy);
1236
- return { resolved: false, code: e.code, message: e.message };
1237
- }
1238
- // Resolution reads the whole registry and refuses a directory or record it cannot use. The meshes
1239
- // reader has already named it, so this is the same gap, and the selection is unresolved.
1240
- if (isMeshRegistryError(e)) {
1241
- gaps.add("MESH_REGISTRY_UNREADABLE", e.message, { file: e.file });
1242
- hints.push(e.message);
1243
- return { resolved: false, code: "registry-unreadable", message: e.message };
1244
- }
1245
- // `up` and `down` refuse a root whose `.cotal` is a link, so the step that would start it there is
1246
- // the one their refusal names.
1247
- const unstarted = e instanceof UnregisteredRoot ? e.root : isWorkspaceTargetError(e) && (e.code === "not-started" || e.code === "no-meshes") ? e.details.root : undefined;
1248
- const link = unstarted === undefined ? undefined : cotalDirLink(unstarted);
1249
- if (unstarted !== undefined && link !== undefined) {
1250
- hints.push(linkedCotalRemedy(unstarted, link));
1251
- return { resolved: false, code: e instanceof UnregisteredRoot ? "unregistered-root" : "not-started", message: `${join(unstarted, ".cotal")} is a link to ${link}, and a stack runs only from a folder whose .cotal is its own directory, so \`${cmd} up\` and \`${cmd} down\` refuse it there` };
1252
- }
1253
- if (e instanceof UnregisteredRoot) {
1254
- const message = `no space is registered or prepared here for ${e.root}`;
1255
- hints.push(`run \`${cmd} up\` in ${e.root} to start one, or select a space with \`${cmd} use <name>\``);
1256
- return { resolved: false, code: "unregistered-root", message };
1257
- }
1258
- if (!isWorkspaceTargetError(e))
1259
- throw e;
1260
- if (!all && e.code === "ambiguous-target" && e.details.server === undefined && e.details.spaces && !isGenuineSpace(folder.root)) {
1261
- hints.push(`check the registered spaces with \`${cmd} status --all\``);
1262
- return { resolved: false, code: e.code, message: `multiple spaces are registered but unchecked: ${(e.details.available ?? []).join(", ")}` };
1263
- }
1264
- // The section states the selection, and Next gives the repair for the specific refusal.
1265
- const { message, remedy, restartRoot } = workspaceErrorParts({ kind: "target", error: e });
1266
- const d = e.details;
1267
- // A copy or a moved folder is reported under the space its records name, as the commands run here
1268
- // refuse under it, and says what the folder holds; Next gives the step they name.
1269
- const elsewhere = e.code === "not-started" ? recordsElsewhereText(d) : undefined;
1270
- const held = e.code === "not-started" && d.stopped && !d.unsettled && d.root && d.space ? await stoppedStackAddressProblem(d.root, d.space) : undefined;
1271
- const result = {
1272
- resolved: false, code: e.code, message: elsewhere ?? (held ? `${message}; ${held.message}` : message),
1273
- ...(e.code === "not-started" && d.space !== undefined && d.root !== undefined && !d.rootMissing ? { space: d.space, root: d.root } : {}),
1274
- ...(elsewhere !== undefined ? { space: targetErrorSpace(d), recordedRoot: d.recordedRoot } : {}),
1275
- };
1276
- // An unwritable store blocks a restart from this root.
1277
- const store = e.code === "not-started" && d.root !== undefined && !d.rootMissing ? rootStoreProblem(d.root) : undefined;
1278
- const journal = e.code === "not-started" && d.root !== undefined && !d.rootMissing ? unusableStackJournal(d.root) : undefined;
1279
- // So does a service instance record of its space that no command can read, which is also a warning.
1280
- const instances = e.code === "not-started" && !journal && d.space !== undefined ? unusableServiceInstances(d.space) : undefined;
1281
- if (instances)
1282
- gaps.add("SERVICE_INSTANCES_UNAVAILABLE", instances.remedy ? `${instances.message}; ${instances.remedy}` : instances.message, { space: d.space, ...instances.target });
1283
- // This folder's stack cut off with no recorded outcome is named under the selected space, and
1284
- // Next names the step that finishes or settles it. One that neither blocks nor stays part way
1285
- // settles from its members' processes when it starts.
1286
- if (journal) {
1287
- const step = journal.remedy ?? journal.message;
1288
- if (!hints.includes(step))
1289
- hints.push(step);
1290
- }
1291
- else if (instances)
1292
- hints.push(instances.remedy ?? instances.message);
1293
- else if (store)
1294
- hints.push(`${store.message}; ${store.remedy}`);
1295
- else if (restartRoot !== undefined) {
1296
- const block = channelSeedRestartBlock(restartRoot);
1297
- if (block) {
1298
- Object.assign(result, { channelSeedBlocksRestart: true, root: restartRoot });
1299
- hints.push(`Restart blocked: ${block.message}. ${block.remedy}`);
1300
- }
1301
- else {
1302
- const legacy = d.lastRun ? await legacyRestartAddressProblem(d.server, `${cmd} up`) : undefined;
1303
- if (legacy)
1304
- result.message += `; ${legacy.message}`;
1305
- hints.push(legacy?.remedy ?? held?.remedy ?? (remedy === undefined ? message : displayRemedy(remedy, cmd)));
1306
- }
1307
- }
1308
- else if (!d.unsettled || !servedStack(folder, result)) {
1309
- hints.push(held?.remedy ?? (remedy === undefined ? message : displayRemedy(remedy, cmd)));
1310
- }
1311
- else if (!folder.stackBlock && !folder.stackUnfinished)
1312
- hints.push(`start it with ${codeSpan(`${cmd} up`)} in ${d.root}`);
1313
- return result;
1314
- }
1315
- const target = selected.target;
1316
- const base = {
1317
- resolved: true,
1318
- space: target.space,
1319
- server: displayStatusBroker(target.server, target.space, gaps),
1320
- mode: target.mode,
1321
- source: target.source,
1322
- root: target.root,
1323
- rootGone: stackRootGone(target.space, target.root),
1324
- tlsRequired: Boolean(target.tlsRequired),
1325
- eventsRequired: target.policy?.events === "required",
1326
- idp: target.userAuth?.idp.url ?? null,
1327
- personas: personaCatalog(target.root, gaps),
1328
- staleRecord: false,
1329
- login: null,
1330
- deliveryResponder: null,
1331
- channels: null,
1332
- membershipFeed: null,
1333
- spaceStreams: { state: "not-checked", root: null, stack: null },
1334
- storedBytes: null,
1335
- };
1336
- // A moved project keeps its trust under its new path. Prefer that specific diagnosis when
1337
- // this folder holds the records, otherwise report the missing stack root before any auth probe.
1338
- const moved = target.mode === "auth" && !target.auth ? movedProject(target.space, target.root) : undefined;
1339
- if (moved) {
1340
- hints.push(moved.remedy);
1341
- return { resolved: false, code: "moved-folder", message: moved.message };
1342
- }
1343
- const overridden = (target.source === "flag-server" || target.source === "flag-space-override") &&
1344
- (target.recordedServer === undefined || brokerUrlKey(target.recordedServer) !== brokerUrlKey(target.server));
1345
- if (base.rootGone && !overridden)
1346
- return { ...base, connection: "root-gone", snapshot: { state: "skipped", reason: "the stack's project folder was moved or deleted" } };
1347
- if (target.mode === "user") {
1348
- // Status never static-mints on a user-auth mesh (the flip). Everything here is offline
1349
- // introspection — the login cache + the locally-readable ledger — plus, only when this
1350
- // machine holds a signed-in AND granted login, a real user-mode connect for the snapshot.
1351
- // Same transport discipline as the open/auth path below: a recorded TLS requirement must
1352
- // not collapse to a bare reachability probe (that green-lights a plaintext substitute).
1353
- const live = await isReachable(target.server, target.tlsRequired ? { tls: true } : {});
1354
- const stateDir = userAuthStateDir(target.root, target.space);
1355
- let st;
1356
- try {
1357
- st = await resolveAuthProvider().userStatus({ store: workspaceSecretStore(target.root), dir: stateDir, space: target.space, actor: CLI_USER_ACTOR });
1358
- }
1359
- catch (e) {
1360
- gaps.add("LOGIN_UNREADABLE", `the login for ${target.space} could not be read: ${e.message}`, { space: target.space });
1361
- }
1362
- const login = st
1363
- ? {
1364
- idp: st.idpUrl,
1365
- subject: st.login?.sub ?? null,
1366
- expiresAt: st.login ? new Date(st.login.expiresAt * 1000).toISOString() : null,
1367
- actor: !st.login ? null : st.grant === "not-granted" ? "not-granted" : st.grant ? "granted" : "not-checkable",
1368
- grant: st.login && st.grant && st.grant !== "not-granted" ? { label: st.grant.label ?? null, read: [...st.grant.allowSubscribe], post: [...st.grant.allowPublish], scope: [...st.grant.scope] } : null,
1369
- }
1370
- : null;
1371
- const granted = Boolean(st?.login && st.grant && st.grant !== "not-granted");
1372
- const result = { ...base, connection: live ? "reachable" : "unreachable", login };
1373
- if (!live)
1374
- return { ...result, snapshot: { state: "skipped", reason: "broker unreachable" } };
1375
- if (!granted)
1376
- return { ...result, snapshot: { state: "skipped", reason: "needs a signed-in, granted login" } };
1377
- return { ...result, ...(await readSnapshot(() => userSnapshotEndpoint(target, stateDir), target.space, true, gaps)) };
1378
- }
1379
- if (preflight === undefined)
1380
- throw new Error("status: selected non-user target has no preflight observation");
1381
- if (!preflight.ok) {
1382
- // A `--server` address that is not the one recorded for the space says nothing about whether its
1383
- // stack runs, so Next names that address as the refusal of other commands does. A stopped stack
1384
- // this machine started keeps its registration, as a connect keeps it, so Next names the `up` that
1385
- // starts it again rather than a registration to repair.
1386
- const offline = preflight.kind === "unreachable" && !overridden && target.origin === "up";
1387
- const store = offline ? rootStoreProblem(target.root) : undefined;
1388
- let seedBlock;
1389
- // A blocked stack refuses that `up`, and Next names the step that clears the block instead.
1390
- if (preflight.kind === "unreachable" && (overridden || offline || target.origin === "manual") && !(servedStack(folder, base) && folder.stackBlock)) {
1391
- const { message, remedy, restartRoot } = workspaceErrorParts({ kind: "preflight", failure: "unreachable", target, pruned: !offline && preflight.prune });
1392
- seedBlock = store || restartRoot === undefined ? undefined : channelSeedRestartBlock(restartRoot);
1393
- if (store)
1394
- hints.push(`${store.message}; ${store.remedy}`);
1395
- else if (seedBlock)
1396
- hints.push(`${message}. Restart blocked: ${seedBlock.message}. ${seedBlock.remedy}`);
1397
- else
1398
- hints.push(remedy === undefined ? message : `${message}; ${displayRemedy(remedy, cmd)}`);
1399
- }
1400
- if (preflight.kind === "non-nats-listener" || preflight.kind === "auth-unsupported" || preflight.kind === "jetstream-unsupported") {
1401
- const { message, remedy } = workspaceErrorParts({ kind: "preflight", failure: preflight.kind, target, pruned: false });
1402
- hints.push(remedy === undefined ? message : `${message}; ${displayRemedy(remedy, cmd)}`);
1403
- }
1404
- return { ...base, connection: preflight.kind, ...(seedBlock ? { channelSeedBlocksRestart: true } : {}), ...(preflight.pid === undefined ? {} : { brokerPid: preflight.pid }), staleRecord: preflight.prune && !offline, snapshot: { state: "skipped", reason: "broker not connected" } };
1405
- }
1406
- // The mesh-level statement of the same axis (#1576). The folder section says what this machine's
1407
- // delivery PROCESS is doing; this says whether the SPACE currently has a bound responder, which is
1408
- // the question "can I spawn into this mesh right now" actually reduces to. An operator reading a
1409
- // reachable broker and a running daemon had, before this, no row that said otherwise.
1410
- return { ...base, connection: "ok", deliveryResponder: target.mode === "open" && !responder.leased ? null : responder.state, ...(await readSnapshot(() => snapshotEndpoint(target), target.space, spaceStreamsExpected(target.space, target.mode), gaps)) };
1411
- }
1412
- async function snapshotEndpoint(target) {
1413
- const id = newIdentity();
1414
- const creds = target.auth ? await mintCreds(target.auth, id, "observer") : undefined;
1415
- return new CotalEndpoint({
1416
- space: target.space,
1417
- servers: target.server,
1418
- // The recorded requirement, for the same reason as the preflight probe: a monitoring command
1419
- // that connects to whatever answers on the address cannot report on the one property this
1420
- // feature provides, and reporting "ok" against a substituted plaintext broker is worse than
1421
- // reporting nothing.
1422
- tls: target.tlsRequired,
1423
- creds,
1424
- channels: [],
1425
- consume: false,
1426
- registerPresence: false,
1427
- // In open mode the endpoint lazily creates KV buckets for watches. Keep status read-only.
1428
- watchPresence: false,
1429
- watchChannels: Boolean(target.auth),
1430
- card: { id: id.id, name: "status", kind: "endpoint" },
1431
- });
1432
- }
1433
- /** The user-auth snapshot endpoint, connected as THIS machine's signed-in, ledger-granted login
1434
- * (bearer + sentinel — the flip forbids a status mint). */
1435
- async function userSnapshotEndpoint(target, stateDir) {
1436
- const { bearer, sentinelCreds } = await resolveAuthProvider().userCredentials({
1437
- store: workspaceSecretStore(target.root),
1438
- dir: stateDir,
1439
- space: target.space,
1440
- actor: CLI_USER_ACTOR,
1441
- });
1442
- return new CotalEndpoint({
1443
- space: target.space,
1444
- servers: target.server,
1445
- // Same reason as the static path: the recorded requirement is the primary fence against a
1446
- // forged INFO, and a monitoring snapshot that auto-upgrades cannot report on it.
1447
- tls: target.tlsRequired,
1448
- bearer,
1449
- sentinelCreds,
1450
- channels: [],
1451
- consume: false,
1452
- registerPresence: false,
1453
- watchPresence: false,
1454
- watchChannels: true,
1455
- card: { name: "status", kind: "endpoint" }, // card.id derives from the bearer principal
1456
- });
1457
- }
1458
- /** The absent streams of `space`, with this machine's stack of it. */
1459
- function absentStreams(space) {
1460
- const local = stackState(space);
1461
- return { state: "absent", root: local?.root ?? null, stack: local?.stack ?? null };
1462
- }
1463
- /** The selected space's channels and membership feed, read over one short-lived connection, and
1464
- * where `streams` says `cotal up` created them, whether its streams are still on the broker. The
1465
- * roster is not part of status: who is present is a separate read. */
1466
- async function readSnapshot(endpoint, space, streams, gaps) {
1467
- let ep;
1468
- try {
1469
- ep = await endpoint();
1470
- ep.on("error", () => { });
1471
- // This endpoint is a one-shot read. Awaited reads and their per-row unavailable results own the
1472
- // verdict, so a recoverable side channel is deliberately quiet rather than duplicated.
1473
- const ignoreSnapshotWarning = () => { };
1474
- ep.on("warning", ignoreSnapshotWarning);
1475
- await ep.start();
1476
- }
1477
- catch (e) {
1478
- gaps.add("SNAPSHOT_UNAVAILABLE", `the channels of ${space} could not be read: ${e.message}`, { space });
1479
- return { snapshot: { state: "unavailable", reason: e.message }, channels: null, membershipFeed: null, spaceStreams: { state: "not-checked", root: null, stack: null }, storedBytes: null };
1480
- }
1481
- try {
1482
- const channels = await ep.listChannels();
1483
- const feed = await ep.readMembership().catch(() => undefined);
1484
- const gone = streams && await chatStreamGone(ep);
1485
- const storedBytes = await ep.storedBytes().catch(() => null);
1486
- return {
1487
- snapshot: { state: "read", reason: null },
1488
- channels: channels.map((ch) => ({ channel: ch.channel, messages: ch.messages })),
1489
- membershipFeed: feed ? { entries: feed.members.length, asOf: feed.asOf ? new Date(feed.asOf).toISOString() : null } : null,
1490
- spaceStreams: !streams ? { state: "not-checked", root: null, stack: null } : gone ? absentStreams(space) : { state: "present", root: null, stack: null },
1491
- storedBytes,
1492
- };
1493
- }
1494
- catch (e) {
1495
- gaps.add("SNAPSHOT_UNAVAILABLE", `the channels of ${space} could not be read: ${e.message}`, { space });
1496
- return { snapshot: { state: "unavailable", reason: e.message }, channels: null, membershipFeed: null, spaceStreams: { state: "not-checked", root: null, stack: null }, storedBytes: null };
1497
- }
1498
- finally {
1499
- await ep.stop().catch(() => { });
1500
- }
1501
- }
1502
- // ---- the report ------------------------------------------------------------------------------
1503
- const cell = (text, tone) => (tone ? { text, tone } : text);
1504
- function personaText(p) {
1505
- if (p.default === "unreadable")
1506
- return `unreadable: ${p.error}`;
1507
- const parts = [p.default === "valid" ? "default" : p.default === "invalid" ? "invalid default" : "no default"];
1508
- if (p.demo)
1509
- parts.push(`demo team ${p.demo}/3`);
1510
- return parts.join(" · ");
1511
- }
1512
- function personaTone(p) {
1513
- return p.default === "valid" ? "ok" : p.default === "invalid" || p.default === "unreadable" ? "failed" : "hint";
1514
- }
1515
- /** A catalog's summary and root. Green only for a `default` that loads, and never for a catalog
1516
- * `dim` marks as not the one spawn launches from. */
1517
- function personaCell(p, dim = false) {
1518
- const tone = dim ? "hint" : personaTone(p);
1519
- return cell(`${personaText(p)} · ${p.root}`, tone);
1520
- }
1521
- function processCell(p) {
1522
- const detail = p.detail ? ` · ${p.detail}` : "";
1523
- if (p.state === "unreadable" || p.state === "unknown")
1524
- return cell(p.detail ?? "process state unknown", "failed");
1525
- if (p.state === "not-serving")
1526
- return cell(`not serving (pid ${p.pid})${detail}`, "failed");
1527
- if (p.state === "running")
1528
- return cell(`running (pid ${p.pid})${detail}`, /NOT BOUND|unreadable/.test(detail) ? "failed" : "ok");
1529
- return cell(p.pid ? `${p.detail ?? "stopped"} (${p.pid})` : (p.detail ?? "down"), "hint");
1530
- }
1531
- function skillsCell(s) {
1532
- const remedy = `${displayCmd()} setup --skills`;
1533
- if (s.state === "unreadable")
1534
- return cell(`bundle error: ${s.error}`, "failed");
1535
- if (s.state === "current")
1536
- return cell(`current (${s.total})`, "ok");
1537
- if (s.state === "not-installed")
1538
- return cell(`not installed · ${remedy}`, "hint");
1539
- return cell(`${s.retired ? `${s.behind} to reconcile (${s.retired} retired)` : `${s.behind}/${s.total} out of date`} · ${remedy}`, "waiting");
1540
- }
1541
- /** The nats-server a broker start would run, or why it refuses the one it found. */
1542
- function brokerExecutable(m) {
1543
- if (m.natsProblem)
1544
- return m.natsProblem;
1545
- return natsServerLabel({ ...m.natsServer, source: m.nats === "path" ? "path" : "bundled" });
1546
- }
1547
- function machineSection(m) {
1548
- const tone = { ok: "ok", warn: "waiting", error: "failed", off: "hint" };
1549
- const rows = [
1550
- ["cotal-ai", cell(`v${m.version} (${m.install.kind === "source" ? "source checkout" : m.install.kind}: ${m.install.root}${m.install.note ? ` · ${m.install.note}` : ""})`, "ok")],
1551
- ["NATS", m.nats === "missing" ? cell("missing", "failed") : cell(brokerExecutable(m), m.natsProblem ? "failed" : "ok")],
1552
- ...m.integrations.map((r) => [r.name, cell(r.text, tone[r.state])]),
1553
- ];
1554
- if (m.connectors === null)
1555
- rows.push(["Connectors", cell("unreadable - see the warning below", "failed")]);
1556
- else if (!m.connectors.length)
1557
- rows.push(["Connectors", cell(`none installed · \`${displayCmd()} setup\``, "hint")]);
1558
- for (const h of m.connectors ?? [])
1559
- rows.push([h.name, h.missing.length ? cell(`${h.missing.join(", ")} not on PATH`, "hint") : cell(h.requires.length ? `${h.requires.join(", ")} on PATH` : "in-process", "ok")]);
1560
- rows.push(["Skills (.agents)", skillsCell(m.skills)]);
1561
- rows.push(["Web extension", m.web.installed === null ? cell(m.web.installedError ?? "unreadable", "failed") : m.web.installed ? cell("installed", "ok") : cell("not installed", "hint")]);
1562
- // An install state that could not be read reads `down`, since only a known absence is `not installed`.
1563
- rows.push(["Web process", m.web.url ? cell(m.web.url, "ok") : m.web.urlError ? cell(m.web.urlError, "failed") : cell(m.web.installed === false ? "not installed" : "down", "hint")]);
1564
- return { title: "Machine", blocks: [{ kind: "fields", rows }] };
1565
- }
1566
- function extensionsSection(e) {
1567
- const rows = [["root", e.root]];
1568
- if (e.items === null)
1569
- rows.push(["installed", cell("manifest unreadable - see the warning below", "failed")]);
1570
- else if (!e.items.length)
1571
- rows.push(["installed", cell("none", "hint")]);
1572
- for (const x of e.items ?? [])
1573
- rows.push([x.label, cell(`v${x.version}${x.package === x.label ? "" : ` · ${x.package}`}`, "ok")]);
1574
- return { title: "Extensions", blocks: [{ kind: "fields", rows }] };
1575
- }
1576
- function folderSection(f, selected) {
1577
- const rows = [["root", f.root]];
1578
- const cwd = canonicalRoot(process.cwd());
1579
- if (cwd !== canonicalRoot(f.root) && (canonicalRoot(f.root) === canonicalRoot(homedir()) || canonicalRoot(join(f.root, ".cotal")) === canonicalRoot(homeCotalDir())))
1580
- rows.push(["root selection", homeHoldsStack(f.root)
1581
- ? cell("inherited the machine's home .cotal, which holds a stack; commands here reach that stack until up here makes this folder its own project root", "hint")
1582
- : cell("inherited the machine's home .cotal; up here makes this folder its own project root", "hint")]);
1583
- const auth = f.auth;
1584
- if (auth.state === "unreadable")
1585
- rows.push(["auth", cell(auth.error ?? "unreadable", "failed")]);
1586
- else if (auth.state === "spaces")
1587
- rows.push(["auth", cell(`${auth.spaces.length} spaces · ${auth.spaces.join(", ")}`, "ok")]);
1588
- else if (auth.state === "space")
1589
- rows.push(["auth", cell(`space ${auth.spaces[0]}${auth.userAuth ? " · user-auth" : ""}`, "ok")]);
1590
- else
1591
- rows.push(["auth", cell("none (open/local only)", "hint")]);
1592
- if (f.launches === null) {
1593
- rows.push(["personas", personaCell(f.personas)]);
1594
- rows.push(["spawn root", cell("unresolved - see Selected Mesh below; until it resolves, no persona here is launchable", "waiting")]);
1595
- }
1596
- else if (f.launches)
1597
- rows.push(["personas", personaCell(f.personas)]);
1598
- else {
1599
- // The divergence. The folder's catalog is real and worth reporting, but it is NOT the spawn
1600
- // catalog, so its `default` must not be green: green here is the false capability claim.
1601
- rows.push(["personas", personaCell(f.personas, true)]);
1602
- if (selected.resolved) {
1603
- rows.push(["spawn root", cell(`differs · ${selected.personas.root}`, "waiting")]);
1604
- rows.push(["→ launches", cell(`${personaText(selected.personas)} · space ${selected.space} · via ${selected.source}`, personaTone(selected.personas))]);
1605
- }
1606
- }
1607
- if (auth.state === "spaces")
1608
- rows.push(["processes", cell("not reported per space on a multi-space root", "hint")]);
1609
- for (const p of f.processes ?? [])
1610
- rows.push([p.name, processCell(p)]);
1611
- if (f.storedState)
1612
- rows.push(["stored state", cell("JetStream store persists across down/up", "hint")]);
1613
- return { title: "This Folder", blocks: [{ kind: "fields", rows }] };
1614
- }
1615
- function meshesSections(m) {
1616
- const check = { reachable: cell("reachable", "ok"), unreachable: cell("down", "failed"), "slow-link": cell("not answering", "failed"), "broker-stopped": cell("broker process is stopped", "failed"), "not-checked": cell("not checked", "hint") };
1617
- const blocks = [];
1618
- if (!m.items.length && !m.unreadable.length)
1619
- blocks.push({ kind: "lines", lines: [cell("none", "hint")] });
1620
- else
1621
- blocks.push({
1622
- kind: "table",
1623
- columns: [
1624
- { key: "space", label: "SPACE" },
1625
- { key: "check", label: "CHECK" },
1626
- { key: "mode", label: "MODE" },
1627
- { key: "server", label: "SERVER" },
1628
- { key: "root", label: "ROOT" },
1629
- { key: "note", label: "NOTE" },
1630
- ],
1631
- rows: m.items.map((x) => ({
1632
- space: x.current ? cell(`* ${x.space}`, "selected") : ` ${x.space}`,
1633
- check: check[x.check],
1634
- mode: x.mode,
1635
- server: x.server ?? cell("unavailable", "failed"),
1636
- root: x.root,
1637
- // A `down` record means two different things, and the repair differs: a mesh this machine
1638
- // started can be re-`up`ed here, one registered by hand runs somewhere this machine doesn't
1639
- // control (and, unlike the others, its record is never swept away for it).
1640
- note: [
1641
- x.origin === "manual" ? "registered" : x.origin === "catalog" ? "discovered" : "",
1642
- x.tlsRequired ? "tls-required" : "",
1643
- x.eventsRequired ? "events: required" : "",
1644
- x.catalog ? `${x.catalog.name ? `${x.catalog.name} ` : ""}catalog ${x.catalog.error ? `stale since ${x.catalog.fetchedAt ?? "unknown"}: ${x.catalog.error}` : `snapshot ${x.catalog.fetchedAt ?? "unknown"}`}` : "",
1645
- ].filter(Boolean).join(" "),
1646
- })),
1647
- });
1648
- if (!m.currentRecorded)
1649
- blocks.push({ kind: "lines", lines: [cell(`note: current mesh "${m.current}" is ${m.currentStopped ? "stopped" : m.currentPrepared ? "prepared, not started" : "not recorded"}`, "hint")] });
1650
- if (m.unreadable.length)
1651
- blocks.push({ kind: "lines", lines: m.unreadable.map((u) => cell(`unreadable: ${u.error}`, "failed")) });
1652
- const sections = [{ title: "Recorded Meshes", blocks }];
1653
- if (m.catalogs.length)
1654
- sections.push({ title: "Space Catalog Accounts", blocks: [{ kind: "lines", lines: m.catalogs.map((r) => `${r.idp} ${r.state}${r.error ? `: ${r.error}` : ""}`) }] });
1655
- return sections;
1656
- }
1657
- /** The pid of the selected space's running stack delivery member, from its owned service record. */
1658
- function stackDeliveryPid(r) {
1659
- return r.services?.instances?.find((item) => item.definition === STACK_DEFINITION.delivery && item.observedProcess === "running")?.pid ?? undefined;
1660
- }
1661
- function selectedSection(s, folder, deliveryPid, storeFull = false) {
1662
- if (!s.resolved)
1663
- return { title: "Selected Mesh", blocks: [{ kind: "fields", rows: [["target", cell(s.code, "failed")]] }] };
1664
- const rows = [
1665
- ["space", s.space],
1666
- ["server", s.server ?? cell("unavailable", "failed")],
1667
- ["mode", s.mode],
1668
- ];
1669
- if (s.eventsRequired)
1670
- rows.push(["events", "required"]);
1671
- if (s.tlsRequired)
1672
- rows.push(["transport", "tls-required"]);
1673
- if (s.idp)
1674
- rows.push(["idp", s.idp]);
1675
- rows.push(["source", s.source], ["root", s.root], ["personas", personaCell(s.personas)]);
1676
- if (s.mode === "user") {
1677
- rows.push(["connection", s.connection === "reachable" ? cell("reachable", "ok") : cell("unreachable", "failed")]);
1678
- const l = s.login;
1679
- if (!l)
1680
- rows.push(["login", cell("unreadable - see the warning below", "failed")]);
1681
- if (l && !l.subject)
1682
- rows.push(["login", cell(`not signed in - ${codeSpan(`${displayCmd()} login --idp ${l.idp}`)}`, "waiting")]);
1683
- if (l?.subject) {
1684
- rows.push(["login", cell(`${l.subject} · session until ${l.expiresAt}`, "ok")]);
1685
- if (l.actor === "not-granted")
1686
- rows.push(["actor", cell(`"${CLI_USER_ACTOR}" not granted - ${codeSpan(`${displayCmd()} actor grant ${CLI_USER_ACTOR} --sub ${l.subject} --full`)}`, "waiting")]);
1687
- else if (l.actor === "granted" && l.grant)
1688
- rows.push([
1689
- "actor",
1690
- cell(`"${CLI_USER_ACTOR}" granted${l.grant.label ? ` (${l.grant.label})` : ""} - read [${l.grant.read.join(", ")}], post [${l.grant.post.join(", ")}]${l.grant.scope.length ? `, scope [${l.grant.scope.join(", ")}]` : ""}`, "ok"),
1691
- ]);
1692
- else
1693
- rows.push(["actor", cell("grant not checkable on this machine (no local ledger)", "hint")]);
1694
- }
1695
- }
1696
- else {
1697
- rows.push(["connection", s.connection === "ok" ? cell("ok", "ok") : cell(`${s.connection}${s.staleRecord ? " (stale registry entry)" : ""}`, "failed")]);
1698
- const responder = responderText(s.deliveryResponder, s.mode, Boolean(servedStack(folder, s) && folder.stackBlock), deliveryPid, storeFull);
1699
- if (responder)
1700
- rows.push(["delivery responder", cell(responder.text, responder.tone)]);
1701
- }
1702
- if (s.snapshot.state === "unavailable" || (s.mode === "user" && s.snapshot.state === "skipped"))
1703
- rows.push(["live snapshot", cell(`${s.snapshot.state === "unavailable" ? "unavailable" : "not read"} (${s.snapshot.reason})`, s.snapshot.state === "unavailable" ? "failed" : "hint")]);
1704
- if (s.channels)
1705
- rows.push(["channels", s.channels.length ? s.channels.map((ch) => `${ch.channel}(${ch.messages})`).join(", ") : "none"]);
1706
- if (s.membershipFeed)
1707
- rows.push(["membership feed", s.membershipFeed.asOf ? cell(`${s.membershipFeed.entries} entries · updated ${formatAge(Math.max(0, Date.now() - Date.parse(s.membershipFeed.asOf)))} ago`, "ok") : cell("no heartbeat", "hint")]);
1708
- return { title: "Selected Mesh", blocks: [{ kind: "fields", rows }] };
1709
- }
1710
- function stateCell(text, tone) {
1711
- return { text, tone, mark: tone === "hint" ? "○" : "●" };
1712
- }
1713
- /** The agent applications this machine has set up: those whose required executables are all on PATH,
1714
- * and the ones that run in this process. The rest are what `cotal setup` adds. */
1715
- function setUpApplications(m) {
1716
- return (m.connectors ?? []).filter((connector) => !connector.missing.length).map((connector) => connector.name);
1717
- }
1718
- /** The applications line: the names that are set up, and how many more `cotal setup` would add. */
1719
- function applicationsCell(m, interactive) {
1720
- if (m.connectors === null)
1721
- return stateCell("could not be read", "failed");
1722
- const setUp = setUpApplications(m), others = m.connectors.length - setUp.length;
1723
- if (!interactive)
1724
- return setUp.length ? stateCell(`${setUp.join(", ")}${others ? ` · ${others} not set up` : ""}`, "ok") : stateCell("not set up", "hint");
1725
- if (!setUp.length)
1726
- return stateCell(`not set up · \`${displayCmd()} setup\` adds one`, "hint");
1727
- return stateCell(`${setUp.join(", ")}${others ? ` · ${others} more with \`${displayCmd()} setup\`` : ""}`, "ok");
1728
- }
1729
- /** The extensions line: one count at the version they share, naming only those that differ from it.
1730
- * The versions are the manifest pins, so a differing one is a skew an upgrade did not carry. */
1731
- function extensionsCell(e) {
1732
- if (e.items === null)
1733
- return stateCell("manifest could not be read", "failed");
1734
- if (!e.items.length)
1735
- return undefined;
1736
- const counts = new Map();
1737
- for (const item of e.items)
1738
- counts.set(item.version, (counts.get(item.version) ?? 0) + 1);
1739
- const shared = [...counts].sort((a, b) => b[1] - a[1])[0][0];
1740
- const odd = e.items.filter((item) => item.version !== shared);
1741
- const text = `${e.items.length} extension${e.items.length === 1 ? "" : "s"} at ${shared}`;
1742
- return odd.length ? stateCell(`${text} · ${odd.map((item) => `${item.label} v${item.version}`).join(" · ")}`, "waiting") : text;
1743
- }
1744
- /**
1745
- * What this machine has set up, and what needs attention.
1746
- *
1747
- * A row in its good state says nothing a reader acts on, and a piece of an application this machine
1748
- * does not have is what `cotal setup` adds, which the applications line already counts. So an
1749
- * application's own rows (the Claude plugin, Desktop and skills) appear only for an application that
1750
- * IS set up, and only when they are not current; the broker executable appears when it is missing or
1751
- * refused and local broker records make it relevant; the dashboard, which is optional, appears
1752
- * when its record cannot be read. `--all` and
1753
- * `--wide` print every row, and `--verbose` adds the installation paths ({@link machineSection}).
1754
- *
1755
- * It used to print one row per known connector whether or not it was set up, every extension label
1756
- * with the same version spelled out on each, and the broker executable's full bundled path on a
1757
- * healthy machine: a block of text whose signal a reader had to hunt for.
1758
- */
1759
- function machineOverview(r, wide, interactive, seed) {
1760
- const m = r.machine;
1761
- const tones = { ok: "ok", warn: "waiting", error: "failed", off: "hint" };
1762
- const setUp = setUpApplications(m);
1763
- // An application's rows carry its name: "Claude plugin" and "claude setup" are both claude's.
1764
- const ownedBySetUp = (label) => setUp.some((name) => label.toLowerCase().includes(name.toLowerCase()));
1765
- const rows = wide
1766
- ? m.integrations.map((item) => [item.name, stateCell(item.text, tones[item.state])])
1767
- : m.integrations.filter((item) => item.state !== "ok" && ownedBySetUp(item.name)).map((item) => [item.name, stateCell(item.text, tones[item.state])]);
1768
- rows.unshift(["Agent applications", applicationsCell(m, interactive)]);
1769
- if (wide)
1770
- for (const connector of m.connectors ?? []) {
1771
- if (m.integrations.some((item) => item.name.toLowerCase().includes(connector.name.toLowerCase())))
1772
- continue;
1773
- rows.push([connector.name, stateCell(connector.missing.length ? `${connector.missing.join(", ")} not on PATH` : connector.requires.length ? "available on PATH" : "in-process", connector.missing.length ? "waiting" : "ok")]);
1774
- }
1775
- // A remote registration uses the broker elsewhere. Keep executable readiness in the full
1776
- // diagnostics, without making a hosted client repair a binary it does not need to run.
1777
- const localBroker = r.meshes.hasPrepared || r.meshes.currentPrepared || r.meshes.unreadable.length > 0 ||
1778
- r.meshes.items.some((entry) => entry.origin !== "manual" && entry.origin !== "catalog") ||
1779
- r.folder.controllerStack || r.folder.storedState || r.folder.auth.state !== "none" ||
1780
- (r.folder.stackJournal !== undefined && r.folder.stackJournal !== "absent") ||
1781
- r.folder.processes?.some((row) => row.name === "nats" && (row.pid !== null || row.state === "unreadable")) ||
1782
- (!r.selected.resolved && (r.selected.code === "not-started" || r.selected.code === "unregistered-root" || r.selected.code === "unreadable-auth"));
1783
- if (wide || (localBroker && (m.nats === "missing" || m.natsProblem)))
1784
- rows.push(["Broker executable", stateCell(m.nats === "missing" ? "not installed" : brokerExecutable(m), m.nats === "missing" ? "waiting" : m.natsProblem ? "failed" : "ok")]);
1785
- if (wide || (m.skills.state !== "current" && setUp.length))
1786
- rows.push(["Agent skills", skillsCell(m.skills)]);
1787
- if (wide || m.web.installed === null)
1788
- rows.push(["Dashboard", stateCell(m.web.installed === null ? "installation could not be read" : m.web.installed ? "installed" : "not installed · optional", m.web.installed === null ? "failed" : m.web.installed ? "ok" : "hint")]);
1789
- const extensions = wide
1790
- ? r.extensions.items === null ? stateCell("manifest could not be read", "failed") : r.extensions.items.length ? r.extensions.items.map((item) => `${item.label} v${item.version}`).join(" · ") : undefined
1791
- : extensionsCell(r.extensions);
1792
- if (extensions !== undefined)
1793
- rows.push(["Extensions", extensions]);
1794
- if (seed)
1795
- rows.push(["Connector setup", stateCell(`incomplete · ${seed.package} failed during ${seed.phase}`, "failed")]);
1796
- return {
1797
- title: "This machine",
1798
- blocks: [
1799
- { kind: "lines", lines: [`cotal ${m.version} · Node ${m.node} · ${m.platform}`] },
1800
- { kind: "fields", rows },
1801
- ],
1802
- };
1803
- }
1804
- function connectionCell(s) {
1805
- if (s.connection === "ok" || s.connection === "reachable")
1806
- return stateCell("reachable", "ok");
1807
- const states = {
1808
- "root-gone": "project folder was moved or deleted",
1809
- unreachable: "unreachable",
1810
- "slow-link": "not answering",
1811
- "broker-stopped": `broker process ${s.brokerPid} is stopped`,
1812
- "tls-trust": "TLS could not be verified",
1813
- "tls-unsupported": "listener does not offer required TLS",
1814
- "auth-unsupported": "listener does not enforce Cotal authentication",
1815
- "jetstream-unsupported": "listener does not offer JetStream",
1816
- "non-nats-listener": "non-NATS listener holds the broker address",
1817
- "stale-auth": "credentials need renewal",
1818
- "auth-required": "authentication required",
1819
- "open-wants-auth": "authentication required",
1820
- "registry-open-now-auth": "authentication required",
1821
- "creds-rejected": "credentials rejected",
1822
- "registry-creds-rejected": "credentials rejected",
1823
- "address-held": "address held by another space",
1824
- };
1825
- return stateCell(`${states[s.connection] ?? s.connection.replaceAll("-", " ")}${s.staleRecord ? " · saved registration needs attention" : ""}`, "failed");
1826
- }
1827
- /** How a space signs a connection in, and what else a reader acts on about it: a mode the record
1828
- * states but no broker was seen to enforce says so, a TLS requirement is named, and an account
1829
- * catalog that could not be refreshed is named on each of its spaces. The broker address is not
1830
- * here: `cotal space show <name>` names it. */
1831
- function signsInText(entry, wide) {
1832
- return [
1833
- `${entry.mode === "user" ? "user sign-in" : entry.mode === "auth" ? "static auth" : "open"}${entry.modeChecked ? "" : ", not checked"}`,
1834
- ...(wide ? [entry.origin === "catalog" ? "saved catalog entry" : entry.origin === "manual" ? "registered endpoint" : "local registration"] : []),
1835
- entry.tlsRequired ? "TLS required" : "",
1836
- entry.catalog?.error ? "catalog refresh failed" : "",
1837
- ].filter(Boolean).join(" · ");
1838
- }
1839
- /** The connection state of one row: the selected space's own dialed state when this row is the
1840
- * address it dialed, else the row's own check. A row that was not dialed carries no state, and the
1841
- * note under the table says so once instead of repeating it on every row. */
1842
- function spaceStateCell(r, entry) {
1843
- const selected = r.selected.resolved && entry.space === r.selected.space;
1844
- // The selected connection describes this row only when it dialed the row's address; under
1845
- // `--all` with a `--server` that names another, the row shows its own address's check.
1846
- if (selected && r.selected.resolved && entry.check !== "not-checked" && r.selected.server !== null && entry.server !== null &&
1847
- brokerUrlKey(r.selected.server) === brokerUrlKey(entry.server))
1848
- return connectionCell(r.selected);
1849
- if (entry.check === "not-checked")
1850
- return "";
1851
- return stateCell(entry.check === "slow-link" ? "not answering" : entry.check === "broker-stopped" ? "broker process is stopped" : entry.check, entry.check === "reachable" ? "ok" : "failed");
1852
- }
1853
- /**
1854
- * The spaces this machine knows: the selected one first with its connection state, then one line
1855
- * each for the others.
1856
- *
1857
- * Only the selected space is dialed, so the others carry no state and ONE note says so, rather than
1858
- * `not checked` repeated on every row; `--all` dials each and fills the column. The broker address
1859
- * is not a group title: it groups spaces by an address a reader does not act on here, and `cotal
1860
- * space show <name>` names it. `--all` and `--wide` keep the grouped report.
1861
- */
1862
- function spacesOverview(r, wide, seedFailed) {
1863
- const blocks = [];
1864
- // The space this report is for: the target it resolved or the space it is about, else the selection
1865
- // it could not resolve.
1866
- const reported = r.selected.space ?? r.meshes.current;
1867
- const row = (entry) => ({
1868
- space: entry.space === reported ? cell(`→ ${entry.space}`, "selected") : entry.space,
1869
- state: spaceStateCell(r, entry),
1870
- detail: cell(signsInText(entry, wide), "hint"),
1871
- });
1872
- const columns = [{ key: "space", label: "Space" }, { key: "state", label: "Connection" }, { key: "detail", label: "Signs in" }];
1873
- if (!r.meshes.items.length && !r.meshes.unreadable.length)
1874
- blocks.push({ kind: "lines", lines: [cell("No spaces registered", "hint"), ...(seedFailed ? [] : [cell(`Sign in to Cotal Cloud with \`${displayCmd()} login\`.`, "hint")])] });
1875
- else if (wide) {
1876
- const groups = new Map();
1877
- for (const entry of r.meshes.items) {
1878
- const key = entry.server ?? `unavailable:${entry.space}`;
1879
- const group = groups.get(key);
1880
- if (group)
1881
- group.push(entry);
1882
- else
1883
- groups.set(key, [entry]);
1884
- }
1885
- for (const entries of groups.values()) {
1886
- blocks.push({ kind: "lines", lines: [cell(entries[0].server ?? "Broker address unavailable", "title")] });
1887
- blocks.push({ kind: "table", header: false, columns, rows: entries.map(row) });
1888
- }
1889
- }
1890
- else {
1891
- // The space this report is for first, then the rest by name: the one a command here targets is
1892
- // the one a reader looks for.
1893
- const ordered = [...r.meshes.items].sort((a, b) => Number(b.space === reported) - Number(a.space === reported) || a.space.localeCompare(b.space));
1894
- blocks.push({ kind: "table", header: false, columns, rows: ordered.map(row) });
1895
- if (r.meshes.items.some((entry) => entry.check === "not-checked"))
1896
- blocks.push({ kind: "lines", lines: [cell(`Unselected spaces are not dialed · \`${displayCmd()} status --all\` dials each`, "hint")] });
1897
- }
1898
- for (const unreadable of r.meshes.unreadable)
1899
- blocks.push({ kind: "lines", lines: [stateCell(`Registration could not be read: ${unreadable.error}`, "failed")] });
1900
- // One line per account, named by the account whose catalog failed rather than by its token URL.
1901
- for (const account of r.meshes.catalogs)
1902
- if (account.error)
1903
- blocks.push({ kind: "lines", lines: [stateCell(`Space catalog for ${account.account ?? account.idp} could not be refreshed: ${account.error}`, "failed")] });
1904
- if (!r.meshes.currentRecorded)
1905
- blocks.push({ kind: "lines", lines: [cell(`Selected space '${r.meshes.current}' is ${r.meshes.currentStopped ? "stopped" : r.meshes.currentPrepared ? "prepared, not started" : "not recorded"}${folderTargeted(r) ? "; it applies outside this folder" : ""}`, "waiting")] });
1906
- return { title: "Spaces", blocks };
1907
- }
1908
- /** The unresolved selections that mean nothing runs or is selected here, rather than a failure. */
1909
- const NOTHING_SELECTED = new Set(["no-meshes", "not-started", "unregistered-root"]);
1910
- /** Whether this report is for this folder's space, which a command without `--space` targets here
1911
- * instead of the selection. */
1912
- function folderTargeted(r) {
1913
- return typeof r.meshes.folder === "string" && r.meshes.folder === r.selected.space;
1914
- }
1915
- function selectedOverview(r) {
1916
- const s = r.selected;
1917
- const title = !s.resolved && s.recordedRoot !== undefined ? "This folder" : folderTargeted(r) ? "This folder's space" : "Selected space";
1918
- // Nothing running or selected is a state to start from, so it does not carry the mark of a live connection.
1919
- if (!s.resolved)
1920
- return { title, blocks: [
1921
- { kind: "lines", lines: [stateCell(s.message, NOTHING_SELECTED.has(s.code) ? "hint" : "failed")] },
1922
- ...(servedStack(r.folder, s) ? stackLines(r.folder) : []),
1923
- ] };
1924
- // A broker named with `--server` is reported even when nothing on this machine is registered.
1925
- if (s.source !== "flag-server" && !r.meshes.items.length && !r.meshes.currentPrepared && r.folder.auth.state === "none" && !r.folder.processes?.some((item) => item.pid !== null))
1926
- return undefined;
1927
- const responder = responderText(s.deliveryResponder, s.mode, Boolean(servedStack(r.folder, s) && r.folder.stackBlock), stackDeliveryPid(r), r.store?.state === "full");
1928
- const rows = [
1929
- ["Broker", s.server ?? stateCell("address unavailable", "failed")],
1930
- ["Connection", connectionCell(s)],
1931
- ...(s.spaceStreams.state === "absent" ? [["Space streams", stateCell(s.spaceStreams.stack === "running" ? "not on the broker · the space was deleted under its running stack" : "not on the broker · a space delete removed them", "failed")]] : []),
1932
- ...(responder ? [["Delivery responder", stateCell(responder.text, responder.tone)]] : []),
1933
- ...(r.store?.state === "write-failed" ? [["Store", stateCell(`write failed at ${r.store.at}: ${r.store.cause}${r.store.path ? ` · ${r.store.path}` : ""}`, "failed")]] : []),
1934
- ...(r.store?.state === "full" ? [["Store", stateCell(`full · ${r.store.used} bytes stored, over its --max-file-store cap of ${r.store.cap} · ${r.store.path}`, "failed")]] : []),
1935
- ...(r.store?.state === "damaged" ? [["Store", stateCell(`damage logged at ${r.store.at}: ${r.store.warning}`, "failed")]] : []),
1936
- ...(r.stackManager ? [["Manager", r.stackManager.endpoint === "answered" ? stateCell("answering", "ok") : r.stackManager.endpoint === "not-answering" ? stateCell(`not answering · stack-manager pid ${r.stackManager.pid}`, "failed") : stateCell("endpoint not checked", "hint")]] : []),
1937
- ["Access", s.mode === "user" ? "user sign-in" : s.mode === "auth" ? "static auth" : "open"],
1938
- ["Project", s.rootGone ? stateCell(`${s.root} · folder is gone`, "failed") : s.root],
1939
- ["Default agent", r.machine.defaults ? `${r.machine.defaults.harness ?? "application unresolved"} · persona ${r.machine.defaults.persona ?? "not set"}` : stateCell("saved defaults could not be read", "failed")],
1940
- ["Persona catalog", s.personas.default === "valid" ? "default available" : stateCell(s.personas.default === "invalid" ? "default is invalid" : s.personas.default === "unreadable" ? "could not be read" : "no default persona", s.personas.default === "invalid" || s.personas.default === "unreadable" ? "failed" : "hint")],
1941
- ];
1942
- if (s.tlsRequired)
1943
- rows.push(["Transport", "TLS required"]);
1944
- if (s.eventsRequired)
1945
- rows.push(["Events", "required"]);
1946
- if (s.mode === "user") {
1947
- if (!s.login)
1948
- rows.push(["Account", stateCell("could not be read", "failed")]);
1949
- else if (!s.login.subject)
1950
- rows.push(["Account", stateCell("not signed in", "waiting")]);
1951
- else {
1952
- rows.push(["Account", `${s.login.subject} · session until ${s.login.expiresAt}`]);
1953
- rows.push(["Grant", stateCell(s.login.actor === "granted" ? "granted" : s.login.actor === "not-granted" ? "not granted" : "not checkable on this machine", s.login.actor === "granted" ? "ok" : s.login.actor === "not-granted" ? "waiting" : "hint")]);
1954
- }
1955
- }
1956
- if (s.snapshot.state === "unavailable")
1957
- rows.push(["Live details", stateCell(`unavailable · ${s.snapshot.reason}`, "waiting")]);
1958
- if (servedStack(r.folder, s) && r.folder.noManager && !r.stackManager) {
1959
- const service = r.folder.managerService;
1960
- const outside = r.outsideStackManager;
1961
- rows.push(["Manager", service
1962
- ? stateCell(`the ${service.definition} service · instance ${service.instanceId} · outside this stack, which was started with --no-manager`, "ok")
1963
- : outside?.endpoint === "answered"
1964
- ? stateCell(`answering${outside.instanceId ? ` · instance ${outside.instanceId}` : ""} · outside this stack, which was started with --no-manager`, "ok")
1965
- : stateCell(`${outside?.endpoint === "not-answering" ? "no manager answered" : "endpoint not checked"} · this stack was started with --no-manager`, "hint")]);
1966
- }
1967
- const blocks = [{ kind: "fields", rows }];
1968
- if (r.folder.root === s.root && r.folder.processSpace === s.space && r.folder.controllerStack) {
1969
- blocks.push({ kind: "lines", lines: [cell("Controller stack · its members are the stack-* rows under Owned services", "hint")] }, ...stackLines(r.folder));
1970
- }
1971
- else if (r.folder.root === s.root && r.folder.stackJournal === "unreadable") {
1972
- 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")] });
1973
- }
1974
- else if (r.folder.root === s.root && r.folder.processSpace === s.space && r.folder.processes) {
1975
- blocks.push({ kind: "lines", lines: [cell("Legacy local process records", "label")] });
1976
- blocks.push({
1977
- kind: "table", header: false,
1978
- columns: [{ key: "name", label: "Service" }, { key: "state", label: "State" }],
1979
- rows: r.folder.processes.map((item) => ({
1980
- name: item.name === "nats" ? "Broker" : item.name === "manager" ? "Manager" : item.name === "delivery" ? "Delivery" : item.name === "web" ? "Web" : item.name,
1981
- state: item.state !== "stopped" ? processCell(item) : stateCell(item.pid === null && item.detail !== "stopped" ? "not started" : item.detail ?? "stopped", "hint"),
1982
- })),
1983
- });
1984
- }
1985
- else
1986
- blocks.push({ kind: "lines", lines: [cell("Legacy process records not checked here · the selected space has a different or unresolved local process scope", "hint")] });
1987
- if (r.folder.launches === false)
1988
- blocks.push({ kind: "lines", lines: [cell(`This folder's personas are not used by the selected space. Spawn uses ${s.personas.root}.`, "waiting")] });
1989
- return { title: `${title} → ${s.space}`, blocks };
1990
- }
1991
- /** The selected space and its root when this folder's controller stack serves it: a resolved one, or
1992
- * a prepared one that is not started, as an `up` cut off before it registered the space leaves it. */
1993
- function servedStack(folder, s) {
1994
- if (s.space === undefined || s.root === undefined)
1995
- return undefined;
1996
- return folder.controllerStack && folder.root === s.root && folder.processSpace === s.space ? { space: s.space, root: s.root } : undefined;
1997
- }
1998
- /** This folder's own controller stack when it does not serve the selected space. The note under the
1999
- * heading sends to status when its last operation has no recorded outcome, so status names it. */
2000
- function folderStack(folder, s) {
2001
- return folder.controllerStack && folder.processSpace !== null && !servedStack(folder, s) ? { space: folder.processSpace, root: folder.root } : undefined;
2002
- }
2003
- /** The lines that name this folder's stack operation cut off with no recorded outcome: one that keeps
2004
- * `up` and `down` from settling it, or one that left the stack part way. */
2005
- function stackLines(folder) {
2006
- const blocks = [];
2007
- if (folder.stackBlock)
2008
- blocks.push({ kind: "lines", lines: [stateCell(`Stack blocked · ${folder.stackBlock.reason}`, "waiting")] });
2009
- const part = folder.stackUnfinished;
2010
- if (part)
2011
- blocks.push({ kind: "lines", lines: [stateCell(part.kind === "up"
2012
- ? part.running.length ? `Half started · the last up ended before ${roleList(part.stopped)} started; ${roleList(part.running)} ${part.running.length === 1 ? "runs" : "run"}` : "Start interrupted · the last up ended before any member started"
2013
- : part.stopped.length ? `Half stopped · the last down ended with ${roleList(part.running)} still running; ${roleList(part.stopped)} ${part.stopped.length === 1 ? "is" : "are"} stopped` : "Stop interrupted · the last down ended before any member stopped", "waiting")] });
2014
- return blocks;
2015
- }
2016
- /** Stack members as a status line names them: `broker`, `delivery and manager`. */
2017
- function roleList(roles) {
2018
- return roles.length > 1 ? `${roles.slice(0, -1).join(", ")} and ${roles.at(-1)}` : roles[0] ?? "";
2019
- }
2020
- /** Pre-commit backup claims and ready cuts with a missing source block ordinary startup. */
2021
- function backupRecovery(maintenance, sourceMissing = false) {
2022
- return maintenance && (maintenance.state === "claimed" || maintenance.state === "restore-ready" || sourceMissing) ? maintenance.next : null;
2023
- }
2024
- function nextActions(r, seedFailed, interactive, recovery, preparedHarness) {
2025
- if (seedFailed)
2026
- return {
2027
- title: "Next",
2028
- blocks: [{ kind: "lines", lines: r.hints.flatMap(hint => hint.split("\n").map(line => cell(line, "hint"))) }],
2029
- };
2030
- if (recovery)
2031
- return { title: "Next", blocks: [...new Set([recovery, ...r.hints])].map((hint) => ({ kind: "lines", lines: [cell(hint, "hint")] })) };
2032
- const cmd = displayCmd();
2033
- const items = [];
2034
- const extra = [];
2035
- let restartBlock;
2036
- const noApplication = !setUpApplications(r.machine).length;
2037
- if (!r.selected.resolved && !r.meshes.items.length && !r.meshes.unreadable.length) {
2038
- items.push({ command: `${cmd} login`, description: "Sign in to Cotal Cloud" });
2039
- }
2040
- if (noApplication) {
2041
- const s = r.selected;
2042
- const connector = r.machine.connectors?.find((row) => row.name === preparedHarness);
2043
- if (interactive)
2044
- items.push({ command: `${cmd} setup`, description: !s.resolved && s.code !== "not-started" ? "Set up an agent application and a space" : "Set up an agent application" });
2045
- else if (connector && !s.resolved && s.code === "not-started" && s.root && s.space && !s.recordedRoot) {
2046
- const guide = Object.hasOwn(OFFICIAL_CONNECTORS, connector.name) ? `connect-${connector.name}` : "connectors";
2047
- extra.push(`Install ${connector.missing.join(", ")} on PATH first. See https://docs.cotal.ai/docs/${guide}/.`);
2048
- items.push({ command: `${cmd} setup --destination local --harness ${shellWord(connector.name)} --project ${shellWord(s.root)} --space ${shellWord(s.space)} --configure-only --no-input`, description: "" });
2049
- }
2050
- else
2051
- items.push({ command: `${cmd} setup --help`, description: "See setup flags for scripts. Bare setup needs a terminal." });
2052
- }
2053
- if (r.selected.resolved) {
2054
- const s = r.selected;
2055
- const reachable = s.connection === "ok" || s.connection === "reachable";
2056
- const scope = { space: s.source === "flag-server" ? undefined : s.space, server: s.source === "flag-server" || s.source === "flag-space-override" ? s.server : undefined };
2057
- if (!noApplication) {
2058
- if (s.personas.default !== "missing" && s.personas.default !== "valid")
2059
- items.push({ command: onRerun(`${cmd} persona show default`, scope), description: "See what is wrong with the default persona" });
2060
- else if (reachable && s.deliveryResponder !== "unbound" && s.deliveryResponder !== "stale")
2061
- items.push({ command: onRerun(`${cmd} spawn`, scope), description: s.personas.default === "missing" ? "Open your default agent; creates the shipped default persona" : "Open your default agent" });
2062
- }
2063
- if (reachable)
2064
- items.push({ command: onRerun(`${cmd} who`, scope), description: "See the live roster" });
2065
- if (r.stackManager?.endpoint === "answered" || r.outsideStackManager?.endpoint === "answered")
2066
- items.push({ command: onRerun(`${cmd} ps`, scope), description: "List managed agents" });
2067
- }
2068
- if (r.selected.resolved || !noApplication) {
2069
- items.push({ command: `${cmd} space`, description: "List the spaces on this machine" });
2070
- const unchecked = r.meshes.items.some(m => m.check === "not-checked");
2071
- if (!r.selected.resolved || r.selected.source !== "registry" || unchecked)
2072
- items.push({ command: `${cmd} use <name>`, description: "Select the default space" });
2073
- if (r.meshes.items.length > 1 && unchecked)
2074
- items.push({ command: `${cmd} status --all`, description: "Check every registered space" });
2075
- }
2076
- // A stopped broker is resumed, not restarted. A local controller stack that does not answer,
2077
- // or one with a member whose process is gone, otherwise restarts its stopped members from its
2078
- // own records. One whose last operation a member keeps unsettled is named the way out that
2079
- // `up` and `down` name instead. A stack started with --no-manager leaves its manager out by choice,
2080
- // so a manager record an earlier up left is not a stopped member, and the restart keeps the flag.
2081
- 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;
2082
- // A connection to a `--server` address other than the recorded one does not say whether the stack
2083
- // answers; the hint `readSelected` adds names that address. A user-auth space is probed on its own path.
2084
- const dialed = r.selected.resolved ? r.selected : undefined;
2085
- const recordedServer = r.meshes.items.find((m) => m.space === dialed?.space)?.server;
2086
- const elsewhere = dialed !== undefined && dialed.mode !== "user" && (dialed.source === "flag-server" || dialed.source === "flag-space-override")
2087
- && (recordedServer == null || dialed.server === null ? recordedServer !== dialed.server : brokerUrlKey(recordedServer) !== brokerUrlKey(dialed.server));
2088
- const stack = servedStack(r.folder, r.selected), own = stack !== undefined;
2089
- const seedBlocksRestart = r.selected.channelSeedBlocksRestart;
2090
- // This folder's own stack is blocked the same way under another selection, and its block leads too.
2091
- const blocked = stack ?? folderStack(r.folder, r.selected);
2092
- const block = blocked ? r.folder.stackBlock : undefined;
2093
- const origin = r.meshes.items.find((m) => m.space === dialed?.space)?.origin;
2094
- const legacy = dialed && !r.folder.controllerStack && r.folder.root === dialed.root && r.folder.processSpace === dialed.space;
2095
- const local = legacy && dialed.mode === "auth" && !["manual", "catalog"].includes(origin ?? "up");
2096
- const exited = legacy ? (r.folder.processes ?? []).filter((row) => (row.name === "nats" || row.name === "manager") && row.state === "stopped" && (row.pid !== null || row.detail === "stopped")).map((row) => row.name) : [];
2097
- const storeBlocked = !elsewhere && r.selected.resolved && r.selected.connection === "unreachable" && rootStoreProblem(r.selected.root) !== undefined;
2098
- if (r.selected.resolved && r.selected.connection === "broker-stopped")
2099
- items.unshift({ command: `kill -CONT ${r.selected.brokerPid}`, description: "Resume the stopped broker process so it answers again" });
2100
- else if (block && blocked) {
2101
- const inspect = { command: `${cmd} service status ${block.definition} --instance ${block.instanceId} --space ${shellWord(blocked.space)}`, description: block.route.kind === "inspect" ? "Inspect the member that keeps up and down from settling" : "Inspect that member" };
2102
- items.unshift(...(block.route.kind === "abandon" ? [{ command: `${cmd} down --abandon-stop ${block.route.requestId} --yes`, description: `Abandon the unconfirmed stop of ${block.definition}; up and down refuse until then` }, inspect] : [inspect]));
2103
- }
2104
- else if (stack && r.folder.stackUnfinished) {
2105
- const part = r.folder.stackUnfinished;
2106
- const restart = `${cmd} up --root ${shellWord(stack.root)}${part.noManager ? " --no-manager" : ""}`;
2107
- // An up that ended before it registered the space cannot be finished: the next up reuses the
2108
- // running broker, and delivery does not start for a space that is not registered.
2109
- items.unshift(...(part.kind === "up"
2110
- ? r.selected.resolved || !part.running.length
2111
- ? seedBlocksRestart ? [] : [{ command: restart, description: `Finish starting the stack: the last up ended before ${roleList(part.stopped)} started` }]
2112
- : [{ command: `${cmd} down --yes`, description: `Stop what the last up started: it ended before it registered the space, so up cannot finish it` }, { command: restart, description: "Then start the stack again" }]
2113
- : [{ command: `${cmd} down --yes`, description: `Finish stopping the stack: the last down ended with ${roleList(part.running)} still running` },
2114
- ...(part.stopped.length && !seedBlocksRestart ? [{ command: `${cmd} up --root ${shellWord(stack.root)}`, description: "Or restart this stack's stopped members from its recorded inputs" }] : [])]));
2115
- }
2116
- else if (r.selected.resolved && r.selected.spaceStreams.state === "absent") {
2117
- // Up creates the streams again only while the stack's other members are stopped.
2118
- const stack = r.selected.spaceStreams.stack;
2119
- if (own && stack === "running")
2120
- items.unshift({ command: `${cmd} down --yes`, description: "Stop the stack its space was deleted under" }, { command: `${cmd} up`, description: "Then start it again; up creates the space's streams, empty" });
2121
- else if (own)
2122
- items.unshift({ command: `${cmd} up --root ${shellWord(r.selected.root)}`, description: stack === "stopped" ? "Create the space's streams again, empty, and restart the stack's stopped members" : `Create the space's streams again, empty; while the stack runs, stop it first with \`${cmd} down --yes\`` });
2123
- else {
2124
- const absent = spaceStreamsAbsent(r.selected.space, r.selected.spaceStreams.root ?? undefined, stack ?? undefined);
2125
- extra.push(`${absent.message}; ${absent.remedy}`);
2126
- }
2127
- }
2128
- else if (!storeBlocked && !seedBlocksRestart && own && r.selected.resolved && r.store?.state !== "full" && (memberGone || !elsewhere && r.selected.connection !== "ok" && r.selected.connection !== "reachable")) {
2129
- // `up` neither adopts nor replaces a service outside the stack that runs one of this root's
2130
- // records, so each is stopped first, with the stop `up` names.
2131
- const held = r.folder.heldServices ?? [], space = r.selected.space;
2132
- items.unshift(...held.map((row) => ({ command: `${cmd} svc stop ${row.definition} --instance ${row.instanceId} --space ${shellWord(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" });
2133
- }
2134
- else if (!elsewhere && legacy && dialed.mode === "open" && dialed.connection === "ok" && origin === "up" && exited.includes("manager") && r.folder.processes?.some((row) => row.name === "nats" && row.state === "running")) {
2135
- restartBlock = channelSeedRestartBlock(dialed.root);
2136
- if (!restartBlock)
2137
- items.unshift({ command: `${cmd} up`, description: "Restart this folder's manager without stopping the broker" });
2138
- }
2139
- else if (!storeBlocked && !seedBlocksRestart && local && exited.length) {
2140
- const broker = exited.includes("nats"), manager = exited.includes("manager");
2141
- const notes = [...(broker ? ["up reopens the recorded store"] : []), ...(manager ? ["pass --runtime again if the manager ran on one"] : [])];
2142
- items.unshift({ command: `${cmd} up`, description: `Restart this folder's ${broker && manager ? "broker and manager" : broker ? "broker" : "manager"}, which exited; ${notes.join("; ")}` });
2143
- }
2144
- else if (!storeBlocked && !seedBlocksRestart && local && r.selected.resolved && r.selected.connection === "unreachable" && (r.folder.processes ?? []).every((row) => row.state === "stopped")) {
2145
- // A clean down leaves every member stopped with no pidfile. Spawn and ps need the stack, so the
2146
- // bare `up` that starts it again on its recorded address and store comes first.
2147
- items.unshift({ command: `${cmd} up`, description: "Start this folder's stopped stack again; pass --runtime again if the manager ran on one" });
2148
- }
2149
- else if (!seedBlocksRestart && !elsewhere && local && r.selected.resolved && r.selected.connection === "ok" && r.store?.state !== "full" && r.store?.state !== "write-failed"
2150
- && (r.selected.deliveryResponder === "unbound" || r.selected.deliveryResponder === "stale")
2151
- && r.folder.processes?.some((row) => row.name === "delivery" && row.state === "stopped")) {
2152
- items.unshift({ command: `${cmd} up`, description: "Restore the delivery responder" });
2153
- }
2154
- // A stack whose folder was deleted stops only from this machine's records.
2155
- if (r.selected.resolved && r.selected.rootGone)
2156
- items.unshift({ command: `${cmd} down --space ${shellWord(r.selected.space)} --yes`, description: "Stop the stack whose folder is gone and free its name" });
2157
- if (r.selected.resolved && r.selected.mode === "user" && r.selected.login && !r.selected.login.subject)
2158
- items.unshift({ command: `${cmd} login --idp ${r.selected.login.idp}`, description: "Sign in to the selected space" });
2159
- // A delivery member that runs with no lease is not replaced by `up`; `down` kills one that does not exit.
2160
- const deliveryPid = stackDeliveryPid(r);
2161
- if (r.selected.resolved && r.selected.deliveryResponder === "unbound" && deliveryPid !== undefined)
2162
- items.unshift({ command: `${cmd} service status stack-delivery${own ? "" : ` --space ${shellWord(r.selected.space)}`}`, description: `Read the delivery member's record: pid ${deliveryPid} is alive but holds no lease, so it is starting or not responding` }, { command: own ? `${cmd} down --yes` : `${cmd} down --space ${shellWord(r.selected.space)} --yes`, description: "If it stays that way, stop the stack; down kills a member that does not exit on SIGTERM" }, { command: own ? `${cmd} up` : `${cmd} up --root ${shellWord(r.selected.root)}`, description: "Then start the stack again" });
2163
- // A manager that does not answer cannot report its stop impact, so no stop route reaches it.
2164
- if (r.stackManager?.endpoint === "not-answering")
2165
- items.unshift({ command: `kill -KILL ${r.stackManager.pid}`, description: `The stack manager does not answer, so \`${cmd} down\` cannot stop it. If it stays that way, end its process; \`${cmd} down --yes\` then records it stopped` });
2166
- // The broker keeps a store write error until it restarts, so messages sent meanwhile may be lost.
2167
- if (r.store?.state === "write-failed") {
2168
- const repair = storeWriteRepair(r.store, r.selected.resolved ? r.selected.root : undefined, r.selected.space ?? "");
2169
- const first = `First ${repair}`;
2170
- // A broker without JetStream cannot record the manager's stop, and it stops only after the manager.
2171
- if (r.store.jetStreamDisabled && r.stackManager && r.selected.resolved)
2172
- items.unshift({ command: `kill -TERM ${r.stackManager.pid}`, description: "The broker disabled JetStream after the write failure and serves none until it restarts, which needs the manager stopped first. On this host, end the manager; it stops its agents by its default policy" }, { command: own ? `${cmd} down --yes` : `${cmd} down --space ${shellWord(r.selected.space)} --yes`, description: "Then stop the other members" }, { command: own ? `${cmd} up` : `${cmd} up --root ${shellWord(r.selected.root)}`, description: `${first}; then up starts the broker again with the history it kept` });
2173
- else
2174
- items.unshift({ command: `${cmd} down`, description: `${first}; then \`${cmd} up\` starts the broker again with the history it kept` });
2175
- }
2176
- // The broker refuses every write while the store is over its cap, so sends store nothing, and a
2177
- // stopped member starts again only once there is room. A larger cap makes that room and keeps the
2178
- // history, but needs the broker restarted, so the manager's own process is ended first where it
2179
- // runs, as a full store refuses its stop. This is the route up names. A history purge is not named:
2180
- // it frees only the channel history's bytes, which may leave the store over its cap.
2181
- if (r.store?.state === "full" && r.selected.resolved) {
2182
- const { root } = r.selected;
2183
- const manager = r.stackManager;
2184
- items.unshift(...(manager ? [{ command: `kill -TERM ${manager.pid}`, description: "End the manager on this host, as a full store refuses its stop; it stops its agents by its default policy" }] : []),
2185
- // `down` stops only the stack of the folder it runs in.
2186
- { command: `${cmd} down --yes`, description: `${manager ? "Then stop the other members" : "Stop the stack"}${own ? "" : `; run it in ${root}`}` }, { command: own ? `${cmd} up --max-file-store <bytes>` : `${cmd} up --root ${shellWord(root)} --max-file-store <bytes>`, description: "Then start it again with a larger cap; the store keeps the history" });
2187
- }
2188
- // The broker keeps serving a store it found damage in, from what it can still read there.
2189
- if (r.store?.state === "damaged" && r.selected.resolved && r.services?.instances?.some((row) => row.definition === STACK_DEFINITION.broker))
2190
- items.unshift({ command: `${cmd} service logs stack-broker${own ? "" : ` --space ${shellWord(r.selected.space)}`}`, description: "Read what the broker logged about the damage it found in its store; history holds only what it could still read" });
2191
- const first = restartBlock ? [{ kind: "lines", lines: [cell(`Restart blocked: ${restartBlock.message}. ${restartBlock.remedy}`, "hint")] }] : [];
2192
- return { title: "Next", blocks: [...first, { kind: "commands", items }, ...[...extra, ...r.hints].map((hint) => ({ kind: "lines", lines: [cell(hint, "hint")] }))] };
2193
- }
2194
- function ownedServicesOverview(services) {
2195
- if (!services || services.state === "not-checked")
2196
- return undefined;
2197
- const blocks = [];
2198
- if (services.definitions === null)
2199
- blocks.push({ kind: "lines", lines: [stateCell("Saved service definitions unavailable", "waiting")] });
2200
- if (services.instances === null)
2201
- blocks.push({ kind: "lines", lines: [stateCell("Owned service instances unavailable; no stopped state inferred", "waiting")] });
2202
- if (services.instances?.length)
2203
- blocks.push({ kind: "table", columns: [{ key: "service", label: "Service" }, { key: "instance", label: "Full instance" }, { key: "host", label: "Execution host" }, { key: "process", label: "Process observation" }, { key: "readiness", label: "Recorded readiness" }, { key: "supervisor", label: "Supervisor record" }], rows: services.instances.slice(0, 100).map((row) => ({
2204
- service: row.definition, instance: row.instanceId, host: row.executionHost,
2205
- process: stateCell(row.observedProcess.replaceAll("-", " "), row.observedProcess === "running" ? "ok" : row.observedProcess === "unreadable" || row.observedProcess === "unresolved-launch" || row.observedProcess === "foreign-host" ? "waiting" : "hint"),
2206
- readiness: cell(`${row.startInterrupted ? "start interrupted" : row.readinessObservation.replaceAll("-", " ")} · ${row.readinessAsOf}`, "hint"),
2207
- supervisor: row.supervisorRecord.mechanism === "none-recorded" ? "not assigned here" : `${row.supervisorRecord.mechanism} · ${row.supervisorRecord.fileObservation}; OS state not checked`,
2208
- })) });
2209
- if (services.instances && services.instances.length > 100)
2210
- blocks.push({ kind: "lines", lines: [cell(`${services.instances.length - 100} instance rows omitted; --json retains the complete readable inventory.`, "hint")] });
2211
- const instantiated = new Set(services.instances?.map((row) => row.definition));
2212
- const saved = services.instances === null ? [] : services.definitions?.filter((row) => !instantiated.has(row.name)) ?? [];
2213
- if (saved.length)
2214
- blocks.push({ kind: "table", columns: [{ key: "service", label: "Saved service" }, { key: "type", label: "Launch type" }, { key: "observation", label: "Instance records" }], rows: saved.slice(0, 100).map((row) => ({ service: row.name, type: row.launch.type === "adapter" ? row.launch.adapter : "process", observation: "no owned instance recorded" })) });
2215
- if (saved.length > 100)
2216
- blocks.push({ kind: "lines", lines: [cell(`${saved.length - 100} saved definitions omitted; --json retains the complete readable inventory.`, "hint")] });
2217
- if (services.definitions?.length === 0 && services.instances?.length === 0)
2218
- blocks.push({ kind: "lines", lines: [cell("No saved definitions or owned instance records in this selected space.", "hint")] });
2219
- blocks.push({ kind: "lines", lines: [cell(`Local records and process observations as of ${services.observedAt}; non-atomic. Recorded readiness is historical, not a fresh endpoint response. No OS unit query, service control, adoption or remote process ownership is implied.`, "hint")] });
2220
- // The space is known here, and a sole instance names its service and full ID as well.
2221
- const sole = services.instances?.length === 1 ? services.instances[0] : undefined;
2222
- if (services.space !== null && (services.instances?.length || services.definitions?.length)) {
2223
- const inspect = `${displayCmd()} svc status ${sole ? `${sole.definition} --instance ${sole.instanceId}` : "<service> --instance <full-id>"} --space ${shellWord(services.space)}`;
2224
- blocks.push({ kind: "commands", items: [{ command: inspect, description: "Inspect one exact owned instance and its recorded supervisor" }, { command: `${displayCmd()} svc`, description: "Read the full saved-service inventory" }] });
2225
- }
2226
- return { title: `Owned services → ${services.space}`, blocks };
2227
- }
2228
- function bootAttemptOverview(snapshot) {
2229
- if (!snapshot)
2230
- return undefined;
2231
- const elsewhere = [...snapshot.elsewhere.slice(0, 100).map((row) => `Launch summary ${row.deploymentId} was recorded at ${row.root}. This folder was moved or copied since, so it reports only that earlier boot and blocks nothing here.`), ...(snapshot.elsewhere.length > 100 ? ["Additional summaries are in JSON."] : [])];
2232
- if (!snapshot.unsettled.length && !snapshot.additive.length && !snapshot.unreadable.length)
2233
- return elsewhere.length ? { title: "Deployment attempts", blocks: [{ kind: "fields", rows: [["Folder root", snapshot.root]] }, { kind: "lines", lines: elsewhere }] } : undefined;
2234
- return { title: "Deployment attempts", blocks: [
2235
- { kind: "fields", rows: [["Folder root", snapshot.root], ["Local read", snapshot.state], ["Unsettled fresh", String(snapshot.unsettled.length)], ["Additive attempts", String(snapshot.additive.length)], ["Unreadable records", String(snapshot.unreadable.length)]] },
2236
- snapshot.unsettled.length ? { kind: "table", columns: [{ key: "id", label: "Fresh boot" }, { key: "space", label: "Space" }, { key: "broker", label: "Recorded broker" }], rows: snapshot.unsettled.slice(0, 100).map((row) => ({ id: row.deploymentId, space: row.space, broker: row.server })) } : { kind: "lines", lines: ["No readable unsettled fresh attempt in this folder."] },
2237
- snapshot.additive.length ? { kind: "table", columns: [{ key: "id", label: "Additive intent" }, { key: "space", label: "Space" }, { key: "state", label: "Recorded state" }], rows: snapshot.additive.slice(0, 100).map((row) => ({ id: row.deploymentId, space: row.space, state: row.recordedState })) } : { kind: "lines", lines: ["No readable additive attempt in this folder."] },
2238
- ...(elsewhere.length ? [{ kind: "lines", lines: elsewhere }] : []),
2239
- { kind: "lines", lines: [...snapshot.unreadable.slice(0, 100).map((path) => `Unreadable record: ${path}`), ...(snapshot.unsettled.length > 100 || snapshot.additive.length > 100 || snapshot.unreadable.length > 100 ? ["Additional records are in JSON."] : []), "A fresh intent may have started a broker; an additive intent may have changed its resources. No retry or stop authority follows from this read."] },
2240
- { kind: "commands", items: [{ command: `${displayCmd()} team show <deployment-id>`, description: "Inspect the original attempt from its recorded root" }] },
2241
- ] };
2242
- }
2243
- function maintenanceOverview(maintenance) {
2244
- if (!maintenance)
2245
- return undefined;
2246
- return { title: "Maintenance", blocks: [
2247
- { kind: "fields", rows: [["Folder root", maintenance.root], ["Space", maintenance.space ?? "not read"], ["State", maintenance.state], ["Attempt", maintenance.attemptId ?? "not read"]] },
2248
- ...(maintenance.next ? [{ kind: "lines", lines: [maintenance.next] }] : []),
2249
- ...(maintenance.rolledBackRuns?.length ? [{ kind: "lines", lines: rolledBackNotes({ runs: maintenance.rolledBackRuns, more: maintenance.rolledBackRunsMore ?? 0 }) }] : []),
2250
- ] };
2251
- }
2252
- /** The approved screen hierarchy; record-level diagnostics are opt-in. `wide` reports every row in
2253
- * full, as `--all` and `--wide` ask. */
2254
- export function statusView(r, verbose = false, wide = false, { interactive = false, preparedHarness, seed, recovery = backupRecovery(r.maintenance) } = {}) {
2255
- const selected = selectedOverview(r);
2256
- // This folder's own stack under another selection, with the lines it has when it is selected.
2257
- const held = folderStack(r.folder, r.selected), heldLines = held ? stackLines(r.folder) : [];
2258
- const heldSection = held && heldLines.length ? { title: `This folder's space → ${held.space}`, blocks: heldLines } : undefined;
2259
- const owned = ownedServicesOverview(r.services);
2260
- const attempts = bootAttemptOverview(r.bootAttempts);
2261
- const maintenance = maintenanceOverview(r.maintenance);
2262
- const sections = [machineOverview(r, wide, interactive, seed), spacesOverview(r, wide, Boolean(seed)), ...(selected ? [selected] : []), ...(heldSection ? [heldSection] : []), ...(maintenance ? [maintenance] : []), ...(attempts ? [attempts] : []), ...(owned ? [owned] : [])];
2263
- if (verbose)
2264
- sections.push(machineSection(r.machine), extensionsSection(r.extensions), folderSection(r.folder, r.selected), ...meshesSections(r.meshes), selectedSection(r.selected, r.folder, stackDeliveryPid(r), r.store?.state === "full"));
2265
- sections.push(nextActions(r, Boolean(seed), interactive, recovery, preparedHarness));
2266
- return { sections };
2267
- }
2268
- function section(name) {
2269
- console.log(`\n${c.bold(name)}`);
2270
- }
2271
- const COMPONENT_EXIT = {
2272
- serving: 0,
2273
- // An optional component that was never installed is not a failed one.
2274
- "not-installed": 0,
2275
- "not-started": 0,
2276
- absent: 1,
2277
- "not-serving": 2,
2278
- refused: 3,
2279
- };
2280
- /** Piped records keep one line per component. Terminal rows that do not fit put their facts below
2281
- * the verdict, wrapping at word boundaries. Escape control characters before layout so a stored
2282
- * reason cannot inject a new component record. */
2283
- function printComponent(component) {
2284
- const heading = ` ${component.name.padEnd(16)} ${component.verdict}`;
2285
- const facts = component.facts.map(oneLine);
2286
- const line = `${heading}${facts.length ? ` · ${facts.join(" · ")}` : ""}`;
2287
- const width = terminalWidth(process.stdout);
2288
- if (displayWidth(line) <= width)
2289
- console.log(line);
2290
- else {
2291
- console.log(heading);
2292
- for (const fact of facts)
2293
- for (const part of wrapWords(fact, width - 4))
2294
- console.log(` ${part}`);
2295
- }
2296
- }
2297
- function componentExit(components) {
2298
- // Refusal outranks every state: an unreadable control surface is not a clean zero even if some
2299
- // other component answered. A process that exists but lacks its serving answer is next, then
2300
- // genuine absence. The order is intentionally one place so a new component cannot accidentally
2301
- // collapse these states by choosing its own exit code.
2302
- return Math.max(...components.map((component) => COMPONENT_EXIT[component.verdict]));
2303
- }
2304
- function processRecord(template, context) {
2305
- try {
2306
- const path = localProcessPath(template, context);
2307
- const state = pidfileState(path);
2308
- if (state.pid === undefined)
2309
- return state.liveness === "dead" ? { kind: "absent" } : { kind: "unattributable", raw: readPidfile(path) ?? "" };
2310
- return { kind: state.liveness === "alive" ? "live" : state.liveness === "dead" ? "dead" : "unknown", pid: state.pid };
2311
- }
2312
- catch (e) {
2313
- // An ambiguous record or any failed read refuses this component's row, never the whole pass.
2314
- return { kind: "unreadable", error: e.message };
2315
- }
2316
- }
2317
- function pidFacts(record) {
2318
- if (record.kind === "live" || record.kind === "dead" || record.kind === "unknown")
2319
- return [`pid ${record.pid}`];
2320
- if (record.kind === "unreadable")
2321
- return [`pidfile unreadable: ${record.error}`];
2322
- return [];
2323
- }
2324
- function processVerdict(record) {
2325
- if (record.kind === "absent" || record.kind === "dead")
2326
- return "absent";
2327
- if (record.kind === "unattributable" || record.kind === "unknown" || record.kind === "unreadable")
2328
- return "refused";
2329
- return undefined;
2330
- }
2331
- /** The probe credential for the components pass, per target mode. Static/open meshes keep the exact
2332
- * mint they had; a user-mode target gets the signed-in login's bearer, or the one-sentence reason
2333
- * it cannot be had. */
2334
- async function componentCredential(target) {
2335
- if (target.mode !== "user")
2336
- return { kind: "static", auth: target.auth };
2337
- try {
2338
- const { bearer, sentinelCreds } = await resolveAuthProvider().userCredentials({
2339
- store: workspaceSecretStore(target.root),
2340
- dir: userAuthStateDir(target.root, target.space),
2341
- space: target.space,
2342
- actor: CLI_USER_ACTOR,
2343
- });
2344
- const { owner, actor, lifecycleUid: uid } = principalFromBearer(bearer);
2345
- return { kind: "user", bearer, sentinelCreds, caller: { owner, actor, uid } };
2346
- }
2347
- catch (e) {
2348
- return { kind: "unavailable", reason: e instanceof Error ? e.message : String(e) };
2349
- }
2350
- }
2351
- async function componentEp(target, credential) {
2352
- await requireGreeting(target);
2353
- const id = newIdentity();
2354
- const user = credential.kind === "user";
2355
- // Static/open: ONE lifecycleUid minted and used both in the credential and as the endpoint's own
2356
- // option, matching `staticServiceAuth`. Two different uids here (a fresh mint per site) is what
2357
- // `permissionsFor: ... mint with opts.lifecycleUid` refuses: the lease read is bound to the uid
2358
- // baked into the credential, not the one the endpoint separately declares (#2073).
2359
- const staticUid = !user && credential.auth ? mintLifecycleUid() : undefined;
2360
- const ep = new CotalEndpoint({
2361
- space: target.space,
2362
- servers: target.server,
2363
- tls: target.tlsRequired,
2364
- // User: the signed-in login's bearer + sentinel; no lifecycleUid mint exists on this path (the
2365
- // bearer carries its own lifecycle claim).
2366
- ...(user
2367
- ? { bearer: credential.bearer, sentinelCreds: credential.sentinelCreds }
2368
- : {
2369
- creds: credential.auth && staticUid ? await mintCreds(credential.auth, id, "deployer", { lifecycleUid: staticUid }) : undefined,
2370
- lifecycleUid: staticUid,
2371
- }),
2372
- channels: [],
2373
- consume: false,
2374
- registerPresence: false,
2375
- watchPresence: false,
2376
- watchChannels: false,
2377
- // A bearer-source endpoint derives its id from the principal; only the minted path names one.
2378
- card: user ? { name: "status-components", kind: "endpoint" } : { id: id.id, name: "status-components", kind: "endpoint" },
2379
- });
2380
- ep.on("error", () => { });
2381
- // Same one-shot policy as renderSnapshot: the command grades the awaited service reply itself.
2382
- const ignoreComponentWarning = () => { };
2383
- ep.on("warning", ignoreComponentWarning);
2384
- await ep.start();
2385
- return { ep, close: () => ep.stop().catch(() => { }) };
2386
- }
2387
- /** Refuse before a probe dials a broker that does not greet on a socket this check owns. A broker
2388
- * that takes the connection and never greets, as a stopped one does, leaves the dial's socket open
2389
- * after its timeout, because the client library does not release a connection it never finished,
2390
- * and status could then never exit. */
2391
- async function requireGreeting(target) {
2392
- const stopped = stoppedLoopbackListener(target.server);
2393
- if (stopped !== undefined)
2394
- throw new Error(`the broker at ${brokerAddressForDisplay(target.server) ?? "an invalid broker address"} is served by process ${stopped}, which is stopped`);
2395
- if (!(await isReachable(target.server, { ...(target.tlsRequired ? { tls: true } : {}), timeoutMs: 3_000 })))
2396
- throw new Error(`the broker at ${brokerAddressForDisplay(target.server) ?? "an invalid broker address"} is not answering`);
2397
- }
2398
- /** The static arm's one-shot service instrument, unchanged from before the user-mode fix: a fresh
2399
- * identity, its minted deployer credential, and the caller triple on the SAME identity — a
2400
- * mismatched random actor would turn an authorized manager into a false no-answer. */
2401
- async function staticServiceAuth(auth) {
2402
- const serviceIdentity = newIdentity();
2403
- const serviceUid = mintLifecycleUid();
2404
- return {
2405
- creds: auth ? await mintCreds(auth, serviceIdentity, "deployer", { lifecycleUid: serviceUid }) : undefined,
2406
- caller: { owner: "local", actor: serviceIdentity.id, uid: serviceUid },
2407
- };
2408
- }
2409
- /** A service registration is the health target itself. Calling its `status` command through a
2410
- * generic endpoint does not work on this base because a passive status endpoint has no v0.4 caller
2411
- * rail; a one-shot standalone caller does. */
2412
- async function managerServiceHealth(target, auth) {
2413
- await requireGreeting(target);
2414
- const nc = await dialerFor(target.server)({
2415
- servers: target.server,
2416
- ...standaloneConnectOpts("bearer" in auth
2417
- ? { bearer: auth.bearer, sentinelCreds: auth.sentinelCreds, tls: target.tlsRequired }
2418
- : auth.creds
2419
- ? { creds: auth.creds, tls: target.tlsRequired }
2420
- : { tls: target.tlsRequired }),
2421
- maxReconnectAttempts: 0,
2422
- });
2423
- try {
2424
- const service = await resolveService(nc, target.space, "manager", auth.caller, { deadlineMs: 3_000, commands: ["status"] });
2425
- const response = await invokeRepairingSplit(nc, target.space, service, "status", undefined, { deadlineMs: 3_000 });
2426
- if (response.reply.ok !== true)
2427
- throw new EpEnvelopeError(response.reply.error.code === "unavailable" ? "unavailable" : "failed-precondition", response.reply.error.message);
2428
- return response.reply.data;
2429
- }
2430
- finally {
2431
- await drainAndClose(nc);
2432
- }
2433
- }
2434
- async function managerHealth(target, context, credential, broker) {
2435
- const record = processRecord(MANAGER_PIDFILE, context);
2436
- const facts = pidFacts(record);
2437
- // A corrupt or kernel-unreadable LOCAL record is neither evidence that the manager is absent nor
2438
- // permission to replace it with a network answer. Name that failed local control surface first.
2439
- if (processVerdict(record) === "refused") {
2440
- if (record.kind === "unattributable")
2441
- facts.push("unattributable pidfile");
2442
- if (record.kind === "unknown")
2443
- facts.push("pid liveness unestablishable");
2444
- return { name: "manager", verdict: "refused", facts };
2445
- }
2446
- if (record.kind === "dead")
2447
- facts.push("stale pidfile");
2448
- let close;
2449
- try {
2450
- if (credential.kind === "unavailable") {
2451
- // USER MODE without a usable login credential: say what is missing instead of probing bare.
2452
- // A bare probe of an authenticated broker reports an Authorization Violation that describes
2453
- // our own missing credential, not the manager's health. `refused` (not absent): the pass
2454
- // could not read this component's control surface, which is exactly what that verdict means.
2455
- facts.push(`probe needs the signed-in login: ${credential.reason}`);
2456
- return { name: "manager", verdict: "refused", facts };
2457
- }
2458
- const component = await componentEp(target, credential);
2459
- close = component.close;
2460
- // The lease sweep needs manager-bucket STREAM.INFO rows an interactive ledger bearer does not
2461
- // hold (provision.ts grants those to the manager/supervisor credentials only; the agent-view
2462
- // comment in core says exactly this). In user mode the SERVICE probe is the whole verdict, so
2463
- // the row says the lease axis is not checkable rather than reporting a refusal the broker
2464
- // makes about our own credential's shape.
2465
- let lease;
2466
- if (credential.kind === "user") {
2467
- facts.push("lease not checkable as the signed-in login (manager-bucket read is a host credential)");
2468
- }
2469
- else {
2470
- lease = await component.ep.readManagerLease();
2471
- if (lease)
2472
- facts.push(`lease holder ${lease.holder}`, `lease pid ${lease.pid}`);
2473
- else
2474
- facts.push("lease absent");
2475
- }
2476
- // Static/open keeps the one-shot instrument on the same identity as its caller triple.
2477
- // User mode calls manager status through the same control path `cotal spawn` uses.
2478
- // The login bearer does not carry that command for a spawn holder.
2479
- // Pin only while this machine's manager process is live. With no live process, an
2480
- // unpinned answer is this row's own verdict and the facts below name its instance.
2481
- const liveLocal = record.kind === "live";
2482
- const localId = credential.kind === "user" && liveLocal ? localManagerInstanceId(context.root, target.space) : undefined;
2483
- const served = credential.kind === "user"
2484
- ? await userManagerStatus(target, liveLocal ? localId : undefined)
2485
- : await managerServiceHealth(target, await staticServiceAuth(credential.auth));
2486
- // A live local process is serving only when its persisted instance answered. An unknown
2487
- // id, or a different one, cannot be attributed: refused, not not-serving, and the remote
2488
- // runtime stays off this row. The facts name the instance that answered.
2489
- if (credential.kind === "user" && liveLocal && (localId === undefined || served.instanceId !== localId)) {
2490
- const answered = typeof served.instanceId === "string" && served.instanceId.length > 0 ? served.instanceId : undefined;
2491
- facts.push(answered === undefined
2492
- ? "the manager answer named no instance, so it is not this machine's manager"
2493
- : localId === undefined
2494
- ? `answered by manager instance ${answered}; this machine's manager instance is not known`
2495
- : `answered by manager instance ${answered}, not this machine's manager ${localId}`);
2496
- return { name: "manager", verdict: "refused", facts };
2497
- }
2498
- facts.push(`service instance ${served.instanceId ?? "unreported"}`);
2499
- facts.push(`runtime ${served.runtime ?? "unreported"}`);
2500
- facts.push(...managerStopImpactFacts(served.stopImpact));
2501
- const reconcile = served.staticReconciliation;
2502
- if (!reconcile) {
2503
- facts.push("static reconciliation not reported by this manager build");
2504
- }
2505
- else {
2506
- facts.push(`static reconciliation ${String(reconcile.state ?? "unreported")}`);
2507
- if (typeof reconcile.lastSweep?.error === "string")
2508
- facts.push(`static sweep error=${reconcile.lastSweep.error}`);
2509
- for (const failure of reconcile.failures ?? []) {
2510
- const next = typeof failure.nextRetryAt === "string" ? ` nextRetryAt=${failure.nextRetryAt}` : "";
2511
- const remedy = typeof failure.remedy === "string" ? ` remedy=${failure.remedy}` : "";
2512
- facts.push(`static alias=${String(failure.alias ?? "unreported")} phase=${String(failure.phase ?? "unreported")} disposition=${String(failure.disposition ?? "unreported")}${next}${remedy}`);
2513
- }
2514
- }
2515
- facts.push("serve reachable");
2516
- // A manager service without its own liveness lease is a contradicted component surface, not a
2517
- // healthy one. It still reports reachability, but cannot claim the required lease holder. In
2518
- // USER MODE neither local axis is checkable from a participant machine (no pidfile under a
2519
- // discovered root, no manager-bucket read), so the manager's own typed service answer carries
2520
- // the verdict alone — reaching this line means it answered, which is the same single answer
2521
- // `ps` grades a user-mode manager by.
2522
- return { name: "manager", verdict: lease || credential.kind === "user" ? "serving" : "not-serving", facts };
2523
- }
2524
- catch (e) {
2525
- // A no-responder service rail or an absent manager registry is definitive no-service evidence.
2526
- // A dead local PID is absent even while its lease awaits expiry. Without a PID record, the
2527
- // lease still identifies an extant component; any other failed probe remains a refusal.
2528
- const noService = managerNoService(e);
2529
- facts.push(noService ? "serve no answer" : `serve probe refused: ${e.message}`);
2530
- if (broker.verdict === "absent" && processVerdict(record) === "absent")
2531
- return { name: "manager", verdict: "absent", facts };
2532
- if (!noService)
2533
- return { name: "manager", verdict: "refused", facts };
2534
- const liveRecord = record.kind === "live";
2535
- const hasLease = facts.some((fact) => fact.startsWith("lease holder "));
2536
- if (!liveRecord && !hasLease) {
2537
- try {
2538
- const journal = readStackJournal(context.root)?.journal;
2539
- const pin = verifyIdentityPin(localProcessPath(MANAGER_OMITTED, context));
2540
- const brokerRecord = processRecord(NATS_PIDFILE, context);
2541
- const omitted = journal?.space === context.space ? stackStartedWithoutManager(journal)
2542
- : pin.kind === "match" && brokerRecord.kind === "live" && pin.record.pid === brokerRecord.pid;
2543
- if (omitted)
2544
- return { name: "manager", verdict: "not-started", facts: [...facts, "started with --no-manager"] };
2545
- }
2546
- catch (error) {
2547
- return { name: "manager", verdict: "refused", facts: [...facts, `startup intent unreadable: ${error.message}`] };
2548
- }
2549
- }
2550
- return { name: "manager", verdict: liveRecord || (record.kind !== "dead" && hasLease) ? "not-serving" : "absent", facts };
2551
- }
2552
- finally {
2553
- await close?.();
2554
- }
2555
- }
2556
- /** True when a delivery-lease read failed because the lease stream/bucket is absent (#3046). */
2557
- export function deliveryLeaseAbsent(e) {
2558
- return isStreamNotFound(e);
2559
- }
2560
- /** Delivery owns two answers: its ready lease is its liveness/control surface; its latest explicit
2561
- * adoption report is the renewal record it writes through the manager-owned renewal pass. The
2562
- * latter is intentionally not inferred from credential mtime or process output. */
2563
- async function deliveryHealth(target, context, credential, brokerOffline) {
2564
- const record = processRecord(DELIVERY_PIDFILE, context);
2565
- const facts = pidFacts(record);
2566
- const stopped = processVerdict(record);
2567
- // The renewal record is PER-SPACE (#1850): read THIS space's record through the workspace seam
2568
- // (`renewalRecordPath` — the same keyed spelling the pidfiles use), never a hand-composed
2569
- // root-only path: a co-resident space's pass must not color this row.
2570
- let renewal;
2571
- try {
2572
- renewal = readRenewalRecord(context.root, context.space);
2573
- }
2574
- catch (e) {
2575
- facts.push(`renewal record unreadable: ${e.message}`);
2576
- return { name: "delivery", verdict: "refused", facts };
2577
- }
2578
- if (renewal?.adoption === undefined)
2579
- facts.push("renewal adoption not reported");
2580
- else
2581
- facts.push(renewal.adoption.ok ? "renewal adoption accepted" : `renewal adoption refused${renewal.adoption.error ? `: ${renewal.adoption.error}` : ""}`);
2582
- const renewalRefused = renewal?.adoption?.ok === false;
2583
- if (target.mode === "open" && record.kind === "absent" && !renewalRefused) {
2584
- if (brokerOffline)
2585
- return { name: "delivery", verdict: "not-started", facts: ["not used on an open mesh"] };
2586
- if (credential.kind === "unavailable")
2587
- return { name: "delivery", verdict: "refused", facts: [credential.reason] };
2588
- try {
2589
- const component = await componentEp(target, credential);
2590
- try {
2591
- if (!await component.ep.readDeliveryLease(0))
2592
- return { name: "delivery", verdict: "not-started", facts: ["not used on an open mesh"] };
2593
- }
2594
- finally {
2595
- await component.close();
2596
- }
2597
- }
2598
- catch (error) {
2599
- if (deliveryLeaseAbsent(error))
2600
- return { name: "delivery", verdict: "not-started", facts: ["not used on an open mesh"] };
2601
- return { name: "delivery", verdict: "refused", facts: [`lease probe refused: ${error instanceof Error ? error.message : String(error)}`] };
2602
- }
2603
- }
2604
- if (stopped) {
2605
- if (record.kind === "dead")
2606
- facts.push("stale pidfile");
2607
- if (record.kind === "unattributable")
2608
- facts.push("unattributable pidfile");
2609
- if (record.kind === "unknown")
2610
- facts.push("pid liveness unestablishable");
2611
- return { name: "delivery", verdict: renewalRefused ? "refused" : stopped, facts };
2612
- }
2613
- let close;
2614
- try {
2615
- if (credential.kind === "unavailable") {
2616
- // Same user-mode discipline as the manager row: never probe an authenticated broker bare.
2617
- facts.push("lease probe needs the signed-in login");
2618
- facts.push(credential.reason);
2619
- return { name: "delivery", verdict: "refused", facts };
2620
- }
2621
- const component = await componentEp(target, credential);
2622
- close = component.close;
2623
- const lease = await component.ep.readDeliveryLease(0);
2624
- // ONE classifier for both surfaces (#1576). `--components` was already right here and bare
2625
- // status was not, which is exactly how the two came to disagree about a mesh's health; routing
2626
- // both through `deliveryResponderFromLease` means a future change cannot fix one and leave the
2627
- // other green. The facts below stay as specific as they were.
2628
- //
2629
- // THE HOLDER IS PART OF THE QUESTION (#837). This surface already PRINTED `lease holder …` as a
2630
- // fact while grading on `ready` alone, so it displayed the evidence that its own verdict was
2631
- // wrong and did not read it. A ready record belonging to a daemon that is gone keeps this row
2632
- // `serving` for the rest of the bucket TTL.
2633
- const state = deliveryResponderFromLease(lease, await expectedDeliveryHolder(target));
2634
- if (!lease) {
2635
- facts.push("ready lease absent", `responder not bound - ${RESPONDER_UNBOUND_CONSEQUENCE}`);
2636
- return { name: "delivery", verdict: renewalRefused ? "refused" : "not-serving", facts };
2637
- }
2638
- facts.push(`lease holder ${lease.holder}`);
2639
- if (state === "stale") {
2640
- // Name WHOSE record it is against whom we expected, because this is the one verdict an
2641
- // operator cannot derive from the other facts on the line.
2642
- facts.push("ready, but held by a DIFFERENT daemon than this workspace launched (a dead holder's record expires on its own)");
2643
- facts.push(`responder not bound - ${RESPONDER_UNBOUND_CONSEQUENCE}`);
2644
- return { name: "delivery", verdict: renewalRefused ? "refused" : "not-serving", facts };
2645
- }
2646
- facts.push(state === "bound" ? "ready" : "starting (lease not ready)");
2647
- if (state !== "bound")
2648
- facts.push(`responder not bound - ${RESPONDER_UNBOUND_CONSEQUENCE}`);
2649
- return { name: "delivery", verdict: renewalRefused ? "refused" : state === "bound" ? "serving" : "not-serving", facts };
2650
- }
2651
- catch (e) {
2652
- // A live recorded daemon with no delivery lease bucket cannot be serving this build's delivery
2653
- // control surface. A denied/timed-out read is different: it is a refusal and must never read
2654
- // as a clean absence.
2655
- const noLeaseSurface = deliveryLeaseAbsent(e);
2656
- const msg = e instanceof Error ? e.message : String(e);
2657
- facts.push(noLeaseSurface ? "ready lease absent" : `lease probe refused: ${msg}`);
2658
- if (isCommandFailure(e) && e.remedy)
2659
- facts.push(e.remedy);
2660
- return { name: "delivery", verdict: renewalRefused || !noLeaseSurface ? "refused" : "not-serving", facts };
2661
- }
2662
- finally {
2663
- await close?.();
2664
- }
2665
- }
2666
- /** The web dashboard owns the HTTP listener and identifies itself through `/api/meta`, including
2667
- * the serving PID. A raw TCP success is insufficient: another program could own its port. */
2668
- async function webHealth(context) {
2669
- const record = processRecord(WEB_PIDFILE, context);
2670
- const facts = pidFacts(record);
2671
- const stopped = processVerdict(record);
2672
- if (record.kind === "absent") {
2673
- try {
2674
- const unsettled = serviceInstances(context.space, "web").map(instanceProjection).find((row) => row.recordedState !== "stopped" && ["gone", "foreign-pid", "previous-boot"].includes(row.observedProcess));
2675
- if (unsettled)
2676
- return { name: "web", verdict: "absent", facts: [`service instance ${unsettled.instanceId}`, `recorded ${unsettled.recordedState}`, unsettled.observedProcess] };
2677
- }
2678
- catch (e) {
2679
- return { name: "web", verdict: "refused", facts: [`service instance records unreadable: ${e.message}`] };
2680
- }
2681
- // An installation that cannot be read keeps the absent verdict rather than a clean zero.
2682
- let installed;
2683
- try {
2684
- installed = webInstalled();
2685
- }
2686
- catch {
2687
- installed = undefined;
2688
- }
2689
- if (installed === false)
2690
- return { name: "web", verdict: "not-installed", facts: ["optional"] };
2691
- if (installed === true)
2692
- return { name: "web", verdict: "not-started", facts: ["optional"] };
2693
- }
2694
- if (stopped) {
2695
- if (record.kind === "dead")
2696
- facts.push("stale pidfile");
2697
- if (record.kind === "unattributable")
2698
- facts.push("unattributable pidfile");
2699
- if (record.kind === "unknown")
2700
- facts.push("pid liveness unestablishable");
2701
- return { name: "web", verdict: stopped, facts };
2702
- }
2703
- // Probe only the address the dashboard recorded once it was listening, never one guessed from its
2704
- // command line or a default: no argv names the port `--port 0` bound. Without that record the
2705
- // control surface cannot be located, which is a probe refusal rather than a not-serving answer.
2706
- if (record.kind !== "live")
2707
- throw new Error("web component record lost its live pid after classification");
2708
- const pid = record.pid;
2709
- let source;
2710
- try {
2711
- source = webSessionSource(context, pid);
2712
- }
2713
- catch (e) {
2714
- return { name: "web", verdict: "refused", facts: [...facts, `service instance records unreadable: ${e.message}`] };
2715
- }
2716
- if (source.instance !== undefined)
2717
- facts.push(`service instance ${source.instance}`);
2718
- let bound;
2719
- try {
2720
- bound = webBoundAddress(source.path);
2721
- }
2722
- catch (e) {
2723
- return { name: "web", verdict: "refused", facts: [...facts, `${source.label} unreadable: ${e.message}`] };
2724
- }
2725
- if (!bound)
2726
- return { name: "web", verdict: "refused", facts: [...facts, "probe refused (no bound address recorded)"] };
2727
- try {
2728
- // The dashboard refuses an anonymous `/api/meta`; the readiness nonce is the one credential its
2729
- // gate accepts there, so without it a live dashboard could only ever answer 401.
2730
- const { status, meta } = await probeWebReadiness(bound.url, bound.readiness);
2731
- if (meta?.pid === pid)
2732
- return { name: "web", verdict: "serving", facts: [...facts, `host ${bound.host}`, `port ${bound.port}`, "http reachable"] };
2733
- return { name: "web", verdict: "not-serving", facts: [...facts, `host ${bound.host}`, `port ${bound.port}`, meta === undefined ? `HTTP ${status}` : "http identity mismatch"] };
2734
- }
2735
- catch {
2736
- // If the recorded address cannot identify the recorded PID, this component is present but not
2737
- // serving.
2738
- }
2739
- return { name: "web", verdict: "not-serving", facts: [...facts, `host ${bound.host}`, `port ${bound.port}`, "http not answered"] };
2740
- }
2741
- async function brokerHealth(target, store) {
2742
- const address = brokerAddressForDisplay(target.server);
2743
- if (address === undefined)
2744
- return { name: "broker", verdict: "refused", facts: ["registered address unavailable", "invalid broker address"] };
2745
- try {
2746
- const context = { root: target.root, space: target.space };
2747
- const journal = readStackJournal(target.root)?.journal;
2748
- const serverKey = brokerUrlKey(target.server);
2749
- if (journal?.space === target.space && brokerUrlKey(journal.server) === serverKey) {
2750
- const member = journal.members.find((row) => row.role === "broker");
2751
- const instance = serviceInstances(target.space, STACK_DEFINITION.broker).find((row) => row.name === member?.instanceId);
2752
- const observed = instance && instanceProjection(instance).observedProcess;
2753
- if (!instance || observed && ["gone", "foreign-pid", "previous-boot"].includes(observed))
2754
- return { name: "broker", verdict: "absent", facts: [`registered ${address}`, observed ?? "no local instance"] };
2755
- if (observed !== "running")
2756
- return { name: "broker", verdict: "refused", facts: [`registered ${address}`, `local process ${observed}`] };
2757
- }
2758
- else if (target.origin === "up" && target.mode !== "user" && (target.recordedServer === undefined || brokerUrlKey(target.recordedServer) === serverKey)) {
2759
- const record = processRecord(NATS_PIDFILE, context);
2760
- const verdict = processVerdict(record);
2761
- if (verdict)
2762
- return { name: "broker", verdict, facts: [`registered ${address}`, ...pidFacts(record), ...(record.kind === "dead" ? ["stale pidfile"] : [])] };
2763
- }
2764
- const storeFailure = store?.state === "write-failed" ? `store write failed: ${store.cause}`
2765
- : store?.state === "full" ? `store full: ${store.used} bytes exceeds ${store.cap} bytes at ${store.path}` : undefined;
2766
- if (target.mode !== "user") {
2767
- const preflight = await preflightTarget(target);
2768
- if (!preflight.ok)
2769
- return { name: "broker", verdict: "not-serving", facts: [`registered ${address}`, workspaceErrorParts({ kind: "preflight", failure: preflight.kind, target, pruned: false, ...(preflight.pid === undefined ? {} : { pid: preflight.pid }) }).message] };
2770
- return { name: "broker", verdict: storeFailure ? "not-serving" : "serving", facts: [`registered ${address}`, "reachable", ...(storeFailure ? [storeFailure] : [])] };
2771
- }
2772
- const reachable = await isReachable(target.server, target.tlsRequired ? { tls: true } : {});
2773
- if (storeFailure)
2774
- return { name: "broker", verdict: "not-serving", facts: [`registered ${address}`, reachable ? "reachable" : "unreachable", storeFailure] };
2775
- return reachable
2776
- ? { name: "broker", verdict: "serving", facts: [`registered ${address}`, "reachable"] }
2777
- : { name: "broker", verdict: "not-serving", facts: [`registered ${address}`, "unreachable"] };
2778
- }
2779
- catch (e) {
2780
- return { name: "broker", verdict: "refused", facts: [`registered ${address}`, `probe refused: ${e.message}`] };
2781
- }
2782
- }
2783
- async function printComponentHealth(selected, store, brokerUnreachable) {
2784
- section("Component Health");
2785
- if (!selected.ok) {
2786
- const error = selected.error;
2787
- const e = isWorkspaceTargetError(error) && error.code === "not-started" && error.details.root !== undefined && !error.details.rootMissing
2788
- ? unusableStackJournal(error.details.root) ?? error : error;
2789
- if (isCommandFailure(e) && (e.code === "SCHEMA_INVALID" || e.code === "PERMISSION_DENIED")) {
2790
- printComponent({ name: "target", verdict: "refused", facts: [e.code, e.message, ...(e.remedy ? [e.remedy] : [])] });
2791
- process.exitCode = COMPONENT_EXIT.refused;
2792
- return;
2793
- }
2794
- if (isMeshRegistryError(e)) {
2795
- printComponent({ name: "target", verdict: "refused", facts: ["SCHEMA_INVALID", e.message] });
2796
- process.exitCode = COMPONENT_EXIT.refused;
2797
- return;
2798
- }
2799
- if (isWorkspaceTargetError(e)) {
2800
- const verdict = e.code === "not-started" ? "absent" : "refused";
2801
- const { message, remedy } = workspaceErrorParts({ kind: "target", error: e });
2802
- printComponent({ name: "target", verdict, facts: [e.code, remedy === undefined ? message : `${message} - ${displayRemedy(remedy)}`] });
2803
- process.exitCode = COMPONENT_EXIT[verdict];
2804
- return;
2805
- }
2806
- if (e instanceof UnregisteredRoot) {
2807
- printComponent({ name: "target", verdict: "refused", facts: ["unregistered-root", `no space is registered or prepared here for ${e.root}`] });
2808
- process.exitCode = COMPONENT_EXIT.refused;
2809
- return;
2810
- }
2811
- throw e;
2812
- }
2813
- const target = selected.target;
2814
- const context = { root: target.root, space: target.space, userAuth: target.mode === "user" };
2815
- // ONE credential read for the whole pass (user mode resolves the signed-in login once; the
2816
- // static shape is just the target's own auth material), shared by the manager and delivery
2817
- // probes so the two rows cannot disagree about whose credential they probed with.
2818
- const credential = await componentCredential(target);
2819
- const broker = await brokerHealth(target, store);
2820
- const components = await Promise.all([
2821
- managerHealth(target, context, credential, broker),
2822
- deliveryHealth(target, context, credential, brokerUnreachable && broker.verdict === "absent"),
2823
- webHealth(context),
2824
- broker,
2825
- ]);
2826
- for (const component of components)
2827
- printComponent(component);
2828
- process.exitCode = componentExit(components);
2829
- }
2830
973
  //# sourceMappingURL=status.js.map