@tpsdev-ai/flair 0.57.0 → 0.59.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 (143) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +4 -1
  3. package/config.yaml +3 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +1726 -376
  6. package/dist/commands/agent.js +160 -2
  7. package/dist/commands/doctor.js +177 -27
  8. package/dist/commands/federation.js +2 -1
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +150 -44
  11. package/dist/commands/mcp.js +53 -22
  12. package/dist/commands/memory.js +24 -2
  13. package/dist/commands/quality.js +26 -18
  14. package/dist/commands/service.js +137 -22
  15. package/dist/commands/status.js +114 -3
  16. package/dist/commands/upgrade.js +204 -84
  17. package/dist/doctor-client.js +50 -4
  18. package/dist/federation/scheduler.js +253 -4
  19. package/dist/install/clients.js +89 -23
  20. package/dist/install/global-bin-path.js +26 -6
  21. package/dist/lib/atomic-write.js +256 -0
  22. package/dist/lib/daemon-liveness.js +103 -0
  23. package/dist/lib/doctor-run.js +72 -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/flair-agent-role.js +116 -0
  27. package/dist/lib/init-admin-pass.js +4 -2
  28. package/dist/lib/init-listener-environ.js +38 -0
  29. package/dist/lib/init-occupied-listener.js +165 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +179 -8
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/mcp-enable.js +667 -72
  34. package/dist/lib/memory-attributes.js +77 -0
  35. package/dist/lib/node-alias-path.js +95 -0
  36. package/dist/lib/npm-registry.js +119 -6
  37. package/dist/lib/owned-pins.js +20 -6
  38. package/dist/lib/process-start-time.js +32 -0
  39. package/dist/lib/service-repoint-apply.js +267 -0
  40. package/dist/lib/service-repoint.js +575 -0
  41. package/dist/lib/toml-string-array.js +104 -0
  42. package/dist/lib/tree-divergence.js +716 -0
  43. package/dist/lib/upgrade-plain-tree.js +18 -8
  44. package/dist/lib/upgrade-prior-liveness.js +69 -0
  45. package/dist/lib/upgrade-rollback.js +116 -0
  46. package/dist/rem/runner.js +11 -0
  47. package/dist/resources/Agent.js +54 -21
  48. package/dist/resources/AgentSeed.js +44 -1
  49. package/dist/resources/Federation.js +84 -54
  50. package/dist/resources/Memory.js +567 -72
  51. package/dist/resources/MemoryArchive.js +9 -0
  52. package/dist/resources/MemoryBootstrap.js +125 -29
  53. package/dist/resources/MemoryFeed.js +204 -3
  54. package/dist/resources/MemoryHostSource.js +90 -0
  55. package/dist/resources/MemoryMaintenance.js +121 -32
  56. package/dist/resources/MemoryReflect.js +4 -1
  57. package/dist/resources/MemoryReindex.js +7 -4
  58. package/dist/resources/MemoryUsage.js +53 -3
  59. package/dist/resources/OrgSkillAssignment.js +209 -0
  60. package/dist/resources/Presence.js +18 -10
  61. package/dist/resources/RecordUsage.js +30 -40
  62. package/dist/resources/Relationship.js +167 -78
  63. package/dist/resources/SemanticSearch.js +19 -6
  64. package/dist/resources/Soul.js +31 -19
  65. package/dist/resources/XAA.js +47 -14
  66. package/dist/resources/agent-auth.js +16 -10
  67. package/dist/resources/agent-status-guard.js +63 -0
  68. package/dist/resources/auth-middleware.js +137 -49
  69. package/dist/resources/auto-promote-lib.js +4 -4
  70. package/dist/resources/bm25-index-service.js +246 -32
  71. package/dist/resources/bm25-status.js +132 -0
  72. package/dist/resources/ed25519-auth.js +11 -54
  73. package/dist/resources/embed-gpu.js +262 -47
  74. package/dist/resources/embeddings-boot.js +52 -17
  75. package/dist/resources/federation-classify.js +34 -0
  76. package/dist/resources/federation-crypto.js +65 -19
  77. package/dist/resources/flair-agent-role-boot.js +26 -0
  78. package/dist/resources/health.js +67 -16
  79. package/dist/resources/host-pointer/registry.js +35 -0
  80. package/dist/resources/host-pointer-adapter.js +15 -0
  81. package/dist/resources/host-source-visibility.js +167 -0
  82. package/dist/resources/host-source.js +151 -0
  83. package/dist/resources/instance-identity.js +3 -2
  84. package/dist/resources/key-lock.js +31 -0
  85. package/dist/resources/mcp-handler.js +147 -51
  86. package/dist/resources/mcp-oauth.js +3 -6
  87. package/dist/resources/mcp-tools.js +47 -25
  88. package/dist/resources/memory-consolidate-lib.js +3 -1
  89. package/dist/resources/memory-declared-attributes.js +103 -0
  90. package/dist/resources/memory-feed-lib.js +5 -1
  91. package/dist/resources/memory-host-source.js +163 -0
  92. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  93. package/dist/resources/migrations/visibility-backfill.js +4 -1
  94. package/dist/resources/multi-worker-guard.js +121 -0
  95. package/dist/resources/oauth-discovery.js +1 -0
  96. package/dist/resources/oauth-wellknown.js +8 -4
  97. package/dist/resources/originator-instance.js +235 -0
  98. package/dist/resources/promotion-stamp.js +2 -0
  99. package/dist/resources/provenance.js +111 -11
  100. package/dist/resources/record-owner-guard.js +19 -0
  101. package/dist/resources/record-type-kit.js +9 -12
  102. package/dist/resources/record-types.js +22 -6
  103. package/dist/resources/relay-ops.js +28 -3
  104. package/dist/resources/replay-store.js +336 -0
  105. package/dist/resources/request-transaction.js +78 -0
  106. package/dist/resources/search-readiness.js +19 -21
  107. package/dist/resources/semantic-retrieval-core.js +5 -1
  108. package/dist/resources/skill-manifest.js +181 -0
  109. package/dist/resources/skill-provenance.js +15 -10
  110. package/dist/resources/table-patch-policy.js +109 -0
  111. package/dist/resources/table-patches.js +17 -0
  112. package/dist/resources/table-post-policy.js +138 -0
  113. package/dist/resources/table-posts.js +22 -0
  114. package/dist/resources/table-subscription-policy.js +135 -0
  115. package/dist/resources/table-subscriptions.js +19 -0
  116. package/dist/resources/tool-descriptors/index.js +15 -15
  117. package/dist/resources/trust-block.js +10 -3
  118. package/dist/resources/usage-recording.js +169 -41
  119. package/dist/src/lib/flair-agent-role.js +116 -0
  120. package/dist/src/lib/memory-attributes.js +77 -0
  121. package/docs/access-control.md +667 -0
  122. package/docs/api-reference.md +85 -17
  123. package/docs/auth.md +4 -0
  124. package/docs/claude-code.md +132 -0
  125. package/docs/deepseek-harness.md +1 -1
  126. package/docs/deployment.md +1 -1
  127. package/docs/federation.md +1 -1
  128. package/docs/integrations.md +6 -6
  129. package/docs/mcp-clients.md +16 -24
  130. package/docs/notes/mcp-oauth-model2.md +15 -1
  131. package/docs/quickstart.md +5 -0
  132. package/docs/releasing.md +152 -20
  133. package/docs/supply-chain-policy.md +10 -5
  134. package/docs/troubleshooting.md +11 -0
  135. package/docs/upgrade.md +187 -61
  136. package/package.json +10 -5
  137. package/schemas/agent.graphql +9 -6
  138. package/schemas/federation.graphql +2 -11
  139. package/schemas/memory.graphql +137 -17
  140. package/schemas/oauth.graphql +8 -4
  141. package/schemas/replay.graphql +18 -0
  142. package/templates/launchd/start-flair-with-admin-pass.sh +95 -0
  143. package/dist/resources/federation-nonce-store.js +0 -195
@@ -0,0 +1,336 @@
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 XAA ID-JAG `jti` record (flair#2073) uses the same `recordOnce` on its
12
+ * own table; see `claimIdJagJti` below.
13
+ *
14
+ * The record of truth is the local `ReplayNonce` table (schemas/replay.graphql:
15
+ * `replicate: false`, `expiration: 120`). Every Harper thread of this instance
16
+ * reads and writes the same rows. Per-thread memory holds only keys this thread
17
+ * has seen recorded — its own write, or a row it read back from the store: it
18
+ * may refuse early on a HIT, and a MISS always goes to the store.
19
+ *
20
+ * Check-and-record, `recordOnce()` (wrapped by each guard's `claim()`):
21
+ * 1. `tryLock([REPLAY_LOCK_NAMESPACE, key])` on the table's primary store. The
22
+ * lock is per key and shared by every thread of the process. Not acquired
23
+ * means another claim of the same key is in progress: "contended". The
24
+ * guard refuses that request as a replay but does not remember the key,
25
+ * because the other claim may still fail to write it.
26
+ * 2. Read the key fresh (`getEntry`; on LMDB the thread's cached read snapshot
27
+ * is dropped first). Present: "replay".
28
+ * 3. `put` the row in its OWN transaction and await the commit.
29
+ * 4. `unlock` in `finally` — only a lock this call acquired.
30
+ * Anything thrown, and any gap in the store contract below, is "unavailable",
31
+ * and every caller REFUSES the request on it. Nothing falls back to memory.
32
+ *
33
+ * Harper 5.2.8 has no conditional create that is atomic across threads; the
34
+ * per-key lock is the primitive that serialises the read with the write (Harper
35
+ * uses it the same way for source-fill de-duplication). The lock space is
36
+ * database-wide on RocksDB, so the key is namespaced.
37
+ *
38
+ * Callers claim a key only AFTER the request's signature has verified, and
39
+ * BEFORE the request has any effect.
40
+ *
41
+ * Eviction is Harper's table expiration: its scan runs on the last worker only,
42
+ * so once per instance, and removes a row no earlier than REPLAY_RETENTION_MS
43
+ * after it was written. A key stays acceptable to its window check for at most
44
+ * 2 × window after it is first recorded, so the retention must exceed twice
45
+ * every window that uses the store; a guard whose window does not fit is
46
+ * unavailable. `primaryStore` is not a documented Harper API: its methods are
47
+ * checked on every claim, reported once per worker at boot, and pinned against
48
+ * the installed Harper by test/unit-isolated/replay-store.test.ts.
49
+ */
50
+ import { databases } from "harper";
51
+ import { WINDOW_MS } from "./ed25519-auth.js";
52
+ import { FEDERATION_WINDOW_MS, verifyBodySignatureFreshOnce } from "./federation-crypto.js";
53
+ /** The table name in the `flair` database (schemas/replay.graphql). */
54
+ export const REPLAY_TABLE = "ReplayNonce";
55
+ /**
56
+ * Seconds a row is kept. MUST equal `expiration:` on `type ReplayNonce` in
57
+ * schemas/replay.graphql (pinned by test/unit-isolated/replay-store.test.ts).
58
+ */
59
+ export const REPLAY_RETENTION_S = 120;
60
+ export const REPLAY_RETENTION_MS = REPLAY_RETENTION_S * 1000;
61
+ /** First element of every lock key, so no other lock on the database collides. */
62
+ export const REPLAY_LOCK_NAMESPACE = "flair-replay";
63
+ /** Named refusal state: the store cannot be used, so signed requests are refused. */
64
+ export class ReplayStoreUnavailable extends Error {
65
+ gap;
66
+ constructor(gap) {
67
+ super(`ReplayStoreUnavailable: ${gap}`);
68
+ this.name = "ReplayStoreUnavailable";
69
+ this.gap = gap;
70
+ }
71
+ }
72
+ /** Harper's `transaction` is assigned onto the global at load (as in request-transaction.ts). */
73
+ export function harperReplayDeps() {
74
+ return {
75
+ table: databases?.flair?.[REPLAY_TABLE],
76
+ transaction: globalThis.transaction,
77
+ };
78
+ }
79
+ const STORE_METHODS = ["tryLock", "unlock", "getEntry"];
80
+ /**
81
+ * What stops the store from being used, or null. Checks the table, the three
82
+ * primary-store methods the claim relies on, the table's `put`, Harper's
83
+ * `transaction`, and — when the table reports its expiration — that rows
84
+ * outlive twice `windowMs`.
85
+ */
86
+ export function replayStoreContractGap(deps, windowMs) {
87
+ const name = deps?.name ?? REPLAY_TABLE;
88
+ const table = deps?.table;
89
+ if (!table)
90
+ return `table flair.${name} is not defined`;
91
+ const store = table.primaryStore;
92
+ if (!store)
93
+ return `flair.${name} has no primaryStore`;
94
+ for (const m of STORE_METHODS) {
95
+ if (typeof store[m] !== "function")
96
+ return `flair.${name}.primaryStore.${m} is not a function`;
97
+ }
98
+ if (typeof table.put !== "function")
99
+ return `flair.${name}.put is not a function`;
100
+ if (typeof deps.transaction !== "function")
101
+ return "Harper's transaction() is not available";
102
+ if (windowMs !== undefined) {
103
+ const expirationMs = table.expirationMS;
104
+ if (typeof expirationMs === "number" && expirationMs > 0 && expirationMs <= 2 * windowMs) {
105
+ return `flair.${name} keeps rows ${expirationMs} ms, not longer than twice the ${windowMs} ms window`;
106
+ }
107
+ }
108
+ return null;
109
+ }
110
+ /**
111
+ * Why a window cannot use the store, or null. `source` names where the window
112
+ * comes from (an env variable), so the refusal says what to change.
113
+ */
114
+ export function replayWindowGap(windowMs, source) {
115
+ const what = source ? `replay window ${windowMs} ms (${source})` : `replay window ${windowMs} ms`;
116
+ if (!Number.isFinite(windowMs) || windowMs <= 0)
117
+ return `${what} is not a positive number`;
118
+ if (2 * windowMs >= REPLAY_RETENTION_MS) {
119
+ 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`;
120
+ }
121
+ return null;
122
+ }
123
+ /**
124
+ * The atomic check-and-record. Resolves "recorded" when this call writes the
125
+ * key's row (one claim per key, across every thread of the instance), "replay"
126
+ * when the row is already in the store, and "contended" when another claim of
127
+ * `key` holds its lock. THROWS on a contract gap or any store error;
128
+ * `ReplayGuard.claim` turns that into "unavailable".
129
+ */
130
+ export async function recordOnce(key, seenAt, deps) {
131
+ const gap = replayStoreContractGap(deps);
132
+ if (gap)
133
+ throw new ReplayStoreUnavailable(gap);
134
+ const { table, transaction } = deps;
135
+ const store = table.primaryStore;
136
+ const lockKey = [deps.lockNamespace ?? REPLAY_LOCK_NAMESPACE, key];
137
+ if (!store.tryLock(lockKey))
138
+ return "contended";
139
+ try {
140
+ store.resetReadTxn?.();
141
+ if (store.getEntry(key) != null)
142
+ return "replay";
143
+ await transaction({}, () => table.put({ id: key, seenAt }));
144
+ return "recorded";
145
+ }
146
+ finally {
147
+ store.unlock(lockKey);
148
+ }
149
+ }
150
+ // ─── Refusal logging (bounded) ─────────────────────────────────────────────
151
+ const LOG_INTERVAL_MS = 10_000;
152
+ const lastLogged = new Map();
153
+ const REFUSED = {
154
+ a: "TPS-Ed25519 signed request",
155
+ f: "federation signed request",
156
+ x: "XAA jwt-bearer grant whose assertion carries a jti",
157
+ };
158
+ function noteUnavailable(scope, err, table = REPLAY_TABLE) {
159
+ const reason = err instanceof ReplayStoreUnavailable
160
+ ? err.message
161
+ : `ReplayStoreUnavailable: store error (${err?.constructor?.name ?? "Error"}: ${String(err?.message ?? err).slice(0, 200)})`;
162
+ const tag = `${scope}|${reason}`;
163
+ const now = Date.now();
164
+ if (now - (lastLogged.get(tag) ?? 0) < LOG_INTERVAL_MS)
165
+ return;
166
+ if (lastLogged.size > 64)
167
+ lastLogged.clear();
168
+ lastLogged.set(tag, now);
169
+ console.error(`[flair-replay] ${reason}. Every ${REFUSED[scope]} is refused until the ` +
170
+ `flair.${table} store is usable (see resources/replay-store.ts).`);
171
+ }
172
+ export function createReplayGuard(opts) {
173
+ const { scope, windowMs, windowSource } = opts;
174
+ const resolveDeps = opts.deps ?? harperReplayDeps;
175
+ const cacheLimit = opts.cacheLimit ?? 100_000;
176
+ const windowGap = replayWindowGap(windowMs, windowSource);
177
+ // A key can pass its window check for at most 2 × window after it is first
178
+ // recorded; past that a memory entry can no longer refuse anything.
179
+ const cacheTtlMs = 2 * windowMs;
180
+ const seen = new Map();
181
+ let lastPrune = 0;
182
+ function prune(now) {
183
+ if (now - lastPrune < 1000 && seen.size < cacheLimit)
184
+ return;
185
+ lastPrune = now;
186
+ for (const [k, t] of seen)
187
+ if (now - t > cacheTtlMs)
188
+ seen.delete(k);
189
+ if (seen.size >= cacheLimit)
190
+ seen.clear();
191
+ }
192
+ return {
193
+ scope,
194
+ windowMs,
195
+ windowSource,
196
+ knownReplay(key, now = Date.now()) {
197
+ prune(now);
198
+ return seen.has(`${scope}:${key}`);
199
+ },
200
+ async claim(key, now = Date.now()) {
201
+ const full = `${scope}:${key}`;
202
+ try {
203
+ if (windowGap)
204
+ throw new ReplayStoreUnavailable(windowGap);
205
+ const deps = resolveDeps();
206
+ const gap = replayStoreContractGap(deps, windowMs);
207
+ if (gap)
208
+ throw new ReplayStoreUnavailable(gap);
209
+ const outcome = await recordOnce(full, now, deps);
210
+ // A contended key is refused for this request but not remembered: the
211
+ // claim holding its lock may still fail to write it, and the next
212
+ // presentation must be decided by the store.
213
+ if (outcome === "contended")
214
+ return "replay";
215
+ // Remembered only once the store has confirmed the row: written here,
216
+ // or read back from it.
217
+ prune(now);
218
+ seen.set(full, now);
219
+ return outcome;
220
+ }
221
+ catch (err) {
222
+ noteUnavailable(scope, err);
223
+ return "unavailable";
224
+ }
225
+ },
226
+ resetCacheForTest() {
227
+ seen.clear();
228
+ lastPrune = 0;
229
+ },
230
+ };
231
+ }
232
+ // ─── The two guards ────────────────────────────────────────────────────────
233
+ /** Agent auth (TPS-Ed25519). Key `a:<agentId>:<nonce>`. */
234
+ export const agentReplayGuard = createReplayGuard({
235
+ scope: "a",
236
+ windowMs: WINDOW_MS,
237
+ windowSource: "FLAIR_AGENT_AUTH_WINDOW_MS",
238
+ });
239
+ /** Federation body signatures. Key `f:<nonce>`. */
240
+ export const federationReplayGuard = createReplayGuard({ scope: "f", windowMs: FEDERATION_WINDOW_MS });
241
+ function agentKey(agentId, nonce) {
242
+ return `${agentId}:${nonce}`;
243
+ }
244
+ /**
245
+ * Memory HIT short-circuit for agent auth. May run before the signature is
246
+ * verified; a false says nothing and the request still has to claim.
247
+ */
248
+ export function isKnownAgentReplay(agentId, nonce, now = Date.now()) {
249
+ return agentReplayGuard.knownReplay(agentKey(agentId, nonce), now);
250
+ }
251
+ /**
252
+ * Claim (agentId, nonce) for this request, instance-wide. Call it after the
253
+ * signature has verified and before the request has any effect; refuse on
254
+ * anything but `{ ok: true }`.
255
+ */
256
+ export async function claimAgentNonce(agentId, nonce, now = Date.now()) {
257
+ const verdict = await agentReplayGuard.claim(agentKey(agentId, nonce), now);
258
+ if (verdict === "recorded")
259
+ return { ok: true };
260
+ if (verdict === "replay")
261
+ return { ok: false, error: "nonce_replay_detected", status: 401 };
262
+ return { ok: false, error: "replay_store_unavailable", status: 503 };
263
+ }
264
+ /**
265
+ * The federation endpoints' check (FederationPair, FederationSync): signature,
266
+ * freshness, then the nonce claimed instance-wide. Refuse on anything but ok.
267
+ */
268
+ export function verifyFederationRequestBody(body, publicKeyB64url) {
269
+ return verifyBodySignatureFreshOnce(body, publicKeyB64url, {
270
+ windowMs: FEDERATION_WINDOW_MS,
271
+ replay: federationReplayGuard,
272
+ });
273
+ }
274
+ // ─── XAA ID-JAG jti (flair#2073) ───────────────────────────────────────────
275
+ /** Used ID-JAG `jti` values (schemas/oauth.graphql), one row per jti, keyed by the jti. */
276
+ export const ID_JAG_REPLAY_TABLE = "IdJagReplay";
277
+ /** First element of every jti lock key, so a jti never shares a lock key with a nonce. */
278
+ export const ID_JAG_LOCK_NAMESPACE = "flair-replay-id-jag";
279
+ function idJagReplayDeps() {
280
+ return {
281
+ table: databases?.flair?.[ID_JAG_REPLAY_TABLE],
282
+ transaction: globalThis.transaction,
283
+ name: ID_JAG_REPLAY_TABLE,
284
+ lockNamespace: ID_JAG_LOCK_NAMESPACE,
285
+ };
286
+ }
287
+ /**
288
+ * Claim an ID-JAG's `jti` once per instance, through `recordOnce`. Call it after
289
+ * the assertion has validated and before the grant has any effect; refuse on
290
+ * anything but "recorded". `minRetentionMs` is the longest an accepted
291
+ * assertion can stay acceptable after its jti is recorded: a table whose rows
292
+ * do not outlive it is unavailable.
293
+ */
294
+ export async function claimIdJagJti(jti, minRetentionMs, now = Date.now()) {
295
+ try {
296
+ const deps = idJagReplayDeps();
297
+ const gap = replayStoreContractGap(deps);
298
+ if (gap)
299
+ throw new ReplayStoreUnavailable(gap);
300
+ const expirationMs = deps.table.expirationMS;
301
+ if (typeof expirationMs === "number" && expirationMs > 0 && expirationMs <= minRetentionMs) {
302
+ throw new ReplayStoreUnavailable(`flair.${ID_JAG_REPLAY_TABLE} keeps rows ${expirationMs} ms, not longer than the ${minRetentionMs} ms an assertion can stay acceptable`);
303
+ }
304
+ // A lock miss ("contended") is refused like a stored row.
305
+ return (await recordOnce(jti, now, deps)) === "recorded" ? "recorded" : "replay";
306
+ }
307
+ catch (err) {
308
+ noteUnavailable("x", err, ID_JAG_REPLAY_TABLE);
309
+ return "unavailable";
310
+ }
311
+ }
312
+ // ─── Boot report ───────────────────────────────────────────────────────────
313
+ /** Every gap that would refuse requests on this thread, or an empty list. */
314
+ export function replayStoreBootGaps(deps = harperReplayDeps()) {
315
+ const gaps = [];
316
+ for (const g of [agentReplayGuard, federationReplayGuard]) {
317
+ const gap = replayWindowGap(g.windowMs, g.windowSource) ?? replayStoreContractGap(deps, g.windowMs);
318
+ if (gap)
319
+ gaps.push(`${g.scope === "a" ? "agent auth" : "federation"}: ${gap}`);
320
+ }
321
+ return gaps;
322
+ }
323
+ // Once per worker thread, after the schema's tables are bound. Harper defines
324
+ // `server.workerCount` on worker threads; unit tests and the CLI never reach it.
325
+ if (typeof setTimeout !== "undefined" && typeof globalThis.server?.workerCount === "number") {
326
+ setTimeout(() => {
327
+ try {
328
+ for (const gap of replayStoreBootGaps()) {
329
+ console.error(`[flair-replay] ReplayStoreUnavailable at boot (${gap}). Signed requests on this path are refused.`);
330
+ }
331
+ }
332
+ catch (err) {
333
+ console.error(`[flair-replay] ReplayStoreUnavailable at boot: ${err?.message ?? err}`);
334
+ }
335
+ }, 0);
336
+ }
@@ -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,15 +80,16 @@ 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.
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.
92
93
  // The persistent BM25 index is in the retrieval path for "hybrid" and
93
94
  // "bm25-only"; a "vector-only" process has no lexical leg to keep warm.
94
95
  // `retrievalMode` is the current selector; `hybridEnabled` is the legacy
@@ -97,11 +98,8 @@ export function resolveSearchReadiness(opts) {
97
98
  const effectiveMode = opts.retrievalMode ?? (opts.hybridEnabled === false ? "vector-only" : "hybrid");
98
99
  const indexInPath = effectiveMode !== "vector-only" && opts.bm25IndexEnabled !== false;
99
100
  if (indexInPath && opts.bm25) {
100
- if (opts.bm25.state === "building") {
101
- return namesLag("bm25 index building — first search is still scanning the corpus");
102
- }
103
- if (opts.bm25.state === "empty") {
104
- 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));
105
103
  }
106
104
  }
107
105
  return { searchReady: true, ok: true, status: 200, searchReadyReason: readyReason };
@@ -91,7 +91,11 @@ 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",