@tpsdev-ai/flair 0.57.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.
- package/README.md +4 -4
- package/SECURITY.md +4 -1
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1685 -279
- package/dist/commands/doctor.js +162 -4
- package/dist/commands/federation.js +2 -1
- package/dist/commands/hook.js +10 -2
- package/dist/commands/init.js +150 -44
- package/dist/commands/memory.js +24 -2
- package/dist/commands/quality.js +26 -18
- package/dist/commands/service.js +137 -22
- package/dist/commands/status.js +114 -3
- package/dist/commands/upgrade.js +204 -84
- package/dist/doctor-client.js +50 -4
- package/dist/federation/scheduler.js +253 -4
- package/dist/install/clients.js +89 -23
- package/dist/install/global-bin-path.js +26 -6
- package/dist/lib/atomic-write.js +256 -0
- package/dist/lib/daemon-liveness.js +61 -0
- package/dist/lib/doctor-run.js +5 -0
- package/dist/lib/embed-gpu-doctor.js +49 -26
- package/dist/lib/federation-memory-attributes.js +15 -0
- package/dist/lib/init-admin-pass.js +4 -2
- package/dist/lib/init-listener-environ.js +38 -0
- package/dist/lib/init-occupied-listener.js +165 -0
- package/dist/lib/launchd-domain-preflight.js +448 -0
- package/dist/lib/launchd-management.js +176 -6
- package/dist/lib/launchd-repair.js +95 -0
- package/dist/lib/memory-attributes.js +77 -0
- package/dist/lib/node-alias-path.js +95 -0
- package/dist/lib/npm-registry.js +119 -6
- package/dist/lib/owned-pins.js +20 -6
- package/dist/lib/service-repoint-apply.js +267 -0
- package/dist/lib/service-repoint.js +575 -0
- package/dist/lib/toml-string-array.js +104 -0
- package/dist/lib/tree-divergence.js +716 -0
- package/dist/lib/upgrade-plain-tree.js +18 -8
- package/dist/lib/upgrade-prior-liveness.js +69 -0
- package/dist/lib/upgrade-rollback.js +116 -0
- package/dist/rem/runner.js +11 -0
- package/dist/resources/Agent.js +27 -14
- package/dist/resources/AgentSeed.js +35 -1
- package/dist/resources/Federation.js +70 -52
- package/dist/resources/Memory.js +567 -72
- package/dist/resources/MemoryArchive.js +9 -0
- package/dist/resources/MemoryBootstrap.js +4 -0
- package/dist/resources/MemoryFeed.js +204 -3
- package/dist/resources/MemoryHostSource.js +90 -0
- package/dist/resources/MemoryMaintenance.js +121 -32
- package/dist/resources/MemoryReflect.js +4 -1
- package/dist/resources/MemoryReindex.js +7 -4
- package/dist/resources/MemoryUsage.js +53 -3
- package/dist/resources/Presence.js +18 -10
- package/dist/resources/RecordUsage.js +30 -40
- package/dist/resources/Relationship.js +167 -78
- package/dist/resources/SemanticSearch.js +19 -6
- package/dist/resources/Soul.js +31 -19
- package/dist/resources/XAA.js +7 -3
- package/dist/resources/agent-auth.js +16 -10
- package/dist/resources/auth-middleware.js +135 -48
- package/dist/resources/auto-promote-lib.js +4 -4
- package/dist/resources/bm25-index-service.js +246 -32
- package/dist/resources/bm25-status.js +132 -0
- package/dist/resources/ed25519-auth.js +11 -54
- package/dist/resources/embed-gpu.js +262 -47
- package/dist/resources/embeddings-boot.js +52 -17
- package/dist/resources/federation-classify.js +12 -0
- package/dist/resources/federation-crypto.js +65 -19
- package/dist/resources/health.js +57 -14
- package/dist/resources/host-pointer/registry.js +35 -0
- package/dist/resources/host-pointer-adapter.js +15 -0
- package/dist/resources/host-source-visibility.js +167 -0
- package/dist/resources/host-source.js +151 -0
- package/dist/resources/instance-identity.js +3 -2
- package/dist/resources/mcp-handler.js +147 -51
- package/dist/resources/mcp-tools.js +25 -21
- package/dist/resources/memory-consolidate-lib.js +3 -1
- package/dist/resources/memory-declared-attributes.js +103 -0
- package/dist/resources/memory-feed-lib.js +5 -1
- package/dist/resources/memory-host-source.js +163 -0
- package/dist/resources/migrations/synthetic-test-migration.js +4 -1
- package/dist/resources/migrations/visibility-backfill.js +4 -1
- package/dist/resources/originator-instance.js +235 -0
- package/dist/resources/promotion-stamp.js +2 -0
- package/dist/resources/provenance.js +111 -11
- package/dist/resources/record-owner-guard.js +19 -0
- package/dist/resources/record-type-kit.js +9 -12
- package/dist/resources/record-types.js +6 -6
- package/dist/resources/relay-ops.js +28 -3
- package/dist/resources/replay-store.js +289 -0
- package/dist/resources/request-transaction.js +78 -0
- package/dist/resources/search-readiness.js +19 -21
- package/dist/resources/semantic-retrieval-core.js +5 -1
- package/dist/resources/table-patch-policy.js +109 -0
- package/dist/resources/table-patches.js +17 -0
- package/dist/resources/table-post-policy.js +138 -0
- package/dist/resources/table-posts.js +22 -0
- package/dist/resources/table-subscription-policy.js +135 -0
- package/dist/resources/table-subscriptions.js +19 -0
- package/dist/resources/tool-descriptors/index.js +15 -15
- package/dist/resources/trust-block.js +10 -3
- package/dist/resources/usage-recording.js +169 -41
- package/dist/src/lib/memory-attributes.js +77 -0
- package/docs/api-reference.md +79 -15
- package/docs/claude-code.md +132 -0
- package/docs/deployment.md +1 -1
- package/docs/federation.md +1 -1
- package/docs/integrations.md +5 -5
- package/docs/mcp-clients.md +11 -21
- package/docs/notes/mcp-oauth-model2.md +15 -1
- package/docs/quickstart.md +5 -0
- package/docs/releasing.md +134 -2
- package/docs/supply-chain-policy.md +10 -5
- package/docs/troubleshooting.md +11 -0
- package/docs/upgrade.md +187 -61
- package/package.json +9 -5
- package/schemas/agent.graphql +9 -6
- package/schemas/federation.graphql +2 -11
- package/schemas/memory.graphql +106 -17
- package/schemas/replay.graphql +18 -0
- package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
- package/dist/resources/federation-nonce-store.js +0 -195
|
@@ -25,13 +25,18 @@
|
|
|
25
25
|
// Maps plus the whole projected corpus INCLUDING content, transiently, on
|
|
26
26
|
// every single query.
|
|
27
27
|
//
|
|
28
|
-
// ──
|
|
29
|
-
//
|
|
30
|
-
//
|
|
31
|
-
//
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
//
|
|
28
|
+
// ── BOOT WARM ───────────────────────────────────────────────────────────────
|
|
29
|
+
// After the embeddings backend registration settles, embeddings-boot.ts calls
|
|
30
|
+
// scheduleBm25BootWarm(). That schedules ensureReady on a later turn, at low
|
|
31
|
+
// priority (setImmediate, then a yield every few dozen documents). Module
|
|
32
|
+
// load, boot, and the first non-search request do not wait on the scan.
|
|
33
|
+
// A text query that arrives while the build is in flight awaits the SAME
|
|
34
|
+
// buildPromise — it does not fall back to the per-query corpus scan.
|
|
35
|
+
//
|
|
36
|
+
// The warm is not started from this module's top level. Importing the service
|
|
37
|
+
// (unit tests, CLI helpers) must not scan. Processes that never load
|
|
38
|
+
// embeddings-boot still build on the first text search, which is what the
|
|
39
|
+
// `empty` status line says.
|
|
35
40
|
//
|
|
36
41
|
// ── STAYING CURRENT ─────────────────────────────────────────────────────────
|
|
37
42
|
// Two mechanisms, deliberately overlapping:
|
|
@@ -47,11 +52,11 @@
|
|
|
47
52
|
// operations-API delete both arrive (put/delete with the full row).
|
|
48
53
|
//
|
|
49
54
|
// 2. SYNCHRONOUS HOOKS at flair's own write surface (`noteMemoryUpsert` /
|
|
50
|
-
// `noteMemoryDelete`) give READ-YOUR-WRITE
|
|
51
|
-
//
|
|
52
|
-
//
|
|
53
|
-
//
|
|
54
|
-
// id, so seeing a write twice is a no-op.
|
|
55
|
+
// `noteMemoryDelete`) give READ-YOUR-WRITE after owned transactions commit.
|
|
56
|
+
// A request-owned Memory delete cannot use this hook before its request
|
|
57
|
+
// commits, so it reaches the index through the committed feed. The feed is
|
|
58
|
+
// asynchronous; other hooked writes avoid that delay. Both mechanisms are
|
|
59
|
+
// idempotent by id, so seeing a committed write twice is a no-op.
|
|
55
60
|
//
|
|
56
61
|
// If the feed cannot be established, or delivers an event shape we do not
|
|
57
62
|
// understand (Harper emits a bare `reload` marker when a base copy / resync is
|
|
@@ -67,14 +72,20 @@
|
|
|
67
72
|
// Both of flair's shipped launch paths pin `THREADS_COUNT=1` (src/cli.ts's
|
|
68
73
|
// launchd plist and its direct-spawn env), as does the integration harness, so
|
|
69
74
|
// the shipped configuration has exactly one worker and "per worker" is "per
|
|
70
|
-
// process".
|
|
71
|
-
//
|
|
75
|
+
// process". Status is still per worker: bm25IndexStatus() names the worker
|
|
76
|
+
// thread when THREADS_COUNT is greater than 1, and never claims to aggregate
|
|
77
|
+
// the other workers' indexes. Cross-worker write visibility rides on
|
|
78
|
+
// mechanism (1): the feed is audit-log-backed and the audit store is shared,
|
|
79
|
+
// so a write committed by
|
|
72
80
|
// another worker still arrives. Mechanism (2) is local to the writing worker,
|
|
73
81
|
// which is why it is an immediacy optimisation and never the correctness
|
|
74
82
|
// argument.
|
|
83
|
+
import { threadId } from "node:worker_threads";
|
|
75
84
|
import { databases } from "harper";
|
|
76
85
|
import { withDetachedTxn } from "./table-helpers.js";
|
|
77
86
|
import { Bm25Index, INDEX_SELECT } from "./bm25-index.js";
|
|
87
|
+
import { BM25_BOOT_WARM_SKIPPED_PREFIX, formatBm25IndexSummary, readThreadsCount } from "./bm25-status.js";
|
|
88
|
+
import { retrievalMode } from "./bm25.js";
|
|
78
89
|
/** Kill switch. Default ON; set FLAIR_BM25_INDEX=false/0/off to force every
|
|
79
90
|
* query back onto the legacy per-query corpus scan + buildBM25(). Read
|
|
80
91
|
* per-call so it can be flipped without a rebuild and set per-case in tests. */
|
|
@@ -82,24 +93,89 @@ export function bm25IndexEnabled() {
|
|
|
82
93
|
const v = (process.env.FLAIR_BM25_INDEX ?? "true").toLowerCase();
|
|
83
94
|
return v === "true" || v === "1" || v === "on";
|
|
84
95
|
}
|
|
96
|
+
/**
|
|
97
|
+
* The index is read only by the "hybrid" and "bm25-only" retrieval modes
|
|
98
|
+
* (semantic-retrieval-core.ts). A "vector-only" process has no lexical leg,
|
|
99
|
+
* so the boot warm does not build an index nothing reads, and status says
|
|
100
|
+
* so instead of claiming a text search will build it. An unrecognized
|
|
101
|
+
* FLAIR_RETRIEVAL_MODE throws on every query anyway; treat it as in the
|
|
102
|
+
* path so this check never hides that error.
|
|
103
|
+
*/
|
|
104
|
+
export function bm25IndexInRetrievalPath() {
|
|
105
|
+
try {
|
|
106
|
+
return retrievalMode() !== "vector-only";
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
85
112
|
const index = new Bm25Index();
|
|
86
113
|
let state = "empty";
|
|
87
114
|
let buildPromise = null;
|
|
88
115
|
let pending = null;
|
|
89
116
|
let feedStarted = false;
|
|
90
117
|
let disabledReason = "";
|
|
118
|
+
let builtCount = 0;
|
|
119
|
+
let totalCount = 0;
|
|
120
|
+
let startedAt = null;
|
|
121
|
+
let finishedAt = null;
|
|
122
|
+
let buildDurationMs = null;
|
|
123
|
+
/** Invalidates an in-flight build when a stale marker or a test reset lands. */
|
|
124
|
+
let buildSerial = 0;
|
|
125
|
+
/** Test seam: awaited once the first document of a multi-doc build is in. */
|
|
126
|
+
let buildPause = null;
|
|
127
|
+
let warmScheduled = false;
|
|
128
|
+
let warmSerial = 0;
|
|
129
|
+
const YIELD_EVERY = 32;
|
|
91
130
|
/** Test seam — resets everything this module owns. */
|
|
92
131
|
export function __resetBm25IndexForTests() {
|
|
132
|
+
buildSerial++;
|
|
133
|
+
warmSerial++;
|
|
134
|
+
warmScheduled = false;
|
|
135
|
+
buildPause = null;
|
|
93
136
|
index.clear();
|
|
94
137
|
state = "empty";
|
|
95
138
|
buildPromise = null;
|
|
96
139
|
pending = null;
|
|
97
140
|
feedStarted = false;
|
|
98
141
|
disabledReason = "";
|
|
142
|
+
builtCount = 0;
|
|
143
|
+
totalCount = 0;
|
|
144
|
+
startedAt = null;
|
|
145
|
+
finishedAt = null;
|
|
146
|
+
buildDurationMs = null;
|
|
99
147
|
}
|
|
100
|
-
/**
|
|
148
|
+
/** Test seam — hold the build after the first admitted document. */
|
|
149
|
+
export function __setBm25BuildPauseForTests(fn) {
|
|
150
|
+
buildPause = fn;
|
|
151
|
+
}
|
|
152
|
+
/** Diagnostics, for tests, /HealthDetail, and `flair status`. */
|
|
101
153
|
export function bm25IndexStatus() {
|
|
102
|
-
|
|
154
|
+
const threadsCount = readThreadsCount();
|
|
155
|
+
const enabled = bm25IndexEnabled();
|
|
156
|
+
const inPath = bm25IndexInRetrievalPath();
|
|
157
|
+
const viewState = enabled && inPath ? state : "disabled";
|
|
158
|
+
const reason = !enabled
|
|
159
|
+
? "FLAIR_BM25_INDEX is off"
|
|
160
|
+
: !inPath
|
|
161
|
+
? "retrieval mode is vector-only; the index is not used"
|
|
162
|
+
: disabledReason;
|
|
163
|
+
const view = {
|
|
164
|
+
state: viewState,
|
|
165
|
+
size: index.size,
|
|
166
|
+
postings: index.postingCount,
|
|
167
|
+
terms: index.termCount,
|
|
168
|
+
reason,
|
|
169
|
+
built: builtCount,
|
|
170
|
+
total: totalCount,
|
|
171
|
+
startedAt,
|
|
172
|
+
finishedAt,
|
|
173
|
+
buildDurationMs,
|
|
174
|
+
workerThreadId: threadId,
|
|
175
|
+
threadsCount,
|
|
176
|
+
scope: "this-worker",
|
|
177
|
+
};
|
|
178
|
+
return { ...view, summary: formatBm25IndexSummary(view) };
|
|
103
179
|
}
|
|
104
180
|
function project(record) {
|
|
105
181
|
if (!record || typeof record.id !== "string")
|
|
@@ -120,6 +196,13 @@ function record(ev) {
|
|
|
120
196
|
if (state === "disabled" || state === "empty")
|
|
121
197
|
return; // a later build will scan it
|
|
122
198
|
if (state === "building") {
|
|
199
|
+
// A throw here is caught by the feed consumer, which disables the index
|
|
200
|
+
// for this worker's lifetime. A missing buffer means this build no longer
|
|
201
|
+
// owns the events; mark stale so the next query rebuilds instead.
|
|
202
|
+
if (pending == null) {
|
|
203
|
+
markBm25IndexStale("in-flight build lost its event buffer");
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
123
206
|
pending.push(ev);
|
|
124
207
|
return;
|
|
125
208
|
}
|
|
@@ -143,9 +226,21 @@ export function noteMemoryDelete(id) {
|
|
|
143
226
|
export function markBm25IndexStale(reason) {
|
|
144
227
|
if (state === "disabled")
|
|
145
228
|
return;
|
|
229
|
+
buildSerial++;
|
|
146
230
|
disabledReason = reason;
|
|
147
231
|
state = "empty";
|
|
148
232
|
buildPromise = null;
|
|
233
|
+
builtCount = 0;
|
|
234
|
+
totalCount = 0;
|
|
235
|
+
startedAt = null;
|
|
236
|
+
finishedAt = null;
|
|
237
|
+
buildDurationMs = null;
|
|
238
|
+
}
|
|
239
|
+
function stampFinished() {
|
|
240
|
+
if (finishedAt != null)
|
|
241
|
+
return;
|
|
242
|
+
finishedAt = Date.now();
|
|
243
|
+
buildDurationMs = startedAt == null ? null : finishedAt - startedAt;
|
|
149
244
|
}
|
|
150
245
|
function disable(reason) {
|
|
151
246
|
state = "disabled";
|
|
@@ -153,6 +248,11 @@ function disable(reason) {
|
|
|
153
248
|
buildPromise = null;
|
|
154
249
|
pending = null;
|
|
155
250
|
index.clear();
|
|
251
|
+
builtCount = 0;
|
|
252
|
+
stampFinished();
|
|
253
|
+
}
|
|
254
|
+
function yieldBackground() {
|
|
255
|
+
return new Promise((resolve) => { setImmediate(resolve); });
|
|
156
256
|
}
|
|
157
257
|
async function startFeed(ctx) {
|
|
158
258
|
if (feedStarted)
|
|
@@ -188,39 +288,91 @@ async function startFeed(ctx) {
|
|
|
188
288
|
})();
|
|
189
289
|
}
|
|
190
290
|
/**
|
|
191
|
-
* Build (or rebuild) the index from
|
|
291
|
+
* Build (or rebuild) the index from the corpus.
|
|
192
292
|
*
|
|
193
|
-
* ORDER IS LOAD-BEARING: the change feed is started BEFORE
|
|
194
|
-
* events it delivers during the
|
|
195
|
-
* delete that lands mid-scan for a row the cursor has
|
|
196
|
-
* otherwise be applied first and then undone by the
|
|
197
|
-
*
|
|
198
|
-
* physically occurred in.
|
|
293
|
+
* ORDER IS LOAD-BEARING: the change feed is started BEFORE either pass, and
|
|
294
|
+
* the events it delivers during the passes are buffered and replayed AFTER
|
|
295
|
+
* the admitting pass. A delete that lands mid-scan for a row the cursor has
|
|
296
|
+
* not reached yet would otherwise be applied first and then undone by the
|
|
297
|
+
* cursor re-adding the row. Replaying after the admitting pass lets the
|
|
298
|
+
* newer event win, whichever order they physically occurred in.
|
|
299
|
+
*
|
|
300
|
+
* Pass 1 counts ids so status can report built/total. Pass 2 admits the
|
|
301
|
+
* projected rows and yields every few dozen documents so a request already
|
|
302
|
+
* on the event loop is not stuck behind the tokenize.
|
|
199
303
|
*/
|
|
200
304
|
async function build(ctx) {
|
|
305
|
+
const serial = ++buildSerial;
|
|
306
|
+
const live = () => state === "building" && serial === buildSerial;
|
|
201
307
|
state = "building";
|
|
202
308
|
pending = [];
|
|
203
309
|
index.clear();
|
|
310
|
+
builtCount = 0;
|
|
311
|
+
totalCount = 0;
|
|
312
|
+
startedAt = Date.now();
|
|
313
|
+
finishedAt = null;
|
|
314
|
+
buildDurationMs = null;
|
|
204
315
|
try {
|
|
205
316
|
await startFeed(ctx);
|
|
317
|
+
if (!live())
|
|
318
|
+
return false;
|
|
319
|
+
// Count first so status can report built/total while the bodies are
|
|
320
|
+
// admitted. Buffering every projected row would hold the corpus in JS
|
|
321
|
+
// for the length of the tokenize; a second id-only pass does not.
|
|
322
|
+
const idScan = withDetachedTxn(ctx, () => databases.flair.Memory.search({ select: ["id"] }));
|
|
323
|
+
let total = 0;
|
|
324
|
+
for await (const row of idScan) {
|
|
325
|
+
if (!live())
|
|
326
|
+
return false;
|
|
327
|
+
if (row && typeof row.id === "string")
|
|
328
|
+
total++;
|
|
329
|
+
}
|
|
330
|
+
if (!live())
|
|
331
|
+
return false;
|
|
332
|
+
totalCount = total;
|
|
333
|
+
// Let a status read observe 0/total before tokenize starts, and let
|
|
334
|
+
// already-queued requests run before this worker spends the scan.
|
|
335
|
+
await yieldBackground();
|
|
336
|
+
if (!live())
|
|
337
|
+
return false;
|
|
206
338
|
const results = withDetachedTxn(ctx, () => databases.flair.Memory.search({ select: INDEX_SELECT }));
|
|
339
|
+
let admitted = 0;
|
|
207
340
|
for await (const row of results) {
|
|
341
|
+
if (!live())
|
|
342
|
+
return false;
|
|
208
343
|
const r = project(row);
|
|
209
|
-
if (r)
|
|
210
|
-
|
|
344
|
+
if (!r)
|
|
345
|
+
continue;
|
|
346
|
+
index.upsert(r);
|
|
347
|
+
admitted++;
|
|
348
|
+
builtCount = admitted;
|
|
349
|
+
if (buildPause && admitted === 1 && total > 1)
|
|
350
|
+
await buildPause();
|
|
351
|
+
if (!live())
|
|
352
|
+
return false;
|
|
353
|
+
if (admitted % YIELD_EVERY === 0)
|
|
354
|
+
await yieldBackground();
|
|
211
355
|
}
|
|
212
356
|
}
|
|
213
357
|
catch (err) {
|
|
214
|
-
|
|
358
|
+
if (serial === buildSerial)
|
|
359
|
+
disable("build failed: " + String(err?.message ?? err));
|
|
215
360
|
return false;
|
|
216
361
|
}
|
|
362
|
+
// Ownership is checked before the buffer is taken. An aborted build
|
|
363
|
+
// resumes after its last for-await yield; by then a stale marker may have
|
|
364
|
+
// started a replacement whose `pending` is a new array. Clearing it here
|
|
365
|
+
// makes the next feed event throw and disables the index for this worker.
|
|
366
|
+
// Nothing awaits between this check and the clear, so the take is atomic
|
|
367
|
+
// on the single thread.
|
|
368
|
+
if (!live())
|
|
369
|
+
return false;
|
|
217
370
|
const buffered = pending ?? [];
|
|
218
371
|
pending = null;
|
|
219
|
-
|
|
220
|
-
// arrived during the scan; in that case do not claim readiness.
|
|
221
|
-
if (state !== "building")
|
|
222
|
-
return false;
|
|
372
|
+
const finished = Date.now();
|
|
223
373
|
state = "ready";
|
|
374
|
+
finishedAt = finished;
|
|
375
|
+
buildDurationMs = finished - (startedAt ?? finished);
|
|
224
376
|
for (const ev of buffered)
|
|
225
377
|
apply(ev);
|
|
226
378
|
return true;
|
|
@@ -232,10 +384,72 @@ async function ensureReady(ctx) {
|
|
|
232
384
|
return false;
|
|
233
385
|
if (state === "ready")
|
|
234
386
|
return true;
|
|
235
|
-
if (!buildPromise)
|
|
236
|
-
|
|
387
|
+
if (!buildPromise) {
|
|
388
|
+
const run = build(ctx).finally(() => {
|
|
389
|
+
if (buildPromise === run)
|
|
390
|
+
buildPromise = null;
|
|
391
|
+
});
|
|
392
|
+
buildPromise = run;
|
|
393
|
+
}
|
|
237
394
|
return buildPromise;
|
|
238
395
|
}
|
|
396
|
+
async function waitForMemorySearch(maxWaitMs = 30_000, intervalMs = 50) {
|
|
397
|
+
const deadline = Date.now() + maxWaitMs;
|
|
398
|
+
for (;;) {
|
|
399
|
+
try {
|
|
400
|
+
const mem = databases.flair?.Memory;
|
|
401
|
+
if (mem && typeof mem.search === "function")
|
|
402
|
+
return true;
|
|
403
|
+
}
|
|
404
|
+
catch { /* tables are not bound yet */ }
|
|
405
|
+
if (Date.now() >= deadline)
|
|
406
|
+
return false;
|
|
407
|
+
await new Promise((r) => setTimeout(r, intervalMs));
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
async function warmWhenReady(serial) {
|
|
411
|
+
if (serial !== warmSerial)
|
|
412
|
+
return;
|
|
413
|
+
if (!bm25IndexEnabled() || !bm25IndexInRetrievalPath())
|
|
414
|
+
return;
|
|
415
|
+
let ready = false;
|
|
416
|
+
try {
|
|
417
|
+
ready = await waitForMemorySearch();
|
|
418
|
+
}
|
|
419
|
+
catch (err) {
|
|
420
|
+
if (serial !== warmSerial || state !== "empty")
|
|
421
|
+
return;
|
|
422
|
+
disabledReason = `${BM25_BOOT_WARM_SKIPPED_PREFIX} ${String(err?.message ?? err)}`;
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
if (serial !== warmSerial)
|
|
426
|
+
return;
|
|
427
|
+
if (!bm25IndexEnabled() || !bm25IndexInRetrievalPath())
|
|
428
|
+
return;
|
|
429
|
+
if (!ready) {
|
|
430
|
+
if (state === "empty") {
|
|
431
|
+
disabledReason = `${BM25_BOOT_WARM_SKIPPED_PREFIX} Memory table was not ready within 30s`;
|
|
432
|
+
}
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
if (state !== "empty")
|
|
436
|
+
return;
|
|
437
|
+
await ensureReady(undefined);
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Start the index build on a later turn. Boot and the caller do not wait.
|
|
441
|
+
* A text query that arrives mid-build shares `buildPromise`.
|
|
442
|
+
* Idempotent per process until a test reset.
|
|
443
|
+
*/
|
|
444
|
+
export function scheduleBm25BootWarm() {
|
|
445
|
+
if (warmScheduled)
|
|
446
|
+
return;
|
|
447
|
+
warmScheduled = true;
|
|
448
|
+
const serial = warmSerial;
|
|
449
|
+
setImmediate(() => {
|
|
450
|
+
void warmWhenReady(serial);
|
|
451
|
+
});
|
|
452
|
+
}
|
|
239
453
|
/**
|
|
240
454
|
* The lexical leg, served from the index. Returns the BM25 candidate ids
|
|
241
455
|
* (score>0, best-first, sliced to `limit`) — or NULL when the index declines,
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Operator text for the persistent BM25 index (flair#2032).
|
|
3
|
+
*
|
|
4
|
+
* Harper-free so `flair status` and the search-readiness decision can share
|
|
5
|
+
* one wording. The index itself is per Harper worker; when THREADS_COUNT is
|
|
6
|
+
* greater than 1 the line names the worker it describes instead of implying
|
|
7
|
+
* a cluster-wide aggregate.
|
|
8
|
+
*/
|
|
9
|
+
/** Stable marker shared by boot-warm status and the public lag classifier. */
|
|
10
|
+
export const BM25_BOOT_WARM_SKIPPED_PREFIX = "background build skipped:";
|
|
11
|
+
/** Positive integer THREADS_COUNT, or null when unset or not a count. */
|
|
12
|
+
export function readThreadsCount(env = process.env) {
|
|
13
|
+
const raw = env.THREADS_COUNT;
|
|
14
|
+
if (raw == null)
|
|
15
|
+
return null;
|
|
16
|
+
const trimmed = raw.trim();
|
|
17
|
+
if (!/^[1-9]\d*$/.test(trimmed))
|
|
18
|
+
return null;
|
|
19
|
+
const n = Number(trimmed);
|
|
20
|
+
return Number.isSafeInteger(n) ? n : null;
|
|
21
|
+
}
|
|
22
|
+
function formatAgo(ms) {
|
|
23
|
+
const elapsed = Math.max(0, ms);
|
|
24
|
+
if (elapsed < 1000)
|
|
25
|
+
return "just now";
|
|
26
|
+
const seconds = Math.floor(elapsed / 1000);
|
|
27
|
+
if (seconds < 60)
|
|
28
|
+
return `${seconds}s ago`;
|
|
29
|
+
const minutes = Math.floor(elapsed / 60_000);
|
|
30
|
+
if (minutes < 60)
|
|
31
|
+
return `${minutes}m ago`;
|
|
32
|
+
const hours = Math.floor(elapsed / 3_600_000);
|
|
33
|
+
if (hours < 48)
|
|
34
|
+
return `${hours}h ago`;
|
|
35
|
+
const days = Math.floor(elapsed / 86_400_000);
|
|
36
|
+
return `${days}d ago`;
|
|
37
|
+
}
|
|
38
|
+
function formatDuration(ms) {
|
|
39
|
+
const n = Math.max(0, ms);
|
|
40
|
+
if (n < 1000)
|
|
41
|
+
return `${Math.round(n)}ms`;
|
|
42
|
+
if (n < 10_000) {
|
|
43
|
+
const tenths = Math.round(n / 100) / 10;
|
|
44
|
+
return `${tenths.toFixed(1)}s`;
|
|
45
|
+
}
|
|
46
|
+
return `${Math.round(n / 1000)}s`;
|
|
47
|
+
}
|
|
48
|
+
function percent(built, total) {
|
|
49
|
+
if (total <= 0)
|
|
50
|
+
return 0;
|
|
51
|
+
return Math.round((built * 100) / total);
|
|
52
|
+
}
|
|
53
|
+
function workerSuffix(threadsCount, workerThreadId) {
|
|
54
|
+
if (threadsCount != null && threadsCount > 1) {
|
|
55
|
+
return ` · worker ${workerThreadId} of ${threadsCount}`;
|
|
56
|
+
}
|
|
57
|
+
return "";
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* One line for HealthDetail and `flair status`.
|
|
61
|
+
*
|
|
62
|
+
* building 312/817 docs (38%) · started 4s ago
|
|
63
|
+
* ready · 817 docs · built in 1.2s · 3m ago
|
|
64
|
+
* disabled — <reason>
|
|
65
|
+
*/
|
|
66
|
+
export function formatBm25IndexSummary(input, now = Date.now()) {
|
|
67
|
+
const suffix = workerSuffix(input.threadsCount, input.workerThreadId);
|
|
68
|
+
const reason = (input.reason ?? "").trim();
|
|
69
|
+
if (input.state === "building") {
|
|
70
|
+
const head = input.total > 0
|
|
71
|
+
? `building ${input.built}/${input.total} docs (${percent(input.built, input.total)}%)`
|
|
72
|
+
: `building ${input.built} docs`;
|
|
73
|
+
const started = input.startedAt == null ? "" : ` · started ${formatAgo(now - input.startedAt)}`;
|
|
74
|
+
return `${head}${started}${suffix}`;
|
|
75
|
+
}
|
|
76
|
+
if (input.state === "ready") {
|
|
77
|
+
const dur = input.buildDurationMs == null ? "" : ` · built in ${formatDuration(input.buildDurationMs)}`;
|
|
78
|
+
const ago = input.finishedAt == null ? "" : ` · ${formatAgo(now - input.finishedAt)}`;
|
|
79
|
+
return `ready · ${input.size} docs${dur}${ago}${suffix}`;
|
|
80
|
+
}
|
|
81
|
+
if (input.state === "disabled" || input.state === "failed") {
|
|
82
|
+
const why = reason.length > 0 ? reason : "no reason recorded";
|
|
83
|
+
const label = input.state === "failed" ? "failed" : "disabled";
|
|
84
|
+
return `${label} — ${why}${suffix}`;
|
|
85
|
+
}
|
|
86
|
+
// `empty`: the warm has not started (or a stale marker cleared a ready
|
|
87
|
+
// index). Say what clears it. A stale reason, when one was recorded, is
|
|
88
|
+
// part of that sentence.
|
|
89
|
+
if (reason.length > 0) {
|
|
90
|
+
return `not built yet — ${reason}; a text search rebuilds it${suffix}`;
|
|
91
|
+
}
|
|
92
|
+
return `not built yet — builds in the background after startup, or on the first text search${suffix}`;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* HealthDetail warning for an index that is `disabled` while search still
|
|
96
|
+
* answers. Only a failure (feed error, failed build, failed rank) warns.
|
|
97
|
+
* `FLAIR_BM25_INDEX=false` and vector-only retrieval are operator settings:
|
|
98
|
+
* the status line states them, and they are not a standing warning.
|
|
99
|
+
*/
|
|
100
|
+
export function bm25DisabledWarning(bm25, opts) {
|
|
101
|
+
if (!opts.indexEnabled || !opts.inRetrievalPath)
|
|
102
|
+
return null;
|
|
103
|
+
if (bm25?.state !== "disabled")
|
|
104
|
+
return null;
|
|
105
|
+
const summary = bm25.summary?.trim() ?? "";
|
|
106
|
+
if (summary.length === 0)
|
|
107
|
+
return null;
|
|
108
|
+
return `bm25 index: ${summary}`;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Lag text for searchReady. A caller that already has a summary (HealthDetail)
|
|
112
|
+
* passes it through; public /Health receives only state and reason. Classify
|
|
113
|
+
* the reason without copying it: stale feed markers and build errors can
|
|
114
|
+
* contain details that do not belong on the unauthenticated endpoint.
|
|
115
|
+
*/
|
|
116
|
+
export function bm25SearchLagReason(bm25) {
|
|
117
|
+
const summary = bm25?.summary?.trim() ?? "";
|
|
118
|
+
if (summary.length > 0) {
|
|
119
|
+
return summary.startsWith("bm25 index:") ? summary : `bm25 index: ${summary}`;
|
|
120
|
+
}
|
|
121
|
+
if (bm25?.state === "building") {
|
|
122
|
+
return "bm25 index: building — a text search waits for this build";
|
|
123
|
+
}
|
|
124
|
+
const reason = bm25?.reason?.trim() ?? "";
|
|
125
|
+
if (bm25?.state === "empty" && reason.startsWith(BM25_BOOT_WARM_SKIPPED_PREFIX)) {
|
|
126
|
+
return "bm25 index not built yet — background build was skipped; a text search builds it";
|
|
127
|
+
}
|
|
128
|
+
if (bm25?.state === "empty" && reason.length > 0) {
|
|
129
|
+
return "bm25 index not built yet — previous index became stale; a text search rebuilds it";
|
|
130
|
+
}
|
|
131
|
+
return "bm25 index not built yet — builds in the background after startup, or on the first text search";
|
|
132
|
+
}
|
|
@@ -6,28 +6,20 @@
|
|
|
6
6
|
* - resources/agent-auth.ts (resolveAgentAuth's per-resource fallback)
|
|
7
7
|
* - resources/Presence.ts (POST /Presence heartbeat auth)
|
|
8
8
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* silently didn't apply to the other two). Consolidating all three into
|
|
15
|
-
* this one module means there is exactly ONE replay guard and ONE
|
|
16
|
-
* key-import implementation, imported by all 3 sites.
|
|
9
|
+
* It holds the replay window, the header parser and the key import, so the
|
|
10
|
+
* three sites cannot drift. The replay guard itself — which nonces have been
|
|
11
|
+
* used — lives in resources/replay-store.ts: one check-and-record against the
|
|
12
|
+
* instance-wide `ReplayNonce` table, shared by all three sites and by every
|
|
13
|
+
* Harper worker thread (flair#2061).
|
|
17
14
|
*
|
|
18
15
|
* `b64ToArrayBuffer` was already unified into resources/b64.ts in a prior
|
|
19
16
|
* pass (see that file's header) — re-exported here so callers can import
|
|
20
17
|
* everything Ed25519-auth-related from one place.
|
|
21
18
|
*
|
|
22
|
-
* NOT included here: resources/Federation.ts's replay guard. Federation
|
|
23
|
-
* uses its own purpose-built NonceStore (federation-crypto.ts) for a
|
|
24
|
-
* different signing scheme (federation peer-to-peer body signatures, not
|
|
25
|
-
* agent TPS-Ed25519 auth) — deliberately left alone.
|
|
26
|
-
*
|
|
27
19
|
* Signed payload format (must match the TPS CLI signer exactly — changing
|
|
28
20
|
* it breaks every agent's auth): `${agentId}:${ts}:${nonce}:${METHOD}:${pathname}${search}`.
|
|
29
21
|
* Auth header format: `TPS-Ed25519 <agentId>:<ts>:<nonce>:<signatureB64>`.
|
|
30
|
-
*
|
|
22
|
+
* Replay key: `${agentId}:${nonce}` (stored as `a:${agentId}:${nonce}`).
|
|
31
23
|
*/
|
|
32
24
|
import { b64ToArrayBuffer } from "./b64.js";
|
|
33
25
|
export { b64ToArrayBuffer };
|
|
@@ -40,6 +32,11 @@ export { b64ToArrayBuffer };
|
|
|
40
32
|
* docs, or test in this repo currently sets that var, so preserving it is
|
|
41
33
|
* additive/no-op for today's deployments while keeping agent-auth.ts's
|
|
42
34
|
* stated "plugin-shaped, config via env" design intent.
|
|
35
|
+
*
|
|
36
|
+
* The replay store keeps a nonce for REPLAY_RETENTION_MS (resources/
|
|
37
|
+
* replay-store.ts); a window that is not shorter than half of that makes the
|
|
38
|
+
* agent-auth replay guard unavailable, and every signed request is refused
|
|
39
|
+
* with a named error.
|
|
43
40
|
*/
|
|
44
41
|
export const WINDOW_MS = Number(process.env.FLAIR_AGENT_AUTH_WINDOW_MS) || 30_000;
|
|
45
42
|
// ─── Auth header parsing (single shared implementation) ────────────────────
|
|
@@ -79,46 +76,6 @@ export function parseTpsEd25519Header(header) {
|
|
|
79
76
|
return null;
|
|
80
77
|
return { agentId: m[1], tsRaw: m[2], nonce: m[3], signatureB64: m[4] };
|
|
81
78
|
}
|
|
82
|
-
// ─── Replay guard (single shared instance) ─────────────────────────────────
|
|
83
|
-
//
|
|
84
|
-
// nonceSeen is the ONE module-level singleton — the whole point of this
|
|
85
|
-
// consolidation. A nonce recorded via any one of the 3 call sites is
|
|
86
|
-
// immediately visible to the other two, because they all import this same
|
|
87
|
-
// module (Node/bun module cache = one instance per process).
|
|
88
|
-
const nonceSeen = new Map();
|
|
89
|
-
/** Remove nonce records older than WINDOW_MS relative to `now`. */
|
|
90
|
-
export function pruneNonces(now = Date.now()) {
|
|
91
|
-
for (const [k, ts] of nonceSeen) {
|
|
92
|
-
if (now - ts > WINDOW_MS)
|
|
93
|
-
nonceSeen.delete(k);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
/**
|
|
97
|
-
* Prune expired entries, then report whether (agentId, nonce) has already
|
|
98
|
-
* been recorded within the current window. Returns true = REPLAY (reject).
|
|
99
|
-
*
|
|
100
|
-
* Deliberately does NOT record as a side effect — callers check this BEFORE
|
|
101
|
-
* verifying the signature and call `recordNonce` only AFTER the signature is
|
|
102
|
-
* confirmed valid (matches the pre-consolidation per-site behavior at all 3
|
|
103
|
-
* sites exactly: an invalid-signature attempt never burns the nonce, so a
|
|
104
|
-
* client that retries with a corrected signature isn't locked out).
|
|
105
|
-
*/
|
|
106
|
-
export function isNonceReplay(agentId, nonce, now = Date.now()) {
|
|
107
|
-
pruneNonces(now);
|
|
108
|
-
return nonceSeen.has(`${agentId}:${nonce}`);
|
|
109
|
-
}
|
|
110
|
-
/** Record (agentId, nonce) as seen at `ts`. Call only after successful verification. */
|
|
111
|
-
export function recordNonce(agentId, nonce, ts) {
|
|
112
|
-
nonceSeen.set(`${agentId}:${nonce}`, ts);
|
|
113
|
-
}
|
|
114
|
-
/**
|
|
115
|
-
* Test-only escape hatch: clear all recorded nonces. Never called by any
|
|
116
|
-
* production call site — exists so unit tests can isolate the shared
|
|
117
|
-
* singleton between cases instead of relying on WINDOW_MS-based expiry.
|
|
118
|
-
*/
|
|
119
|
-
export function __clearNoncesForTest() {
|
|
120
|
-
nonceSeen.clear();
|
|
121
|
-
}
|
|
122
79
|
// ─── Ed25519 public key import (cached) ────────────────────────────────────
|
|
123
80
|
//
|
|
124
81
|
// Single shared key cache, keyed by the raw publicKeyStr. Consolidating the
|