@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
@@ -26,7 +26,8 @@
26
26
  */
27
27
  import { request as httpRequest } from "node:http";
28
28
  import { createConnection } from "node:net";
29
- import { existsSync, statSync } from "node:fs";
29
+ import { createRequire } from "node:module";
30
+ import { closeSync, lstatSync, openSync, statSync } from "node:fs";
30
31
  import { dirname, join } from "node:path";
31
32
  /** Copy-pasteable recovery commands. Tests assert these strings verbatim. */
32
33
  export const INIT_RESET_ADMIN_PASS_COMMAND = "flair init --reset-admin-pass";
@@ -54,12 +55,12 @@ export function resolveInitAdminPasswordSource(adminPassFileExists, ctx = {}) {
54
55
  if (adminPassFileExists && !reset) {
55
56
  return "reuse-existing";
56
57
  }
58
+ if (explicit && !reset) {
59
+ return "re-persist";
60
+ }
57
61
  if (!adminPassFileExists && !persisted && !reset) {
58
62
  return "generate-new";
59
63
  }
60
- if (persisted && explicit && !reset) {
61
- return "re-persist";
62
- }
63
64
  // Rotate is production credential rotation. The ONLY way in is the
64
65
  // explicit `--reset-admin-pass` flag — never a missing-file guess.
65
66
  if (reset) {
@@ -83,20 +84,95 @@ export function resolveInitAdminPasswordRefuseReason(adminPassFileExists, ctx =
83
84
  return "persisted-missing-file";
84
85
  }
85
86
  /**
86
- * Harper's own install-validator signal that a rootPath already has a user
87
- * record (`system/hdb_user/data.mdb` or the legacy `system/hdb_user.mdb`).
88
- * Config presence alone is not enough — an interrupted install can write
89
- * harper-config.yaml before the user hash lands.
87
+ * Where each storage engine keeps the system schema (and so the admin user).
88
+ *
89
+ * Older data directories use LMDB: one file per table, at
90
+ * `system/hdb_user/data.mdb`, or the legacy single `system/hdb_user.mdb`.
91
+ *
92
+ * Harper 5 uses RocksDB: the whole `system` database is ONE column-family
93
+ * database at `database/system`, and each table's primary store is a column
94
+ * family named `<table>/` (Harper names a table's primary store with a
95
+ * trailing slash).
96
+ */
97
+ export const HARPER_SYSTEM_DB_REL = join("database", "system");
98
+ export const HDB_USER_PRIMARY_CF = "hdb_user/";
99
+ /**
100
+ * Match `hdb_user/` or the `hdb_user/@` prefix.
101
+ */
102
+ export function isHdbUserPrimaryColumn(column) {
103
+ return column === HDB_USER_PRIMARY_CF || column.startsWith(`${HDB_USER_PRIMARY_CF}@`);
104
+ }
105
+ /**
106
+ * Count the rows in the `hdb_user` primary store of a Harper 5 system
107
+ * database, opened READ-ONLY (RocksDB read-only needs no lock, so this works
108
+ * while the instance is running, and writes nothing).
109
+ *
110
+ * Both physical layouts are accepted (see `isHdbUserPrimaryColumn`); every
111
+ * matching family is counted.
112
+ *
113
+ * `@harperfast/rocksdb-js` is resolved through the installed `harper`
114
+ * package: flair does not depend on it directly, and the reader must be the
115
+ * same engine Harper wrote the store with.
90
116
  */
117
+ export function countRocksAdminUsers(systemDbDir) {
118
+ const requireFromHere = createRequire(import.meta.url);
119
+ const rocksPath = createRequire(requireFromHere.resolve("harper")).resolve("@harperfast/rocksdb-js");
120
+ const { RocksDatabase } = requireFromHere(rocksPath);
121
+ const probe = RocksDatabase.open(systemDbDir, { readOnly: true });
122
+ let userStores;
123
+ try {
124
+ if (!Array.isArray(probe.columns) || !probe.columns.every(column => typeof column === "string")) {
125
+ throw new Error(`Invalid RocksDB columns metadata at ${systemDbDir}`);
126
+ }
127
+ userStores = probe.columns.filter(isHdbUserPrimaryColumn);
128
+ }
129
+ finally {
130
+ probe.close?.();
131
+ }
132
+ if (userStores.length === 0) {
133
+ throw new Error(`MISSING_HDB_USER_COLUMN: existing system store at ${systemDbDir} lacks ${HDB_USER_PRIMARY_CF}. Repair the system store or select the correct --data-dir.`);
134
+ }
135
+ let total = 0;
136
+ for (const name of userStores) {
137
+ const users = RocksDatabase.open(systemDbDir, { name, readOnly: true });
138
+ try {
139
+ total += users.getKeysCount();
140
+ }
141
+ finally {
142
+ users.close?.();
143
+ }
144
+ }
145
+ return total;
146
+ }
147
+ /** A populated user store is evidence that the install is not fresh. */
91
148
  export function detectPersistedAdminUser(dataDir) {
92
- const dir = dataDir;
93
- return (existsSync(join(dir, "system", "hdb_user", "data.mdb")) ||
94
- existsSync(join(dir, "system", "hdb_user.mdb")));
149
+ for (const path of [join(dataDir, "system", "hdb_user", "data.mdb"), join(dataDir, "system", "hdb_user.mdb")]) {
150
+ try {
151
+ const fd = openSync(path, "r");
152
+ closeSync(fd);
153
+ return true;
154
+ }
155
+ catch (err) {
156
+ if (err.code !== "ENOENT")
157
+ throw err;
158
+ }
159
+ }
160
+ const systemDbDir = join(dataDir, HARPER_SYSTEM_DB_REL);
161
+ try {
162
+ lstatSync(systemDbDir);
163
+ }
164
+ catch (err) {
165
+ if (err.code === "ENOENT")
166
+ return false;
167
+ throw err;
168
+ }
169
+ return countRocksAdminUsers(systemDbDir) > 0;
95
170
  }
96
171
  export function initAdminPassRefusalMessage(reason, opts = {}) {
97
172
  if (reason === "foreign-instance") {
98
173
  const port = opts.httpPort ?? 19926;
99
- const head = `A Harper instance is already answering on port ${port} and this data directory has no persisted admin user.`;
174
+ const pid = opts.pid === undefined ? "" : `, pid ${opts.pid}`;
175
+ const head = `Refusing init: port ${port}${pid}: persisted admin user was not detected in this data directory.`;
100
176
  if (opts.offerFlairStop === false)
101
177
  return head;
102
178
  return (`${head} Stop that process before initializing a new instance:\n ${INIT_STOP_FOREIGN_COMMAND}`);
@@ -4,8 +4,7 @@
4
4
  * Linux reads `/proc/<pid>/environ` (NUL-separated, so a space in the path
5
5
  * stays part of the value). macOS `ps -E` output does not separate arguments
6
6
  * from the environment, so it cannot establish ROOTPATH. On macOS, and on
7
- * any failed read, the directory is unavailable. Init must not refuse
8
- * before auth from a directory it cannot read, and must not invent one.
7
+ * any failed read, the directory is unavailable.
9
8
  *
10
9
  * Daemon sidecar recovery keeps its own reader. This module is init's.
11
10
  */
@@ -1,44 +1,17 @@
1
- /**
2
- * init-occupied-listener.ts — flair#1749
3
- *
4
- * `flair init` used to treat "something already answered /health" as "our
5
- * Harper is up", skip its own start, and then explain an operations-API 401
6
- * as a wrong `--admin-pass`. Two claims that message must not make:
7
- *
8
- * - A different data directory does not prove the admin passwords differ.
9
- * - The process holding the HTTP port is not necessarily the one that
10
- * rejected an operations-port request. Those ports are resolved separately
11
- * and can have different owners.
12
- *
13
- * Init can name a different data directory only when that one read could
14
- * read one. An unreadable ROOTPATH is not proof of a foreign instance.
15
- * On macOS the directory is unavailable, so init does not refuse before
16
- * auth from a parsed ROOTPATH.
17
- *
18
- * That pre-auth observation is a single read. It is not the operations-port
19
- * 401 check. A 401 names a pid only when the read before the insert and the
20
- * read after the 401 are the same sole PID. Several holders, or a holder
21
- * that changed during the request, stay "a Harper instance this init did
22
- * not start".
23
- *
24
- * These messages do not offer `flair stop`. `flair stop` cannot be promised
25
- * to act on this listener. The remedy is `kill <pid>` when one process is
26
- * named. Init never signals a process it did not start.
27
- */
28
- import { canonicalLexicalPath } from "./daemon-liveness.js";
29
1
  /**
30
2
  * One observation of who is listening. An unreadable ROOTPATH is omitted,
31
3
  * so it cannot become a pre-auth refusal. Does not decide `flair stop`.
32
4
  */
33
5
  export function listenerFromLookup(port, lookup) {
34
- const pids = lookup.pids(port) ?? [];
6
+ const read = lookup.pids(port);
7
+ const pids = read ?? [];
35
8
  const dataDirs = [];
36
9
  for (const pid of pids) {
37
- const read = lookup.rootPath(pid);
38
- if (read.environReadable && read.rootPath && !dataDirs.includes(read.rootPath))
39
- dataDirs.push(read.rootPath);
10
+ const root = lookup.rootPath(pid);
11
+ if (root.environReadable && root.rootPath && !dataDirs.includes(root.rootPath))
12
+ dataDirs.push(root.rootPath);
40
13
  }
41
- return { port, pids, dataDirs };
14
+ return { port, pids, dataDirs, pidsKnown: read !== null };
42
15
  }
43
16
  /**
44
17
  * The process a 401 can be tied to.
@@ -53,97 +26,27 @@ export function stableAnsweredHolder(before, after) {
53
26
  after.pids.length === 1 &&
54
27
  before.pids[0] === after.pids[0];
55
28
  if (!sameSingle) {
56
- return { port: after.port, pids: [], dataDirs: [] };
29
+ return { port: after.port, pids: [], dataDirs: [], pidsKnown: after.pidsKnown };
57
30
  }
58
31
  return {
59
32
  port: after.port,
60
33
  pids: [after.pids[0]],
61
34
  dataDirs: after.dataDirs,
35
+ pidsKnown: after.pidsKnown,
62
36
  };
63
37
  }
64
- const UNATTRIBUTED = "a Harper instance this init did not start";
65
- /**
66
- * Name the listener for an operator. A pid is included only when exactly one
67
- * was read — several holders are not a kill list. Pid and data directory
68
- * when both were read; whichever was read, plus the fallback phrase, when
69
- * only one was; the fallback phrase alone when neither was.
70
- */
71
- export function describeOccupiedListener(listener) {
72
- const pid = listener.pids.length === 1 ? `pid ${listener.pids[0]}` : null;
73
- const dir = listener.dataDirs.length > 0 ? `data dir ${listener.dataDirs.join(", ")}` : null;
74
- if (pid && dir)
75
- return `${pid}, ${dir}`;
76
- if (pid || dir)
77
- return `${pid ?? dir} (${UNATTRIBUTED})`;
78
- return UNATTRIBUTED;
79
- }
80
- /** Sentence carried wherever a different directory might be misread as a password fact. */
81
- export const DIFFERENT_DIR_DOES_NOT_PROVE_PASSWORD = "A different data directory does not prove the admin passwords differ.";
82
- /** Sentence carried on an operations-port rejection. The HTTP holder is a different fact. */
83
- export const HTTP_HOLDER_DID_NOT_NECESSARILY_REJECT = "The process holding the HTTP port is not necessarily the one that rejected the operations request.";
84
- function foreignDataDirs(expectedDataDir, dataDirs) {
85
- const expected = canonicalLexicalPath(expectedDataDir);
86
- return dataDirs.filter((dir) => canonicalLexicalPath(dir) !== expected);
87
- }
88
- /**
89
- * Printed from the single pre-auth read of the HTTP listener, when that
90
- * read included a ROOTPATH other than this init's data directory. Init
91
- * exits on it — before the authenticated health request and before the
92
- * operations insert. This is not the before-and-after 401 attribution.
93
- * A different directory is not proof the passwords differ. Returns null
94
- * when the directory matches or could not be read: an unreadable lookup
95
- * is not a foreign instance.
96
- */
97
- export function staleHarperBeforeAuthNotice(expectedDataDir, listener) {
98
- const foreign = foreignDataDirs(expectedDataDir, listener.dataDirs);
99
- if (foreign.length === 0)
100
- return null;
101
- const who = describeOccupiedListener({ pids: listener.pids, dataDirs: foreign });
102
- const lines = [
103
- `Harper on port ${listener.port} is ${who}, not this init's data dir ${expectedDataDir}.`,
104
- ` ${DIFFERENT_DIR_DOES_NOT_PROVE_PASSWORD}`,
105
- ` This init will not send its admin password to that process.`,
106
- ` This init will not stop a process it did not start.`,
107
- ];
108
- appendRemedy(lines, listener);
109
- return lines.join("\n");
110
- }
111
- /**
112
- * Appended when init refuses before start because the port is already
113
- * answering and this data directory has no persisted admin user. Names only
114
- * what was read. Does not claim the passwords differ.
115
- */
116
- export function foreignOccupiedListenerDetail(listener, expectedDataDir) {
117
- const lines = [
118
- `The process listening on port ${listener.port} is ${describeOccupiedListener(listener)}.`,
119
- `This init will not send its admin password to a process it did not start.`,
120
- ];
121
- if (expectedDataDir && foreignDataDirs(expectedDataDir, listener.dataDirs).length > 0) {
122
- lines.push(DIFFERENT_DIR_DOES_NOT_PROVE_PASSWORD);
123
- }
124
- lines.push(`This init will not stop a process it did not start.`);
38
+ export function foreignOccupiedListenerDetail(listener) {
39
+ const lines = [];
125
40
  appendRemedy(lines, listener);
126
41
  return lines.join("\n");
127
42
  }
128
- /**
129
- * The operations-API 401 after init skipped its own start. Unlike the
130
- * pre-auth notice, which is one read, `listener` here is the before-and-after
131
- * attribution for the operations port: the same sole PID on both sides,
132
- * or the unattributed fallback. Do not pass the HTTP port's pids through.
133
- * The rejection is not proof the passwords differ, and it is not proof the
134
- * HTTP listener caused it. The message does not offer `flair stop`.
135
- */
136
43
  export function occupiedListenerAuthFailure(input) {
137
- const who = describeOccupiedListener(input.listener);
44
+ const pid = input.listener.pids.length === 1 ? `, pid ${input.listener.pids[0]}` : "";
138
45
  const lines = [
139
46
  `${input.lead}${input.bodyText}`,
140
- ` The operations port ${input.listener.port} rejected this init's admin credentials.`,
141
- ` ${HTTP_HOLDER_DID_NOT_NECESSARILY_REJECT}`,
142
- ` ${DIFFERENT_DIR_DOES_NOT_PROVE_PASSWORD}`,
143
- ` The process holding the operations port is ${who}.`,
144
- ` This init will not stop a process it did not start.`,
47
+ ` Port ${input.listener.port}${pid}: admin authentication failed.`,
145
48
  ];
146
- appendRemedy(lines, input.listener);
49
+ lines.push("Remedy: check the admin password for this data directory, then rerun init.");
147
50
  return lines.join("\n");
148
51
  }
149
52
  /**
@@ -151,6 +54,7 @@ export function occupiedListenerAuthFailure(input) {
151
54
  * promised to act on this listener.
152
55
  */
153
56
  function appendRemedy(lines, listener) {
57
+ lines.push("Remedy: free the port or choose --port and --ops-port, then rerun init.");
154
58
  if (listener.pids.length === 1)
155
59
  lines.push(` kill ${listener.pids[0]}`);
156
60
  for (const dir of listener.dataDirs) {
@@ -158,7 +62,7 @@ function appendRemedy(lines, listener) {
158
62
  }
159
63
  }
160
64
  /** Quote a path that would split on the shell. Numbers and plain paths stay bare. */
161
- function commandArg(value) {
65
+ export function commandArg(value) {
162
66
  if (/^[A-Za-z0-9_./:@+-]+$/.test(value))
163
67
  return value;
164
68
  return `'${value.replace(/'/g, `'\\''`)}'`;
@@ -0,0 +1,73 @@
1
+ import { readFileSync, readdirSync, readlinkSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { canonicalLexicalPath } from "./daemon-liveness.js";
4
+ import { readInitListenerRootPath } from "./init-listener-environ.js";
5
+ export function initChildOwnsProcPort(pid, port, procRoot = "/proc") {
6
+ try {
7
+ const inodes = new Set();
8
+ for (const table of ["tcp", "tcp6"]) {
9
+ const rows = readFileSync(join(procRoot, "net", table), "utf8").trim().split("\n").slice(1);
10
+ for (const row of rows) {
11
+ const fields = row.trim().split(/\s+/);
12
+ if (fields[3] !== "0A" || parseInt(fields[1]?.split(":")[1] ?? "", 16) !== port)
13
+ continue;
14
+ if (!fields[9] || !/^[1-9]\d*$/.test(fields[9]))
15
+ return false;
16
+ inodes.add(fields[9]);
17
+ }
18
+ }
19
+ if (inodes.size === 0)
20
+ return false;
21
+ const owned = new Set();
22
+ const fdDir = join(procRoot, String(pid), "fd");
23
+ for (const fd of readdirSync(fdDir)) {
24
+ try {
25
+ const match = /^socket:\[(\d+)\]$/.exec(readlinkSync(join(fdDir, fd)));
26
+ if (match)
27
+ owned.add(match[1]);
28
+ }
29
+ catch { }
30
+ }
31
+ return [...inodes].every(inode => owned.has(inode));
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ export function trackInitChild(child, options = {}) {
38
+ const pid = child.pid;
39
+ const processGroup = process.platform === "win32" ? undefined : pid;
40
+ let exited = false;
41
+ child.once("exit", () => { exited = true; });
42
+ child.once("error", () => { exited = true; });
43
+ return {
44
+ pid,
45
+ processGroup,
46
+ attributes(listener, dataDir, freePorts) {
47
+ if (!pid || exited || child.exitCode != null || child.signalCode != null || !freePorts.has(listener.port))
48
+ return false;
49
+ if (listener.pids.length > 1)
50
+ return false;
51
+ if (listener.pids.some(holder => holder !== pid))
52
+ return false;
53
+ if ((options.platform ?? process.platform) === "linux") {
54
+ if (!initChildOwnsProcPort(pid, listener.port, options.procRoot))
55
+ return false;
56
+ }
57
+ else if (!listener.pidsKnown || listener.pids.length !== 1)
58
+ return false;
59
+ if (listener.dataDirs.some(dir => canonicalLexicalPath(dir) !== canonicalLexicalPath(dataDir)))
60
+ return false;
61
+ try {
62
+ process.kill(pid, 0);
63
+ if (processGroup)
64
+ process.kill(-processGroup, 0);
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ const root = readInitListenerRootPath(pid);
70
+ return !root.environReadable || (root.rootPath !== null && canonicalLexicalPath(root.rootPath) === canonicalLexicalPath(dataDir));
71
+ },
72
+ };
73
+ }
@@ -0,0 +1,33 @@
1
+ import { createConnection } from "node:net";
2
+ export async function localPortState(port, bindHost, connect = createConnection) {
3
+ const host = ["0.0.0.0", "::", "0:0:0:0:0:0:0:0"].includes(bindHost) ? "127.0.0.1" : bindHost;
4
+ const configured = await tcpPortState(port, host, connect);
5
+ if (host === "127.0.0.1")
6
+ return configured;
7
+ const loopback = await tcpPortState(port, "127.0.0.1", connect);
8
+ if (configured === "listening" || loopback === "listening")
9
+ return "listening";
10
+ if (configured === "unknown" || loopback === "unknown")
11
+ return "unknown";
12
+ return "free";
13
+ }
14
+ function tcpPortState(port, host, connect) {
15
+ return new Promise((resolveState) => {
16
+ let socket;
17
+ try {
18
+ socket = connect({ host, port });
19
+ }
20
+ catch {
21
+ resolveState("unknown");
22
+ return;
23
+ }
24
+ const finish = (state) => {
25
+ socket.destroy();
26
+ resolveState(state);
27
+ };
28
+ socket.setTimeout(1000);
29
+ socket.once("connect", () => finish("listening"));
30
+ socket.once("error", (error) => finish(error.code === "ECONNREFUSED" ? "free" : "unknown"));
31
+ socket.once("timeout", () => finish("unknown"));
32
+ });
33
+ }
@@ -503,6 +503,26 @@ export async function probeInstanceIdentity(endpoint) {
503
503
  const roleNames = await readRoleNames(endpoint);
504
504
  return { rows, roleNames };
505
505
  }
506
+ export async function probeInstanceIds(endpoint) {
507
+ try {
508
+ const rows = await readInstanceRows(endpoint);
509
+ const ids = rows.map((r) => r.id);
510
+ try {
511
+ const parsed = await opsPost(endpoint, { operation: "sql", sql: "SELECT id FROM flair.Agent" }, "Agent read");
512
+ const agents = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.results) ? parsed.results : null;
513
+ if (agents === null || agents.some((row) => typeof row?.id !== "string" || !row.id.trim())) {
514
+ throw new Error("Agent read returned no usable row list");
515
+ }
516
+ return { state: "read", ids, agentIds: agents.map((row) => row.id) };
517
+ }
518
+ catch (err) {
519
+ return { state: "read", ids, agentIds: null, agentReadReason: err instanceof Error ? err.message : String(err) };
520
+ }
521
+ }
522
+ catch (err) {
523
+ return { state: "unreadable", reason: err instanceof Error ? err.message : String(err) };
524
+ }
525
+ }
506
526
  /**
507
527
  * What a prune prints when it is about to delete rows (flair#1883 round 3).
508
528
  *
@@ -0,0 +1,17 @@
1
+ /**
2
+ * instruction-event-contract.ts — the shared reserved-event predicate
3
+ * (flair#2139 slice 3a). Kept in `src/lib` so both the OrgEvent resource and
4
+ * the `flair doctor` check import one definition without crossing the CLI
5
+ * build's rootDir.
6
+ */
7
+ export const RESERVED_EVENT_KINDS = Object.freeze(["soul.changed", "skill.changed"]);
8
+ export const RESERVED_EVENT_ID_PREFIX = "instruction-change:";
9
+ /** Whether a record carries a reserved kind or id prefix. Non-records are not reserved. */
10
+ export function isReservedEventRecord(record) {
11
+ if (record == null || typeof record !== "object" || Array.isArray(record))
12
+ return false;
13
+ const { kind, id } = record;
14
+ if (typeof kind === "string" && RESERVED_EVENT_KINDS.includes(kind))
15
+ return true;
16
+ return typeof id === "string" && id.startsWith(RESERVED_EVENT_ID_PREFIX);
17
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * instruction-event-doctor.ts — the `flair doctor` check for stored OrgEvents
3
+ * that carry a reserved marker but fail the reader rule
4
+ * (flair#2139 slice 3a).
5
+ *
6
+ * Main never refused reserved kinds or the `instruction-change:` id prefix, so
7
+ * a store may already hold rows that were written through the operations API.
8
+ * The reader rule is: the id carries the prefix, the kind is a reserved kind,
9
+ * the refId names an existing InstructionVersion, that version's id is the
10
+ * event id's suffix, and its subject type matches the kind.
11
+ *
12
+ * The decision is pure; the reads use the operations API and return null on a
13
+ * failed read (never an empty list).
14
+ */
15
+ import { RESERVED_EVENT_ID_PREFIX, RESERVED_EVENT_KINDS, isReservedEventRecord } from "./instruction-event-contract.js";
16
+ export const INSTRUCTION_EVENT_ROWS_SQL = "SELECT id, kind, refId FROM flair.OrgEvent";
17
+ export const INSTRUCTION_VERSION_ROWS_SQL = "SELECT id, subjectType FROM flair.InstructionVersion";
18
+ const KIND_SUBJECT = Object.freeze({
19
+ "soul.changed": "soul",
20
+ "skill.changed": "skill",
21
+ });
22
+ function instructionEventReaderFailure(event, version) {
23
+ const id = event.id;
24
+ const kind = event.kind;
25
+ if (typeof id !== "string" || !id.startsWith(RESERVED_EVENT_ID_PREFIX))
26
+ return "missing prefix";
27
+ if (typeof kind !== "string" || !RESERVED_EVENT_KINDS.includes(kind))
28
+ return "kind mismatch";
29
+ if (!version || typeof version.id !== "string")
30
+ return "no matching version";
31
+ if (version.id !== id.slice(RESERVED_EVENT_ID_PREFIX.length))
32
+ return "suffix mismatch";
33
+ if (version.subjectType !== KIND_SUBJECT[kind])
34
+ return "kind mismatch";
35
+ return null;
36
+ }
37
+ /** Whether a stored event satisfies the reader rule. */
38
+ export function instructionEventSatisfiesReaderRule(event, version) {
39
+ return instructionEventReaderFailure(event, version) === null;
40
+ }
41
+ /**
42
+ * Every stored event that carries a reserved marker but fails the reader rule,
43
+ * sorted by id. An event with neither marker is not an impostor.
44
+ */
45
+ function findInstructionEventFailures(events, versions) {
46
+ const byId = new Map();
47
+ for (const version of versions) {
48
+ if (typeof version.id === "string")
49
+ byId.set(version.id, version);
50
+ }
51
+ const impostors = [];
52
+ for (const event of events) {
53
+ const id = event.id;
54
+ if (!isReservedEventRecord(event))
55
+ continue;
56
+ const version = typeof event.refId === "string" ? byId.get(event.refId) : undefined;
57
+ const reason = instructionEventReaderFailure(event, version);
58
+ if (reason) {
59
+ impostors.push({ id: typeof id === "string" && id.length > 0 ? id : "(no id)", reason });
60
+ }
61
+ }
62
+ return impostors.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
63
+ }
64
+ export function findInstructionEventImpostors(events, versions) {
65
+ return findInstructionEventFailures(events, versions).map(({ id }) => id);
66
+ }
67
+ /** The doctor line for a stored impostor set: null when the store is clean. */
68
+ export function describeInstructionEventImpostors(events, versions) {
69
+ const impostors = findInstructionEventFailures(events, versions);
70
+ if (impostors.length === 0)
71
+ return null;
72
+ return `${impostors.length} stored OrgEvent ${impostors.length === 1 ? "row carries" : "rows carry"} a reserved kind or id but ${impostors.length === 1 ? "fails" : "fail"} the instruction-event reader rule: ${impostors.map(({ id, reason }) => `${id} (${reason})`).join(", ")}`;
73
+ }
74
+ /** Read both tables through the ops API; null when either read fails. */
75
+ export async function readInstructionEventTables(args) {
76
+ const fetchImpl = args.fetchImpl ?? fetch;
77
+ const read = async (sql) => {
78
+ try {
79
+ const res = await fetchImpl(args.opsUrl, {
80
+ method: "POST",
81
+ headers: { "Content-Type": "application/json", Authorization: args.authHeader },
82
+ body: JSON.stringify({ operation: "sql", sql }),
83
+ signal: AbortSignal.timeout(args.timeoutMs ?? 5000),
84
+ });
85
+ if (!res.ok)
86
+ return null;
87
+ const data = await res.json();
88
+ return Array.isArray(data) ? data : Array.isArray(data?.results) ? data.results : null;
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ };
94
+ const events = await read(INSTRUCTION_EVENT_ROWS_SQL);
95
+ const versions = await read(INSTRUCTION_VERSION_ROWS_SQL);
96
+ if (events === null || versions === null)
97
+ return null;
98
+ return {
99
+ events: events,
100
+ versions: versions,
101
+ };
102
+ }
@@ -308,12 +308,17 @@ export function readLaunchctlJobState(label, list) {
308
308
  res = list(label);
309
309
  }
310
310
  catch {
311
- return { registered: false, pid: null, lastExitStatus: null };
311
+ return { registered: false, readable: false, pid: null, lastExitStatus: null };
312
312
  }
313
+ // 113 is launchd's "service not found": an ANSWER that the job is not
314
+ // loaded. Any other non-zero code is a failed lookup, which must not be read
315
+ // as "not loaded" by a caller that acts on the answer (flair#3067).
316
+ if (res.code === 113)
317
+ return { registered: false, readable: true, pid: null, lastExitStatus: null };
313
318
  if (res.code !== 0)
314
- return { registered: false, pid: null, lastExitStatus: null };
319
+ return { registered: false, readable: false, pid: null, lastExitStatus: null };
315
320
  const { pid, lastExitStatus } = parseLaunchctlList(res.stdout);
316
- return { registered: true, pid, lastExitStatus };
321
+ return { registered: true, readable: true, pid, lastExitStatus };
317
322
  }
318
323
  /**
319
324
  * Which PID to treat as "the process serving this instance".
@@ -400,6 +405,7 @@ export function assessLaunchdManagement(input) {
400
405
  return { state: "no-service", detail: `no launchd service is registered for this instance (${plistPath})` };
401
406
  }
402
407
  const job = readLaunchctlJobState(label, list);
408
+ const jobLoaded = !job.readable ? "unknown" : job.registered ? "loaded" : "not-loaded";
403
409
  const diagnose = input.diagnose ?? ((p) => diagnoseLaunchdPlistPaths(p));
404
410
  const detachedRemedy = () => {
405
411
  const stale = diagnose(plistPath);
@@ -416,6 +422,7 @@ export function assessLaunchdManagement(input) {
416
422
  return {
417
423
  state: "detached",
418
424
  label,
425
+ jobLoaded,
419
426
  detail: `the launchd service ${label} is registered on disk but not loaded, so launchd is not managing this instance.${because}`,
420
427
  remedy,
421
428
  };
@@ -428,6 +435,7 @@ export function assessLaunchdManagement(input) {
428
435
  return {
429
436
  state: "detached",
430
437
  label,
438
+ jobLoaded,
431
439
  detail: `the launchd job ${label} is loaded but not running, so whatever is serving this instance was not started by launchd.${exit}${because}`,
432
440
  remedy,
433
441
  };
@@ -437,6 +445,7 @@ export function assessLaunchdManagement(input) {
437
445
  return {
438
446
  state: "detached",
439
447
  label,
448
+ jobLoaded,
440
449
  detail: `this instance is served by process ${instancePid}, but launchd's job ${label} is process ${job.pid} — ` +
441
450
  `the running instance is not the one launchd manages.${because}`,
442
451
  remedy,
@@ -452,6 +461,7 @@ export function assessLaunchdManagement(input) {
452
461
  return {
453
462
  state: "unverified",
454
463
  label,
464
+ jobLoaded,
455
465
  detail: `launchd job ${label} is running as process ${job.pid}, but the process serving this instance could not be ` +
456
466
  "identified (no live hdb.pid, and no listener found on its port), so launchd management is NOT verified",
457
467
  remedy: ["flair restart"],
@@ -462,6 +472,7 @@ export function assessLaunchdManagement(input) {
462
472
  return {
463
473
  state: "managed",
464
474
  label,
475
+ jobLoaded,
465
476
  detail: `launchd job ${label} is running as process ${job.pid}`,
466
477
  launchdPid: job.pid,
467
478
  servingPid: instancePid,
@@ -487,6 +498,30 @@ export function renderDetachedWarning(m, headline) {
487
498
  lines.push(` Fix: ${m.remedy.join(" && ")}`);
488
499
  return lines;
489
500
  }
501
+ /**
502
+ * The lines for an unconfirmed managed start (flair#2422). Names what was
503
+ * observed: the reachability wait before the probe passed, and the probe's
504
+ * result by name. "Flair is running" is printed for `flair` — the result whose
505
+ * probe saw Flair shape — and the other results say what they saw instead.
506
+ * Kept here so the wording is assertable without a launchd host.
507
+ */
508
+ export function renderManagedStartUnconfirmed(input) {
509
+ const { port, confirmation, detail, moved, launchdDetail, remedy } = input;
510
+ const headline = {
511
+ flair: `Flair is running on port ${port}, but it is NOT verified as launchd-managed`,
512
+ foreign: `The initial reachability wait on port ${port} passed, but the confirmation probe got a response that was not a Flair health answer (non-2xx or not Flair-shaped), so Flair is NOT verified as launchd-managed`,
513
+ refused: `The initial reachability wait on port ${port} passed, but the confirmation probe's connection was refused (nothing was listening), so Flair is NOT verified as launchd-managed`,
514
+ unreachable: `The initial reachability wait on port ${port} passed, but the confirmation probe could not reach the port (timeout or network error), so Flair is NOT verified as launchd-managed`,
515
+ };
516
+ const lines = [`⚠️ ${headline[confirmation]}`, ` ${detail}`];
517
+ if (moved)
518
+ lines.push(` ${moved}`);
519
+ if (launchdDetail)
520
+ lines.push(` ${launchdDetail}`);
521
+ if (remedy?.length)
522
+ lines.push(` Fix: ${remedy.join(" && ")}`);
523
+ return lines;
524
+ }
490
525
  // renderVerifiedSummary used to live here and qualify ✅ from version +
491
526
  // LaunchdManagement alone (flair#1022). That signature was the ceiling on
492
527
  // what it could notice — a blacklist of one known-unhealthy form. The