@tpsdev-ai/flair 0.58.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +1030 -343
  10. package/dist/commands/agent.js +384 -45
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +601 -163
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +146 -53
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +120 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +27 -2
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1775 -338
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +103 -7
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +227 -64
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -28,9 +28,17 @@
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` 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.
34
42
  *
35
43
  * THIS IS LOAD-BEARING, confirmed empirically while building
36
44
  * test/integration/migrations-embedding-stamp-e2e.test.ts against real
@@ -42,27 +50,23 @@
42
50
  * for a genuine `/Memory` request. Calling `.put()` on the raw reference
43
51
  * writes the record fine (confirmed: fields land exactly as passed) but
44
52
  * 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.
53
+ * re-embed branch this migration exists to trigger. Reads
54
+ * (`.search()`/`.get()`, used below for detect/countPending/candidate-selection)
55
+ * are unaffected by this — only the re-embed request needs the real dispatch,
56
+ * hence the loopback HTTP call for exactly that one step.
50
57
  *
51
58
  * Query correctness (also verified against real Harper): Harper's
52
59
  * `not_equal` comparator only matches rows where the attribute holds an
53
60
  * EXPLICIT value (including explicit `null`) — a row where the attribute
54
61
  * was NEVER SET AT ALL (`getIndexedValues()` returns `undefined` for a
55
62
  * 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
63
+ * invisible to ANY condition-based query, not just `not_equal`. A re-embed
64
+ * request that fails (engine not yet warmed up, transient failure, admin
65
+ * credential unavailable this cycle) is retried on a later cycle while the row
66
+ * still matches the pending condition.
67
+ * The pending condition is an OR of `not_equal <current>` (catches a
68
+ * stale non-null model string) and `equals null` (catches an explicit-null
69
+ * state). A row whose `embeddingModel` was NEVER
66
70
  * touched by anything (truly absent from its very first write — only
67
71
  * possible if the embeddings engine was down for that entire write) is a
68
72
  * known, narrow gap this bounded query cannot see;
@@ -103,15 +107,16 @@
103
107
  * negated comparator — no analogous bypass exists or is needed; its
104
108
  * behavior was already verified against real Harper per the doc above).
105
109
  *
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.
110
+ * NO `recheckPending()` (the runner's flair#807 completion-gate safety net,
111
+ * resources/migrations/runner.ts) since flair#2465. `countPending()` now scans
112
+ * every row's live value instead of querying an index, so there is no index
113
+ * artifact for that net to excuse. A recheck that re-derived its candidates
114
+ * from the `staleCondition()` query could also sample rows other than the ones
115
+ * the scan counted (a row pending only on its stored hash is invisible to that
116
+ * query) and pass the gate with that row still pending.
112
117
  *
113
118
  * ROOT-CAUSE GUARD — recall graph correctness (recall-hnsw-graph-heal).
114
- * This migration RE-EMBEDS rows in BULK via `PUT /Memory/:id` — it replaces
119
+ * This migration RE-EMBEDS rows in BULK via `PATCH /Memory/:id` — it replaces
115
120
  * the stored vector of many rows in place. Historically, an OLDER (pre-fix)
116
121
  * Harper's INCREMENTAL HNSW update left stale/asymmetric reverse edges under
117
122
  * exactly this kind of bulk re-embed (order-dependent), which collapsed prod
@@ -132,13 +137,40 @@
132
137
  * engine is rebuilt on the upgrade boot (observed/ledgered by
133
138
  * resources/migrations/graph-heal.ts). Before enabling any FUTURE bulk
134
139
  * re-embed, ship a structural reindex trigger with it.
140
+ *
141
+ * flair#2465 part 2 — the stored text hash. A re-embed can still store the
142
+ * vector for the text it read when a text edit commits after that read and
143
+ * 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
146
+ * `embeddedContentHash` (resources/memory-embed-hash.ts) when it computes a
147
+ * vector on a guarded path for a row with a non-empty owner, and this migration
148
+ * re-queues a row whose stored hash differs from the expected hash of its
149
+ * current embedding text. No query can compute that expected hash (a condition
150
+ * compares a stored value to a constant), so finding a mismatch takes a LIVE
151
+ * SCAN: `detect` runs the `staleCondition()` query first and scans only when
152
+ * the query finds nothing; `countPending` and `run` scan the whole table
153
+ * directly, applying `rowEmbeddingCurrent` per row. A row with no stored hash
154
+ * (e.g. written before this change, created with a vector accepted from the
155
+ * caller, or with an empty owner) bypasses only the hash comparison: it is
156
+ * current when its model is current-space. A rule that queued every missing hash
157
+ * would queue every legacy row at upgrade, and could leave pending a row that
158
+ * cannot get a hash (one with an empty owner); a missing hash skips the
159
+ * comparison instead.
135
160
  */
136
161
  import { databases } from "harper";
137
- import { getModelId } from "../embeddings-provider.js";
162
+ import { isDeepStrictEqual } from "node:util";
163
+ import { confirmCommittedRow } from "../write-back.js";
164
+ import { getEmbedding, getModelId } from "../embeddings-provider.js";
165
+ import { withOwnedTransaction } from "../request-transaction.js";
166
+ import { txnPausePoint } from "../txn-pause-point.js";
138
167
  import { harperPortValue } from "../../src/lib/harper-port-value.js";
139
168
  import { DEFAULT_HTTP_PORT } from "../a2a-url.js";
140
169
  import { currentSpaceRawForms, isCurrentSpaceStamp } from "../embedding-space-guard.js";
141
170
  import { EMBEDDING_STAMP_ID } from "./stamp-outstanding.js";
171
+ import { endsWithContentSelectorSuffix } from "../../src/lib/memory-id-policy.js";
172
+ import { skillEmbedText } from "../skill-write.js";
173
+ import { embeddedHashMatches, embeddedTextHash } from "../memory-embed-hash.js";
142
174
  export { EMBEDDING_STAMP_ID };
143
175
  function defaultMemoryTable() {
144
176
  return databases.flair.Memory;
@@ -155,7 +187,7 @@ function resolveAdminAuthHeader() {
155
187
  * Base URL for the loopback self-call that regenerates an embedding.
156
188
  *
157
189
  * ALWAYS loopback. This is the destination of a credentialed self-call —
158
- * `regenViaHttpPut` sends `Authorization: Basic` carrying the admin password to
190
+ * `regenViaHttpPatch` sends `Authorization: Basic` carrying the admin password to
159
191
  * it — so it must never leave the box. `FLAIR_PUBLIC_URL` names a remote /
160
192
  * reverse-proxied origin and is deliberately ignored here, matching
161
193
  * `a2a-url.localBaseUrl` ("never the public/proxy URL"): two self-call
@@ -183,21 +215,21 @@ export function resolveSelfBaseUrl(env = process.env) {
183
215
  return `http://127.0.0.1:${harperPortValue(env.HTTP_PORT) ?? DEFAULT_HTTP_PORT}`;
184
216
  }
185
217
  /**
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.
218
+ * Triggers Memory.patch()'s re-embed branch via a genuine loopback HTTP
219
+ * PATCH — the ONLY reliable way to reach resources/Memory.ts's subclass logic
220
+ * (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.
191
223
  */
192
- async function regenViaHttpPut(id, existing, fetchImpl) {
224
+ async function regenViaHttpPatch(id, fetchImpl) {
193
225
  const authHeader = resolveAdminAuthHeader();
194
226
  if (!authHeader)
195
227
  return false; // no admin credential available this cycle — retried next boot
196
228
  try {
197
229
  const res = await fetchImpl(`${resolveSelfBaseUrl()}/Memory/${encodeURIComponent(id)}`, {
198
- method: "PUT",
230
+ method: "PATCH",
199
231
  headers: { "Content-Type": "application/json", Authorization: authHeader },
200
- body: JSON.stringify({ ...existing, embedding: null, embeddingModel: null }),
232
+ body: JSON.stringify({ embedding: null, embeddingModel: null }),
201
233
  signal: AbortSignal.timeout(REGEN_HTTP_TIMEOUT_MS),
202
234
  });
203
235
  return res.ok;
@@ -206,6 +238,92 @@ async function regenViaHttpPut(id, existing, fetchImpl) {
206
238
  return false;
207
239
  }
208
240
  }
241
+ /** A vector this migration may stamp as current: a non-empty array of finite numbers. */
242
+ function isUsableEmbedding(value) {
243
+ return Array.isArray(value) && value.length > 0 && value.every((n) => typeof n === "number" && Number.isFinite(n));
244
+ }
245
+ /**
246
+ * Is this row's stored embedding current? Current means BOTH its
247
+ * `embeddingModel` is a current-space stamp for `currentModelId` AND either it
248
+ * stores no `embeddedContentHash` or the stored hash equals the expected hash of
249
+ * the row's current embedding text (`memory-embed-hash.ts`). No query can
250
+ * compute that expected hash, so a caller that needs to find a hash mismatch
251
+ * must scan (see each method below).
252
+ */
253
+ function rowEmbeddingCurrent(row, currentModelId) {
254
+ return isCurrentSpaceStamp(row.embeddingModel, currentModelId) &&
255
+ embeddedHashMatches(row);
256
+ }
257
+ const defaultContentSuffixRegenDeps = {
258
+ embed: (text) => getEmbedding(text, "document"),
259
+ inTransaction: (fn) => withOwnedTransaction(undefined, fn),
260
+ };
261
+ /**
262
+ * Re-embed a legacy row whose id ends in the `.content` property suffix. The
263
+ * loopback `PATCH /Memory/:id` the regen path uses cannot address such an id
264
+ * (Harper's REST by-id path reads the suffix as a selector, and the write path
265
+ * refuses the id), so this computes the embedding itself and writes through the
266
+ * raw table handle.
267
+ *
268
+ * The text embedded is the one Memory's own write paths embed for the row
269
+ * (`skillEmbedText`: a skill row's `trigger` when present, else `content`); a
270
+ * row with no such text is not embedded.
271
+ *
272
+ * Writes a usable vector in an owned transaction. It STAGES an incremental
273
+ * `update` of only `embedding`, `embeddingModel`, `updatedAt` and
274
+ * `embeddedContentHash` — the same field-only write Memory's own re-embed branch
275
+ * uses (flair#2465), never a full-row put — and the write touches no other field
276
+ * of the committed row.
277
+ * Then it CONFIRMS the committed row (an explicit fresh context) is still the
278
+ * row this transaction read and embedded; a row gone or distinguishably changed
279
+ * at confirmation aborts the owned transaction and returns false.
280
+ *
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
283
+ * with the row read (the supersede-close pattern), which is stronger than the
284
+ * identity list alone: a content-only change to a row that lacks a stored
285
+ * incarnation token (a legacy row may lack one) still fails it. The vector is computed for text unchanged through confirmation.
286
+ *
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.
291
+ */
292
+ async function regenContentSuffixRow(table, id, existing, current, deps) {
293
+ try {
294
+ const text = skillEmbedText(existing);
295
+ if (typeof text !== "string" || text.length === 0)
296
+ return false;
297
+ const embedding = await deps.embed(text);
298
+ 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);
309
+ // 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
+ });
321
+ }
322
+ catch {
323
+ // Includes CommittedRowChanged: the transaction was aborted, nothing written.
324
+ return false;
325
+ }
326
+ }
209
327
  /**
210
328
  * `getTable`/`getCurrentModelId`/`regen` are injectable so unit tests can
211
329
  * exercise this migration's full detect/countPending/run logic against an
@@ -215,11 +333,10 @@ async function regenViaHttpPut(id, existing, fetchImpl) {
215
333
  * loopback-HTTP regen path is exercised for real in
216
334
  * test/integration/migrations-embedding-stamp-e2e.test.ts.
217
335
  */
218
- export function createEmbeddingStampMigration(getTable = defaultMemoryTable, getCurrentModelId = getModelId, regen = (id, existing) => regenViaHttpPut(id, existing, fetch)) {
336
+ export function createEmbeddingStampMigration(getTable = defaultMemoryTable, getCurrentModelId = getModelId, regen = (id) => regenViaHttpPatch(id, fetch), contentSuffixRegen = defaultContentSuffixRegenDeps) {
219
337
  function staleCondition() {
220
338
  // 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
339
+ // string; `equals null` catches an explicit-null state (see the
223
340
  // module doc above — Harper's index never sees a TRULY ABSENT
224
341
  // property, only an explicit null).
225
342
  //
@@ -273,24 +390,41 @@ export function createEmbeddingStampMigration(getTable = defaultMemoryTable, get
273
390
  alwaysDetect: true,
274
391
  async detect() {
275
392
  const table = getTable();
393
+ // The query leg first: a row whose stamp is not current-space (cheap,
394
+ // index- or live-read backed — see staleCondition()).
276
395
  for await (const _row of table.search({ conditions: staleCondition(), limit: 1 })) {
277
396
  return true;
278
397
  }
398
+ // The mismatch leg: a row whose stamp IS current-space but whose stored
399
+ // hash differs from the expected hash of its current text. No query can
400
+ // compute that expected hash, so this is a live scan; it exits at the
401
+ // first mismatch.
402
+ const current = getCurrentModelId();
403
+ for await (const row of table.search({})) {
404
+ if (!rowEmbeddingCurrent(row, current))
405
+ return true;
406
+ }
279
407
  return false;
280
408
  },
281
409
  async countPending() {
282
410
  const table = getTable();
411
+ const current = getCurrentModelId();
283
412
  let n = 0;
284
- for await (const _row of table.search({ conditions: staleCondition() }))
285
- n++;
413
+ for await (const row of table.search({})) {
414
+ if (!rowEmbeddingCurrent(row, current))
415
+ n++;
416
+ }
286
417
  return n;
287
418
  },
288
419
  async run(batchSize) {
289
420
  const table = getTable();
290
421
  const current = getCurrentModelId();
291
422
  const candidates = [];
292
- for await (const row of table.search({ conditions: staleCondition(), limit: batchSize })) {
293
- candidates.push(row);
423
+ for await (const row of table.search({})) {
424
+ if (!rowEmbeddingCurrent(row, current))
425
+ candidates.push(row);
426
+ if (candidates.length >= batchSize)
427
+ break;
294
428
  }
295
429
  const touchedIds = [];
296
430
  for (const row of candidates) {
@@ -300,48 +434,28 @@ export function createEmbeddingStampMigration(getTable = defaultMemoryTable, get
300
434
  const existing = await table.get(id);
301
435
  if (!existing)
302
436
  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);
437
+ if (rowEmbeddingCurrent(existing, current))
438
+ continue; // already current (stamp and hash) — idempotent skip
439
+ let ok;
440
+ if (endsWithContentSelectorSuffix(id)) {
441
+ ok = await regenContentSuffixRow(table, id, existing, current, contentSuffixRegen);
442
+ }
443
+ else {
444
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
445
+ const pause = txnPausePoint("embedding-stamp-regen-pre");
446
+ if (pause)
447
+ await pause;
448
+ ok = await regen(id, existing);
449
+ }
306
450
  if (ok)
307
451
  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.
452
+ // A false result does not add the row to touchedIds. It does not prove
453
+ // nothing was written (a loopback PATCH can commit before its response
454
+ // fails); the next live scan decides, retrying the row only if it is
455
+ // still pending. Only the `.content`-suffix path's aborted local
456
+ // transaction is known to write nothing.
311
457
  }
312
458
  return { processed: touchedIds.length, touchedIds };
313
459
  },
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++;
343
- }
344
- return { sampled: ids.length, falsePositives };
345
- },
346
460
  };
347
461
  }
@@ -21,6 +21,7 @@ export function createContentOnlyExport(opts, deps) {
21
21
  const now = deps.now();
22
22
  const iso = now.toISOString().replace(/[:.]/g, "-");
23
23
  const dir = join(deps.exportRoot, `${sanitizeIdPart(opts.migrationId)}-${opts.table}-${iso}`);
24
+ ensureSecureDir(deps.exportRoot);
24
25
  ensureSecureDir(dir);
25
26
  const fields = sourceFieldsFor(opts.table);
26
27
  const lines = opts.rows.map((row) => {
@@ -32,15 +32,10 @@
32
32
  * healthy after the boot, so the heal is auditable and version-gated (runs
33
33
  * once per upgrade, then the runner's state-file short-circuit — state.ts —
34
34
  * skips it). It touches ZERO rows: riskClass 'derived-only', countPending()
35
- * is always 0, run() writes one structural-only OrgEvent and returns
36
- * `processed: 0`. The runner (resources/migrations/runner.ts) then records
37
- * success in the state file, short-circuiting every subsequent boot at this
38
- * version.
35
+ * is always 0. After verified recall, run() attempts a structural-only
36
+ * OrgEvent and returns `processed: 0`.
39
37
  *
40
- * NON-THROWING throughout (invariant II — the runner halts-not-bricks): a
41
- * canary that can't run, an index still mid-rebuild, or a ledger-write
42
- * failure all degrade to "not verified this boot, retry next boot" or a
43
- * best-effort skip — never an exception into the boot path.
38
+ * Failed re-verification throws to the runner's halt path; boot continues.
44
39
  *
45
40
  * DEFENSE-IN-DEPTH RULE (a prudent, version-independent default — NOT a
46
41
  * workaround for a live bug): any BULK re-embed of the corpus should be paired
@@ -61,6 +56,7 @@ import { databases } from "harper";
61
56
  import { existsSync, readFileSync } from "node:fs";
62
57
  import { dirname, join } from "node:path";
63
58
  import { fileURLToPath } from "node:url";
59
+ import { embeddingSpaceVerdict, spaceGuardState } from "../embedding-space-guard.js";
64
60
  export const GRAPH_HEAL_ID = "graph-heal";
65
61
  /** How many rows to scan for a canary that carries a real embedding. Bounded — detect() must stay cheap. */
66
62
  const CANARY_SCAN_LIMIT = 8;
@@ -121,7 +117,7 @@ async function pickCanary(table) {
121
117
  * The id of the HNSW nearest neighbor of `target` — the exact cosine-sort
122
118
  * query the retrieval path (resources/semantic-retrieval-core.ts) uses,
123
119
  * bounded to rank 1. Throws if the index is unavailable / mid-rebuild; the
124
- * caller treats a throw as "not verified this boot".
120
+ * caller treats a throw as failed verification.
125
121
  */
126
122
  async function topNeighborId(table, target) {
127
123
  for await (const row of table.search({
@@ -140,9 +136,18 @@ async function topNeighborId(table, target) {
140
136
  * and the cleanest black-box proof the graph rebuilt and is serving (a
141
137
  * mid-rebuild index throws or returns nothing; a store with no embedded rows
142
138
  * has no canary). Never throws (invariant II).
139
+ *
140
+ * A state other than `uniform` skips the comparison and logs the state.
143
141
  */
144
142
  async function recallHealthy(table) {
145
143
  try {
144
+ let { state } = spaceGuardState();
145
+ if (state !== "unverified")
146
+ ({ state } = await embeddingSpaceVerdict());
147
+ if (state !== "uniform") {
148
+ console.warn(`graph-heal: canary recall verification skipped — embedding space is not known uniform (state: ${state})`);
149
+ return { verified: false, hasData: true };
150
+ }
146
151
  const canary = await pickCanary(table);
147
152
  if (!canary)
148
153
  return { verified: false, hasData: false };
@@ -209,15 +214,7 @@ export function createGraphHealMigration(getTable = defaultMemoryTable, getOrgEv
209
214
  id: GRAPH_HEAL_ID,
210
215
  riskClass: "derived-only",
211
216
  affectsTables: ["Memory"],
212
- /**
213
- * True only when recall is confirmed healthy AND there is embedded data
214
- * to verify — i.e. the graph rebuilt and is serving. Returns false (the
215
- * runner marks the migration completed for this boot WITHOUT writing a
216
- * success state entry, so detect() runs again next boot) when the index
217
- * is still mid-rebuild or the store has nothing embedded yet. This is the
218
- * enrollment gate: only a confirmed-healthy boot proceeds to run() +
219
- * ledger + the version short-circuit.
220
- */
217
+ /** A false detect writes no durable success entry; a later cycle can retry. */
221
218
  async detect() {
222
219
  const { verified } = await recallHealthy(getTable());
223
220
  return verified;
@@ -226,16 +223,12 @@ export function createGraphHealMigration(getTable = defaultMemoryTable, getOrgEv
226
223
  async countPending() {
227
224
  return 0;
228
225
  },
229
- /**
230
- * Called exactly once (countPending() is 0 → the runner's batch loop runs
231
- * once and breaks). Re-verifies recall for the ledger snapshot, counts
232
- * the embedded vectors, writes ONE structural-only OrgEvent, and returns
233
- * `processed: 0` so the completion gate (count+marker, derived-only)
234
- * passes and the runner records success → short-circuit next boot.
235
- */
226
+ /** Re-verifies recall before the observation and the runner's completion gate. */
236
227
  async run(_batchSize) {
237
228
  const table = getTable();
238
229
  const { verified } = await recallHealthy(table);
230
+ if (!verified)
231
+ throw new Error("graph-heal: recall re-verification failed");
239
232
  const embeddedVectorCount = await countEmbeddedVectors(table);
240
233
  try {
241
234
  await writeGraphHealEvent({ verified, embeddedVectorCount, runningVersion: getVersion(), at: now().toISOString() }, getOrgEventTable());
@@ -78,7 +78,13 @@ export function acquireMigrationLock(deps) {
78
78
  if (inProcessHeld) {
79
79
  return { acquired: false, reason: "already held in-process (another async caller in this process holds it)" };
80
80
  }
81
- mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 });
81
+ try {
82
+ mkdirSync(dirname(lockPath), { mode: 0o700 });
83
+ }
84
+ catch (err) {
85
+ if (err.code !== "EEXIST")
86
+ throw err;
87
+ }
82
88
  if (existsSync(lockPath)) {
83
89
  const holder = readHolder(lockPath);
84
90
  let ageMs = Infinity;
@@ -42,6 +42,7 @@ export function createMigrationSnapshot(opts, deps) {
42
42
  const now = deps.now();
43
43
  const iso = now.toISOString().replace(/[:.]/g, "-");
44
44
  const dir = join(deps.snapshotRoot, `${sanitizeIdPart(opts.migrationId)}-${iso}`);
45
+ ensureSecureDir(deps.snapshotRoot);
45
46
  ensureSecureDir(dir);
46
47
  const manifest = {
47
48
  migrationId: opts.migrationId,
@@ -20,6 +20,7 @@
20
20
  * corpus-level hash.
21
21
  */
22
22
  import { createHash } from "node:crypto";
23
+ import { protoSafeRecord } from "../../src/lib/proto-safe-record.js";
23
24
  export const MEMORY_SOURCE_FIELDS = [
24
25
  "content",
25
26
  "agentId",
@@ -62,11 +63,10 @@ function canonicalize(value) {
62
63
  if (Array.isArray(value))
63
64
  return value.map(canonicalize);
64
65
  if (value && typeof value === "object") {
65
- const out = {};
66
- for (const k of Object.keys(value).sort()) {
67
- out[k] = canonicalize(value[k]);
68
- }
69
- return out;
66
+ const src = value;
67
+ // A null-prototype copy: an own `__proto__` key in a source field is kept
68
+ // and hashed rather than silently dropped from the envelope (flair#2235).
69
+ return protoSafeRecord(src, { keys: Object.keys(src).sort(), map: canonicalize });
70
70
  }
71
71
  return value === undefined ? null : value;
72
72
  }
@@ -28,7 +28,8 @@
28
28
  * re-reading the row itself (invariant IV: state lives IN the data).
29
29
  */
30
30
  import { databases } from "harper";
31
- import { stripUndeclaredMemoryAttributes } from "../memory-declared-attributes.js";
31
+ import { writeBackCommittedRow as writeBackCommittedRowImpl } from "../write-back.js";
32
+ import { txnPausePoint } from "../txn-pause-point.js";
32
33
  export const SYNTHETIC_MIGRATION_ID = "synthetic-ci-schema-stamp";
33
34
  export const RESERVED_TEST_AGENT_ID = "__flair_migration_synthetic_test_agent__";
34
35
  export const SYNTHETIC_TARGET_MARKER = `${SYNTHETIC_MIGRATION_ID}-done`;
@@ -44,7 +45,7 @@ export function shouldRegisterSyntheticMigration(env = process.env) {
44
45
  function defaultMemoryTable() {
45
46
  return databases.flair.Memory;
46
47
  }
47
- export function createSyntheticTestMigration(getTable = defaultMemoryTable) {
48
+ export function createSyntheticTestMigration(getTable = defaultMemoryTable, writeBackCommittedRow = writeBackCommittedRowImpl) {
48
49
  function pendingCondition() {
49
50
  return [
50
51
  { attribute: "agentId", comparator: "equals", value: RESERVED_TEST_AGENT_ID },
@@ -80,15 +81,17 @@ export function createSyntheticTestMigration(getTable = defaultMemoryTable) {
80
81
  const id = String(row.id ?? "");
81
82
  if (!id)
82
83
  continue;
83
- const existing = await table.get(id);
84
- if (!existing)
85
- continue;
86
- if (existing.source === SYNTHETIC_TARGET_MARKER)
87
- continue; // already stamped — idempotent skip
88
- const synthRow = { ...existing, source: SYNTHETIC_TARGET_MARKER };
89
- stripUndeclaredMemoryAttributes(synthRow);
90
- await table.put(synthRow);
91
- touchedIds.push(id);
84
+ const outcome = await writeBackCommittedRow(table, id, (existing) => {
85
+ if (!existing || existing.agentId !== RESERVED_TEST_AGENT_ID)
86
+ return { skip: true };
87
+ if (existing.source === SYNTHETIC_TARGET_MARKER)
88
+ return { skip: true }; // already stamped — idempotent skip
89
+ // Only `source`: an incremental update, never a
90
+ // full-row put of the row read above (flair#2470).
91
+ return { update: { source: SYNTHETIC_TARGET_MARKER } };
92
+ }, { label: "synthetic-test-migration", pausePre: () => txnPausePoint("synthetic-test-pre"), pausePoint: () => txnPausePoint("synthetic-test"), expectedRow: row });
93
+ if (!("skip" in outcome))
94
+ touchedIds.push(id);
92
95
  }
93
96
  return { processed: touchedIds.length, touchedIds };
94
97
  },