@tpsdev-ai/flair 0.59.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (359) hide show
  1. package/README.md +10 -10
  2. package/SECURITY.md +49 -5
  3. package/config.yaml +23 -12
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/execute.js +1 -0
  6. package/dist/bridges/runtime/import-runner.js +12 -0
  7. package/dist/bridges/runtime/load-plugin.js +42 -13
  8. package/dist/bridges/runtime/yaml-loader.js +4 -2
  9. package/dist/bridges/types.js +1 -0
  10. package/dist/build-info.json +3 -3
  11. package/dist/cli.js +1054 -367
  12. package/dist/commands/agent.js +233 -90
  13. package/dist/commands/attention.js +4 -3
  14. package/dist/commands/backup-approval.js +218 -0
  15. package/dist/commands/backup.js +211 -39
  16. package/dist/commands/bootstrap.js +3 -1
  17. package/dist/commands/bridge.js +172 -119
  18. package/dist/commands/deploy.js +71 -8
  19. package/dist/commands/doctor.js +711 -146
  20. package/dist/commands/export.js +57 -23
  21. package/dist/commands/federation.js +787 -82
  22. package/dist/commands/grant.js +5 -6
  23. package/dist/commands/help.js +25 -0
  24. package/dist/commands/hook.js +155 -2
  25. package/dist/commands/idp.js +27 -19
  26. package/dist/commands/import.js +136 -20
  27. package/dist/commands/init.js +469 -200
  28. package/dist/commands/integrity.js +387 -0
  29. package/dist/commands/keys.js +247 -58
  30. package/dist/commands/mcp.js +108 -52
  31. package/dist/commands/memory.js +203 -35
  32. package/dist/commands/migrate-harness-memory.js +3 -2
  33. package/dist/commands/orgevent.js +51 -47
  34. package/dist/commands/presence.js +4 -3
  35. package/dist/commands/principal.js +428 -62
  36. package/dist/commands/quality.js +13 -1
  37. package/dist/commands/reembed.js +141 -17
  38. package/dist/commands/relationship.js +2 -1
  39. package/dist/commands/rem.js +537 -80
  40. package/dist/commands/restore.js +413 -65
  41. package/dist/commands/search.js +6 -4
  42. package/dist/commands/service.js +235 -40
  43. package/dist/commands/soul.js +4 -9
  44. package/dist/commands/status.js +94 -38
  45. package/dist/commands/test.js +7 -3
  46. package/dist/commands/upgrade.js +77 -23
  47. package/dist/commands/workspace.js +13 -11
  48. package/dist/component-env.js +31 -41
  49. package/dist/deploy.js +136 -4
  50. package/dist/doctor-client.js +534 -92
  51. package/dist/engine-version-contract.js +1 -0
  52. package/dist/engine-version.js +23 -3
  53. package/dist/fabric-upgrade.js +12 -2
  54. package/dist/federation/presence-send.js +139 -0
  55. package/dist/federation-verify.js +273 -180
  56. package/dist/hook-install.js +670 -6
  57. package/dist/install/clients.js +171 -35
  58. package/dist/keystore.js +72 -0
  59. package/dist/lib/action-recall-runtime.js +328 -0
  60. package/dist/lib/agent-home-fields.js +132 -0
  61. package/dist/lib/agent-home.js +427 -0
  62. package/dist/lib/agent-id-rule.js +88 -0
  63. package/dist/lib/agent-roster.js +33 -0
  64. package/dist/lib/atomic-write.js +1 -1
  65. package/dist/lib/auth-resolve.js +1069 -60
  66. package/dist/lib/backup-approval-store.js +612 -0
  67. package/dist/lib/backup-artifact.js +343 -0
  68. package/dist/lib/capture-runtime.js +124 -0
  69. package/dist/lib/config-critical-section.js +212 -25
  70. package/dist/lib/connect-phase.js +33 -0
  71. package/dist/lib/credential-status-rule.js +78 -0
  72. package/dist/lib/daemon-liveness.js +43 -11
  73. package/dist/lib/doctor-run.js +75 -37
  74. package/dist/lib/durability-copy.js +10 -0
  75. package/dist/lib/embedding-space-doctor.js +75 -0
  76. package/dist/lib/federation-pair-access.js +4 -0
  77. package/dist/lib/federation-retry-queue.js +283 -0
  78. package/dist/lib/federation-retry-row.js +101 -0
  79. package/dist/lib/flair-agent-role.js +4 -0
  80. package/dist/lib/hub-url.js +12 -0
  81. package/dist/lib/init-admin-pass.js +88 -12
  82. package/dist/lib/init-listener-environ.js +1 -2
  83. package/dist/lib/init-occupied-listener.js +15 -111
  84. package/dist/lib/init-spawn-attribution.js +73 -0
  85. package/dist/lib/init-tcp-probe.js +33 -0
  86. package/dist/lib/instance-identity-row.js +20 -0
  87. package/dist/lib/instruction-event-contract.js +17 -0
  88. package/dist/lib/instruction-event-doctor.js +102 -0
  89. package/dist/lib/launchd-management.js +38 -3
  90. package/dist/lib/listener-table.js +268 -0
  91. package/dist/lib/local-delete-instance.js +27 -0
  92. package/dist/lib/local-instance-pair.js +256 -0
  93. package/dist/lib/mcp-enable.js +1182 -341
  94. package/dist/lib/mcp-oauth-env-core.js +133 -0
  95. package/dist/lib/mcp-oauth-env.js +125 -0
  96. package/dist/lib/mcp-spec.js +17 -1
  97. package/dist/lib/memory-attributes.js +4 -0
  98. package/dist/lib/memory-id-policy.js +46 -0
  99. package/dist/lib/memory-integrity.js +309 -0
  100. package/dist/lib/memory-provider-timeout.js +33 -0
  101. package/dist/lib/memory-purge-response.js +20 -0
  102. package/dist/lib/mqtt-config.js +132 -0
  103. package/dist/lib/mqtt-listener-doctor.js +104 -0
  104. package/dist/lib/open-live-row.js +20 -0
  105. package/dist/lib/ops-table-count.js +25 -0
  106. package/dist/lib/ops-url.js +52 -0
  107. package/dist/lib/owned-pins.js +67 -10
  108. package/dist/lib/peer-status.js +27 -0
  109. package/dist/lib/principal-status.js +29 -0
  110. package/dist/lib/process-start-time.js +76 -12
  111. package/dist/lib/promotion-content-hash.js +20 -0
  112. package/dist/lib/proto-safe-record.js +42 -0
  113. package/dist/lib/record-id-path.js +25 -0
  114. package/dist/lib/reembed-server-support.js +66 -0
  115. package/dist/lib/restore-archive.js +760 -0
  116. package/dist/lib/restore-verify.js +104 -0
  117. package/dist/lib/scheduler-platform.js +10 -6
  118. package/dist/lib/secret-keys.js +25 -0
  119. package/dist/lib/secrets-push.js +50 -22
  120. package/dist/lib/skill-assignment-preflight.js +159 -0
  121. package/dist/lib/skill-seed-pending.js +24 -0
  122. package/dist/lib/skill-seed.js +448 -0
  123. package/dist/lib/skill-tombstone-doctor.js +133 -0
  124. package/dist/lib/soul-scope-fields.js +26 -0
  125. package/dist/lib/stop-start-recovery.js +54 -0
  126. package/dist/lib/uninstall-purge.js +266 -11
  127. package/dist/lib/upgrade-prior-liveness.js +2 -1
  128. package/dist/lib/using-flair-skill.js +87 -0
  129. package/dist/mcp-client-assertion.js +114 -14
  130. package/dist/memory-id-checkpoint.js +347 -0
  131. package/dist/memory-node-compare.js +207 -0
  132. package/dist/mqtt-off-deploy.js +550 -0
  133. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  134. package/dist/rem/promote-policy.js +3 -3
  135. package/dist/rem/restore.js +303 -26
  136. package/dist/rem/runner.js +317 -96
  137. package/dist/rem/scheduler.js +21 -4
  138. package/dist/resources/A2AAdapter.js +131 -178
  139. package/dist/resources/AdminMemory.js +2 -0
  140. package/dist/resources/AdminMemoryCandidates.js +116 -0
  141. package/dist/resources/Agent.js +463 -33
  142. package/dist/resources/AgentCard.js +4 -0
  143. package/dist/resources/AgentKeyRegister.js +248 -0
  144. package/dist/resources/AgentKeyRegistration.js +28 -0
  145. package/dist/resources/AgentReadPosition.js +7 -0
  146. package/dist/resources/AgentSeed.js +238 -107
  147. package/dist/resources/AutoPromoteCandidates.js +413 -78
  148. package/dist/resources/Credential.js +183 -10
  149. package/dist/resources/Federation.js +915 -145
  150. package/dist/resources/FederationRetry.js +140 -0
  151. package/dist/resources/InstructionVersion.js +220 -0
  152. package/dist/resources/Integration.js +300 -25
  153. package/dist/resources/MCPClientMetadata.js +6 -3
  154. package/dist/resources/Memory.js +3300 -758
  155. package/dist/resources/MemoryArchive.js +171 -53
  156. package/dist/resources/MemoryBootstrap.js +122 -61
  157. package/dist/resources/MemoryCandidate.js +37 -3
  158. package/dist/resources/MemoryConsolidate.js +2 -2
  159. package/dist/resources/MemoryDedupStats.js +30 -1
  160. package/dist/resources/MemoryFeed.js +545 -50
  161. package/dist/resources/MemoryGrant.js +21 -1
  162. package/dist/resources/MemoryMaintenance.js +368 -46
  163. package/dist/resources/MemoryPurge.js +348 -0
  164. package/dist/resources/MemoryReflect.js +71 -12
  165. package/dist/resources/MemoryReindex.js +111 -17
  166. package/dist/resources/Message.js +16 -5
  167. package/dist/resources/OAuth.js +342 -48
  168. package/dist/resources/OAuthClient.js +1 -1
  169. package/dist/resources/OrgEvent.js +405 -19
  170. package/dist/resources/OrgEventCatchup.js +7 -0
  171. package/dist/resources/OrgEventMaintenance.js +48 -10
  172. package/dist/resources/PairingToken.js +1 -1
  173. package/dist/resources/Presence.js +166 -51
  174. package/dist/resources/PromoteMemoryCandidate.js +24 -7
  175. package/dist/resources/RecordUsage.js +2 -4
  176. package/dist/resources/Relationship.js +23 -0
  177. package/dist/resources/SemanticSearch.js +63 -32
  178. package/dist/resources/Soul.js +191 -76
  179. package/dist/resources/SoulFeed.js +2 -1
  180. package/dist/resources/TeamDirectory.js +35 -0
  181. package/dist/resources/WorkspaceLatest.js +4 -0
  182. package/dist/resources/WorkspaceState.js +21 -1
  183. package/dist/resources/XAA.js +207 -63
  184. package/dist/resources/a2a-stream.js +313 -0
  185. package/dist/resources/a2a-url.js +4 -5
  186. package/dist/resources/agent-admin.js +10 -1
  187. package/dist/resources/agent-auth.js +138 -83
  188. package/dist/resources/agent-read-position-lib.js +4 -1
  189. package/dist/resources/agent-status-guard.js +9 -7
  190. package/dist/resources/auth-middleware.js +534 -171
  191. package/dist/resources/authority-field-guard.js +9 -11
  192. package/dist/resources/auto-promote-lib.js +8 -5
  193. package/dist/resources/basic-auth-header.js +21 -0
  194. package/dist/resources/bm25-index-service.js +4 -5
  195. package/dist/resources/dedup-cluster.js +6 -1
  196. package/dist/resources/ed25519-auth.js +1 -1
  197. package/dist/resources/embedding-space-guard.js +366 -72
  198. package/dist/resources/embeddings-provider.js +25 -0
  199. package/dist/resources/engine-version-stamp-boot.js +53 -0
  200. package/dist/resources/federation-classify.js +161 -0
  201. package/dist/resources/federation-crypto.js +5 -5
  202. package/dist/resources/federation-retry-lib.js +60 -0
  203. package/dist/resources/grant-visibility.js +135 -0
  204. package/dist/resources/harper-routing.js +83 -0
  205. package/dist/resources/health.js +163 -22
  206. package/dist/resources/host-pointer/registry.js +29 -0
  207. package/dist/resources/host-pointer-adapter.js +1 -0
  208. package/dist/resources/host-source-citation.js +49 -0
  209. package/dist/resources/host-source-visibility.js +7 -6
  210. package/dist/resources/in-process.js +24 -22
  211. package/dist/resources/instance-create-lock.js +17 -0
  212. package/dist/resources/instance-identity.js +23 -0
  213. package/dist/resources/instruction-version-record.js +587 -0
  214. package/dist/resources/internal-authority.js +13 -0
  215. package/dist/resources/key-lock.js +3 -3
  216. package/dist/resources/mcp-handler.js +141 -19
  217. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  218. package/dist/resources/mcp-oauth-flag.js +12 -14
  219. package/dist/resources/mcp-oauth.js +450 -56
  220. package/dist/resources/mcp-tool-arguments.js +4 -6
  221. package/dist/resources/mcp-tools.js +187 -40
  222. package/dist/resources/memory-bootstrap-lib.js +5 -15
  223. package/dist/resources/memory-declared-attributes.js +4 -1
  224. package/dist/resources/memory-deletion-history.js +55 -0
  225. package/dist/resources/memory-durability.js +54 -0
  226. package/dist/resources/memory-embed-hash.js +144 -0
  227. package/dist/resources/memory-embedding-value.js +8 -0
  228. package/dist/resources/memory-host-source.js +32 -7
  229. package/dist/resources/memory-id-guard.js +75 -0
  230. package/dist/resources/memory-redaction.js +236 -0
  231. package/dist/resources/memory-reflect-lib.js +1 -1
  232. package/dist/resources/memory-supplied-vector.js +72 -0
  233. package/dist/resources/memory-write-lock.js +489 -0
  234. package/dist/resources/memory-write-response.js +139 -0
  235. package/dist/resources/memory-write-transaction.js +243 -0
  236. package/dist/resources/migration-boot.js +17 -12
  237. package/dist/resources/migrations/boot-progress.js +25 -0
  238. package/dist/resources/migrations/data-dir.js +90 -19
  239. package/dist/resources/migrations/dir-safety.js +61 -3
  240. package/dist/resources/migrations/embedding-stamp.js +462 -82
  241. package/dist/resources/migrations/export.js +1 -0
  242. package/dist/resources/migrations/graph-heal.js +27 -27
  243. package/dist/resources/migrations/ledger.js +5 -2
  244. package/dist/resources/migrations/lock.js +870 -77
  245. package/dist/resources/migrations/progress.js +71 -10
  246. package/dist/resources/migrations/runner.js +212 -18
  247. package/dist/resources/migrations/snapshot.js +1 -0
  248. package/dist/resources/migrations/source-fields.js +5 -5
  249. package/dist/resources/migrations/state.js +36 -1
  250. package/dist/resources/migrations/status.js +2 -13
  251. package/dist/resources/migrations/synthetic-test-migration.js +81 -12
  252. package/dist/resources/migrations/types.js +26 -1
  253. package/dist/resources/migrations/visibility-backfill.js +113 -72
  254. package/dist/resources/oauth-discovery.js +0 -5
  255. package/dist/resources/object-body-guard.js +40 -0
  256. package/dist/resources/org-event-created-at.js +133 -0
  257. package/dist/resources/org-event-reserved.js +92 -0
  258. package/dist/resources/org-event-write-fault.js +19 -0
  259. package/dist/resources/originator-instance.js +39 -7
  260. package/dist/resources/owner-delete-recheck.js +78 -0
  261. package/dist/resources/owner-field-guard.js +39 -5
  262. package/dist/resources/owner-scoped-write-policy.js +256 -0
  263. package/dist/resources/owner-scoped-writes.js +89 -0
  264. package/dist/resources/path-id-rewrite.js +76 -0
  265. package/dist/resources/presence-internal.js +5 -5
  266. package/dist/resources/presence-receipt.js +236 -0
  267. package/dist/resources/promotion-binding.js +43 -0
  268. package/dist/resources/promotion-stamp.js +143 -17
  269. package/dist/resources/protocol-context.js +189 -0
  270. package/dist/resources/record-owner-guard.js +74 -26
  271. package/dist/resources/record-type-kit.js +2 -4
  272. package/dist/resources/record-types.js +1 -1
  273. package/dist/resources/relay-ops.js +78 -6
  274. package/dist/resources/replay-store.js +96 -19
  275. package/dist/resources/request-target.js +163 -0
  276. package/dist/resources/request-transaction.js +46 -1
  277. package/dist/resources/search-readiness.js +4 -1
  278. package/dist/resources/seed-ids.js +9 -0
  279. package/dist/resources/seed-reservation.js +116 -0
  280. package/dist/resources/semantic-retrieval-core.js +27 -15
  281. package/dist/resources/server-row-validation.js +71 -0
  282. package/dist/resources/skill-manifest.js +24 -14
  283. package/dist/resources/skill-subject.js +53 -0
  284. package/dist/resources/skill-version-write.js +789 -0
  285. package/dist/resources/skill-write-fault.js +20 -0
  286. package/dist/resources/skill-write-policy.js +68 -0
  287. package/dist/resources/skill-write.js +67 -7
  288. package/dist/resources/soul-write-policy.js +26 -7
  289. package/dist/resources/table-helpers.js +10 -7
  290. package/dist/resources/table-subscription-policy.js +518 -85
  291. package/dist/resources/table-subscriptions.js +20 -7
  292. package/dist/resources/team-directory.js +248 -0
  293. package/dist/resources/tool-descriptors/index.js +69 -8
  294. package/dist/resources/txn-pause-point.js +235 -0
  295. package/dist/resources/usage-recording.js +186 -70
  296. package/dist/resources/write-back.js +383 -0
  297. package/dist/resources/write-journal-context.js +5 -0
  298. package/dist/resources/write-journal.js +289 -0
  299. package/dist/src/engine-version-contract.js +1 -0
  300. package/dist/src/keystore.js +72 -0
  301. package/dist/src/lib/agent-home-fields.js +132 -0
  302. package/dist/src/lib/agent-id-rule.js +88 -0
  303. package/dist/src/lib/agent-key-register.js +80 -0
  304. package/dist/src/lib/atomic-write.js +256 -0
  305. package/dist/src/lib/credential-status-rule.js +78 -0
  306. package/dist/src/lib/expired-by-agent.js +37 -0
  307. package/dist/src/lib/federation-retry-row.js +101 -0
  308. package/dist/src/lib/flair-agent-role.js +4 -0
  309. package/dist/src/lib/idp-mapping-rule.js +81 -0
  310. package/dist/src/lib/instance-identity-row.js +20 -0
  311. package/dist/src/lib/instruction-event-contract.js +17 -0
  312. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  313. package/dist/src/lib/memory-attributes.js +4 -0
  314. package/dist/src/lib/memory-id-policy.js +46 -0
  315. package/dist/src/lib/open-live-row.js +20 -0
  316. package/dist/src/lib/principal-status.js +29 -0
  317. package/dist/src/lib/proto-safe-record.js +42 -0
  318. package/dist/src/lib/reembed-server-support.js +66 -0
  319. package/dist/src/lib/scheduler-platform.js +10 -6
  320. package/dist/src/lib/soul-scope-fields.js +26 -0
  321. package/dist/src/lib/systemd-agent-id.js +38 -0
  322. package/dist/src/rem/promote-policy.js +3 -3
  323. package/dist/src/rem/scheduler.js +21 -4
  324. package/docs/access-control.md +164 -54
  325. package/docs/api-reference.md +165 -32
  326. package/docs/auth.md +46 -30
  327. package/docs/bridges.md +11 -0
  328. package/docs/claude-code.md +37 -7
  329. package/docs/deploying-on-fabric.md +178 -0
  330. package/docs/deployment.md +19 -0
  331. package/docs/embedding-in-a-harper-app.md +17 -15
  332. package/docs/entity-vocabulary.md +3 -6
  333. package/docs/federation.md +61 -3
  334. package/docs/hosted-on-fabric.md +43 -36
  335. package/docs/integrations.md +14 -14
  336. package/docs/mcp-clients.md +12 -7
  337. package/docs/n8n.md +17 -11
  338. package/docs/notes/mcp-agent-auth-consumer.md +16 -13
  339. package/docs/notes/mcp-oauth-model2.md +40 -11
  340. package/docs/openclaw.md +1 -1
  341. package/docs/quickstart-fabric.md +4 -4
  342. package/docs/quickstart.md +12 -4
  343. package/docs/releasing.md +25 -19
  344. package/docs/rem.md +32 -3
  345. package/docs/secrets-and-keys.md +21 -4
  346. package/docs/standalone-local.md +30 -2
  347. package/docs/supply-chain-policy.md +34 -16
  348. package/docs/the-team.md +2 -2
  349. package/docs/upgrade.md +46 -6
  350. package/package.json +24 -12
  351. package/schemas/agent-key-registration.graphql +22 -0
  352. package/schemas/agent.graphql +6 -3
  353. package/schemas/federation.graphql +41 -1
  354. package/schemas/memory.graphql +91 -7
  355. package/schemas/oauth.graphql +19 -0
  356. package/schemas/schema.graphql +2 -0
  357. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  358. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  359. package/dist/resources/soul-adk-guard.js +0 -68
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from "commander";
3
3
  import { load as parseYaml } from "js-yaml";
4
- import { existsSync, mkdirSync, writeFileSync, readFileSync, openSync, closeSync, chmodSync, renameSync, cpSync, rmSync, mkdtempSync, readdirSync, statSync, lstatSync, realpathSync, unlinkSync, chownSync, constants as fsConstants, } from "node:fs";
4
+ import { existsSync, mkdirSync, writeFileSync, readFileSync, openSync, closeSync, chmodSync, renameSync, cpSync, rmSync, mkdtempSync, readdirSync, statSync, lstatSync, fstatSync, fchmodSync, realpathSync, unlinkSync, chownSync, constants as fsConstants, } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join, resolve, dirname, basename } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
@@ -21,15 +21,19 @@ import { detectClients } from "./install/clients.js";
21
21
  import { flairCliVersion, mcpServerSpec } from "./lib/mcp-spec.js";
22
22
  import { harperPortValue } from "./lib/harper-port-value.js";
23
23
  import { flairConfigPath, flairDataDir } from "./lib/flair-paths.js";
24
+ import { encodeRecordId } from "./lib/record-id-path.js";
25
+ import { invalidAgentIdMessage, isValidAgentId } from "./lib/agent-id-rule.js";
26
+ import { agentHomeEndpoint, decideProbedPairIdentity, readHttpInstanceIdentity, resolveTargetInstanceId, resolveTargetInstanceIdentity, stampAgentHome } from "./lib/agent-home.js";
27
+ import { proveLocalInstancePair } from "./lib/local-instance-pair.js";
24
28
  import { httpBind, httpCorsAccessList, preserveHttpPortValue, preserveSecurePort, qualifySecureBindValue, DEFAULT_HTTP_BIND_HOST, } from "./lib/http-bind.js";
25
29
  import { isNodeKeyId, partitionKeyIds, } from "./doctor-client.js";
26
30
  import { cliBootPathWarning, } from "./install/global-bin-path.js";
27
- import { 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";
28
32
  import { resolveSigningIdentity, emitSigningIdentityDebug, } from "./lib/signing-identity.js";
29
33
  import { entityFormatHint, parseEntitiesCsv } from "./lib/entity-vocab-cli.js";
30
34
  import { escapeXml, unescapeXml } from "./lib/xml-escape.js";
31
35
  import { assessLaunchdManagement, verifyLaunchdManagement, checkLaunchdPlistBeforeLoad, diagnoseLaunchdPlistPaths, isDetached, pickInstancePid, plistCarriesInlineAdminPassword, readLaunchctlJobState, readPlistProgramRefs, LAUNCHCTL_QUERY_TIMEOUT_MS, } from "./lib/launchd-management.js";
32
- import { classifyPlist, planLaunchdRepair, mapRepairThrow, decideAdoptStopWithWait, verifyAdoptServingWithWait, awaitLaunchdJobServing, judgeLaunchdJobServing, domainPreflightRefusal, } from "./lib/launchd-repair.js";
36
+ import { classifyPlist, planLaunchdRepair, mapRepairThrow, decideAdoptStop, verifyAdoptServingWithWait, awaitLaunchdJobServing, judgeLaunchdJobServing, domainPreflightRefusal, } from "./lib/launchd-repair.js";
33
37
  import { assessLaunchdLoadability, describeLoadabilityProblem, ensureLaunchdJobAbsent, firstLaunchdJobNotProvenAbsent, isLaunchdValidationRefusal, launchdJobPresence, launchdGuiDomain, loadabilityAllowsAttempt, loadabilityRemedy, loadLaunchdJob, LaunchdValidationRefusal, renderStartLaunchdFailed, renderStartLaunchdUnavailable, renderStartLaunchdUnloadUncertain, renderStartLaunchdValidationBlocked, renderStartLaunchdValidationRefused, DIRECT_PROCESS_GUARD_NOTE, DOMAIN_PROBE_TIMEOUT_MS, RUN_AT_LOAD_NOTE, } from "./lib/launchd-domain-preflight.js";
34
38
  import { assessTreeDivergence, linuxUnitProbe, mainPidFromShow, proveServingTree, systemdUnitStateFromShow, } from "./lib/tree-divergence.js";
35
39
  import { planPlistRuntimeRepoint } from "./lib/service-repoint.js";
@@ -39,10 +43,12 @@ import { applyRepointPlan, repointSystemdUserUnit, restartOnLinux } from "./lib/
39
43
  import { snapshotRegularFile } from "./lib/atomic-write.js";
40
44
  import { preferVersionManagerAlias } from "./lib/node-alias-path.js";
41
45
  import { stabilizeMqttNetworkKeyOrder } from "./lib/stabilize-mqtt-network.js";
46
+ import { MQTT_DISABLED_CONFIG } from "./lib/mqtt-config.js";
47
+ import { FABRIC_OPS_PORT, resolveOpsUrlFromTarget } from "./lib/ops-url.js";
42
48
  import { detectOpsApiAllInterfacesBind } from "./lib/ops-api-bind.js";
43
49
  import { applyUpgradeHookConsent, runDoctorChecks, } from "./lib/doctor-run.js";
44
50
  import { classifyInstalledVersion, shouldPrintUpgradeLine, upgradeStatusSuffix } from "./lib/upgrade-status.js";
45
- import { classifyDaemonState, verifyIdentity, isHarperProcessCommandLine, sidecarStartAgrees, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, classifySidecarStaleness, shouldRemoveSidecarAfterStop, livenessFromKillError, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
51
+ import { classifyDaemonState, verifyIdentity, isHarperProcessCommandLine, sidecarStartAgrees, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, classifySidecarStaleness, shouldRemoveSidecarAfterStop, livenessFromKillError, parseProcStatState, isExitedState, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
46
52
  import { readProcessStartSecondMs, readProcessStartTimeMs } from "./lib/process-start-time.js";
47
53
  import { readInitListenerRootPath } from "./lib/init-listener-environ.js";
48
54
  import { listenerFromLookup, occupiedListenerAuthFailure, stableAnsweredHolder, } from "./lib/init-occupied-listener.js";
@@ -50,7 +56,7 @@ import { bindCli as bindFederationCli, register as registerFederation, signReque
50
56
  import { describeFederationPairHubAccessError, describeFederationPairLocalAccessError, rewriteFederationPairHubAccessError, rewriteFederationPairLocalAccessError, } from "./lib/federation-pair-access.js";
51
57
  import { bindCli as bindMemoryCli, register as registerMemory, categorizeForHygiene, HYGIENE_TEST_CONTENT_PATTERNS, } from "./commands/memory.js";
52
58
  import { bindCli as bindSoulCli, register as registerSoul, } from "./commands/soul.js";
53
- import { bindCli as bindRemCli, register as registerRem, } from "./commands/rem.js";
59
+ import { bindCli as bindRemCli, exitUnknownOutcome, register as registerRem, } from "./commands/rem.js";
54
60
  import { bindCli as bindFleetCli, register as registerFleet, } from "./commands/fleet.js";
55
61
  import { bindCli as bindMcpCli, register as registerMcp, } from "./commands/mcp.js";
56
62
  import { bindCli as bindIdpCli, register as registerIdp, } from "./commands/idp.js";
@@ -69,6 +75,7 @@ import { defaultReadProcessCmdline, defaultReadProcessCwd, findFlairPackageDir,
69
75
  import { applyPlainTreeUpgrade, userSystemdDir, } from "./lib/upgrade-plain-tree.js";
70
76
  import { bindCli as bindOrgeventCli, register as registerOrgevent, MAX_ORGEVENT_DETAIL_LENGTH, MAX_ORGEVENT_SUMMARY_LENGTH, publishOrgEvent, } from "./commands/orgevent.js";
71
77
  import { bindCli as bindAttentionCli, register as registerAttention, } from "./commands/attention.js";
78
+ import { registerHelp } from "./commands/help.js";
72
79
  import { bindCli as bindBootstrapCli, register as registerBootstrap, } from "./commands/bootstrap.js";
73
80
  import { bindCli as bindTestCli, register as registerTest, } from "./commands/test.js";
74
81
  import { bindCli as bindReembedCli, register as registerReembed, } from "./commands/reembed.js";
@@ -78,6 +85,7 @@ import { bindCli as bindMigrateHarnessMemoryCli, register as registerMigrateHarn
78
85
  import { bindCli as bindSearchCli, register as registerSearch, } from "./commands/search.js";
79
86
  import { bindCli as bindBackupCli, register as registerBackup, } from "./commands/backup.js";
80
87
  import { bindCli as bindRestoreCli, register as registerRestore, } from "./commands/restore.js";
88
+ import { bindCli as bindBackupApprovalCli, register as registerBackupApproval, } from "./commands/backup-approval.js";
81
89
  import { bindCli as bindExportCli, register as registerExport, } from "./commands/export.js";
82
90
  import { bindCli as bindImportCli, register as registerImport, } from "./commands/import.js";
83
91
  import { register as registerInspect, } from "./commands/inspect.js";
@@ -88,6 +96,7 @@ import { bindCli as bindServiceCli, register as registerService, } from "./comma
88
96
  import { bindCli as bindDoctorCli, register as registerDoctor, } from "./commands/doctor.js";
89
97
  import { bindCli as bindQualityCli, register as registerQuality, } from "./commands/quality.js";
90
98
  import { bindCli as bindGrantCli, register as registerGrant, } from "./commands/grant.js";
99
+ import { bindIntegrityCli, register as registerIntegrity, } from "./commands/integrity.js";
91
100
  import { resolveHome } from "./lib/home.js";
92
101
  import { FLAIR_AGENT_PERMISSION } from "./lib/flair-agent-role.js";
93
102
  // Federation crypto helpers + private-visibility filter live with the
@@ -139,11 +148,16 @@ function shouldShowInlineSecretWarning(optValue, fromEnv, secretFlagNames, flagN
139
148
  }
140
149
  // ─── Defaults ────────────────────────────────────────────────────────────────
141
150
  const DEFAULT_PORT = 19926;
142
- const DEFAULT_OPS_PORT = 19925;
143
- const FABRIC_OPS_PORT = 9925;
151
+ // DEFAULT_OPS_PORT and FABRIC_OPS_PORT live in src/lib/ops-url.ts with
152
+ // resolveOpsUrlFromTarget, shared with the deploy channel (src/deploy.ts).
144
153
  // DEFAULT_ADMIN_USER + resolveAdminUser (flag > FLAIR_ADMIN_USER env > "admin")
145
154
  // live in src/lib/auth-resolve.ts — imported above (flair#1345).
146
- const STARTUP_TIMEOUT_MS = 60_000;
155
+ //
156
+ // Exported (flair#2568) so the test harness's readiness budget
157
+ // (HARPER_STARTUP_BUDGET_MS in test/helpers/harper-lifecycle.ts) can be pinned
158
+ // equal to the budget `flair init`'s TCP readiness check polls under.
159
+ export const STARTUP_TIMEOUT_MS = 60_000;
160
+ const ADOPT_STOP_TIMEOUT_MS = 60_000;
147
161
  const HEALTH_POLL_INTERVAL_MS = 500;
148
162
  // flair#670 — single-host default for the Harper ops API bind address.
149
163
  // Loopback-only (+ the domain socket, always provisioned) shrinks the
@@ -267,15 +281,29 @@ export function launchdLauncherPath(packageRoot = flairPackageDir()) {
267
281
  * Write `content` to `path` atomically: write to a temp file in the SAME
268
282
  * directory, then rename over the target. Same-fs rename is atomic on POSIX,
269
283
  * so a reader never observes a half-written file. `mode` is applied to the
270
- * temp file from creation — pass 0o600 when `content` holds a secret, so the
271
- * secret is never briefly world-readable on disk (flair#1573 slice a).
284
+ * temp file from creation (subject to umask) — pass 0o600 when `content`
285
+ * holds a secret, so the secret is never briefly world-readable on disk
286
+ * (flair#1573 slice a). `exactMode` is for restoring a captured file mode:
287
+ * it sets that mode on the temporary file's descriptor before the rename.
272
288
  */
273
- export function writeFileAtomic(path, content, mode) {
289
+ export function writeFileAtomic(path, content, mode, options = {}) {
274
290
  const dir = dirname(path);
275
291
  mkdirSync(dir, { recursive: true });
276
292
  const tmpPath = join(dir, `.${basename(path)}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`);
277
293
  try {
278
- writeFileSync(tmpPath, content, { mode });
294
+ if (options.exactMode) {
295
+ const fd = openSync(tmpPath, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL, mode);
296
+ try {
297
+ writeFileSync(fd, content);
298
+ fchmodSync(fd, mode);
299
+ }
300
+ finally {
301
+ closeSync(fd);
302
+ }
303
+ }
304
+ else {
305
+ writeFileSync(tmpPath, content, { mode });
306
+ }
279
307
  renameSync(tmpPath, path);
280
308
  }
281
309
  catch (err) {
@@ -286,13 +314,25 @@ export function writeFileAtomic(path, content, mode) {
286
314
  throw err;
287
315
  }
288
316
  }
289
- /**
290
- * Write the admin password to `path` with mode 0600 from creation (flair#1573
291
- * slice a). The secret is written to a temp file in the same dir (0600) and
292
- * renamed into place, so it is never briefly world-readable.
293
- */
294
317
  export function writeAdminPassFile(path, content) {
295
- writeFileAtomic(path, content, 0o600);
318
+ let target;
319
+ try {
320
+ target = lstatSync(path);
321
+ }
322
+ catch (err) {
323
+ if (err.code !== "ENOENT")
324
+ throw err;
325
+ }
326
+ if (target) {
327
+ if (target.isSymbolicLink())
328
+ throw new Error(`Refusing to write admin password at ${path}: symbolic link`);
329
+ if (!target.isFile())
330
+ throw new Error(`Refusing to write admin password at ${path}: not a regular file`);
331
+ if (typeof process.getuid === "function" && target.uid !== process.getuid()) {
332
+ throw new Error(`Refusing to write admin password at ${path}: owned by another user`);
333
+ }
334
+ }
335
+ writeFileAtomic(path, content, 0o600, { exactMode: true });
296
336
  }
297
337
  /**
298
338
  * Which launchd label an existing installation for `dataDir` is actually
@@ -705,6 +745,27 @@ function readOpsPortFromConfig(path = configPath()) {
705
745
  catch { /* ignore */ }
706
746
  return null;
707
747
  }
748
+ /**
749
+ * The HTTP value treated as NAMED: a `--port` value accepted by the existing
750
+ * resolver, else the first `:digits` match in `FLAIR_URL` converted to a number;
751
+ * null when neither supplies one. These are the first two rungs of
752
+ * `resolveHttpPort`, which reads them through this function, so
753
+ * `resolveAgentHomeTarget` and `resolveHttpPort` agree on what was named.
754
+ */
755
+ function namedHttpPort(opts) {
756
+ if (opts.port !== undefined && opts.port !== null) {
757
+ const n = Number(opts.port);
758
+ if (!isNaN(n) && n > 0)
759
+ return n;
760
+ }
761
+ const envUrl = process.env.FLAIR_URL;
762
+ if (envUrl) {
763
+ const m = envUrl.match(/:(\d+)/);
764
+ if (m)
765
+ return Number(m[1]);
766
+ }
767
+ return null;
768
+ }
708
769
  /**
709
770
  * Unified port resolution: `--port` flag > `FLAIR_URL` env > Harper's own config
710
771
  * in the instance's data directory > (default install only) the per-user config
@@ -744,17 +805,9 @@ function readOpsPortFromConfig(path = configPath()) {
744
805
  * it is for the default install that has always relied on it.
745
806
  */
746
807
  function resolveHttpPort(opts, mode = "address") {
747
- if (opts.port !== undefined && opts.port !== null) {
748
- const n = Number(opts.port);
749
- if (!isNaN(n) && n > 0)
750
- return n;
751
- }
752
- const envUrl = process.env.FLAIR_URL;
753
- if (envUrl) {
754
- const m = envUrl.match(/:(\d+)/);
755
- if (m)
756
- return Number(m[1]);
757
- }
808
+ const named = namedHttpPort(opts);
809
+ if (named !== null)
810
+ return named;
758
811
  const dataDir = instanceDataDir(opts);
759
812
  // 1. Harper's own config for this instance. Once Harper has written one it is
760
813
  // the only answer — it is maintained by the process that binds the socket.
@@ -880,51 +933,19 @@ export const SHARED_IDENTITY_FLAGS = {
880
933
  agent: "--agent <id>",
881
934
  };
882
935
  function addSharedCredentialOptions(cmd) {
883
- return cmd
884
- .option(ADMIN_PASS_FLAG, ADMIN_PASS_HELP)
885
- .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
936
+ return addAdminPassOptions(cmd)
886
937
  .option(SHARED_CREDENTIAL_FLAGS.adminUser, "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)");
887
938
  }
888
939
  function addSharedIdentityOption(cmd) {
889
940
  return cmd.option(SHARED_IDENTITY_FLAGS.agent, "Agent ID (or set FLAIR_AGENT_ID env)");
890
941
  }
891
- /**
892
- * Resolve the admin password for the commands that declare the shared
893
- * credential flags, through the ONE resolver (`resolveAdminPassFromSources` —
894
- * the same one `federation token`/`pair` use, flair#1873/#1910). The resolved
895
- * value is written back into the `adminPass` slot every call site reads.
896
- *
897
- * Precedence, as the usage text states: an explicit `--admin-pass-file` or
898
- * `--admin-pass` over the ambient `FLAIR_ADMIN_PASS`/`HDB_ADMIN_PASSWORD`.
899
- * Supplying BOTH the file and the flag is a usage error (it used to let the
900
- * flag silently win); a file that is missing, empty or group-/world-readable
901
- * is refused naming the path and its mode. Never prints the value.
902
- */
903
- function applyAdminPassFile(opts) {
904
- try {
905
- // envPass is DELIBERATELY omitted: this wrapper folds an explicit
906
- // `--admin-pass-file` (or `--admin-pass`) into `opts.adminPass`, and each
907
- // call site keeps its own `opts.adminPass ?? FLAIR_ADMIN_PASS` fallback —
908
- // exactly main's shape. Resolving the ambient env HERE would pre-fill
909
- // `opts.adminPass`, and a call site that threads it as `explicitAdminPass`
910
- // (memory add, soul, …) would then send ambient admin Basic auth where it
911
- // used to send nothing and let the `--agent`/env tier decide (flair#1910
912
- // round 2: `federation sync` merged nothing in the mixed-version compat
913
- // lane because `memory add --agent X` with FLAIR_ADMIN_PASS set signed as
914
- // admin, not as X).
915
- const pass = resolveAdminPassFromSources({
916
- adminPassFile: opts.adminPassFile,
917
- adminPass: opts.adminPass,
918
- });
919
- if (pass)
920
- opts.adminPass = pass;
921
- }
922
- catch (err) {
923
- console.error(`Error: ${err.message}`);
924
- process.exit(1);
925
- }
926
- }
927
- // Ops port resolution: --ops-port flag > FLAIR_OPS_PORT env > config opsPort > httpPort - 1
942
+ // Ops port resolution: valid --ops-port flag > FLAIR_OPS_PORT env > config opsPort > httpPort - 1.
943
+ // An explicit invalid --ops-port refuses; it never falls through to another rung.
944
+ //
945
+ // `httpPortBase` is the HTTP port the last rung derives from. A caller that
946
+ // already resolved the HTTP port — or, for `flair doctor`, probed the port it
947
+ // actually reached — passes it so that rung matches that port rather than
948
+ // re-resolving the configured one (flair#2562).
928
949
  //
929
950
  // Deliberately NOT routed through Harper's per-instance config the way
930
951
  // resolveHttpPort is (flair#914). The last rung couples the ops port to the HTTP
@@ -934,11 +955,14 @@ function applyAdminPassFile(opts) {
934
955
  // which is the bug flair#914 fixed pointing the other way. The ops port becomes
935
956
  // per-instance when the lifecycle commands grow `--data-dir` and there is a
936
957
  // named instance to attribute it to.
937
- function resolveOpsPort(opts) {
958
+ function resolveOpsPort(opts, httpPortBase) {
938
959
  if (opts.opsPort !== undefined && opts.opsPort !== null) {
939
960
  const n = Number(opts.opsPort);
940
- if (!isNaN(n) && n > 0)
961
+ if (Number.isInteger(n) && n >= 1 && n <= 65535)
941
962
  return n;
963
+ console.error(`Error: invalid --ops-port ${JSON.stringify(String(opts.opsPort))}. `
964
+ + "Pass an integer from 1 to 65535, or omit --ops-port to use FLAIR_OPS_PORT, local config, or the resolved HTTP port minus one.");
965
+ process.exit(1);
942
966
  }
943
967
  const envOps = process.env.FLAIR_OPS_PORT;
944
968
  if (envOps)
@@ -955,7 +979,246 @@ function resolveOpsPort(opts) {
955
979
  }
956
980
  catch { /* ignore */ }
957
981
  // Default: httpPort - 1
958
- return resolveHttpPort(opts) - 1;
982
+ return (httpPortBase ?? resolveHttpPort(opts)) - 1;
983
+ }
984
+ /** The named refusal for a configured-pair conflict or an unpaired one-sided target (flair#2474). */
985
+ export const AMBIGUOUS_INSTANCE_TARGET_ERROR = "ambiguous_instance_target";
986
+ /** The remedy appended to an {@link AMBIGUOUS_INSTANCE_TARGET_ERROR} refusal. */
987
+ export const INSTANCE_TARGET_REMEDY = "Pass both ports (--port and --ops-port) for one instance.";
988
+ /**
989
+ * The pairing rule of {@link resolveAgentHomeTarget} (flair#2474).
990
+ * With a COMPLETE configured pair (both ports recorded):
991
+ * - an ops port that is not named is the pair's ops port;
992
+ * - if exactly ONE of the two ports equals its side of the pair, the target is
993
+ * REFUSED: the target conflicts with the configured pair;
994
+ * - if both equal the pair, the pair is used; if NEITHER does, the ports are
995
+ * used as given (from resolveAgentHomeTarget that happens only when the
996
+ * caller named both, since a port it does not name is the pair's).
997
+ *
998
+ * With NO complete configured pair resolved (one side or both null):
999
+ * - exactly one port named is REFUSED: its counterpart cannot be established
1000
+ * from a configured pair, so the two could address different instances;
1001
+ * - both named: used as given;
1002
+ * - neither named: the HTTP port as resolved and the ops port from `deriveOps`.
1003
+ *
1004
+ * Ports used "as given" are NOT VERIFIED: nothing here contacts an instance to
1005
+ * confirm that two named ports belong to one instance.
1006
+ */
1007
+ export function decideAgentHomeTarget(i) {
1008
+ const { httpPort, httpNamed, namedOps, configuredHttp, configuredOps } = i;
1009
+ const remedy = INSTANCE_TARGET_REMEDY;
1010
+ if (configuredHttp !== null && configuredOps !== null) {
1011
+ const opsPort = namedOps ?? configuredOps;
1012
+ const httpMatches = httpPort === configuredHttp;
1013
+ const opsMatches = opsPort === configuredOps;
1014
+ if (httpMatches !== opsMatches) {
1015
+ throw new Error(`${AMBIGUOUS_INSTANCE_TARGET_ERROR}: the target (HTTP port ${httpPort}, ops port ${opsPort}) conflicts with the configured pair — `
1016
+ + `the config pairs HTTP ${configuredHttp} with ops ${configuredOps}. ${remedy}`);
1017
+ }
1018
+ return { httpPort, opsPort };
1019
+ }
1020
+ const opsNamed = namedOps !== null;
1021
+ if (httpNamed !== opsNamed) {
1022
+ const [named, namedPort, other] = httpNamed ? ["HTTP", httpPort, "ops"] : ["ops", namedOps, "HTTP"];
1023
+ throw new Error(`${AMBIGUOUS_INSTANCE_TARGET_ERROR}: only the ${named} port (${namedPort}) was named, and no complete port pair could be resolved from config `
1024
+ + `(HTTP ${configuredHttp ?? "none"}, ops ${configuredOps ?? "none"}) to take the ${other} port from, so the two ports could address different instances. ${remedy}`);
1025
+ }
1026
+ if (namedOps !== null)
1027
+ return { httpPort, opsPort: namedOps };
1028
+ return { httpPort, opsPort: i.deriveOps() };
1029
+ }
1030
+ /**
1031
+ * The ports `flair agent stamp-home` and `flair principal add` address
1032
+ * (flair#2474). Each command talks to an ops API (stamp-home's roster read and
1033
+ * read-backs; principal add's stored-home reads and its insert) AND sends its
1034
+ * guarded PATCH to the Agent resource on the HTTP port. Resolving the two
1035
+ * INDEPENDENTLY — `resolveOpsPort(opts)` and `resolveHttpPort(opts)` — let
1036
+ * `--ops-port` name one instance and `--port` another, so the read landed on the
1037
+ * first and the write on the second.
1038
+ *
1039
+ * The configured pair is what the instance's config records: Harper's config in
1040
+ * its data directory records `http.port` and `operationsApi.network.port`; for
1041
+ * the default install, `~/.flair/config.yaml`'s `port`/`opsPort` supplies a side
1042
+ * Harper's config does not record. The pairing rule is
1043
+ * {@link decideAgentHomeTarget}: a port that matches its side of a COMPLETE
1044
+ * configured pair binds the other to that pair; a target with only ONE port
1045
+ * named is refused when no complete configured pair is resolved; two ports the
1046
+ * caller names that match neither side of a complete pair (or any two named
1047
+ * ports when there is no complete pair) are used as given, without
1048
+ * verification. Every refusal is `ambiguous_instance_target`.
1049
+ */
1050
+ export function resolveAgentHomeTarget(opts, httpPortOverride) {
1051
+ // `flair doctor` probes the port it actually reached (a PID-discovered
1052
+ // `effectivePort` can differ from the configured one), so it passes that port
1053
+ // here; every other caller lets the resolver resolve it. When neither port is
1054
+ // named and the config records no complete pair, `deriveOps` takes THIS port
1055
+ // as the base for its port-minus-one default, so the fallback matches the
1056
+ // port doctor reached rather than the configured one (flair#2562).
1057
+ const httpPort = httpPortOverride ?? resolveHttpPort(opts);
1058
+ const dataDir = instanceDataDir(opts);
1059
+ const fromHarper = harperPortValue(readHarperConfig(dataDir)?.operationsApi?.network?.port);
1060
+ const configuredOps = fromHarper ?? (isDefaultDataDir(dataDir) ? readOpsPortFromConfig() : null);
1061
+ const configuredHttp = readPortFromHarperConfig(dataDir) ?? (isDefaultDataDir(dataDir) ? readPortFromConfig() : null);
1062
+ let namedOps = null;
1063
+ if (opts.opsPort !== undefined && opts.opsPort !== null) {
1064
+ const n = Number(opts.opsPort);
1065
+ if (!(Number.isInteger(n) && n >= 1 && n <= 65535)) {
1066
+ // An invalid --ops-port is refused by resolveOpsPort, which exits.
1067
+ return { httpPort, opsPort: resolveOpsPort(opts) };
1068
+ }
1069
+ namedOps = n;
1070
+ }
1071
+ else if (process.env.FLAIR_OPS_PORT) {
1072
+ const n = Number(process.env.FLAIR_OPS_PORT);
1073
+ namedOps = Number.isInteger(n) && n >= 1 && n <= 65535 ? n : null;
1074
+ }
1075
+ return decideAgentHomeTarget({
1076
+ httpPort,
1077
+ httpNamed: namedHttpPort(opts) !== null,
1078
+ namedOps,
1079
+ configuredHttp,
1080
+ configuredOps,
1081
+ deriveOps: () => resolveOpsPort(opts, httpPort),
1082
+ });
1083
+ }
1084
+ /**
1085
+ * The remedy `flair doctor` prints when it cannot establish the pair check
1086
+ * between the HTTP port it probed and the ops endpoint (flair#2483): select the
1087
+ * actual instance's ports, or correct that instance's configuration and restart
1088
+ * it. Recording a pair that merely matches is not a remedy: configured ports
1089
+ * are not proof of the live process.
1090
+ */
1091
+ export const DOCTOR_ROSTER_TARGET_REMEDY = "Pass --port with the HTTP port of the instance to inspect, and unset FLAIR_OPS_PORT or set it to that instance's ops port; "
1092
+ + "if that instance's configuration records ports it does not serve, correct its configuration and restart it.";
1093
+ /**
1094
+ * The remedy `flair doctor` prints when the ops endpoint refuses its admin
1095
+ * credential, so the configuration check could not run (flair#2483).
1096
+ */
1097
+ export const DOCTOR_ROSTER_CREDENTIAL_REMEDY = "Check that the admin credential doctor reads (FLAIR_ADMIN_USER, and FLAIR_ADMIN_PASS or ~/.flair/admin-pass) "
1098
+ + "is the probed instance's, and unset or correct FLAIR_OPS_PORT if it is set.";
1099
+ /**
1100
+ * The candidate ops endpoint for `flair doctor`'s instance reads (flair#2483,
1101
+ * #2520), picked by {@link resolveAgentHomeTarget}'s pairing rule
1102
+ * (flair#2474/#2491) against the HTTP port doctor actually probed.
1103
+ *
1104
+ * This only picks the candidate: the pairing rule works from config and named
1105
+ * ports and cannot show which instance an ops port addresses — it DELIBERATELY
1106
+ * trusts two ports the caller names. Doctor therefore checks the candidate
1107
+ * before the reads ({@link verifyDoctorRosterInstance}). A refusal here (a
1108
+ * probed port that conflicts with the configured pair, or exactly one port
1109
+ * named with no complete pair to complete it) is likewise NOT RUN, naming the
1110
+ * reason and the remedy.
1111
+ */
1112
+ export function resolveDoctorRosterTarget(opts, probedHttpPort) {
1113
+ try {
1114
+ return { kind: "run", opsPort: resolveAgentHomeTarget(opts, probedHttpPort).opsPort };
1115
+ }
1116
+ catch (err) {
1117
+ const message = err instanceof Error ? err.message : String(err);
1118
+ // The resolver's refusal ends with the stamp-home-shaped remedy; doctor has
1119
+ // no --ops-port flag, so drop it and let the caller print doctor's own.
1120
+ const reason = message.endsWith(INSTANCE_TARGET_REMEDY)
1121
+ ? message.slice(0, -INSTANCE_TARGET_REMEDY.length).trimEnd()
1122
+ : message;
1123
+ return { kind: "not-run", reason, remedy: DOCTOR_ROSTER_TARGET_REMEDY };
1124
+ }
1125
+ }
1126
+ /**
1127
+ * Whether the candidate ops endpoint pairs with the HTTP port doctor probed
1128
+ * (flair#2483). `proof` is {@link proveLocalInstancePair}'s answer for
1129
+ * `opsPort`, the check the local delete paths use
1130
+ * (src/lib/local-delete-instance.ts): the configuration records `opsPort` as
1131
+ * its ops port and an HTTP port bound on loopback or on all interfaces, and the
1132
+ * OS listener table shows one process listening on both, with a recognized
1133
+ * Harper command line and the same pid and start time on two reads. This
1134
+ * decides `run` only when that configured HTTP port is `probedHttpPort`. An unproven
1135
+ * pair, or a proven one naming another HTTP port, is `not-run`, with the
1136
+ * proof's own remedy when it carries one.
1137
+ */
1138
+ export function decideDoctorRosterPair(opsPort, probedHttpPort, proof) {
1139
+ if (proof.kind === "unproven") {
1140
+ const credentialRefused = proof.status === 401 || proof.status === 403;
1141
+ return {
1142
+ kind: "not-run",
1143
+ reason: `the ops endpoint on port ${opsPort} did not prove a live HTTP/ops pair (${proof.detail}), so this check cannot be established for the probed HTTP port ${probedHttpPort}`,
1144
+ remedy: proof.remedy ?? (credentialRefused ? DOCTOR_ROSTER_CREDENTIAL_REMEDY : DOCTOR_ROSTER_TARGET_REMEDY),
1145
+ ...(credentialRefused ? { credentialRefused: true } : {}),
1146
+ };
1147
+ }
1148
+ if (proof.httpPort !== probedHttpPort) {
1149
+ return {
1150
+ kind: "not-run",
1151
+ reason: `the configured HTTP/ops pair does not match: the ops endpoint on port ${opsPort} is configured with HTTP port ${proof.httpPort}, not the probed HTTP port ${probedHttpPort}, so this check cannot be established`,
1152
+ remedy: DOCTOR_ROSTER_TARGET_REMEDY,
1153
+ };
1154
+ }
1155
+ return { kind: "run", opsPort };
1156
+ }
1157
+ /**
1158
+ * The instance-identity comparison behind doctor's instance reads
1159
+ * (flair#2483), applied only after {@link decideDoctorRosterPair} decided
1160
+ * `run`. When the probed HTTP port and the ops endpoint each report one
1161
+ * `flair.Instance` id and the two differ, they are two instances: `not-run`.
1162
+ * Every other identity outcome (equal ids, no row on either side as on a fresh
1163
+ * install, several rows, or an unread table) leaves the pair check's `run`
1164
+ * standing.
1165
+ */
1166
+ export function decideDoctorRosterIdentity(opsPort, pair) {
1167
+ if (pair.kind === "different") {
1168
+ return {
1169
+ kind: "not-run",
1170
+ reason: `the ops endpoint on port ${opsPort} is configured with the probed HTTP port, but the two report different instance identities, so they are not one instance`,
1171
+ remedy: DOCTOR_ROSTER_TARGET_REMEDY,
1172
+ };
1173
+ }
1174
+ return { kind: "run", opsPort };
1175
+ }
1176
+ /**
1177
+ * The ops endpoint `flair doctor` may read the probed instance from, or a
1178
+ * refusal naming why it may not (flair#2483).
1179
+ *
1180
+ * 1. Picks the candidate with {@link resolveDoctorRosterTarget} against the HTTP
1181
+ * port doctor actually probed (a PID-discovered port included).
1182
+ * 2. Asks the candidate for its configuration ({@link proveLocalInstancePair},
1183
+ * the check the local delete paths use) and requires it to record the
1184
+ * candidate as its ops port and the probed port as its HTTP port, bound on
1185
+ * loopback or on all interfaces, with the OS listener table showing one
1186
+ * process listening on both, with a recognized Harper command line and the
1187
+ * same pid and start time on two reads ({@link decideDoctorRosterPair}). No
1188
+ * Instance row is needed, so a fresh install passes.
1189
+ * 3. Only then compares the instance identities both endpoints report
1190
+ * ({@link decideDoctorRosterIdentity}): two different single ids refuse.
1191
+ *
1192
+ * Any `not-run` means doctor reports the sections that use this answer NOT
1193
+ * RUN, and their diagnostic reads do not run: all four section reads, unless a
1194
+ * `--fix` step that may have changed the serving process made the roster and
1195
+ * home sections ask again (the answer describes the process serving the probed
1196
+ * port when it was taken). Doctor also derives from it whether its later
1197
+ * diagnostic requests to the probed HTTP port may be sent (flair#2526); the
1198
+ * pair proof (step 2) precedes any credentialed HTTP request, and step 3's
1199
+ * Basic identity read on the HTTP port follows only a proven pair. Reaching a
1200
+ * `not-run` may itself have read the candidate's configuration (step 2) and
1201
+ * both endpoints' instance identities (step 3).
1202
+ * Step 2 sees only the listeners this CLI can see: one outside that view
1203
+ * (another network namespace or container, or a user this CLI may not
1204
+ * inspect), or a port held by a forwarder whose command line does not match
1205
+ * Harper's, is NOT RUN; step 3 adds a
1206
+ * check only when both endpoints have exactly one Instance row.
1207
+ */
1208
+ export async function verifyDoctorRosterInstance(opts, probedHttpPort, adminPass) {
1209
+ const candidate = resolveDoctorRosterTarget(opts, probedHttpPort);
1210
+ if (candidate.kind === "not-run")
1211
+ return candidate;
1212
+ const adminUser = resolveAdminUser(undefined);
1213
+ const authorization = `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
1214
+ const configured = decideDoctorRosterPair(candidate.opsPort, probedHttpPort, await proveLocalInstancePair(candidate.opsPort, authorization));
1215
+ if (configured.kind === "not-run")
1216
+ return configured;
1217
+ const [httpIdentity, opsIdentity] = await Promise.all([
1218
+ readHttpInstanceIdentity(`http://127.0.0.1:${probedHttpPort}`, adminUser, adminPass),
1219
+ resolveTargetInstanceIdentity(agentHomeEndpoint(candidate.opsPort, adminUser, adminPass)),
1220
+ ]);
1221
+ return decideDoctorRosterIdentity(candidate.opsPort, decideProbedPairIdentity(httpIdentity, opsIdentity));
959
1222
  }
960
1223
  // Ops API bind-host resolution (flair#670, #863): --ops-bind flag >
961
1224
  // FLAIR_OPS_BIND env > persisted `opsBind` in ~/.flair/config.yaml > loopback
@@ -1065,26 +1328,9 @@ export function buildOperationsApiConfig(opsPort, opsSocket, opsBindHost) {
1065
1328
  network: { port: opsNetworkPortValue(opsBindHost, opsPort), cors: true, domainSocket: opsSocket },
1066
1329
  };
1067
1330
  }
1068
- /**
1069
- * Harper config that fully disables the MQTT broker (flair#1586).
1070
- *
1071
- * Flair does not use MQTT. Harper's mqtt component (server/mqtt.ts
1072
- * `handleApplication`) binds a TCP listener on `mqtt.network.port` (1883) and
1073
- * a TLS listener on `mqtt.network.securePort` (8883) whenever EITHER is truthy
1074
- * (`if (port || securePort)`), plus a WebSocket upgrade path when
1075
- * `mqtt.webSocket` is true. Nulling only `network.port` leaves
1076
- * `network.securePort` at its 8883 default, so the TLS listener still binds.
1077
- * Fully disabling MQTT requires nulling BOTH ports and turning off the
1078
- * WebSocket path.
1079
- *
1080
- * Note: config-root.schema.json still documents a flat `mqtt.port` /
1081
- * `mqtt.securePort`, but the runtime reads the nested `mqtt.network.*` form
1082
- * (see static/defaultConfig.yaml) — the flat keys are stale.
1083
- */
1084
- const MQTT_DISABLED_CONFIG = {
1085
- network: { port: null, securePort: null },
1086
- webSocket: false,
1087
- };
1331
+ // MQTT_DISABLED_CONFIG — the Harper `mqtt` section with every MQTT listener
1332
+ // off — lives in src/lib/mqtt-config.ts, shared with the component-deployment
1333
+ // channel (src/deploy.ts) and `flair doctor`.
1088
1334
  /**
1089
1335
  * Build the flair-owned environment overrides for a DIRECT (non-launchd)
1090
1336
  * Harper spawn (flair#863) — shared by `flair start`'s fallback path and
@@ -1551,17 +1797,6 @@ function resolveTarget(opts) {
1551
1797
  function resolveOpsTarget(opts) {
1552
1798
  return opts.opsTarget || process.env.FLAIR_OPS_TARGET || undefined;
1553
1799
  }
1554
- /** Derive the ops API URL from a Flair base URL.
1555
- * https with effective port 443 (no explicit port, or explicit :443): returns
1556
- * <host>:9925 (FABRIC_OPS_PORT) — the Fabric managed case where port-1/:442
1557
- * is a dead-end.
1558
- * All other cases unchanged:
1559
- * https with non-443 explicit port → port-1 (self-hosted TLS: 19926→19925, 8443→8442)
1560
- * http with explicit port → port-1 (19926→19925)
1561
- * http with no port → DEFAULT_OPS_PORT (19925)
1562
- * Bare hosts are normalised to https:// (effective-443 → Fabric path).
1563
- * Throws on unparseable URLs or out-of-range ports.
1564
- */
1565
1800
  /** Compute the effective ops API URL for remote commands.
1566
1801
  * - If --ops-target is set, use it directly (no derivation).
1567
1802
  * - Else if --target is set, derive ops URL via resolveOpsUrlFromTarget.
@@ -1576,37 +1811,6 @@ function resolveEffectiveOpsUrl(opts) {
1576
1811
  return resolveOpsUrlFromTarget(target);
1577
1812
  return undefined;
1578
1813
  }
1579
- function resolveOpsUrlFromTarget(targetUrl) {
1580
- // Normalise bare hosts: add https:// prefix so URL parser can handle them.
1581
- const normalised = targetUrl.includes("://") ? targetUrl : `https://${targetUrl}`;
1582
- const url = new URL(normalised);
1583
- // https target with effective port 443 (no explicit port, or explicit :443):
1584
- // this is the Fabric managed case — the ops API is on the well-known Fabric
1585
- // ops port, never REST-adjacent. The port-1 / :442 logic is a dead-end here.
1586
- if (url.protocol === "https:" && (url.port === "" || url.port === "443")) {
1587
- url.port = String(FABRIC_OPS_PORT);
1588
- return url.toString().replace(/\/$/, "");
1589
- }
1590
- // All other cases: unchanged port-1 convention.
1591
- // https with non-443 explicit port → port-1 (self-hosted TLS: 19926→19925, 8443→8442)
1592
- // http with explicit port → port-1 (19926→19925)
1593
- // http with no port → DEFAULT_OPS_PORT (19925)
1594
- const port = parseInt(url.port, 10);
1595
- if (!isNaN(port) && port > 0 && port <= 65535) {
1596
- const opsPort = port - 1;
1597
- if (opsPort < 1)
1598
- throw new Error(`Derived ops port ${opsPort} is out of range; target port must be > 1`);
1599
- url.port = String(opsPort);
1600
- return url.toString().replace(/\/$/, "");
1601
- }
1602
- // No valid explicit port — reject port 0 or out-of-range
1603
- if (url.port !== "" && url.port !== undefined) {
1604
- throw new Error(`Invalid target port: ${url.port} (must be 1-65535)`);
1605
- }
1606
- // No explicit port on http — use the default ops port.
1607
- url.port = String(DEFAULT_OPS_PORT);
1608
- return url.toString().replace(/\/$/, "");
1609
- }
1610
1814
  /**
1611
1815
  * Persist the instance coordinates other commands need to find and re-assert
1612
1816
  * this install (flair#863).
@@ -1873,16 +2077,38 @@ async function api(method, path, body, options) {
1873
2077
  explicitAdminPass: options?.explicitAdminPass,
1874
2078
  adminUser: options?.adminUser,
1875
2079
  agentIdSource: options?.agentIdSource,
2080
+ signedOnly: options?.signedOnly,
2081
+ refuseRedirects: options?.refuseRedirects,
2082
+ deadlineMs: options?.deadlineMs,
2083
+ deadlineSource: options?.deadlineSource,
2084
+ tolerateUnparsedSuccessBody: options?.tolerateUnparsedSuccessBody,
1876
2085
  };
2086
+ // The port the operator wrote in ~/.flair/config.yaml, when it differs from
2087
+ // the resolved one and no explicit base was given: the only port a
2088
+ // connect-phase failure may fall back to (flair#1719).
2089
+ const altPort = hasExplicitBase ? null : alternateConfiguredLocalPort({});
2090
+ const readOnly = method.toUpperCase() === "GET" || method.toUpperCase() === "HEAD";
2091
+ // Following a redirect can start another connection attempt; a connect-phase
2092
+ // failure there could cause the original write to be replayed on the alternate.
2093
+ // Refusing it (redirect: "manual") yields a named HTTP 3xx error, which is
2094
+ // never fallback-eligible because it is not a connect-phase failure.
2095
+ if (altPort !== null && !readOnly)
2096
+ requestOptions.refuseRedirects = true;
1877
2097
  try {
1878
2098
  return await authedRequest(method, path, body, requestOptions);
1879
2099
  }
1880
2100
  catch (err) {
2101
+ // A write that reached its deadline may have committed. Never replay it
2102
+ // against another port: that is a blind retry of an unknown outcome.
2103
+ // pinned by test/unit/request-deadline-2789.test.ts "a write whose deadline
2104
+ // expires exits 3 and the alternate configured port receives no request"
2105
+ if (err instanceof ApiRequestOutcomeUnknown)
2106
+ throw err;
1881
2107
  // flair#1719: the resolved port came from Harper's boot record, which can
1882
2108
  // be stale for the default install. Before surfacing a connect failure,
1883
- // try the port the operator actually wrote in ~/.flair/config.yaml.
1884
- const altPort = hasExplicitBase ? null : alternateConfiguredLocalPort({});
1885
- if (altPort !== null && isFederationStatusConnectFailure(err)) {
2109
+ // try the port the operator actually wrote in ~/.flair/config.yaml. Only a
2110
+ // connect-phase failure qualifies (flair#2869).
2111
+ if (altPort !== null && isConnectPhaseFailure(err)) {
1886
2112
  const altUrl = `http://127.0.0.1:${altPort}`;
1887
2113
  try {
1888
2114
  return await authedRequest(method, path, body, { ...requestOptions, baseUrl: altUrl });
@@ -1895,15 +2121,11 @@ async function api(method, path, body, options) {
1895
2121
  }
1896
2122
  }
1897
2123
  /**
1898
- * Turn undici/Node's bare `TypeError: fetch failed` into a sentence naming the
1899
- * actor (the Flair instance URL), the state (no HTTP response) and a remedy
1900
- * the operator can act on — flair#1719 requirement 3. Non-connect errors
1901
- * (HTTP 401/403/5xx, auth failures) pass through unchanged so callers keep
1902
- * their own handling. The `flairFriendly` marker lets the top-level CLI entry
1903
- * print just the message instead of a stack.
2124
+ * Give connect-phase errors a URL and remedy; pass other errors through.
2125
+ * `flairFriendly` prints the message without a stack.
1904
2126
  */
1905
2127
  function describeApiConnectFailure(err, url) {
1906
- if (!isFederationStatusConnectFailure(err))
2128
+ if (!isConnectPhaseFailure(err))
1907
2129
  return err;
1908
2130
  const friendly = new Error(`Cannot reach the Flair instance at ${url} — the connection failed (no HTTP response).\n`
1909
2131
  + ` Start it with \`flair start\`, or point this command at the right instance with `
@@ -1946,12 +2168,13 @@ export async function verifyAuthedGet(baseUrl, path, keysDir) {
1946
2168
  export function isCredentialOnlyFailure(result) {
1947
2169
  return result.healthy === true && result.authFailureKind === "credentials";
1948
2170
  }
1949
- async function waitForHealth(httpPort, adminUser, adminPass, timeoutMs) {
2171
+ async function waitForHealth(httpPort, adminUser, adminPass, timeoutMs, beforeRequest) {
1950
2172
  const url = `http://127.0.0.1:${httpPort}/Health`;
1951
2173
  const deadline = Date.now() + timeoutMs;
1952
2174
  let attempt = 0;
1953
2175
  while (Date.now() < deadline) {
1954
2176
  attempt++;
2177
+ await beforeRequest?.();
1955
2178
  try {
1956
2179
  const res = await fetch(url, {
1957
2180
  headers: { Authorization: `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}` },
@@ -2069,7 +2292,7 @@ export async function verifySemanticSearch(baseUrl, agentIdOpt, keysDir) {
2069
2292
  let stored = false;
2070
2293
  try {
2071
2294
  // Write the test memory (ephemeral so it's never durable). PUT /Memory/<id>.
2072
- const writeRes = await authFetch(baseUrl, agentId, keyPath, "PUT", `/Memory/${id}`, {
2295
+ const writeRes = await authFetch(baseUrl, agentId, keyPath, "PUT", `/Memory/${encodeRecordId(id)}`, {
2073
2296
  id, agentId, content, durability: "ephemeral", createdAt: new Date().toISOString(),
2074
2297
  });
2075
2298
  if (!writeRes.ok && writeRes.status !== 204) {
@@ -2135,7 +2358,7 @@ export async function verifySemanticSearch(baseUrl, agentIdOpt, keysDir) {
2135
2358
  // Best-effort cleanup of the ephemeral probe memory.
2136
2359
  if (stored) {
2137
2360
  try {
2138
- await authFetch(baseUrl, agentId, keyPath, "DELETE", `/Memory/${id}`);
2361
+ await authFetch(baseUrl, agentId, keyPath, "DELETE", `/Memory/${encodeRecordId(id)}`);
2139
2362
  }
2140
2363
  catch { /* leave the ephemeral row; it'll age out */ }
2141
2364
  }
@@ -2194,7 +2417,7 @@ export async function verifyAuditLog(baseUrl, agentIdOpt, keysDir, opsUrl, admin
2194
2417
  };
2195
2418
  }
2196
2419
  const id = `flair-doctor-audit-probe-${randomUUID()}`;
2197
- const path = `/Memory/${id}`;
2420
+ const path = `/Memory/${encodeRecordId(id)}`;
2198
2421
  let stored = false;
2199
2422
  try {
2200
2423
  // Write 1: PUT the probe row. Ephemeral durability — TTL is the cleanup
@@ -2369,7 +2592,7 @@ export async function checkAgentRegistered(baseUrl, agentId, keysDir) {
2369
2592
  return { state: "no-key", detail: `no local key for agent '${agentId}' to sign the check` };
2370
2593
  }
2371
2594
  try {
2372
- const res = await authFetch(baseUrl, agentId, keyPath, "GET", `/Agent/${agentId}`);
2595
+ const res = await authFetch(baseUrl, agentId, keyPath, "GET", `/Agent/${encodeRecordId(agentId)}`);
2373
2596
  if (res.ok)
2374
2597
  return { state: "registered" };
2375
2598
  if (res.status === 404)
@@ -2392,10 +2615,6 @@ export async function checkAgentRegistered(baseUrl, agentId, keysDir) {
2392
2615
  return { state: "unreachable", detail: `instance unreachable: ${message.slice(0, 100)}` };
2393
2616
  }
2394
2617
  }
2395
- // Blocks until the given PID is gone (ESRCH from signal 0), or timeout.
2396
- // Used during restart to confirm the old Harper process actually exited before
2397
- // we start polling /Health — otherwise the still-shutting-down old process can
2398
- // answer and we'd declare restart success while a gap is still ahead.
2399
2618
  /**
2400
2619
  * Is `pid` a process that exists right now? Signal 0 performs the permission
2401
2620
  * and existence checks without delivering anything (flair#1022) — a `hdb.pid`
@@ -2411,16 +2630,19 @@ function isProcessAlive(pid) {
2411
2630
  return false;
2412
2631
  }
2413
2632
  }
2414
- async function waitForProcessExit(pid, timeoutMs) {
2633
+ // Used during restart to confirm the old Harper process actually exited before
2634
+ // we start polling /Health — otherwise the still-shutting-down old process can
2635
+ // answer and we'd declare restart success while a gap is still ahead.
2636
+ // Cap sleeps at the remaining time; probe once after the last wake, then stop (flair#2357).
2637
+ export async function waitForProcessExit(pid, timeoutMs, probe = probePidLiveness) {
2415
2638
  const deadline = Date.now() + timeoutMs;
2416
- while (Date.now() < deadline) {
2417
- try {
2418
- process.kill(pid, 0);
2419
- }
2420
- catch {
2639
+ while (true) {
2640
+ if (probe(pid).kind === "gone")
2421
2641
  return;
2422
- }
2423
- await new Promise((r) => setTimeout(r, HEALTH_POLL_INTERVAL_MS));
2642
+ const remaining = deadline - Date.now();
2643
+ if (remaining <= 0)
2644
+ break;
2645
+ await new Promise((r) => setTimeout(r, Math.min(HEALTH_POLL_INTERVAL_MS, remaining)));
2424
2646
  }
2425
2647
  throw new Error(`Process ${pid} did not exit within ${timeoutMs}ms`);
2426
2648
  }
@@ -2619,7 +2841,21 @@ export async function seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, ad
2619
2841
  * data directory does not prove the passwords differ, and the HTTP holder
2620
2842
  * is not assumed to be the process that rejected this request.
2621
2843
  */
2622
- occupiedListener) {
2844
+ occupiedListener,
2845
+ /**
2846
+ * The target instance's own federation id, resolved by the caller through
2847
+ * the rule in src/lib/agent-home.ts. When supplied (including an explicit
2848
+ * null), the new Agent row carries it as its home (`originatorInstanceId`),
2849
+ * and the create ignores any other source. When omitted, the field is left
2850
+ * off the row.
2851
+ */
2852
+ homeInstanceId) {
2853
+ // flair#2359 — the ONE agent-ID rule, before the operations-API insert. This
2854
+ // is the write path for `flair agent add`, `flair import` and `flair init`,
2855
+ // so a caller-supplied id is refused here by name before any HTTP call.
2856
+ if (!isValidAgentId(agentId)) {
2857
+ throw new Error(invalidAgentIdMessage(agentId));
2858
+ }
2623
2859
  const url = typeof opsPortOrUrl === "number"
2624
2860
  ? `http://127.0.0.1:${opsPortOrUrl}/`
2625
2861
  : `${opsPortOrUrl.replace(/\/$/, "")}/`;
@@ -2632,23 +2868,30 @@ occupiedListener) {
2632
2868
  // and is invisible to roster/presence/Office-Space queries that filter on
2633
2869
  // status='active' or kind='agent' (#521). Mirror Agent.post() exactly here.
2634
2870
  const now = new Date().toISOString();
2871
+ const record = {
2872
+ id: agentId,
2873
+ name: agentId,
2874
+ type: "agent",
2875
+ kind: "agent",
2876
+ status: "active",
2877
+ displayName: agentId,
2878
+ admin: false,
2879
+ defaultTrustTier: "unverified",
2880
+ publicKey: pubKeyB64url,
2881
+ createdAt: now,
2882
+ updatedAt: now,
2883
+ };
2884
+ // flair#2433 — the new row's home is the creating instance's id. A create
2885
+ // stamps it and ignores anything else; the caller passes the id it resolved
2886
+ // through the one shared rule (src/lib/agent-home.ts). An omitted id leaves the
2887
+ // field off (the pre-fix shape, for callers that do not stamp).
2888
+ if (homeInstanceId !== undefined)
2889
+ stampAgentHome(record, homeInstanceId);
2635
2890
  const body = {
2636
2891
  operation: "insert",
2637
2892
  database: "flair",
2638
2893
  table: "Agent",
2639
- records: [{
2640
- id: agentId,
2641
- name: agentId,
2642
- type: "agent",
2643
- kind: "agent",
2644
- status: "active",
2645
- displayName: agentId,
2646
- admin: false,
2647
- defaultTrustTier: "unverified",
2648
- publicKey: pubKeyB64url,
2649
- createdAt: now,
2650
- updatedAt: now,
2651
- }],
2894
+ records: [record],
2652
2895
  };
2653
2896
  await opsSeedInsertWithRetry({
2654
2897
  url,
@@ -2667,7 +2910,7 @@ occupiedListener) {
2667
2910
  after = occupiedListener.reread();
2668
2911
  }
2669
2912
  catch {
2670
- after = { port: occupiedListener.before.port, pids: [], dataDirs: [] };
2913
+ after = { port: occupiedListener.before.port, pids: [], dataDirs: [], pidsKnown: false };
2671
2914
  }
2672
2915
  return occupiedListenerAuthFailure({
2673
2916
  lead: "Operations API insert failed (401): ",
@@ -2684,6 +2927,18 @@ occupiedListener) {
2684
2927
  // ops-insert body to the REST root, which Harper 405s as a collection POST to
2685
2928
  // /Agent (the Agent table resource has no POST handler). It was removed in the
2686
2929
  // #499 fix; do not reintroduce a REST-root insert path.
2930
+ /**
2931
+ * Seed an agent through the ops API, stamping the TARGET instance's own
2932
+ * federation id as the new row's home (flair#2433). The id is resolved through
2933
+ * the one shared rule (src/lib/agent-home.ts, over the same
2934
+ * src/lib/instance-identity-row.ts decision the server uses), so this path
2935
+ * cannot disagree with the Agent resource's own stamp. A null id (no single
2936
+ * Instance row) writes an explicit null — the defined local-origin state.
2937
+ */
2938
+ export async function seedAgentWithLocalHome(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass, occupiedListener) {
2939
+ const home = await resolveTargetInstanceId(agentHomeEndpoint(opsPortOrUrl, adminUser, adminPass));
2940
+ await seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass, occupiedListener, home);
2941
+ }
2687
2942
  // ─── FederationInstance seed via ops API ──────────────────────────────────────
2688
2943
  //
2689
2944
  // Remote init writes FederationInstance through the ops API (Basic auth with
@@ -3586,6 +3841,10 @@ program.configureHelp({ showGlobalOptions: true });
3586
3841
  program.hook("preAction", async (_thisCommand, actionCommand) => {
3587
3842
  if (actionCommand.name() === "doctor")
3588
3843
  return;
3844
+ // flair#2887: `help` only prints. Skip the handshake probe so showing help
3845
+ // never reaches the server.
3846
+ if (actionCommand.name() === "help")
3847
+ return;
3589
3848
  // flair#2034 §2: `status` reports the server's version itself, next to this
3590
3849
  // CLI's and the install tree that serves it, and decides the advice from
3591
3850
  // that one comparison — a second, tree-blind "run: flair restart" line here
@@ -3649,6 +3908,7 @@ bindInitCli({
3649
3908
  repointMainServiceUnit,
3650
3909
  resolveHttpPort,
3651
3910
  writeAdminPassFile,
3911
+ proveAdminPassAgainstInstance,
3652
3912
  resolveOpsBindHost,
3653
3913
  resolveHttpBindFor,
3654
3914
  resolveOpsPort,
@@ -3657,14 +3917,17 @@ bindInitCli({
3657
3917
  resolveTarget,
3658
3918
  runSoulWizard,
3659
3919
  seedAgentViaOpsApi,
3920
+ seedAgentWithLocalHome,
3660
3921
  seedFederationInstanceViaOpsApi,
3661
3922
  readOccupiedListener,
3923
+ resolveInstanceServingPid,
3662
3924
  shouldShowInlineSecretWarning,
3663
3925
  verifyAuditLog,
3664
3926
  verifySemanticSearch,
3665
3927
  waitForHealth,
3666
3928
  writeDaemonSidecar,
3667
3929
  registerInitLaunchdService,
3930
+ initLaunchdExitCode,
3668
3931
  MQTT_DISABLED_CONFIG,
3669
3932
  STARTUP_TIMEOUT_MS,
3670
3933
  });
@@ -3680,8 +3943,10 @@ bindAgentCli({
3680
3943
  shouldShowInlineSecretWarning,
3681
3944
  resolveHttpPort,
3682
3945
  resolveOpsPort,
3946
+ resolveAgentHomeTarget,
3683
3947
  resolveEffectiveOpsUrl,
3684
3948
  seedAgentViaOpsApi,
3949
+ seedAgentWithLocalHome,
3685
3950
  agentRecordIsAdmin,
3686
3951
  });
3687
3952
  registerAgent(program);
@@ -3692,6 +3957,9 @@ bindKeysCli({
3692
3957
  checkAgentRegistered,
3693
3958
  probeFlairReachable,
3694
3959
  resolveBaseUrl,
3960
+ resolveOpsPort,
3961
+ resolveHttpPort,
3962
+ readPortFromHarperConfig,
3695
3963
  });
3696
3964
  registerKeys(program);
3697
3965
  // ─── flair hook ──────────────────────────────────────────────────────────────
@@ -3721,6 +3989,8 @@ bindPrincipalCli({
3721
3989
  pubKeyPath,
3722
3990
  relativeTime,
3723
3991
  resolveOpsPort,
3992
+ resolveHttpPort,
3993
+ resolveAgentHomeTarget,
3724
3994
  });
3725
3995
  registerPrincipal(program);
3726
3996
  // ─── flair idp ───────────────────────────────────────────────────────────────
@@ -3740,6 +4010,14 @@ bindGrantCli({
3740
4010
  resolveAdminUser,
3741
4011
  });
3742
4012
  registerGrant(program);
4013
+ // ─── flair integrity ──────────────────────────────────────────────────────────
4014
+ // Command group lives in src/commands/integrity.ts (flair#2213). Bind shared
4015
+ // helpers first so the extracted module never imports this file.
4016
+ bindIntegrityCli({
4017
+ resolveOpsPort,
4018
+ resolveAdminUser,
4019
+ });
4020
+ registerIntegrity(program);
3743
4021
  // ─── flair federation ────────────────────────────────────────────────────────
3744
4022
  // Command group lives in src/commands/federation.ts (flair#1620). Bind shared
3745
4023
  // helpers first so the extracted module never imports this file.
@@ -3749,7 +4027,6 @@ bindFederationCli({
3749
4027
  resolveBaseUrl,
3750
4028
  resolveEffectiveOpsUrl,
3751
4029
  resolveOpsPort,
3752
- applyAdminPassFile,
3753
4030
  addSharedCredentialOptions,
3754
4031
  addSharedIdentityOption,
3755
4032
  shouldShowInlineSecretWarning,
@@ -3761,10 +4038,12 @@ registerFederation(program);
3761
4038
  bindRemCli({
3762
4039
  api,
3763
4040
  resolveOpsPort,
3764
- applyAdminPassFile,
3765
4041
  addSharedCredentialOptions,
3766
4042
  readPortFromConfig,
3767
4043
  resolveHttpPort,
4044
+ resolveOpsUrlFromTarget,
4045
+ resolveAgentHomeTarget,
4046
+ INSTANCE_TARGET_REMEDY,
3768
4047
  humanBytes,
3769
4048
  relativeTime,
3770
4049
  DEFAULT_PORT,
@@ -3949,6 +4228,7 @@ bindUpgradeCli({
3949
4228
  probeOpenclawPluginVersion,
3950
4229
  relativeTime,
3951
4230
  resolveFabricCredentials,
4231
+ resolveEffectiveOpsUrl,
3952
4232
  resolveFlairMcpFinding,
3953
4233
  resolveHttpPort,
3954
4234
  resolveInstalledFlairCli,
@@ -4048,11 +4328,61 @@ export function readSidecar(dataDir) {
4048
4328
  }
4049
4329
  return { kind: "present", ...parsed };
4050
4330
  }
4051
- /** `kill(pid, 0)` as a four-way: alive / gone (ESRCH) / eperm (another user's) / unknown. */
4052
- function probePidLiveness(pid) {
4331
+ export const DARWIN_STATE_READ_TIMEOUT_MS = 5_000;
4332
+ const DARWIN_STATE_READ_MIN_MS = 1_000;
4333
+ function readDarwinProcessState(pid, timeoutMs, onReadError) {
4334
+ try {
4335
+ const out = execFileSync("/bin/ps", ["-o", "stat=", "-p", String(pid)], {
4336
+ encoding: "utf-8",
4337
+ env: { ...process.env, LC_ALL: "C" },
4338
+ timeout: timeoutMs,
4339
+ killSignal: "SIGKILL",
4340
+ stdio: ["ignore", "pipe", "ignore"],
4341
+ }).trim();
4342
+ return out.length > 0 ? out[0] : null;
4343
+ }
4344
+ catch (error) {
4345
+ onReadError?.(error, timeoutMs);
4346
+ return null;
4347
+ }
4348
+ }
4349
+ /**
4350
+ * The kernel's state character for an existing pid, or null when it cannot be
4351
+ * read (flair#2313). Linux reads field 3 of `/proc/<pid>/stat`; Darwin reads the
4352
+ * first character of `/bin/ps -o stat=` (flair#2330). A read failure returns
4353
+ * null — the caller treats that as "not exited", never as exited (fail safe).
4354
+ */
4355
+ function readProcessState(pid, timeoutMs, onReadError) {
4356
+ if (process.platform === "linux") {
4357
+ try {
4358
+ return parseProcStatState(readFileSync(`/proc/${pid}/stat`, "utf-8"));
4359
+ }
4360
+ catch {
4361
+ return null;
4362
+ }
4363
+ }
4364
+ if (process.platform === "darwin")
4365
+ return readDarwinProcessState(pid, timeoutMs, onReadError);
4366
+ return null;
4367
+ }
4368
+ /**
4369
+ * Process liveness: alive / gone (ESRCH or zombie) / eperm (another user's) /
4370
+ * unknown.
4371
+ *
4372
+ * Signal 0 says the pid EXISTS, which is not the same as running: an exited
4373
+ * child whose parent has not reaped it is a zombie (state `Z`, `<defunct>`) that
4374
+ * still answers signal 0. After the signal-0 probe succeeds, read the process
4375
+ * state and report a zombie as `gone`, so `flair doctor`'s stop wait stops
4376
+ * waiting on a process that has already exited (flair#2313). An unreadable
4377
+ * state stays `alive` — a read failure must never report a live process as
4378
+ * exited.
4379
+ *
4380
+ * The state reader is injectable so the unreadable and retried branches are
4381
+ * unit-testable without a real unreadable process.
4382
+ */
4383
+ export function probePidLiveness(pid, readState = readProcessState, deadlineMs = Infinity, onReadError) {
4053
4384
  try {
4054
4385
  process.kill(pid, 0);
4055
- return { kind: "alive" };
4056
4386
  }
4057
4387
  catch (err) {
4058
4388
  // `gone` ONLY for ESRCH. Any other errno (EINVAL, EACCES, ...) is `unknown`,
@@ -4060,15 +4390,56 @@ function probePidLiveness(pid) {
4060
4390
  // classifier's unknown state (flair#2055).
4061
4391
  return livenessFromKillError(err?.code);
4062
4392
  }
4393
+ let state = null;
4394
+ for (let attempt = 0; attempt < 2; attempt++) {
4395
+ const remainingMs = deadlineMs - Date.now();
4396
+ if (remainingMs <= 0)
4397
+ break;
4398
+ const timeoutMs = Math.min(DARWIN_STATE_READ_TIMEOUT_MS, Math.max(DARWIN_STATE_READ_MIN_MS, remainingMs));
4399
+ state = readState(pid, timeoutMs, onReadError);
4400
+ if (state !== null)
4401
+ break;
4402
+ }
4403
+ return isExitedState(state) ? { kind: "gone" } : { kind: "alive" };
4404
+ }
4405
+ /**
4406
+ * Poll the process-liveness probe for `pid` until it reports `gone` or
4407
+ * `deadlineMs` passes; return whether `gone` was read and the last read
4408
+ * (flair#2330). This is `flair doctor`'s stop wait.
4409
+ *
4410
+ * If both state reads fail, that poll stays `alive`.
4411
+ * Check expiry before each read; an admitted read gets at least 1s to finish.
4412
+ * Readers honoring their timeout allow deadline + 1s, plus scheduling and subprocess overhead.
4413
+ */
4414
+ export async function waitForPidGone(pid, deadlineMs, readState = readProcessState, pollMs = HEALTH_POLL_INTERVAL_MS, onReadError) {
4415
+ let last = { kind: "unknown", reason: "the stop deadline passed before a probe" };
4416
+ while (Date.now() < deadlineMs) {
4417
+ last = probePidLiveness(pid, readState, deadlineMs, onReadError);
4418
+ if (last.kind === "gone")
4419
+ return { gone: true, last };
4420
+ if (Date.now() >= deadlineMs)
4421
+ return { gone: false, last };
4422
+ const remaining = deadlineMs - Date.now();
4423
+ if (remaining <= 0)
4424
+ break;
4425
+ await new Promise((r) => setTimeout(r, Math.min(pollMs, remaining)));
4426
+ }
4427
+ return { gone: false, last };
4063
4428
  }
4064
4429
  /**
4065
4430
  * The health probe (flair#1478): ok only when the response is 2xx AND the
4066
4431
  * body is flair's /Health shape. A decoy that answers 200 is `foreign`,
4067
4432
  * not healed.
4433
+ *
4434
+ * flair#2485: the probe answers only for the port it probed. `redirect:
4435
+ * "manual"` stops it following a 3xx — a redirect from this port is a
4436
+ * response that is not a Flair health answer (`foreign`), so a port that
4437
+ * merely forwards elsewhere is never reported as ours (a followed redirect
4438
+ * could land on a Flair instance on another port and pass the fingerprint).
4068
4439
  */
4069
4440
  async function probeHealth(port) {
4070
4441
  try {
4071
- const res = await fetch(`http://127.0.0.1:${port}/Health`, { signal: AbortSignal.timeout(2000) });
4442
+ const res = await fetch(`http://127.0.0.1:${port}/Health`, { redirect: "manual", signal: AbortSignal.timeout(2000) });
4072
4443
  let body;
4073
4444
  try {
4074
4445
  body = await res.json();
@@ -4079,12 +4450,56 @@ async function probeHealth(port) {
4079
4450
  return classifyHealthProbe({ kind: "response", status: res.status, body });
4080
4451
  }
4081
4452
  catch (err) {
4082
- // Node's undici fetch reports ECONNREFUSED on `err.cause.code`; Bun reports
4083
- // `ConnectionRefused` on `err.code`. Both mean "nothing is listening".
4084
4453
  const code = err?.cause?.code ?? err?.code;
4085
4454
  return classifyHealthProbe({ kind: "network-error", code });
4086
4455
  }
4087
4456
  }
4457
+ /**
4458
+ * The adopt stop path's port-free probe (stopDirectProcessForAdopt). It
4459
+ * classifies the response with classifyHealthProbe, as probeHealth does, and
4460
+ * returns `unreachable` after 2 s or at `deadline`, whichever comes first.
4461
+ * Exported for tests.
4462
+ *
4463
+ * flair#2485: like probeHealth, it answers only for the port it probed —
4464
+ * `redirect: "manual"` stops it following a 3xx, so a redirect from this port
4465
+ * is a response that is not a Flair health answer (`foreign`).
4466
+ */
4467
+ export async function probeHealthBeforeDeadline(port, deadline) {
4468
+ const timeoutMs = Math.min(2000, deadline - Date.now());
4469
+ if (timeoutMs <= 0)
4470
+ return { kind: "unreachable" };
4471
+ const controller = new AbortController();
4472
+ let timer;
4473
+ const timeout = new Promise((resolve) => {
4474
+ timer = setTimeout(() => {
4475
+ controller.abort();
4476
+ resolve({ kind: "unreachable" });
4477
+ }, timeoutMs);
4478
+ });
4479
+ const observe = async () => {
4480
+ try {
4481
+ const res = await fetch(`http://127.0.0.1:${port}/Health`, { redirect: "manual", signal: controller.signal });
4482
+ let body;
4483
+ try {
4484
+ body = await res.json();
4485
+ }
4486
+ catch {
4487
+ body = null;
4488
+ }
4489
+ return classifyHealthProbe({ kind: "response", status: res.status, body });
4490
+ }
4491
+ catch (err) {
4492
+ const code = err?.cause?.code ?? err?.code;
4493
+ return classifyHealthProbe({ kind: "network-error", code });
4494
+ }
4495
+ };
4496
+ try {
4497
+ return await Promise.race([observe(), timeout]);
4498
+ }
4499
+ finally {
4500
+ clearTimeout(timer);
4501
+ }
4502
+ }
4088
4503
  /**
4089
4504
  * PIDs LISTENING on `port` via `lsof -ti :<port> -sTCP:LISTEN`, or null
4090
4505
  * when lsof is absent / unusable. Empty array means lsof ran and saw no
@@ -4172,12 +4587,22 @@ function inspectServingFlairPackage(pid) {
4172
4587
  return null;
4173
4588
  return resolveServingFlairPackage(pid) !== null;
4174
4589
  }
4175
- /** Gather every piece of evidence the classifier needs, in one place. */
4176
- export async function gatherDaemonEvidence(port, dataDir) {
4590
+ export function gatherDaemonOwnerEvidence(dataDir) {
4177
4591
  const dataDirUnsafe = checkDataDirSafe(dataDir);
4178
4592
  const pidfile = readPidfile(dataDir);
4179
- const pidLiveness = pidfile.kind === "present" ? probePidLiveness(pidfile.pid) : null;
4180
- let sidecar = readSidecar(dataDir);
4593
+ const sidecar = readSidecar(dataDir);
4594
+ const sidecarLiveness = sidecar.kind === "present" ? probePidLiveness(sidecar.pid) : null;
4595
+ const lastKnownPid = pidfile.kind === "absent" && sidecar.kind === "present" ? sidecar.pid : undefined;
4596
+ const pidLiveness = pidfile.kind === "present" ? probePidLiveness(pidfile.pid)
4597
+ : lastKnownPid !== undefined ? probePidLiveness(lastKnownPid)
4598
+ : pidfile.kind === "absent" && sidecar.kind === "unreadable" ? { kind: "unknown", reason: sidecar.reason } : null;
4599
+ return { dataDirUnsafe, pidfile, lastKnownPid, pidLiveness, sidecar, sidecarLiveness };
4600
+ }
4601
+ /** Gather every piece of evidence the classifier needs, in one place. */
4602
+ export async function gatherDaemonEvidence(port, dataDir) {
4603
+ const owner = gatherDaemonOwnerEvidence(dataDir);
4604
+ const { dataDirUnsafe, pidfile, lastKnownPid, pidLiveness, sidecarLiveness } = owner;
4605
+ let sidecar = owner.sidecar;
4181
4606
  // flair#2055: a sidecar that names a pid which is CONFIRMED gone is STALE, not
4182
4607
  // a disagreement with hdb.pid. After `flair stop` ended a directly started
4183
4608
  // Harper, the sidecar it wrote still names the stopped pid; a later instance
@@ -4189,7 +4614,7 @@ export async function gatherDaemonEvidence(port, dataDir) {
4189
4614
  // Liveness that cannot be determined is NOT stale: the sidecar stays and the
4190
4615
  // refusal stands (unknown evidence never licenses an action).
4191
4616
  if (sidecar.kind === "present" && dataDirUnsafe === null) {
4192
- if (classifySidecarStaleness(sidecar, probePidLiveness(sidecar.pid)).kind === "stale") {
4617
+ if (classifySidecarStaleness(sidecar, sidecarLiveness).kind === "stale") {
4193
4618
  sidecar = { kind: "absent" };
4194
4619
  }
4195
4620
  }
@@ -4210,8 +4635,7 @@ export async function gatherDaemonEvidence(port, dataDir) {
4210
4635
  // A stale or foreign pid holding the port is NOT healed. False-green is
4211
4636
  // worse than no self-heal.
4212
4637
  //
4213
- // The write uses the same O_NOFOLLOW / 0600 / atomic-rename posture as every
4214
- // other sidecar write. We skip self-heal when the dataDir is unsafe
4638
+ // The write uses mode 0600 and atomic rename. We skip self-heal when the dataDir is unsafe
4215
4639
  // (symlink / world-writable) — the check has already happened above.
4216
4640
  let portOwner = { kind: "unavailable" };
4217
4641
  let instanceMatch = { kind: "unavailable" };
@@ -4257,15 +4681,14 @@ export async function gatherDaemonEvidence(port, dataDir) {
4257
4681
  sidecar,
4258
4682
  readStartTime: readProcessStartTimeMs,
4259
4683
  });
4260
- return { dataDirUnsafe, pidfile, pidLiveness, identity, health };
4684
+ return { ...owner, identity, health };
4261
4685
  }
4262
4686
  /**
4263
- * Write the identity sidecar atomically (temp + rename) at spawn time or
4264
- * during self-heal (flair#1454 decision 3). `pid` is the spawned process's
4265
- * pid — the same number Harper writes to `hdb.pid`, since Harper runs
4266
- * in-process. `startTimeMs` defaults to `Date.now()` for a fresh spawn.
4687
+ * Write the identity sidecar atomically (temp + rename) for direct starts,
4688
+ * confirmed managed starts, or self-heal (flair#1454 decision 3).
4689
+ * `startTimeMs` defaults to `Date.now()` for a fresh direct spawn.
4267
4690
  *
4268
- * Self-heal callers pass the live process's actual start time (from
4691
+ * Managed start and self-heal callers pass the live process's actual start time (from
4269
4692
  * readProcessStartTimeMs) so the sidecar records an accurate epoch, not a
4270
4693
  * wall-clock approximation. Note: in the self-heal path the ±2s start-time
4271
4694
  * check in verifyIdentity is NOT what prevents recycled-pid adoption —
@@ -4288,40 +4711,17 @@ function writeDaemonSidecar(dataDir, pid, port, startTimeMs = Date.now()) {
4288
4711
  chmodSync(finalPath, 0o600);
4289
4712
  }
4290
4713
  /**
4291
- * Remove the identity sidecar left behind by a stop (flair#2055).
4292
- *
4293
- * A sidecar that still names a pid which is CONFIRMED gone is a leftover, and
4294
- * leaving it makes a later instance under a DIFFERENT supervisor refuse
4295
- * ("its identity could not be verified"). The removal is gated twice:
4296
- *
4297
- * 1. the pid the sidecar names must be CONFIRMED gone (ESRCH) — `unknown` or
4298
- * EPERM liveness removes nothing; and
4299
- * 2. a FRESH O_NOFOLLOW read taken just before the unlink must still name
4300
- * that pid. A sidecar another supervisor rewrote in between names a
4301
- * different pid and is left alone; a symlinked or malformed one reads as
4302
- * `unreadable` and is not removed either, because the re-read never
4303
- * followed the link.
4304
- *
4305
- * There is no lock: the re-read narrows the window to the gap between the read
4306
- * and the unlink, and the only loser of that race is a start that rewrote the
4307
- * sidecar in the gap — a live daemon left with no sidecar, which a later
4308
- * port-based stop or restart can RECOVER by self-heal once the live process
4309
- * supplies the required pidfile and health evidence (shouldAdoptMissingSidecar
4310
- * adopts the identity from the live process; see the recovery test). `flair
4311
- * status` does not re-adopt. A lock would buy
4312
- * nothing here and add a crash-recovery hazard, so the design relies on the
4313
- * self-heal instead. A writer OUTSIDE flair could substitute a symlink after
4314
- * the final read; that is out of scope (same as any other path flair re-reads
4315
- * by name). Best-effort: a failure to unlink is reported, never fatal.
4316
- */
4317
- export function removeStaleSidecarIfConfirmedDead(dataDir) {
4714
+ * Best-effort removal of a sidecar naming a PID the probe observed gone.
4715
+ * A matching confirmedGonePid skips another liveness probe; null probes it.
4716
+ * A fresh O_NOFOLLOW read must still name that PID. Non-ENOENT unlink errors are logged.
4717
+ */
4718
+ export function removeStaleSidecarIfConfirmedDead(dataDir, confirmedGonePid = null, probe = probePidLiveness) {
4318
4719
  const observed = readSidecar(dataDir);
4319
4720
  if (observed.kind !== "present")
4320
4721
  return;
4321
4722
  const observedPid = observed.pid;
4322
- const observedPidLiveness = probePidLiveness(observedPid);
4323
- // Re-read: only the sidecar that still names the confirmed-dead pid is ours
4324
- // to remove (a sidecar rewritten in the gap is left alone).
4723
+ const observedPidLiveness = confirmedGonePid !== null && confirmedGonePid === observedPid ? { kind: "gone" } : probe(observedPid);
4724
+ // A re-read naming a different PID is left alone.
4325
4725
  const fresh = readSidecar(dataDir);
4326
4726
  if (!shouldRemoveSidecarAfterStop({ observedPid, observedPidLiveness, sidecar: fresh }))
4327
4727
  return;
@@ -4397,6 +4797,7 @@ bindServiceCli({
4397
4797
  ensureLaunchdServiceLoaded,
4398
4798
  flairPackageDir,
4399
4799
  gatherDaemonEvidence,
4800
+ gatherDaemonOwnerEvidence,
4400
4801
  guardEngineNotBackwards,
4401
4802
  harperBinNotFoundMessage,
4402
4803
  harperSearchRoots,
@@ -4405,6 +4806,7 @@ bindServiceCli({
4405
4806
  observeLaunchdManagement,
4406
4807
  probeHealth,
4407
4808
  readyOpsSocketPosture,
4809
+ recordManagedStartSidecar,
4408
4810
  resolveHarperBin,
4409
4811
  resolveHttpBindHost,
4410
4812
  resolveHttpPort,
@@ -4576,10 +4978,11 @@ function validateLaunchdPlistContent(content, lint = lintLaunchdPlistContent) {
4576
4978
  * `null` (neither available) is handled by the caller as "no evidence", never
4577
4979
  * as "detached".
4578
4980
  */
4579
- function resolveInstanceServingPid(dataDir, port) {
4981
+ function resolveInstanceServingPid(dataDir, port, deps = {}) {
4580
4982
  let listeningPids = [];
4581
4983
  try {
4582
- listeningPids = listeningPidsOnPort(port, (cmd) => execSync(cmd, { encoding: "utf-8" }));
4984
+ listeningPids = deps.findListeningPids?.(port)
4985
+ ?? listeningPidsOnPort(port, () => execFileSync("lsof", ["-ti", `:${port}`, "-sTCP:LISTEN"], { encoding: "utf-8", timeout: 2_000, killSignal: "SIGKILL" }));
4583
4986
  }
4584
4987
  catch { /* lsof unavailable — the PID file may still answer */ }
4585
4988
  // flair#2056: the `hdb.pid` pid is used as PID-file evidence only when it is
@@ -4597,11 +5000,11 @@ function resolveInstanceServingPid(dataDir, port) {
4597
5000
  if (sidecar.kind === "present") {
4598
5001
  if (sidecar.pid !== pid)
4599
5002
  return false;
4600
- const startSecondMs = readProcessStartSecondMs(pid);
5003
+ const startSecondMs = (deps.readStartSecondMs ?? readProcessStartSecondMs)(pid);
4601
5004
  if (startSecondMs === null || !sidecarStartAgrees(startSecondMs, sidecar.startTimeMs))
4602
5005
  return false;
4603
5006
  }
4604
- const cmdline = defaultReadProcessCmdline(pid);
5007
+ const cmdline = (deps.readCmdline ?? defaultReadProcessCmdline)(pid);
4605
5008
  return cmdline !== null && isHarperProcessCommandLine(cmdline);
4606
5009
  };
4607
5010
  return pickInstancePid({
@@ -4947,6 +5350,92 @@ function observeLaunchdManagement(dataDir, port) {
4947
5350
  list: realLaunchctlLister,
4948
5351
  });
4949
5352
  }
5353
+ /**
5354
+ * Record the identity sidecar for the instance a launchd-managed start brought
5355
+ * up during a CLI-managed start (flair#2411). The direct start path writes one
5356
+ * immediately after spawn. A launchd KeepAlive relaunch does not write one.
5357
+ *
5358
+ * The sidecar is written after launchd reports the same pid before and after a
5359
+ * Flair-shaped health response and matching serving-pid and hdb.pid reads.
5360
+ * The writer uses an atomic temp+rename and mode 0600; pidfile and sidecar
5361
+ * reads use O_NOFOLLOW.
5362
+ *
5363
+ * A throwing waitForHealth call rethrows its original error so the caller's
5364
+ * existing fallback still runs; a failed Flair fingerprint and the other
5365
+ * unconfirmed cases return `recorded: false`. Each unconfirmed return also
5366
+ * names what the confirmation probe saw in `confirmation`, so the caller's
5367
+ * warning can report it (flair#2422).
5368
+ */
5369
+ export async function recordManagedStartSidecar(dataDir, port, label, deps = {}) {
5370
+ const warn = deps.warn ?? ((line) => console.error(line));
5371
+ const timeoutMs = deps.timeoutMs ?? STARTUP_TIMEOUT_MS;
5372
+ try {
5373
+ await (deps.waitForHealth ?? waitForHealth)(port, deps.adminUser ?? DEFAULT_ADMIN_USER, deps.adminPass ?? process.env.HDB_ADMIN_PASSWORD ?? "", timeoutMs);
5374
+ }
5375
+ catch (err) {
5376
+ warn(`⚠️ the instance for launchd job ${label} did not answer health within ${timeoutMs}ms, so its identity sidecar was not written (${err?.message ?? err})`);
5377
+ throw err;
5378
+ }
5379
+ // flair#2422: read launchd's job state, then probe health BEFORE branching on
5380
+ // that read. The probe is the confirmation's second look at the port, and its
5381
+ // result is what an unconfirmed start's warning reports.
5382
+ const job = readLaunchctlJobState(label, deps.list ?? realLaunchctlLister);
5383
+ const health = await (deps.probeHealth ?? probeHealth)(port);
5384
+ if (health.kind !== "ok") {
5385
+ const detail = `the instance for launchd job ${label} did not return Flair health (${health.kind}), so its identity sidecar was not written`;
5386
+ warn(`⚠️ ${detail}`);
5387
+ return { recorded: false, confirmation: health.kind, detail };
5388
+ }
5389
+ if (!job.registered) {
5390
+ const detail = `could not read launchd job ${label}, so its identity sidecar was not written`;
5391
+ warn(`⚠️ ${detail}`);
5392
+ return { recorded: false, confirmation: "flair", detail };
5393
+ }
5394
+ if (job.pid === null) {
5395
+ const detail = `launchd did not report a running pid for job ${label}, so its identity sidecar was not written`;
5396
+ warn(`⚠️ ${detail}`);
5397
+ return { recorded: false, confirmation: "flair", detail };
5398
+ }
5399
+ const serving = (deps.servingPid ?? ((_dataDir, httpPort) => {
5400
+ const listeners = resolveListenerPids(httpPort);
5401
+ return listeners?.length === 1 ? listeners[0] : null;
5402
+ }))(dataDir, port);
5403
+ if (serving === null) {
5404
+ const detail = `launchd job ${label} runs as process ${job.pid}, but the process serving this instance could not be identified, so its identity sidecar was not written`;
5405
+ warn(`⚠️ ${detail}`);
5406
+ return { recorded: false, confirmation: "flair", detail };
5407
+ }
5408
+ if (serving !== job.pid) {
5409
+ const detail = `the process answering on port ${port} is ${serving}, not launchd's process ${job.pid} for job ${label}, so its identity sidecar was not written`;
5410
+ warn(`⚠️ ${detail}`);
5411
+ return { recorded: false, confirmation: "flair", detail };
5412
+ }
5413
+ const again = readLaunchctlJobState(label, deps.list ?? realLaunchctlLister);
5414
+ if (!again.registered) {
5415
+ const detail = `could not re-read launchd job ${label}, so its identity sidecar was not written`;
5416
+ warn(`⚠️ ${detail}`);
5417
+ return { recorded: false, confirmation: "flair", detail };
5418
+ }
5419
+ if (again.pid !== job.pid) {
5420
+ const detail = `launchd job ${label} changed pid during health confirmation, so its identity sidecar was not written`;
5421
+ warn(`⚠️ ${detail}`);
5422
+ return { recorded: false, confirmation: "flair", detail };
5423
+ }
5424
+ const pidfile = readPidfile(dataDir);
5425
+ if (pidfile.kind !== "present" || pidfile.pid !== job.pid) {
5426
+ const detail = `hdb.pid does not confirm launchd job ${label}'s process ${job.pid}, so its identity sidecar was not written`;
5427
+ warn(`⚠️ ${detail}`);
5428
+ return { recorded: false, confirmation: "flair", detail };
5429
+ }
5430
+ const startTimeMs = (deps.readStartTime ?? readProcessStartTimeMs)(job.pid);
5431
+ if (startTimeMs === null) {
5432
+ const detail = `could not read the start time of launchd job ${label}'s process ${job.pid}, so its identity sidecar was not written`;
5433
+ warn(`⚠️ ${detail}`);
5434
+ return { recorded: false, confirmation: "flair", detail };
5435
+ }
5436
+ (deps.write ?? writeDaemonSidecar)(dataDir, job.pid, port, startTimeMs);
5437
+ return { recorded: true, pid: job.pid, detail: `launchd job ${label} is running as process ${job.pid}` };
5438
+ }
4950
5439
  // `preserveHttpPortValue` / `preserveSecurePort` / `bindHostOf` live in
4951
5440
  // src/lib/http-bind.ts so the CLI's plist writer and the pure repair PLANNER
4952
5441
  // (src/lib/launchd-repair.ts) share the exact same preservation rules, and the
@@ -5088,24 +5577,25 @@ function resolveAdminPassAvailability(path) {
5088
5577
  `Run 'flair init' to provision ${path}, or start the instance and re-run 'flair doctor --fix'.`,
5089
5578
  };
5090
5579
  }
5091
- /**
5092
- * Prove an admin credential belongs to the running instance before adoption
5093
- * materializes it into the 0600 pass file (flair#1685). The admin-gated
5094
- * /HealthDetail read is the proof: a rejected Basic credential produces 401 and
5095
- * is NOT retried through the agent-key floor (that floor only engages when no
5096
- * credential was sent at all), so success here means THIS credential was
5097
- * accepted by THIS instance. Never logs the secret.
5098
- */
5099
- async function proveAdminPassAgainstInstance(port, adminPass) {
5580
+ export async function proveAdminPassAgainstInstance(port, adminPass) {
5100
5581
  try {
5101
- await api("GET", "/HealthDetail", undefined, {
5582
+ await api("GET", "/FederationPeers", undefined, {
5102
5583
  baseUrl: `http://127.0.0.1:${port}`,
5103
5584
  explicitAdminPass: adminPass,
5585
+ adminUser: DEFAULT_ADMIN_USER,
5104
5586
  });
5105
5587
  return null;
5106
5588
  }
5107
5589
  catch (err) {
5108
- return err instanceof Error ? err.message : String(err);
5590
+ if (err instanceof Error && err.cause instanceof ApiHttpError)
5591
+ err = err.cause;
5592
+ if (err instanceof ApiHttpError && (err.status === 401 || err.status === 403)) {
5593
+ return `the supplied admin credential was rejected (HTTP ${err.status})`;
5594
+ }
5595
+ // Each ApiHttpError sendJsonRequest raises for this request begins its
5596
+ // message with `HTTP <status>`.
5597
+ const detail = err instanceof Error ? err.message : String(err);
5598
+ return `admin credential verification could not be completed (${detail})`;
5109
5599
  }
5110
5600
  }
5111
5601
  /**
@@ -5150,10 +5640,6 @@ function validateAdminPassFileForLauncher(path) {
5150
5640
  * file and the command named and write NO plist. Never a plist whose
5151
5641
  * launcher argv cannot be satisfied.
5152
5642
  *
5153
- * The proof uses the same authed `GET /HealthDetail` as the doctor arms (a
5154
- * rejected Basic credential is a 401 and never falls through to the agent-key
5155
- * floor), so a credential that does not belong to THIS instance is refused
5156
- * rather than baked into a pass file the instance would reject.
5157
5643
  */
5158
5644
  export async function writeInitLaunchdPlist(opts, deps = {}) {
5159
5645
  const prove = deps.prove ?? proveAdminPassAgainstInstance;
@@ -5293,8 +5779,16 @@ export async function writeInitLaunchdPlist(opts, deps = {}) {
5293
5779
  return { kind: "written", plistPath: opts.plistPath };
5294
5780
  }
5295
5781
  /**
5296
- * Put the plist `flair init` wrote back as `prior` recorded it (flair#2040,
5297
- * flair#2078): its prior bytes, or removed when there was none. Never throws:
5782
+ * The exit code `flair init` uses for its launchd step's outcome (flair#2040):
5783
+ * 1 for the refused, down and uncertain failure outcomes; 0 otherwise.
5784
+ * A refusal may leave an existing launchd registration serving normally.
5785
+ */
5786
+ function initLaunchdExitCode(kind) {
5787
+ return kind === "refused" || kind === "down" || kind === "uncertain" ? 1 : 0;
5788
+ }
5789
+ /**
5790
+ * Restore the plist path to `prior` (flair#2040, flair#2078): its prior bytes,
5791
+ * or absent when there was none. Never throws:
5298
5792
  * `ok` false means the put-back FAILED, and `text` says so with the error.
5299
5793
  */
5300
5794
  function putInitPlistBack(path, prior) {
@@ -5306,12 +5800,29 @@ function putInitPlistBack(path, prior) {
5306
5800
  }
5307
5801
  return {
5308
5802
  ok: true,
5309
- text: prior.kind === "absent" ? `the new plist ${path} was removed again` : `the plist at ${path} was put back as it was`,
5803
+ text: prior.kind === "absent" ? `the new plist ${path} was removed again` : `the prior plist bytes and mode at ${path} were restored`,
5310
5804
  };
5311
5805
  }
5806
+ function validateInitPlistAfterWrite(write) {
5807
+ const installing = `the plist init would install for ${write.label}`;
5808
+ let refusal = null;
5809
+ try {
5810
+ const problem = validateLaunchdPlistContent(readFileSync(write.plistPath, "utf-8"), (content) => lintReplacementPlist(content, launchdMigrationLintForTests ?? lintLaunchdPlistContent, (failure) => `${installing} could not be validated (${failure})`));
5811
+ if (problem !== null) {
5812
+ refusal = { why: `${installing} cannot be loaded (${problem})`, fix: "npm install -g @tpsdev-ai/flair && flair init" };
5813
+ }
5814
+ }
5815
+ catch (e) {
5816
+ refusal = isLaunchdValidationRefusal(e)
5817
+ ? { why: e.message, fix: `make sure the temporary directory (${tmpdir()}) exists and is writable, and re-run 'flair init'.` }
5818
+ : { why: `${installing} could not be validated (${e?.message ?? String(e)})`, fix: "resolve the error above, and re-run 'flair init'." };
5819
+ }
5820
+ return refusal;
5821
+ }
5312
5822
  /**
5313
- * `flair init`'s launchd step (flair#2040): write this instance's plist, retire
5314
- * a pre-flair#693 legacy registration, and report ONLY what was verified.
5823
+ * `flair init`'s launchd step (flair#2040): may write or repoint this
5824
+ * instance's plist, retire a pre-flair#693 legacy registration, and report ONLY
5825
+ * what was verified.
5315
5826
  *
5316
5827
  * init starts Flair DIRECTLY and, since 9e3bd9ad, deliberately does not bounce
5317
5828
  * a running instance into launchd — so the ordinary outcome is "plist on disk,
@@ -5322,21 +5833,29 @@ function putInitPlistBack(path, prior) {
5322
5833
  * The one path that stops something is retiring a LEGACY job that is the
5323
5834
  * process serving this instance: booting it out stops Flair. That path follows
5324
5835
  * the same rule as `doctor --fix`: preflight first (domain reachable, job
5325
- * enabled), write + validate the replacement plist while the instance is still
5836
+ * enabled), prepare + validate the replacement plist while the instance is still
5326
5837
  * up, and only then boot the legacy job out, load the replacement with
5327
- * targeted commands and verify it; any failure after the boot-out restores the
5328
- * legacy plist and job (or, failing that, starts Flair directly) and says so.
5838
+ * targeted commands, and verify it.
5329
5839
  * If the preflight fails, NOTHING is unloaded, removed or written; if the
5330
- * validation fails — a lint that throws included (flair#2078) — nothing is
5331
- * unloaded or removed, and the plist init wrote is put back as it was.
5840
+ * validation fails — a lint that throws included (flair#2078) — no job is
5841
+ * unloaded and plist rollback is attempted; failure returns `uncertain`. The
5842
+ * non-legacy path uses the same rule (flair#2085).
5332
5843
  */
5333
- async function registerInitLaunchdService(input) {
5844
+ async function registerInitLaunchdService(input, validateAfterWrite = validateInitPlistAfterWrite) {
5334
5845
  const { dataDir, port, plistDir, write } = input;
5335
5846
  const uid = currentUid();
5336
5847
  const domain = launchdGuiDomain(uid);
5337
5848
  const lines = [];
5338
5849
  const out = (text) => lines.push({ stream: "out", text });
5339
5850
  const err = (text) => lines.push({ stream: "err", text });
5851
+ const refuseInvalidPlist = (prior, frame) => {
5852
+ const refusal = validateAfterWrite(write);
5853
+ if (refusal === null)
5854
+ return null;
5855
+ const putBack = putInitPlistBack(write.plistPath, prior);
5856
+ frame(refusal, putBack);
5857
+ return { kind: putBack.ok ? "skipped" : "uncertain", lines };
5858
+ };
5340
5859
  const legacyPath = launchdPlistPath(LEGACY_LAUNCHD_LABEL, plistDir);
5341
5860
  const legacyRoot = existsSync(legacyPath) ? readPlistRootPath(legacyPath) : null;
5342
5861
  const legacyOwned = legacyRoot !== null && resolve(legacyRoot) === resolve(dataDir);
@@ -5345,9 +5864,35 @@ async function registerInitLaunchdService(input) {
5345
5864
  // helper prints why. With no legacy plist it is a no-op.
5346
5865
  if (existsSync(legacyPath))
5347
5866
  cleanupLegacyLaunchdPlist(dataDir, plistDir, realLaunchctlCommand, uid);
5867
+ // flair#2085: with no owned legacy job, the writer may write, repoint or
5868
+ // leave the plist unchanged. Validate the target (a thrown lint refuses).
5869
+ // On failure, attempt rollback; failure returns `uncertain`. No launchctl
5870
+ // mutation occurs on this path. Refuse an unsafe snapshot before writing.
5871
+ const priorNew = snapshotFile(write.plistPath);
5872
+ if (priorNew.kind === "symlink") {
5873
+ err(`⚠️ Launchd: not registered — ${write.plistPath} is a symbolic link, so no plist was written.`);
5874
+ err(` Fix: move or remove the symbolic link at ${write.plistPath}, then re-run 'flair init'.`);
5875
+ return { kind: "skipped", lines };
5876
+ }
5877
+ const unreadableNew = unreadableSnapshot([[write.plistPath, priorNew]]);
5878
+ if (unreadableNew) {
5879
+ err(`⚠️ Launchd: not registered — ${unreadableNew} could not be safely snapshotted, so it could not be put back. No plist was written.`);
5880
+ return { kind: "skipped", lines };
5881
+ }
5348
5882
  const outcome = await writeInitLaunchdPlist(write);
5349
5883
  if (outcome.kind === "refused")
5350
5884
  return { kind: "refused", lines: [{ stream: "err", text: `Error: ${outcome.detail}` }] };
5885
+ const refused = refuseInvalidPlist(priorNew, (refusal, putBack) => {
5886
+ err(`⚠️ Launchd: not registered — ${refusal.why}. ${putBack.text}.`);
5887
+ if (!putBack.ok) {
5888
+ err(` Fix: remove ${write.plistPath} (its loadability is unverified and rollback failed); then ${refusal.fix}`);
5889
+ }
5890
+ else {
5891
+ err(` Fix: ${refusal.fix}`);
5892
+ }
5893
+ });
5894
+ if (refused)
5895
+ return refused;
5351
5896
  return reportInitLaunchd(dataDir, port, write, outcome, lines);
5352
5897
  }
5353
5898
  const keptLegacy = `Nothing was unloaded or removed: the legacy job ${LEGACY_LAUNCHD_LABEL} and its plist at ${legacyPath} were left as they were`;
@@ -5413,13 +5958,18 @@ async function registerInitLaunchdService(input) {
5413
5958
  // cannot be read cannot be put back: refuse before anything is written.
5414
5959
  const priorNew = snapshotFile(write.plistPath);
5415
5960
  const priorLegacy = snapshotFile(legacyPath);
5961
+ if (priorNew.kind === "symlink") {
5962
+ err(`⚠️ Launchd: not re-registered — ${write.plistPath} is a symbolic link, so no new plist was written. ${keptLegacy}.`);
5963
+ err(` Fix: move or remove the symbolic link at ${write.plistPath}, then re-run 'flair init'.`);
5964
+ return { kind: "skipped", lines };
5965
+ }
5416
5966
  const unreadable = unreadableSnapshot([[write.plistPath, priorNew], [legacyPath, priorLegacy]]);
5417
5967
  if (unreadable) {
5418
- err(`⚠️ Launchd: not re-registered — ${unreadable} exists but could not be read, so it could not be put back. ${keptLegacy}.`);
5968
+ err(`⚠️ Launchd: not re-registered — ${unreadable} could not be safely snapshotted, so it could not be put back. ${keptLegacy}.`);
5419
5969
  return { kind: "skipped", lines };
5420
5970
  }
5421
- // The replacement is written and validated while the instance is still up
5422
- // (the writer proves the credential against it).
5971
+ // The writer may write, repoint or leave the plist unchanged. Validate the
5972
+ // target while the instance is up.
5423
5973
  const outcome = await writeInitLaunchdPlist(write);
5424
5974
  if (outcome.kind === "refused") {
5425
5975
  return {
@@ -5430,45 +5980,26 @@ async function registerInitLaunchdService(input) {
5430
5980
  ],
5431
5981
  };
5432
5982
  }
5433
- // Every failed validation is a refusal made before anything is unloaded: a
5434
- // problem the checks REPORT, and — as in the start paths' migration — a lint
5435
- // that THROWS (lintReplacementPlist) or a written plist that cannot be read
5436
- // back (flair#2078). Each puts the plist just written back as it was, or
5437
- // removes it when there was none: left beside the legacy plist, it would give
5438
- // launchd two jobs for one data directory at the next login.
5439
- const installing = `the plist init would install for ${write.label}`;
5440
- let refusal = null;
5441
- try {
5442
- const problem = validateLaunchdPlistContent(readFileSync(write.plistPath, "utf-8"), (content) => lintReplacementPlist(content, launchdMigrationLintForTests ?? lintLaunchdPlistContent, (failure) => `${installing} could not be validated (${failure})`));
5443
- if (problem !== null) {
5444
- refusal = { why: `${installing} cannot be loaded (${problem})`, fix: "npm install -g @tpsdev-ai/flair && flair init" };
5445
- }
5446
- }
5447
- catch (e) {
5448
- refusal = isLaunchdValidationRefusal(e)
5449
- ? { why: e.message, fix: `make sure the temporary directory (${tmpdir()}) exists and is writable, and re-run 'flair init'.` }
5450
- : { why: `${installing} could not be validated (${e?.message ?? String(e)})`, fix: "resolve the error above, and re-run 'flair init'." };
5451
- }
5452
- if (refusal !== null) {
5453
- const putBack = putInitPlistBack(write.plistPath, priorNew);
5983
+ const refused = refuseInvalidPlist(priorNew, (refusal, putBack) => {
5454
5984
  err(`⚠️ Launchd: not re-registered — ${refusal.why}. Nothing was unloaded: the legacy job ${LEGACY_LAUNCHD_LABEL} ` +
5455
5985
  `and its plist at ${legacyPath} were left as they were, and ${putBack.text}.`);
5456
5986
  if (!putBack.ok) {
5457
5987
  err(` Fix: remove ${write.plistPath} (beside the legacy plist, launchd would load two jobs for this data ` +
5458
5988
  `directory at the next login); then ${refusal.fix}`);
5459
- return { kind: "uncertain", lines };
5460
5989
  }
5461
- err(` Fix: ${refusal.fix}`);
5462
- return { kind: "skipped", lines };
5463
- }
5990
+ else {
5991
+ err(` Fix: ${refusal.fix}`);
5992
+ }
5993
+ });
5994
+ if (refused)
5995
+ return refused;
5464
5996
  if (role !== "serving") {
5465
5997
  // PROVEN not serving (absent, or idle): retiring it stops nothing.
5466
5998
  const cleanup = cleanupLegacyLaunchdPlist(dataDir, plistDir, realLaunchctlCommand, uid);
5467
5999
  if (cleanup.action === "unload-unconfirmed") {
5468
6000
  // flair#2040: the legacy job could not be shown unloaded, and the helper
5469
- // KEPT its plist. The replacement written above must not stay beside it
5470
- // (two plists for one data directory would give launchd two jobs), so it
5471
- // is put back as it was, and nothing is reported as registered.
6001
+ // KEPT its plist. Rollback attempts to restore the target's prior state;
6002
+ // the result is uncertain even if rollback succeeds.
5472
6003
  const putBack = putInitPlistBack(write.plistPath, priorNew);
5473
6004
  err(`⚠️ Launchd: not re-registered — the legacy job ${LEGACY_LAUNCHD_LABEL} could not be shown unloaded ` +
5474
6005
  `(${cleanup.unloadFailed}), so it may still be loaded. Its plist at ${legacyPath} was left in place, and ${putBack.text}.`);
@@ -5745,10 +6276,7 @@ function planLaunchdRepairFor(dataDir, port) {
5745
6276
  * TWO PHASES (flair#2040). The rule for this handoff: the running instance
5746
6277
  * is not stopped, and no launchd job is unloaded, until every check that can
5747
6278
  * be made about the replacement from THIS session has passed; an UNKNOWN
5748
- * answer is a failed check, never a pass. Every failure after that point is
5749
- * followed by an attempt to bring back what was running, and the result
5750
- * reports the state the instance was left in — including when that state
5751
- * could not be established.
6279
+ * answer is a failed check, never a pass.
5752
6280
  *
5753
6281
  * 1. PREPARE (prepareLaunchdRepair) — reads and validation; the running
5754
6282
  * instance and launchd are untouched:
@@ -5778,14 +6306,7 @@ function planLaunchdRepairFor(dataDir, port) {
5778
6306
  * its port does not answer, and verify STRICTLY: Flair's /Health answers
5779
6307
  * ok and launchd's pid is the IDENTIFIED serving pid
5780
6308
  * (judgeLaunchdJobServing), and on adopt the serving pid
5781
- * changed and the old one is dead (flair#1684/#1685). ANY failure here
5782
- * goes through restoreAfterFailedRepair.
5783
- *
5784
- * The preflight cannot PROVE a bootstrap will succeed — only loading something
5785
- * proves that — which is why phase 2 restores rather than assumes.
5786
- *
5787
- * Never reports success on a direct start or an unattributed process. Every
5788
- * throw becomes a named result, never a crash mid-report.
6309
+ * changed and the old one is dead (flair#1684/#1685).
5789
6310
  */
5790
6311
  async function repairLaunchdManagement(dataDir, port) {
5791
6312
  const { plan, plistPath, isLegacy, config } = planLaunchdRepairFor(dataDir, port);
@@ -5818,31 +6339,54 @@ async function repairLaunchdManagement(dataDir, port) {
5818
6339
  }
5819
6340
  }
5820
6341
  function snapshotFile(path) {
6342
+ let stat;
5821
6343
  try {
5822
- const bytes = readFileSync(path);
5823
- return { kind: "present", bytes, mode: statSync(path).mode & 0o777 };
6344
+ stat = lstatSync(path);
5824
6345
  }
5825
6346
  catch (err) {
5826
6347
  if (err?.code === "ENOENT")
5827
6348
  return { kind: "absent" };
5828
6349
  return { kind: "unreadable", error: `${err?.code ?? "error"}: ${err?.message ?? err}` };
5829
6350
  }
6351
+ if (stat.isSymbolicLink())
6352
+ return { kind: "symlink" };
6353
+ try {
6354
+ // O_NOFOLLOW also rejects a link substituted after lstat. Read and stat
6355
+ // the same opened file, so a replacement cannot mix bytes with old mode.
6356
+ const fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
6357
+ try {
6358
+ const opened = fstatSync(fd);
6359
+ if (!opened.isFile())
6360
+ return { kind: "unreadable", error: "not a regular file" };
6361
+ return { kind: "present", bytes: readFileSync(fd), mode: opened.mode & 0o7777 };
6362
+ }
6363
+ finally {
6364
+ closeSync(fd);
6365
+ }
6366
+ }
6367
+ catch (err) {
6368
+ return { kind: "unreadable", error: `${err?.code ?? "error"}: ${err?.message ?? err}` };
6369
+ }
5830
6370
  }
5831
6371
  /** The first snapshot that could not be taken, as "<path> (<error>)", or null. */
5832
6372
  function unreadableSnapshot(entries) {
5833
6373
  for (const [path, snap] of entries) {
5834
- if (snap && snap.kind === "unreadable")
6374
+ if (snap?.kind === "symlink")
6375
+ return `${path} (symbolic link)`;
6376
+ if (snap?.kind === "unreadable")
5835
6377
  return `${path} (${snap.error})`;
5836
6378
  }
5837
6379
  return null;
5838
6380
  }
5839
6381
  /**
5840
6382
  * Put a file back as `snapshot` recorded it: rewritten byte-for-byte (the raw
5841
- * buffer) when it was present, removed ONLY when it was proven absent. An
5842
- * unreadable snapshot is never "restored" — that would delete or clobber a
5843
- * file whose bytes were never known.
6383
+ * buffer) when it was present, removed ONLY when it was proven absent. A
6384
+ * symlink or unreadable snapshot is never "restored" as a regular file.
5844
6385
  */
5845
6386
  function restoreFile(path, snapshot) {
6387
+ if (snapshot.kind === "symlink") {
6388
+ throw new Error(`not restoring ${path}: its prior state was a symbolic link`);
6389
+ }
5846
6390
  if (snapshot.kind === "unreadable") {
5847
6391
  throw new Error(`not restoring ${path}: its prior contents could not be read (${snapshot.error})`);
5848
6392
  }
@@ -5856,7 +6400,7 @@ function restoreFile(path, snapshot) {
5856
6400
  }
5857
6401
  return;
5858
6402
  }
5859
- writeFileAtomic(path, snapshot.bytes, snapshot.mode);
6403
+ writeFileAtomic(path, snapshot.bytes, snapshot.mode, { exactMode: true });
5860
6404
  }
5861
6405
  /**
5862
6406
  * Phase 1 of the repair: every check that can be made without stopping the
@@ -5902,7 +6446,7 @@ async function prepareLaunchdRepair(dataDir, port, plan, resolvedPlistPath, isLe
5902
6446
  return {
5903
6447
  kind: "refused",
5904
6448
  reason: "unreadable-prior-state",
5905
- detail: `refusing to repair launchd management: ${unreadable} exists but could not be read, so a failed hand-off ` +
6449
+ detail: `refusing to repair launchd management: ${unreadable} could not be safely snapshotted, so a failed hand-off ` +
5906
6450
  `could not put it back. ${untouched}`,
5907
6451
  plistPath: resolvedPlistPath,
5908
6452
  };
@@ -6027,7 +6571,6 @@ async function prepareLaunchdRepair(dataDir, port, plan, resolvedPlistPath, isLe
6027
6571
  },
6028
6572
  };
6029
6573
  }
6030
- /** Phase 2: the bounce, with restore on any failure. */
6031
6574
  async function commitLaunchdRepair(p) {
6032
6575
  const done = { unloadedPrior: false, stopped: false, wrotePlist: false, removedLegacy: false, wroteConfig: false, loaded: false };
6033
6576
  try {
@@ -6049,10 +6592,18 @@ async function commitLaunchdRepair(p) {
6049
6592
  // job does not collide on the port. The captured pid is the evidence the
6050
6593
  // verify uses to prove the serving pid CHANGED.
6051
6594
  if (p.arm === "adopt") {
6052
- done.stopped = true;
6053
6595
  const stop = await stopDirectProcessForAdopt(p.port, p.dataDir);
6054
- if (stop)
6055
- throw new Error(stop.kind === "failed" || stop.kind === "refused" ? stop.detail : "the direct process could not be stopped");
6596
+ if (stop) {
6597
+ if (done.unloadedPrior && (stop.failure.kind === "failed" || stop.failure.kind === "refused")) {
6598
+ stop.failure.detail += " Previously loaded launchd jobs were unloaded.";
6599
+ }
6600
+ if (stop.observedExit && stop.failure.kind === "failed") {
6601
+ done.stopped = true;
6602
+ throw new Error(stop.failure.detail);
6603
+ }
6604
+ return stop.failure;
6605
+ }
6606
+ done.stopped = true;
6056
6607
  }
6057
6608
  // 3. Write the validated plist (pass-file mode, no secret: 0644).
6058
6609
  done.wrotePlist = true;
@@ -6249,7 +6800,7 @@ async function restoreAfterFailedRepair(p, done, cause) {
6249
6800
  }
6250
6801
  /**
6251
6802
  * Clean-stop the direct (non-launchd) process serving `dataDir`+`port` for the
6252
- * adopt path (flair#1573 slice b2). Returns a `failed` result when the process
6803
+ * adopt path (flair#1573 slice b2). Returns a failure outcome when the process
6253
6804
  * cannot be attributed (never stop a foreign process) or the port is still
6254
6805
  * occupied after the stop; returns null when the port is free and the caller
6255
6806
  * should proceed to regenerate + load.
@@ -6262,41 +6813,104 @@ async function restoreAfterFailedRepair(p, done, cause) {
6262
6813
  async function stopDirectProcessForAdopt(port, dataDir) {
6263
6814
  const evidence = await gatherDaemonEvidence(port, dataDir);
6264
6815
  const state = classifyDaemonState(evidence, { port, dataDir });
6265
- // SIGTERM + wait for exit for a verified live pid (RUNNING or WEDGED — a
6266
- // wedged daemon is recovery, not a recycled-pid gamble).
6816
+ const stopDeadline = Date.now() + ADOPT_STOP_TIMEOUT_MS;
6817
+ let observedExit = false;
6818
+ const failure = (result) => ({ failure: result, observedExit });
6819
+ const timeoutResult = (stage) => ({
6820
+ kind: "failed",
6821
+ detail: `Timed out after ${ADOPT_STOP_TIMEOUT_MS}ms ${stage} for ${dataDir}. No replacement launchd job was loaded.`,
6822
+ remedy: [`Inspect ${dataDir}/log/hdb.log; run flair doctor --fix after resolving the stop failure`],
6823
+ });
6267
6824
  if (state.state === "RUNNING" || state.state === "WEDGED") {
6825
+ let signalResult = "SIGTERM sent";
6268
6826
  try {
6269
6827
  process.kill(state.pid, "SIGTERM");
6270
6828
  }
6271
- catch { /* already gone */ }
6272
- try {
6273
- await waitForProcessExit(state.pid, STARTUP_TIMEOUT_MS);
6829
+ catch (err) {
6830
+ signalResult = err?.code === "ESRCH" ? "SIGTERM found no process (ESRCH)" : `SIGTERM failed (${err?.code ?? "unknown error"})`;
6274
6831
  }
6275
- catch { /* best-effort — the port check below surfaces the real problem */ }
6832
+ const identity = verifyIdentity({
6833
+ pidfilePid: state.pid,
6834
+ sidecar: evidence.identity.kind === "verified" ? readSidecar(dataDir) : { kind: "absent" },
6835
+ readStartTime: (pid) => readProcessStartTimeMs(pid, Math.min(stopDeadline, Date.now() + 2_000)),
6836
+ });
6837
+ const identityObservedAt = Date.now();
6838
+ const stopGone = await waitForPidGone(state.pid, stopDeadline);
6839
+ if (!stopGone.gone) {
6840
+ const liveness = stopGone.last;
6841
+ const result = timeoutResult(`waiting for direct Harper process ${state.pid} to exit`);
6842
+ const identityDetail = identityObservedAt < stopDeadline
6843
+ ? `${identity.kind}, observed at ${new Date(identityObservedAt).toISOString()}`
6844
+ : "not observed before the deadline";
6845
+ if (result.kind === "failed")
6846
+ result.detail += ` ${signalResult}; not observed to exit before the deadline (liveness: ${liveness.kind}; identity: ${identityDetail}).`;
6847
+ return failure(result);
6848
+ }
6849
+ observedExit = true;
6850
+ }
6851
+ const stateDecision = decideAdoptStop(state, { kind: "refused" });
6852
+ if (stateDecision !== "proceed")
6853
+ return failure(stateDecision);
6854
+ let health = { kind: "unreachable" };
6855
+ while (Date.now() < stopDeadline) {
6856
+ health = await probeHealthBeforeDeadline(port, stopDeadline);
6857
+ if (Date.now() >= stopDeadline)
6858
+ break;
6859
+ if (health.kind === "refused")
6860
+ break;
6861
+ const remaining = stopDeadline - Date.now();
6862
+ if (remaining <= 0)
6863
+ break;
6864
+ await new Promise((r) => setTimeout(r, Math.min(250, remaining)));
6865
+ }
6866
+ if (Date.now() >= stopDeadline)
6867
+ return failure(timeoutResult(`waiting for port ${port} to free (last health probe: ${health.kind})`));
6868
+ const decision = decideAdoptStop(state, health);
6869
+ if (decision !== "proceed")
6870
+ return failure(decision);
6871
+ const listenerTimeout = Math.min(2_000, stopDeadline - Date.now());
6872
+ if (listenerTimeout <= 0)
6873
+ return failure(timeoutResult(`checking the final listener on port ${port}`));
6874
+ let output;
6875
+ let noMatch = false;
6876
+ try {
6877
+ output = execFileSync("lsof", ["-ti", `:${port}`, "-sTCP:LISTEN"], {
6878
+ encoding: "utf-8", timeout: listenerTimeout, killSignal: "SIGKILL",
6879
+ });
6276
6880
  }
6277
- // flair#1827: poll the post-stop health until the port is provably free — a
6278
- // single observation that caught the listener mid-release flaked with "port
6279
- // not confirmed free". decideAdoptStop is UNCHANGED; it decides on the final
6280
- // observation, and a timeout names the wait and the last probe.
6281
- const decision = await decideAdoptStopWithWait(state, {
6282
- observe: () => probeHealth(port),
6283
- deadlineMs: STARTUP_TIMEOUT_MS,
6284
- });
6285
- if (decision.decision !== "proceed")
6286
- return decision.decision;
6287
- // Belt-and-suspenders: lsof confirms no TCP listener remains before the
6288
- // caller loads the plist. probeHealth "refused" (ECONNREFUSED) already means
6289
- // nothing is listening, but a port that is BOUND yet refuses connections
6290
- // (backlog-full, or a non-HTTP listener) would still EADDRINUSE on load —
6291
- // this catches that rare case the HTTP probe cannot see.
6292
- const { execSync } = await import("node:child_process");
6293
- const listeners = listeningPidsOnPort(port, (cmd) => execSync(cmd, { encoding: "utf-8" }));
6881
+ catch (err) {
6882
+ if (err?.status === 1 && !err?.error && !err?.code && !err?.signal &&
6883
+ typeof err?.stdout === "string" && err.stdout.trim() === "" &&
6884
+ typeof err?.stderr === "string" && err.stderr.trim() === "") {
6885
+ output = "";
6886
+ noMatch = true;
6887
+ }
6888
+ else {
6889
+ return failure({
6890
+ kind: "failed",
6891
+ detail: `Final listener probe failed for port ${port} (${err?.code ?? err?.signal ?? err?.status ?? "unknown error"}). No replacement launchd job was loaded.`,
6892
+ remedy: ["Check lsof; run flair doctor --fix after resolving the probe failure"],
6893
+ });
6894
+ }
6895
+ }
6896
+ if (Date.now() >= stopDeadline)
6897
+ return failure(timeoutResult(`checking the final listener on port ${port}`));
6898
+ if (noMatch)
6899
+ return null;
6900
+ if (typeof output !== "string" || output.trim() === "") {
6901
+ return failure({ kind: "failed", detail: `Final listener probe failed for port ${port} (unusable lsof output).`, remedy: ["Check lsof", "flair doctor --fix"] });
6902
+ }
6903
+ const lines = output.trim().split("\n");
6904
+ if (lines.some((line) => !/^[1-9][0-9]*$/.test(line.trim()) || !Number.isSafeInteger(Number(line.trim())))) {
6905
+ return failure({ kind: "failed", detail: `Final listener probe failed for port ${port} (unusable lsof output).`, remedy: ["Check lsof", "flair doctor --fix"] });
6906
+ }
6907
+ const listeners = lines.map(Number);
6294
6908
  if (listeners.length > 0) {
6295
- return {
6909
+ return failure({
6296
6910
  kind: "failed",
6297
6911
  detail: `port still occupied after stopping the direct process (listener pid ${listeners.join(", ")})`,
6298
6912
  remedy: ["flair stop", "flair doctor --fix"],
6299
- };
6913
+ });
6300
6914
  }
6301
6915
  return null;
6302
6916
  }
@@ -6324,7 +6938,16 @@ async function stopDirectProcessForAdopt(port, dataDir) {
6324
6938
  * the liveness machine. Callers already treat a failed stop as fatal, which
6325
6939
  * is the point: refusing beats quiescing the wrong install.
6326
6940
  */
6327
- async function stopFlairProcess(port, dataDir) {
6941
+ async function stopFlairProcess(port, dataDir, opts = {}) {
6942
+ const waitForExit = opts.waitForExit ?? waitForProcessExit;
6943
+ let launchdExitFailure = null;
6944
+ const fallbackOutcome = (outcome) => {
6945
+ if (!launchdExitFailure)
6946
+ return outcome;
6947
+ if (probePidLiveness(launchdExitFailure.pid).kind !== "gone")
6948
+ return launchdExitFailure;
6949
+ return { pid: outcome.pid ?? launchdExitFailure.pid, exited: outcome.exited };
6950
+ };
6328
6951
  if (process.platform === "darwin") {
6329
6952
  // resolveLaunchdLabel (flair#693) finds whichever label this data dir
6330
6953
  // is currently registered under (new instance-scoped, or a
@@ -6372,22 +6995,33 @@ async function stopFlairProcess(port, dataDir) {
6372
6995
  plistPath,
6373
6996
  instancePid: oldPid,
6374
6997
  plistExists: existsSync,
6375
- list: realLaunchctlLister,
6998
+ list: opts.launchctl?.list ?? realLaunchctlLister,
6376
6999
  })
6377
7000
  : null;
6378
7001
  // unload stops the job AND prevents KeepAlive from respawning it.
6379
7002
  // launchctl stop alone is insufficient for a KeepAlive job (flair#874).
6380
7003
  try {
6381
- execSync(`launchctl unload "${plistPath}"`, { stdio: "pipe" });
7004
+ if (opts.launchctl)
7005
+ opts.launchctl.unload(plistPath);
7006
+ else
7007
+ execSync(`launchctl unload "${plistPath}"`, { stdio: "pipe" });
6382
7008
  }
6383
7009
  catch { }
6384
7010
  if (managed && isDetached(managed)) {
6385
7011
  throw new Error(`launchd is not running this instance — ${managed.detail}`
6386
7012
  + `${managed.remedy?.length ? ` Fix it with: ${managed.remedy.join(" && ")}` : ""}`);
6387
7013
  }
6388
- if (oldPid)
6389
- await waitForProcessExit(oldPid, STARTUP_TIMEOUT_MS);
6390
- return;
7014
+ if (oldPid) {
7015
+ try {
7016
+ await waitForExit(oldPid, STARTUP_TIMEOUT_MS);
7017
+ }
7018
+ catch (err) {
7019
+ launchdExitFailure = { pid: oldPid, exited: false };
7020
+ throw err;
7021
+ }
7022
+ }
7023
+ removeStaleSidecarIfConfirmedDead(dataDir, oldPid);
7024
+ return { pid: oldPid ?? null, exited: true };
6391
7025
  }
6392
7026
  catch (err) {
6393
7027
  console.error(`launchd stop failed, falling back to port-based stop: ${err.message}`);
@@ -6417,29 +7051,30 @@ async function stopFlairProcess(port, dataDir) {
6417
7051
  // blind sleep is not a guarantee — Harper may be flushing RocksDB
6418
7052
  // WAL/MANIFEST, and the next start fails with a locked data directory if
6419
7053
  // the old process hasn't released it yet.
7054
+ let exited = true;
6420
7055
  try {
6421
- await waitForProcessExit(pid, STARTUP_TIMEOUT_MS);
7056
+ await waitForExit(pid, STARTUP_TIMEOUT_MS);
6422
7057
  }
6423
- catch { /* best-effort — the next start will surface the real problem */ }
6424
- // flair#2055: once the process is CONFIRMED gone, drop the identity
6425
- // sidecar. Gated on a fresh O_NOFOLLOW read that still names the pid it
6426
- // named before (a sidecar another supervisor rewrote in between is left
6427
- // alone); a process that survived the wait (or whose liveness is unknown)
6428
- // removes nothing.
6429
- removeStaleSidecarIfConfirmedDead(dataDir);
6430
- return;
7058
+ catch {
7059
+ exited = false; /* best-effort — the restart leg refuses instead (flair#2365) */
7060
+ }
7061
+ // Use the PID the exit probe observed gone; null makes cleanup probe
7062
+ // the sidecar's PID. A re-read naming a different PID is left alone.
7063
+ removeStaleSidecarIfConfirmedDead(dataDir, exited ? pid : null);
7064
+ return fallbackOutcome({ pid, exited });
6431
7065
  }
6432
7066
  case "NOT_RUNNING": {
6433
- // Idempotent no-op for the process — but a sidecar left naming a pid that
6434
- // is CONFIRMED gone is a leftover too (flair#2055), and removing it here
6435
- // keeps a repeat stop from carrying the refusal forward.
7067
+ // Probe the sidecar's PID before best-effort removal.
6436
7068
  removeStaleSidecarIfConfirmedDead(dataDir);
6437
- return;
7069
+ return fallbackOutcome({ pid: null, exited: true });
6438
7070
  }
6439
7071
  case "DISAGREEMENT":
6440
7072
  case "UNKNOWN":
6441
7073
  // Deliberately outside any catch: a refusal must reach the caller, not
6442
7074
  // be swallowed as "not running" and reported as a successful stop.
7075
+ if (launchdExitFailure && !fallbackOutcome({ pid: null, exited: true }).exited) {
7076
+ throw new StopExitWaitError(launchdExitFailure, `refusing to stop: ${state.detail}`);
7077
+ }
6443
7078
  throw new Error(`refusing to stop: ${state.detail}`);
6444
7079
  }
6445
7080
  }
@@ -6531,7 +7166,9 @@ async function startFlairProcess(port, dataDir) {
6531
7166
  throw new LaunchdValidationRefusal(`${stalePlist.message} Fix it with: ${stalePlist.remedy.join(" && ")}`);
6532
7167
  }
6533
7168
  ensureLaunchdServiceLoaded(dataDir, realLaunchctlCommand);
6534
- await waitForHealth(port, DEFAULT_ADMIN_USER, process.env.HDB_ADMIN_PASSWORD ?? "", STARTUP_TIMEOUT_MS);
7169
+ await recordManagedStartSidecar(dataDir, port, launchdLabel(dataDir), {
7170
+ adminPass: process.env.HDB_ADMIN_PASSWORD ?? "",
7171
+ });
6535
7172
  readyOpsSocketPosture(dataDir); // flair#763: re-assert socket posture across restart/upgrade
6536
7173
  stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
6537
7174
  return;
@@ -6607,6 +7244,21 @@ async function startFlairDirect(port, dataDir) {
6607
7244
  stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
6608
7245
  return proc.pid ?? null;
6609
7246
  }
7247
+ class StopExitWaitError extends Error {
7248
+ outcome;
7249
+ detail;
7250
+ constructor(outcome, detail) {
7251
+ super(`${detail ? `${detail}. ` : ""}Could not confirm that the old Flair process (pid ${outcome.pid ?? "unknown"}) exited within ${STARTUP_TIMEOUT_MS}ms`);
7252
+ this.outcome = outcome;
7253
+ this.detail = detail;
7254
+ }
7255
+ }
7256
+ function refuseReplacementAfterExitTimeout(outcome, detail) {
7257
+ if (outcome.exited)
7258
+ return;
7259
+ throw new Error(`${detail ? `${detail}. ` : ""}Could not confirm that the old Flair process (pid ${outcome.pid ?? "unknown"}) exited within ${STARTUP_TIMEOUT_MS}ms; refusing to start a replacement. `
7260
+ + `Stop it, then re-run 'flair restart'.`);
7261
+ }
6610
7262
  /**
6611
7263
  * The ONE restart mechanism for a local Flair install. Shared by `flair
6612
7264
  * restart` and `flair upgrade`'s post-install restart step (flair#635) so
@@ -6623,7 +7275,20 @@ async function startFlairDirect(port, dataDir) {
6623
7275
  * named at the call site rather than assumed from `defaultDataDir()` two
6624
7276
  * frames down.
6625
7277
  */
6626
- async function restartFlair(port, dataDir) {
7278
+ export async function restartFlair(port, dataDir, deps = {}) {
7279
+ const startReplacement = deps.startReplacement ?? startFlairProcess;
7280
+ const stopForRestart = async () => {
7281
+ let outcome;
7282
+ try {
7283
+ outcome = await stopFlairProcess(port, dataDir, deps);
7284
+ }
7285
+ catch (err) {
7286
+ if (err instanceof StopExitWaitError)
7287
+ refuseReplacementAfterExitTimeout(err.outcome, err.detail);
7288
+ throw err;
7289
+ }
7290
+ refuseReplacementAfterExitTimeout(outcome);
7291
+ };
6627
7292
  // flair#2034 §2: on Linux, an instance proven to run under a systemd USER
6628
7293
  // unit (found from the serving process's cgroup; its MainPID is that
6629
7294
  // process) is restarted THROUGH that unit, and the unit's new main process
@@ -6661,8 +7326,8 @@ async function restartFlair(port, dataDir) {
6661
7326
  guardEngineNotBackwards(dataDir);
6662
7327
  },
6663
7328
  direct: async () => {
6664
- await stopFlairProcess(port, dataDir);
6665
- await startFlairProcess(port, dataDir);
7329
+ await stopForRestart();
7330
+ await startReplacement(port, dataDir);
6666
7331
  },
6667
7332
  log: (line) => console.log(line),
6668
7333
  });
@@ -6672,8 +7337,8 @@ async function restartFlair(port, dataDir) {
6672
7337
  }
6673
7338
  }
6674
7339
  else {
6675
- await stopFlairProcess(port, dataDir);
6676
- await startFlairProcess(port, dataDir);
7340
+ await stopForRestart();
7341
+ await startReplacement(port, dataDir);
6677
7342
  }
6678
7343
  // Bust the version-handshake cache so the next preAction nudge re-fetches
6679
7344
  // the LIVE version instead of the pre-restart cached one (the false
@@ -6804,6 +7469,7 @@ registerTest(program);
6804
7469
  // Command registration lives in src/commands/deploy.ts (flair#1636).
6805
7470
  // Bind shared cli-locals first so the extracted module never imports this file.
6806
7471
  bindDeployCli({
7472
+ resolveEffectiveOpsUrl,
6807
7473
  fleetSweepCallerExitMessage,
6808
7474
  resolveFabricCredentials,
6809
7475
  shouldRunFleetVerify,
@@ -6837,6 +7503,7 @@ bindDoctorCli({
6837
7503
  repairLaunchdManagement,
6838
7504
  repointMainServiceUnit,
6839
7505
  resolveHttpPort,
7506
+ verifyDoctorRosterInstance,
6840
7507
  restartFlair,
6841
7508
  resolveOpsPort,
6842
7509
  verifyAuditLog,
@@ -6893,15 +7560,17 @@ const ENTITIES_OPTION_DESCRIPTION = "Comma-separated entity vocabulary strings t
6893
7560
  // Command group lives in src/commands/memory.ts (flair#1621). Bind shared
6894
7561
  // helpers first so the extracted module never imports this file.
6895
7562
  bindMemoryCli({
7563
+ resolveEffectiveOpsUrl,
6896
7564
  api,
6897
7565
  resolveBaseUrl,
6898
7566
  resolveSigningAgentId,
6899
- applyAdminPassFile,
6900
7567
  addSharedCredentialOptions,
6901
7568
  addSharedIdentityOption,
6902
7569
  resolveOpsPort,
7570
+ resolveHttpPort,
6903
7571
  parseEntitiesOptionOrExit,
6904
7572
  ENTITIES_OPTION_DESCRIPTION,
7573
+ resolveFabricCredentials,
6905
7574
  });
6906
7575
  registerMemory(program);
6907
7576
  // ─── flair search ────────────────────────────────────────────────────────────
@@ -6934,7 +7603,6 @@ registerRelationship(program);
6934
7603
  bindSoulCli({
6935
7604
  api,
6936
7605
  resolveSigningAgentId,
6937
- applyAdminPassFile,
6938
7606
  addSharedCredentialOptions,
6939
7607
  });
6940
7608
  registerSoul(program);
@@ -6951,8 +7619,10 @@ registerBridge(program);
6951
7619
  // Bind shared cli-locals first so the extracted module never imports this file.
6952
7620
  bindBackupCli({
6953
7621
  addSharedCredentialOptions,
6954
- applyAdminPassFile,
6955
7622
  resolveHttpPort,
7623
+ resolveOpsPort,
7624
+ resolveOpsTarget,
7625
+ resolveOpsUrlFromTarget,
6956
7626
  });
6957
7627
  registerBackup(program);
6958
7628
  // ─── flair restore ────────────────────────────────────────────────────────────
@@ -6962,6 +7632,14 @@ bindRestoreCli({
6962
7632
  resolveHttpPort,
6963
7633
  });
6964
7634
  registerRestore(program);
7635
+ // ─── flair backup-approval ───────────────────────────────────────────────────
7636
+ // Command registration lives in src/commands/backup-approval.ts (flair#2664).
7637
+ // Bind shared cli-locals first so the extracted module never imports this file.
7638
+ bindBackupApprovalCli({
7639
+ addSharedCredentialOptions,
7640
+ resolveOpsPort,
7641
+ });
7642
+ registerBackupApproval(program);
6965
7643
  // ─── flair export ────────────────────────────────────────────────────────────
6966
7644
  // Command registration lives in src/commands/export.ts (flair#1636).
6967
7645
  // Bind shared cli-locals first so the extracted module never imports this file.
@@ -6980,6 +7658,7 @@ bindImportCli({
6980
7658
  resolveHttpPort,
6981
7659
  resolveOpsPort,
6982
7660
  seedAgentViaOpsApi,
7661
+ seedAgentWithLocalHome,
6983
7662
  });
6984
7663
  registerImport(program);
6985
7664
  // ─── flair inspect ────────────────────────────────────────────────────────────
@@ -7028,6 +7707,9 @@ bindAttentionCli({
7028
7707
  resolveSigningAgentId,
7029
7708
  });
7030
7709
  registerAttention(program);
7710
+ // ─── flair help ──────────────────────────────────────────────────────────────
7711
+ // Command registration lives in src/commands/help.ts (flair#2887).
7712
+ registerHelp(program);
7031
7713
  // Parse argv and run the CLI. Exported so the CommonJS preflight shim
7032
7714
  // (cli-shim.cts → dist/cli-shim.cjs, the real bin entry) can invoke it after
7033
7715
  // its Node-version check passes. The shim imports this module, so import.meta.main
@@ -7065,6 +7747,11 @@ async function runCli() {
7065
7747
  await program.parseAsync();
7066
7748
  }
7067
7749
  catch (err) {
7750
+ // A write that crossed its whole-request deadline may have committed.
7751
+ // Report it exactly as `flair rem` does and exit 3 ("unknown"), so every
7752
+ // command that lets the error propagate gives the same answer.
7753
+ if (err instanceof ApiRequestOutcomeUnknown)
7754
+ exitUnknownOutcome(err);
7068
7755
  // Errors the API layer already translated (flair#1719) carry a sentence
7069
7756
  // naming the actor, state and remedy; print it without the undici stack.
7070
7757
  if (err && typeof err === "object" && err.flairFriendly === true) {
@@ -7096,7 +7783,7 @@ LEGACY_LAUNCHD_LABEL, launchdLabel, launchdPlistPath, cleanupLegacyLaunchdPlist,
7096
7783
  observeLaunchdManagement, resolveInstanceServingPid,
7097
7784
  // launchd preflight, repair and init registration (flair#2040) — exported so
7098
7785
  // the command-level tests drive them against a stubbed launchctl.
7099
- observeLaunchdLoadability, repairLaunchdManagement, registerInitLaunchdService, startFlairProcess, };
7786
+ observeLaunchdLoadability, repairLaunchdManagement, registerInitLaunchdService, validateInitPlistAfterWrite, initLaunchdExitCode, startFlairProcess, };
7100
7787
  // Shared with `flair status` via src/lib/ops-api-bind.ts (flair#852).
7101
7788
  export { detectOpsApiAllInterfacesBind };
7102
7789
  export { searchScoringFormula, buildSearchExplain, formatSearchExplain } from "./commands/search.js";