@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
@@ -28,9 +28,24 @@
28
28
  * runner loops until processed=0 — and a re-run is idempotent.
29
29
  *
30
30
  * Reuses Memory's OWN regen branch — never duplicates embedding logic —
31
- * via the SAME mechanism `flair reembed` (src/cli.ts) already uses in
32
- * production: a genuine `PUT /Memory/:id` HTTP request (admin-authenticated
31
+ * via a genuine `PATCH /Memory/:id` HTTP request (admin-authenticated
33
32
  * loopback), not an in-process call on `databases.flair.Memory` directly.
33
+ * The one exception is a row whose id ends in `.content`, which that request
34
+ * cannot address (see regenContentSuffixRow below).
35
+ *
36
+ * The request is the re-embed PATCH (flair#2296): body
37
+ * `{"embedding": null, "embeddingModel": null}`. Memory.patch() embeds the row
38
+ * the PATCH handler reads and writes `embedding`, `embeddingModel`, `updatedAt`
39
+ * and `embeddedContentHash` (and `instanceToken` on a legacy row that has none).
40
+ * Edits committed after this migration's read and before the PATCH handler's
41
+ * stored-row read are kept (flair#2275); the handler reads, embeds and commits
42
+ * under the id's per-id write lock (flair#2478, below). A text change by a
43
+ * writer outside that lock is detected only up to and including the request's
44
+ * final post-commit read-back: seen at an attempt's fresh read it is
45
+ * re-embedded; seen at the confirmation or a read-back, the attempt retries
46
+ * within its bound or the request refuses, as Memory.patch documents. A
47
+ * lock-bypassing write committed after that final read-back is not detected by
48
+ * this request.
34
49
  *
35
50
  * THIS IS LOAD-BEARING, confirmed empirically while building
36
51
  * test/integration/migrations-embedding-stamp-e2e.test.ts against real
@@ -42,27 +57,23 @@
42
57
  * for a genuine `/Memory` request. Calling `.put()` on the raw reference
43
58
  * writes the record fine (confirmed: fields land exactly as passed) but
44
59
  * silently skips every override in resources/Memory.ts, INCLUDING the
45
- * `if (content.content && !content.embedding) { regenerate } ` branch this
46
- * migration exists to trigger. Reads (`.search()`/`.get()`, used below for
47
- * detect/countPending/candidate-selection) are unaffected by this — only
48
- * `.put()` needs the real dispatch, hence the loopback HTTP call for
49
- * exactly that one step.
60
+ * re-embed branch this migration exists to trigger. Reads
61
+ * (`.search()`/`.get()`, used below for detect/countPending/candidate-selection)
62
+ * are unaffected by this — only the re-embed request needs the real dispatch,
63
+ * hence the loopback HTTP call for exactly that one step.
50
64
  *
51
65
  * Query correctness (also verified against real Harper): Harper's
52
66
  * `not_equal` comparator only matches rows where the attribute holds an
53
67
  * EXPLICIT value (including explicit `null`) — a row where the attribute
54
68
  * was NEVER SET AT ALL (`getIndexedValues()` returns `undefined` for a
55
69
  * truly-absent property, never indexed regardless of `indexNulls`) is
56
- * invisible to ANY condition-based query, not just `not_equal`. Clearing to
57
- * `null` (never `undefined`) on write is therefore load-bearing: if the
58
- * regen HTTP call fails (engine not yet warmed up, transient failure,
59
- * admin credential unavailable this cycle), the row must land back in an
60
- * EXPLICIT-null state — queryable and retried on the next boot — never a
61
- * truly-absent one that would be permanently invisible to this migration
62
- * again. The pending condition is an OR of `not_equal <current>` (catches a
63
- * stale non-null model string) and `equals null` (catches that
64
- * explicit-null state) — together they catch every state this migration's
65
- * OWN writes can ever produce. A row whose `embeddingModel` was NEVER
70
+ * invisible to ANY condition-based query, not just `not_equal`. A re-embed
71
+ * request that fails (engine not yet warmed up, transient failure, admin
72
+ * credential unavailable this cycle) is retried on a later cycle while the row
73
+ * still matches the pending condition.
74
+ * The pending condition is an OR of `not_equal <current>` (catches a
75
+ * stale non-null model string) and `equals null` (catches an explicit-null
76
+ * state). A row whose `embeddingModel` was NEVER
66
77
  * touched by anything (truly absent from its very first write — only
67
78
  * possible if the embeddings engine was down for that entire write) is a
68
79
  * known, narrow gap this bounded query cannot see;
@@ -103,15 +114,16 @@
103
114
  * negated comparator — no analogous bypass exists or is needed; its
104
115
  * behavior was already verified against real Harper per the doc above).
105
116
  *
106
- * `recheckPending()` below is a SEPARATE, generic defense-in-depth layer
107
- * (wired into resources/migrations/runner.ts's completion gate) — even a
108
- * migration whose countPending() query is airtight can be defeated by some
109
- * OTHER, not-yet-understood counting artifact; this lets the runner PROVE
110
- * (via `.get()`, a primary-key lookup — always live, never index-assisted)
111
- * that a nonzero countPending() result is real before halting on it.
117
+ * NO `recheckPending()` (the runner's flair#807 completion-gate safety net,
118
+ * resources/migrations/runner.ts) since flair#2465. `countPending()` now scans
119
+ * every row's live value instead of querying an index, so there is no index
120
+ * artifact for that net to excuse. A recheck that re-derived its candidates
121
+ * from the `staleCondition()` query could also sample rows other than the ones
122
+ * the scan counted (a row pending only on its stored hash is invisible to that
123
+ * query) and pass the gate with that row still pending.
112
124
  *
113
125
  * ROOT-CAUSE GUARD — recall graph correctness (recall-hnsw-graph-heal).
114
- * This migration RE-EMBEDS rows in BULK via `PUT /Memory/:id` — it replaces
126
+ * This migration RE-EMBEDS rows in BULK via `PATCH /Memory/:id` — it replaces
115
127
  * the stored vector of many rows in place. Historically, an OLDER (pre-fix)
116
128
  * Harper's INCREMENTAL HNSW update left stale/asymmetric reverse edges under
117
129
  * exactly this kind of bulk re-embed (order-dependent), which collapsed prod
@@ -132,18 +144,101 @@
132
144
  * engine is rebuilt on the upgrade boot (observed/ledgered by
133
145
  * resources/migrations/graph-heal.ts). Before enabling any FUTURE bulk
134
146
  * re-embed, ship a structural reindex trigger with it.
147
+ *
148
+ * flair#2465 part 2 — the stored text hash. A re-embed can still store the
149
+ * vector for the text it read when a text edit commits after that read and
150
+ * before the commit (Harper has no compare-and-set; the field-only write and the
151
+ * committed-row confirm are checked again by the post-commit verification, which
152
+ * retries from a fresh read). To catch the rows an earlier edit leaves behind,
153
+ * the server stores a newly computed
154
+ * `embeddedContentHash` (resources/memory-embed-hash.ts) when it computes a
155
+ * vector on a guarded path for a row with a non-empty owner, and this migration
156
+ * re-queues a row whose stored hash differs from the expected hash of its
157
+ * current embedding text. No query can compute that expected hash (a condition
158
+ * compares a stored value to a constant), so finding a mismatch takes a LIVE
159
+ * SCAN: `detect` runs the `staleCondition()` query first and scans only when
160
+ * the query finds nothing; `countPending` and `run` scan the whole table
161
+ * directly, applying `rowEmbeddingCurrent` per row. A row with no stored hash
162
+ * (e.g. written before this change, created with a vector accepted from the
163
+ * caller, or with an empty owner) bypasses only the hash comparison: it is
164
+ * current when its model is current-space. A rule that queued every missing hash
165
+ * would queue every legacy row at upgrade, and could leave pending a row that
166
+ * cannot get a hash (one with an empty owner); a missing hash skips the
167
+ * comparison instead.
168
+ *
169
+ * flair#2478 slice 3 — the per-id Memory write lock. Both write paths write
170
+ * under the id's lock shared with the owner verbs (resources/memory-write-lock.ts).
171
+ * The HTTP delegation's `PATCH /Memory/:id` takes it in Memory.patch (phase
172
+ * `patch-reembed`) with the owner budget; a refusal (`503 memory_busy`,
173
+ * `write_outcome_unknown`, `memory_provider_timeout`) is logged and leaves the
174
+ * row uncounted; the next scan decides whether it is still stale (an owner write
175
+ * can make it current meanwhile). Under the lock that PATCH re-reads the
176
+ * committed row and embeds its stored text, so an owner edit committed after
177
+ * this migration's read is the row it re-embeds; it writes only the embedding
178
+ * fields (and gives a legacy row with no `instanceToken` one) and commits before
179
+ * the lock is released. The `.content`-suffix fallback computes its vector
180
+ * first, then takes the id's lock (phase `embedding-stamp-content-suffix`) with
181
+ * one non-waiting acquisition per attempt; a retry acquires it again. On a
182
+ * held id, an id with an unresolved write outcome, or a store with no lock,
183
+ * that attempt writes nothing and is logged, and the row is left uncounted;
184
+ * the next scan decides whether it is still stale. After an earlier attempt
185
+ * for the same row committed unconfirmed, that line says the outcome is
186
+ * unknown, and the unconfirmed outcome is logged as well. Under the lock it re-reads the committed row, writes only when
187
+ * that row is the one it embedded, and commits and verifies the committed row
188
+ * before the release. A row changed at that in-lock read, or a change visible
189
+ * at the confirmation (which aborts the transaction), writes nothing and leaves
190
+ * the row uncounted. A readable read-back mismatch retries with a fresh read, a
191
+ * vector computed before the lock and a new acquisition, at most
192
+ * CONTENT_SUFFIX_REGEN_ATTEMPTS (3) attempts; an unreadable read-back, or the
193
+ * attempts exhausted, is logged as unconfirmed and leaves the row uncounted
194
+ * for the next scan. A retry after an unconfirmed attempt compares the row's
195
+ * stored vector with the vector that attempt staged (within a relative
196
+ * tolerance that accepts a float32 copy of an in-range component; a non-finite
197
+ * component never matches), not the stored text hash (null for a row with an
198
+ * empty owner): a match beside a changed text is not treated as current, so the
199
+ * retry re-embeds the current text. A row whose stamp is not current or whose
200
+ * stored hash does not match its text is re-embedded whatever vector it holds; the
201
+ * staged-vector comparison only decides, on a retry, whether a row that
202
+ * otherwise counts as current (a null hash passes for any text) is re-embedded.
135
203
  */
136
204
  import { databases } from "harper";
137
- import { getModelId } from "../embeddings-provider.js";
205
+ import { appendFileSync } from "node:fs";
206
+ import { join } from "node:path";
207
+ import { isDeepStrictEqual } from "node:util";
208
+ import { confirmCommittedRow, verifyCommittedFields } from "../write-back.js";
209
+ import { withMemoryWriteLockOnce } from "../memory-write-lock.js";
210
+ import { getEmbedding, getModelId } from "../embeddings-provider.js";
211
+ import { withOwnedTransaction } from "../request-transaction.js";
212
+ import { txnPausePoint } from "../txn-pause-point.js";
138
213
  import { harperPortValue } from "../../src/lib/harper-port-value.js";
139
214
  import { DEFAULT_HTTP_PORT } from "../a2a-url.js";
140
215
  import { currentSpaceRawForms, isCurrentSpaceStamp } from "../embedding-space-guard.js";
216
+ import { BatchOutcomeError } from "./types.js";
141
217
  import { EMBEDDING_STAMP_ID } from "./stamp-outstanding.js";
218
+ import { endsWithContentSelectorSuffix } from "../../src/lib/memory-id-policy.js";
219
+ import { skillEmbedText } from "../skill-write.js";
220
+ import { embeddedHashMatches, embeddedTextHash, holdsOwnStaleVector } from "../memory-embed-hash.js";
142
221
  export { EMBEDDING_STAMP_ID };
143
222
  function defaultMemoryTable() {
144
223
  return databases.flair.Memory;
145
224
  }
146
225
  const REGEN_HTTP_TIMEOUT_MS = 20_000; // a real embedding compute can be slow on constrained hardware
226
+ /** Attempt bound for a `.content`-suffix re-embed. */
227
+ const CONTENT_SUFFIX_REGEN_ATTEMPTS = 3;
228
+ /** Test-only: record each run's result when fault injection is armed. */
229
+ function noteTestMigrationRun(result) {
230
+ if (process.env.FLAIR_ENABLE_TEST_FAULT_INJECTION !== "1")
231
+ return;
232
+ const dir = process.env.FLAIR_TEST_PAUSE_DIR;
233
+ if (!dir)
234
+ return;
235
+ try {
236
+ appendFileSync(join(dir, "embedding-stamp-runs.jsonl"), `${JSON.stringify(result)}\n`);
237
+ }
238
+ catch {
239
+ // Append errors are ignored.
240
+ }
241
+ }
147
242
  /** Same admin-password resolution as resources/auth-middleware.ts's getAdminPass(). */
148
243
  function resolveAdminAuthHeader() {
149
244
  const pass = process.env.HDB_ADMIN_PASSWORD ?? process.env.FLAIR_ADMIN_PASSWORD;
@@ -155,13 +250,13 @@ function resolveAdminAuthHeader() {
155
250
  * Base URL for the loopback self-call that regenerates an embedding.
156
251
  *
157
252
  * ALWAYS loopback. This is the destination of a credentialed self-call —
158
- * `regenViaHttpPut` sends `Authorization: Basic` carrying the admin password to
253
+ * `regenViaHttpPatch` sends `Authorization: Basic` carrying the admin password to
159
254
  * it — so it must never leave the box. `FLAIR_PUBLIC_URL` names a remote /
160
255
  * reverse-proxied origin and is deliberately ignored here, matching
161
256
  * `a2a-url.localBaseUrl` ("never the public/proxy URL"): two self-call
162
257
  * resolvers, both pinned to loopback. The public-facing resolvers (e.g.
163
- * oauth-discovery, AdminInstance, XAA; also a2a-url.resolvePublicBaseUrl and
164
- * the MCP issuer resolvers) honour `FLAIR_PUBLIC_URL` precisely because their
258
+ * oauth-discovery, AdminInstance, XAA and a2a-url.resolvePublicBaseUrl)
259
+ * honour `FLAIR_PUBLIC_URL` precisely because their
165
260
  * output is meant to be reachable off-box; this one's output is not. That list
166
261
  * is illustrative, not exhaustive — the deciding question is whether the URL
167
262
  * leaves the box, not a roster of call sites.
@@ -183,29 +278,206 @@ export function resolveSelfBaseUrl(env = process.env) {
183
278
  return `http://127.0.0.1:${harperPortValue(env.HTTP_PORT) ?? DEFAULT_HTTP_PORT}`;
184
279
  }
185
280
  /**
186
- * Triggers Memory.put()'s regen branch via a genuine loopback HTTP PUT —
187
- * the ONLY reliable way to reach resources/Memory.ts's subclass logic (see
188
- * module doc). Returns true iff the request succeeded (2xx); NEVER throws
189
- * — a failure just leaves the row in its current (queryable, explicit-null
190
- * or stale-string) state for the next attempt.
281
+ * Triggers Memory.patch()'s re-embed branch via a genuine loopback HTTP
282
+ * PATCH — the ONLY reliable way to reach resources/Memory.ts's subclass logic
283
+ * (see module doc). The body names only the two embedding fields, never the
284
+ * row this migration read. Returns true iff the request succeeded (2xx); a
285
+ * 503 `write_outcome_unknown` answers `{ ok: false, unconfirmed: true }`;
286
+ * NEVER throws — a false outcome is re-checked on the next batch or cycle.
191
287
  */
192
- async function regenViaHttpPut(id, existing, fetchImpl) {
288
+ async function regenViaHttpPatch(id, fetchImpl) {
193
289
  const authHeader = resolveAdminAuthHeader();
194
290
  if (!authHeader)
195
291
  return false; // no admin credential available this cycle — retried next boot
196
292
  try {
197
293
  const res = await fetchImpl(`${resolveSelfBaseUrl()}/Memory/${encodeURIComponent(id)}`, {
198
- method: "PUT",
294
+ method: "PATCH",
199
295
  headers: { "Content-Type": "application/json", Authorization: authHeader },
200
- body: JSON.stringify({ ...existing, embedding: null, embeddingModel: null }),
296
+ body: JSON.stringify({ embedding: null, embeddingModel: null }),
201
297
  signal: AbortSignal.timeout(REGEN_HTTP_TIMEOUT_MS),
202
298
  });
299
+ if (res.status === 503) {
300
+ const code = await logRegenRefusal(id, res);
301
+ // The id has an unresolved write, which may have committed: report it by
302
+ // id as unconfirmed (flair#2840).
303
+ if (code === "write_outcome_unknown")
304
+ return { ok: false, unconfirmed: true };
305
+ }
203
306
  return res.ok;
204
307
  }
205
308
  catch {
206
309
  return false;
207
310
  }
208
311
  }
312
+ /** A 503 from the re-embed request (flair#2478). `memory_busy` (the id stayed
313
+ * held through the request's wait budget) and `memory_provider_timeout` (the
314
+ * locked-provider bound) mean the request wrote nothing: a provider timeout
315
+ * after an earlier attempt of the same request committed unconfirmed answers
316
+ * `write_outcome_unknown` instead. `write_outcome_unknown` means the id has an
317
+ * unresolved write, which can be this request's own re-embed (a committed row
318
+ * it could not read back, or one whose read-back did not show the write, or a
319
+ * step after a commit that failed before any read-back), so that write may have
320
+ * committed. The row is uncounted; the next scan decides whether it is still
321
+ * stale. Returns the refusal's code (or `unnamed`). */
322
+ async function logRegenRefusal(id, res) {
323
+ let code = "unnamed";
324
+ try {
325
+ const body = (await res.json());
326
+ if (typeof body?.error === "string")
327
+ code = body.error;
328
+ }
329
+ catch {
330
+ // An unreadable refusal body is logged as unnamed.
331
+ }
332
+ console.warn("[embedding-stamp] %s: the re-embed request was refused 503 %s; the row is uncounted and the next scan decides whether it is still stale", id, code);
333
+ return code;
334
+ }
335
+ /** A vector this migration may stamp as current: a non-empty array of finite numbers. */
336
+ function isUsableEmbedding(value) {
337
+ return Array.isArray(value) && value.length > 0 && value.every((n) => typeof n === "number" && Number.isFinite(n));
338
+ }
339
+ /**
340
+ * Is this row's stored embedding current? Current means BOTH its
341
+ * `embeddingModel` is a current-space stamp for `currentModelId` AND either it
342
+ * stores no `embeddedContentHash` or the stored hash equals the expected hash of
343
+ * the row's current embedding text (`memory-embed-hash.ts`). No query can
344
+ * compute that expected hash, so a caller that needs to find a hash mismatch
345
+ * must scan (see each method below).
346
+ */
347
+ function rowEmbeddingCurrent(row, currentModelId) {
348
+ return isCurrentSpaceStamp(row.embeddingModel, currentModelId) &&
349
+ embeddedHashMatches(row);
350
+ }
351
+ /** The Memory table's primary store, whose per-id lock the owner verbs take. */
352
+ function defaultMemoryLockStore() {
353
+ return defaultMemoryTable().primaryStore;
354
+ }
355
+ const defaultContentSuffixRegenDeps = {
356
+ embed: (text) => getEmbedding(text, "document"),
357
+ inTransaction: (fn) => withOwnedTransaction(undefined, fn),
358
+ lockStore: defaultMemoryLockStore,
359
+ };
360
+ /**
361
+ * Re-embed a legacy row whose id ends in the `.content` property suffix. The
362
+ * loopback `PATCH /Memory/:id` the regen path uses cannot address such an id
363
+ * (Harper's REST by-id path reads the suffix as a selector, and the write path
364
+ * refuses the id), so this computes the embedding itself and writes through the
365
+ * raw table handle.
366
+ *
367
+ * The text embedded is the one Memory's own write paths embed for the row
368
+ * (`skillEmbedText`: a skill row's `trigger` when present, else `content`); a
369
+ * row with no such text is not embedded.
370
+ *
371
+ * The vector is computed BEFORE the id's per-id write lock is taken
372
+ * (flair#2478): no provider call runs while the id is locked. Each call of this
373
+ * function is one attempt and tries the lock once, without waiting (the
374
+ * caller's retry calls it again); a held id, an unresolved-outcome marker or a store with no lock answers
375
+ * `lock` and writes nothing. Holding it, the attempt re-reads the committed row:
376
+ * a row that is not the one the vector was computed for (gone, or any field
377
+ * changed) is `skipped` and nothing is written; a later scan decides whether
378
+ * it is still stale, and if so computes again.
379
+ *
380
+ * Writes a usable vector in an owned transaction. It STAGES an incremental
381
+ * `update` of only `embedding`, `embeddingModel`, `updatedAt` and
382
+ * `embeddedContentHash` — the field-only write Memory's own re-embed branch
383
+ * uses (flair#2465), never a full-row put — and the write touches no other field
384
+ * of the committed row. (Memory's re-embed branch also gives a legacy row with
385
+ * no `instanceToken` one, flair#2478; this fallback writes no token.)
386
+ * Then it CONFIRMS the committed row (an explicit fresh context) is still the
387
+ * row this transaction read and embedded; a row gone or distinguishably changed
388
+ * at confirmation aborts the owned transaction (`skipped`, nothing written).
389
+ *
390
+ * The post-commit read detects surviving differences in compared fields,
391
+ * identity or embedding text. The confirmation compares the WHOLE committed row
392
+ * with the row read (the supersede-close pattern), which is stronger than the
393
+ * identity list alone: a content-only change to a row that lacks a stored
394
+ * incarnation token (a legacy row may lack one) still fails it. The vector is computed for text unchanged through confirmation.
395
+ *
396
+ * After the commit, still holding the lock, it re-reads the committed row in a
397
+ * fresh context (flair#2656) and returns the verdict: `shown` only when the row
398
+ * still has this attempt's identity, the staged fields, and the text the vector
399
+ * was computed for. The lock is released after that read. A row this attempt
400
+ * did not confirm is uncounted; the next batch or scan decides whether it is
401
+ * still stale.
402
+ */
403
+ async function regenContentSuffixRow(table, id, existing, current, deps) {
404
+ try {
405
+ const text = skillEmbedText(existing);
406
+ if (typeof text !== "string" || text.length === 0)
407
+ return { kind: "skipped" };
408
+ const embedding = await deps.embed(text);
409
+ if (!isUsableEmbedding(embedding))
410
+ return { kind: "skipped" };
411
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
412
+ // The vector is computed and the id's lock is not yet taken.
413
+ const before = txnPausePoint("embedding-stamp-content-suffix-pre");
414
+ if (before)
415
+ await before;
416
+ const locked = await withMemoryWriteLockOnce((deps.lockStore ?? defaultMemoryLockStore)(), [id], async () => {
417
+ const staged = await stageContentSuffixUpdate(table, id, existing, current, embedding, text, deps);
418
+ if (!staged)
419
+ return { kind: "skipped" };
420
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
421
+ // After this attempt's transaction commits and before its committed-row
422
+ // read-back; the lock is held.
423
+ const verifyPause = txnPausePoint("embedding-stamp-content-suffix-verify");
424
+ if (verifyPause)
425
+ await verifyPause;
426
+ // The staged vector counts only when the committed row still carries the
427
+ // exact text the vector was computed for.
428
+ const verdict = await verifyCommittedFields(table, id, staged.identity, staged.fields, (committed) => skillEmbedText(committed) === staged.text);
429
+ // Test-only: the attempt has committed and read its row back; the lock is
430
+ // still held.
431
+ const committedPause = txnPausePoint("embedding-stamp-content-suffix-committed");
432
+ if (committedPause)
433
+ await committedPause;
434
+ return { kind: "verified", verdict, staged: { embedding, text: staged.text } };
435
+ }, { phase: "embedding-stamp-content-suffix" });
436
+ if (locked.kind !== "done")
437
+ return { kind: "lock", outcome: locked.kind };
438
+ return locked.value;
439
+ }
440
+ catch {
441
+ // Includes CommittedRowChanged: the transaction was aborted, nothing written.
442
+ return { kind: "skipped" };
443
+ }
444
+ }
445
+ /** The fallback's owned transaction, run while the caller holds the id's lock:
446
+ * the re-read, the staged update, the committed-row confirmation and the commit.
447
+ * Returns the staged row and fields, or false when the re-read row is not the
448
+ * row the vector was computed for. A failed confirmation throws (the
449
+ * transaction aborts). */
450
+ async function stageContentSuffixUpdate(table, id, existing, current, embedding, text, deps) {
451
+ return deps.inTransaction(async (txn) => {
452
+ const fresh = await table.get(id, txn);
453
+ if (!fresh || !isDeepStrictEqual(fresh, existing))
454
+ return false;
455
+ // flair#2465: an incremental update of ONLY the embedding fields, not a
456
+ // full-row put. A full-row put carries this transaction's re-read row and
457
+ // can revert a field an owner edit committed meanwhile; this write touches
458
+ // only embedding/embeddingModel/updatedAt and the embedded-text hash.
459
+ const update = { embedding, embeddingModel: current, updatedAt: new Date().toISOString(), embeddedContentHash: embeddedTextHash(existing) ?? null };
460
+ await table.update(id, update, txn);
461
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
462
+ // After the write is STAGED and before the transaction commits.
463
+ const pause = txnPausePoint("embedding-stamp-content-suffix");
464
+ if (pause)
465
+ await pause;
466
+ // Stage first, then confirm the COMMITTED row is still the row this
467
+ // transaction read and embedded; gone or distinguishably changed at
468
+ // confirmation aborts (the staged write is discarded). Post-commit
469
+ // verification retries surviving differences in compared fields, identity
470
+ // or embedding text from a fresh read.
471
+ await confirmCommittedRow(table, id, (committed) => isDeepStrictEqual(committed, fresh));
472
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
473
+ // Holds the regen after its final pre-commit confirmation and before its
474
+ // owned transaction commits (flair#2656).
475
+ const commitPause = txnPausePoint("embedding-stamp-content-suffix-commit");
476
+ if (commitPause)
477
+ await commitPause;
478
+ return { identity: fresh, fields: update, text };
479
+ });
480
+ }
209
481
  /**
210
482
  * `getTable`/`getCurrentModelId`/`regen` are injectable so unit tests can
211
483
  * exercise this migration's full detect/countPending/run logic against an
@@ -215,11 +487,10 @@ async function regenViaHttpPut(id, existing, fetchImpl) {
215
487
  * loopback-HTTP regen path is exercised for real in
216
488
  * test/integration/migrations-embedding-stamp-e2e.test.ts.
217
489
  */
218
- export function createEmbeddingStampMigration(getTable = defaultMemoryTable, getCurrentModelId = getModelId, regen = (id, existing) => regenViaHttpPut(id, existing, fetch)) {
490
+ export function createEmbeddingStampMigration(getTable = defaultMemoryTable, getCurrentModelId = getModelId, regen = (id) => regenViaHttpPatch(id, fetch), contentSuffixRegen = defaultContentSuffixRegenDeps) {
219
491
  function staleCondition() {
220
492
  // OR-combined: `not_equals <current>` catches a stale non-null model
221
- // string; `equals null` catches the explicit-null state this
222
- // migration's own writes leave behind on a failed regen (see the
493
+ // string; `equals null` catches an explicit-null state (see the
223
494
  // module doc above — Harper's index never sees a TRULY ABSENT
224
495
  // property, only an explicit null).
225
496
  //
@@ -273,26 +544,52 @@ export function createEmbeddingStampMigration(getTable = defaultMemoryTable, get
273
544
  alwaysDetect: true,
274
545
  async detect() {
275
546
  const table = getTable();
547
+ // The query leg first: a row whose stamp is not current-space (cheap,
548
+ // index- or live-read backed — see staleCondition()).
276
549
  for await (const _row of table.search({ conditions: staleCondition(), limit: 1 })) {
277
550
  return true;
278
551
  }
552
+ // The mismatch leg: a row whose stamp IS current-space but whose stored
553
+ // hash differs from the expected hash of its current text. No query can
554
+ // compute that expected hash, so this is a live scan; it exits at the
555
+ // first mismatch.
556
+ const current = getCurrentModelId();
557
+ for await (const row of table.search({})) {
558
+ if (!rowEmbeddingCurrent(row, current))
559
+ return true;
560
+ }
279
561
  return false;
280
562
  },
281
563
  async countPending() {
282
564
  const table = getTable();
565
+ const current = getCurrentModelId();
283
566
  let n = 0;
284
- for await (const _row of table.search({ conditions: staleCondition() }))
285
- n++;
567
+ for await (const row of table.search({})) {
568
+ if (!rowEmbeddingCurrent(row, current))
569
+ n++;
570
+ }
286
571
  return n;
287
572
  },
573
+ async checkUnconfirmed(id) {
574
+ const row = await getTable().get(id);
575
+ if (!row)
576
+ return "no-row";
577
+ return rowEmbeddingCurrent(row, getCurrentModelId())
578
+ ? "at-target"
579
+ : "pending";
580
+ },
288
581
  async run(batchSize) {
289
582
  const table = getTable();
290
583
  const current = getCurrentModelId();
291
584
  const candidates = [];
292
- for await (const row of table.search({ conditions: staleCondition(), limit: batchSize })) {
293
- candidates.push(row);
585
+ for await (const row of table.search({})) {
586
+ if (!rowEmbeddingCurrent(row, current))
587
+ candidates.push(row);
588
+ if (candidates.length >= batchSize)
589
+ break;
294
590
  }
295
591
  const touchedIds = [];
592
+ const unconfirmedIds = [];
296
593
  for (const row of candidates) {
297
594
  const id = String(row.id ?? "");
298
595
  if (!id)
@@ -300,48 +597,131 @@ export function createEmbeddingStampMigration(getTable = defaultMemoryTable, get
300
597
  const existing = await table.get(id);
301
598
  if (!existing)
302
599
  continue; // deleted since the search above — nothing to fix
303
- if (isCurrentSpaceStamp(existing.embeddingModel, current))
304
- continue; // already current-space (incl. bare equivalent) — idempotent skip
305
- const ok = await regen(id, existing);
600
+ if (rowEmbeddingCurrent(existing, current)) {
601
+ // Current now although the scan above selected it: another writer's
602
+ // change between the scan and this read. This run has not attempted
603
+ // the row, so it is not this migration's work and stays uncounted
604
+ // (flair#2840).
605
+ continue;
606
+ }
607
+ let ok;
608
+ // Set when this row's outcome is unconfirmed (flair#2840). On the
609
+ // `.content` path: an attempt whose committed effect the post-commit
610
+ // verification read did not show; the row is counted as done only if a
611
+ // later attempt in that loop is verified (`ok`), and otherwise it is
612
+ // reported by id when the batch returns or the retry read throws (the
613
+ // BatchOutcomeError below). On the loopback path: a 503
614
+ // `write_outcome_unknown` answer, which can reflect an earlier writer's
615
+ // unresolved write; `regenViaHttpPatch` answers `ok: false`, and the
616
+ // row is reported by id when the batch returns. A throw elsewhere in the
617
+ // batch that does not wrap its outcome loses the id.
618
+ let unconfirmed = false;
619
+ if (endsWithContentSelectorSuffix(id)) {
620
+ // flair#2656: the commit is not proof the update landed. A newer write
621
+ // committing after the confirm read can make the commit resolve while
622
+ // discarding this update. Re-read from committed state within this
623
+ // bound; count the row touched only when the committed row shows the
624
+ // staged fields and the text the vector was computed for.
625
+ ok = false;
626
+ // The vector and text of this row's last unconfirmed attempt.
627
+ let ownUnconfirmed;
628
+ // One guard over the whole retry loop (flair#2478): when the loop ends
629
+ // without a verified attempt after an attempt whose committed write is
630
+ // unconfirmed, by a break, a refusal or a thrown error, the unconfirmed
631
+ // outcome is logged exactly once. A later verified attempt sets `ok`,
632
+ // and nothing is logged. An error the loop itself throws (a retry's
633
+ // fresh read of the row) leaves as a BatchOutcomeError carrying this
634
+ // row and the batch's earlier outcomes, after the line is logged; an
635
+ // error inside an attempt is caught by regenContentSuffixRow and ends
636
+ // the loop as a skipped attempt.
637
+ try {
638
+ for (let attempt = 1; attempt <= CONTENT_SUFFIX_REGEN_ATTEMPTS; attempt++) {
639
+ const rowNow = attempt === 1 ? existing : await table.get(id);
640
+ if (!rowNow)
641
+ break;
642
+ // A row another writer already made current is not this migration's
643
+ // write. Leave it uncounted; a later scan decides whether anything
644
+ // still needs re-embedding. A row whose stored vector matches the
645
+ // vector this loop's last unconfirmed attempt staged (within a
646
+ // relative tolerance, holdsOwnStaleVector) while its text changed is
647
+ // not current, whatever its stored hash says: a row with an empty
648
+ // owner stores a null hash, which passes the hash comparison for any
649
+ // text (flair#2478). Who stored a matching vector is not known.
650
+ if (attempt > 1 && rowEmbeddingCurrent(rowNow, current) &&
651
+ !holdsOwnStaleVector(rowNow, ownUnconfirmed))
652
+ break;
653
+ const attemptResult = await regenContentSuffixRow(table, id, rowNow, current, contentSuffixRegen);
654
+ if (attemptResult.kind === "lock") {
655
+ // This attempt wrote nothing. After an earlier unconfirmed attempt
656
+ // of this loop the row may hold that attempt's write, so the line
657
+ // says the outcome is unknown (the unconfirmed line below follows).
658
+ console.warn("[embedding-stamp] %s: the per-id write lock answered %s; %s; the row is uncounted and the next scan decides whether it is still stale", id, attemptResult.outcome, unconfirmed
659
+ ? "this attempt wrote nothing, but an earlier attempt's write was not confirmed, so the outcome is unknown"
660
+ : "nothing was written");
661
+ break;
662
+ }
663
+ if (attemptResult.kind === "skipped")
664
+ break;
665
+ // Safe to retry from a fresh read: the same text yields the same
666
+ // vector and hash, and a retry restages `updatedAt`. A readable
667
+ // post-commit mismatch retries from a fresh read (and a new vector,
668
+ // computed before the lock) within CONTENT_SUFFIX_REGEN_ATTEMPTS; an
669
+ // unreadable verification stops without a retry.
670
+ if (attemptResult.verdict === "shown") {
671
+ ok = true;
672
+ break;
673
+ }
674
+ unconfirmed = true;
675
+ ownUnconfirmed = attemptResult.staged;
676
+ if (attemptResult.verdict === "unreadable")
677
+ break;
678
+ }
679
+ }
680
+ catch (err) {
681
+ // flair#2840: carry this batch's outcomes on the error — the runner
682
+ // has no RunBatchResult to read when run() throws.
683
+ if (unconfirmed)
684
+ unconfirmedIds.push(id);
685
+ throw new BatchOutcomeError({ touchedIds, unconfirmedIds }, err);
686
+ }
687
+ finally {
688
+ if (!ok && unconfirmed) {
689
+ console.warn("[embedding-stamp] %s: the content-suffix re-embed did not confirm its committed row; outcome: unconfirmed, the row is uncounted and a later scan decides pending state", id);
690
+ }
691
+ }
692
+ }
693
+ else {
694
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
695
+ const pause = txnPausePoint("embedding-stamp-regen-pre");
696
+ if (pause)
697
+ await pause;
698
+ const outcome = await regen(id, existing);
699
+ if (typeof outcome === "boolean") {
700
+ ok = outcome;
701
+ }
702
+ else {
703
+ ok = outcome.ok;
704
+ // The loopback PATCH answered 503 write_outcome_unknown: the id has
705
+ // an unresolved write, which may have committed (flair#2840).
706
+ if (outcome.unconfirmed)
707
+ unconfirmed = true;
708
+ }
709
+ }
306
710
  if (ok)
307
711
  touchedIds.push(id);
308
- // A failed regen leaves the row untouched (still matching
309
- // staleCondition — retried next batch/boot), never partially
310
- // written or marked done.
311
- }
312
- return { processed: touchedIds.length, touchedIds };
313
- },
314
- /**
315
- * flair#807 completion-gate safety net (resources/migrations/runner.ts
316
- * calls this ONLY when a nonzero countPending() would otherwise halt the
317
- * migration). Re-derives up to `limit` currently-"pending" ids via the
318
- * SAME staleCondition() search countPending() uses, then re-checks each
319
- * one by a DIRECT `.get()` — a primary-key lookup, never index-assisted,
320
- * so it can't be fooled by the same secondary-index divergence that can
321
- * make the search-based count wrong. Returns counts only (never ids —
322
- * matches this codebase's structural-only-disclosure discipline, e.g.
323
- * resources/migrations/ledger.ts's module doc), so the runner can log a
324
- * loud, actionable WARN without ever needing to know which rows.
325
- */
326
- async recheckPending(limit) {
327
- const table = getTable();
328
- const current = getCurrentModelId();
329
- const ids = [];
330
- for await (const row of table.search({ conditions: staleCondition(), limit })) {
331
- const id = String(row.id ?? "");
332
- if (id)
333
- ids.push(id);
334
- }
335
- let falsePositives = 0;
336
- for (const id of ids) {
337
- const existing = await table.get(id);
338
- // A row that vanished since the search, OR whose live embeddingModel
339
- // still doesn't match current, is a GENUINE pending row (or a
340
- // concurrent delete) — never counted as a false positive.
341
- if (existing && isCurrentSpaceStamp(existing.embeddingModel, current))
342
- falsePositives++;
712
+ else if (unconfirmed)
713
+ unconfirmedIds.push(id);
714
+ // A false result does not add the row to touchedIds. It does not prove
715
+ // nothing was written (a loopback PATCH can commit before its response
716
+ // fails); the next live scan decides, retrying the row only if it is
717
+ // still pending. Only the `.content`-suffix path's aborted local
718
+ // transaction is known to write nothing.
343
719
  }
344
- return { sampled: ids.length, falsePositives };
720
+ const result = unconfirmedIds.length > 0
721
+ ? { processed: touchedIds.length, touchedIds, unconfirmedIds }
722
+ : { processed: touchedIds.length, touchedIds };
723
+ noteTestMigrationRun(result);
724
+ return result;
345
725
  },
346
726
  };
347
727
  }