@tpsdev-ai/flair 0.58.0 → 0.62.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 (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +1030 -343
  10. package/dist/commands/agent.js +384 -45
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +601 -163
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +146 -53
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +120 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +27 -2
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1775 -338
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +103 -7
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +227 -64
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -1,19 +1,27 @@
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 { readAgentRoster } from "../lib/agent-roster.js";
8
14
  import { flairConfigYamlCandidates, readPortFromYamlFile, resolveFlairConfigYaml } from "../lib/doctor-config-path.js";
9
15
  import { collectFederationEnv, describeFederationDriverFinding, federationPeersConfigured, loadYamlDoc } from "../lib/doctor-federation-driver.js";
10
16
  import { plistCarriesInlineAdminPassword } from "../lib/launchd-management.js";
11
- import { DOCTOR_CHECK_IDS, catalogIssueDelta, mcpRepinIcon, renderCatalogDoctorLines, runDoctorChecks } from "../lib/doctor-run.js";
17
+ import { DOCTOR_CHECK_IDS, catalogIssueDelta, mcpRepinIcon, probeFlairHealth, renderCatalogDoctorLines, runDoctorChecks } from "../lib/doctor-run.js";
12
18
  import { describeEmbedGpuDoctorFinding } from "../lib/embed-gpu-doctor.js";
19
+ import { describeEmbeddingSpaceDoctorFinding } from "../lib/embedding-space-doctor.js";
13
20
  import { adminPassDesyncFinding, detectPersistedAdminUser } from "../lib/init-admin-pass.js";
14
21
  import { opsApiBindFinding } from "../lib/ops-api-bind.js";
15
22
  import { instanceIdentityLines, probeInstanceIdentity, } from "../lib/instance-identity-row.js";
16
23
  import { flairCliVersion, unpinnedSpecWarning } from "../lib/mcp-spec.js";
24
+ import { discriminateMcpOAuthDiscovery, reportMcpOAuthDiscovery } from "../lib/mcp-enable.js";
17
25
  import { mcpClientPinFindings, refreshOwnedPins, repinSessionStartHookGuarded, sessionStartHookPinFindings } from "../lib/owned-pins.js";
18
26
  import * as render from "../render.js";
19
27
  import { checkVersion, formatVersionNudge, probeInstanceVersion, FLAIR_PKG_NAME } from "../version-check.js";
@@ -23,12 +31,89 @@ import { rewriteFederationSchedulerRuntime } from "../federation/scheduler.js";
23
31
  import { existsSync, readFileSync, statSync } from "node:fs";
24
32
  import { dirname, join } from "node:path";
25
33
  import { resolveHome } from "../lib/home.js";
34
+ export async function fetchAndRenderMigrations(healthDetailUrl, headers, indent) {
35
+ let issues = 0;
36
+ try {
37
+ const migRes = await fetch(healthDetailUrl, { headers, signal: AbortSignal.timeout(5000) });
38
+ if (!migRes.ok) {
39
+ console.log(`${indent}${render.icons.warn} Could not fetch migration state (HTTP ${migRes.status})`);
40
+ return issues;
41
+ }
42
+ const detail = (await migRes.json());
43
+ const migBlock = detail?.migrations;
44
+ if (!migBlock || !Array.isArray(migBlock.migrations) || migBlock.migrations.length === 0) {
45
+ console.log(`${indent}${render.icons.info} No migrations registered on this instance`);
46
+ return issues;
47
+ }
48
+ if (migBlock.cyclePhase === "pre-hash") {
49
+ console.log(`${indent}${render.icons.info} Pre-flight integrity check in progress — migrations deferred until it completes`);
50
+ }
51
+ // flair#812: the boot trigger sets `scheduled` synchronously at
52
+ // module load, so `idle` means resources/migration-boot.js never
53
+ // loaded in the serving process — NO migration will ever run on
54
+ // this instance, which is precisely the failure that went unnoticed
55
+ // because a skipped cycle looked identical to a clean one.
56
+ if (migBlock.cyclePhase === "idle") {
57
+ 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.`);
58
+ issues++;
59
+ }
60
+ if (migBlock.lastCycleError) {
61
+ console.log(`${indent}${render.icons.error} Last migration cycle did not complete: ${migBlock.lastCycleError}`);
62
+ issues++;
63
+ }
64
+ for (const m of migBlock.migrations) {
65
+ if (m.state === "completed") {
66
+ // Print the state-file short-circuit qualification (flair#812).
67
+ const note = m.reason ? ` ${render.wrap(render.c.dim, `(${m.reason})`)}` : "";
68
+ console.log(`${indent}${render.icons.ok} ${m.id}: completed${note}`);
69
+ }
70
+ else if (m.state === "halted" || m.state === "failed") {
71
+ console.log(`${indent}${render.icons.error} ${m.id}: ${m.state}${m.reason ? ` — ${m.reason}` : ""}`);
72
+ issues++;
73
+ }
74
+ else if (m.state === "running") {
75
+ console.log(`${indent}${render.icons.info} ${m.id}: in progress (${m.rowsDone} done, ${m.rowsRemaining} remaining)`);
76
+ }
77
+ else {
78
+ console.log(`${indent}${render.icons.info} ${m.id}: ${m.state}`);
79
+ }
80
+ }
81
+ }
82
+ catch (err) {
83
+ console.log(`${indent}${render.icons.warn} Migration state check failed: ${err?.message ?? err}`);
84
+ }
85
+ return issues;
86
+ }
87
+ export async function readNodeSeedAdvisory(input) {
88
+ if (input.nodeKeyIds.length === 0)
89
+ return null;
90
+ const read = await makeReadInstanceIds(input)();
91
+ return orphanInstanceSeedAdvisory({
92
+ ...input,
93
+ instanceIds: read.state === "read" ? read.ids : null,
94
+ agentIds: read.state === "read" ? read.agentIds : null,
95
+ unreadableReason: read.state === "read" ? read.agentReadReason : read.reason,
96
+ });
97
+ }
26
98
  let cli;
27
99
  /** Bind the cli-locals this module depends on. */
28
100
  export function bindCli(fns) {
29
101
  cli = fns;
30
102
  }
103
+ /**
104
+ * flair#2526: true while doctor's HTTP-port gate is `http-only` (the probed
105
+ * port's listener is proven but the HTTP/ops pair is not). Every `api()` call
106
+ * doctor makes then runs with the shared resolver's `signedOnly` transport:
107
+ * no Authorization header or an Ed25519 signature; never a Basic or Bearer
108
+ * header, from any source. Set by the doctor action each time it decides the
109
+ * gate.
110
+ */
111
+ let signedOnlyTransport = false;
31
112
  function api(...args) {
113
+ if (signedOnlyTransport) {
114
+ const options = args[3] && typeof args[3] === "object" ? args[3] : {};
115
+ args[3] = { ...options, signedOnly: true };
116
+ }
32
117
  return cli.api(...args);
33
118
  }
34
119
  function checkAgentRegistered(...args) {
@@ -73,6 +158,67 @@ function repairLaunchdManagement(...args) {
73
158
  function resolveHttpPort(...args) {
74
159
  return cli.resolveHttpPort(...args);
75
160
  }
161
+ function verifyDoctorRosterInstance(...args) {
162
+ return cli.verifyDoctorRosterInstance(...args);
163
+ }
164
+ /**
165
+ * Whether `url` uses `httpPort`, the port the pair check proves, on ANY host,
166
+ * so a credentialed request to it waits for that check. The host is not
167
+ * compared: alternate host spellings and the wildcard address (`0.0.0.0`,
168
+ * `localhost.`, an IPv4-mapped address) can reach the probed listener under
169
+ * names no list can enumerate, so the gate conservatively holds any URL on
170
+ * the probed port, whatever its host, without claiming that every spelling
171
+ * reaches the listener. An unparseable URL is held too.
172
+ */
173
+ export function targetsProbedHttpPort(url, httpPort) {
174
+ let parsed;
175
+ try {
176
+ parsed = new URL(url);
177
+ }
178
+ catch {
179
+ return true;
180
+ }
181
+ const port = parsed.port === "" ? (parsed.protocol === "https:" ? 443 : 80) : Number(parsed.port);
182
+ return port === httpPort;
183
+ }
184
+ /** What doctor prints when it has no admin credential to run the pair check with. */
185
+ 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 "
186
+ + "endpoint's configuration, then re-run flair doctor.";
187
+ /**
188
+ * Derive the HTTP-port gate (flair#2526) from the probed target flair#2520
189
+ * resolves (the admin credential and `verifyDoctorRosterInstance`'s answer for
190
+ * it, which includes the live-process pair proof). A proven pair runs; a pair
191
+ * check that ran and refused holds every credentialed request. When the pair
192
+ * could not be checked for want of a usable admin credential, the probed
193
+ * port's own listener is proven without any credential instead.
194
+ */
195
+ function decideDoctorPairGate(probed, probedHttpPort, proveListener = proveLocalHarperListener) {
196
+ const read = probed.read;
197
+ if (read?.kind === "run")
198
+ return read;
199
+ if (read?.kind === "not-run" && read.credentialRefused !== true) {
200
+ return { kind: "not-run", reason: read.reason, remedy: read.remedy };
201
+ }
202
+ const unchecked = read !== null
203
+ ? { reason: read.reason, remedy: read.remedy }
204
+ : probed.credIssue !== null
205
+ ? {
206
+ reason: `the admin credential could not be resolved (${probed.credIssue}), so the HTTP/ops pair check could not run`,
207
+ remedy: DOCTOR_PAIR_NO_CREDENTIAL_REMEDY,
208
+ }
209
+ : {
210
+ reason: "no admin credential to read the ops endpoint's configuration with, so the HTTP/ops pair check could not run",
211
+ remedy: DOCTOR_PAIR_NO_CREDENTIAL_REMEDY,
212
+ };
213
+ const listener = proveListener(probedHttpPort);
214
+ if (listener.kind === "proven")
215
+ return { kind: "http-only", ...unchecked };
216
+ return {
217
+ kind: "not-run",
218
+ reason: `${unchecked.reason}; nor is the HTTP port's own listener proven (${listener.detail})`,
219
+ remedy: listener.remedy ?? unchecked.remedy,
220
+ };
221
+ }
76
222
  function resolveOpsPort(...args) {
77
223
  return cli.resolveOpsPort(...args);
78
224
  }
@@ -132,6 +278,25 @@ export function renderEmbedGpuDoctorFinding(embedding, write = (line) => console
132
278
  write(line);
133
279
  return { lines, issueDelta: finding.isIssue ? 1 : 0 };
134
280
  }
281
+ /**
282
+ * flair#2530 — the single place a /Health embedding-space verdict becomes doctor
283
+ * output and exit-code weight, extracted like renderEmbedGpuDoctorFinding so the
284
+ * four states are exercised on the real counting path. Only the `mixed` state is
285
+ * a blocking finding; `uniform` prints an OK line and the two unverified states
286
+ * print advisories.
287
+ */
288
+ export function renderEmbeddingSpaceDoctorFinding(embeddingSpace, write = (line) => console.log(line)) {
289
+ const finding = describeEmbeddingSpaceDoctorFinding(embeddingSpace);
290
+ if (!finding)
291
+ return { lines: [], issueDelta: 0 };
292
+ const icon = finding.icon === "ok" ? render.icons.ok : finding.icon === "warn" ? render.icons.warn : render.icons.error;
293
+ const lines = [` ${icon} ${finding.message}`];
294
+ if (finding.fixHint)
295
+ lines.push(` ${render.wrap(render.c.dim, "Fix:")} ${finding.fixHint}`);
296
+ for (const line of lines)
297
+ write(line);
298
+ return { lines, issueDelta: finding.isIssue ? 1 : 0 };
299
+ }
135
300
  /**
136
301
  * flair#2034 §2 — the "Install tree" doctor section: is the instance served
137
302
  * from this CLI's install tree, and does the federation-sync shim run it?
@@ -287,6 +452,7 @@ export function register(program) {
287
452
  .option("--fix", "Automatically fix issues where possible")
288
453
  .option("--dry-run", "Show what --fix would do without making changes")
289
454
  .action(async (opts) => {
455
+ signedOnlyTransport = false; // flair#2526: decided per run, below
290
456
  const port = resolveHttpPort(opts);
291
457
  const autoFix = opts.fix ?? false;
292
458
  const dryRun = opts.dryRun ?? false;
@@ -385,24 +551,12 @@ export function register(program) {
385
551
  console.log(` ${render.icons.ok} npm global bin dir ${render.wrap(render.c.dim, binCheck.binDir)} is on PATH`);
386
552
  }
387
553
  }
388
- // Helper: try to reach Harper on a given port.
389
- // Must return true ONLY when Harper's /Health endpoint returns 200 OK.
390
- // A generic HTTP status > 0 (flair#862) would accept 404 from a Node
391
- // inspector on 9229 or any other service — "present but wrong" beats
392
- // "absent but correct".
554
+ // Probe a port's /Health.
393
555
  async function probePort(p) {
394
- try {
395
- const res = await fetch(`http://127.0.0.1:${p}/Health`, { signal: AbortSignal.timeout(3000) });
396
- return res.ok; // 200-299 only — /Health returns { ok: true } on 200
397
- }
398
- catch {
399
- return false;
400
- }
556
+ const probe = await probeFlairHealth(`http://127.0.0.1:${p}/Health`);
557
+ return probe.reaching;
401
558
  }
402
- // Helper: discover what port a Harper PID is listening on.
403
- // Scans ALL listening ports for this PID and returns the first one that
404
- // responds to /Health with 200 OK. This avoids picking a debug port (9229)
405
- // or any non-Flair listener that happens to share the process (flair#862).
559
+ // Find the PID's port by probing /Health.
406
560
  async function discoverPortFromPid(pid) {
407
561
  // Defense-in-depth: caller already validates, but re-check here
408
562
  if (!/^\d+$/.test(pid))
@@ -414,7 +568,6 @@ export function register(program) {
414
568
  const ports = [...out.matchAll(/n(?:\S+):(\d+)/g)].map(m => Number(m[1]));
415
569
  if (ports.length === 0)
416
570
  return null;
417
- // Try each port until one responds to /Health with 200 OK
418
571
  for (const port of ports) {
419
572
  if (await probePort(port))
420
573
  return port;
@@ -445,7 +598,24 @@ export function register(program) {
445
598
  console.log(` ${render.icons.warn} PID file contains non-numeric value: ${render.wrap(render.c.dim, pidFile0)} — skipping`);
446
599
  }
447
600
  }
448
- if (await probePort(port)) {
601
+ // flair#2530: a readiness 503 whose body has Flair's /Health fields (see
602
+ // readFlairHealthBody) is reported as Flair answering without serving
603
+ // search. It is an issue, never "responding", so the checks that need a
604
+ // serving instance stay skipped; its body still carries the version and the
605
+ // embedding-space guard state, read in 1a below. It is checked BEFORE
606
+ // `reaching`: a 503 can carry a multi-worker refusal too, which makes the
607
+ // probe `reaching`, but search is still not served. The worker-thread
608
+ // finding is reported separately by the catalog check.
609
+ let flairNotReady = false;
610
+ const configuredProbe = await probeFlairHealth(`http://127.0.0.1:${port}/Health`);
611
+ if (configuredProbe.notReady) {
612
+ const why = configuredProbe.notReadyReason ? ` (${configuredProbe.notReadyReason})` : "";
613
+ console.log(` ${render.icons.error} Flair is answering on port ${render.wrap(render.c.bold, String(port))} but not serving search${why}`);
614
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} wait for startup to finish; if it persists, flair restart`);
615
+ flairNotReady = true;
616
+ issues++;
617
+ }
618
+ else if (configuredProbe.reaching) {
449
619
  console.log(` ${render.icons.ok} Harper responding on port ${render.wrap(render.c.bold, String(port))}`);
450
620
  harperResponding = true;
451
621
  }
@@ -540,13 +710,21 @@ export function register(program) {
540
710
  // picture here instead of a one-liner and `--fix` offers the restart.
541
711
  let runningVersion = null;
542
712
  let embedGpuFromHealth;
543
- if (harperResponding) {
713
+ let embeddingSpaceFromHealth;
714
+ let workerThreads;
715
+ if (harperResponding || flairNotReady) {
544
716
  try {
545
- const healthRes = await fetch(`${baseUrl}/Health`, { signal: AbortSignal.timeout(3000) });
546
- if (healthRes.ok) {
547
- const body = (await healthRes.json());
548
- runningVersion = typeof body?.version === "string" ? body.version : null;
549
- embedGpuFromHealth = body.embedding;
717
+ const probe = await probeFlairHealth(`${baseUrl}/Health`);
718
+ if (probe.reaching)
719
+ workerThreads = probe.observation ?? undefined;
720
+ // A 2xx body, or a 503 body with Flair's /Health fields (flair#2530).
721
+ // Reading a 503 body does not make it healthy; the port check or the
722
+ // worker-threads check counts it.
723
+ if (probe.healthBody) {
724
+ const healthBody = probe.healthBody;
725
+ runningVersion = typeof healthBody.version === "string" ? healthBody.version : null;
726
+ embedGpuFromHealth = healthBody.embedding;
727
+ embeddingSpaceFromHealth = healthBody.embeddingSpace;
550
728
  }
551
729
  }
552
730
  catch { /* leave runningVersion null — reported below as "unknown" */ }
@@ -585,6 +763,89 @@ export function register(program) {
585
763
  // does NOT fail the run, while an explicit request or an unrecognized
586
764
  // source still fails closed. A stated CPU default is silent here.
587
765
  issues += renderEmbedGpuDoctorFinding(embedGpuFromHealth).issueDelta;
766
+ // flair#2530 — the embedding-space guard's verdict, from /Health. The
767
+ // `mixed` state is a blocking finding; the two unverified states are advisories.
768
+ issues += renderEmbeddingSpaceDoctorFinding(embeddingSpaceFromHealth).issueDelta;
769
+ }
770
+ // flair#2520: the audit-log, instance-identity, Agent-roster and Agent-homes
771
+ // reads go through an ops endpoint, which must belong to the instance doctor
772
+ // probed. Resolve the admin credential and verify that target with it here,
773
+ // using the pair check flair#2483 applies (with flair#2526's live-process
774
+ // proof). The order is: pair proof, then (only when the pair is proven)
775
+ // the Basic `/Instance/` identity read on the probed HTTP port, then the
776
+ // gate below for the later diagnostic requests. Diagnostic reads that run use
777
+ // the verified target; pairing refusals report NOT RUN with the shared
778
+ // reason and remedy, and existing UNVERIFIED/skipped outcomes remain. With
779
+ // no resolvable admin password there is no target (`read` null) and no ops
780
+ // endpoint is read. A resolved password that the ops endpoint rejects
781
+ // (HTTP 401/403) has been sent there, and the answer is `not-run`. `effectivePort` is final: PID discovery (step 1) and any
782
+ // --fix re-record have already run. This answer describes the credential
783
+ // and the process serving the probed port at this point, so it is shared
784
+ // only until a --fix step may change either: the launchd repair (7b, which
785
+ // can also write the admin-pass file from HDB_ADMIN_PASSWORD) and the
786
+ // install-tree restart (7c), both below. Those steps set
787
+ // `servingProcessMayHaveChanged`; the credential is then resolved again
788
+ // and, when one is available, the target verified with it, once, right
789
+ // after those steps (7a), and the Agent-roster and Agent-homes checks and
790
+ // the later credentialed HTTP reads use only that answer.
791
+ async function resolveProbedTarget() {
792
+ let adminPass;
793
+ let credIssue = null;
794
+ try {
795
+ adminPass = resolveLocalAdminPass(undefined);
796
+ }
797
+ catch (err) {
798
+ credIssue = err instanceof Error ? err.message : String(err);
799
+ }
800
+ const read = adminPass
801
+ ? await verifyDoctorRosterInstance(opts, effectivePort, adminPass)
802
+ : null;
803
+ return { adminPass, credIssue, read };
804
+ }
805
+ const probed = harperResponding
806
+ ? await resolveProbedTarget()
807
+ : { adminPass: undefined, credIssue: null, read: null };
808
+ const { adminPass: probedAdminPass, credIssue: probedCredIssue, read: probedRead } = probed;
809
+ let servingProcessMayHaveChanged = false;
810
+ // flair#2526: doctor sends a credential to the probed HTTP port only after
811
+ // that port is proven. The pair proof above runs before any credentialed
812
+ // HTTP request (its own Basic `/Instance/` identity read follows only a
813
+ // proven pair). The gate is derived from that answer (decideDoctorPairGate)
814
+ // for the later diagnostic requests. Unauthenticated reads
815
+ // (/Health, /OAuthMetadata, OAuth discovery, an unsigned /Presence) do not
816
+ // wait for it.
817
+ // - `run` (the HTTP/ops pair is proven): the gate permits every section;
818
+ // each section's own prerequisites still apply.
819
+ // - `http-only` (no usable admin credential to check the pair with, but
820
+ // the probed port's listener passes the listener-only check): requests
821
+ // to the HTTP port are permitted with no Authorization header or an
822
+ // Ed25519 signature; never Basic or Bearer. Every
823
+ // api() call runs signedOnly, so no Basic or Bearer header goes out from
824
+ // any source (FLAIR_TOKEN, FLAIR_ADMIN_PASS, HDB_ADMIN_PASSWORD, the
825
+ // admin-pass file). flair#2270: `doctor --agent` with an unusable
826
+ // ambient credential still reads the redirect state. Sections that join
827
+ // the HTTP port with the ops endpoint are not permitted.
828
+ // - `not-run`: later credentialed HTTP requests are held. Fully held
829
+ // diagnostic sections report NOT RUN; Scheduled drivers skips the live
830
+ // `/FederationPeers` read and continues using configured peers.
831
+ // After a --fix step that may change the serving process, the gate is
832
+ // derived again from the re-resolved target (7a below).
833
+ let pairGate = harperResponding ? decideDoctorPairGate(probed, effectivePort) : null;
834
+ /** Why the HTTP/ops pair is unproven (`http-only` or `not-run`), else null. */
835
+ let pairNotRun = pairGate !== null && pairGate.kind !== "run" ? pairGate : null;
836
+ /** Whether requests to the probed HTTP port are held. */
837
+ let httpHeld = pairGate?.kind === "not-run";
838
+ signedOnlyTransport = pairGate?.kind === "http-only";
839
+ let pairRemedyShown = false;
840
+ /** Print `<label>: NOT RUN — <reason>`, with the remedy the first time. */
841
+ function reportPairNotRun(label, indent = " ") {
842
+ if (!pairNotRun)
843
+ return;
844
+ console.log(`${indent}${render.icons.warn} ${label}: NOT RUN — ${pairNotRun.reason}`);
845
+ if (!pairRemedyShown) {
846
+ console.log(`${indent} ${render.wrap(render.c.dim, "Fix:")} ${pairNotRun.remedy}`);
847
+ pairRemedyShown = true;
848
+ }
588
849
  }
589
850
  // 2. Keys directory
590
851
  const keysDir = defaultKeysDir();
@@ -618,6 +879,18 @@ export function register(program) {
618
879
  console.log(` ${render.wrap(render.c.dim, "Fix:")} flair init --agent-id <your-agent>`);
619
880
  issues++;
620
881
  }
882
+ if (nodeKeyIds.length > 0 && harperResponding) {
883
+ if (pairNotRun) {
884
+ reportPairNotRun("Node key instance check");
885
+ }
886
+ else {
887
+ const advisory = await readNodeSeedAdvisory({
888
+ nodeKeyIds, keysDir, baseUrl, port: opts.port, resolveHttpPort, resolveOpsPort,
889
+ });
890
+ if (advisory)
891
+ console.log(` ${render.icons.info} ${advisory}`);
892
+ }
893
+ }
621
894
  }
622
895
  else {
623
896
  console.log(` ${render.icons.error} Keys directory missing: ${render.wrap(render.c.dim, keysDir)}`);
@@ -670,16 +943,29 @@ export function register(program) {
670
943
  // The remedy names the two exits: `--admin-pass-file` / `--reset-admin-pass`.
671
944
  try {
672
945
  const dataDir = defaultDataDir();
673
- const finding = adminPassDesyncFinding({
674
- adminPassFileExists: existsSync(defaultAdminPassPath()),
675
- persistedAdminUser: detectPersistedAdminUser(dataDir),
676
- dataDir,
677
- adminPassPath: defaultAdminPassPath(),
678
- });
679
- if (finding?.flagged) {
680
- console.log(` ${render.icons.error} ${finding.message}`);
681
- console.log(` ${render.wrap(render.c.dim, finding.remedy)}`);
946
+ let persistedAdminUser;
947
+ try {
948
+ persistedAdminUser = detectPersistedAdminUser(dataDir);
949
+ }
950
+ catch {
951
+ persistedAdminUser = null;
952
+ }
953
+ if (persistedAdminUser === null) {
682
954
  issues++;
955
+ 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`)}`);
956
+ }
957
+ else {
958
+ const finding = adminPassDesyncFinding({
959
+ adminPassFileExists: existsSync(defaultAdminPassPath()),
960
+ persistedAdminUser,
961
+ dataDir,
962
+ adminPassPath: defaultAdminPassPath(),
963
+ });
964
+ if (finding?.flagged) {
965
+ console.log(` ${render.icons.error} ${finding.message}`);
966
+ console.log(` ${render.wrap(render.c.dim, finding.remedy)}`);
967
+ issues++;
968
+ }
683
969
  }
684
970
  }
685
971
  catch { /* best-effort — a missing data dir is not a doctor crash */ }
@@ -729,13 +1015,14 @@ export function register(program) {
729
1015
  // READs it for drift detection, but describePublicUrlFinding never names
730
1016
  // it as the fix (flair#1313 — wiped on every upgrade).
731
1017
  const componentEnvPath = join(flairPackageDir(), COMPONENT_ENV_FILENAME);
732
- let componentEnvValue = null;
1018
+ let componentEnvText = null;
733
1019
  try {
734
- if (existsSync(componentEnvPath)) {
735
- componentEnvValue = readEnvValue(readFileSync(componentEnvPath, "utf-8"), PUBLIC_URL_KEY);
736
- }
1020
+ if (existsSync(componentEnvPath))
1021
+ componentEnvText = readFileSync(componentEnvPath, "utf-8");
737
1022
  }
738
1023
  catch { /* unreadable → treat as absent */ }
1024
+ const componentEnvValue = readEnvValue(componentEnvText, PUBLIC_URL_KEY);
1025
+ const componentMcpIssuer = readEnvValue(componentEnvText, MCP_ISSUER_KEY);
739
1026
  const finding = describePublicUrlFinding({
740
1027
  advertisedIssuer,
741
1028
  componentEnvValue,
@@ -752,6 +1039,41 @@ export function register(program) {
752
1039
  if (finding.isIssue)
753
1040
  issues++;
754
1041
  }
1042
+ const mcpRedirectFinding = httpHeld
1043
+ ? null
1044
+ : await readTargetMcpRedirectFinding(() => api("GET", "/HealthDetail", undefined, {
1045
+ baseUrl,
1046
+ keysDir: defaultKeysDir(),
1047
+ ...(opts.agent ? { agentId: opts.agent, agentIdSource: "flag" } : {}),
1048
+ }));
1049
+ if (httpHeld)
1050
+ reportPairNotRun("MCP OAuth redirect");
1051
+ if (mcpRedirectFinding) {
1052
+ console.log(` ${mcpRedirectFinding.isIssue ? render.icons.error : render.icons.warn} ${mcpRedirectFinding.message}`);
1053
+ if (mcpRedirectFinding.fixHint)
1054
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${mcpRedirectFinding.fixHint}`);
1055
+ if (mcpRedirectFinding.isIssue)
1056
+ issues++;
1057
+ }
1058
+ // flair#2283: share enable's discovery discriminator and infer report severity locally.
1059
+ const discovery = await discriminateMcpOAuthDiscovery(baseUrl, {
1060
+ expectedIssuers: [componentMcpIssuer, componentEnvValue, process.env.FLAIR_MCP_ISSUER, process.env.FLAIR_PUBLIC_URL].filter((issuer) => typeof issuer === "string" && issuer.trim() !== ""),
1061
+ });
1062
+ const discoveryReport = reportMcpOAuthDiscovery(discovery, mcpOAuthEnabledFromComponentEnv(componentEnvText, process.env));
1063
+ const discoveryIcons = {
1064
+ ok: render.icons.ok,
1065
+ info: render.icons.info,
1066
+ warn: render.icons.warn,
1067
+ error: render.icons.error,
1068
+ };
1069
+ discoveryReport.lines.forEach((line, index) => {
1070
+ console.log(index === 0 ? ` ${discoveryIcons[discoveryReport.severity]} ${line}` : ` ${line}`);
1071
+ });
1072
+ if (discoveryReport.severity === "error")
1073
+ issues++;
1074
+ }
1075
+ else {
1076
+ console.log(` ${render.icons.warn} MCP OAuth redirect: cannot verify target configuration`);
755
1077
  }
756
1078
  // 4. Embeddings check — REAL semantic round-trip (only if Harper is responding).
757
1079
  //
@@ -763,7 +1085,10 @@ export function register(program) {
763
1085
  // "no issues found". This now stores a memory with a distinctive phrase and
764
1086
  // searches for a PARAPHRASE (no shared keywords). If the top result isn't
765
1087
  // recovered by MEANING, recall-by-meaning is broken and doctor FAILS LOUDLY.
766
- if (harperResponding) {
1088
+ if (harperResponding && httpHeld) {
1089
+ reportPairNotRun("Embeddings");
1090
+ }
1091
+ else if (harperResponding) {
767
1092
  const semanticStatus = await verifySemanticSearch(baseUrl, opts.agent, defaultKeysDir());
768
1093
  switch (semanticStatus.state) {
769
1094
  case "ok":
@@ -816,51 +1141,63 @@ export function register(program) {
816
1141
  // agent's Ed25519 header cannot authenticate — resolve the local admin
817
1142
  // credential (env or ~/.flair/admin-pass; never prompts). A file with
818
1143
  // unsafe permissions throws — that is "could not probe", not "broken".
819
- let auditAdminPass;
820
- let auditCredIssue = null;
821
- try {
822
- auditAdminPass = resolveLocalAdminPass(undefined);
1144
+ if (probedCredIssue) {
1145
+ console.log(` ${render.icons.warn} Audit log: UNVERIFIED (could not probe — ${probedCredIssue})`);
823
1146
  }
824
- catch (err) {
825
- auditCredIssue = err instanceof Error ? err.message : String(err);
1147
+ else if (probedRead?.kind === "not-run") {
1148
+ // flair#2520: the pair-refused target the instance-identity section
1149
+ // also uses (and the roster and home sections, unless a --fix step
1150
+ // makes them verify again); name why and the remedy, and count it. This
1151
+ // section's diagnostic read does not run.
1152
+ issues++;
1153
+ console.log(` ${render.icons.warn} Audit log: NOT RUN — ${probedRead.reason}`);
1154
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${probedRead.remedy}`);
826
1155
  }
827
- const auditStatus = auditCredIssue
828
- ? { state: "skipped", reason: "no-admin-credentials", detail: auditCredIssue }
829
- : await verifyAuditLog(baseUrl, opts.agent, defaultKeysDir(), `http://127.0.0.1:${resolveOpsPort(opts)}`, resolveAdminUser(undefined), auditAdminPass);
830
- switch (auditStatus.state) {
831
- case "ok":
832
- // Present-tense claim ONLY (see AuditVerifyResult): the probe
833
- // proves the log records writes NOW — never that history is
834
- // complete. Overclaiming here would rebuild the false trust
835
- // anchor this check exists to kill, one layer up.
836
- 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)")}`);
837
- break;
838
- case "degraded":
839
- if (auditStatus.cause === "disabled") {
840
- console.log(` ${render.icons.error} Audit log DISABLED ${render.wrap(render.c.dim, `— ${auditStatus.detail}`)}`);
841
- 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.")}`);
842
- }
843
- else {
844
- console.log(` ${render.icons.error} Audit log NOT RECORDING ${render.wrap(render.c.dim, `— ${auditStatus.detail}`)}`);
845
- 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.")}`);
846
- 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\".")}`);
847
- 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.")}`);
848
- }
849
- issues++;
850
- break;
851
- case "failed":
852
- // Same loud discipline as the embeddings probe above (flair#1501).
853
- console.log(` ${render.icons.error} Audit log: probe rejected ${render.wrap(render.c.dim, `— ${auditStatus.detail}`)}`);
854
- 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>.")}`);
855
- issues++;
856
- break;
857
- case "skipped":
858
- // An unrun check must not look like a pass — UNVERIFIED, visually
859
- // distinct from ok, but not a hard issue (mirrors the embeddings
860
- // skip: the operator may simply have no agent or no local admin
861
- // credential on this box).
862
- console.log(` ${render.icons.warn} Audit log: UNVERIFIED (could not probe — ${auditStatus.detail})`);
863
- break;
1156
+ else if (httpHeld) {
1157
+ // flair#2526: the probe writes through the HTTP port, which is not
1158
+ // proven, so nothing credentialed goes to it.
1159
+ reportPairNotRun("Audit log");
1160
+ }
1161
+ else {
1162
+ // A verified target, or null with no admin credential. With none,
1163
+ // verifyAuditLog answers its no-credential/no-agent skip before it would
1164
+ // address the ops URL, so the empty URL is never fetched.
1165
+ const auditStatus = await verifyAuditLog(baseUrl, opts.agent, defaultKeysDir(), probedRead ? `http://127.0.0.1:${probedRead.opsPort}` : "", resolveAdminUser(undefined), probedAdminPass);
1166
+ switch (auditStatus.state) {
1167
+ case "ok":
1168
+ // Present-tense claim ONLY (see AuditVerifyResult): the probe
1169
+ // proves the log records writes NOW — never that history is
1170
+ // complete. Overclaiming here would rebuild the false trust
1171
+ // anchor this check exists to kill, one layer up.
1172
+ 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)")}`);
1173
+ break;
1174
+ case "degraded":
1175
+ if (auditStatus.cause === "disabled") {
1176
+ console.log(` ${render.icons.error} Audit log DISABLED ${render.wrap(render.c.dim, `— ${auditStatus.detail}`)}`);
1177
+ 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.")}`);
1178
+ }
1179
+ else {
1180
+ console.log(` ${render.icons.error} Audit log NOT RECORDING ${render.wrap(render.c.dim, `— ${auditStatus.detail}`)}`);
1181
+ 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.")}`);
1182
+ 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\".")}`);
1183
+ 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.")}`);
1184
+ }
1185
+ issues++;
1186
+ break;
1187
+ case "failed":
1188
+ // Same loud discipline as the embeddings probe above (flair#1501).
1189
+ console.log(` ${render.icons.error} Audit log: probe rejected ${render.wrap(render.c.dim, `— ${auditStatus.detail}`)}`);
1190
+ 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>.")}`);
1191
+ issues++;
1192
+ break;
1193
+ case "skipped":
1194
+ // An unrun check must not look like a pass — UNVERIFIED, visually
1195
+ // distinct from ok, but not a hard issue (mirrors the embeddings
1196
+ // skip: the operator may simply have no agent or no local admin
1197
+ // credential on this box).
1198
+ console.log(` ${render.icons.warn} Audit log: UNVERIFIED (could not probe — ${auditStatus.detail})`);
1199
+ break;
1200
+ }
864
1201
  }
865
1202
  }
866
1203
  // 4c. Instance identity (flair#1883). A hub's identity is ONE
@@ -878,21 +1215,28 @@ export function register(program) {
878
1215
  // unreadable leaves the pairing-role check UNVERIFIED while the row facts
879
1216
  // are still reported — a green line would claim a check that did not run.
880
1217
  if (harperResponding) {
881
- let identityAdminPass;
882
- let identityCredIssue = null;
883
- try {
884
- identityAdminPass = resolveLocalAdminPass(undefined);
1218
+ if (probedCredIssue) {
1219
+ console.log(` ${render.icons.warn} Instance identity: UNVERIFIED (could not probe — ${probedCredIssue})`);
885
1220
  }
886
- catch (err) {
887
- identityCredIssue = err instanceof Error ? err.message : String(err);
1221
+ else if (probedRead?.kind === "not-run") {
1222
+ // flair#2520: the pair-refused target the audit-log section also uses
1223
+ // (and the roster and home sections, unless a --fix step makes them
1224
+ // verify again); name why and the remedy, and count it. This section's
1225
+ // diagnostic read does not run.
1226
+ issues++;
1227
+ console.log(` ${render.icons.warn} Instance identity: NOT RUN — ${probedRead.reason}`);
1228
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${probedRead.remedy}`);
888
1229
  }
889
- if (identityCredIssue) {
890
- console.log(` ${render.icons.warn} Instance identity: UNVERIFIED (could not probe — ${identityCredIssue})`);
1230
+ else if (probedRead === null) {
1231
+ // No admin credential: the Instance table cannot be read, and no ops
1232
+ // endpoint is addressed. Same UNVERIFIED state as before the target was
1233
+ // shared.
1234
+ console.log(` ${render.icons.warn} Instance identity: UNVERIFIED (could not read the Instance table via the ops API)`);
891
1235
  }
892
1236
  else {
893
1237
  const probe = await probeInstanceIdentity({
894
- opsUrl: `http://127.0.0.1:${resolveOpsPort(opts)}`,
895
- credentials: { user: resolveAdminUser(undefined), pass: identityAdminPass ?? "" },
1238
+ opsUrl: `http://127.0.0.1:${probedRead.opsPort}`,
1239
+ credentials: { user: resolveAdminUser(undefined), pass: probedAdminPass ?? "" },
896
1240
  });
897
1241
  if (probe.rows === null) {
898
1242
  console.log(` ${render.icons.warn} Instance identity: UNVERIFIED (could not read the Instance table via the ops API)`);
@@ -1002,6 +1346,7 @@ export function register(program) {
1002
1346
  keysDir,
1003
1347
  keyAgentIds,
1004
1348
  agentFlag: typeof opts.agent === "string" ? opts.agent : undefined,
1349
+ workerThreads,
1005
1350
  };
1006
1351
  const catalogBefore = runDoctorChecks(doctorCtx, { catalogIds: doctorCatalogIds });
1007
1352
  // flair#1834 PR-H: a hook file on disk IS the wiring — the same rule the
@@ -1133,6 +1478,10 @@ export function register(program) {
1133
1478
  continue;
1134
1479
  }
1135
1480
  console.log(` ${render.icons.ok} FLAIR_URL ${render.wrap(render.c.dim, urlLabel)} reachable`);
1481
+ if (httpHeld && targetsProbedHttpPort(eff.url, effectivePort)) {
1482
+ reportPairNotRun(`agent '${block.agentId}' registration`, " ");
1483
+ continue;
1484
+ }
1136
1485
  const reg = await checkAgentRegistered(eff.url, block.agentId, defaultKeysDir());
1137
1486
  if (reg.state === "registered") {
1138
1487
  console.log(` ${render.icons.ok} agent '${block.agentId}' registered`);
@@ -1282,7 +1631,11 @@ export function register(program) {
1282
1631
  // ✓ "still runs". Check freshness first so a stale pin cannot
1283
1632
  // hide behind the execution probe. Catalog owns the issue count.
1284
1633
  const claudeStale = sessionStartHookPinFindings(resolveHome()).find((f) => f.reading.target.id === "claude-code");
1285
- if (claudeStale && claudeStale.direction === "unknown") {
1634
+ if (claudeStale?.reading.held) {
1635
+ // flair#2291: a held hook shape (see readOwnedPin).
1636
+ console.log(` ${render.icons.warn} SessionStart hook: ${claudeStale.reading.held}`);
1637
+ }
1638
+ else if (claudeStale && claudeStale.direction === "unknown") {
1286
1639
  // flair#1778: a pin we cannot compare is its OWN finding — a warn,
1287
1640
  // never the stale "old adapter" error, and NOT re-pinned (the
1288
1641
  // refresh holds an unreadable pin). Needs no --fix.
@@ -1491,7 +1844,11 @@ export function register(program) {
1491
1844
  const hook = codexHook;
1492
1845
  if (hook.present) {
1493
1846
  const codexStale = sessionStartHookPinFindings(resolveHome()).find((f) => f.reading.target.id === "codex");
1494
- if (codexStale && codexStale.direction === "unknown") {
1847
+ if (codexStale?.reading.held) {
1848
+ // flair#2291: same held rule as Claude Code above.
1849
+ console.log(` ${render.icons.warn} SessionStart hook (codex): ${codexStale.reading.held}`);
1850
+ }
1851
+ else if (codexStale && codexStale.direction === "unknown") {
1495
1852
  // flair#1778: same direction rule as Claude Code above.
1496
1853
  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`);
1497
1854
  }
@@ -1624,6 +1981,16 @@ export function register(program) {
1624
1981
  // Execute the repair directly; it re-derives the plan internally and
1625
1982
  // verifies via assessLaunchdManagement (fail-loud, never a silent pass).
1626
1983
  const repairResult = await repairLaunchdManagement(defaultDataDir(), effectivePort);
1984
+ // flair#2520: only a no-op is certain to leave the instance and the admin
1985
+ // credential as they were. A repair or a failure may have clean-stopped
1986
+ // the direct process and loaded a launchd job, and any outcome but a
1987
+ // no-op may come after the repair wrote the 0600 admin-pass file from
1988
+ // HDB_ADMIN_PASSWORD (flair#1685; a later refusal leaves the file in
1989
+ // place). So the credential and target resolved before the repair no
1990
+ // longer hold: the Agent-roster and Agent-homes checks resolve the
1991
+ // credential again and, when one is available, verify the target again.
1992
+ if (repairResult.kind !== "no-op")
1993
+ servingProcessMayHaveChanged = true;
1627
1994
  switch (repairResult.kind) {
1628
1995
  case "no-op":
1629
1996
  console.log(` ${render.icons.ok} ${repairResult.detail}`);
@@ -1709,7 +2076,13 @@ export function register(program) {
1709
2076
  runningVersion: effectivePort === port ? instanceVersion : null,
1710
2077
  }),
1711
2078
  repoint: (dry) => cli.repointMainServiceUnit(defaultDataDir(), effectivePort, { dryRun: dry }),
1712
- restart: () => cli.restartFlair(effectivePort, defaultDataDir()),
2079
+ // flair#2520: set before the restart runs, so a restart that fails
2080
+ // part-way still makes the later checks resolve the credential again
2081
+ // and, when one is available, verify the target again.
2082
+ restart: () => {
2083
+ servingProcessMayHaveChanged = true;
2084
+ return cli.restartFlair(effectivePort, defaultDataDir());
2085
+ },
1713
2086
  rewriteFederation: (dry) => rewriteFederationSchedulerRuntime({ dryRun: dry }),
1714
2087
  });
1715
2088
  issues += treeSection.issues;
@@ -1736,11 +2109,26 @@ export function register(program) {
1736
2109
  // never aborts the others — that's the failure isolation flair#722 asks
1737
2110
  // for; describeAgentGateFinding (src/doctor-client.ts) is pure decision
1738
2111
  // logic so it's unit-tested without a real Harper.
2112
+ // flair#2520/#2526: a --fix step above (7b, 7c) may have changed the serving
2113
+ // process or written the admin-pass file. Resolve the credential and the
2114
+ // target again, once, here, and derive the HTTP-port gate from that answer
2115
+ // for every credentialed read below; the Agent-roster and Agent-homes
2116
+ // checks use the same answer.
2117
+ const lateProbe = servingProcessMayHaveChanged ? await resolveProbedTarget() : probed;
2118
+ if (lateProbe !== probed) {
2119
+ pairGate = harperResponding ? decideDoctorPairGate(lateProbe, effectivePort) : null;
2120
+ pairNotRun = pairGate !== null && pairGate.kind !== "run" ? pairGate : null;
2121
+ httpHeld = pairGate?.kind === "not-run";
2122
+ signedOnlyTransport = pairGate?.kind === "http-only";
2123
+ pairRemedyShown = false;
2124
+ }
1739
2125
  const verifiedReadAgentIds = harperResponding
1740
2126
  ? planAgentIterations(keyAgentIds, opts.agent || process.env.FLAIR_AGENT_ID)
1741
2127
  : [];
2128
+ // flair#2526: these reads are agent-signed, held when the pair check refused.
2129
+ const signedReadsNotRun = httpHeld && verifiedReadAgentIds.length > 0;
1742
2130
  const agentGates = [];
1743
- for (const id of verifiedReadAgentIds) {
2131
+ for (const id of signedReadsNotRun ? [] : verifiedReadAgentIds) {
1744
2132
  const reg = await checkAgentRegistered(baseUrl, id, defaultKeysDir());
1745
2133
  agentGates.push({ id, state: reg.state, detail: reg.detail });
1746
2134
  // harperResponding is necessarily true here (verifiedReadAgentIds is
@@ -1796,9 +2184,10 @@ export function register(program) {
1796
2184
  // pre-#722 single unauthenticated read (hidden versions, "Pass --agent"
1797
2185
  // hint) — there's no agent to sign as, but remote agents may still have
1798
2186
  // heartbeated onto this instance and identities are worth showing.
2187
+ const presenceUrl = requestUrl(baseUrl, "/Presence");
1799
2188
  async function fetchAndRenderFleetPresence(headers, canSign, indent) {
1800
2189
  try {
1801
- const presRes = await fetch(`${baseUrl}/Presence`, { headers, signal: AbortSignal.timeout(5000) });
2190
+ const presRes = await fetch(presenceUrl, { headers, signal: AbortSignal.timeout(5000) });
1802
2191
  if (!presRes.ok) {
1803
2192
  // flair#1880: GET /Presence requires a verified reader by default, so
1804
2193
  // a keyless (unsigned) read now gets 401. Say so plainly instead of a
@@ -1861,7 +2250,10 @@ export function register(program) {
1861
2250
  }
1862
2251
  if (harperResponding) {
1863
2252
  console.log(`\n ${render.wrap(render.c.bold, "Fleet presence")}`);
1864
- if (agentGates.length === 0) {
2253
+ if (signedReadsNotRun) {
2254
+ reportPairNotRun("Fleet presence");
2255
+ }
2256
+ else if (agentGates.length === 0) {
1865
2257
  await fetchAndRenderFleetPresence({}, false, " ");
1866
2258
  }
1867
2259
  else {
@@ -1870,11 +2262,107 @@ export function register(program) {
1870
2262
  if (!registered)
1871
2263
  continue;
1872
2264
  const keyPath = resolveKeyPath(gate.id) ?? join(defaultKeysDir(), `${gate.id}.key`);
1873
- const headers = { Authorization: buildEd25519Auth(gate.id, "GET", "/Presence", keyPath) };
2265
+ const headers = { Authorization: buildEd25519Auth(gate.id, "GET", requestTarget(presenceUrl), keyPath) };
1874
2266
  await fetchAndRenderFleetPresence(headers, true, " ");
1875
2267
  }
1876
2268
  }
1877
2269
  }
2270
+ // 8b. Agent ID rule (flair#2359) — report a stored Agent id outside
2271
+ // the shared agent-ID rule. Read-only: nothing is rewritten.
2272
+ if (harperResponding) {
2273
+ console.log(`\n ${render.wrap(render.c.bold, "Agent IDs")}`);
2274
+ let roster = null;
2275
+ let rosterReadAttempted = false;
2276
+ // flair#2483/#2520: read from the verified instance target. That is the
2277
+ // answer resolved above, unless a --fix step since then may have changed
2278
+ // the serving process or written the admin-pass file
2279
+ // (servingProcessMayHaveChanged): the credential is then resolved and the
2280
+ // target verified with it again, once, right after those steps (7a,
2281
+ // `lateProbe`), and only that answer is used. The roster read addresses the verified ops port,
2282
+ // or both the roster and home checks report NOT RUN (counted as an issue)
2283
+ // and no Agent row is read. No admin credential leaves the target null;
2284
+ // the roster read is skipped and named below.
2285
+ const rosterProbe = lateProbe;
2286
+ const rosterAdminPass = rosterProbe.adminPass;
2287
+ const rosterNotRun = rosterProbe.read?.kind === "not-run" ? rosterProbe.read : null;
2288
+ const rosterOpsPort = rosterProbe.read?.kind === "run" ? rosterProbe.read.opsPort : null;
2289
+ if (rosterAdminPass && rosterOpsPort !== null) {
2290
+ rosterReadAttempted = true;
2291
+ const auth = Buffer.from(`${resolveAdminUser()}:${rosterAdminPass}`).toString("base64");
2292
+ roster = await readAgentRoster({
2293
+ opsUrl: `http://127.0.0.1:${rosterOpsPort}/`,
2294
+ authHeader: `Basic ${auth}`,
2295
+ timeoutMs: 5000,
2296
+ });
2297
+ }
2298
+ if (rosterNotRun) {
2299
+ // A pair-refused check is not a clean result and not a finding about
2300
+ // another instance: count it, and name why and the remedy. (The Agent
2301
+ // homes no-credential skip below is different: it reads nothing and
2302
+ // counts nothing.)
2303
+ issues++;
2304
+ console.log(` ${render.icons.warn} Agent IDs: NOT RUN — ${rosterNotRun.reason}`);
2305
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${rosterNotRun.remedy}`);
2306
+ }
2307
+ else if (roster === null) {
2308
+ // A check that could not run is not a clean result: it counts as an
2309
+ // issue, so the summary and exit status never report "No issues found"
2310
+ // for an Agent-ID check that did not happen.
2311
+ issues++;
2312
+ console.log(rosterProbe.credIssue
2313
+ ? ` ${render.icons.warn} Skipped: the admin credential could not be resolved (${rosterProbe.credIssue}), so the agent-id check did not run.`
2314
+ : rosterReadAttempted
2315
+ ? ` ${render.icons.warn} Could not read the stored Agent roster, so the agent-id check did not run.`
2316
+ : ` ${render.icons.warn} Skipped: no admin credentials to read the stored Agent roster, so the agent-id check did not run.`);
2317
+ }
2318
+ else {
2319
+ const finding = describeAgentIdRuleFinding(roster);
2320
+ if (!finding) {
2321
+ console.log(` ${render.icons.ok} No stored agent id is outside ${AGENT_ID_RULE}.`);
2322
+ }
2323
+ else {
2324
+ issues++;
2325
+ console.log(` ${render.icons.warn} ${finding.message}`);
2326
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${finding.fixHint}`);
2327
+ }
2328
+ }
2329
+ // 8c. Agent homes (flair#2433) — report every stored Agent row with no
2330
+ // home instance (`originatorInstanceId`) and name the remedy that
2331
+ // back-fills it. Read-only: nothing is rewritten here.
2332
+ console.log(`\n ${render.wrap(render.c.bold, "Agent homes")}`);
2333
+ if (rosterNotRun) {
2334
+ issues++;
2335
+ console.log(` ${render.icons.warn} Agent homes: NOT RUN — ${rosterNotRun.reason}`);
2336
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${rosterNotRun.remedy}`);
2337
+ }
2338
+ else if (!rosterAdminPass) {
2339
+ console.log(` ${render.icons.info} Agent homes check skipped (no admin credential).`);
2340
+ }
2341
+ else {
2342
+ const homeOpsUrl = `http://127.0.0.1:${rosterOpsPort}/`;
2343
+ const homeEndpoint = agentHomeEndpoint(homeOpsUrl, resolveAdminUser(), rosterAdminPass);
2344
+ const homeAuth = `Basic ${Buffer.from(`${resolveAdminUser()}:${rosterAdminPass}`).toString("base64")}`;
2345
+ const homeRows = await readAgentHomeRows({ opsUrl: homeOpsUrl, authHeader: homeAuth, timeoutMs: 5000 });
2346
+ if (homeRows === null) {
2347
+ issues++;
2348
+ console.log(` ${render.icons.warn} Could not read the stored Agent roster, so the home-instance check did not run.`);
2349
+ }
2350
+ else {
2351
+ const homeIdentity = await resolveTargetInstanceIdentity(homeEndpoint);
2352
+ const homeFinding = describeAgentHomeFinding(homeRows, homeIdentity);
2353
+ if (!homeFinding) {
2354
+ console.log(` ${render.icons.ok} Every stored agent row names a home instance.`);
2355
+ }
2356
+ else {
2357
+ console.log(` ${homeFinding.severity === "info" ? render.icons.info : render.icons.warn} ${homeFinding.message}`);
2358
+ if (homeFinding.fixHint)
2359
+ console.log(` ${render.wrap(render.c.dim, "Fix:")} ${homeFinding.fixHint}`);
2360
+ if (homeFinding.isIssue)
2361
+ issues++;
2362
+ }
2363
+ }
2364
+ }
2365
+ }
1878
2366
  // 9. Migration state (flair#695) — pending/in-progress/blocked + last
1879
2367
  // ledger-derived outcome per registered migration, read off the same
1880
2368
  // authenticated /HealthDetail the "Fleet presence" section above
@@ -1893,66 +2381,13 @@ export function register(program) {
1893
2381
  // iterates only the gate-passed agents and rolls the rest into one
1894
2382
  // aggregate skip line. The issue COUNT is unaffected either way — gate
1895
2383
  // findings are counted exactly once, at gate-resolution time (step 7a).
1896
- async function fetchAndRenderMigrations(headers, indent) {
1897
- try {
1898
- const migRes = await fetch(`${baseUrl}/HealthDetail`, { headers, signal: AbortSignal.timeout(5000) });
1899
- if (!migRes.ok) {
1900
- console.log(`${indent}${render.icons.warn} Could not fetch migration state (HTTP ${migRes.status})`);
1901
- return;
1902
- }
1903
- const detail = (await migRes.json());
1904
- const migBlock = detail?.migrations;
1905
- if (!migBlock || !Array.isArray(migBlock.migrations) || migBlock.migrations.length === 0) {
1906
- console.log(`${indent}${render.icons.info} No migrations registered on this instance`);
1907
- return;
1908
- }
1909
- if (migBlock.cyclePhase === "pre-hash") {
1910
- console.log(`${indent}${render.icons.info} Pre-flight integrity check in progress — migrations deferred until it completes`);
1911
- }
1912
- // flair#812: the boot trigger sets `scheduled` synchronously at
1913
- // module load, so `idle` means resources/migration-boot.js never
1914
- // loaded in the serving process — NO migration will ever run on
1915
- // this instance, which is precisely the failure that went unnoticed
1916
- // because a skipped cycle looked identical to a clean one.
1917
- if (migBlock.cyclePhase === "idle") {
1918
- 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.`);
1919
- issues++;
1920
- }
1921
- // A cycle that reached a terminal phase carrying an error explains
1922
- // itself here rather than only in the process log — the reason
1923
- // string names the paths tried and the remedy.
1924
- if (migBlock.lastCycleError) {
1925
- console.log(`${indent}${render.icons.error} Last migration cycle did not complete: ${migBlock.lastCycleError}`);
1926
- issues++;
1927
- }
1928
- for (const m of migBlock.migrations) {
1929
- if (m.state === "completed") {
1930
- // flair#812: a `reason` on a COMPLETED migration means the
1931
- // runner short-circuited it from the (hand-editable) state file
1932
- // rather than verifying the corpus this boot. Print it, so an
1933
- // unverified claim is never rendered as a verified one.
1934
- const note = m.reason ? ` ${render.wrap(render.c.dim, `(${m.reason})`)}` : "";
1935
- console.log(`${indent}${render.icons.ok} ${m.id}: completed${note}`);
1936
- }
1937
- else if (m.state === "halted" || m.state === "failed") {
1938
- console.log(`${indent}${render.icons.error} ${m.id}: ${m.state}${m.reason ? ` — ${m.reason}` : ""}`);
1939
- issues++;
1940
- }
1941
- else if (m.state === "running") {
1942
- console.log(`${indent}${render.icons.info} ${m.id}: in progress (${m.rowsDone} done, ${m.rowsRemaining} remaining)`);
1943
- }
1944
- else {
1945
- console.log(`${indent}${render.icons.info} ${m.id}: ${m.state}`);
1946
- }
1947
- }
1948
- }
1949
- catch (err) {
1950
- console.log(`${indent}${render.icons.warn} Migration state check failed: ${err?.message ?? err}`);
1951
- }
1952
- }
2384
+ const healthDetailUrl = requestUrl(baseUrl, "/HealthDetail");
1953
2385
  if (harperResponding) {
1954
2386
  console.log(`\n ${render.wrap(render.c.bold, "Migrations")}`);
1955
- if (agentGates.length === 0) {
2387
+ if (signedReadsNotRun) {
2388
+ reportPairNotRun("Migrations");
2389
+ }
2390
+ else if (agentGates.length === 0) {
1956
2391
  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.`);
1957
2392
  }
1958
2393
  else {
@@ -1960,8 +2395,8 @@ export function register(program) {
1960
2395
  for (const gate of passedGates) {
1961
2396
  renderAgentGateHeader(gate);
1962
2397
  const keyPath = resolveKeyPath(gate.id) ?? join(defaultKeysDir(), `${gate.id}.key`);
1963
- const headers = { Authorization: buildEd25519Auth(gate.id, "GET", "/HealthDetail", keyPath) };
1964
- await fetchAndRenderMigrations(headers, " ");
2398
+ const headers = { Authorization: buildEd25519Auth(gate.id, "GET", requestTarget(healthDetailUrl), keyPath) };
2399
+ issues += await fetchAndRenderMigrations(healthDetailUrl, headers, " ");
1965
2400
  }
1966
2401
  const skipped = agentGates.length - passedGates.length;
1967
2402
  if (skipped > 0) {
@@ -1996,7 +2431,10 @@ export function register(program) {
1996
2431
  const remSched = await import("../rem/scheduler.js");
1997
2432
  const guiDomain = `gui/${process.getuid?.() ?? ""}`;
1998
2433
  let livePeerCount = null;
1999
- if (harperResponding) {
2434
+ // flair#2526: a credentialed read, held while the gate is `not-run`; in
2435
+ // `http-only` it runs signed-only (no Basic or Bearer header). An unread
2436
+ // count falls back to the configured peers below.
2437
+ if (harperResponding && !httpHeld) {
2000
2438
  try {
2001
2439
  const r = await api("GET", "/FederationPeers", undefined, { baseUrl });
2002
2440
  const peers = Array.isArray(r?.peers) ? r.peers : [];