@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
@@ -62,7 +62,7 @@ export const MAX_AUTH_HEADER_LEN = 4096;
62
62
  * agentId / nonce / signature never contains whitespace, so excluding it is
63
63
  * behavior-preserving for well-formed headers.
64
64
  */
65
- export const TPS_ED25519_HEADER_RE = /^TPS-Ed25519\s+([^:\s]+):(\d+):([^:\s]+):(.+)$/;
65
+ export const TPS_ED25519_HEADER_RE = /^TPS-Ed25519\s+([^:\s]+):(\d+):([^:\s]+):(.+)$/i;
66
66
  /**
67
67
  * Parse a TPS-Ed25519 `Authorization` header value into its fields, or return
68
68
  * null if it is over `MAX_AUTH_HEADER_LEN` or doesn't match the grammar.
@@ -2,32 +2,52 @@
2
2
  * embedding-space-guard.ts — the QUERY-TIME vector-space uniformity gate
3
3
  * (embedding-provider-seam design §3, slice 1; K&S-final).
4
4
  *
5
- * ─── The bug this closes ────────────────────────────────────────────────────
6
- * There is NO query-time embedding-space guard today. Search cosines a query
7
- * against every stored vector regardless of its `embeddingModel` stamp;
8
- * Harper's `cosineDistance` silently zero-pads a mismatched-dimension vector
9
- * and returns a garbage score instead of throwing (same-dims/different-space
10
- * is silent garbage too), and `health.ts` only *warns*. So a mixed-space
11
- * corpus — the transient state during ANY re-embed / model change — serves
12
- * silently-wrong recall. This module makes a mismatched-space cosine
13
- * impossible by construction on BOTH runtime cosine legs (recall + write-time
14
- * dedup), the load-bearing safety piece Kern made a condition of sign-off.
15
- *
16
5
  * ─── Shape ──────────────────────────────────────────────────────────────────
17
6
  * A PURE core (`normalizeStamp` / `currentSpaceRawForms` / `isUniformStampSet`
18
7
  * — Harper-free, unit-testable directly, same discipline as dedup.ts / bm25.ts)
19
8
  * plus a boot-computed + write-maintained "corpus uniform in the current space"
20
9
  * LATCH so the gate costs ~nothing per query:
21
- * - boot pre-warm scans the DISTINCT active stamps once (module side effect,
22
- * same convention as embeddings-boot.ts / migration-boot.ts);
10
+ * - boot pre-warm scans the corpus;
23
11
  * - a write persisting a FOREIGN stamp (federation / replication / an
24
12
  * explicit-stamp PUT) trips the latch immediately, no rescan;
25
13
  * - while tripped, a consult re-verifies at most once per RECHECK_MS, so a
26
14
  * completed re-embed REOPENS the gate automatically (any re-embed path —
27
15
  * the boot migration OR a live `flair reembed`), with no cross-process
28
16
  * signal needed.
29
- * Both runtime legs consult the SAME `isEmbeddingSpaceUniform()` — a single
30
- * chokepoint (like `prefixesEnabled()`), never scattered per-call-site checks.
17
+ * Both runtime legs consult the SAME verdict — the recall leg through
18
+ * `embeddingSpaceVerdict()`, the dedup leg through `isEmbeddingSpaceUniform()`,
19
+ * both over one consult — a single chokepoint (like `prefixesEnabled()`), never
20
+ * scattered per-call-site checks.
21
+ *
22
+ * ─── Unknown verdict = FAIL CLOSED (flair#2530) ──────────────────────────────
23
+ * A scan can be pending (before the first scan completes) or fail (a boot race,
24
+ * a transient read error). The verdict is then UNKNOWN, and "unknown" is NOT
25
+ * "known uniform". The scan counts rows with any array or typed array, empty
26
+ * included, whose `embeddingModel` is not a trusted current-space stamp — an
27
+ * absent stamp, the hash-fallback marker `hash-512d`, or a foreign model — using
28
+ * the vector query's raw stamp comparison,
29
+ * and a count above zero makes the verdict non-uniform (flair#2573 slice 1).
30
+ * Raw operations-API inserts are uncovered until a rescan; the latch observes
31
+ * only writes that call `noteWriteStamp`. Caller-supplied vector bytes remain
32
+ * unverified (slice 2). Every non-uniform state — pending
33
+ * (`unverified`), a failed scan (`scan-failed`), a non-current stamp observed
34
+ * by a scan or a foreign write (`mixed`), or an excluded array or typed array
35
+ * (`excluded`) — makes a consumer take its
36
+ * MIXED-space path: when a query embedding is available outside bm25-only
37
+ * mode, the recall leg drops it and
38
+ * serves keyword-only results (none, for a request with no query text; for
39
+ * `explain: true`, a plan with no embedding leg) with a state-named warning;
40
+ * the dedup leg no-ops. A recall in bm25-only mode (which never uses a query
41
+ * embedding, so a supplied one is dropped unconsulted) or after a failed
42
+ * embedding generation never consults the guard and has no state to name. A
43
+ * consult never blocks on an in-flight scan to obtain a verdict; it fails closed now,
44
+ * and only a later SUCCESSFUL scan that finds the stamps uniform reopens the
45
+ * gate. An error from the scan's table lookup or corpus read is classified into
46
+ * a bounded reason (never row content); a published failure is logged once per
47
+ * reason, a refused stale one each time it is refused; the consult schedule
48
+ * retries unchanged. A known foreign stamp outranks a scan error: the state is
49
+ * `mixed` whenever one is known, and `reason` keeps the last failed scan's
50
+ * error whether that scan failed before or after the stamp was seen.
31
51
  *
32
52
  * ─── Why the harper import is deferred ──────────────────────────────────────
33
53
  * `harper` is dynamic-imported inside the scan only (never a top-level import)
@@ -38,15 +58,9 @@
38
58
  * carry no harper dependency at all.
39
59
  */
40
60
  import { EMBEDDING_ENGINE, getModelId } from "./embeddings-provider.js";
61
+ import { TEST_FAULT_INJECTION_ENV, txnPausePoint } from "./txn-pause-point.js";
41
62
  // ─── Pure core (Harper-free) ────────────────────────────────────────────────
42
- /**
43
- * Stamps that denote "no real vector space" and so never contribute to the
44
- * uniformity set: an absent/empty stamp, and the legacy `hash-512d`
45
- * hash-fallback marker (a row with no genuine model embedding). A missing or
46
- * empty stored embedding cosines to a safe 0 (retrieval-core / dedup both
47
- * guard `Array.isArray(embedding) ? … : []`), never a cross-space garbage
48
- * score, so excluding these mirrors health.ts's own `realModels` filter.
49
- */
63
+ /** Stamps omitted from the space-bearing stamp set. */
50
64
  const NON_SPACE_STAMPS = new Set(["hash-512d"]);
51
65
  /**
52
66
  * Canonicalize an `embeddingModel` stamp to its ENGINE-QUALIFIED space id, or
@@ -93,11 +107,17 @@ export function isCurrentSpaceStamp(stamp, currentModelId) {
93
107
  const n = normalizeStamp(stamp);
94
108
  return n !== null && n === normalizeStamp(currentModelId);
95
109
  }
96
- /**
97
- * Pure: is every active (real-vector) stamp in the set the current space? An
98
- * empty set (fresh store) is uniform. No-vector stamps (null / `hash-512d`)
99
- * are ignored — they carry no cross-space cosine hazard.
100
- */
110
+ /** Pure: is the stored value an array or typed array, including an empty one? */
111
+ export function hasStoredVector(value) {
112
+ return Array.isArray(value) || (ArrayBuffer.isView(value) && !(value instanceof DataView));
113
+ }
114
+ /** Pure: is `stamp` EXACTLY one of the current space's raw forms? The vector
115
+ * query's stamp condition matches raw strings (Harper `equals`), so this is the
116
+ * comparison the admission rule makes — no trimming. */
117
+ export function isTrustedRawStamp(stamp, currentModelId) {
118
+ return typeof stamp === "string" && currentSpaceRawForms(currentModelId).includes(stamp);
119
+ }
120
+ /** Pure: are all space-bearing stamps current? An empty set is uniform. */
101
121
  export function isUniformStampSet(distinctStamps, currentModelId) {
102
122
  const current = normalizeStamp(currentModelId);
103
123
  for (const raw of distinctStamps) {
@@ -120,37 +140,135 @@ let _modelIdGetter = getModelId;
120
140
  // than caching a verdict we could not compute.
121
141
  let _uniform = undefined;
122
142
  let _activeStamps = []; // normalized, capped — for the degrade diagnostic only
143
+ // Rows with an array or typed array (empty included) and no trusted stamp in
144
+ // the last published scan. Null means no count has published.
145
+ let _excluded = null;
146
+ // Guard-notified writes that may change the count invalidate in-flight scans.
147
+ // A scan publishing a fresh count clears this flag.
148
+ let _excludedStale = false;
123
149
  let _lastScanAt = 0;
124
150
  let _scanning;
151
+ // flair#2481 — foreign-space write notes invalidate an in-flight scan's verdict.
152
+ let _writeEpoch = 0;
153
+ // flair#2530 — the bounded reason of the last failed scan that published, or
154
+ // null; cleared when a later scan publishes a verdict. It reads as
155
+ // `scan-failed` unless a foreign stamp is known, which makes the state `mixed`
156
+ // (see guardSnapshot).
157
+ let _lastScanError = null;
158
+ const _loggedScanErrorReasons = new Set();
159
+ // flair#2508 — scan-start ordering. `recomputeLatch()` (the boot pre-warm's
160
+ // path) runs `scan()` directly, bypassing the `_scanning` latch that serialises
161
+ // consult scans, so two scans can overlap; a scan that started earlier and
162
+ // finishes later must not overwrite the verdict of one that started later.
163
+ // Each scan takes the next sequence number when it begins and publishes only
164
+ // when no scan that started later has already published. When the write epoch
165
+ // is unchanged, a refused publish is named and writes nothing; when a foreign
166
+ // write changed the epoch, the #2481 check in scan() runs first instead,
167
+ // discarding the scan and resetting the retry timer. A failed scan's error
168
+ // (flair#2530) is an outcome under the same rules: it publishes, and advances
169
+ // `_publishedScanSeq`, only when no later-started scan has published.
170
+ let _scanSeq = 0;
171
+ let _publishedScanSeq = 0;
125
172
  // While the latch is TRIPPED, re-verify at most this often, so a completed
126
173
  // re-embed reopens the gate without paying a scan on every degraded query.
127
174
  // The happy (uniform) path never scans here at all — it returns in O(1).
128
175
  const RECHECK_MS = 30_000;
129
176
  const MAX_DIAG_STAMPS = 12;
130
177
  async function scan() {
131
- const current = normalizeStamp(_modelIdGetter());
178
+ const startEpoch = _writeEpoch;
179
+ const scanSeq = ++_scanSeq;
180
+ // Test-only: inert unless the fault-injection opt-in is set and this point is
181
+ // armed. It holds this scan before its read, so a consult that arrives while
182
+ // the boot pre-warm is parked observes the unknown (not-yet-verified) verdict
183
+ // a real boot window exposes.
184
+ const parked = txnPausePoint("space-guard-scan");
185
+ if (parked)
186
+ await parked;
187
+ const currentStamp = _modelIdGetter();
188
+ const currentNorm = normalizeStamp(currentStamp);
189
+ // The raw forms that denote the current space, compared EXACTLY as the vector
190
+ // query's stamp condition compares them (Harper `equals` applies no whitespace
191
+ // or prefix normalisation). The query's stamp condition filters a row whose raw
192
+ // stamp is not one of these from the returned set; HNSW can still compute that
193
+ // row's distance during traversal, so the protection at traversal level is this
194
+ // scan's verdict, not the condition.
195
+ const trustedRaw = new Set(currentSpaceRawForms(currentStamp));
132
196
  const seen = new Set();
133
197
  let uniform = true;
198
+ // Count every array or typed array without a trusted stamp, including empty ones.
199
+ let excluded = 0;
200
+ // Which half of the scan threw, for the bounded failure reason below.
201
+ let phase = "table";
134
202
  try {
135
203
  const table = await _tableGetter();
136
- // Project ONLY the stamp — never the vector — so the boot scan is far
137
- // cheaper than health.ts's existing full-record corpus read.
138
- for await (const row of table.search({ select: ["embeddingModel"] })) {
139
- const n = normalizeStamp(row.embeddingModel);
140
- if (n === null)
141
- continue;
142
- if (seen.size < MAX_DIAG_STAMPS)
143
- seen.add(n);
144
- if (n !== current)
145
- uniform = false;
204
+ phase = "read";
205
+ // Project the stamp and the vector attribute. Two rules, kept separate:
206
+ // - uniformity (flair#2481, unchanged): any space-bearing stamp that is not
207
+ // the current space makes the corpus `mixed`, whether or not the row
208
+ // stores a vector;
209
+ // - the excluded count (flair#2573): any array or typed array, empty included,
210
+ // without a trusted current-space stamp.
211
+ for await (const row of table.search({ select: ["embeddingModel", "embedding"] })) {
212
+ const rec = row;
213
+ const raw = typeof rec.embeddingModel === "string" ? rec.embeddingModel : null;
214
+ const n = normalizeStamp(raw);
215
+ if (n !== null) {
216
+ if (seen.size < MAX_DIAG_STAMPS)
217
+ seen.add(n);
218
+ if (n !== currentNorm)
219
+ uniform = false;
220
+ }
221
+ if (hasStoredVector(rec.embedding) && !(raw !== null && trustedRaw.has(raw)))
222
+ excluded++;
223
+ }
224
+ // Test-only: inert unless the fault-injection opt-in is set and this point
225
+ // is armed (flair#2508). It holds this scan after its read, so a scan that
226
+ // started later can read and publish before this one resumes.
227
+ const paused = txnPausePoint("scan-verdict");
228
+ if (paused)
229
+ await paused;
230
+ // A changed epoch discards this scan's verdict and makes the next consult rescan.
231
+ if (_writeEpoch !== startEpoch) {
232
+ _lastScanAt = 0;
233
+ return;
234
+ }
235
+ // flair#2508 — a scan that started later already published its verdict; this
236
+ // stale one must not overwrite it. Refused by name; nothing is written.
237
+ if (scanSeq < _publishedScanSeq) {
238
+ console.warn(`embedding-space-guard: stale scan verdict refused (scan ${scanSeq} superseded by scan ${_publishedScanSeq}); nothing written`);
239
+ return;
146
240
  }
147
241
  _activeStamps = [...seen];
148
242
  _uniform = uniform;
243
+ _excluded = excluded;
244
+ _excludedStale = false;
245
+ _publishedScanSeq = scanSeq;
149
246
  _lastScanAt = Date.now();
247
+ // A published verdict clears any earlier failed-scan state.
248
+ _lastScanError = null;
150
249
  }
151
250
  catch {
152
- // No live table yet (boot race) — leave the prior verdict untouched and
153
- // retry on the next consult. Never cache a verdict we couldn't compute.
251
+ // The same two checks as the verdict publish above, in the same order. A
252
+ // changed epoch discards this scan (flair#2481) — the foreign write already
253
+ // closed the gate.
254
+ if (_writeEpoch !== startEpoch) {
255
+ _lastScanAt = 0;
256
+ return;
257
+ }
258
+ // flair#2508 — a scan that started later already published its outcome; this
259
+ // stale failure must not turn that verdict back to unknown. Refused by name.
260
+ if (scanSeq < _publishedScanSeq) {
261
+ console.warn(`embedding-space-guard: stale scan failure refused (scan ${scanSeq} superseded by scan ${_publishedScanSeq}); nothing written`);
262
+ return;
263
+ }
264
+ // Record a bounded reason (never row content) and log each reason once; the
265
+ // prior verdict is left untouched and the consult schedule retries. The
266
+ // state now reads `scan-failed`, or stays `mixed` when a foreign stamp is
267
+ // known; either way consumers fail closed (flair#2530). The failure is this
268
+ // scan's published outcome, so an earlier-started scan that finishes later
269
+ // cannot clear it.
270
+ noteScanFailure(phase === "table" ? SCAN_ERROR_TABLE_UNAVAILABLE : SCAN_ERROR_SCAN_FAILED);
271
+ _publishedScanSeq = scanSeq;
154
272
  }
155
273
  }
156
274
  function runScan() {
@@ -158,48 +276,196 @@ function runScan() {
158
276
  _scanning = scan().finally(() => { _scanning = undefined; });
159
277
  return _scanning;
160
278
  }
279
+ /** The state-named warning a guard-degraded consumer surfaces when it refuses
280
+ * its embedding leg (flair#2530, flair#2559). The verdict is never `uniform`
281
+ * here (that state is never degraded), so the four cases are exactly the
282
+ * non-uniform states. Each names itself; the non-current-stamp wording is used
283
+ * ONLY for the `mixed` state. `response` says what the caller gets back:
284
+ * keyword-only results (the request has query text), no results (it has none),
285
+ * or an `explain` plan with no embedding leg. Shared by the recall leg
286
+ * (resources/SemanticSearch.ts) and MemoryBootstrap's task-relevant selection
287
+ * (resources/MemoryBootstrap.ts) so both name the state with ONE wording. */
288
+ export function spaceGuardWarning(v, response) {
289
+ const outcome = response === "keyword" ? "results are keyword-only"
290
+ : response === "none" ? "no results (the request has no query text to fall back on)"
291
+ : "the plan has no embedding leg";
292
+ if (v.state === "scan-failed") {
293
+ return `semantic search unavailable — embedding space unverified: last scan failed (${v.reason}); ${outcome}.`;
294
+ }
295
+ if (v.state === "unverified") {
296
+ return `semantic search unavailable — embedding space not yet verified; ${outcome}.`;
297
+ }
298
+ if (v.state === "excluded") {
299
+ return (`semantic search unavailable — the last scan found a stored vector with no trusted current-space stamp ` +
300
+ `(${v.excluded ?? "unknown"} row(s)); ${outcome}. Re-embed or remove the row`);
301
+ }
302
+ return (`semantic search unavailable — a non-current embedding model stamp was observed ` +
303
+ `(current: ${v.current}; found: ${v.found.join(", ")}); ${outcome}. ` +
304
+ `Reconcile to one space with: flair reembed --stale-only`);
305
+ }
306
+ /** Bounded, row-content-free reasons a scan can fail with. An error from the
307
+ * scan's table lookup or corpus read is classified into one of these; the raw
308
+ * message is never surfaced or logged. */
309
+ export const SCAN_ERROR_TABLE_UNAVAILABLE = "the Memory table was not available";
310
+ export const SCAN_ERROR_SCAN_FAILED = "the Memory corpus scan failed";
311
+ /** Record a scan failure: remember the bounded reason and log each reason ONCE.
312
+ * The consult schedule retries unchanged; this only names the state. Never
313
+ * logs the raw error (which could carry row content). */
314
+ function noteScanFailure(reason) {
315
+ _lastScanError = reason;
316
+ if (_loggedScanErrorReasons.has(reason))
317
+ return;
318
+ _loggedScanErrorReasons.add(reason);
319
+ console.warn(`embedding-space-guard: corpus scan failed (${reason}); ` +
320
+ `the store is not known to be uniform until a scan succeeds`);
321
+ }
322
+ /** Read the verdict + its state together, without scanning. Callers must not
323
+ * use this to decide AND expect it to reflect a scan they just started. */
324
+ function guardSnapshot() {
325
+ const current = normalizeStamp(_modelIdGetter()) ?? _modelIdGetter();
326
+ const found = [..._activeStamps];
327
+ const excluded = _excluded;
328
+ // A known foreign stamp comes first, so no failed scan, earlier or later,
329
+ // turns the `mixed` state into an advisory `scan-failed`; the error rides in `reason`.
330
+ if (_uniform === false)
331
+ return { uniform: false, state: "mixed", reason: _lastScanError, current, found, excluded };
332
+ if (_lastScanError !== null) {
333
+ return { uniform: false, state: "scan-failed", reason: _lastScanError, current, found, excluded };
334
+ }
335
+ // flair#2573 — a guard-notified write may have changed the count since
336
+ // publication. An unknown count fails closed until a scan republishes.
337
+ if (_excludedStale)
338
+ return { uniform: false, state: "unverified", reason: null, current, found, excluded };
339
+ if (_uniform === true) {
340
+ if (excluded !== null && excluded > 0) {
341
+ // The scan found an array or typed array without a trusted stamp and no foreign space-bearing stamp.
342
+ return { uniform: false, state: "excluded", reason: null, current, found, excluded };
343
+ }
344
+ return { uniform: true, state: "uniform", reason: null, current, found, excluded };
345
+ }
346
+ return { uniform: false, state: "unverified", reason: null, current, found, excluded };
347
+ }
348
+ /** The consult decision. Fails closed and never awaits an in-flight scan: an
349
+ * unknown verdict must be reported NOW (the caller takes its mixed-space path).
350
+ * Non-uniform verdicts trigger rescans immediately when unknown or stale,
351
+ * otherwise after RECHECK_MS.
352
+ * The snapshot is taken synchronously, so the state cannot drift from the
353
+ * decision. */
354
+ function consultGuard() {
355
+ if (guardSnapshot().uniform)
356
+ return guardSnapshot();
357
+ if (_uniform === undefined || _excludedStale || Date.now() - _lastScanAt >= RECHECK_MS) {
358
+ void runScan();
359
+ }
360
+ return guardSnapshot();
361
+ }
362
+ /** Returns the guard verdict: only a successful scan with no excluded arrays or
363
+ * typed arrays and no foreign space-bearing stamps permits the embedding leg. */
364
+ export function isEmbeddingSpaceUniform() {
365
+ return Promise.resolve(consultGuard().uniform);
366
+ }
161
367
  /**
162
- * THE single chokepoint. Returns true when the store is uniform in the current
163
- * embedding space (safe to cosine the query/candidate against stored vectors),
164
- * false when it is not (a mixed-space corpus — the caller must NOT cosine).
165
- *
166
- * O(1) on the happy path: once known-uniform, no scan, no allocation. Only
167
- * (re)scans when the latch is unknown (pre-boot) or tripped-and-stale.
368
+ * flair#2573 slice 1 — is `stamp` a trusted current-space model stamp for the
369
+ * configured model? True only for a space-bearing stamp that denotes the current
370
+ * space (the engine-qualified id or its bare-name equivalent), compared exactly
371
+ * as the vector query's stamp condition compares it. An absent stamp, the
372
+ * `hash-512d` marker and a foreign model are all untrusted. Reads the injectable
373
+ * model-id getter so tests can pin the space. Metadata compare only (never a
374
+ * vector-byte comparison).
168
375
  */
169
- export async function isEmbeddingSpaceUniform() {
170
- if (_uniform === true)
171
- return true;
172
- if (_uniform === undefined || Date.now() - _lastScanAt >= RECHECK_MS) {
173
- await runScan();
174
- }
175
- return _uniform ?? true;
376
+ export function isTrustedVectorStamp(stamp) {
377
+ return isTrustedRawStamp(stamp, _modelIdGetter());
176
378
  }
177
379
  /**
178
- * Write-maintained trip: a persisted FOREIGN-space stamp closes the gate
179
- * immediately, no rescan. A normal local write always stamps the current id
180
- * (`getModelId()`), so it never trips; only a federation/replication write or
181
- * an explicit-stamp PUT carrying another space's stamp does.
380
+ * flair#2573 slice 1 — the Harper condition matching rows whose `embeddingModel`
381
+ * is one of the current space's raw forms. This is DEFENCE IN DEPTH: the guard's
382
+ * verdict is the load-bearing exclusion (a non-uniform verdict makes every
383
+ * consumer refuse the embedding leg), and a query `conditions` entry cannot keep
384
+ * a vector out of Harper's HNSW traversal — its distance is computed before an
385
+ * admission condition is applied. Used as an ADDITIONAL condition on a vector
386
+ * (HNSW) query ONLY — never folded into the caller's `conditions`, which also
387
+ * drive the lexical leg (a row with an untrusted stamp remains eligible for
388
+ * lexical matching).
182
389
  */
183
- export function noteWriteStamp(stamp) {
184
- const n = normalizeStamp(stamp);
185
- if (n === null)
186
- return;
187
- if (n !== normalizeStamp(_modelIdGetter())) {
390
+ export function trustedVectorCondition() {
391
+ return {
392
+ operator: "or",
393
+ conditions: currentSpaceRawForms(_modelIdGetter()).map((value) => ({
394
+ attribute: "embeddingModel",
395
+ comparator: "equals",
396
+ value,
397
+ })),
398
+ };
399
+ }
400
+ /** The full verdict for a consumer that must NAME the state it degraded on
401
+ * (the recall leg's `_warning`). Decision and state are captured together, so
402
+ * the state cannot drift from the decision under a concurrent scan. Fails
403
+ * closed exactly as `isEmbeddingSpaceUniform()` does. */
404
+ export function embeddingSpaceVerdict() {
405
+ return Promise.resolve(consultGuard());
406
+ }
407
+ /** The guard state for an operator surface (`flair doctor` via /Health), without
408
+ * running a scan. Never blocks, never reads a vector. */
409
+ export function spaceGuardState() {
410
+ const v = guardSnapshot();
411
+ return { state: v.state, reason: v.reason, excluded: v.excluded };
412
+ }
413
+ /**
414
+ * Call after persisting a vector or embeddingModel write, passing the resulting
415
+ * stamp (possibly absent) and the row the write replaced: `null` when there was
416
+ * none, omitted when the caller did not read it. Metadata-only PATCHes must not
417
+ * call this hook. A write invalidates the count when its stamp is untrusted or it
418
+ * may repair an untrusted vector: the replaced row stored one, or the replaced
419
+ * row is unknown while the verdict is non-uniform. A trusted write over a known
420
+ * row with no untrusted vector leaves the published count, and so the state,
421
+ * as it was. A foreign space also closes the latch.
422
+ */
423
+ export function noteWriteStamp(stamp, previous) {
424
+ let n;
425
+ let current;
426
+ try {
427
+ const currentStamp = _modelIdGetter();
428
+ const replacesUntrusted = hasStoredVector(previous?.embedding) &&
429
+ !isTrustedRawStamp(typeof previous?.embeddingModel === "string" ? previous.embeddingModel : null, currentStamp);
430
+ if (isTrustedRawStamp(stamp, currentStamp) && !replacesUntrusted &&
431
+ (previous !== undefined || guardSnapshot().uniform))
432
+ return;
433
+ n = normalizeStamp(stamp);
434
+ current = normalizeStamp(currentStamp);
435
+ }
436
+ catch (err) {
437
+ // The stamp could not be read against the current space: fail closed, as
438
+ // for any other unreadable state, and invalidate an in-flight scan.
439
+ _uniform = false;
440
+ _excludedStale = true;
441
+ _writeEpoch++;
442
+ throw err;
443
+ }
444
+ // This notified write may change the excluded count. Invalidate an in-flight
445
+ // scan; the next published scan clears the stale flag.
446
+ _excludedStale = true;
447
+ _writeEpoch++;
448
+ // A space-bearing, non-current stamp additionally trips the uniformity latch
449
+ // now, with no rescan, and is named in the diagnostic.
450
+ if (n !== null && n !== current) {
188
451
  if (!_activeStamps.includes(n) && _activeStamps.length < MAX_DIAG_STAMPS)
189
452
  _activeStamps.push(n);
190
453
  _uniform = false;
191
454
  }
192
455
  }
193
456
  /**
194
- * Force a fresh corpus scan and return the resulting uniformity. The explicit
195
- * "re-embed completion clears it" primitive — used by the boot pre-warm, and
196
- * callable after a bulk re-embed to reopen the gate promptly rather than
197
- * waiting out RECHECK_MS.
457
+ * Force a fresh corpus scan, then return the current published latch
458
+ * decision: true only when the latch reads verified uniform with no scan error.
459
+ * The explicit "re-embed completion clears it" primitive — used by the boot
460
+ * pre-warm, and callable after a bulk re-embed to reopen the gate promptly
461
+ * rather than waiting out RECHECK_MS. A later-started scan may have published
462
+ * that decision, so it does not say whether THIS scan succeeded.
198
463
  */
199
464
  export async function recomputeLatch() {
200
465
  _lastScanAt = 0; // bypass the throttle
201
466
  await scan();
202
- return _uniform ?? true;
467
+ // Any excluded array or typed array makes the verdict non-uniform.
468
+ return _uniform === true && _lastScanError === null && !_excludedStale && (_excluded === null || _excluded === 0);
203
469
  }
204
470
  /**
205
471
  * Structured diagnostic for the degrade path — the current space id and the
@@ -213,15 +479,34 @@ export function spaceGuardDiagnostics() {
213
479
  // ─── Boot pre-warm (module side effect) ──────────────────────────────────────
214
480
  // Best-effort, single-shot, deferred to after the current synchronous load
215
481
  // phase (same setImmediate convention as migration-boot.ts). If it fires
216
- // before the Memory table is live, the scan silently no-ops and the first real
217
- // consult computes the latch lazily — correctness never depends on this
218
- // pre-warm, only the first query's latency does.
482
+ // before the Memory table is live, the scan fails (`scan-failed`) and a later
483
+ // consult rescans — correctness never depends on this pre-warm (fail-closed
484
+ // either way); it only decides whether the first queries serve embeddings or
485
+ // take the mixed-space path until a scan completes.
219
486
  let _prewarmScheduled = false;
487
+ // Settles when the most recently scheduled pre-warm's scan has finished,
488
+ // whatever its outcome. Read only through `_prewarmSettledForTests()`.
489
+ let _prewarmSettled;
220
490
  export function scheduleSpaceGuardPrewarm() {
221
491
  if (_prewarmScheduled)
222
492
  return;
223
493
  _prewarmScheduled = true;
224
- setImmediate(() => { void recomputeLatch().catch(() => { }); });
494
+ _prewarmSettled = new Promise((resolve) => {
495
+ setImmediate(() => { void recomputeLatch().catch(() => { }).then(() => resolve()); });
496
+ });
497
+ }
498
+ /**
499
+ * Test-only barrier (flair#2508): resolves once the most recently scheduled
500
+ * pre-warm's scan has finished, so a test can wait for it before it injects a
501
+ * table getter or arms a pause point. Gated like the pause points: returns
502
+ * `undefined` unless the fault-injection opt-in
503
+ * (`FLAIR_ENABLE_TEST_FAULT_INJECTION=1`) is set, and also when no pre-warm
504
+ * was ever scheduled.
505
+ */
506
+ export function _prewarmSettledForTests(env = process.env) {
507
+ if (env[TEST_FAULT_INJECTION_ENV] !== "1")
508
+ return undefined;
509
+ return _prewarmSettled;
225
510
  }
226
511
  // Test-only seams — mirror embeddings-boot.ts's `_resetEmbeddingsBackendRegistrationForTests`.
227
512
  export function _setGuardTableGetterForTests(fn) { _tableGetter = fn; }
@@ -231,8 +516,17 @@ export function _resetGuardForTests() {
231
516
  _modelIdGetter = getModelId;
232
517
  _uniform = undefined;
233
518
  _activeStamps = [];
519
+ _excluded = null;
520
+ _excludedStale = false;
234
521
  _lastScanAt = 0;
235
522
  _scanning = undefined;
523
+ _writeEpoch = 0;
524
+ _lastScanError = null;
525
+ _loggedScanErrorReasons.clear();
526
+ _scanSeq = 0;
527
+ _publishedScanSeq = 0;
528
+ // `_prewarmSettled` is kept: a reset cannot cancel a pre-warm that is already
529
+ // scheduled, so its barrier must stay awaitable.
236
530
  _prewarmScheduled = false;
237
531
  }
238
532
  scheduleSpaceGuardPrewarm();
@@ -0,0 +1,53 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { ENGINE_VERSION_STAMP } from "../src/engine-version-contract.js";
7
+ /** The flair package root (`<pkg>/dist/resources/x.js` → `<pkg>`). */
8
+ function packageRoot() {
9
+ return resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
10
+ }
11
+ /** Attempt to stamp the data directory. */
12
+ export function stampEngineVersionOnBoot(dataDir = process.env.ROOTPATH || join((process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME) || homedir(), ".flair", "data")) {
13
+ try {
14
+ if (!existsSync(dataDir))
15
+ return;
16
+ for (const name of ["harper", "@harperfast/harper"]) {
17
+ let version;
18
+ try {
19
+ const pkgPath = join(packageRoot(), "node_modules", ...name.split("/"), "package.json");
20
+ version = JSON.parse(readFileSync(pkgPath, "utf8")).version;
21
+ }
22
+ catch {
23
+ continue;
24
+ }
25
+ if (version) {
26
+ const stampPath = join(dataDir, ENGINE_VERSION_STAMP);
27
+ const temporary = `${stampPath}.${process.pid}.${randomUUID()}.tmp`;
28
+ let fd;
29
+ try {
30
+ fd = openSync(temporary, "wx", 0o600);
31
+ writeFileSync(fd, `${version}\n`, "utf8");
32
+ fsyncSync(fd);
33
+ closeSync(fd);
34
+ fd = undefined;
35
+ renameSync(temporary, stampPath);
36
+ }
37
+ finally {
38
+ if (fd !== undefined)
39
+ closeSync(fd);
40
+ try {
41
+ unlinkSync(temporary);
42
+ }
43
+ catch { }
44
+ }
45
+ return;
46
+ }
47
+ }
48
+ }
49
+ catch {
50
+ // Best-effort: a stamp write is never allowed to fail a boot.
51
+ }
52
+ }
53
+ stampEngineVersionOnBoot();