@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
@@ -1,19 +1,30 @@
1
- import { COMPONENT_ENV_FILENAME, PUBLIC_URL_KEY, describePublicUrlFinding, readEnvValue } from "../component-env.js";
2
- import { checkClaudeMdBootstrap, checkContinuityCaptureHooks, continuityWriteBlockers, describeAgentGateFinding, effectiveFlairUrl, embeddingsSkipRemedy, fixClaudeMdBootstrap, fixCommandAgentHint, fixContinuityCaptureHooks, fixSessionStartHook, inspectSessionStartHook, partitionKeyIds, planAgentIterations, readClientMcpBlock, resolveFixAgentId, resolveWireFlairUrl, upgradeSessionStartHookCommand } from "../doctor-client.js";
1
+ import { makeReadInstanceIds } from "./keys.js";
2
+ import { COMPONENT_ENV_FILENAME, MCP_ISSUER_KEY, PUBLIC_URL_KEY, describePublicUrlFinding, readEnvValue } from "../component-env.js";
3
+ import { readTargetMcpRedirectFinding, mcpOAuthEnabledFromComponentEnv } from "../lib/mcp-oauth-env.js";
4
+ import { checkClaudeMdBootstrap, checkContinuityCaptureHooks, continuityWriteBlockers, describeAgentGateFinding, describeAgentHomeFinding, describeAgentIdRuleFinding, effectiveFlairUrl, embeddingsSkipRemedy, fixClaudeMdBootstrap, fixCommandAgentHint, fixContinuityCaptureHooks, fixSessionStartHook, inspectSessionStartHook, orphanInstanceSeedAdvisory, partitionKeyIds, planAgentIterations, readClientMcpBlock, resolveFixAgentId, resolveWireFlairUrl, upgradeSessionStartHookCommand } from "../doctor-client.js";
3
5
  import { markStale, sortOldestVersionFirst } from "../fleet-presence.js";
4
6
  import { hookSettingsPath, resolveHookAgentId } from "../hook-install.js";
5
7
  import { ALL_CLIENTS, decideCodexPinOnly, decideJsonPinOnly, detectClients, wireAntigravity, wireClaudeCode, wireCodex, wireCursor, wireGemini } from "../install/clients.js";
6
8
  import { checkGlobalBinOnPath, resolveNpmGlobalPrefix } from "../install/global-bin-path.js";
7
- import { buildEd25519Auth, defaultAdminPassPath, defaultKeysDir, resolveAdminUser, resolveKeyPath, resolveLocalAdminPass } from "../lib/auth-resolve.js";
9
+ import { buildEd25519Auth, defaultAdminPassPath, defaultKeysDir, requestTarget, requestUrl, resolveAdminUser, resolveKeyPath, resolveLocalAdminPass } from "../lib/auth-resolve.js";
10
+ import { proveLocalHarperListener } from "../lib/local-instance-pair.js";
11
+ import { AGENT_ID_RULE } from "../lib/agent-id-rule.js";
12
+ import { agentHomeEndpoint, readAgentHomeRows, resolveTargetInstanceIdentity } from "../lib/agent-home.js";
13
+ import { describeInstructionEventImpostors, readInstructionEventTables } from "../lib/instruction-event-doctor.js";
14
+ import { describeLiveSkillTombstones, readSkillTombstoneTables } from "../lib/skill-tombstone-doctor.js";
15
+ import { MQTT_CONFIGURATION_NOTE, mqttListenerSection, readInstanceConfiguration } from "../lib/mqtt-listener-doctor.js";
16
+ import { readAgentRoster } from "../lib/agent-roster.js";
8
17
  import { flairConfigYamlCandidates, readPortFromYamlFile, resolveFlairConfigYaml } from "../lib/doctor-config-path.js";
9
18
  import { collectFederationEnv, describeFederationDriverFinding, federationPeersConfigured, loadYamlDoc } from "../lib/doctor-federation-driver.js";
10
19
  import { plistCarriesInlineAdminPassword } from "../lib/launchd-management.js";
11
20
  import { DOCTOR_CHECK_IDS, catalogIssueDelta, mcpRepinIcon, probeFlairHealth, renderCatalogDoctorLines, runDoctorChecks } from "../lib/doctor-run.js";
12
21
  import { describeEmbedGpuDoctorFinding } from "../lib/embed-gpu-doctor.js";
22
+ import { describeEmbeddingSpaceDoctorFinding } from "../lib/embedding-space-doctor.js";
13
23
  import { adminPassDesyncFinding, detectPersistedAdminUser } from "../lib/init-admin-pass.js";
14
24
  import { opsApiBindFinding } from "../lib/ops-api-bind.js";
15
25
  import { instanceIdentityLines, probeInstanceIdentity, } from "../lib/instance-identity-row.js";
16
26
  import { flairCliVersion, unpinnedSpecWarning } from "../lib/mcp-spec.js";
27
+ import { discriminateMcpOAuthDiscovery, reportMcpOAuthDiscovery } from "../lib/mcp-enable.js";
17
28
  import { mcpClientPinFindings, refreshOwnedPins, repinSessionStartHookGuarded, sessionStartHookPinFindings } from "../lib/owned-pins.js";
18
29
  import * as render from "../render.js";
19
30
  import { checkVersion, formatVersionNudge, probeInstanceVersion, FLAIR_PKG_NAME } from "../version-check.js";
@@ -23,12 +34,89 @@ import { rewriteFederationSchedulerRuntime } from "../federation/scheduler.js";
23
34
  import { existsSync, readFileSync, statSync } from "node:fs";
24
35
  import { dirname, join } from "node:path";
25
36
  import { resolveHome } from "../lib/home.js";
37
+ export async function fetchAndRenderMigrations(healthDetailUrl, headers, indent) {
38
+ let issues = 0;
39
+ try {
40
+ const migRes = await fetch(healthDetailUrl, { headers, signal: AbortSignal.timeout(5000) });
41
+ if (!migRes.ok) {
42
+ console.log(`${indent}${render.icons.warn} Could not fetch migration state (HTTP ${migRes.status})`);
43
+ return issues;
44
+ }
45
+ const detail = (await migRes.json());
46
+ const migBlock = detail?.migrations;
47
+ if (!migBlock || !Array.isArray(migBlock.migrations) || migBlock.migrations.length === 0) {
48
+ console.log(`${indent}${render.icons.info} No migrations registered on this instance`);
49
+ return issues;
50
+ }
51
+ if (migBlock.cyclePhase === "pre-hash") {
52
+ console.log(`${indent}${render.icons.info} Pre-flight integrity check in progress — migrations deferred until it completes`);
53
+ }
54
+ // flair#812: the boot trigger sets `scheduled` synchronously at
55
+ // module load, so `idle` means resources/migration-boot.js never
56
+ // loaded in the serving process — NO migration will ever run on
57
+ // this instance, which is precisely the failure that went unnoticed
58
+ // because a skipped cycle looked identical to a clean one.
59
+ if (migBlock.cyclePhase === "idle") {
60
+ console.log(`${indent}${render.icons.error} Migration boot cycle never fired on this instance — no migration will run until this is resolved. Check the instance log for [flair-migrations] and confirm the running build ships dist/resources/migration-boot.js.`);
61
+ issues++;
62
+ }
63
+ if (migBlock.lastCycleError) {
64
+ console.log(`${indent}${render.icons.error} Last migration cycle did not complete: ${migBlock.lastCycleError}`);
65
+ issues++;
66
+ }
67
+ for (const m of migBlock.migrations) {
68
+ if (m.state === "completed") {
69
+ // Print the state-file short-circuit qualification (flair#812).
70
+ const note = m.reason ? ` ${render.wrap(render.c.dim, `(${m.reason})`)}` : "";
71
+ console.log(`${indent}${render.icons.ok} ${m.id}: completed${note}`);
72
+ }
73
+ else if (m.state === "halted" || m.state === "failed") {
74
+ console.log(`${indent}${render.icons.error} ${m.id}: ${m.state}${m.reason ? ` — ${m.reason}` : ""}`);
75
+ issues++;
76
+ }
77
+ else if (m.state === "running") {
78
+ console.log(`${indent}${render.icons.info} ${m.id}: in progress (${m.rowsDone} done, ${m.rowsRemaining} remaining)`);
79
+ }
80
+ else {
81
+ console.log(`${indent}${render.icons.info} ${m.id}: ${m.state}`);
82
+ }
83
+ }
84
+ }
85
+ catch (err) {
86
+ console.log(`${indent}${render.icons.warn} Migration state check failed: ${err?.message ?? err}`);
87
+ }
88
+ return issues;
89
+ }
90
+ export async function readNodeSeedAdvisory(input) {
91
+ if (input.nodeKeyIds.length === 0)
92
+ return null;
93
+ const read = await makeReadInstanceIds(input)();
94
+ return orphanInstanceSeedAdvisory({
95
+ ...input,
96
+ instanceIds: read.state === "read" ? read.ids : null,
97
+ agentIds: read.state === "read" ? read.agentIds : null,
98
+ unreadableReason: read.state === "read" ? read.agentReadReason : read.reason,
99
+ });
100
+ }
26
101
  let cli;
27
102
  /** Bind the cli-locals this module depends on. */
28
103
  export function bindCli(fns) {
29
104
  cli = fns;
30
105
  }
106
+ /**
107
+ * flair#2526: true while doctor's HTTP-port gate is `http-only` (the probed
108
+ * port's listener is proven but the HTTP/ops pair is not). Every `api()` call
109
+ * doctor makes then runs with the shared resolver's `signedOnly` transport:
110
+ * no Authorization header or an Ed25519 signature; never a Basic or Bearer
111
+ * header, from any source. Set by the doctor action each time it decides the
112
+ * gate.
113
+ */
114
+ let signedOnlyTransport = false;
31
115
  function api(...args) {
116
+ if (signedOnlyTransport) {
117
+ const options = args[3] && typeof args[3] === "object" ? args[3] : {};
118
+ args[3] = { ...options, signedOnly: true };
119
+ }
32
120
  return cli.api(...args);
33
121
  }
34
122
  function checkAgentRegistered(...args) {
@@ -73,6 +161,67 @@ function repairLaunchdManagement(...args) {
73
161
  function resolveHttpPort(...args) {
74
162
  return cli.resolveHttpPort(...args);
75
163
  }
164
+ function verifyDoctorRosterInstance(...args) {
165
+ return cli.verifyDoctorRosterInstance(...args);
166
+ }
167
+ /**
168
+ * Whether `url` uses `httpPort`, the port the pair check proves, on ANY host,
169
+ * so a credentialed request to it waits for that check. The host is not
170
+ * compared: alternate host spellings and the wildcard address (`0.0.0.0`,
171
+ * `localhost.`, an IPv4-mapped address) can reach the probed listener under
172
+ * names no list can enumerate, so the gate conservatively holds any URL on
173
+ * the probed port, whatever its host, without claiming that every spelling
174
+ * reaches the listener. An unparseable URL is held too.
175
+ */
176
+ export function targetsProbedHttpPort(url, httpPort) {
177
+ let parsed;
178
+ try {
179
+ parsed = new URL(url);
180
+ }
181
+ catch {
182
+ return true;
183
+ }
184
+ const port = parsed.port === "" ? (parsed.protocol === "https:" ? 443 : 80) : Number(parsed.port);
185
+ return port === httpPort;
186
+ }
187
+ /** What doctor prints when it has no admin credential to run the pair check with. */
188
+ const DOCTOR_PAIR_NO_CREDENTIAL_REMEDY = "Set FLAIR_ADMIN_PASS, or restore ~/.flair/admin-pass (`flair init` writes it), so doctor can read the ops "
189
+ + "endpoint's configuration, then re-run flair doctor.";
190
+ /**
191
+ * Derive the HTTP-port gate (flair#2526) from the probed target flair#2520
192
+ * resolves (the admin credential and `verifyDoctorRosterInstance`'s answer for
193
+ * it, which includes the live-process pair proof). A proven pair runs; a pair
194
+ * check that ran and refused holds every credentialed request. When the pair
195
+ * could not be checked for want of a usable admin credential, the probed
196
+ * port's own listener is proven without any credential instead.
197
+ */
198
+ function decideDoctorPairGate(probed, probedHttpPort, proveListener = proveLocalHarperListener) {
199
+ const read = probed.read;
200
+ if (read?.kind === "run")
201
+ return read;
202
+ if (read?.kind === "not-run" && read.credentialRefused !== true) {
203
+ return { kind: "not-run", reason: read.reason, remedy: read.remedy };
204
+ }
205
+ const unchecked = read !== null
206
+ ? { reason: read.reason, remedy: read.remedy }
207
+ : probed.credIssue !== null
208
+ ? {
209
+ reason: `the admin credential could not be resolved (${probed.credIssue}), so the HTTP/ops pair check could not run`,
210
+ remedy: DOCTOR_PAIR_NO_CREDENTIAL_REMEDY,
211
+ }
212
+ : {
213
+ reason: "no admin credential to read the ops endpoint's configuration with, so the HTTP/ops pair check could not run",
214
+ remedy: DOCTOR_PAIR_NO_CREDENTIAL_REMEDY,
215
+ };
216
+ const listener = proveListener(probedHttpPort);
217
+ if (listener.kind === "proven")
218
+ return { kind: "http-only", ...unchecked };
219
+ return {
220
+ kind: "not-run",
221
+ reason: `${unchecked.reason}; nor is the HTTP port's own listener proven (${listener.detail})`,
222
+ remedy: listener.remedy ?? unchecked.remedy,
223
+ };
224
+ }
76
225
  function resolveOpsPort(...args) {
77
226
  return cli.resolveOpsPort(...args);
78
227
  }
@@ -132,6 +281,25 @@ export function renderEmbedGpuDoctorFinding(embedding, write = (line) => console
132
281
  write(line);
133
282
  return { lines, issueDelta: finding.isIssue ? 1 : 0 };
134
283
  }
284
+ /**
285
+ * flair#2530 — the single place a /Health embedding-space verdict becomes doctor
286
+ * output and exit-code weight, extracted like renderEmbedGpuDoctorFinding so the
287
+ * four states are exercised on the real counting path. Only the `mixed` state is
288
+ * a blocking finding; `uniform` prints an OK line and the two unverified states
289
+ * print advisories.
290
+ */
291
+ export function renderEmbeddingSpaceDoctorFinding(embeddingSpace, write = (line) => console.log(line)) {
292
+ const finding = describeEmbeddingSpaceDoctorFinding(embeddingSpace);
293
+ if (!finding)
294
+ return { lines: [], issueDelta: 0 };
295
+ const icon = finding.icon === "ok" ? render.icons.ok : finding.icon === "warn" ? render.icons.warn : render.icons.error;
296
+ const lines = [` ${icon} ${finding.message}`];
297
+ if (finding.fixHint)
298
+ lines.push(` ${render.wrap(render.c.dim, "Fix:")} ${finding.fixHint}`);
299
+ for (const line of lines)
300
+ write(line);
301
+ return { lines, issueDelta: finding.isIssue ? 1 : 0 };
302
+ }
135
303
  /**
136
304
  * flair#2034 §2 — the "Install tree" doctor section: is the instance served
137
305
  * from this CLI's install tree, and does the federation-sync shim run it?
@@ -287,6 +455,7 @@ export function register(program) {
287
455
  .option("--fix", "Automatically fix issues where possible")
288
456
  .option("--dry-run", "Show what --fix would do without making changes")
289
457
  .action(async (opts) => {
458
+ signedOnlyTransport = false; // flair#2526: decided per run, below
290
459
  const port = resolveHttpPort(opts);
291
460
  const autoFix = opts.fix ?? false;
292
461
  const dryRun = opts.dryRun ?? false;
@@ -432,7 +601,24 @@ export function register(program) {
432
601
  console.log(` ${render.icons.warn} PID file contains non-numeric value: ${render.wrap(render.c.dim, pidFile0)} — skipping`);
433
602
  }
434
603
  }
435
- if (await probePort(port)) {
604
+ // flair#2530: a readiness 503 whose body has Flair's /Health fields (see
605
+ // readFlairHealthBody) is reported as Flair answering without serving
606
+ // search. It is an issue, never "responding", so the checks that need a
607
+ // serving instance stay skipped; its body still carries the version and the
608
+ // embedding-space guard state, read in 1a below. It is checked BEFORE
609
+ // `reaching`: a 503 can carry a multi-worker refusal too, which makes the
610
+ // probe `reaching`, but search is still not served. The worker-thread
611
+ // finding is reported separately by the catalog check.
612
+ let flairNotReady = false;
613
+ const configuredProbe = await probeFlairHealth(`http://127.0.0.1:${port}/Health`);
614
+ if (configuredProbe.notReady) {
615
+ const why = configuredProbe.notReadyReason ? ` (${configuredProbe.notReadyReason})` : "";
616
+ console.log(` ${render.icons.error} Flair is answering on port ${render.wrap(render.c.bold, String(port))} but not serving search${why}`);
617
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} wait for startup to finish; if it persists, flair restart`);
618
+ flairNotReady = true;
619
+ issues++;
620
+ }
621
+ else if (configuredProbe.reaching) {
436
622
  console.log(` ${render.icons.ok} Harper responding on port ${render.wrap(render.c.bold, String(port))}`);
437
623
  harperResponding = true;
438
624
  }
@@ -527,17 +713,21 @@ export function register(program) {
527
713
  // picture here instead of a one-liner and `--fix` offers the restart.
528
714
  let runningVersion = null;
529
715
  let embedGpuFromHealth;
716
+ let embeddingSpaceFromHealth;
530
717
  let workerThreads;
531
- if (harperResponding) {
718
+ if (harperResponding || flairNotReady) {
532
719
  try {
533
720
  const probe = await probeFlairHealth(`${baseUrl}/Health`);
534
- if (probe.reaching) {
721
+ if (probe.reaching)
535
722
  workerThreads = probe.observation ?? undefined;
536
- if (probe.status >= 200 && probe.status < 300 && probe.body && typeof probe.body === "object") {
537
- const healthBody = probe.body;
538
- runningVersion = typeof healthBody.version === "string" ? healthBody.version : null;
539
- embedGpuFromHealth = healthBody.embedding;
540
- }
723
+ // A 2xx body, or a 503 body with Flair's /Health fields (flair#2530).
724
+ // Reading a 503 body does not make it healthy; the port check or the
725
+ // worker-threads check counts it.
726
+ if (probe.healthBody) {
727
+ const healthBody = probe.healthBody;
728
+ runningVersion = typeof healthBody.version === "string" ? healthBody.version : null;
729
+ embedGpuFromHealth = healthBody.embedding;
730
+ embeddingSpaceFromHealth = healthBody.embeddingSpace;
541
731
  }
542
732
  }
543
733
  catch { /* leave runningVersion null — reported below as "unknown" */ }
@@ -576,6 +766,89 @@ export function register(program) {
576
766
  // does NOT fail the run, while an explicit request or an unrecognized
577
767
  // source still fails closed. A stated CPU default is silent here.
578
768
  issues += renderEmbedGpuDoctorFinding(embedGpuFromHealth).issueDelta;
769
+ // flair#2530 — the embedding-space guard's verdict, from /Health. The
770
+ // `mixed` state is a blocking finding; the two unverified states are advisories.
771
+ issues += renderEmbeddingSpaceDoctorFinding(embeddingSpaceFromHealth).issueDelta;
772
+ }
773
+ // flair#2520: the audit-log, instance-identity, Agent-roster and Agent-homes
774
+ // reads go through an ops endpoint, which must belong to the instance doctor
775
+ // probed. Resolve the admin credential and verify that target with it here,
776
+ // using the pair check flair#2483 applies (with flair#2526's live-process
777
+ // proof). The order is: pair proof, then (only when the pair is proven)
778
+ // the Basic `/Instance/` identity read on the probed HTTP port, then the
779
+ // gate below for the later diagnostic requests. Diagnostic reads that run use
780
+ // the verified target; pairing refusals report NOT RUN with the shared
781
+ // reason and remedy, and existing UNVERIFIED/skipped outcomes remain. With
782
+ // no resolvable admin password there is no target (`read` null) and no ops
783
+ // endpoint is read. A resolved password that the ops endpoint rejects
784
+ // (HTTP 401/403) has been sent there, and the answer is `not-run`. `effectivePort` is final: PID discovery (step 1) and any
785
+ // --fix re-record have already run. This answer describes the credential
786
+ // and the process serving the probed port at this point, so it is shared
787
+ // only until a --fix step may change either: the launchd repair (7b, which
788
+ // can also write the admin-pass file from HDB_ADMIN_PASSWORD) and the
789
+ // install-tree restart (7c), both below. Those steps set
790
+ // `servingProcessMayHaveChanged`; the credential is then resolved again
791
+ // and, when one is available, the target verified with it, once, right
792
+ // after those steps (7a), and the Agent-roster and Agent-homes checks and
793
+ // the later credentialed HTTP reads use only that answer.
794
+ async function resolveProbedTarget() {
795
+ let adminPass;
796
+ let credIssue = null;
797
+ try {
798
+ adminPass = resolveLocalAdminPass(undefined);
799
+ }
800
+ catch (err) {
801
+ credIssue = err instanceof Error ? err.message : String(err);
802
+ }
803
+ const read = adminPass
804
+ ? await verifyDoctorRosterInstance(opts, effectivePort, adminPass)
805
+ : null;
806
+ return { adminPass, credIssue, read };
807
+ }
808
+ const probed = harperResponding
809
+ ? await resolveProbedTarget()
810
+ : { adminPass: undefined, credIssue: null, read: null };
811
+ const { adminPass: probedAdminPass, credIssue: probedCredIssue, read: probedRead } = probed;
812
+ let servingProcessMayHaveChanged = false;
813
+ // flair#2526: doctor sends a credential to the probed HTTP port only after
814
+ // that port is proven. The pair proof above runs before any credentialed
815
+ // HTTP request (its own Basic `/Instance/` identity read follows only a
816
+ // proven pair). The gate is derived from that answer (decideDoctorPairGate)
817
+ // for the later diagnostic requests. Unauthenticated reads
818
+ // (/Health, /OAuthMetadata, OAuth discovery, an unsigned /Presence) do not
819
+ // wait for it.
820
+ // - `run` (the HTTP/ops pair is proven): the gate permits every section;
821
+ // each section's own prerequisites still apply.
822
+ // - `http-only` (no usable admin credential to check the pair with, but
823
+ // the probed port's listener passes the listener-only check): requests
824
+ // to the HTTP port are permitted with no Authorization header or an
825
+ // Ed25519 signature; never Basic or Bearer. Every
826
+ // api() call runs signedOnly, so no Basic or Bearer header goes out from
827
+ // any source (FLAIR_TOKEN, FLAIR_ADMIN_PASS, HDB_ADMIN_PASSWORD, the
828
+ // admin-pass file). flair#2270: `doctor --agent` with an unusable
829
+ // ambient credential still reads the redirect state. Sections that join
830
+ // the HTTP port with the ops endpoint are not permitted.
831
+ // - `not-run`: later credentialed HTTP requests are held. Fully held
832
+ // diagnostic sections report NOT RUN; Scheduled drivers skips the live
833
+ // `/FederationPeers` read and continues using configured peers.
834
+ // After a --fix step that may change the serving process, the gate is
835
+ // derived again from the re-resolved target (7a below).
836
+ let pairGate = harperResponding ? decideDoctorPairGate(probed, effectivePort) : null;
837
+ /** Why the HTTP/ops pair is unproven (`http-only` or `not-run`), else null. */
838
+ let pairNotRun = pairGate !== null && pairGate.kind !== "run" ? pairGate : null;
839
+ /** Whether requests to the probed HTTP port are held. */
840
+ let httpHeld = pairGate?.kind === "not-run";
841
+ signedOnlyTransport = pairGate?.kind === "http-only";
842
+ let pairRemedyShown = false;
843
+ /** Print `<label>: NOT RUN — <reason>`, with the remedy the first time. */
844
+ function reportPairNotRun(label, indent = " ") {
845
+ if (!pairNotRun)
846
+ return;
847
+ console.log(`${indent}${render.icons.warn} ${label}: NOT RUN — ${pairNotRun.reason}`);
848
+ if (!pairRemedyShown) {
849
+ console.log(`${indent} ${render.wrap(render.c.dim, "Fix:")} ${pairNotRun.remedy}`);
850
+ pairRemedyShown = true;
851
+ }
579
852
  }
580
853
  // 2. Keys directory
581
854
  const keysDir = defaultKeysDir();
@@ -609,6 +882,18 @@ export function register(program) {
609
882
  console.log(` ${render.wrap(render.c.dim, "Fix:")} flair init --agent-id <your-agent>`);
610
883
  issues++;
611
884
  }
885
+ if (nodeKeyIds.length > 0 && harperResponding) {
886
+ if (pairNotRun) {
887
+ reportPairNotRun("Node key instance check");
888
+ }
889
+ else {
890
+ const advisory = await readNodeSeedAdvisory({
891
+ nodeKeyIds, keysDir, baseUrl, port: opts.port, resolveHttpPort, resolveOpsPort,
892
+ });
893
+ if (advisory)
894
+ console.log(` ${render.icons.info} ${advisory}`);
895
+ }
896
+ }
612
897
  }
613
898
  else {
614
899
  console.log(` ${render.icons.error} Keys directory missing: ${render.wrap(render.c.dim, keysDir)}`);
@@ -661,16 +946,29 @@ export function register(program) {
661
946
  // The remedy names the two exits: `--admin-pass-file` / `--reset-admin-pass`.
662
947
  try {
663
948
  const dataDir = defaultDataDir();
664
- const finding = adminPassDesyncFinding({
665
- adminPassFileExists: existsSync(defaultAdminPassPath()),
666
- persistedAdminUser: detectPersistedAdminUser(dataDir),
667
- dataDir,
668
- adminPassPath: defaultAdminPassPath(),
669
- });
670
- if (finding?.flagged) {
671
- console.log(` ${render.icons.error} ${finding.message}`);
672
- console.log(` ${render.wrap(render.c.dim, finding.remedy)}`);
949
+ let persistedAdminUser;
950
+ try {
951
+ persistedAdminUser = detectPersistedAdminUser(dataDir);
952
+ }
953
+ catch {
954
+ persistedAdminUser = null;
955
+ }
956
+ if (persistedAdminUser === null) {
673
957
  issues++;
958
+ console.log(` ${render.icons.warn} ${render.wrap(render.c.yellow, `could not read the Harper system database under ${dataDir} to tell whether an admin user is persisted — not assessing the admin-pass desync`)}`);
959
+ }
960
+ else {
961
+ const finding = adminPassDesyncFinding({
962
+ adminPassFileExists: existsSync(defaultAdminPassPath()),
963
+ persistedAdminUser,
964
+ dataDir,
965
+ adminPassPath: defaultAdminPassPath(),
966
+ });
967
+ if (finding?.flagged) {
968
+ console.log(` ${render.icons.error} ${finding.message}`);
969
+ console.log(` ${render.wrap(render.c.dim, finding.remedy)}`);
970
+ issues++;
971
+ }
674
972
  }
675
973
  }
676
974
  catch { /* best-effort — a missing data dir is not a doctor crash */ }
@@ -720,13 +1018,14 @@ export function register(program) {
720
1018
  // READs it for drift detection, but describePublicUrlFinding never names
721
1019
  // it as the fix (flair#1313 — wiped on every upgrade).
722
1020
  const componentEnvPath = join(flairPackageDir(), COMPONENT_ENV_FILENAME);
723
- let componentEnvValue = null;
1021
+ let componentEnvText = null;
724
1022
  try {
725
- if (existsSync(componentEnvPath)) {
726
- componentEnvValue = readEnvValue(readFileSync(componentEnvPath, "utf-8"), PUBLIC_URL_KEY);
727
- }
1023
+ if (existsSync(componentEnvPath))
1024
+ componentEnvText = readFileSync(componentEnvPath, "utf-8");
728
1025
  }
729
1026
  catch { /* unreadable → treat as absent */ }
1027
+ const componentEnvValue = readEnvValue(componentEnvText, PUBLIC_URL_KEY);
1028
+ const componentMcpIssuer = readEnvValue(componentEnvText, MCP_ISSUER_KEY);
730
1029
  const finding = describePublicUrlFinding({
731
1030
  advertisedIssuer,
732
1031
  componentEnvValue,
@@ -743,6 +1042,41 @@ export function register(program) {
743
1042
  if (finding.isIssue)
744
1043
  issues++;
745
1044
  }
1045
+ const mcpRedirectFinding = httpHeld
1046
+ ? null
1047
+ : await readTargetMcpRedirectFinding(() => api("GET", "/HealthDetail", undefined, {
1048
+ baseUrl,
1049
+ keysDir: defaultKeysDir(),
1050
+ ...(opts.agent ? { agentId: opts.agent, agentIdSource: "flag" } : {}),
1051
+ }));
1052
+ if (httpHeld)
1053
+ reportPairNotRun("MCP OAuth redirect");
1054
+ if (mcpRedirectFinding) {
1055
+ console.log(` ${mcpRedirectFinding.isIssue ? render.icons.error : render.icons.warn} ${mcpRedirectFinding.message}`);
1056
+ if (mcpRedirectFinding.fixHint)
1057
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${mcpRedirectFinding.fixHint}`);
1058
+ if (mcpRedirectFinding.isIssue)
1059
+ issues++;
1060
+ }
1061
+ // flair#2283: share enable's discovery discriminator and infer report severity locally.
1062
+ const discovery = await discriminateMcpOAuthDiscovery(baseUrl, {
1063
+ expectedIssuers: [componentMcpIssuer, componentEnvValue, process.env.FLAIR_MCP_ISSUER, process.env.FLAIR_PUBLIC_URL].filter((issuer) => typeof issuer === "string" && issuer.trim() !== ""),
1064
+ });
1065
+ const discoveryReport = reportMcpOAuthDiscovery(discovery, mcpOAuthEnabledFromComponentEnv(componentEnvText, process.env));
1066
+ const discoveryIcons = {
1067
+ ok: render.icons.ok,
1068
+ info: render.icons.info,
1069
+ warn: render.icons.warn,
1070
+ error: render.icons.error,
1071
+ };
1072
+ discoveryReport.lines.forEach((line, index) => {
1073
+ console.log(index === 0 ? ` ${discoveryIcons[discoveryReport.severity]} ${line}` : ` ${line}`);
1074
+ });
1075
+ if (discoveryReport.severity === "error")
1076
+ issues++;
1077
+ }
1078
+ else {
1079
+ console.log(` ${render.icons.warn} MCP OAuth redirect: cannot verify target configuration`);
746
1080
  }
747
1081
  // 4. Embeddings check — REAL semantic round-trip (only if Harper is responding).
748
1082
  //
@@ -754,7 +1088,10 @@ export function register(program) {
754
1088
  // "no issues found". This now stores a memory with a distinctive phrase and
755
1089
  // searches for a PARAPHRASE (no shared keywords). If the top result isn't
756
1090
  // recovered by MEANING, recall-by-meaning is broken and doctor FAILS LOUDLY.
757
- if (harperResponding) {
1091
+ if (harperResponding && httpHeld) {
1092
+ reportPairNotRun("Embeddings");
1093
+ }
1094
+ else if (harperResponding) {
758
1095
  const semanticStatus = await verifySemanticSearch(baseUrl, opts.agent, defaultKeysDir());
759
1096
  switch (semanticStatus.state) {
760
1097
  case "ok":
@@ -807,51 +1144,63 @@ export function register(program) {
807
1144
  // agent's Ed25519 header cannot authenticate — resolve the local admin
808
1145
  // credential (env or ~/.flair/admin-pass; never prompts). A file with
809
1146
  // unsafe permissions throws — that is "could not probe", not "broken".
810
- let auditAdminPass;
811
- let auditCredIssue = null;
812
- try {
813
- auditAdminPass = resolveLocalAdminPass(undefined);
1147
+ if (probedCredIssue) {
1148
+ console.log(` ${render.icons.warn} Audit log: UNVERIFIED (could not probe — ${probedCredIssue})`);
814
1149
  }
815
- catch (err) {
816
- auditCredIssue = err instanceof Error ? err.message : String(err);
1150
+ else if (probedRead?.kind === "not-run") {
1151
+ // flair#2520: the pair-refused target the instance-identity section
1152
+ // also uses (and the roster and home sections, unless a --fix step
1153
+ // makes them verify again); name why and the remedy, and count it. This
1154
+ // section's diagnostic read does not run.
1155
+ issues++;
1156
+ console.log(` ${render.icons.warn} Audit log: NOT RUN — ${probedRead.reason}`);
1157
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${probedRead.remedy}`);
817
1158
  }
818
- const auditStatus = auditCredIssue
819
- ? { state: "skipped", reason: "no-admin-credentials", detail: auditCredIssue }
820
- : await verifyAuditLog(baseUrl, opts.agent, defaultKeysDir(), `http://127.0.0.1:${resolveOpsPort(opts)}`, resolveAdminUser(undefined), auditAdminPass);
821
- switch (auditStatus.state) {
822
- case "ok":
823
- // Present-tense claim ONLY (see AuditVerifyResult): the probe
824
- // proves the log records writes NOW — never that history is
825
- // complete. Overclaiming here would rebuild the false trust
826
- // anchor this check exists to kill, one layer up.
827
- console.log(` ${render.icons.ok} Audit log: recording (verified now) ${render.wrap(render.c.dim, "(verifies current recording, not history — a resynced node's audit has a hard start boundary at its copy time)")}`);
828
- break;
829
- case "degraded":
830
- if (auditStatus.cause === "disabled") {
831
- console.log(` ${render.icons.error} Audit log DISABLED ${render.wrap(render.c.dim, `— ${auditStatus.detail}`)}`);
832
- console.log(` ${render.wrap(render.c.dim, "Fix: enable logging.auditLog in the ROOT harperdb-config.yaml (the Harper instance config, NOT flair's component config.yaml), then restart Harper.")}`);
833
- }
834
- else {
835
- console.log(` ${render.icons.error} Audit log NOT RECORDING ${render.wrap(render.c.dim, `— ${auditStatus.detail}`)}`);
836
- console.log(` ${render.wrap(render.c.red, "Audit reports as enabled, but fresh writes produced no audit entries — do not treat the audit log as a record of what happened.")}`);
837
- console.log(` ${render.wrap(render.c.dim, "On a node that joined or resynced via cluster base copy, audit history has a hard start boundary at copy time (harper#2212) — \"no history\" does not mean \"nothing happened\".")}`);
838
- console.log(` ${render.wrap(render.c.dim, "Check logging.auditLog in the ROOT harperdb-config.yaml (not flair's component config.yaml), then restart Harper.")}`);
839
- }
840
- issues++;
841
- break;
842
- case "failed":
843
- // Same loud discipline as the embeddings probe above (flair#1501).
844
- console.log(` ${render.icons.error} Audit log: probe rejected ${render.wrap(render.c.dim, `— ${auditStatus.detail}`)}`);
845
- console.log(` ${render.wrap(render.c.dim, "Fix: register this key on the instance (`flair agent add <id>`) or pass --agent <a registered agent id>.")}`);
846
- issues++;
847
- break;
848
- case "skipped":
849
- // An unrun check must not look like a pass — UNVERIFIED, visually
850
- // distinct from ok, but not a hard issue (mirrors the embeddings
851
- // skip: the operator may simply have no agent or no local admin
852
- // credential on this box).
853
- console.log(` ${render.icons.warn} Audit log: UNVERIFIED (could not probe — ${auditStatus.detail})`);
854
- break;
1159
+ else if (httpHeld) {
1160
+ // flair#2526: the probe writes through the HTTP port, which is not
1161
+ // proven, so nothing credentialed goes to it.
1162
+ reportPairNotRun("Audit log");
1163
+ }
1164
+ else {
1165
+ // A verified target, or null with no admin credential. With none,
1166
+ // verifyAuditLog answers its no-credential/no-agent skip before it would
1167
+ // address the ops URL, so the empty URL is never fetched.
1168
+ const auditStatus = await verifyAuditLog(baseUrl, opts.agent, defaultKeysDir(), probedRead ? `http://127.0.0.1:${probedRead.opsPort}` : "", resolveAdminUser(undefined), probedAdminPass);
1169
+ switch (auditStatus.state) {
1170
+ case "ok":
1171
+ // Present-tense claim ONLY (see AuditVerifyResult): the probe
1172
+ // proves the log records writes NOW — never that history is
1173
+ // complete. Overclaiming here would rebuild the false trust
1174
+ // anchor this check exists to kill, one layer up.
1175
+ console.log(` ${render.icons.ok} Audit log: recording (verified now) ${render.wrap(render.c.dim, "(verifies current recording, not history — a resynced node's audit has a hard start boundary at its copy time)")}`);
1176
+ break;
1177
+ case "degraded":
1178
+ if (auditStatus.cause === "disabled") {
1179
+ console.log(` ${render.icons.error} Audit log DISABLED ${render.wrap(render.c.dim, `— ${auditStatus.detail}`)}`);
1180
+ console.log(` ${render.wrap(render.c.dim, "Fix: enable logging.auditLog in the ROOT harperdb-config.yaml (the Harper instance config, NOT flair's component config.yaml), then restart Harper.")}`);
1181
+ }
1182
+ else {
1183
+ console.log(` ${render.icons.error} Audit log NOT RECORDING ${render.wrap(render.c.dim, `— ${auditStatus.detail}`)}`);
1184
+ console.log(` ${render.wrap(render.c.red, "Audit reports as enabled, but fresh writes produced no audit entries — do not treat the audit log as a record of what happened.")}`);
1185
+ console.log(` ${render.wrap(render.c.dim, "On a node that joined or resynced via cluster base copy, audit history has a hard start boundary at copy time (harper#2212) — \"no history\" does not mean \"nothing happened\".")}`);
1186
+ console.log(` ${render.wrap(render.c.dim, "Check logging.auditLog in the ROOT harperdb-config.yaml (not flair's component config.yaml), then restart Harper.")}`);
1187
+ }
1188
+ issues++;
1189
+ break;
1190
+ case "failed":
1191
+ // Same loud discipline as the embeddings probe above (flair#1501).
1192
+ console.log(` ${render.icons.error} Audit log: probe rejected ${render.wrap(render.c.dim, `— ${auditStatus.detail}`)}`);
1193
+ console.log(` ${render.wrap(render.c.dim, "Fix: register this key on the instance (`flair agent add <id>`) or pass --agent <a registered agent id>.")}`);
1194
+ issues++;
1195
+ break;
1196
+ case "skipped":
1197
+ // An unrun check must not look like a pass — UNVERIFIED, visually
1198
+ // distinct from ok, but not a hard issue (mirrors the embeddings
1199
+ // skip: the operator may simply have no agent or no local admin
1200
+ // credential on this box).
1201
+ console.log(` ${render.icons.warn} Audit log: UNVERIFIED (could not probe — ${auditStatus.detail})`);
1202
+ break;
1203
+ }
855
1204
  }
856
1205
  }
857
1206
  // 4c. Instance identity (flair#1883). A hub's identity is ONE
@@ -869,21 +1218,28 @@ export function register(program) {
869
1218
  // unreadable leaves the pairing-role check UNVERIFIED while the row facts
870
1219
  // are still reported — a green line would claim a check that did not run.
871
1220
  if (harperResponding) {
872
- let identityAdminPass;
873
- let identityCredIssue = null;
874
- try {
875
- identityAdminPass = resolveLocalAdminPass(undefined);
1221
+ if (probedCredIssue) {
1222
+ console.log(` ${render.icons.warn} Instance identity: UNVERIFIED (could not probe — ${probedCredIssue})`);
876
1223
  }
877
- catch (err) {
878
- identityCredIssue = err instanceof Error ? err.message : String(err);
1224
+ else if (probedRead?.kind === "not-run") {
1225
+ // flair#2520: the pair-refused target the audit-log section also uses
1226
+ // (and the roster and home sections, unless a --fix step makes them
1227
+ // verify again); name why and the remedy, and count it. This section's
1228
+ // diagnostic read does not run.
1229
+ issues++;
1230
+ console.log(` ${render.icons.warn} Instance identity: NOT RUN — ${probedRead.reason}`);
1231
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${probedRead.remedy}`);
879
1232
  }
880
- if (identityCredIssue) {
881
- console.log(` ${render.icons.warn} Instance identity: UNVERIFIED (could not probe — ${identityCredIssue})`);
1233
+ else if (probedRead === null) {
1234
+ // No admin credential: the Instance table cannot be read, and no ops
1235
+ // endpoint is addressed. Same UNVERIFIED state as before the target was
1236
+ // shared.
1237
+ console.log(` ${render.icons.warn} Instance identity: UNVERIFIED (could not read the Instance table via the ops API)`);
882
1238
  }
883
1239
  else {
884
1240
  const probe = await probeInstanceIdentity({
885
- opsUrl: `http://127.0.0.1:${resolveOpsPort(opts)}`,
886
- credentials: { user: resolveAdminUser(undefined), pass: identityAdminPass ?? "" },
1241
+ opsUrl: `http://127.0.0.1:${probedRead.opsPort}`,
1242
+ credentials: { user: resolveAdminUser(undefined), pass: probedAdminPass ?? "" },
887
1243
  });
888
1244
  if (probe.rows === null) {
889
1245
  console.log(` ${render.icons.warn} Instance identity: UNVERIFIED (could not read the Instance table via the ops API)`);
@@ -1125,6 +1481,10 @@ export function register(program) {
1125
1481
  continue;
1126
1482
  }
1127
1483
  console.log(` ${render.icons.ok} FLAIR_URL ${render.wrap(render.c.dim, urlLabel)} reachable`);
1484
+ if (httpHeld && targetsProbedHttpPort(eff.url, effectivePort)) {
1485
+ reportPairNotRun(`agent '${block.agentId}' registration`, " ");
1486
+ continue;
1487
+ }
1128
1488
  const reg = await checkAgentRegistered(eff.url, block.agentId, defaultKeysDir());
1129
1489
  if (reg.state === "registered") {
1130
1490
  console.log(` ${render.icons.ok} agent '${block.agentId}' registered`);
@@ -1274,7 +1634,11 @@ export function register(program) {
1274
1634
  // ✓ "still runs". Check freshness first so a stale pin cannot
1275
1635
  // hide behind the execution probe. Catalog owns the issue count.
1276
1636
  const claudeStale = sessionStartHookPinFindings(resolveHome()).find((f) => f.reading.target.id === "claude-code");
1277
- if (claudeStale && claudeStale.direction === "unknown") {
1637
+ if (claudeStale?.reading.held) {
1638
+ // flair#2291: a held hook shape (see readOwnedPin).
1639
+ console.log(` ${render.icons.warn} SessionStart hook: ${claudeStale.reading.held}`);
1640
+ }
1641
+ else if (claudeStale && claudeStale.direction === "unknown") {
1278
1642
  // flair#1778: a pin we cannot compare is its OWN finding — a warn,
1279
1643
  // never the stale "old adapter" error, and NOT re-pinned (the
1280
1644
  // refresh holds an unreadable pin). Needs no --fix.
@@ -1483,7 +1847,11 @@ export function register(program) {
1483
1847
  const hook = codexHook;
1484
1848
  if (hook.present) {
1485
1849
  const codexStale = sessionStartHookPinFindings(resolveHome()).find((f) => f.reading.target.id === "codex");
1486
- if (codexStale && codexStale.direction === "unknown") {
1850
+ if (codexStale?.reading.held) {
1851
+ // flair#2291: same held rule as Claude Code above.
1852
+ console.log(` ${render.icons.warn} SessionStart hook (codex): ${codexStale.reading.held}`);
1853
+ }
1854
+ else if (codexStale && codexStale.direction === "unknown") {
1487
1855
  // flair#1778: same direction rule as Claude Code above.
1488
1856
  console.log(` ${render.icons.warn} SessionStart hook (codex): pin is not a version I can compare: ${codexStale.reading.pin} — not re-pinned; re-run flair init or edit the hook if this is unintended`);
1489
1857
  }
@@ -1616,6 +1984,16 @@ export function register(program) {
1616
1984
  // Execute the repair directly; it re-derives the plan internally and
1617
1985
  // verifies via assessLaunchdManagement (fail-loud, never a silent pass).
1618
1986
  const repairResult = await repairLaunchdManagement(defaultDataDir(), effectivePort);
1987
+ // flair#2520: only a no-op is certain to leave the instance and the admin
1988
+ // credential as they were. A repair or a failure may have clean-stopped
1989
+ // the direct process and loaded a launchd job, and any outcome but a
1990
+ // no-op may come after the repair wrote the 0600 admin-pass file from
1991
+ // HDB_ADMIN_PASSWORD (flair#1685; a later refusal leaves the file in
1992
+ // place). So the credential and target resolved before the repair no
1993
+ // longer hold: the Agent-roster and Agent-homes checks resolve the
1994
+ // credential again and, when one is available, verify the target again.
1995
+ if (repairResult.kind !== "no-op")
1996
+ servingProcessMayHaveChanged = true;
1619
1997
  switch (repairResult.kind) {
1620
1998
  case "no-op":
1621
1999
  console.log(` ${render.icons.ok} ${repairResult.detail}`);
@@ -1701,7 +2079,13 @@ export function register(program) {
1701
2079
  runningVersion: effectivePort === port ? instanceVersion : null,
1702
2080
  }),
1703
2081
  repoint: (dry) => cli.repointMainServiceUnit(defaultDataDir(), effectivePort, { dryRun: dry }),
1704
- restart: () => cli.restartFlair(effectivePort, defaultDataDir()),
2082
+ // flair#2520: set before the restart runs, so a restart that fails
2083
+ // part-way still makes the later checks resolve the credential again
2084
+ // and, when one is available, verify the target again.
2085
+ restart: () => {
2086
+ servingProcessMayHaveChanged = true;
2087
+ return cli.restartFlair(effectivePort, defaultDataDir());
2088
+ },
1705
2089
  rewriteFederation: (dry) => rewriteFederationSchedulerRuntime({ dryRun: dry }),
1706
2090
  });
1707
2091
  issues += treeSection.issues;
@@ -1728,11 +2112,26 @@ export function register(program) {
1728
2112
  // never aborts the others — that's the failure isolation flair#722 asks
1729
2113
  // for; describeAgentGateFinding (src/doctor-client.ts) is pure decision
1730
2114
  // logic so it's unit-tested without a real Harper.
2115
+ // flair#2520/#2526: a --fix step above (7b, 7c) may have changed the serving
2116
+ // process or written the admin-pass file. Resolve the credential and the
2117
+ // target again, once, here, and derive the HTTP-port gate from that answer
2118
+ // for every credentialed read below; the Agent-roster and Agent-homes
2119
+ // checks use the same answer.
2120
+ const lateProbe = servingProcessMayHaveChanged ? await resolveProbedTarget() : probed;
2121
+ if (lateProbe !== probed) {
2122
+ pairGate = harperResponding ? decideDoctorPairGate(lateProbe, effectivePort) : null;
2123
+ pairNotRun = pairGate !== null && pairGate.kind !== "run" ? pairGate : null;
2124
+ httpHeld = pairGate?.kind === "not-run";
2125
+ signedOnlyTransport = pairGate?.kind === "http-only";
2126
+ pairRemedyShown = false;
2127
+ }
1731
2128
  const verifiedReadAgentIds = harperResponding
1732
2129
  ? planAgentIterations(keyAgentIds, opts.agent || process.env.FLAIR_AGENT_ID)
1733
2130
  : [];
2131
+ // flair#2526: these reads are agent-signed, held when the pair check refused.
2132
+ const signedReadsNotRun = httpHeld && verifiedReadAgentIds.length > 0;
1734
2133
  const agentGates = [];
1735
- for (const id of verifiedReadAgentIds) {
2134
+ for (const id of signedReadsNotRun ? [] : verifiedReadAgentIds) {
1736
2135
  const reg = await checkAgentRegistered(baseUrl, id, defaultKeysDir());
1737
2136
  agentGates.push({ id, state: reg.state, detail: reg.detail });
1738
2137
  // harperResponding is necessarily true here (verifiedReadAgentIds is
@@ -1788,9 +2187,10 @@ export function register(program) {
1788
2187
  // pre-#722 single unauthenticated read (hidden versions, "Pass --agent"
1789
2188
  // hint) — there's no agent to sign as, but remote agents may still have
1790
2189
  // heartbeated onto this instance and identities are worth showing.
2190
+ const presenceUrl = requestUrl(baseUrl, "/Presence");
1791
2191
  async function fetchAndRenderFleetPresence(headers, canSign, indent) {
1792
2192
  try {
1793
- const presRes = await fetch(`${baseUrl}/Presence`, { headers, signal: AbortSignal.timeout(5000) });
2193
+ const presRes = await fetch(presenceUrl, { headers, signal: AbortSignal.timeout(5000) });
1794
2194
  if (!presRes.ok) {
1795
2195
  // flair#1880: GET /Presence requires a verified reader by default, so
1796
2196
  // a keyless (unsigned) read now gets 401. Say so plainly instead of a
@@ -1853,7 +2253,10 @@ export function register(program) {
1853
2253
  }
1854
2254
  if (harperResponding) {
1855
2255
  console.log(`\n ${render.wrap(render.c.bold, "Fleet presence")}`);
1856
- if (agentGates.length === 0) {
2256
+ if (signedReadsNotRun) {
2257
+ reportPairNotRun("Fleet presence");
2258
+ }
2259
+ else if (agentGates.length === 0) {
1857
2260
  await fetchAndRenderFleetPresence({}, false, " ");
1858
2261
  }
1859
2262
  else {
@@ -1862,11 +2265,223 @@ export function register(program) {
1862
2265
  if (!registered)
1863
2266
  continue;
1864
2267
  const keyPath = resolveKeyPath(gate.id) ?? join(defaultKeysDir(), `${gate.id}.key`);
1865
- const headers = { Authorization: buildEd25519Auth(gate.id, "GET", "/Presence", keyPath) };
2268
+ const headers = { Authorization: buildEd25519Auth(gate.id, "GET", requestTarget(presenceUrl), keyPath) };
1866
2269
  await fetchAndRenderFleetPresence(headers, true, " ");
1867
2270
  }
1868
2271
  }
1869
2272
  }
2273
+ // 8b. Agent ID rule (flair#2359) — report a stored Agent id outside
2274
+ // the shared agent-ID rule. Read-only: nothing is rewritten.
2275
+ if (harperResponding) {
2276
+ console.log(`\n ${render.wrap(render.c.bold, "Agent IDs")}`);
2277
+ let roster = null;
2278
+ let rosterReadAttempted = false;
2279
+ // flair#2483/#2520: read from the verified instance target. That is the
2280
+ // answer resolved above, unless a --fix step since then may have changed
2281
+ // the serving process or written the admin-pass file
2282
+ // (servingProcessMayHaveChanged): the credential is then resolved and the
2283
+ // target verified with it again, once, right after those steps (7a,
2284
+ // `lateProbe`), and only that answer is used. The roster read addresses the verified ops port,
2285
+ // or both the roster and home checks report NOT RUN (counted as an issue)
2286
+ // and no Agent row is read. No admin credential leaves the target null;
2287
+ // the roster read is skipped and named below.
2288
+ const rosterProbe = lateProbe;
2289
+ const rosterAdminPass = rosterProbe.adminPass;
2290
+ const rosterNotRun = rosterProbe.read?.kind === "not-run" ? rosterProbe.read : null;
2291
+ const rosterOpsPort = rosterProbe.read?.kind === "run" ? rosterProbe.read.opsPort : null;
2292
+ if (rosterAdminPass && rosterOpsPort !== null) {
2293
+ rosterReadAttempted = true;
2294
+ const auth = Buffer.from(`${resolveAdminUser()}:${rosterAdminPass}`).toString("base64");
2295
+ roster = await readAgentRoster({
2296
+ opsUrl: `http://127.0.0.1:${rosterOpsPort}/`,
2297
+ authHeader: `Basic ${auth}`,
2298
+ timeoutMs: 5000,
2299
+ });
2300
+ }
2301
+ if (rosterNotRun) {
2302
+ // A pair-refused check is not a clean result and not a finding about
2303
+ // another instance: count it, and name why and the remedy. (The Agent
2304
+ // homes no-credential skip below is different: it reads nothing and
2305
+ // counts nothing.)
2306
+ issues++;
2307
+ console.log(` ${render.icons.warn} Agent IDs: NOT RUN — ${rosterNotRun.reason}`);
2308
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${rosterNotRun.remedy}`);
2309
+ }
2310
+ else if (roster === null) {
2311
+ // A check that could not run is not a clean result: it counts as an
2312
+ // issue, so the summary and exit status never report "No issues found"
2313
+ // for an Agent-ID check that did not happen.
2314
+ issues++;
2315
+ console.log(rosterProbe.credIssue
2316
+ ? ` ${render.icons.warn} Skipped: the admin credential could not be resolved (${rosterProbe.credIssue}), so the agent-id check did not run.`
2317
+ : rosterReadAttempted
2318
+ ? ` ${render.icons.warn} Could not read the stored Agent roster, so the agent-id check did not run.`
2319
+ : ` ${render.icons.warn} Skipped: no admin credentials to read the stored Agent roster, so the agent-id check did not run.`);
2320
+ }
2321
+ else {
2322
+ const finding = describeAgentIdRuleFinding(roster);
2323
+ if (!finding) {
2324
+ console.log(` ${render.icons.ok} No stored agent id is outside ${AGENT_ID_RULE}.`);
2325
+ }
2326
+ else {
2327
+ issues++;
2328
+ console.log(` ${render.icons.warn} ${finding.message}`);
2329
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${finding.fixHint}`);
2330
+ }
2331
+ }
2332
+ // 8c. Agent homes (flair#2433) — report every stored Agent row with no
2333
+ // home instance (`originatorInstanceId`) and name the remedy that
2334
+ // back-fills it. Read-only: nothing is rewritten here.
2335
+ console.log(`\n ${render.wrap(render.c.bold, "Agent homes")}`);
2336
+ if (rosterNotRun) {
2337
+ issues++;
2338
+ console.log(` ${render.icons.warn} Agent homes: NOT RUN — ${rosterNotRun.reason}`);
2339
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${rosterNotRun.remedy}`);
2340
+ }
2341
+ else if (!rosterAdminPass) {
2342
+ console.log(` ${render.icons.info} Agent homes check skipped (no admin credential).`);
2343
+ }
2344
+ else {
2345
+ const homeOpsUrl = `http://127.0.0.1:${rosterOpsPort}/`;
2346
+ const homeEndpoint = agentHomeEndpoint(homeOpsUrl, resolveAdminUser(), rosterAdminPass);
2347
+ const homeAuth = `Basic ${Buffer.from(`${resolveAdminUser()}:${rosterAdminPass}`).toString("base64")}`;
2348
+ const homeRows = await readAgentHomeRows({ opsUrl: homeOpsUrl, authHeader: homeAuth, timeoutMs: 5000 });
2349
+ if (homeRows === null) {
2350
+ issues++;
2351
+ console.log(` ${render.icons.warn} Could not read the stored Agent roster, so the home-instance check did not run.`);
2352
+ }
2353
+ else {
2354
+ const homeIdentity = await resolveTargetInstanceIdentity(homeEndpoint);
2355
+ const homeFinding = describeAgentHomeFinding(homeRows, homeIdentity);
2356
+ if (!homeFinding) {
2357
+ console.log(` ${render.icons.ok} Every stored agent row names a home instance.`);
2358
+ }
2359
+ else {
2360
+ console.log(` ${homeFinding.severity === "info" ? render.icons.info : render.icons.warn} ${homeFinding.message}`);
2361
+ if (homeFinding.fixHint)
2362
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${homeFinding.fixHint}`);
2363
+ if (homeFinding.isIssue)
2364
+ issues++;
2365
+ }
2366
+ }
2367
+ }
2368
+ // 8d. Instruction events (flair#2139 slice 3a) — name every stored
2369
+ // OrgEvent that carries a reserved kind or the reserved id prefix but
2370
+ // does not satisfy the reader rule. Read-only: nothing is rewritten.
2371
+ console.log(`\n ${render.wrap(render.c.bold, "Instruction events")}`);
2372
+ if (rosterNotRun) {
2373
+ issues++;
2374
+ console.log(` ${render.icons.warn} Instruction events: NOT RUN — ${rosterNotRun.reason}`);
2375
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${rosterNotRun.remedy}`);
2376
+ }
2377
+ else if (!rosterAdminPass || rosterOpsPort === null) {
2378
+ console.log(` ${render.icons.info} Instruction-event check skipped (no admin credential or unverified ops endpoint).`);
2379
+ }
2380
+ else {
2381
+ const instructionAuth = `Basic ${Buffer.from(`${resolveAdminUser()}:${rosterAdminPass}`).toString("base64")}`;
2382
+ const tables = await readInstructionEventTables({
2383
+ opsUrl: `http://127.0.0.1:${rosterOpsPort}/`,
2384
+ authHeader: instructionAuth,
2385
+ timeoutMs: 5000,
2386
+ });
2387
+ if (tables === null) {
2388
+ issues++;
2389
+ console.log(` ${render.icons.warn} Could not read the stored OrgEvent and InstructionVersion tables, so the instruction-event check did not run.`);
2390
+ }
2391
+ else {
2392
+ const finding = describeInstructionEventImpostors(tables.events, tables.versions);
2393
+ if (!finding) {
2394
+ console.log(` ${render.icons.ok} No stored OrgEvent with a reserved kind or id fails the instruction-event reader rule.`);
2395
+ }
2396
+ else {
2397
+ issues++;
2398
+ console.log(` ${render.icons.warn} ${finding}`);
2399
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} confirm it is not a genuine instruction event, then delete the row through the operations API.`);
2400
+ }
2401
+ }
2402
+ }
2403
+ // 8e. Skill tombstones (flair#2662) — for each skill subject whose
2404
+ // newest InstructionVersion is a `delete` tombstone, report the subject
2405
+ // when its Memory row is still open-live (the skill writer's predicate:
2406
+ // not archived, not expired, no validTo). Read-only: nothing is
2407
+ // rewritten. A table read that fails while this section runs is NOT RUN
2408
+ // and counted; when Harper is not responding, the enclosing gate skips
2409
+ // the section and doctor counts the server problem elsewhere.
2410
+ console.log(`\n ${render.wrap(render.c.bold, "Skill tombstones")}`);
2411
+ if (rosterNotRun) {
2412
+ issues++;
2413
+ console.log(` ${render.icons.warn} Skill tombstones: NOT RUN — ${rosterNotRun.reason}`);
2414
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${rosterNotRun.remedy}`);
2415
+ }
2416
+ else if (!rosterAdminPass || rosterOpsPort === null) {
2417
+ issues++;
2418
+ const reason = rosterProbe.credIssue
2419
+ ? `the admin credential could not be resolved (${rosterProbe.credIssue})`
2420
+ : rosterAdminPass ? "the ops endpoint was not verified" : "no admin credentials to read the stored tables";
2421
+ console.log(` ${render.icons.warn} Skill tombstones: NOT RUN — ${reason}.`);
2422
+ }
2423
+ else {
2424
+ const tombstoneAuth = `Basic ${Buffer.from(`${resolveAdminUser()}:${rosterAdminPass}`).toString("base64")}`;
2425
+ const tables = await readSkillTombstoneTables({
2426
+ opsUrl: `http://127.0.0.1:${rosterOpsPort}/`,
2427
+ authHeader: tombstoneAuth,
2428
+ timeoutMs: 5000,
2429
+ });
2430
+ if (tables === null) {
2431
+ issues++;
2432
+ console.log(` ${render.icons.warn} Could not read the stored InstructionVersion and Memory tables, so the skill-tombstone check did not run.`);
2433
+ }
2434
+ else {
2435
+ const finding = describeLiveSkillTombstones(tables.versions, tables.memories);
2436
+ if (!finding) {
2437
+ console.log(` ${render.icons.ok} No delete tombstone is the newest version of a skill with an open-live Memory row (not archived, not expired, no validTo).`);
2438
+ }
2439
+ else {
2440
+ issues++;
2441
+ console.log(` ${render.icons.warn} ${finding}`);
2442
+ console.log(` ${render.wrap(render.c.dim, "Report only:")} this check does not modify the store.`);
2443
+ }
2444
+ }
2445
+ }
2446
+ // 8f. MQTT listeners — report when the instance's root configuration
2447
+ // starts an MQTT listener (TCP, TLS or the WebSocket path). Flair runs
2448
+ // Harper with MQTT off; the read is the instance's own configuration,
2449
+ // through the same verified ops endpoint and admin credential as the
2450
+ // sections above. Read-only: nothing is changed. A configuration read
2451
+ // that fails, or an answer that is not a recognizable root
2452
+ // configuration (`{}` included), is NOT RUN and counted. It reports the
2453
+ // saved configuration, not the running listeners, and prints that note
2454
+ // on every path below, the two NOT RUN paths included.
2455
+ console.log(`\n ${render.wrap(render.c.bold, "MQTT listeners (configuration)")}`);
2456
+ if (rosterNotRun) {
2457
+ issues++;
2458
+ console.log(` ${render.icons.warn} MQTT listeners: NOT RUN — ${rosterNotRun.reason}`);
2459
+ console.log(` ${render.wrap(render.c.dim, MQTT_CONFIGURATION_NOTE)}`);
2460
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${rosterNotRun.remedy}`);
2461
+ }
2462
+ else if (!rosterAdminPass || rosterOpsPort === null) {
2463
+ issues++;
2464
+ const reason = rosterProbe.credIssue
2465
+ ? `the admin credential could not be resolved (${rosterProbe.credIssue})`
2466
+ : rosterAdminPass ? "the ops endpoint was not verified" : "no admin credentials to read the instance configuration";
2467
+ console.log(` ${render.icons.warn} MQTT listeners: NOT RUN — ${reason}.`);
2468
+ console.log(` ${render.wrap(render.c.dim, MQTT_CONFIGURATION_NOTE)}`);
2469
+ }
2470
+ else {
2471
+ const configuration = await readInstanceConfiguration({
2472
+ opsUrl: `http://127.0.0.1:${rosterOpsPort}/`,
2473
+ authHeader: `Basic ${Buffer.from(`${resolveAdminUser()}:${rosterAdminPass}`).toString("base64")}`,
2474
+ timeoutMs: 5000,
2475
+ });
2476
+ const section = mqttListenerSection(configuration);
2477
+ if (section.status !== "ok")
2478
+ issues++;
2479
+ console.log(` ${section.status === "ok" ? render.icons.ok : render.icons.warn} ${section.line}`);
2480
+ console.log(` ${render.wrap(render.c.dim, section.note)}`);
2481
+ if (section.fix)
2482
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${section.fix}`);
2483
+ }
2484
+ }
1870
2485
  // 9. Migration state (flair#695) — pending/in-progress/blocked + last
1871
2486
  // ledger-derived outcome per registered migration, read off the same
1872
2487
  // authenticated /HealthDetail the "Fleet presence" section above
@@ -1885,66 +2500,13 @@ export function register(program) {
1885
2500
  // iterates only the gate-passed agents and rolls the rest into one
1886
2501
  // aggregate skip line. The issue COUNT is unaffected either way — gate
1887
2502
  // findings are counted exactly once, at gate-resolution time (step 7a).
1888
- async function fetchAndRenderMigrations(headers, indent) {
1889
- try {
1890
- const migRes = await fetch(`${baseUrl}/HealthDetail`, { headers, signal: AbortSignal.timeout(5000) });
1891
- if (!migRes.ok) {
1892
- console.log(`${indent}${render.icons.warn} Could not fetch migration state (HTTP ${migRes.status})`);
1893
- return;
1894
- }
1895
- const detail = (await migRes.json());
1896
- const migBlock = detail?.migrations;
1897
- if (!migBlock || !Array.isArray(migBlock.migrations) || migBlock.migrations.length === 0) {
1898
- console.log(`${indent}${render.icons.info} No migrations registered on this instance`);
1899
- return;
1900
- }
1901
- if (migBlock.cyclePhase === "pre-hash") {
1902
- console.log(`${indent}${render.icons.info} Pre-flight integrity check in progress — migrations deferred until it completes`);
1903
- }
1904
- // flair#812: the boot trigger sets `scheduled` synchronously at
1905
- // module load, so `idle` means resources/migration-boot.js never
1906
- // loaded in the serving process — NO migration will ever run on
1907
- // this instance, which is precisely the failure that went unnoticed
1908
- // because a skipped cycle looked identical to a clean one.
1909
- if (migBlock.cyclePhase === "idle") {
1910
- console.log(`${indent}${render.icons.error} Migration boot cycle never fired on this instance — no migration will run until this is resolved. Check the instance log for [flair-migrations] and confirm the running build ships dist/resources/migration-boot.js.`);
1911
- issues++;
1912
- }
1913
- // A cycle that reached a terminal phase carrying an error explains
1914
- // itself here rather than only in the process log — the reason
1915
- // string names the paths tried and the remedy.
1916
- if (migBlock.lastCycleError) {
1917
- console.log(`${indent}${render.icons.error} Last migration cycle did not complete: ${migBlock.lastCycleError}`);
1918
- issues++;
1919
- }
1920
- for (const m of migBlock.migrations) {
1921
- if (m.state === "completed") {
1922
- // flair#812: a `reason` on a COMPLETED migration means the
1923
- // runner short-circuited it from the (hand-editable) state file
1924
- // rather than verifying the corpus this boot. Print it, so an
1925
- // unverified claim is never rendered as a verified one.
1926
- const note = m.reason ? ` ${render.wrap(render.c.dim, `(${m.reason})`)}` : "";
1927
- console.log(`${indent}${render.icons.ok} ${m.id}: completed${note}`);
1928
- }
1929
- else if (m.state === "halted" || m.state === "failed") {
1930
- console.log(`${indent}${render.icons.error} ${m.id}: ${m.state}${m.reason ? ` — ${m.reason}` : ""}`);
1931
- issues++;
1932
- }
1933
- else if (m.state === "running") {
1934
- console.log(`${indent}${render.icons.info} ${m.id}: in progress (${m.rowsDone} done, ${m.rowsRemaining} remaining)`);
1935
- }
1936
- else {
1937
- console.log(`${indent}${render.icons.info} ${m.id}: ${m.state}`);
1938
- }
1939
- }
1940
- }
1941
- catch (err) {
1942
- console.log(`${indent}${render.icons.warn} Migration state check failed: ${err?.message ?? err}`);
1943
- }
1944
- }
2503
+ const healthDetailUrl = requestUrl(baseUrl, "/HealthDetail");
1945
2504
  if (harperResponding) {
1946
2505
  console.log(`\n ${render.wrap(render.c.bold, "Migrations")}`);
1947
- if (agentGates.length === 0) {
2506
+ if (signedReadsNotRun) {
2507
+ reportPairNotRun("Migrations");
2508
+ }
2509
+ else if (agentGates.length === 0) {
1948
2510
  console.log(` ${render.icons.info} Pass --agent <id> (with a matching key in ~/.flair/keys) to see migration state — requires a verified read, same as Fleet presence above.`);
1949
2511
  }
1950
2512
  else {
@@ -1952,8 +2514,8 @@ export function register(program) {
1952
2514
  for (const gate of passedGates) {
1953
2515
  renderAgentGateHeader(gate);
1954
2516
  const keyPath = resolveKeyPath(gate.id) ?? join(defaultKeysDir(), `${gate.id}.key`);
1955
- const headers = { Authorization: buildEd25519Auth(gate.id, "GET", "/HealthDetail", keyPath) };
1956
- await fetchAndRenderMigrations(headers, " ");
2517
+ const headers = { Authorization: buildEd25519Auth(gate.id, "GET", requestTarget(healthDetailUrl), keyPath) };
2518
+ issues += await fetchAndRenderMigrations(healthDetailUrl, headers, " ");
1957
2519
  }
1958
2520
  const skipped = agentGates.length - passedGates.length;
1959
2521
  if (skipped > 0) {
@@ -1988,7 +2550,10 @@ export function register(program) {
1988
2550
  const remSched = await import("../rem/scheduler.js");
1989
2551
  const guiDomain = `gui/${process.getuid?.() ?? ""}`;
1990
2552
  let livePeerCount = null;
1991
- if (harperResponding) {
2553
+ // flair#2526: a credentialed read, held while the gate is `not-run`; in
2554
+ // `http-only` it runs signed-only (no Basic or Bearer header). An unread
2555
+ // count falls back to the configured peers below.
2556
+ if (harperResponding && !httpHeld) {
1992
2557
  try {
1993
2558
  const r = await api("GET", "/FederationPeers", undefined, { baseUrl });
1994
2559
  const peers = Array.isArray(r?.peers) ? r.peers : [];