@tpsdev-ai/flair 0.62.0 → 0.63.1

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 (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
package/dist/cli.js CHANGED
@@ -24,12 +24,13 @@ import { flairConfigPath, flairDataDir } from "./lib/flair-paths.js";
24
24
  import { encodeRecordId } from "./lib/record-id-path.js";
25
25
  import { invalidAgentIdMessage, isValidAgentId } from "./lib/agent-id-rule.js";
26
26
  import { agentHomeEndpoint, decideProbedPairIdentity, readHttpInstanceIdentity, resolveTargetInstanceId, resolveTargetInstanceIdentity, stampAgentHome } from "./lib/agent-home.js";
27
- import { proveLocalInstancePair } from "./lib/local-instance-pair.js";
27
+ import { IncompleteInstancePairError, proveLocalInstancePair } from "./lib/local-instance-pair.js";
28
28
  import { httpBind, httpCorsAccessList, preserveHttpPortValue, preserveSecurePort, qualifySecureBindValue, DEFAULT_HTTP_BIND_HOST, } from "./lib/http-bind.js";
29
29
  import { isNodeKeyId, partitionKeyIds, } from "./doctor-client.js";
30
30
  import { cliBootPathWarning, } from "./install/global-bin-path.js";
31
- import { ApiHttpError, readSecretFileSecure, readAdminPassFileSecure, defaultAdminPassPath, defaultKeysDir, resolveLocalAdminPass, resolveAdminPassFromSources, ADMIN_PASS_FLAG, ADMIN_PASS_HELP, ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP, DEFAULT_ADMIN_USER, resolveAdminUser, resolveKeyPath, buildEd25519Auth, authFetch, KeyLoadError, isLocalBase, authedRequest, } from "./lib/auth-resolve.js";
31
+ import { ApiHttpError, ApiRequestOutcomeUnknown, isConnectPhaseFailure, readSecretFileSecure, readAdminPassFileSecure, defaultAdminPassPath, defaultKeysDir, resolveLocalAdminPass, addAdminPassOptions, DEFAULT_ADMIN_USER, resolveAdminUser, resolveKeyPath, buildEd25519Auth, authFetch, KeyLoadError, isLocalBase, authedRequest, } from "./lib/auth-resolve.js";
32
32
  import { resolveSigningIdentity, emitSigningIdentityDebug, } from "./lib/signing-identity.js";
33
+ import { AgentKeyPathRefusal, agentKeyPath, agentPubKeyPath } from "./lib/key-dir.js";
33
34
  import { entityFormatHint, parseEntitiesCsv } from "./lib/entity-vocab-cli.js";
34
35
  import { escapeXml, unescapeXml } from "./lib/xml-escape.js";
35
36
  import { assessLaunchdManagement, verifyLaunchdManagement, checkLaunchdPlistBeforeLoad, diagnoseLaunchdPlistPaths, isDetached, pickInstancePid, plistCarriesInlineAdminPassword, readLaunchctlJobState, readPlistProgramRefs, LAUNCHCTL_QUERY_TIMEOUT_MS, } from "./lib/launchd-management.js";
@@ -41,8 +42,10 @@ import { applyRepointPlan, repointSystemdUserUnit, restartOnLinux } from "./lib/
41
42
  // Aliased: this file also declares its own FileSnapshot (flair#2040's raw-bytes
42
43
  // snapshot for byte-exact restores); this is atomic-write's regular-file snapshot.
43
44
  import { snapshotRegularFile } from "./lib/atomic-write.js";
44
- import { preferVersionManagerAlias } from "./lib/node-alias-path.js";
45
+ import { homebrewOptAlias, preferVersionManagerAlias } from "./lib/node-alias-path.js";
45
46
  import { stabilizeMqttNetworkKeyOrder } from "./lib/stabilize-mqtt-network.js";
47
+ import { MQTT_DISABLED_CONFIG } from "./lib/mqtt-config.js";
48
+ import { FABRIC_OPS_PORT, resolveOpsUrlFromTarget } from "./lib/ops-url.js";
46
49
  import { detectOpsApiAllInterfacesBind } from "./lib/ops-api-bind.js";
47
50
  import { applyUpgradeHookConsent, runDoctorChecks, } from "./lib/doctor-run.js";
48
51
  import { classifyInstalledVersion, shouldPrintUpgradeLine, upgradeStatusSuffix } from "./lib/upgrade-status.js";
@@ -54,7 +57,7 @@ import { bindCli as bindFederationCli, register as registerFederation, signReque
54
57
  import { describeFederationPairHubAccessError, describeFederationPairLocalAccessError, rewriteFederationPairHubAccessError, rewriteFederationPairLocalAccessError, } from "./lib/federation-pair-access.js";
55
58
  import { bindCli as bindMemoryCli, register as registerMemory, categorizeForHygiene, HYGIENE_TEST_CONTENT_PATTERNS, } from "./commands/memory.js";
56
59
  import { bindCli as bindSoulCli, register as registerSoul, } from "./commands/soul.js";
57
- import { bindCli as bindRemCli, register as registerRem, } from "./commands/rem.js";
60
+ import { bindCli as bindRemCli, exitUnknownOutcome, register as registerRem, } from "./commands/rem.js";
58
61
  import { bindCli as bindFleetCli, register as registerFleet, } from "./commands/fleet.js";
59
62
  import { bindCli as bindMcpCli, register as registerMcp, } from "./commands/mcp.js";
60
63
  import { bindCli as bindIdpCli, register as registerIdp, } from "./commands/idp.js";
@@ -73,6 +76,7 @@ import { defaultReadProcessCmdline, defaultReadProcessCwd, findFlairPackageDir,
73
76
  import { applyPlainTreeUpgrade, userSystemdDir, } from "./lib/upgrade-plain-tree.js";
74
77
  import { bindCli as bindOrgeventCli, register as registerOrgevent, MAX_ORGEVENT_DETAIL_LENGTH, MAX_ORGEVENT_SUMMARY_LENGTH, publishOrgEvent, } from "./commands/orgevent.js";
75
78
  import { bindCli as bindAttentionCli, register as registerAttention, } from "./commands/attention.js";
79
+ import { registerHelp } from "./commands/help.js";
76
80
  import { bindCli as bindBootstrapCli, register as registerBootstrap, } from "./commands/bootstrap.js";
77
81
  import { bindCli as bindTestCli, register as registerTest, } from "./commands/test.js";
78
82
  import { bindCli as bindReembedCli, register as registerReembed, } from "./commands/reembed.js";
@@ -82,6 +86,7 @@ import { bindCli as bindMigrateHarnessMemoryCli, register as registerMigrateHarn
82
86
  import { bindCli as bindSearchCli, register as registerSearch, } from "./commands/search.js";
83
87
  import { bindCli as bindBackupCli, register as registerBackup, } from "./commands/backup.js";
84
88
  import { bindCli as bindRestoreCli, register as registerRestore, } from "./commands/restore.js";
89
+ import { bindCli as bindBackupApprovalCli, register as registerBackupApproval, } from "./commands/backup-approval.js";
85
90
  import { bindCli as bindExportCli, register as registerExport, } from "./commands/export.js";
86
91
  import { bindCli as bindImportCli, register as registerImport, } from "./commands/import.js";
87
92
  import { register as registerInspect, } from "./commands/inspect.js";
@@ -144,8 +149,8 @@ function shouldShowInlineSecretWarning(optValue, fromEnv, secretFlagNames, flagN
144
149
  }
145
150
  // ─── Defaults ────────────────────────────────────────────────────────────────
146
151
  const DEFAULT_PORT = 19926;
147
- const DEFAULT_OPS_PORT = 19925;
148
- const FABRIC_OPS_PORT = 9925;
152
+ // DEFAULT_OPS_PORT and FABRIC_OPS_PORT live in src/lib/ops-url.ts with
153
+ // resolveOpsUrlFromTarget, shared with the deploy channel (src/deploy.ts).
149
154
  // DEFAULT_ADMIN_USER + resolveAdminUser (flag > FLAIR_ADMIN_USER env > "admin")
150
155
  // live in src/lib/auth-resolve.ts — imported above (flair#1345).
151
156
  //
@@ -929,50 +934,12 @@ export const SHARED_IDENTITY_FLAGS = {
929
934
  agent: "--agent <id>",
930
935
  };
931
936
  function addSharedCredentialOptions(cmd) {
932
- return cmd
933
- .option(ADMIN_PASS_FLAG, ADMIN_PASS_HELP)
934
- .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
937
+ return addAdminPassOptions(cmd)
935
938
  .option(SHARED_CREDENTIAL_FLAGS.adminUser, "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)");
936
939
  }
937
940
  function addSharedIdentityOption(cmd) {
938
941
  return cmd.option(SHARED_IDENTITY_FLAGS.agent, "Agent ID (or set FLAIR_AGENT_ID env)");
939
942
  }
940
- /**
941
- * Resolve the admin password for the commands that declare the shared
942
- * credential flags, through the ONE resolver (`resolveAdminPassFromSources` —
943
- * the same one `federation token`/`pair` use, flair#1873/#1910). The resolved
944
- * value is written back into the `adminPass` slot every call site reads.
945
- *
946
- * Precedence, as the usage text states: an explicit `--admin-pass-file` or
947
- * `--admin-pass` over the ambient `FLAIR_ADMIN_PASS`/`HDB_ADMIN_PASSWORD`.
948
- * Supplying BOTH the file and the flag is a usage error (it used to let the
949
- * flag silently win); a file that is missing, empty or group-/world-readable
950
- * is refused naming the path and its mode. Never prints the value.
951
- */
952
- function applyAdminPassFile(opts) {
953
- try {
954
- // envPass is DELIBERATELY omitted: this wrapper folds an explicit
955
- // `--admin-pass-file` (or `--admin-pass`) into `opts.adminPass`, and each
956
- // call site keeps its own `opts.adminPass ?? FLAIR_ADMIN_PASS` fallback —
957
- // exactly main's shape. Resolving the ambient env HERE would pre-fill
958
- // `opts.adminPass`, and a call site that threads it as `explicitAdminPass`
959
- // (memory add, soul, …) would then send ambient admin Basic auth where it
960
- // used to send nothing and let the `--agent`/env tier decide (flair#1910
961
- // round 2: `federation sync` merged nothing in the mixed-version compat
962
- // lane because `memory add --agent X` with FLAIR_ADMIN_PASS set signed as
963
- // admin, not as X).
964
- const pass = resolveAdminPassFromSources({
965
- adminPassFile: opts.adminPassFile,
966
- adminPass: opts.adminPass,
967
- });
968
- if (pass)
969
- opts.adminPass = pass;
970
- }
971
- catch (err) {
972
- console.error(`Error: ${err.message}`);
973
- process.exit(1);
974
- }
975
- }
976
943
  // Ops port resolution: valid --ops-port flag > FLAIR_OPS_PORT env > config opsPort > httpPort - 1.
977
944
  // An explicit invalid --ops-port refuses; it never falls through to another rung.
978
945
  //
@@ -1049,17 +1016,19 @@ export function decideAgentHomeTarget(i) {
1049
1016
  throw new Error(`${AMBIGUOUS_INSTANCE_TARGET_ERROR}: the target (HTTP port ${httpPort}, ops port ${opsPort}) conflicts with the configured pair — `
1050
1017
  + `the config pairs HTTP ${configuredHttp} with ops ${configuredOps}. ${remedy}`);
1051
1018
  }
1052
- return { httpPort, opsPort };
1019
+ // Both sides equal the configured pair (or neither does — only when the
1020
+ // caller named both, since an unnamed port is taken from the pair).
1021
+ return { httpPort, opsPort, pairBound: httpMatches && opsMatches };
1053
1022
  }
1054
1023
  const opsNamed = namedOps !== null;
1055
1024
  if (httpNamed !== opsNamed) {
1056
1025
  const [named, namedPort, other] = httpNamed ? ["HTTP", httpPort, "ops"] : ["ops", namedOps, "HTTP"];
1057
- throw new Error(`${AMBIGUOUS_INSTANCE_TARGET_ERROR}: only the ${named} port (${namedPort}) was named, and no complete port pair could be resolved from config `
1058
- + `(HTTP ${configuredHttp ?? "none"}, ops ${configuredOps ?? "none"}) to take the ${other} port from, so the two ports could address different instances. ${remedy}`);
1026
+ throw new IncompleteInstancePairError(`${AMBIGUOUS_INSTANCE_TARGET_ERROR}: only the ${named} port (${namedPort}) was named, and no complete port pair could be resolved from config `
1027
+ + `(HTTP ${configuredHttp ?? "none"}, ops ${configuredOps ?? "none"}) to take the ${other} port from, so the two ports could address different instances. ${remedy}`, named, other);
1059
1028
  }
1060
1029
  if (namedOps !== null)
1061
- return { httpPort, opsPort: namedOps };
1062
- return { httpPort, opsPort: i.deriveOps() };
1030
+ return { httpPort, opsPort: namedOps, pairBound: false };
1031
+ return { httpPort, opsPort: i.deriveOps(), pairBound: false };
1063
1032
  }
1064
1033
  /**
1065
1034
  * The ports `flair agent stamp-home` and `flair principal add` address
@@ -1098,7 +1067,7 @@ export function resolveAgentHomeTarget(opts, httpPortOverride) {
1098
1067
  const n = Number(opts.opsPort);
1099
1068
  if (!(Number.isInteger(n) && n >= 1 && n <= 65535)) {
1100
1069
  // An invalid --ops-port is refused by resolveOpsPort, which exits.
1101
- return { httpPort, opsPort: resolveOpsPort(opts) };
1070
+ return { httpPort, opsPort: resolveOpsPort(opts), pairBound: false };
1102
1071
  }
1103
1072
  namedOps = n;
1104
1073
  }
@@ -1362,26 +1331,9 @@ export function buildOperationsApiConfig(opsPort, opsSocket, opsBindHost) {
1362
1331
  network: { port: opsNetworkPortValue(opsBindHost, opsPort), cors: true, domainSocket: opsSocket },
1363
1332
  };
1364
1333
  }
1365
- /**
1366
- * Harper config that fully disables the MQTT broker (flair#1586).
1367
- *
1368
- * Flair does not use MQTT. Harper's mqtt component (server/mqtt.ts
1369
- * `handleApplication`) binds a TCP listener on `mqtt.network.port` (1883) and
1370
- * a TLS listener on `mqtt.network.securePort` (8883) whenever EITHER is truthy
1371
- * (`if (port || securePort)`), plus a WebSocket upgrade path when
1372
- * `mqtt.webSocket` is true. Nulling only `network.port` leaves
1373
- * `network.securePort` at its 8883 default, so the TLS listener still binds.
1374
- * Fully disabling MQTT requires nulling BOTH ports and turning off the
1375
- * WebSocket path.
1376
- *
1377
- * Note: config-root.schema.json still documents a flat `mqtt.port` /
1378
- * `mqtt.securePort`, but the runtime reads the nested `mqtt.network.*` form
1379
- * (see static/defaultConfig.yaml) — the flat keys are stale.
1380
- */
1381
- const MQTT_DISABLED_CONFIG = {
1382
- network: { port: null, securePort: null },
1383
- webSocket: false,
1384
- };
1334
+ // MQTT_DISABLED_CONFIG — the Harper `mqtt` section with every MQTT listener
1335
+ // off — lives in src/lib/mqtt-config.ts, shared with the component-deployment
1336
+ // channel (src/deploy.ts) and `flair doctor`.
1385
1337
  /**
1386
1338
  * Build the flair-owned environment overrides for a DIRECT (non-launchd)
1387
1339
  * Harper spawn (flair#863) — shared by `flair start`'s fallback path and
@@ -1848,17 +1800,6 @@ function resolveTarget(opts) {
1848
1800
  function resolveOpsTarget(opts) {
1849
1801
  return opts.opsTarget || process.env.FLAIR_OPS_TARGET || undefined;
1850
1802
  }
1851
- /** Derive the ops API URL from a Flair base URL.
1852
- * https with effective port 443 (no explicit port, or explicit :443): returns
1853
- * <host>:9925 (FABRIC_OPS_PORT) — the Fabric managed case where port-1/:442
1854
- * is a dead-end.
1855
- * All other cases unchanged:
1856
- * https with non-443 explicit port → port-1 (self-hosted TLS: 19926→19925, 8443→8442)
1857
- * http with explicit port → port-1 (19926→19925)
1858
- * http with no port → DEFAULT_OPS_PORT (19925)
1859
- * Bare hosts are normalised to https:// (effective-443 → Fabric path).
1860
- * Throws on unparseable URLs or out-of-range ports.
1861
- */
1862
1803
  /** Compute the effective ops API URL for remote commands.
1863
1804
  * - If --ops-target is set, use it directly (no derivation).
1864
1805
  * - Else if --target is set, derive ops URL via resolveOpsUrlFromTarget.
@@ -1873,37 +1814,6 @@ function resolveEffectiveOpsUrl(opts) {
1873
1814
  return resolveOpsUrlFromTarget(target);
1874
1815
  return undefined;
1875
1816
  }
1876
- function resolveOpsUrlFromTarget(targetUrl) {
1877
- // Normalise bare hosts: add https:// prefix so URL parser can handle them.
1878
- const normalised = targetUrl.includes("://") ? targetUrl : `https://${targetUrl}`;
1879
- const url = new URL(normalised);
1880
- // https target with effective port 443 (no explicit port, or explicit :443):
1881
- // this is the Fabric managed case — the ops API is on the well-known Fabric
1882
- // ops port, never REST-adjacent. The port-1 / :442 logic is a dead-end here.
1883
- if (url.protocol === "https:" && (url.port === "" || url.port === "443")) {
1884
- url.port = String(FABRIC_OPS_PORT);
1885
- return url.toString().replace(/\/$/, "");
1886
- }
1887
- // All other cases: unchanged port-1 convention.
1888
- // https with non-443 explicit port → port-1 (self-hosted TLS: 19926→19925, 8443→8442)
1889
- // http with explicit port → port-1 (19926→19925)
1890
- // http with no port → DEFAULT_OPS_PORT (19925)
1891
- const port = parseInt(url.port, 10);
1892
- if (!isNaN(port) && port > 0 && port <= 65535) {
1893
- const opsPort = port - 1;
1894
- if (opsPort < 1)
1895
- throw new Error(`Derived ops port ${opsPort} is out of range; target port must be > 1`);
1896
- url.port = String(opsPort);
1897
- return url.toString().replace(/\/$/, "");
1898
- }
1899
- // No valid explicit port — reject port 0 or out-of-range
1900
- if (url.port !== "" && url.port !== undefined) {
1901
- throw new Error(`Invalid target port: ${url.port} (must be 1-65535)`);
1902
- }
1903
- // No explicit port on http — use the default ops port.
1904
- url.port = String(DEFAULT_OPS_PORT);
1905
- return url.toString().replace(/\/$/, "");
1906
- }
1907
1817
  /**
1908
1818
  * Persist the instance coordinates other commands need to find and re-assert
1909
1819
  * this install (flair#863).
@@ -1959,10 +1869,10 @@ function persistDefaultInstallCoordinates(dataDir, port, opsPort, opsBind, httpB
1959
1869
  writeConfig(port, opsPort, opsBind, configPath(), httpBind);
1960
1870
  }
1961
1871
  function privKeyPath(agentId, keysDir) {
1962
- return join(keysDir, `${agentId}.key`);
1872
+ return agentKeyPath(keysDir, agentId);
1963
1873
  }
1964
1874
  function pubKeyPath(agentId, keysDir) {
1965
- return join(keysDir, `${agentId}.pub`);
1875
+ return agentPubKeyPath(keysDir, agentId);
1966
1876
  }
1967
1877
  function flairPackageDir() {
1968
1878
  // dist/cli.js → package root (one level up from dist/)
@@ -2171,16 +2081,37 @@ async function api(method, path, body, options) {
2171
2081
  adminUser: options?.adminUser,
2172
2082
  agentIdSource: options?.agentIdSource,
2173
2083
  signedOnly: options?.signedOnly,
2084
+ refuseRedirects: options?.refuseRedirects,
2085
+ deadlineMs: options?.deadlineMs,
2086
+ deadlineSource: options?.deadlineSource,
2087
+ tolerateUnparsedSuccessBody: options?.tolerateUnparsedSuccessBody,
2174
2088
  };
2089
+ // The port the operator wrote in ~/.flair/config.yaml, when it differs from
2090
+ // the resolved one and no explicit base was given: the only port a
2091
+ // connect-phase failure may fall back to (flair#1719).
2092
+ const altPort = hasExplicitBase ? null : alternateConfiguredLocalPort({});
2093
+ const readOnly = method.toUpperCase() === "GET" || method.toUpperCase() === "HEAD";
2094
+ // Following a redirect can start another connection attempt; a connect-phase
2095
+ // failure there could cause the original write to be replayed on the alternate.
2096
+ // Refusing it (redirect: "manual") yields a named HTTP 3xx error, which is
2097
+ // never fallback-eligible because it is not a connect-phase failure.
2098
+ if (altPort !== null && !readOnly)
2099
+ requestOptions.refuseRedirects = true;
2175
2100
  try {
2176
2101
  return await authedRequest(method, path, body, requestOptions);
2177
2102
  }
2178
2103
  catch (err) {
2104
+ // A write that reached its deadline may have committed. Never replay it
2105
+ // against another port: that is a blind retry of an unknown outcome.
2106
+ // pinned by test/unit/request-deadline-2789.test.ts "a write whose deadline
2107
+ // expires exits 3 and the alternate configured port receives no request"
2108
+ if (err instanceof ApiRequestOutcomeUnknown)
2109
+ throw err;
2179
2110
  // flair#1719: the resolved port came from Harper's boot record, which can
2180
2111
  // be stale for the default install. Before surfacing a connect failure,
2181
- // try the port the operator actually wrote in ~/.flair/config.yaml.
2182
- const altPort = hasExplicitBase ? null : alternateConfiguredLocalPort({});
2183
- if (altPort !== null && isFederationStatusConnectFailure(err)) {
2112
+ // try the port the operator actually wrote in ~/.flair/config.yaml. Only a
2113
+ // connect-phase failure qualifies (flair#2869).
2114
+ if (altPort !== null && isConnectPhaseFailure(err)) {
2184
2115
  const altUrl = `http://127.0.0.1:${altPort}`;
2185
2116
  try {
2186
2117
  return await authedRequest(method, path, body, { ...requestOptions, baseUrl: altUrl });
@@ -2193,15 +2124,11 @@ async function api(method, path, body, options) {
2193
2124
  }
2194
2125
  }
2195
2126
  /**
2196
- * Turn undici/Node's bare `TypeError: fetch failed` into a sentence naming the
2197
- * actor (the Flair instance URL), the state (no HTTP response) and a remedy
2198
- * the operator can act on — flair#1719 requirement 3. Non-connect errors
2199
- * (HTTP 401/403/5xx, auth failures) pass through unchanged so callers keep
2200
- * their own handling. The `flairFriendly` marker lets the top-level CLI entry
2201
- * print just the message instead of a stack.
2127
+ * Give connect-phase errors a URL and remedy; pass other errors through.
2128
+ * `flairFriendly` prints the message without a stack.
2202
2129
  */
2203
2130
  function describeApiConnectFailure(err, url) {
2204
- if (!isFederationStatusConnectFailure(err))
2131
+ if (!isConnectPhaseFailure(err))
2205
2132
  return err;
2206
2133
  const friendly = new Error(`Cannot reach the Flair instance at ${url} — the connection failed (no HTTP response).\n`
2207
2134
  + ` Start it with \`flair start\`, or point this command at the right instance with `
@@ -2269,7 +2196,7 @@ async function waitForHealth(httpPort, adminUser, adminPass, timeoutMs, beforeRe
2269
2196
  /** `<keysDir>/<id>.key` — the fallback key location for tests and non-standard
2270
2197
  * key dirs; the standard `resolveKeyPath` lookup is always tried first. */
2271
2198
  function fallbackKeyPath(keysDir, agentId) {
2272
- const candidate = join(keysDir, `${agentId}.key`);
2199
+ const candidate = agentKeyPath(keysDir, agentId);
2273
2200
  return existsSync(candidate) ? candidate : null;
2274
2201
  }
2275
2202
  /**
@@ -2304,7 +2231,7 @@ export async function resolveProbeSigningIdentity(baseUrl, agentIdOpt, keysDir)
2304
2231
  catch { /* keysDir missing */ }
2305
2232
  const candidates = keyFiles
2306
2233
  .map((f) => f.replace(/\.key$/, ""))
2307
- .filter((id) => !isNodeKeyId(id, keysDir));
2234
+ .filter((id) => isValidAgentId(id) && !isNodeKeyId(id, keysDir));
2308
2235
  if (candidates.length === 0) {
2309
2236
  return { agentId: null, source: "none", detail: "no agent id or key found" };
2310
2237
  }
@@ -2658,11 +2585,19 @@ export async function probeFlairReachable(url, timeoutMs = 2000) {
2658
2585
  * server naming the agent unknown is a reliable, actionable signal.
2659
2586
  */
2660
2587
  export async function checkAgentRegistered(baseUrl, agentId, keysDir) {
2661
- let keyPath = resolveKeyPath(agentId);
2662
- if (!keyPath) {
2663
- const candidate = join(keysDir, `${agentId}.key`);
2664
- if (existsSync(candidate))
2665
- keyPath = candidate;
2588
+ let keyPath;
2589
+ try {
2590
+ keyPath = resolveKeyPath(agentId);
2591
+ if (!keyPath) {
2592
+ const candidate = agentKeyPath(keysDir, agentId);
2593
+ if (existsSync(candidate))
2594
+ keyPath = candidate;
2595
+ }
2596
+ }
2597
+ catch (err) {
2598
+ if (err instanceof AgentKeyPathRefusal)
2599
+ return { state: "no-key", detail: err.message };
2600
+ throw err;
2666
2601
  }
2667
2602
  if (!keyPath) {
2668
2603
  return { state: "no-key", detail: `no local key for agent '${agentId}' to sign the check` };
@@ -3139,11 +3074,81 @@ async function assertSingleInstanceRowAfterWrite(endpoint, expectedId) {
3139
3074
  if (verification.kind === "not-verified")
3140
3075
  throw new Error(instanceWriteNotVerifiedMessage(expectedId, verification.found));
3141
3076
  }
3142
- // ─── Provision Flair on Harper Fabric ──────────────────────────────────────
3143
- //
3144
- // Atomic provisioning for a fresh Harper Fabric cluster: builds a deploy
3145
- // tarball with .env baked in, deploys via ops API, waits for restart, and
3146
- // creates the super_user admin account.
3077
+ const OPS_API_ERROR_DESCRIPTIONS = {
3078
+ "already-exists": "the user already exists",
3079
+ "not-permitted": "the operation is not permitted for this role",
3080
+ "authentication-failed": "authentication failed",
3081
+ };
3082
+ const OPS_API_REFUSAL_DESCRIPTION = "the ops API refused the request (details withheld)";
3083
+ /**
3084
+ * Harper's exact wording for each category, anchored to the whole field value.
3085
+ * These strings are read here, for classification only, and are never copied
3086
+ * into a message.
3087
+ */
3088
+ const OPS_API_ERROR_PATTERNS = [
3089
+ ["already-exists", /^User (.+) already exists$/],
3090
+ ["not-permitted", /^This operation is not authorized due to role restrictions and\/or invalid database items$/],
3091
+ ["authentication-failed", /^Login failed$/],
3092
+ ];
3093
+ /** The status (and, for already-exists, operation) each category is defined by. */
3094
+ function categoryMatches(category, status, operation) {
3095
+ switch (category) {
3096
+ case "already-exists":
3097
+ return status === 409 && operation === "add_user";
3098
+ case "not-permitted":
3099
+ return status === 403;
3100
+ case "authentication-failed":
3101
+ return status === 401;
3102
+ }
3103
+ }
3104
+ /** A non-2xx ops API response, reduced to a category and a fixed description. */
3105
+ export class OpsApiError extends Error {
3106
+ status;
3107
+ operation;
3108
+ category;
3109
+ constructor(status, operation, category) {
3110
+ super(`Ops API call failed (${status}) for '${operation}': ` +
3111
+ (category === null ? OPS_API_REFUSAL_DESCRIPTION : OPS_API_ERROR_DESCRIPTIONS[category]));
3112
+ this.name = "OpsApiError";
3113
+ this.status = status;
3114
+ this.operation = operation;
3115
+ this.category = category;
3116
+ }
3117
+ }
3118
+ function classifyOpsApiError(status, operation, body, text) {
3119
+ // Classify the parsed body's `error` string, or `message` only when the body
3120
+ // has no `error` key at all, and only when the status (and, for already-exists,
3121
+ // operation) is the category's own. Anything else — a non-JSON body, a value
3122
+ // that is not a string, another field, another status, or another operation for
3123
+ // already-exists — is unclassified. The value is never returned or printed.
3124
+ let parsed;
3125
+ try {
3126
+ parsed = JSON.parse(text);
3127
+ }
3128
+ catch {
3129
+ return null;
3130
+ }
3131
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
3132
+ return null;
3133
+ const record = parsed;
3134
+ const value = "error" in record ? record.error : record.message;
3135
+ if (typeof value !== "string")
3136
+ return null;
3137
+ for (const [category, pattern] of OPS_API_ERROR_PATTERNS) {
3138
+ if (!categoryMatches(category, status, operation))
3139
+ continue;
3140
+ const match = pattern.exec(value);
3141
+ if (match === null)
3142
+ continue;
3143
+ if (category === "already-exists") {
3144
+ // Match the submitted username, not another user named by the response.
3145
+ if (typeof body.username !== "string" || match[1] !== body.username)
3146
+ return null;
3147
+ }
3148
+ return category;
3149
+ }
3150
+ return null;
3151
+ }
3147
3152
  export async function callOpsApi(opsUrl, body, user, pass) {
3148
3153
  const url = `${opsUrl.replace(/\/$/, "")}/`;
3149
3154
  const auth = Buffer.from(`${user}:${pass}`).toString("base64");
@@ -3157,14 +3162,35 @@ export async function callOpsApi(opsUrl, body, user, pass) {
3157
3162
  });
3158
3163
  }
3159
3164
  catch (err) {
3160
- const message = err instanceof Error ? err.message : String(err);
3161
- throw new Error(`ops API unreachable at ${opsUrl} (derived from --target). ` +
3162
- `Set --ops-target or FLAIR_OPS_TARGET to override. ` +
3163
- `(${message})`);
3165
+ let target = "the configured ops target";
3166
+ try {
3167
+ const parsed = new URL(opsUrl);
3168
+ if (parsed.protocol === "http:" || parsed.protocol === "https:")
3169
+ target = parsed.origin;
3170
+ }
3171
+ catch { }
3172
+ let category = "no response";
3173
+ const seen = new Set();
3174
+ for (let current = err; current && typeof current === "object" && !seen.has(current);) {
3175
+ seen.add(current);
3176
+ const failure = current;
3177
+ if (failure.code === "ECONNREFUSED" || failure.code === "ConnectionRefused") {
3178
+ category = "connection refused";
3179
+ break;
3180
+ }
3181
+ if (failure.name === "TimeoutError" || failure.code === "ETIMEDOUT" || failure.code === "UND_ERR_CONNECT_TIMEOUT") {
3182
+ category = "timed out";
3183
+ break;
3184
+ }
3185
+ current = failure.cause;
3186
+ }
3187
+ throw new Error(`ops API request got no response from ${target} (${category}). ` +
3188
+ `Set --ops-target or FLAIR_OPS_TARGET to override.`);
3164
3189
  }
3165
3190
  if (!res.ok) {
3166
3191
  const text = await res.text().catch(() => "");
3167
- throw new Error(`Ops API call failed (${res.status}): ${text}`);
3192
+ const operation = typeof body.operation === "string" ? body.operation : "unknown";
3193
+ throw new OpsApiError(res.status, operation, classifyOpsApiError(res.status, operation, body, text));
3168
3194
  }
3169
3195
  return res.json();
3170
3196
  }
@@ -3261,10 +3287,79 @@ export async function waitForFlairRestart(targetUrl, maxWaitMs = 30_000) {
3261
3287
  }
3262
3288
  throw new Error(`Flair did not respond within ${maxWaitMs / 1000}s`);
3263
3289
  }
3264
- export async function provisionFabric(target, opsTarget, clusterAdminUser, clusterAdminPass, flairAdminPass) {
3290
+ export async function provisionFabric(target, opsTarget, clusterAdminUser, clusterAdminPass, flairAdminPass, hooks = {}) {
3265
3291
  const projectRoot = process.cwd();
3266
- // 1. Build and deploy component tarball. `target` is the served URL this
3267
- // function verifies against in step 2 — the same value the component must
3292
+ // 1. Read the cluster's existing users BEFORE any cluster write. The answer
3293
+ // decides whether this run attempts to set `admin`'s password, and a read that fails
3294
+ // must refuse: treating an unknown as "not a super_user" would go on to
3295
+ // change a cluster we could not read.
3296
+ console.log("Checking existing cluster users via ops API...");
3297
+ let userInfo;
3298
+ try {
3299
+ userInfo = await callOpsApi(opsTarget, {
3300
+ operation: "list_users",
3301
+ }, clusterAdminUser, clusterAdminPass);
3302
+ }
3303
+ catch (err) {
3304
+ const message = err instanceof Error ? err.message : String(err);
3305
+ throw new Error(`Could not read the cluster's existing users, so provisioning refused to change anything: ${message}`);
3306
+ }
3307
+ // list_users returns an array of user objects with role/permission info.
3308
+ // A success response of any other shape is unknown, and an unknown is never
3309
+ // "no super_user": refuse before the password is saved or anything is written.
3310
+ if (!Array.isArray(userInfo)) {
3311
+ throw new Error("The cluster's list_users response was not an array, so provisioning refused to change anything");
3312
+ }
3313
+ const users = userInfo;
3314
+ const usernames = [];
3315
+ const superUsers = [];
3316
+ for (const record of users) {
3317
+ const username = record !== null && typeof record === "object" && !Array.isArray(record)
3318
+ ? typeof record.username === "string"
3319
+ ? record.username
3320
+ : typeof record.user?.username === "string"
3321
+ ? record.user.username
3322
+ : undefined
3323
+ : undefined;
3324
+ // A record with no readable username could be the cluster administrator,
3325
+ // so it still refuses before anything is staged or written.
3326
+ if (username === undefined || username === "") {
3327
+ throw new Error("The cluster's list_users response contained a record with no readable username, so provisioning refused to change anything");
3328
+ }
3329
+ usernames.push(username);
3330
+ // Only the authenticated cluster administrator and `admin` decide
3331
+ // provisioning, so only their records need a boolean super_user. Harper
3332
+ // accepts a role that holds database grants and no super_user flag, and
3333
+ // such an unrelated user must not make remote init refuse.
3334
+ if (username === clusterAdminUser || username === DEFAULT_ADMIN_USER) {
3335
+ const permission = record?.role?.permission ?? record?.permission;
3336
+ const superUser = permission?.super_user;
3337
+ if (typeof superUser !== "boolean") {
3338
+ throw new Error("The cluster's list_users response contained a malformed record for a user that decides provisioning, so provisioning refused to change anything");
3339
+ }
3340
+ superUsers.push(superUser);
3341
+ }
3342
+ else {
3343
+ superUsers.push(undefined);
3344
+ }
3345
+ }
3346
+ const clusterAdminRecords = usernames.filter((name) => name === clusterAdminUser).length;
3347
+ if (clusterAdminRecords !== 1) {
3348
+ throw new Error(`The cluster's list_users response does not confirm the cluster administrator '${clusterAdminUser}' exactly once, so provisioning refused to change anything`);
3349
+ }
3350
+ const adminRecords = usernames.filter((name) => name === DEFAULT_ADMIN_USER).length;
3351
+ if (adminRecords > 1) {
3352
+ throw new Error(`The cluster's list_users response lists more than one Flair administrator '${DEFAULT_ADMIN_USER}' record, so provisioning refused to change anything`);
3353
+ }
3354
+ const clusterAdminIndex = usernames.indexOf(clusterAdminUser);
3355
+ const clusterAdminIsSuperUser = superUsers[clusterAdminIndex] === true;
3356
+ const adminExists = adminRecords === 1;
3357
+ if (!clusterAdminIsSuperUser) {
3358
+ // Save the password before anything on the cluster changes.
3359
+ hooks.beforeAdminPasswordApplied?.();
3360
+ }
3361
+ // 2. Build and deploy component tarball. `target` is the served URL this
3362
+ // function verifies against in step 3 — the same value the component must
3268
3363
  // advertise in OAuth/A2A discovery, so it is what FLAIR_PUBLIC_URL is set from
3269
3364
  // (flair#1005). A loopback target supplies nothing: see resolveDeployPublicUrl.
3270
3365
  console.log("Building deploy tarball...");
@@ -3276,62 +3371,33 @@ export async function provisionFabric(target, opsTarget, clusterAdminUser, clust
3276
3371
  payload: tarballB64,
3277
3372
  restart: "rolling",
3278
3373
  }, clusterAdminUser, clusterAdminPass);
3279
- // 2. Wait for restart
3374
+ // 3. Wait for restart
3280
3375
  console.log("Waiting for Flair to restart...");
3281
3376
  await waitForFlairRestart(target);
3282
3377
  console.log("Flair is running ✓");
3283
- // 3. Provision Harper super_user
3378
+ // 4. Provision Harper super_user
3284
3379
  // Since custom-admin-username support is merged, the username doesn't have to be "admin".
3285
3380
  // We can use the cluster-admin user directly if it's already a super_user.
3286
- // Check if cluster admin is already a super_user first:
3287
- let clusterAdminIsSuperUser = false;
3288
- try {
3289
- const userInfo = await callOpsApi(opsTarget, {
3290
- operation: "list_users",
3291
- }, clusterAdminUser, clusterAdminPass);
3292
- // list_users returns an array of user objects with role/permission info
3293
- const users = Array.isArray(userInfo) ? userInfo : [];
3294
- const adminRecord = users.find((u) => u.username === clusterAdminUser || u.user?.username === clusterAdminUser);
3295
- clusterAdminIsSuperUser = !!(adminRecord?.role?.permission?.super_user ??
3296
- adminRecord?.permission?.super_user ??
3297
- false);
3298
- }
3299
- catch {
3300
- // If we can't check, assume not and proceed with add_user
3301
- }
3302
3381
  if (clusterAdminIsSuperUser) {
3303
- console.log(`Cluster admin '${clusterAdminUser}' is already a super_user — skipping user provisioning`);
3382
+ // Reuse branch: the cluster administrator is already a super_user, so the
3383
+ // later calls authenticate as that administrator with the password the
3384
+ // operator supplied; this run did not create `admin`.
3385
+ console.log(`Cluster admin '${clusterAdminUser}' is already a super_user — reusing it as the init principal`);
3386
+ return { username: clusterAdminUser, password: clusterAdminPass, created: false };
3304
3387
  }
3305
3388
  else {
3306
3389
  console.log(`Provisioning Harper user 'admin' as super_user...`);
3307
- try {
3308
- await callOpsApi(opsTarget, {
3309
- operation: "add_user",
3310
- username: "admin",
3311
- password: flairAdminPass,
3312
- role: "super_user",
3313
- active: true,
3314
- }, clusterAdminUser, clusterAdminPass);
3315
- console.log("User 'admin' created ✓");
3316
- }
3317
- catch (err) {
3318
- const msg = err instanceof Error ? err.message : String(err);
3319
- if (msg.includes("already exists") || msg.includes("duplicate")) {
3320
- // Idempotent: fall back to alter_user
3321
- console.log("User 'admin' already exists — updating password...");
3322
- await callOpsApi(opsTarget, {
3323
- operation: "alter_user",
3324
- username: "admin",
3325
- password: flairAdminPass,
3326
- role: "super_user",
3327
- active: true,
3328
- }, clusterAdminUser, clusterAdminPass);
3329
- console.log("User 'admin' updated ✓");
3330
- }
3331
- else {
3332
- throw err;
3333
- }
3334
- }
3390
+ hooks.adminPasswordRequestSent?.();
3391
+ await callOpsApi(opsTarget, {
3392
+ operation: adminExists ? "alter_user" : "add_user",
3393
+ username: "admin",
3394
+ password: flairAdminPass,
3395
+ role: "super_user",
3396
+ active: true,
3397
+ }, clusterAdminUser, clusterAdminPass);
3398
+ console.log(adminExists ? "User 'admin' updated ✓" : "User 'admin' created ✓");
3399
+ hooks.afterAdminPasswordApplied?.();
3400
+ return { username: "admin", password: flairAdminPass, created: true };
3335
3401
  }
3336
3402
  }
3337
3403
  // ─── flair_pair_initiator role ──────────────────────────────────────────────
@@ -3917,6 +3983,10 @@ program.configureHelp({ showGlobalOptions: true });
3917
3983
  program.hook("preAction", async (_thisCommand, actionCommand) => {
3918
3984
  if (actionCommand.name() === "doctor")
3919
3985
  return;
3986
+ // flair#2887: `help` only prints. Skip the handshake probe so showing help
3987
+ // never reaches the server.
3988
+ if (actionCommand.name() === "help")
3989
+ return;
3920
3990
  // flair#2034 §2: `status` reports the server's version itself, next to this
3921
3991
  // CLI's and the install tree that serves it, and decides the advice from
3922
3992
  // that one comparison — a second, tree-blind "run: flair restart" line here
@@ -3955,7 +4025,7 @@ program.hook("preAction", async (_thisCommand, actionCommand) => {
3955
4025
  });
3956
4026
  // ─── flair init ────────────────────────────────────────────────────────────
3957
4027
  // Command registration lives in src/commands/init.ts (flair#1636).
3958
- // Bind shared cli-locals first so the extracted module never imports this file.
4028
+ // Bind shared cli-locals first so the extracted module never imports this file at runtime.
3959
4029
  bindInitCli({
3960
4030
  api,
3961
4031
  b64url,
@@ -3965,6 +4035,7 @@ bindInitCli({
3965
4035
  ensureFlairAgentRole,
3966
4036
  ensureFlairAgentUser,
3967
4037
  ensureFlairPairInitiatorRole,
4038
+ FLAIR_AGENT_USERNAME,
3968
4039
  flairPackageDir,
3969
4040
  harperBin,
3970
4041
  harperConfigPath,
@@ -4099,7 +4170,6 @@ bindFederationCli({
4099
4170
  resolveBaseUrl,
4100
4171
  resolveEffectiveOpsUrl,
4101
4172
  resolveOpsPort,
4102
- applyAdminPassFile,
4103
4173
  addSharedCredentialOptions,
4104
4174
  addSharedIdentityOption,
4105
4175
  shouldShowInlineSecretWarning,
@@ -4111,10 +4181,12 @@ registerFederation(program);
4111
4181
  bindRemCli({
4112
4182
  api,
4113
4183
  resolveOpsPort,
4114
- applyAdminPassFile,
4115
4184
  addSharedCredentialOptions,
4116
4185
  readPortFromConfig,
4117
4186
  resolveHttpPort,
4187
+ resolveOpsUrlFromTarget,
4188
+ resolveAgentHomeTarget,
4189
+ INSTANCE_TARGET_REMEDY,
4118
4190
  humanBytes,
4119
4191
  relativeTime,
4120
4192
  DEFAULT_PORT,
@@ -4299,6 +4371,7 @@ bindUpgradeCli({
4299
4371
  probeOpenclawPluginVersion,
4300
4372
  relativeTime,
4301
4373
  resolveFabricCredentials,
4374
+ resolveEffectiveOpsUrl,
4302
4375
  resolveFlairMcpFinding,
4303
4376
  resolveHttpPort,
4304
4377
  resolveInstalledFlairCli,
@@ -4444,8 +4517,8 @@ function readProcessState(pid, timeoutMs, onReadError) {
4444
4517
  * still answers signal 0. After the signal-0 probe succeeds, read the process
4445
4518
  * state and report a zombie as `gone`, so `flair doctor`'s stop wait stops
4446
4519
  * waiting on a process that has already exited (flair#2313). An unreadable
4447
- * state stays `alive` — a read failure must never report a live process as
4448
- * exited.
4520
+ * state stays `alive` unless a re-probe reports ESRCH — a read failure must
4521
+ * never report a live process as exited.
4449
4522
  *
4450
4523
  * The state reader is injectable so the unreadable and retried branches are
4451
4524
  * unit-testable without a real unreadable process.
@@ -4470,6 +4543,19 @@ export function probePidLiveness(pid, readState = readProcessState, deadlineMs =
4470
4543
  if (state !== null)
4471
4544
  break;
4472
4545
  }
4546
+ if (state === null) {
4547
+ // The pid can exit between the signal-0 probe and the state reads: signal 0
4548
+ // then says it exists while the reads find nothing. Re-probe the pid; ESRCH
4549
+ // is evidence it is gone, where an unreadable state alone stays fail-safe.
4550
+ try {
4551
+ process.kill(pid, 0);
4552
+ }
4553
+ catch (err) {
4554
+ if (err?.code === "ESRCH")
4555
+ return { kind: "gone" };
4556
+ }
4557
+ return { kind: "alive" };
4558
+ }
4473
4559
  return isExitedState(state) ? { kind: "gone" } : { kind: "alive" };
4474
4560
  }
4475
4561
  /**
@@ -4477,7 +4563,8 @@ export function probePidLiveness(pid, readState = readProcessState, deadlineMs =
4477
4563
  * `deadlineMs` passes; return whether `gone` was read and the last read
4478
4564
  * (flair#2330). This is `flair doctor`'s stop wait.
4479
4565
  *
4480
- * If both state reads fail, that poll stays `alive`.
4566
+ * If both state reads fail and the pid still answers signal 0, that poll stays
4567
+ * `alive`; an ESRCH at the re-probe reports it `gone`.
4481
4568
  * Check expiry before each read; an admitted read gets at least 1s to finish.
4482
4569
  * Readers honoring their timeout allow deadline + 1s, plus scheduling and subprocess overhead.
4483
4570
  */
@@ -5107,6 +5194,7 @@ function realRepointDeps() {
5107
5194
  samePath: samePathCanonical,
5108
5195
  canonical: canonicalOr,
5109
5196
  treeVersion: (dir) => readFlairPackageAt(dir)?.version ?? null,
5197
+ homebrewOptAlias: (nodeBin) => homebrewOptAlias(nodeBin),
5110
5198
  };
5111
5199
  }
5112
5200
  /**
@@ -5662,9 +5750,10 @@ export async function proveAdminPassAgainstInstance(port, adminPass) {
5662
5750
  if (err instanceof ApiHttpError && (err.status === 401 || err.status === 403)) {
5663
5751
  return `the supplied admin credential was rejected (HTTP ${err.status})`;
5664
5752
  }
5753
+ // Each ApiHttpError sendJsonRequest raises for this request begins its
5754
+ // message with `HTTP <status>`.
5665
5755
  const detail = err instanceof Error ? err.message : String(err);
5666
- const status = err instanceof ApiHttpError ? `HTTP ${err.status}: ` : "";
5667
- return `admin credential verification could not be completed (${status}${detail})`;
5756
+ return `admin credential verification could not be completed (${detail})`;
5668
5757
  }
5669
5758
  }
5670
5759
  /**
@@ -5699,8 +5788,8 @@ function validateAdminPassFileForLauncher(path) {
5699
5788
  * 1. An on-disk plist that is provably ours IN THE PASS-FILE SHAPE is never
5700
5789
  * regenerated. An adopted instance is never downgraded, and a re-run of
5701
5790
  * init does not churn mtime / flap launchd state. Its runtime paths alone
5702
- * are re-pointed when it serves another npm-global tree (flair#2034,
5703
- * src/lib/service-repoint.ts); otherwise it is left byte-for-byte unchanged.
5791
+ * are re-pointed in the cases src/lib/service-repoint.ts lists (flair#2034);
5792
+ * otherwise it is left byte-for-byte unchanged.
5704
5793
  * 2. A plist that is provably another instance's (`foreign`) or cannot be
5705
5794
  * attributed (`unattributable`) is refused, naming `flair doctor --fix`.
5706
5795
  * 3. Otherwise, resolve the pass file BEFORE writing anything: reuse an
@@ -7524,6 +7613,8 @@ bindReembedCli({
7524
7613
  privKeyPath,
7525
7614
  resolveHttpPort,
7526
7615
  resolveOpsPort,
7616
+ resolveAgentHomeTarget,
7617
+ ambiguousInstanceTargetError: AMBIGUOUS_INSTANCE_TARGET_ERROR,
7527
7618
  });
7528
7619
  registerReembed(program);
7529
7620
  // ─── flair test ────────────────────────────────────────────────────────────
@@ -7633,7 +7724,6 @@ bindMemoryCli({
7633
7724
  api,
7634
7725
  resolveBaseUrl,
7635
7726
  resolveSigningAgentId,
7636
- applyAdminPassFile,
7637
7727
  addSharedCredentialOptions,
7638
7728
  addSharedIdentityOption,
7639
7729
  resolveOpsPort,
@@ -7673,7 +7763,6 @@ registerRelationship(program);
7673
7763
  bindSoulCli({
7674
7764
  api,
7675
7765
  resolveSigningAgentId,
7676
- applyAdminPassFile,
7677
7766
  addSharedCredentialOptions,
7678
7767
  });
7679
7768
  registerSoul(program);
@@ -7690,7 +7779,6 @@ registerBridge(program);
7690
7779
  // Bind shared cli-locals first so the extracted module never imports this file.
7691
7780
  bindBackupCli({
7692
7781
  addSharedCredentialOptions,
7693
- applyAdminPassFile,
7694
7782
  resolveHttpPort,
7695
7783
  resolveOpsPort,
7696
7784
  resolveOpsTarget,
@@ -7704,6 +7792,14 @@ bindRestoreCli({
7704
7792
  resolveHttpPort,
7705
7793
  });
7706
7794
  registerRestore(program);
7795
+ // ─── flair backup-approval ───────────────────────────────────────────────────
7796
+ // Command registration lives in src/commands/backup-approval.ts (flair#2664).
7797
+ // Bind shared cli-locals first so the extracted module never imports this file.
7798
+ bindBackupApprovalCli({
7799
+ addSharedCredentialOptions,
7800
+ resolveOpsPort,
7801
+ });
7802
+ registerBackupApproval(program);
7707
7803
  // ─── flair export ────────────────────────────────────────────────────────────
7708
7804
  // Command registration lives in src/commands/export.ts (flair#1636).
7709
7805
  // Bind shared cli-locals first so the extracted module never imports this file.
@@ -7771,6 +7867,9 @@ bindAttentionCli({
7771
7867
  resolveSigningAgentId,
7772
7868
  });
7773
7869
  registerAttention(program);
7870
+ // ─── flair help ──────────────────────────────────────────────────────────────
7871
+ // Command registration lives in src/commands/help.ts (flair#2887).
7872
+ registerHelp(program);
7774
7873
  // Parse argv and run the CLI. Exported so the CommonJS preflight shim
7775
7874
  // (cli-shim.cts → dist/cli-shim.cjs, the real bin entry) can invoke it after
7776
7875
  // its Node-version check passes. The shim imports this module, so import.meta.main
@@ -7808,6 +7907,11 @@ async function runCli() {
7808
7907
  await program.parseAsync();
7809
7908
  }
7810
7909
  catch (err) {
7910
+ // A write that crossed its whole-request deadline may have committed.
7911
+ // Report it exactly as `flair rem` does and exit 3 ("unknown"), so every
7912
+ // command that lets the error propagate gives the same answer.
7913
+ if (err instanceof ApiRequestOutcomeUnknown)
7914
+ exitUnknownOutcome(err);
7811
7915
  // Errors the API layer already translated (flair#1719) carry a sentence
7812
7916
  // naming the actor, state and remedy; print it without the undici stack.
7813
7917
  if (err && typeof err === "object" && err.flairFriendly === true) {