@tpsdev-ai/flair 0.56.0 → 0.58.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 (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
@@ -0,0 +1,289 @@
1
+ /**
2
+ * replay-store.ts — the ONE instance-wide check-and-record behind both replay
3
+ * guards (flair#2061, slice S1a of flair#2052):
4
+ *
5
+ * - agent auth (TPS-Ed25519), key `a:<agentId>:<nonce>` — the auth gate
6
+ * (auth-middleware.ts), the per-resource fallback (agent-auth.ts) and the
7
+ * Presence heartbeat (Presence.ts);
8
+ * - federation body signatures, key `f:<nonce>` — FederationPair and
9
+ * FederationSync (Federation.ts, via verifyFederationRequestBody).
10
+ *
11
+ * The record of truth is the local `ReplayNonce` table (schemas/replay.graphql:
12
+ * `replicate: false`, `expiration: 120`). Every Harper thread of this instance
13
+ * reads and writes the same rows. Per-thread memory holds only keys this thread
14
+ * has seen recorded — its own write, or a row it read back from the store: it
15
+ * may refuse early on a HIT, and a MISS always goes to the store.
16
+ *
17
+ * Check-and-record, `recordOnce()` (wrapped by each guard's `claim()`):
18
+ * 1. `tryLock([REPLAY_LOCK_NAMESPACE, key])` on the table's primary store. The
19
+ * lock is per key and shared by every thread of the process. Not acquired
20
+ * means another claim of the same key is in progress: "contended". The
21
+ * guard refuses that request as a replay but does not remember the key,
22
+ * because the other claim may still fail to write it.
23
+ * 2. Read the key fresh (`getEntry`; on LMDB the thread's cached read snapshot
24
+ * is dropped first). Present: "replay".
25
+ * 3. `put` the row in its OWN transaction and await the commit.
26
+ * 4. `unlock` in `finally` — only a lock this call acquired.
27
+ * Anything thrown, and any gap in the store contract below, is "unavailable",
28
+ * and every caller REFUSES the request on it. Nothing falls back to memory.
29
+ *
30
+ * Harper 5.2.8 has no conditional create that is atomic across threads; the
31
+ * per-key lock is the primitive that serialises the read with the write (Harper
32
+ * uses it the same way for source-fill de-duplication). The lock space is
33
+ * database-wide on RocksDB, so the key is namespaced.
34
+ *
35
+ * Callers claim a key only AFTER the request's signature has verified, and
36
+ * BEFORE the request has any effect.
37
+ *
38
+ * Eviction is Harper's table expiration: its scan runs on the last worker only,
39
+ * so once per instance, and removes a row no earlier than REPLAY_RETENTION_MS
40
+ * after it was written. A key stays acceptable to its window check for at most
41
+ * 2 × window after it is first recorded, so the retention must exceed twice
42
+ * every window that uses the store; a guard whose window does not fit is
43
+ * unavailable. `primaryStore` is not a documented Harper API: its methods are
44
+ * checked on every claim, reported once per worker at boot, and pinned against
45
+ * the installed Harper by test/unit-isolated/replay-store.test.ts.
46
+ */
47
+ import { databases } from "harper";
48
+ import { WINDOW_MS } from "./ed25519-auth.js";
49
+ import { FEDERATION_WINDOW_MS, verifyBodySignatureFreshOnce } from "./federation-crypto.js";
50
+ /** The table name in the `flair` database (schemas/replay.graphql). */
51
+ export const REPLAY_TABLE = "ReplayNonce";
52
+ /**
53
+ * Seconds a row is kept. MUST equal `expiration:` on `type ReplayNonce` in
54
+ * schemas/replay.graphql (pinned by test/unit-isolated/replay-store.test.ts).
55
+ */
56
+ export const REPLAY_RETENTION_S = 120;
57
+ export const REPLAY_RETENTION_MS = REPLAY_RETENTION_S * 1000;
58
+ /** First element of every lock key, so no other lock on the database collides. */
59
+ export const REPLAY_LOCK_NAMESPACE = "flair-replay";
60
+ /** Named refusal state: the store cannot be used, so signed requests are refused. */
61
+ export class ReplayStoreUnavailable extends Error {
62
+ gap;
63
+ constructor(gap) {
64
+ super(`ReplayStoreUnavailable: ${gap}`);
65
+ this.name = "ReplayStoreUnavailable";
66
+ this.gap = gap;
67
+ }
68
+ }
69
+ /** Harper's `transaction` is assigned onto the global at load (as in request-transaction.ts). */
70
+ export function harperReplayDeps() {
71
+ return {
72
+ table: databases?.flair?.[REPLAY_TABLE],
73
+ transaction: globalThis.transaction,
74
+ };
75
+ }
76
+ const STORE_METHODS = ["tryLock", "unlock", "getEntry"];
77
+ /**
78
+ * What stops the store from being used, or null. Checks the table, the three
79
+ * primary-store methods the claim relies on, the table's `put`, Harper's
80
+ * `transaction`, and — when the table reports its expiration — that rows
81
+ * outlive twice `windowMs`.
82
+ */
83
+ export function replayStoreContractGap(deps, windowMs) {
84
+ const table = deps?.table;
85
+ if (!table)
86
+ return `table flair.${REPLAY_TABLE} is not defined`;
87
+ const store = table.primaryStore;
88
+ if (!store)
89
+ return `flair.${REPLAY_TABLE} has no primaryStore`;
90
+ for (const m of STORE_METHODS) {
91
+ if (typeof store[m] !== "function")
92
+ return `flair.${REPLAY_TABLE}.primaryStore.${m} is not a function`;
93
+ }
94
+ if (typeof table.put !== "function")
95
+ return `flair.${REPLAY_TABLE}.put is not a function`;
96
+ if (typeof deps.transaction !== "function")
97
+ return "Harper's transaction() is not available";
98
+ if (windowMs !== undefined) {
99
+ const expirationMs = table.expirationMS;
100
+ if (typeof expirationMs === "number" && expirationMs > 0 && expirationMs <= 2 * windowMs) {
101
+ return `flair.${REPLAY_TABLE} keeps rows ${expirationMs} ms, not longer than twice the ${windowMs} ms window`;
102
+ }
103
+ }
104
+ return null;
105
+ }
106
+ /**
107
+ * Why a window cannot use the store, or null. `source` names where the window
108
+ * comes from (an env variable), so the refusal says what to change.
109
+ */
110
+ export function replayWindowGap(windowMs, source) {
111
+ const what = source ? `replay window ${windowMs} ms (${source})` : `replay window ${windowMs} ms`;
112
+ if (!Number.isFinite(windowMs) || windowMs <= 0)
113
+ return `${what} is not a positive number`;
114
+ if (2 * windowMs >= REPLAY_RETENTION_MS) {
115
+ return `${what} must be below ${REPLAY_RETENTION_MS / 2} ms: flair.${REPLAY_TABLE} keeps a nonce ${REPLAY_RETENTION_MS} ms, and that must exceed twice the window`;
116
+ }
117
+ return null;
118
+ }
119
+ /**
120
+ * The atomic check-and-record. Resolves "recorded" when this call writes the
121
+ * key's row (one claim per key, across every thread of the instance), "replay"
122
+ * when the row is already in the store, and "contended" when another claim of
123
+ * `key` holds its lock. THROWS on a contract gap or any store error;
124
+ * `ReplayGuard.claim` turns that into "unavailable".
125
+ */
126
+ export async function recordOnce(key, seenAt, deps) {
127
+ const gap = replayStoreContractGap(deps);
128
+ if (gap)
129
+ throw new ReplayStoreUnavailable(gap);
130
+ const { table, transaction } = deps;
131
+ const store = table.primaryStore;
132
+ const lockKey = [REPLAY_LOCK_NAMESPACE, key];
133
+ if (!store.tryLock(lockKey))
134
+ return "contended";
135
+ try {
136
+ store.resetReadTxn?.();
137
+ if (store.getEntry(key) != null)
138
+ return "replay";
139
+ await transaction({}, () => table.put({ id: key, seenAt }));
140
+ return "recorded";
141
+ }
142
+ finally {
143
+ store.unlock(lockKey);
144
+ }
145
+ }
146
+ // ─── Refusal logging (bounded) ─────────────────────────────────────────────
147
+ const LOG_INTERVAL_MS = 10_000;
148
+ const lastLogged = new Map();
149
+ function noteUnavailable(scope, err) {
150
+ const reason = err instanceof ReplayStoreUnavailable
151
+ ? err.message
152
+ : `ReplayStoreUnavailable: store error (${err?.constructor?.name ?? "Error"}: ${String(err?.message ?? err).slice(0, 200)})`;
153
+ const tag = `${scope}|${reason}`;
154
+ const now = Date.now();
155
+ if (now - (lastLogged.get(tag) ?? 0) < LOG_INTERVAL_MS)
156
+ return;
157
+ if (lastLogged.size > 64)
158
+ lastLogged.clear();
159
+ lastLogged.set(tag, now);
160
+ console.error(`[flair-replay] ${reason}. Every ${scope === "a" ? "TPS-Ed25519" : "federation"} signed request is refused until the ` +
161
+ `flair.${REPLAY_TABLE} store is usable (see resources/replay-store.ts).`);
162
+ }
163
+ export function createReplayGuard(opts) {
164
+ const { scope, windowMs, windowSource } = opts;
165
+ const resolveDeps = opts.deps ?? harperReplayDeps;
166
+ const cacheLimit = opts.cacheLimit ?? 100_000;
167
+ const windowGap = replayWindowGap(windowMs, windowSource);
168
+ // A key can pass its window check for at most 2 × window after it is first
169
+ // recorded; past that a memory entry can no longer refuse anything.
170
+ const cacheTtlMs = 2 * windowMs;
171
+ const seen = new Map();
172
+ let lastPrune = 0;
173
+ function prune(now) {
174
+ if (now - lastPrune < 1000 && seen.size < cacheLimit)
175
+ return;
176
+ lastPrune = now;
177
+ for (const [k, t] of seen)
178
+ if (now - t > cacheTtlMs)
179
+ seen.delete(k);
180
+ if (seen.size >= cacheLimit)
181
+ seen.clear();
182
+ }
183
+ return {
184
+ scope,
185
+ windowMs,
186
+ windowSource,
187
+ knownReplay(key, now = Date.now()) {
188
+ prune(now);
189
+ return seen.has(`${scope}:${key}`);
190
+ },
191
+ async claim(key, now = Date.now()) {
192
+ const full = `${scope}:${key}`;
193
+ try {
194
+ if (windowGap)
195
+ throw new ReplayStoreUnavailable(windowGap);
196
+ const deps = resolveDeps();
197
+ const gap = replayStoreContractGap(deps, windowMs);
198
+ if (gap)
199
+ throw new ReplayStoreUnavailable(gap);
200
+ const outcome = await recordOnce(full, now, deps);
201
+ // A contended key is refused for this request but not remembered: the
202
+ // claim holding its lock may still fail to write it, and the next
203
+ // presentation must be decided by the store.
204
+ if (outcome === "contended")
205
+ return "replay";
206
+ // Remembered only once the store has confirmed the row: written here,
207
+ // or read back from it.
208
+ prune(now);
209
+ seen.set(full, now);
210
+ return outcome;
211
+ }
212
+ catch (err) {
213
+ noteUnavailable(scope, err);
214
+ return "unavailable";
215
+ }
216
+ },
217
+ resetCacheForTest() {
218
+ seen.clear();
219
+ lastPrune = 0;
220
+ },
221
+ };
222
+ }
223
+ // ─── The two guards ────────────────────────────────────────────────────────
224
+ /** Agent auth (TPS-Ed25519). Key `a:<agentId>:<nonce>`. */
225
+ export const agentReplayGuard = createReplayGuard({
226
+ scope: "a",
227
+ windowMs: WINDOW_MS,
228
+ windowSource: "FLAIR_AGENT_AUTH_WINDOW_MS",
229
+ });
230
+ /** Federation body signatures. Key `f:<nonce>`. */
231
+ export const federationReplayGuard = createReplayGuard({ scope: "f", windowMs: FEDERATION_WINDOW_MS });
232
+ function agentKey(agentId, nonce) {
233
+ return `${agentId}:${nonce}`;
234
+ }
235
+ /**
236
+ * Memory HIT short-circuit for agent auth. May run before the signature is
237
+ * verified; a false says nothing and the request still has to claim.
238
+ */
239
+ export function isKnownAgentReplay(agentId, nonce, now = Date.now()) {
240
+ return agentReplayGuard.knownReplay(agentKey(agentId, nonce), now);
241
+ }
242
+ /**
243
+ * Claim (agentId, nonce) for this request, instance-wide. Call it after the
244
+ * signature has verified and before the request has any effect; refuse on
245
+ * anything but `{ ok: true }`.
246
+ */
247
+ export async function claimAgentNonce(agentId, nonce, now = Date.now()) {
248
+ const verdict = await agentReplayGuard.claim(agentKey(agentId, nonce), now);
249
+ if (verdict === "recorded")
250
+ return { ok: true };
251
+ if (verdict === "replay")
252
+ return { ok: false, error: "nonce_replay_detected", status: 401 };
253
+ return { ok: false, error: "replay_store_unavailable", status: 503 };
254
+ }
255
+ /**
256
+ * The federation endpoints' check (FederationPair, FederationSync): signature,
257
+ * freshness, then the nonce claimed instance-wide. Refuse on anything but ok.
258
+ */
259
+ export function verifyFederationRequestBody(body, publicKeyB64url) {
260
+ return verifyBodySignatureFreshOnce(body, publicKeyB64url, {
261
+ windowMs: FEDERATION_WINDOW_MS,
262
+ replay: federationReplayGuard,
263
+ });
264
+ }
265
+ // ─── Boot report ───────────────────────────────────────────────────────────
266
+ /** Every gap that would refuse requests on this thread, or an empty list. */
267
+ export function replayStoreBootGaps(deps = harperReplayDeps()) {
268
+ const gaps = [];
269
+ for (const g of [agentReplayGuard, federationReplayGuard]) {
270
+ const gap = replayWindowGap(g.windowMs, g.windowSource) ?? replayStoreContractGap(deps, g.windowMs);
271
+ if (gap)
272
+ gaps.push(`${g.scope === "a" ? "agent auth" : "federation"}: ${gap}`);
273
+ }
274
+ return gaps;
275
+ }
276
+ // Once per worker thread, after the schema's tables are bound. Harper defines
277
+ // `server.workerCount` on worker threads; unit tests and the CLI never reach it.
278
+ if (typeof setTimeout !== "undefined" && typeof globalThis.server?.workerCount === "number") {
279
+ setTimeout(() => {
280
+ try {
281
+ for (const gap of replayStoreBootGaps()) {
282
+ console.error(`[flair-replay] ReplayStoreUnavailable at boot (${gap}). Signed requests on this path are refused.`);
283
+ }
284
+ }
285
+ catch (err) {
286
+ console.error(`[flair-replay] ReplayStoreUnavailable at boot: ${err?.message ?? err}`);
287
+ }
288
+ }, 0);
289
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * request-transaction.ts — one shared write scope for the host-pointer path
3
+ * (flair#1940 slice 1). A Memory row and its `MemoryHostSource` pointer row
4
+ * must commit together or not at all. When a request carries an open,
5
+ * joinable transaction, both writes join it (the request owns commit). When it
6
+ * does NOT — an internal caller with no request context, e.g. a direct
7
+ * `new Memory().post(...)` — the Memory write would otherwise commit
8
+ * immediately on its own and a failed pointer write would leave a row without
9
+ * its pointer. {@link withSharedWriteTransaction} creates that missing
10
+ * transaction with Harper's `transaction(ctx, cb)` (dist/resources/
11
+ * transaction.js), which creates one when absent and owns its commit/abort.
12
+ * If Harper's transaction function is NOT available, this THROWS — an unwrapped
13
+ * write could commit the Memory row before its pointer write fails, which A7
14
+ * forbids. There is no silent fallback.
15
+ *
16
+ * Pinned by test/unit/memory-host-source.test.ts (r20-atomic) for the owned
17
+ * transaction the context-less path needs, and by
18
+ * test/unit/host-pointer-round7.test.ts (tx1) for the throw — each fails if the
19
+ * branch it names is removed.
20
+ */
21
+ /** Harper's own `isJoinableScope` (DatabaseTransaction.ts): OPEN and not a
22
+ * self-committing link. A context with no such transaction needs one. */
23
+ export function isJoinableTransaction(ctx) {
24
+ const t = ctx?.transaction;
25
+ return !!t && t.open === 1 && !t.saveCommits;
26
+ }
27
+ /** The `transaction` helper Harper assigns onto the GLOBAL at load
28
+ * (`global.transaction`). Read from the global so it is robust to the
29
+ * shared-process `mock.module` race; the unit mock sets the same global. */
30
+ function harperTransaction() {
31
+ const g = globalThis?.transaction;
32
+ return typeof g === "function" ? g : undefined;
33
+ }
34
+ /**
35
+ * Run `fn` so every write it performs shares ONE transaction, and hand `fn` the
36
+ * context object the writes must be given. If `ctx` already carries a JOINABLE
37
+ * (OPEN, not self-committing) transaction, `fn` joins it — the request owns
38
+ * commit/abort. A CLOSED transaction left on the chain by a drained generator
39
+ * is NOT joined (that is the detached-transaction discipline in
40
+ * table-helpers.ts); a fresh, owned transaction is created instead. Otherwise
41
+ * Harper creates and owns a transaction around `fn` — which is what makes an
42
+ * internal, context-less caller atomic. When Harper's transaction function is
43
+ * unavailable this THROWS (no unwrapped fallback).
44
+ *
45
+ * Pinned by test/unit/memory-host-source.test.ts (r20-atomic) — the owned
46
+ * branch for a context-less internal create — and by
47
+ * test/unit/host-pointer-round7.test.ts (tx1) — the missing-function throw.
48
+ */
49
+ export async function withSharedWriteTransaction(ctx, fn) {
50
+ const shared = ctx ?? {};
51
+ if (isJoinableTransaction(shared))
52
+ return fn(shared);
53
+ const txn = harperTransaction();
54
+ if (!txn) {
55
+ throw new Error("flair: Harper's transaction() is unavailable — refusing to run a Memory/pointer write unwrapped (A7: no silent loss)");
56
+ }
57
+ return (await txn(shared, () => fn(shared)));
58
+ }
59
+ /**
60
+ * Run `fn` in a transaction this call OWNS even when `ctx` already carries an
61
+ * open request transaction. Used for a batch operation (the MemoryMaintenance
62
+ * expiry/archive arms and the orphan sweep) where one item's failure must abort
63
+ * only THAT item, not the whole request. The request transaction is detached
64
+ * for `fn` (a fresh, owned one is created) and restored afterwards; the owned
65
+ * transaction commits or aborts when `fn` settles.
66
+ */
67
+ export async function withOwnedTransaction(ctx, fn) {
68
+ if (!ctx)
69
+ return withSharedWriteTransaction(ctx, fn);
70
+ const saved = ctx.transaction;
71
+ ctx.transaction = undefined;
72
+ try {
73
+ return await withSharedWriteTransaction(ctx, fn);
74
+ }
75
+ finally {
76
+ ctx.transaction = saved;
77
+ }
78
+ }
@@ -7,9 +7,9 @@
7
7
  * 1. Boot window — jsResources register incrementally. /Health can be up
8
8
  * while /Memory and /SemanticSearch still 404 from Harper's catch-all
9
9
  * (documented in packages/adk-flair-js/test/helpers/boot-harper.mjs).
10
- * 2. Cold BM25 index — hybrid retrieval's persistent index is lazy-built
11
- * on the first search, not at component start (bm25-index-service.ts).
12
- * That first-query corpus scan grows with store size. /Health answering
10
+ * 2. BM25 index still empty or building — the persistent index warms in
11
+ * the background after embeddings boot (bm25-index-service.ts). Until
12
+ * that build finishes, a text search waits for it. /Health answering
13
13
  * is not "recall is warm."
14
14
  *
15
15
  * This module is Harper-free so the decision is unit-testable against the
@@ -20,14 +20,14 @@
20
20
  * - Routes/table not mounted → not healthy (ok:false, HTTP 503). A
21
21
  * traffic-gating probe that only looks at status must not get a green
22
22
  * light for a node whose search routes are not serving.
23
- * - Routes up but index still cold → process is live (ok:true, HTTP 200)
24
- * and searchReady:false names the lag. We do NOT 503 on a cold index:
25
- * the index builds on the first search, and a health check must not
26
- * trigger that scan (bm25-index-service.ts: "Eager building would add a
27
- * full corpus scan to every boot including … health checks"). 503-until-
28
- * warm would deadlock — health waits for the index, the index waits for
29
- * a search that never comes.
23
+ * - Routes up but the BM25 index is still empty or building → process is
24
+ * live (ok:true, HTTP 200) and searchReady:false names the lag. We do
25
+ * NOT 503 on an unready index: a health check must not be what builds
26
+ * it, and 503-until-warm would make a traffic gate wait on a scan the
27
+ * gate itself is not supposed to run. The background warm (or a text
28
+ * search) is what clears `empty`.
30
29
  */
30
+ import { bm25SearchLagReason } from "./bm25-status.js";
31
31
  /**
32
32
  * How a ready result was verified. Constant strings — no interpolation
33
33
  * (flair#1411). Public /Health still omits this field when searchReady is
@@ -80,22 +80,26 @@ export function resolveSearchReadiness(opts) {
80
80
  if (!opts.memoryTable || typeof opts.memoryTable.search !== "function") {
81
81
  return notServing("memory table not queryable");
82
82
  }
83
- // Hybrid + the persistent index are default-on. A cold or in-flight BM25
84
- // index means the first search will pay a full corpus scan — the #1326
85
- // lag. Name it; do not fail liveness.
83
+ // Hybrid + the persistent index are default-on. An empty or in-flight BM25
84
+ // index means a text search waits for the build — the #1326 lag. Name it;
85
+ // do not fail liveness.
86
86
  //
87
87
  // `disabled` (feed/build failure) and `FLAIR_BM25_INDEX=false` both fall
88
88
  // back to the per-query scan. The kill switch never calls ensureReady, so
89
- // status stays `empty` for the life of the process — that is serving, not
90
- // cold. Treating it as lag would make searchReady false forever and refuse
91
- // a node that is already answering recall.
92
- const indexInPath = opts.hybridEnabled !== false && opts.bm25IndexEnabled !== false;
89
+ // the underlying state stays `empty` while status() reports `disabled` —
90
+ // that is serving, not an unready index. Treating the kill switch as lag
91
+ // would make searchReady false forever and refuse a node that is already
92
+ // answering recall. Callers pass `bm25IndexEnabled: false` for that case.
93
+ // The persistent BM25 index is in the retrieval path for "hybrid" and
94
+ // "bm25-only"; a "vector-only" process has no lexical leg to keep warm.
95
+ // `retrievalMode` is the current selector; `hybridEnabled` is the legacy
96
+ // boolean callers passed before it — an unset retrievalMode falls back to it
97
+ // exactly (false ⇒ vector-only, so the shipped behavior is unchanged).
98
+ const effectiveMode = opts.retrievalMode ?? (opts.hybridEnabled === false ? "vector-only" : "hybrid");
99
+ const indexInPath = effectiveMode !== "vector-only" && opts.bm25IndexEnabled !== false;
93
100
  if (indexInPath && opts.bm25) {
94
- if (opts.bm25.state === "building") {
95
- return namesLag("bm25 index building — first search is still scanning the corpus");
96
- }
97
- if (opts.bm25.state === "empty") {
98
- return namesLag("bm25 index not built (cold boot; first search scans the corpus)");
101
+ if (opts.bm25.state === "building" || opts.bm25.state === "empty") {
102
+ return namesLag(bm25SearchLagReason(opts.bm25));
99
103
  }
100
104
  }
101
105
  return { searchReady: true, ok: true, status: 200, searchReadyReason: readyReason };
@@ -91,19 +91,23 @@ function distanceToSimilarity(distance) {
91
91
  // deliberately omits `provenance` (it's only needed for the trust block), and
92
92
  // adding it unconditionally would change every existing recall response's
93
93
  // bytes. See SemanticSearch.ts / MemoryBootstrap.ts's `includeTrust` handling.
94
- export const DEFAULT_SELECT = ["id", "agentId", "content", "contentHash", "visibility", "tags", "durability",
94
+ // flair#1940 A3: `instanceToken` IS in the default projection — the gated host
95
+ // pointer join (host-source-visibility.ts's pointerOutcomeFor) binds a pointer
96
+ // to the row's CURRENT incarnation token, so a semantic result must carry it or
97
+ // a permitted reader would never see their pointer.
98
+ export const DEFAULT_SELECT = ["id", "agentId", "content", "contentHash", "visibility", "instanceToken", "tags", "durability",
95
99
  "source", "createdAt", "updatedAt", "expiresAt", "retrievalCount", "usageCount", "lastRetrieved",
96
100
  "promotionStatus", "promotedAt", "promotedBy", "archived", "archivedAt", "archivedBy",
97
101
  "parentId", "derivedFrom", "sessionId", "lastReflected", "supersedes", "subject", "summary",
98
102
  "validFrom", "validTo", "_safetyFlags"];
99
103
  export async function retrieveCandidates(params) {
100
- const { queryEmbedding: qEmb, q, conditions, limit, select = DEFAULT_SELECT, includeSuperseded = false, scoring = "raw", temporalBoost = 1.0, sinceDate = null, asOf, minScore = 0, agentId, isAllowed, hybrid, ctx, withSemSimilarity = false, onLegs, } = params;
104
+ const { queryEmbedding: qEmb, q, conditions, limit, select = DEFAULT_SELECT, includeSuperseded = false, scoring = "raw", temporalBoost = 1.0, sinceDate = null, asOf, minScore = 0, agentId, isAllowed, mode, ctx, withSemSimilarity = false, onLegs, } = params;
101
105
  const passesAllowed = (record) => !isAllowed || isAllowed(record);
102
106
  const hnswSelect = [...select, "$distance"];
103
107
  const results = [];
104
108
  const hnswLegIds = [];
105
109
  const bm25LegIds = [];
106
- if (hybrid) {
110
+ if (mode === "hybrid") {
107
111
  // ─── BM25 + union-RRF hybrid path ────────────────────────────────────
108
112
  // 1. Semantic candidates via HNSW (unchanged fetch). 2. BM25 lexical pass
109
113
  // over the SCOPED corpus. 3. SECURITY: the BM25 candidate set is filtered
@@ -356,8 +360,103 @@ export async function retrieveCandidates(params) {
356
360
  }
357
361
  }
358
362
  }
363
+ else if (mode === "bm25-only") {
364
+ // ─── BM25-only path (benchmark arm) ────────────────────────────────────
365
+ // The lexical leg ALONE: no HNSW leg, no query embedding, no RRF fusion.
366
+ // `semIds` stays empty by construction and any qEmb the caller passed is
367
+ // IGNORED — ranking comes from the BM25 list and nothing else, so the arm
368
+ // measures exactly what its name says. The result shape is identical to
369
+ // the other modes (same keys, same `_rank` ordering key, stripped before
370
+ // return). `_score` carries no semantic evidence on this path (there is no
371
+ // cosine to report): it is the legacy keyword bump alone, the same value
372
+ // the no-embedding fallback reports.
373
+ const allowedById = new Map();
374
+ let bm25Ids = [];
375
+ let servedFromIndex = false;
376
+ if (q) {
377
+ const fromIndex = await indexedBm25Ids({
378
+ q: String(q),
379
+ conditions: conditions,
380
+ timeFilters: { sinceDate, asOf },
381
+ isAllowed,
382
+ limit: SEM_LIMIT,
383
+ ctx,
384
+ });
385
+ if (fromIndex) {
386
+ bm25Ids = fromIndex;
387
+ servedFromIndex = true;
388
+ }
389
+ }
390
+ if (!servedFromIndex && q) {
391
+ // Legacy path: scoped corpus scan + per-query buildBM25() (see the
392
+ // hybrid branch above for the flair#1357 rationale).
393
+ const corpusQuery = conditions.length > 0 ? { conditions, select } : { select };
394
+ const corpusResults = withDetachedTxn(ctx, () => databases.flair.Memory.search(corpusQuery));
395
+ const bm25Docs = [];
396
+ for await (const record of corpusResults) {
397
+ if (!isAllowedBm25Candidate(record, conditions, { sinceDate, asOf }))
398
+ continue;
399
+ if (!passesAllowed(record))
400
+ continue;
401
+ allowedById.set(record.id, record);
402
+ bm25Docs.push({ id: record.id, content: record.content });
403
+ }
404
+ const bm25 = buildBM25(bm25Docs);
405
+ const ranked = bm25.rank(String(q));
406
+ bm25Ids = ranked.filter(r => r.score > 0).slice(0, SEM_LIMIT).map(r => r.id);
407
+ }
408
+ if (servedFromIndex) {
409
+ const resolved = [];
410
+ for (const id of bm25Ids) {
411
+ if (allowedById.has(id)) {
412
+ resolved.push(id);
413
+ continue;
414
+ }
415
+ const full = await withDetachedTxn(ctx, () => databases.flair.Memory.get(id));
416
+ if (!full)
417
+ continue;
418
+ if (!isAllowedBm25Candidate(full, conditions, { sinceDate, asOf }))
419
+ continue;
420
+ if (!passesAllowed(full))
421
+ continue;
422
+ const projected = {};
423
+ for (const key of select)
424
+ if (key in full)
425
+ projected[key] = full[key];
426
+ allowedById.set(id, projected);
427
+ resolved.push(id);
428
+ }
429
+ bm25Ids = resolved;
430
+ }
431
+ bm25LegIds.push(...bm25Ids);
432
+ // Emit in BM25 order alone — rank 0 gets the highest `_rank`, so the final
433
+ // descending sort keeps the lexical order. No fusion, no cosine.
434
+ for (let i = 0; i < bm25Ids.length; i++) {
435
+ const id = bm25Ids[i];
436
+ const record = allowedById.get(id);
437
+ if (!record)
438
+ continue;
439
+ let keywordHit = false;
440
+ if (q && String(record.content || "").toLowerCase().includes(String(q).toLowerCase())) {
441
+ keywordHit = true;
442
+ }
443
+ const rawScore = keywordHit ? 0.05 : 0;
444
+ let finalScore = scoring === "raw" ? rawScore : compositeScore(rawScore, record);
445
+ if (temporalBoost > 1.0)
446
+ finalScore *= temporalBoost;
447
+ const isFlagged = record._safetyFlags && Array.isArray(record._safetyFlags) && record._safetyFlags.length > 0;
448
+ const source = record.agentId !== agentId ? record.agentId : undefined;
449
+ pushRanked(results, {
450
+ ...record,
451
+ content: isFlagged ? wrapUntrusted(record.content, source) : record.content,
452
+ _score: Math.round(finalScore * 1000) / 1000,
453
+ _rawScore: scoring !== "raw" ? Math.round(rawScore * 1000) / 1000 : undefined,
454
+ _source: source,
455
+ }, bm25Ids.length - i);
456
+ }
457
+ }
359
458
  else if (qEmb) {
360
- // ─── HNSW vector search path (legacy, hybrid flag OFF — the
459
+ // ─── HNSW vector search path (legacy, mode "vector-only" — the
361
460
  // FLAIR_HYBRID_RETRIEVAL kill-switch path for BOTH production callers
362
461
  // since flair#1246) ─────────────────────────────────────────────────────
363
462
  const query = {
@@ -60,3 +60,36 @@ export function withDetachedTxn(ctx, fn) {
60
60
  ctx.transaction = saved;
61
61
  }
62
62
  }
63
+ /**
64
+ * AWAITED variant (flair#1897): holds the detached window through the promise.
65
+ *
66
+ * The sync `withDetachedTxn` restores `ctx.transaction` in `finally` as soon as
67
+ * `fn` RETURNS — for an async `fn` that is when the PROMISE IS CREATED, not when
68
+ * it settles. Harper's static `put` can resolve the resource asynchronously
69
+ * before `_writeUpdate` picks its transaction via `txnForContext(getContext())`;
70
+ * if that pick runs after the restore, the write rejoins the request's deferred
71
+ * transaction and commits after the caller has moved on. This variant keeps the
72
+ * transaction detached until `fn`'s promise settles: save, clear, `await fn()`,
73
+ * THEN restore. Use it for a WRITE you need committed before the next reader.
74
+ *
75
+ * Relied-on Harper behaviour (5.2.8, exact branches): `txnForContext`
76
+ * (Table.ts:5767) selects the LMDB OR RocksDB `ImmediateTransaction`
77
+ * (LMDBTransaction.ts:349 / DatabaseTransaction.ts:1465) when `context.transaction`
78
+ * is not a joinable scope; an immediate transaction writes on its own, while a
79
+ * joined one commits when its transaction function completes. The 50-round
80
+ * integration test
81
+ * (`test/integration/federation-instance-create-race-1897.test.ts`, run in the
82
+ * REQUIRED `Integration Tests` job) is the tripwire for an upgrade changing this.
83
+ */
84
+ export async function withDetachedTxnAsync(ctx, fn) {
85
+ if (!ctx)
86
+ return fn();
87
+ const saved = ctx.transaction;
88
+ ctx.transaction = undefined;
89
+ try {
90
+ return await fn();
91
+ }
92
+ finally {
93
+ ctx.transaction = saved;
94
+ }
95
+ }