@tpsdev-ai/flair 0.62.0 → 0.63.1

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 (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -35,10 +35,17 @@
35
35
  *
36
36
  * The request is the re-embed PATCH (flair#2296): body
37
37
  * `{"embedding": null, "embeddingModel": null}`. Memory.patch() embeds the row
38
- * the PATCH handler reads and writes `embedding`, `embeddingModel` and
39
- * `updatedAt`. Edits committed after this migration's read and before the PATCH
40
- * handler's stored-row read are kept (flair#2275). An edit committed while
41
- * Memory.patch() awaits the embedding is a separate, tracked window.
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.
42
49
  *
43
50
  * THIS IS LOAD-BEARING, confirmed empirically while building
44
51
  * test/integration/migrations-embedding-stamp-e2e.test.ts against real
@@ -141,8 +148,9 @@
141
148
  * flair#2465 part 2 — the stored text hash. A re-embed can still store the
142
149
  * vector for the text it read when a text edit commits after that read and
143
150
  * before the commit (Harper has no compare-and-set; the field-only write and the
144
- * committed-row confirm narrow — not close — that window). To catch the rows
145
- * such an edit leaves behind, the server stores a newly computed
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
146
154
  * `embeddedContentHash` (resources/memory-embed-hash.ts) when it computes a
147
155
  * vector on a guarded path for a row with a non-empty owner, and this migration
148
156
  * re-queues a row whose stored hash differs from the expected hash of its
@@ -157,25 +165,80 @@
157
165
  * would queue every legacy row at upgrade, and could leave pending a row that
158
166
  * cannot get a hash (one with an empty owner); a missing hash skips the
159
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.
160
203
  */
161
204
  import { databases } from "harper";
205
+ import { appendFileSync } from "node:fs";
206
+ import { join } from "node:path";
162
207
  import { isDeepStrictEqual } from "node:util";
163
- import { confirmCommittedRow } from "../write-back.js";
208
+ import { confirmCommittedRow, verifyCommittedFields } from "../write-back.js";
209
+ import { withMemoryWriteLockOnce } from "../memory-write-lock.js";
164
210
  import { getEmbedding, getModelId } from "../embeddings-provider.js";
165
211
  import { withOwnedTransaction } from "../request-transaction.js";
166
212
  import { txnPausePoint } from "../txn-pause-point.js";
167
213
  import { harperPortValue } from "../../src/lib/harper-port-value.js";
168
214
  import { DEFAULT_HTTP_PORT } from "../a2a-url.js";
169
215
  import { currentSpaceRawForms, isCurrentSpaceStamp } from "../embedding-space-guard.js";
216
+ import { BatchOutcomeError } from "./types.js";
170
217
  import { EMBEDDING_STAMP_ID } from "./stamp-outstanding.js";
171
218
  import { endsWithContentSelectorSuffix } from "../../src/lib/memory-id-policy.js";
172
219
  import { skillEmbedText } from "../skill-write.js";
173
- import { embeddedHashMatches, embeddedTextHash } from "../memory-embed-hash.js";
220
+ import { embeddedHashMatches, embeddedTextHash, holdsOwnStaleVector } from "../memory-embed-hash.js";
174
221
  export { EMBEDDING_STAMP_ID };
175
222
  function defaultMemoryTable() {
176
223
  return databases.flair.Memory;
177
224
  }
178
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
+ }
179
242
  /** Same admin-password resolution as resources/auth-middleware.ts's getAdminPass(). */
180
243
  function resolveAdminAuthHeader() {
181
244
  const pass = process.env.HDB_ADMIN_PASSWORD ?? process.env.FLAIR_ADMIN_PASSWORD;
@@ -192,8 +255,8 @@ function resolveAdminAuthHeader() {
192
255
  * reverse-proxied origin and is deliberately ignored here, matching
193
256
  * `a2a-url.localBaseUrl` ("never the public/proxy URL"): two self-call
194
257
  * resolvers, both pinned to loopback. The public-facing resolvers (e.g.
195
- * oauth-discovery, AdminInstance, XAA; also a2a-url.resolvePublicBaseUrl and
196
- * 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
197
260
  * output is meant to be reachable off-box; this one's output is not. That list
198
261
  * is illustrative, not exhaustive — the deciding question is whether the URL
199
262
  * leaves the box, not a roster of call sites.
@@ -218,8 +281,9 @@ export function resolveSelfBaseUrl(env = process.env) {
218
281
  * Triggers Memory.patch()'s re-embed branch via a genuine loopback HTTP
219
282
  * PATCH — the ONLY reliable way to reach resources/Memory.ts's subclass logic
220
283
  * (see module doc). The body names only the two embedding fields, never the
221
- * row this migration read. Returns true iff the request succeeded (2xx);
222
- * NEVER throws — on false the row is re-checked on the next batch or cycle.
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.
223
287
  */
224
288
  async function regenViaHttpPatch(id, fetchImpl) {
225
289
  const authHeader = resolveAdminAuthHeader();
@@ -232,12 +296,42 @@ async function regenViaHttpPatch(id, fetchImpl) {
232
296
  body: JSON.stringify({ embedding: null, embeddingModel: null }),
233
297
  signal: AbortSignal.timeout(REGEN_HTTP_TIMEOUT_MS),
234
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
+ }
235
306
  return res.ok;
236
307
  }
237
308
  catch {
238
309
  return false;
239
310
  }
240
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
+ }
241
335
  /** A vector this migration may stamp as current: a non-empty array of finite numbers. */
242
336
  function isUsableEmbedding(value) {
243
337
  return Array.isArray(value) && value.length > 0 && value.every((n) => typeof n === "number" && Number.isFinite(n));
@@ -254,9 +348,14 @@ function rowEmbeddingCurrent(row, currentModelId) {
254
348
  return isCurrentSpaceStamp(row.embeddingModel, currentModelId) &&
255
349
  embeddedHashMatches(row);
256
350
  }
351
+ /** The Memory table's primary store, whose per-id lock the owner verbs take. */
352
+ function defaultMemoryLockStore() {
353
+ return defaultMemoryTable().primaryStore;
354
+ }
257
355
  const defaultContentSuffixRegenDeps = {
258
356
  embed: (text) => getEmbedding(text, "document"),
259
357
  inTransaction: (fn) => withOwnedTransaction(undefined, fn),
358
+ lockStore: defaultMemoryLockStore,
260
359
  };
261
360
  /**
262
361
  * Re-embed a legacy row whose id ends in the `.content` property suffix. The
@@ -269,61 +368,116 @@ const defaultContentSuffixRegenDeps = {
269
368
  * (`skillEmbedText`: a skill row's `trigger` when present, else `content`); a
270
369
  * row with no such text is not embedded.
271
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
+ *
272
380
  * Writes a usable vector in an owned transaction. It STAGES an incremental
273
381
  * `update` of only `embedding`, `embeddingModel`, `updatedAt` and
274
- * `embeddedContentHash` — the same field-only write Memory's own re-embed branch
382
+ * `embeddedContentHash` — the field-only write Memory's own re-embed branch
275
383
  * uses (flair#2465), never a full-row put — and the write touches no other field
276
- * of the committed row.
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.)
277
386
  * Then it CONFIRMS the committed row (an explicit fresh context) is still the
278
387
  * row this transaction read and embedded; a row gone or distinguishably changed
279
- * at confirmation aborts the owned transaction and returns false.
388
+ * at confirmation aborts the owned transaction (`skipped`, nothing written).
280
389
  *
281
- * Harper has no compare-and-set: a change committed after confirmation and
282
- * before commit is not seen. The confirmation compares the WHOLE committed row
390
+ * The post-commit read detects surviving differences in compared fields,
391
+ * identity or embedding text. The confirmation compares the WHOLE committed row
283
392
  * with the row read (the supersede-close pattern), which is stronger than the
284
393
  * identity list alone: a content-only change to a row that lacks a stored
285
394
  * incarnation token (a legacy row may lack one) still fails it. The vector is computed for text unchanged through confirmation.
286
395
  *
287
- * Returns true when the update is staged, confirmation passes and the owned
288
- * transaction completes; otherwise false.
289
- * A row that still exists with a stale stamp stays pending for the next batch
290
- * or cycle.
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.
291
402
  */
292
403
  async function regenContentSuffixRow(table, id, existing, current, deps) {
293
404
  try {
294
405
  const text = skillEmbedText(existing);
295
406
  if (typeof text !== "string" || text.length === 0)
296
- return false;
407
+ return { kind: "skipped" };
297
408
  const embedding = await deps.embed(text);
298
409
  if (!isUsableEmbedding(embedding))
299
- return false;
300
- return await deps.inTransaction(async (txn) => {
301
- const fresh = await table.get(id, txn);
302
- if (!fresh || !isDeepStrictEqual(fresh, existing))
303
- return false;
304
- // flair#2465: an incremental update of ONLY the embedding fields, not a
305
- // full-row put. A full-row put carries this transaction's re-read row and
306
- // can revert a field an owner edit committed meanwhile; this write touches
307
- // only embedding/embeddingModel/updatedAt and the embedded-text hash.
308
- await table.update(id, { embedding, embeddingModel: current, updatedAt: new Date().toISOString(), embeddedContentHash: embeddedTextHash(existing) ?? null }, txn);
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" };
309
420
  // Test-only: inert unless the fault-injection env opt-in is set and armed.
310
- // After the write is STAGED and before the transaction commits.
311
- const pause = txnPausePoint("embedding-stamp-content-suffix");
312
- if (pause)
313
- await pause;
314
- // Stage first, then confirm the COMMITTED row is still the row this
315
- // transaction read and embedded; gone or distinguishably changed at
316
- // confirmation aborts (the staged write is discarded). A change committed
317
- // after this re-read and before the commit is not seen.
318
- await confirmCommittedRow(table, id, (committed) => isDeepStrictEqual(committed, fresh));
319
- return true;
320
- });
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;
321
439
  }
322
440
  catch {
323
441
  // Includes CommittedRowChanged: the transaction was aborted, nothing written.
324
- return false;
442
+ return { kind: "skipped" };
325
443
  }
326
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
+ }
327
481
  /**
328
482
  * `getTable`/`getCurrentModelId`/`regen` are injectable so unit tests can
329
483
  * exercise this migration's full detect/countPending/run logic against an
@@ -416,6 +570,14 @@ export function createEmbeddingStampMigration(getTable = defaultMemoryTable, get
416
570
  }
417
571
  return n;
418
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
+ },
419
581
  async run(batchSize) {
420
582
  const table = getTable();
421
583
  const current = getCurrentModelId();
@@ -427,6 +589,7 @@ export function createEmbeddingStampMigration(getTable = defaultMemoryTable, get
427
589
  break;
428
590
  }
429
591
  const touchedIds = [];
592
+ const unconfirmedIds = [];
430
593
  for (const row of candidates) {
431
594
  const id = String(row.id ?? "");
432
595
  if (!id)
@@ -434,28 +597,131 @@ export function createEmbeddingStampMigration(getTable = defaultMemoryTable, get
434
597
  const existing = await table.get(id);
435
598
  if (!existing)
436
599
  continue; // deleted since the search above — nothing to fix
437
- if (rowEmbeddingCurrent(existing, current))
438
- continue; // already current (stamp and hash) — idempotent skip
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
+ }
439
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;
440
619
  if (endsWithContentSelectorSuffix(id)) {
441
- ok = await regenContentSuffixRow(table, id, existing, current, contentSuffixRegen);
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
+ }
442
692
  }
443
693
  else {
444
694
  // Test-only: inert unless the fault-injection env opt-in is set and armed.
445
695
  const pause = txnPausePoint("embedding-stamp-regen-pre");
446
696
  if (pause)
447
697
  await pause;
448
- ok = await regen(id, existing);
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
+ }
449
709
  }
450
710
  if (ok)
451
711
  touchedIds.push(id);
712
+ else if (unconfirmed)
713
+ unconfirmedIds.push(id);
452
714
  // A false result does not add the row to touchedIds. It does not prove
453
715
  // nothing was written (a loopback PATCH can commit before its response
454
716
  // fails); the next live scan decides, retrying the row only if it is
455
717
  // still pending. Only the `.content`-suffix path's aborted local
456
718
  // transaction is known to write nothing.
457
719
  }
458
- return { processed: touchedIds.length, touchedIds };
720
+ const result = unconfirmedIds.length > 0
721
+ ? { processed: touchedIds.length, touchedIds, unconfirmedIds }
722
+ : { processed: touchedIds.length, touchedIds };
723
+ noteTestMigrationRun(result);
724
+ return result;
459
725
  },
460
726
  };
461
727
  }
@@ -57,6 +57,8 @@ import { existsSync, readFileSync } from "node:fs";
57
57
  import { dirname, join } from "node:path";
58
58
  import { fileURLToPath } from "node:url";
59
59
  import { embeddingSpaceVerdict, spaceGuardState } from "../embedding-space-guard.js";
60
+ import { maybeFaultOrgEventRow } from "../org-event-write-fault.js";
61
+ import { validateServerRow } from "../server-row-validation.js";
60
62
  export const GRAPH_HEAL_ID = "graph-heal";
61
63
  /** How many rows to scan for a canary that carries a real embedding. Bounded — detect() must stay cheap. */
62
64
  const CANARY_SCAN_LIMIT = 8;
@@ -184,7 +186,7 @@ async function writeGraphHealEvent(obs, table) {
184
186
  const countNote = obs.embeddedVectorCount != null
185
187
  ? ` (${obs.embeddedVectorCount} embedded vector${obs.embeddedVectorCount === 1 ? "" : "s"})`
186
188
  : "";
187
- await table.put({
189
+ const row = {
188
190
  id: `migration-graph-heal-verified-${obs.at}`,
189
191
  authorId: "flair-migrations",
190
192
  kind: "migration",
@@ -200,7 +202,12 @@ async function writeGraphHealEvent(obs, table) {
200
202
  }),
201
203
  refId: GRAPH_HEAL_ID,
202
204
  createdAt: obs.at,
203
- });
205
+ };
206
+ // Test-only: the hook may corrupt the exact row about to be staged (inert
207
+ // unless a fixture installs one).
208
+ maybeFaultOrgEventRow("graph-heal", row);
209
+ validateServerRow(table, row);
210
+ await table.put(row);
204
211
  }
205
212
  /**
206
213
  * `getTable`/`getOrgEventTable`/`getVersion`/`now` are injectable so tests can
@@ -18,6 +18,7 @@
18
18
  * server-internal writes with no HTTP caller behind them.
19
19
  */
20
20
  import { databases } from "harper";
21
+ import { validateServerRow } from "../server-row-validation.js";
21
22
  function defaultOrgEventTable() {
22
23
  return databases.flair.OrgEvent;
23
24
  }
@@ -42,7 +43,7 @@ export async function writeLedgerEvent(evt, deps = {}) {
42
43
  const table = deps.orgEventTable ?? defaultOrgEventTable();
43
44
  const id = `migration-${evt.migrationId}-${evt.endedAt}`;
44
45
  const remainingNote = evt.rowsRemaining > 0 ? `, ${evt.rowsRemaining} remaining` : "";
45
- await table.put({
46
+ const row = {
46
47
  id,
47
48
  authorId: "flair-migrations",
48
49
  kind: "migration",
@@ -51,5 +52,7 @@ export async function writeLedgerEvent(evt, deps = {}) {
51
52
  detail: buildLedgerDetail(evt),
52
53
  refId: evt.migrationId,
53
54
  createdAt: evt.endedAt,
54
- });
55
+ };
56
+ validateServerRow(table, row);
57
+ await table.put(row);
55
58
  }