@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
@@ -9,7 +9,9 @@
9
9
  * FederationSync (Federation.ts, via verifyFederationRequestBody).
10
10
  *
11
11
  * The XAA ID-JAG `jti` record (flair#2073) uses the same `recordOnce` on its
12
- * own table; see `claimIdJagJti` below.
12
+ * own table; see `claimIdJagJti` below. The OAuth single-use record (flair#2145)
13
+ * uses it on one more, for claims to redeem an authorization code (`c:<sha256>`)
14
+ * or rotate a refresh token (`r:<sha256>`); see `claimOAuthSingleUse` below.
13
15
  *
14
16
  * The record of truth is the local `ReplayNonce` table (schemas/replay.graphql:
15
17
  * `replicate: false`, `expiration: 120`). Every Harper thread of this instance
@@ -154,6 +156,7 @@ const REFUSED = {
154
156
  a: "TPS-Ed25519 signed request",
155
157
  f: "federation signed request",
156
158
  x: "XAA jwt-bearer grant whose assertion carries a jti",
159
+ o: "OAuth request that redeems an authorization code or rotates a refresh token",
157
160
  };
158
161
  function noteUnavailable(scope, err, table = REPLAY_TABLE) {
159
162
  const reason = err instanceof ReplayStoreUnavailable
@@ -276,7 +279,7 @@ export function verifyFederationRequestBody(body, publicKeyB64url) {
276
279
  export const ID_JAG_REPLAY_TABLE = "IdJagReplay";
277
280
  /** First element of every jti lock key, so a jti never shares a lock key with a nonce. */
278
281
  export const ID_JAG_LOCK_NAMESPACE = "flair-replay-id-jag";
279
- function idJagReplayDeps() {
282
+ export function idJagReplayDeps() {
280
283
  return {
281
284
  table: databases?.flair?.[ID_JAG_REPLAY_TABLE],
282
285
  transaction: globalThis.transaction,
@@ -284,6 +287,20 @@ function idJagReplayDeps() {
284
287
  lockNamespace: ID_JAG_LOCK_NAMESPACE,
285
288
  };
286
289
  }
290
+ /**
291
+ * The reason `deps`' table cannot remember a key for `minRetentionMs`, or null.
292
+ * `basis` completes the sentence that says what the minimum covers.
293
+ */
294
+ export function storeRetentionGap(deps, minRetentionMs, basis) {
295
+ const gap = replayStoreContractGap(deps);
296
+ if (gap)
297
+ return gap;
298
+ const expirationMs = deps.table.expirationMS;
299
+ if (typeof expirationMs === "number" && expirationMs > 0 && expirationMs <= minRetentionMs) {
300
+ return `flair.${deps.name ?? REPLAY_TABLE} keeps rows ${expirationMs} ms, not longer than the ${minRetentionMs} ms ${basis}`;
301
+ }
302
+ return null;
303
+ }
287
304
  /**
288
305
  * Claim an ID-JAG's `jti` once per instance, through `recordOnce`. Call it after
289
306
  * the assertion has validated and before the grant has any effect; refuse on
@@ -294,13 +311,9 @@ function idJagReplayDeps() {
294
311
  export async function claimIdJagJti(jti, minRetentionMs, now = Date.now()) {
295
312
  try {
296
313
  const deps = idJagReplayDeps();
297
- const gap = replayStoreContractGap(deps);
314
+ const gap = storeRetentionGap(deps, minRetentionMs, "an assertion can stay acceptable");
298
315
  if (gap)
299
316
  throw new ReplayStoreUnavailable(gap);
300
- const expirationMs = deps.table.expirationMS;
301
- if (typeof expirationMs === "number" && expirationMs > 0 && expirationMs <= minRetentionMs) {
302
- throw new ReplayStoreUnavailable(`flair.${ID_JAG_REPLAY_TABLE} keeps rows ${expirationMs} ms, not longer than the ${minRetentionMs} ms an assertion can stay acceptable`);
303
- }
304
317
  // A lock miss ("contended") is refused like a stored row.
305
318
  return (await recordOnce(jti, now, deps)) === "recorded" ? "recorded" : "replay";
306
319
  }
@@ -309,6 +322,43 @@ export async function claimIdJagJti(jti, minRetentionMs, now = Date.now()) {
309
322
  return "unavailable";
310
323
  }
311
324
  }
325
+ // ─── OAuth single-use records (flair#2145) ─────────────────────────────────
326
+ /** One row per claim to redeem a code or rotate a refresh token (schemas/oauth.graphql). */
327
+ export const OAUTH_SINGLE_USE_TABLE = "OAuthSingleUse";
328
+ /** First element of every single-use lock key, so it never collides with a nonce or a jti lock. */
329
+ export const OAUTH_SINGLE_USE_LOCK_NAMESPACE = "flair-replay-oauth";
330
+ export function oauthSingleUseDeps() {
331
+ return {
332
+ table: databases?.flair?.[OAUTH_SINGLE_USE_TABLE],
333
+ transaction: globalThis.transaction,
334
+ name: OAUTH_SINGLE_USE_TABLE,
335
+ lockNamespace: OAUTH_SINGLE_USE_LOCK_NAMESPACE,
336
+ };
337
+ }
338
+ /**
339
+ * Claim an authorization code presented for redemption (`c:<sha256>`) or a
340
+ * refresh token presented for rotation (`r:<sha256>`) once per instance,
341
+ * through `recordOnce`. Call it after the request has been validated and before
342
+ * the handler attempts its later write or token issuance; refuse on anything
343
+ * but "recorded". `sha256Hex` is the SHA-256 of the code or token, so the
344
+ * record holds no redeemable secret. `minRetentionMs` is the longest the code
345
+ * or token can be presented after its row is recorded: a table whose rows do
346
+ * not outlive it is unavailable.
347
+ */
348
+ export async function claimOAuthSingleUse(kind, sha256Hex, minRetentionMs, now = Date.now()) {
349
+ try {
350
+ const deps = oauthSingleUseDeps();
351
+ const gap = storeRetentionGap(deps, minRetentionMs, "a redeemed authorization code or refresh token can be presented");
352
+ if (gap)
353
+ throw new ReplayStoreUnavailable(gap);
354
+ // A lock miss ("contended") is refused like a stored row.
355
+ return (await recordOnce(`${kind === "refresh" ? "r" : "c"}:${sha256Hex}`, now, deps)) === "recorded" ? "recorded" : "replay";
356
+ }
357
+ catch (err) {
358
+ noteUnavailable("o", err, OAUTH_SINGLE_USE_TABLE);
359
+ return "unavailable";
360
+ }
361
+ }
312
362
  // ─── Boot report ───────────────────────────────────────────────────────────
313
363
  /** Every gap that would refuse requests on this thread, or an empty list. */
314
364
  export function replayStoreBootGaps(deps = harperReplayDeps()) {
@@ -320,17 +370,44 @@ export function replayStoreBootGaps(deps = harperReplayDeps()) {
320
370
  }
321
371
  return gaps;
322
372
  }
323
- // Once per worker thread, after the schema's tables are bound. Harper defines
324
- // `server.workerCount` on worker threads; unit tests and the CLI never reach it.
325
- if (typeof setTimeout !== "undefined" && typeof globalThis.server?.workerCount === "number") {
326
- setTimeout(() => {
327
- try {
328
- for (const gap of replayStoreBootGaps()) {
329
- console.error(`[flair-replay] ReplayStoreUnavailable at boot (${gap}). Signed requests on this path are refused.`);
330
- }
331
- }
332
- catch (err) {
333
- console.error(`[flair-replay] ReplayStoreUnavailable at boot: ${err?.message ?? err}`);
373
+ /** Run during the awaited resource-module import, after graphqlSchema loads. */
374
+ function reportAtBoot(fn) {
375
+ // Harper defines `server.workerCount` on worker threads; unit tests and the
376
+ // CLI never reach this. The jsResource initial load awaits module imports,
377
+ // and the worker waits for that load before it starts listening.
378
+ if (typeof globalThis.server?.workerCount !== "number")
379
+ return;
380
+ try {
381
+ fn();
382
+ }
383
+ catch (err) {
384
+ console.error(`[flair-replay] ReplayStoreUnavailable at boot: ${err?.message ?? err}`);
385
+ }
386
+ }
387
+ // Once per worker thread, after the schema's tables are bound.
388
+ reportAtBoot(() => {
389
+ for (const gap of replayStoreBootGaps()) {
390
+ console.error(`[flair-replay] ReplayStoreUnavailable at boot (${gap}). Signed requests on this path are refused.`);
391
+ }
392
+ });
393
+ /**
394
+ * Every gap that would refuse a request through `store` on this thread, each
395
+ * labelled with the store's name, or an empty list.
396
+ */
397
+ export function replayStoreStoreGaps(store) {
398
+ const gap = storeRetentionGap(store.deps(), store.minRetentionMs, store.retentionBasis);
399
+ return gap ? [`${store.label}: ${gap}`] : [];
400
+ }
401
+ /**
402
+ * Print `store`'s gaps once per worker thread at boot, beside the replay
403
+ * guards' (`replayStoreBootGaps`): a misconfigured table is named before the
404
+ * first request instead of on the first claim. Call it at module load, from the
405
+ * module that owns the store, while Harper awaits that resource import.
406
+ */
407
+ export function reportReplayStoreGapsAtBoot(store) {
408
+ reportAtBoot(() => {
409
+ for (const gap of replayStoreStoreGaps(store)) {
410
+ console.error(`[flair-replay] ReplayStoreUnavailable at boot (${gap}). Requests through that store are refused until it is usable (see resources/replay-store.ts).`);
334
411
  }
335
- }, 0);
412
+ });
336
413
  }
@@ -0,0 +1,163 @@
1
+ /**
2
+ * request-target.ts — the raw request target the auth middleware decides on.
3
+ *
4
+ * Before any other request processing, the middleware answers a target that is not in
5
+ * canonical form with a named 400 (`non_canonical_request_target`). A raw
6
+ * target is canonical unless its path (the part before the first `?`) has:
7
+ *
8
+ * - a `.` or `..` segment, raw or percent-encoded as a whole segment
9
+ * (`%2e`, `%2E%2e`, `.%2e`, …);
10
+ * - repeated slashes (`//`) anywhere in the path;
11
+ * - a raw backslash.
12
+ *
13
+ * Everything else is canonical, including `%2F` and `%5C` inside a segment, a
14
+ * dot inside a segment (`a.b`), and any query string.
15
+ *
16
+ * PURE: no imports and no I/O; the comparisons use the global `URL`.
17
+ */
18
+ /** The named error a non-canonical request target is refused with. */
19
+ export const NON_CANONICAL_REQUEST_TARGET_ERROR = "non_canonical_request_target";
20
+ /** A whole segment that is `.` or `..`, each dot raw or percent-encoded. */
21
+ const DOT_SEGMENT = /^(?:\.|%2e){1,2}$/i;
22
+ /**
23
+ * The path part of a raw request target: everything before the first `?`.
24
+ */
25
+ export function requestPath(rawTarget) {
26
+ const q = rawTarget.indexOf("?");
27
+ return q === -1 ? rawTarget : rawTarget.slice(0, q);
28
+ }
29
+ /** The query part of a raw request target: everything after the first `?` ("" when none). */
30
+ export function requestQuery(rawTarget) {
31
+ const q = rawTarget.indexOf("?");
32
+ return q === -1 ? "" : rawTarget.slice(q + 1);
33
+ }
34
+ /** True when the serialized WHATWG `pathname + search` equals `rawTarget`. */
35
+ export function whatwgUrlMatchesRawTarget(rawTarget) {
36
+ let url;
37
+ try {
38
+ url = new URL(rawTarget, "http://localhost");
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ return url.pathname + url.search === rawTarget;
44
+ }
45
+ /** True when the serialized WHATWG `search` without its leading `?` equals `requestQuery(rawTarget)`. */
46
+ export function whatwgQueryMatchesRawTarget(rawTarget) {
47
+ let url;
48
+ try {
49
+ url = new URL(rawTarget, "http://localhost");
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ return url.search.slice(1) === requestQuery(rawTarget);
55
+ }
56
+ /** True when a raw request target is in canonical form (see the module header). */
57
+ export function isCanonicalRequestTarget(rawTarget) {
58
+ const path = requestPath(rawTarget);
59
+ if (path.includes("\\"))
60
+ return false;
61
+ if (path.includes("//"))
62
+ return false;
63
+ return !path.split("/").some((segment) => DOT_SEGMENT.test(segment));
64
+ }
65
+ /** The named 400 for a non-canonical request target. HEAD gets no body. */
66
+ export function nonCanonicalRequestTargetRefusal(method) {
67
+ const body = JSON.stringify({
68
+ error: NON_CANONICAL_REQUEST_TARGET_ERROR,
69
+ message: "the request target must be in canonical form: no '.' or '..' path segment, no repeated slashes (`//`), and no backslash",
70
+ });
71
+ return new Response(method === "HEAD" ? null : body, {
72
+ status: 400,
73
+ headers: { "content-type": "application/json" },
74
+ });
75
+ }
76
+ /**
77
+ * The raw path's segments, split on `/` FIRST and still percent-encoded.
78
+ * Empty segments are dropped.
79
+ */
80
+ export function rawPathSegments(path) {
81
+ return path.split("/").filter(Boolean);
82
+ }
83
+ /** The last raw segment of a path (still percent-encoded). */
84
+ export function lastRawPathSegment(path) {
85
+ return path.slice(path.lastIndexOf("/") + 1);
86
+ }
87
+ /** Decode one raw path segment; null when it is not valid percent-encoding. */
88
+ export function decodePathSegment(segment) {
89
+ try {
90
+ return decodeURIComponent(segment);
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ }
96
+ /**
97
+ * For a plain one-level resource path, return the first segment and the
98
+ * still-encoded remainder after it, removing one leading slash.
99
+ */
100
+ export function routedResourceAndRemainder(path) {
101
+ const p = path.startsWith("/") ? path.slice(1) : path;
102
+ const slash = p.indexOf("/");
103
+ if (slash === -1)
104
+ return { resource: p, remainder: "" };
105
+ return { resource: p.slice(0, slash), remainder: p.slice(slash + 1) };
106
+ }
107
+ /**
108
+ * Return the resource segment and fully decoded remainder (the initial
109
+ * RequestTarget id for a plain one-level resource path). `parsePath` can change
110
+ * the final row id. Null for an empty, trailing-slash or malformed remainder.
111
+ */
112
+ export function routedRecordId(path) {
113
+ const { resource, remainder } = routedResourceAndRemainder(path);
114
+ if (remainder === "" || remainder.endsWith("/"))
115
+ return null;
116
+ let id;
117
+ try {
118
+ id = decodeURIComponent(remainder);
119
+ }
120
+ catch {
121
+ return null;
122
+ }
123
+ if (id === "")
124
+ return null;
125
+ return { resource, id };
126
+ }
127
+ /**
128
+ * Return the prefix before the first dot when its suffix is in
129
+ * `declaredAttributes`; otherwise return the id unchanged.
130
+ */
131
+ export function routedIdAfterPropertyRule(id, declaredAttributes) {
132
+ const dot = id.indexOf(".");
133
+ if (dot > -1 && declaredAttributes.has(id.slice(dot + 1)))
134
+ return id.slice(0, dot);
135
+ return id;
136
+ }
137
+ /**
138
+ * Return the first nonempty segment if `isKnown` accepts it, otherwise its
139
+ * prefix before the first dot if accepted, otherwise the segment unchanged.
140
+ */
141
+ export function routedFirstResourceName(path, isKnown) {
142
+ const seg = rawPathSegments(path)[0] ?? "";
143
+ if (isKnown(seg))
144
+ return seg;
145
+ const dot = seg.indexOf(".");
146
+ if (dot > -1 && isKnown(seg.slice(0, dot)))
147
+ return seg.slice(0, dot);
148
+ return seg;
149
+ }
150
+ /**
151
+ * For a path with one leading slash, return it with the first segment replaced
152
+ * by `routedFirstResourceName`; unchanged when that name does not change.
153
+ */
154
+ export function routedResourcePath(path, known) {
155
+ const segs = rawPathSegments(path);
156
+ const first = segs[0];
157
+ if (first === undefined)
158
+ return path;
159
+ const name = routedFirstResourceName(path, (n) => known.has(n));
160
+ if (name === first)
161
+ return path;
162
+ return `/${name}${path.slice(1 + first.length)}`;
163
+ }
@@ -1,3 +1,4 @@
1
+ import { currentWriteJournal } from "./write-journal-context.js";
1
2
  /**
2
3
  * request-transaction.ts — one shared write scope for the host-pointer path
3
4
  * (flair#1940 slice 1). A Memory row and its `MemoryHostSource` pointer row
@@ -54,7 +55,16 @@ export async function withSharedWriteTransaction(ctx, fn) {
54
55
  if (!txn) {
55
56
  throw new Error("flair: Harper's transaction() is unavailable — refusing to run a Memory/pointer write unwrapped (A7: no silent loss)");
56
57
  }
57
- return (await txn(shared, () => fn(shared)));
58
+ const journal = currentWriteJournal();
59
+ if (!journal)
60
+ return (await txn(shared, () => fn(shared)));
61
+ return journal.transaction(shared, (capture, complete) => txn(shared, async () => {
62
+ capture();
63
+ const result = await fn(shared);
64
+ journal.assertCoverage();
65
+ complete();
66
+ return result;
67
+ }));
58
68
  }
59
69
  /**
60
70
  * Run `fn` in a transaction this call OWNS even when `ctx` already carries an
@@ -76,3 +86,38 @@ export async function withOwnedTransaction(ctx, fn) {
76
86
  ctx.transaction = saved;
77
87
  }
78
88
  }
89
+ /** Marks a context whose OPEN write transaction belongs to an in-process
90
+ * caller that composes a Memory write into it. A Symbol, so no request body
91
+ * or header can set it. */
92
+ const COMPOSED_WRITE = Symbol("flair.composedMemoryWrite");
93
+ /**
94
+ * Run `fn` in a shared write transaction ({@link withSharedWriteTransaction})
95
+ * and mark `shared` for the duration, so `Memory.put()` JOINS this transaction
96
+ * instead of owning one (flair#2478 slice 1, part 1). The caller owns the
97
+ * commit: its own writes in `fn` commit or abort with the Memory row. Manual
98
+ * promotion uses it, so its Memory write and verdict stamp stay one
99
+ * transaction (flair#2354). The per-id write lock orders the put's read and
100
+ * decision against other owner PUT/PATCH writers of that id, but this
101
+ * transaction commits after the lock is released, so its commit is not
102
+ * serialized with theirs; writers that take no lock are not serialized at all.
103
+ */
104
+ export async function withComposedWriteTransaction(ctx, fn) {
105
+ return withSharedWriteTransaction(ctx, async (shared) => {
106
+ const had = Object.prototype.hasOwnProperty.call(shared, COMPOSED_WRITE);
107
+ const prior = shared[COMPOSED_WRITE];
108
+ shared[COMPOSED_WRITE] = true;
109
+ try {
110
+ return await fn(shared);
111
+ }
112
+ finally {
113
+ if (had)
114
+ shared[COMPOSED_WRITE] = prior;
115
+ else
116
+ delete shared[COMPOSED_WRITE];
117
+ }
118
+ });
119
+ }
120
+ /** Is `ctx` inside {@link withComposedWriteTransaction} with its transaction still open? */
121
+ export function composesCallerWrite(ctx) {
122
+ return !!ctx && ctx[COMPOSED_WRITE] === true && isJoinableTransaction(ctx);
123
+ }
@@ -28,6 +28,7 @@
28
28
  * search) is what clears `empty`.
29
29
  */
30
30
  import { bm25SearchLagReason } from "./bm25-status.js";
31
+ import { MEMORY_REEMBED_PATCH_CAPABILITY } from "../src/lib/reembed-server-support.js";
31
32
  /**
32
33
  * How a ready result was verified. Constant strings — no interpolation
33
34
  * (flair#1411). Public /Health still omits this field when searchReady is
@@ -117,8 +118,10 @@ export function buildPublicHealthBody(readiness, identity) {
117
118
  version: identity.version,
118
119
  buildCommit: identity.buildCommit,
119
120
  searchReady: readiness.searchReady,
121
+ // flair#2337: this build advertises the re-embed PATCH token.
122
+ // The shared constant aligns this build's CLI and server literals.
123
+ capabilities: [MEMORY_REEMBED_PATCH_CAPABILITY],
120
124
  };
121
- // Public shape is unchanged: searchReadyReason is still present iff !searchReady.
122
125
  // Ready-path verification constants stay on the decision object (flair#1411).
123
126
  if (!readiness.searchReady && readiness.searchReadyReason) {
124
127
  body.searchReadyReason = readiness.searchReadyReason;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * seed-ids.ts — the `using-flair` seed's fixed skill row id (flair#2141 S2).
3
+ *
4
+ * Pure, with no runtime import, so a unit test can read it without a Harper
5
+ * instance. resources/seed-reservation.ts reserves it; src/lib/skill-seed.ts
6
+ * writes it (its `SEED_SKILL_ID` must equal this value, and
7
+ * test/unit/skill-seed.test.ts pins that).
8
+ */
9
+ export const SEED_SKILL_ROW_ID = "skill:using-flair";
@@ -0,0 +1,116 @@
1
+ /**
2
+ * seed-reservation.ts — reserve the `using-flair` seed's fixed ids for the
3
+ * operator source (flair#2141 S2).
4
+ *
5
+ * Normal `flair init` seeds one skill row at a FIXED Memory id and one org
6
+ * assignment at a FIXED OrgSkillAssignment id that points at it. Re-initializing
7
+ * an already-installed default local instance with `flair init --skip-start`
8
+ * defers the seed until a later `flair start` that has the admin credential.
9
+ * Bootstrap may list the
10
+ * assignment for an active agent when it wins same-name conflict resolution,
11
+ * the agent has not opted out, and the entry fits its budget. The row behind
12
+ * that id must be the operator's. The rule:
13
+ *
14
+ * A create, PUT, PATCH or DELETE of the reserved Memory id needs the operator
15
+ * source: an authenticated Basic administrator, or a deliberate internal call
16
+ * (`soulWriteSource`, the same predicate that gates every OrgSkillAssignment
17
+ * write). Every other caller is refused, an agent key whose id equals the
18
+ * administrator's username and an admin agent key included.
19
+ *
20
+ * The decision reads the auth verdict and the request's credential class. It
21
+ * never compares the stored owner with the caller's id: an agent can hold the
22
+ * id the operator's rows are attributed to.
23
+ *
24
+ * The assignment id needs no entry here: every OrgSkillAssignment write
25
+ * already requires the operator source (resources/OrgSkillAssignment.ts), and
26
+ * test/unit/org-skill-assignment-writer-coverage.test.ts pins its writers.
27
+ *
28
+ * Where it applies: Memory post/put/patch/delete, the supersede target, and
29
+ * FeedMemories check caller-chosen ids before writing; federation skips a
30
+ * reserved id (`seed_id_not_federated`). Server bookkeeping is also allowed:
31
+ * lastReflected and embedding backfill update their selected fields. Usage
32
+ * recording can receive an agent-supplied id. The coverage test classifies raw Memory
33
+ * write sites detected by its supported source patterns; it does not prove
34
+ * that every possible write path is classified.
35
+ */
36
+ import { resolveAgentAuth } from "./agent-auth.js";
37
+ import { FORBIDDEN, UNAUTH } from "./record-type-kit.js";
38
+ import { soulWriteSource } from "./soul-write-policy.js";
39
+ import { SEED_SKILL_ROW_ID } from "./seed-ids.js";
40
+ export { SEED_SKILL_ROW_ID };
41
+ /** Table → ids reserved for the operator source, subject to documented bookkeeping writes. */
42
+ export const RESERVED_SEED_IDS = Object.freeze({
43
+ Memory: Object.freeze([SEED_SKILL_ROW_ID]),
44
+ });
45
+ /** Whether `id` is a reserved seed id on `table`. */
46
+ export function isReservedSeedId(table, id) {
47
+ if (typeof id !== "string" && typeof id !== "number")
48
+ return false;
49
+ return (RESERVED_SEED_IDS[table] ?? []).includes(String(id));
50
+ }
51
+ /** The ids a resource write names: the URL-bound id and any body id (one record or an array). */
52
+ export function writeTargetIds(resource, content) {
53
+ const ids = [];
54
+ try {
55
+ const getId = resource?.getId;
56
+ if (typeof getId === "function")
57
+ ids.push(getId.call(resource));
58
+ }
59
+ catch {
60
+ /* no bound id */
61
+ }
62
+ const records = Array.isArray(content) ? content : [content];
63
+ for (const record of records) {
64
+ if (record && typeof record === "object" && "id" in record)
65
+ ids.push(record.id);
66
+ }
67
+ return ids;
68
+ }
69
+ /**
70
+ * The decision: null when no id is reserved or the caller has operator
71
+ * authority; otherwise 401 (anonymous) or 403.
72
+ */
73
+ export function reservedSeedWriteDenial(table, ids, context, auth) {
74
+ const reserved = ids.find((id) => isReservedSeedId(table, id));
75
+ if (reserved === undefined)
76
+ return null;
77
+ if (auth.kind === "anonymous")
78
+ return UNAUTH();
79
+ if (soulWriteSource(context, auth))
80
+ return null;
81
+ return FORBIDDEN(`seed_id_reserved: ${table} ${JSON.stringify(String(reserved))} requires the operator source ` +
82
+ "(an authenticated Basic administrator or deliberate internal call)");
83
+ }
84
+ /** `reservedSeedWriteDenial`, resolving the auth verdict only when an id is reserved. */
85
+ export async function refuseReservedSeedWrite(table, ids, context) {
86
+ if (!ids.some((id) => isReservedSeedId(table, id)))
87
+ return null;
88
+ return reservedSeedWriteDenial(table, ids, context, await resolveAgentAuth(context));
89
+ }
90
+ /**
91
+ * The LINEAGE form of the reservation (flair#2139 S2). A skill update SUPERSEDES
92
+ * into a fresh physical Memory row that carries the stable logical
93
+ * `skillSubjectId` forward, so reserving the seed's physical id alone would let
94
+ * another caller enter the seed's lineage through a successor row whose own id
95
+ * is not the reserved one. This denies a write whose skill SUBJECT is reserved
96
+ * unless the caller has the operator source, exactly as the physical-id check
97
+ * does. `subjectIds` are the resolved logical subject ids the write targets.
98
+ */
99
+ export function reservedSeedSubjectDenial(table, subjectIds, context, auth) {
100
+ const reserved = subjectIds.find((id) => isReservedSeedId(table, id));
101
+ if (reserved === undefined)
102
+ return null;
103
+ if (auth.kind === "anonymous")
104
+ return UNAUTH();
105
+ if (soulWriteSource(context, auth))
106
+ return null;
107
+ return FORBIDDEN(`seed_subject_reserved: the ${table} ${JSON.stringify(String(reserved))} lineage requires the operator source ` +
108
+ "(an authenticated Basic administrator or deliberate internal call)");
109
+ }
110
+ export function reservedSeedFeedWriteDenial(table, ids) {
111
+ const reserved = ids.find((id) => id != null && isReservedSeedId(table, String(id)));
112
+ if (reserved === undefined)
113
+ return null;
114
+ return FORBIDDEN(`seed_id_reserved: ${table} ${JSON.stringify(String(reserved))} is written by the flair init seed; ` +
115
+ "the feed ingest does not write it");
116
+ }
@@ -63,6 +63,8 @@ import { buildBM25, fuseRrfNormalized, SEM_LIMIT } from "./bm25.js";
63
63
  import { isAllowedBm25Candidate } from "./bm25-filter.js";
64
64
  import { indexedBm25Ids } from "./bm25-index-service.js";
65
65
  import { byRecencyThenId } from "./sort-comparators.js";
66
+ import { isTrustedVectorStamp, trustedVectorCondition } from "./embedding-space-guard.js";
67
+ import { applyPromotionBinding } from "./promotion-binding.js";
66
68
  /**
67
69
  * The only way a row enters the ranked pool. `_rank` is a required
68
70
  * argument — not an object property that `...any` can swallow — so a
@@ -97,7 +99,7 @@ function distanceToSimilarity(distance) {
97
99
  // a permitted reader would never see their pointer.
98
100
  export const DEFAULT_SELECT = ["id", "agentId", "content", "contentHash", "visibility", "instanceToken", "tags", "durability",
99
101
  "source", "createdAt", "updatedAt", "expiresAt", "retrievalCount", "usageCount", "lastRetrieved",
100
- "promotionStatus", "promotedAt", "promotedBy", "archived", "archivedAt", "archivedBy",
102
+ "promotionStatus", "promotedAt", "promotedBy", "promotionContentHash", "archived", "archivedAt", "archivedBy",
101
103
  "parentId", "derivedFrom", "sessionId", "lastReflected", "supersedes", "subject", "summary",
102
104
  "validFrom", "validTo", "_safetyFlags"];
103
105
  export async function retrieveCandidates(params) {
@@ -131,8 +133,14 @@ export async function retrieveCandidates(params) {
131
133
  select: hnswSelect,
132
134
  limit,
133
135
  };
134
- if (conditions.length > 0)
135
- semQuery.conditions = conditions;
136
+ // flair#2573 slice 1: defence in depth on the vector leg. The guard's
137
+ // verdict is the load-bearing exclusion — a non-uniform verdict makes the
138
+ // caller drop the query embedding. This condition is added to the HNSW
139
+ // query alone — never to `conditions`, which the lexical leg shares (a row
140
+ // with an untrusted stamp remains eligible for lexical matching). A query
141
+ // condition cannot keep a vector out of Harper's HNSW traversal; it only
142
+ // excludes the row from the returned set.
143
+ semQuery.conditions = [...conditions, trustedVectorCondition()];
136
144
  const semResults = withDetachedTxn(ctx, () => databases.flair.Memory.search(semQuery));
137
145
  for await (const record of semResults) {
138
146
  if (record.expiresAt && Date.parse(record.expiresAt) < Date.now())
@@ -269,7 +277,8 @@ export async function retrieveCandidates(params) {
269
277
  if (key in full)
270
278
  projected[key] = full[key];
271
279
  allowedById.set(id, projected);
272
- if (qEmb) {
280
+ // A trusted stamp permits cosine scoring; an absent vector scores zero.
281
+ if (qEmb && isTrustedVectorStamp(full.embeddingModel)) {
273
282
  const storedEmbedding = Array.isArray(full.embedding) ? full.embedding : [];
274
283
  semSimById.set(id, cosineSimilarity(qEmb, storedEmbedding));
275
284
  }
@@ -289,7 +298,7 @@ export async function retrieveCandidates(params) {
289
298
  const isFlagged = record._safetyFlags && Array.isArray(record._safetyFlags) && record._safetyFlags.length > 0;
290
299
  const source = record.agentId !== agentId ? record.agentId : undefined;
291
300
  pushRanked(results, {
292
- ...record,
301
+ ...applyPromotionBinding(record),
293
302
  content: isFlagged ? wrapUntrusted(record.content, source) : record.content,
294
303
  _score: Math.round(finalScore * 1000) / 1000,
295
304
  _rawScore: scoring !== "raw" ? Math.round(rawScore * 1000) / 1000 : undefined,
@@ -328,9 +337,12 @@ export async function retrieveCandidates(params) {
328
337
  let semSim = semSimById.get(id);
329
338
  if (semSim === undefined && qEmb) {
330
339
  const full = await withDetachedTxn(ctx, () => databases.flair.Memory.get(id));
331
- const storedEmbedding = Array.isArray(full?.embedding) ? full.embedding : [];
332
- semSim = cosineSimilarity(qEmb, storedEmbedding);
333
- semSimById.set(id, semSim);
340
+ // A trusted stamp permits cosine scoring; an absent vector scores zero.
341
+ if (isTrustedVectorStamp(full?.embeddingModel)) {
342
+ const storedEmbedding = Array.isArray(full?.embedding) ? full.embedding : [];
343
+ semSim = cosineSimilarity(qEmb, storedEmbedding);
344
+ semSimById.set(id, semSim);
345
+ }
334
346
  }
335
347
  let keywordHit = false;
336
348
  if (q && String(record.content || "").toLowerCase().includes(String(q).toLowerCase())) {
@@ -346,7 +358,7 @@ export async function retrieveCandidates(params) {
346
358
  // composite mode (composite ordering is unchanged by #985 — its
347
359
  // rrfRaw input and result order are exactly the pre-#985 behavior).
348
360
  pushRanked(results, {
349
- ...record,
361
+ ...applyPromotionBinding(record),
350
362
  content: isFlagged ? wrapUntrusted(record.content, source) : record.content,
351
363
  _score: Math.round(finalScore * 1000) / 1000,
352
364
  _rawScore: scoring !== "raw" ? Math.round(rawScore * 1000) / 1000 : undefined,
@@ -447,7 +459,7 @@ export async function retrieveCandidates(params) {
447
459
  const isFlagged = record._safetyFlags && Array.isArray(record._safetyFlags) && record._safetyFlags.length > 0;
448
460
  const source = record.agentId !== agentId ? record.agentId : undefined;
449
461
  pushRanked(results, {
450
- ...record,
462
+ ...applyPromotionBinding(record),
451
463
  content: isFlagged ? wrapUntrusted(record.content, source) : record.content,
452
464
  _score: Math.round(finalScore * 1000) / 1000,
453
465
  _rawScore: scoring !== "raw" ? Math.round(rawScore * 1000) / 1000 : undefined,
@@ -463,10 +475,10 @@ export async function retrieveCandidates(params) {
463
475
  sort: { attribute: "embedding", target: qEmb, distance: "cosine" },
464
476
  select: hnswSelect,
465
477
  limit,
478
+ // flair#2573 slice 1: defence in depth on the vector leg (see the hybrid
479
+ // sem leg above); the guard's verdict is the load-bearing exclusion.
480
+ conditions: [...conditions, trustedVectorCondition()],
466
481
  };
467
- if (conditions.length > 0) {
468
- query.conditions = conditions;
469
- }
470
482
  const memoryResults = withDetachedTxn(ctx, () => databases.flair.Memory.search(query));
471
483
  for await (const record of memoryResults) {
472
484
  if (record.expiresAt && Date.parse(record.expiresAt) < Date.now())
@@ -514,7 +526,7 @@ export async function retrieveCandidates(params) {
514
526
  // bump) is the abstention confidence signal on this legacy/bootstrap
515
527
  // (HNSW-leg-only) path.
516
528
  pushRanked(results, {
517
- ...rest,
529
+ ...applyPromotionBinding(rest),
518
530
  content: isFlagged ? wrapUntrusted(rest.content, source) : rest.content,
519
531
  _score: Math.round(finalScore * 1000) / 1000,
520
532
  _rawScore: scoring !== "raw" ? Math.round(rawScore * 1000) / 1000 : undefined,
@@ -560,7 +572,7 @@ export async function retrieveCandidates(params) {
560
572
  const isFlagged = rest._safetyFlags && Array.isArray(rest._safetyFlags) && rest._safetyFlags.length > 0;
561
573
  const source = record.agentId !== agentId ? record.agentId : undefined;
562
574
  pushRanked(results, {
563
- ...rest,
575
+ ...applyPromotionBinding(rest),
564
576
  content: isFlagged ? wrapUntrusted(rest.content, source) : rest.content,
565
577
  _score: Math.round(finalScore * 1000) / 1000,
566
578
  _rawScore: scoring !== "raw" ? Math.round(rawScore * 1000) / 1000 : undefined,