@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
@@ -45,6 +45,7 @@ export const DOCTOR_CHECK_IDS = [
45
45
  "verified-read",
46
46
  "keys-prune",
47
47
  "launchd-management",
48
+ "worker-threads",
48
49
  ];
49
50
  const MCP_CLIENT_IDS = ["claude-code", "codex", "gemini", "cursor", "antigravity"];
50
51
  function result(id, label, status, extra = {}) {
@@ -261,43 +262,42 @@ function runSessionStartHook(ctx) {
261
262
  });
262
263
  }
263
264
  const expected = flairCliVersion();
264
- if (isResolvedVersion(expected)) {
265
- const findings = sessionStartHookPinFindings(ctx.homeDir, expected)
266
- .filter((f) => harnesses.includes(f.reading.target.id));
267
- if (findings.length > 0) {
268
- // flair#1778 follow-up: PIN DIRECTION matters, and there are THREE cases.
269
- // behind -> stale, blocking: today's error + re-pin.
270
- // ahead -> a held PASS: re-pinning would LOWER it, so it is not a
271
- // failure and doctor exits on the state it preserves.
272
- // unknown -> a pin we cannot compare: its OWN warn finding. It is NOT
273
- // blocking, NOT auto-re-pinned, and never worded as an old
274
- // adapter — the guard holds an unreadable pin.
275
- const behind = findings.filter((f) => f.direction === "behind");
276
- const unknownFindings = findings.filter((f) => f.direction === "unknown");
277
- const aheadFindings = findings.filter((f) => f.direction === "ahead");
278
- if (behind.length > 0) {
279
- const readings = behind.map((f) => f.reading);
280
- const first = readings[0];
281
- const detail = behind.length === 1
282
- ? `SessionStart hook (${first.target.id}): pinned to flair-mcp@${first.pin} (installed CLI is ${expected})`
283
- : `SessionStart hook: stale pins ${readings.map((r) => `${r.target.id}@${r.pin}`).join(", ")} (installed CLI is ${expected})`;
284
- return result(id, label, "fail", {
285
- detail,
286
- remedy: staleHookRemedy(readings),
287
- });
288
- }
289
- if (unknownFindings.length > 0) {
290
- const detail = unknownFindings.length === 1
291
- ? `SessionStart hook (${unknownFindings[0].reading.target.id}): pin is not a version I can compare: ${unknownFindings[0].reading.pin} — not re-pinned; re-run flair init or edit the hook if this is unintended`
292
- : `SessionStart hook: pins I cannot compare: ${unknownFindings.map((f) => `${f.reading.target.id}@${f.reading.pin}`).join(", ")} — not re-pinned; re-run flair init or edit the hook if this is unintended`;
293
- return result(id, label, "warn", { detail });
294
- }
295
- const aheadDetail = aheadFindings.length === 1
296
- ? `SessionStart hook (${aheadFindings[0].reading.target.id}): pinned to flair-mcp@${aheadFindings[0].reading.pin}, ahead of the installed CLI ${expected} — held`
297
- : `SessionStart hook: pins ahead of the installed CLI ${expected} — held (${aheadFindings.map((f) => `${f.reading.target.id}@${f.reading.pin}`).join(", ")})`;
298
- return result(id, label, "pass", { detail: aheadDetail });
265
+ const findings = sessionStartHookPinFindings(ctx.homeDir, expected)
266
+ .filter((f) => harnesses.includes(f.reading.target.id));
267
+ const heldFindings = findings.filter((f) => f.reading.held);
268
+ if (isResolvedVersion(expected) && findings.length > 0) {
269
+ const behind = findings.filter((f) => f.direction === "behind");
270
+ if (behind.length > 0) {
271
+ const readings = behind.map((f) => f.reading);
272
+ const first = readings[0];
273
+ const detail = behind.length === 1
274
+ ? `SessionStart hook (${first.target.id}): pinned to flair-mcp@${first.pin} (installed CLI is ${expected})`
275
+ : `SessionStart hook: stale pins ${readings.map((r) => `${r.target.id}@${r.pin}`).join(", ")} (installed CLI is ${expected})`;
276
+ return result(id, label, "fail", {
277
+ detail,
278
+ remedy: staleHookRemedy(readings),
279
+ });
299
280
  }
300
281
  }
282
+ if (heldFindings.length > 0) {
283
+ return result(id, label, "warn", {
284
+ detail: heldFindings.map((f) => `SessionStart hook (${f.reading.target.id}): ${f.reading.held}`).join("; "),
285
+ });
286
+ }
287
+ if (isResolvedVersion(expected) && findings.length > 0) {
288
+ const unknownFindings = findings.filter((f) => f.direction === "unknown" && !f.reading.held);
289
+ const aheadFindings = findings.filter((f) => f.direction === "ahead");
290
+ if (unknownFindings.length > 0) {
291
+ const detail = unknownFindings.length === 1
292
+ ? `SessionStart hook (${unknownFindings[0].reading.target.id}): pin is not a version I can compare: ${unknownFindings[0].reading.pin} — not re-pinned; re-run flair init or edit the hook if this is unintended`
293
+ : `SessionStart hook: pins I cannot compare: ${unknownFindings.map((f) => `${f.reading.target.id}@${f.reading.pin}`).join(", ")} — not re-pinned; re-run flair init or edit the hook if this is unintended`;
294
+ return result(id, label, "warn", { detail });
295
+ }
296
+ const aheadDetail = aheadFindings.length === 1
297
+ ? `SessionStart hook (${aheadFindings[0].reading.target.id}): pinned to flair-mcp@${aheadFindings[0].reading.pin}, ahead of the installed CLI ${expected} — held`
298
+ : `SessionStart hook: pins ahead of the installed CLI ${expected} — held (${aheadFindings.map((f) => `${f.reading.target.id}@${f.reading.pin}`).join(", ")})`;
299
+ return result(id, label, "pass", { detail: aheadDetail });
300
+ }
301
301
  return result(id, label, "pass", {
302
302
  detail: `wired for ${harnesses.join(", ")}`,
303
303
  });
@@ -331,6 +331,110 @@ function runKeysPrune(ctx) {
331
331
  detail: `classified ${agentKeyIds.length} agent / ${nodeKeyIds.length} node key(s)`,
332
332
  });
333
333
  }
334
+ export function readWorkerThreadsObservation(raw) {
335
+ if (raw === undefined)
336
+ return { kind: "serving" };
337
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
338
+ return { kind: "unknown" };
339
+ const rec = raw;
340
+ if (rec.state !== "refused" && rec.state !== "unsafe-opt-in")
341
+ return { kind: "unknown" };
342
+ const workerCount = rec.workerCount;
343
+ return {
344
+ kind: "refused",
345
+ state: rec.state,
346
+ workerCount: typeof workerCount === "number" && Number.isFinite(workerCount) ? workerCount : null,
347
+ };
348
+ }
349
+ export function interpretFlairHealth(status, body) {
350
+ const observation = readWorkerThreadsObservation(body?.multiWorker);
351
+ if (status >= 200 && status < 300)
352
+ return { reaching: true, observation };
353
+ if (status === 503 && observation.kind === "refused")
354
+ return { reaching: true, observation };
355
+ return { reaching: false, observation: null };
356
+ }
357
+ /**
358
+ * flair#2530 — the /Health body doctor may read fields from (version, embedding,
359
+ * embeddingSpace). A 2xx object body is read as before. A 503 is read only when
360
+ * its body has the fields Health.get builds (ok:false, a version string, a
361
+ * boolean searchReady, a capabilities array), so a 503 without them (a typical
362
+ * proxy or other-service error) is not read. The check is on shape only; it
363
+ * cannot prove the response came from Flair. Reading a 503 never makes the
364
+ * instance healthy: `notReady` marks a readiness refusal.
365
+ */
366
+ export function readFlairHealthBody(status, body) {
367
+ if (body === null || typeof body !== "object" || Array.isArray(body))
368
+ return null;
369
+ const rec = body;
370
+ if (status >= 200 && status < 300)
371
+ return { body: rec, notReady: false, notReadyReason: null };
372
+ if (status !== 503)
373
+ return null;
374
+ if (rec.ok !== false ||
375
+ typeof rec.version !== "string" ||
376
+ typeof rec.searchReady !== "boolean" ||
377
+ !Array.isArray(rec.capabilities)) {
378
+ return null;
379
+ }
380
+ const reason = rec.searchReadyReason;
381
+ // /Health is unauthenticated: print the reason only when it is short and has
382
+ // no control characters.
383
+ const printable = typeof reason === "string" && reason.trim().length > 0 && reason.length <= 200 && !/[\u0000-\u001f\u007f]/.test(reason)
384
+ ? reason.trim()
385
+ : null;
386
+ return { body: rec, notReady: rec.searchReady === false, notReadyReason: rec.searchReady === false ? printable : null };
387
+ }
388
+ export async function probeFlairHealth(url, fetchImpl = fetch, timeoutMs = 3000) {
389
+ try {
390
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });
391
+ let body = null;
392
+ try {
393
+ body = await res.json();
394
+ }
395
+ catch {
396
+ body = null;
397
+ }
398
+ const verdict = interpretFlairHealth(res.status, body);
399
+ const read = readFlairHealthBody(res.status, body);
400
+ return {
401
+ ...verdict,
402
+ status: res.status,
403
+ body,
404
+ healthBody: read?.body ?? null,
405
+ notReady: read?.notReady ?? false,
406
+ notReadyReason: read?.notReadyReason ?? null,
407
+ };
408
+ }
409
+ catch {
410
+ return { reaching: false, status: 0, body: null, observation: null, healthBody: null, notReady: false, notReadyReason: null };
411
+ }
412
+ }
413
+ function runWorkerThreads(ctx) {
414
+ const id = "worker-threads";
415
+ const label = "worker threads";
416
+ const observed = ctx.workerThreads;
417
+ if (!observed) {
418
+ return result(id, label, "skip", { detail: "no /Health response observed at the configured URL" });
419
+ }
420
+ if (observed.kind === "unknown") {
421
+ return result(id, label, "fail", {
422
+ detail: "the /Health response carried a worker-thread state this doctor does not recognize",
423
+ remedy: "Inspect /Health and re-run doctor",
424
+ });
425
+ }
426
+ if (observed.kind === "serving") {
427
+ return result(id, label, "pass", { detail: "the configured /Health response has no multi-worker refusal field" });
428
+ }
429
+ const count = observed.workerCount === null ? "an unreadable worker count" : `${observed.workerCount} Harper worker threads`;
430
+ const detail = observed.state === "refused"
431
+ ? `the configured /Health response reports refusal with ${count}; multi-worker is unsupported until the readiness work lands`
432
+ : `the configured /Health response reports ${count} and an explicit unsafe opt-in`;
433
+ return result(id, label, "fail", {
434
+ detail,
435
+ remedy: "Set THREADS_COUNT=1 and restart flair",
436
+ });
437
+ }
334
438
  function runLaunchdManagement(ctx) {
335
439
  const id = "launchd-management";
336
440
  const label = "launchd management";
@@ -388,6 +492,7 @@ export const DOCTOR_CHECKS = [
388
492
  { id: "verified-read", label: "per-agent verified-read", run: runVerifiedRead },
389
493
  { id: "keys-prune", label: "keys prune classification", run: runKeysPrune },
390
494
  { id: "launchd-management", label: "launchd management", run: runLaunchdManagement },
495
+ { id: "worker-threads", label: "worker threads", run: runWorkerThreads },
391
496
  ];
392
497
  /**
393
498
  * Run every catalog id. Missing implementations and thrown runners become
@@ -0,0 +1,10 @@
1
+ export const DURABILITY_TIER_GUARANTEES = [
2
+ "permanent — routine maintenance never reaps or age-archives it (an expired validTo archives an eligible row; an acquired expiresAt never reaps it); it never decays; bootstrap considers the bootstrapping agent's own permanent memories before recent rows, subject to scope, expiry/closure and the token budget.",
3
+ "persistent — routine maintenance never reaps or age-archives it (an expired validTo archives an eligible row; an acquired expiresAt never reaps it).",
4
+ "standard — routine maintenance archives it once its validTo passes or, as a session note, after 30 days.",
5
+ "ephemeral — routine maintenance reaps it once its TTL (24h by default) passes.",
6
+ ];
7
+ /** The one-sentence limit every durability tier shares. */
8
+ export const DURABILITY_CAVEAT = "No tier adds a flush, fsync, backup or replica acknowledgement: an explicit delete (owner or admin) or a store failure can end any of them.";
9
+ /** Single-line form for a commander `--durability` option description. */
10
+ export const DURABILITY_TIERS_HELP = DURABILITY_TIER_GUARANTEES.join(" ") + " " + DURABILITY_CAVEAT;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * A bounded, printable reason for a failed scan. The guard's own
3
+ * reason strings are short and content-free, but /Health is unauthenticated, so
4
+ * bound the length and reject control characters before printing the string.
5
+ */
6
+ export function boundedScanFailureReason(reason) {
7
+ if (typeof reason !== "string")
8
+ return "unspecified";
9
+ const s = reason.trim();
10
+ if (s.length === 0 || s.length > 120 || /[\u0000-\u001f\u007f]/.test(s))
11
+ return "unspecified";
12
+ return s;
13
+ }
14
+ /**
15
+ * The guard's `excluded` count as a printable whole number, or null when it is
16
+ * absent or malformed (an older or foreign server, or no scan has published a
17
+ * count). Never rendered as zero on unknown evidence.
18
+ */
19
+ function excludedCount(value) {
20
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
21
+ }
22
+ /** The clause naming the excluded count, or "" when it is unknown. */
23
+ function excludedClause(value) {
24
+ const n = excludedCount(value);
25
+ if (n === null)
26
+ return "";
27
+ return `; excluded from the vector leg: ${n} row(s) with no trusted model stamp`;
28
+ }
29
+ /**
30
+ * Doctor finding, or null when there is nothing to say. The five states map to
31
+ * a distinct line: `uniform` an OK line; `mixed` and `excluded` blocking
32
+ * findings with a remedy; `unverified` and `scan-failed` advisories naming the
33
+ * state.
34
+ */
35
+ export function describeEmbeddingSpaceDoctorFinding(field) {
36
+ if (field == null || typeof field !== "object" || Array.isArray(field))
37
+ return null;
38
+ const rec = field;
39
+ switch (rec.state) {
40
+ case "uniform":
41
+ return { isIssue: false, icon: "ok", message: "embedding model stamps verified uniform" };
42
+ case "mixed":
43
+ return {
44
+ isIssue: true,
45
+ icon: "error",
46
+ message: "a non-current embedding model stamp was observed — the embedding leg is refused" +
47
+ // A known foreign stamp outranks a scan error; name the error too.
48
+ (rec.reason == null ? "" : `; last scan failed (${boundedScanFailureReason(rec.reason)})`),
49
+ fixHint: "Reconcile to one space with: flair reembed --stale-only",
50
+ };
51
+ case "excluded":
52
+ return {
53
+ isIssue: true,
54
+ icon: "error",
55
+ message: "the last scan found a stored vector with no trusted current-space stamp — the embedding leg is refused" +
56
+ excludedClause(rec.excluded),
57
+ fixHint: "Re-embed or remove the stored vector; a later embedding query must trigger and complete a rescan before flair doctor can confirm the repair",
58
+ };
59
+ case "unverified":
60
+ return {
61
+ isIssue: false,
62
+ icon: "warn",
63
+ message: "embedding space not yet verified — the embedding leg is refused until a scan verifies the stamps",
64
+ };
65
+ case "scan-failed":
66
+ return {
67
+ isIssue: false,
68
+ icon: "warn",
69
+ message: `embedding space unverified: last scan failed (${boundedScanFailureReason(rec.reason)}) — ` +
70
+ `the embedding leg is refused`,
71
+ };
72
+ default:
73
+ return null;
74
+ }
75
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * flair-agent-role.ts — the `flair_agent` Harper role's grant spec, shared by
3
+ * the CLI (`ensureFlairAgentRole`, src/cli.ts) and the server's startup check
4
+ * (resources/flair-agent-role-boot.ts). No Harper imports.
5
+ */
6
+ // ─── flair_agent role ────────────────────────────────────────────────────────
7
+ //
8
+ // The auth reshape replaces the global gate's "verified agent borrows admin
9
+ // super_user" elevation with a real, least-privilege Harper role. After an
10
+ // agent's Ed25519 signature verifies, resources resolve the request to the
11
+ // shared `flair_agent`-roled user instead of admin. Critically: with no
12
+ // `super_user` and no operations grants, /sql and /graphql become NATIVELY 403
13
+ // for agents (the raw-query block the gate hand-rolled is now enforced by
14
+ // Harper itself).
15
+ // Harper 5.0.21 add_role requires an `attribute_permissions` array on EVERY table
16
+ // grant (empty = no attribute-level restriction, so the table-level CRUD applies);
17
+ // omitting it makes add_role reject the whole spec ("Missing 'attribute_permissions'
18
+ // array"). Validated live against a spawned Harper. This helper guarantees the
19
+ // array is never forgotten. Also: `cluster_user` is NOT a valid top-level key —
20
+ // Harper reads unrecognized top-level keys as database names ("database
21
+ // 'cluster_user' does not exist"); only super_user / structure_user are recognized.
22
+ const grant = (read, insert, update, del) => ({ read, insert, update, delete: del, attribute_permissions: [] });
23
+ /** Canonical permission spec for flair_agent (least-privilege; real @table names). */
24
+ export const FLAIR_AGENT_PERMISSION = {
25
+ super_user: false,
26
+ structure_user: false,
27
+ flair: {
28
+ tables: {
29
+ // Core agent-owned data — CRUD envelope.
30
+ Memory: grant(true, true, true, true),
31
+ MemoryCandidate: grant(true, true, true, true),
32
+ MemoryGrant: grant(true, true, true, true),
33
+ // Asset (images-in-Flair slice 1). Harper authorizes BEFORE Asset.post
34
+ // runs, so a de-elevated flair_agent needs the table grant or signed
35
+ // POST /Asset 403s as AccessViolation (Kern P0). CRUD envelope;
36
+ // owner-only + write-time size/MIME gates live in resources/Asset.ts.
37
+ Asset: grant(true, true, true, true),
38
+ Soul: grant(true, true, true, false),
39
+ OrgEvent: grant(true, true, true, true),
40
+ WorkspaceState: grant(true, true, true, true),
41
+ Relationship: grant(true, true, true, true),
42
+ // Flair Relay S1 (flair#1521). Harper authorizes BEFORE the resource
43
+ // methods run, so a de-elevated flair_agent needs the table grant OR it
44
+ // 403s on POST /Message before relaySend is reached (Kern P0-2). read =
45
+ // the party-scoped collection (Message.search); insert = send via post().
46
+ // update = FALSE (least privilege, Kern P0 blocker): the ack's write goes
47
+ // through the IN-PROCESS static accessor (relayConsume → deps.messages.put),
48
+ // which bypasses role gates entirely — the same raw-put seam Federation.ts
49
+ // relies on — so update:true is NOT needed for any legitimate path. Leaving
50
+ // it granted let PATCH /Message/<id> reach Table's update verb, whose
51
+ // authorize step consults update:true and PASSES for any de-elevated agent,
52
+ // bypassing Message.put()'s FORBIDDEN guard AND relayConsume's recipient-only
53
+ // check (Message has no patch() at the platform level → TableResource.patch
54
+ // runs update()+save() directly). delete = false: direct deletes are
55
+ // admin/internal only. Message.patch() also guards the verb in-resource.
56
+ Message: grant(true, true, false, false),
57
+ Integration: grant(true, true, true, true),
58
+ Credential: grant(true, true, true, true),
59
+ Presence: grant(true, true, true, false),
60
+ // MemoryUsage (flair#683): the usage-feedback dedup ledger. Read (own
61
+ // contributions, scoped in resources/MemoryUsage.ts) + insert (a fresh
62
+ // contribution row) only — NO update/delete. This is load-bearing, not
63
+ // just least-privilege tidiness: the dedup rule ("(agent, memory)
64
+ // contributes ≤ 1") is enforced by requiring a NEW ledger row before
65
+ // any usageCount bump; if an agent could delete its own row, it could
66
+ // re-trigger the /RecordUsage endpoint for the same memory indefinitely
67
+ // (create → count → delete → count again → repeat), defeating the cap
68
+ // entirely. See resources/MemoryUsage.ts's module doc.
69
+ MemoryUsage: grant(true, true, false, false),
70
+ // MemoryHitStat (flair#1528): internal search-hit ledger. No agent REST
71
+ // surface (@table without @export). Counts overlay onto Memory reads.
72
+ MemoryHitStat: grant(false, false, false, false),
73
+ // Agent: read for discovery, update own card; creation/removal is admin.
74
+ Agent: grant(true, false, true, false),
75
+ // Read-only reference data.
76
+ Instance: grant(true, false, false, false),
77
+ // flair#2141 S1: org-scope skill assignments. Agents read them; every
78
+ // write is operator/internal only (resources/OrgSkillAssignment.ts), so
79
+ // no write grant. The history table has no direct REST route.
80
+ OrgSkillAssignment: grant(true, false, false, false),
81
+ OrgSkillAssignmentHistory: grant(false, false, false, false),
82
+ // flair#2139 S1: instruction-version history. Read only — the resource
83
+ // itself denies every mutation verb to every principal, and the only
84
+ // application writer is the in-process append helper. See resources/InstructionVersion.ts.
85
+ InstructionVersion: grant(true, false, false, false),
86
+ // Federation / OAuth / IdP / internal — system + admin only; agents get none.
87
+ Peer: grant(false, false, false, false),
88
+ PairingToken: grant(false, false, false, false),
89
+ SyncLog: grant(false, false, false, false),
90
+ OAuthClient: grant(false, false, false, false),
91
+ OAuthToken: grant(false, false, false, false),
92
+ OAuthAuthCode: grant(false, false, false, false),
93
+ IdpConfig: grant(false, false, false, false),
94
+ IdJagReplay: grant(false, false, false, false),
95
+ },
96
+ },
97
+ };
98
+ export const FLAIR_AGENT_ROLE_NAME = "flair_agent";
99
+ /**
100
+ * Brings an existing `flair_agent` role to FLAIR_AGENT_PERMISSION (flair#2141
101
+ * S1): "updated" after an `alter_role`, "unchanged" when it already matches,
102
+ * "absent" when the instance has no such role (this never creates it). Throws
103
+ * when the role list cannot be read; nothing is written then.
104
+ */
105
+ export async function alignFlairAgentRole(op) {
106
+ const roles = await op({ operation: "list_roles" });
107
+ if (!Array.isArray(roles))
108
+ throw new Error("list_roles did not return a list of roles");
109
+ const existing = roles.find((r) => r?.role === FLAIR_AGENT_ROLE_NAME || r?.name === FLAIR_AGENT_ROLE_NAME);
110
+ if (!existing)
111
+ return "absent";
112
+ const permission = existing.permission ?? existing.role?.permission;
113
+ if (JSON.stringify(permission) === JSON.stringify(FLAIR_AGENT_PERMISSION))
114
+ return "unchanged";
115
+ // Harper's alter_role addresses the role by its `id`.
116
+ if (typeof existing.id !== "string" || existing.id.length === 0)
117
+ throw new Error("the flair_agent role has no id");
118
+ await op({ operation: "alter_role", id: existing.id, role: FLAIR_AGENT_ROLE_NAME, permission: FLAIR_AGENT_PERMISSION });
119
+ return "updated";
120
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * hub-url.ts — normalize a federation hub URL.
3
+ *
4
+ * New pairings store the normalized hub URL; sync normalizes previously stored
5
+ * endpoints when sending. This strips trailing slashes only; it does not
6
+ * otherwise validate the hub URL's path.
7
+ */
8
+ export function normalizeHubUrl(hubUrl) {
9
+ // A non-string (a peer row without an endpoint or id) is passed through
10
+ // unchanged, exactly as it was used before.
11
+ return typeof hubUrl === "string" ? hubUrl.replace(/\/+$/, "") : hubUrl;
12
+ }
@@ -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
  */