@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
|
@@ -218,19 +218,16 @@ export function makeByIdReadGate(readScope) {
|
|
|
218
218
|
return superGet(target);
|
|
219
219
|
}
|
|
220
220
|
// Non-admin agent: scoped per the table's own read-scope model. The scope
|
|
221
|
-
// is evaluated on the
|
|
222
|
-
//
|
|
223
|
-
//
|
|
221
|
+
// is evaluated on the UNSELECTED row: the gate passes super.get a fresh plain
|
|
222
|
+
// object it builds itself, carrying only the id (or nothing, when the target
|
|
223
|
+
// has no id), and checks the row that returns. In Harper's default instance
|
|
224
|
+
// mode the resource is loaded by id before get runs, and get returns that
|
|
225
|
+
// whole record when the target carries no select or property. The caller's
|
|
226
|
+
// target, and anything its class does when constructed, never shapes the row
|
|
227
|
+
// the decision sees. A target that asks for a selection or a single property
|
|
228
|
+
// gets that shaped result only once the unselected row passes.
|
|
224
229
|
const shaped = typeof target === "object" && target !== null && (target.select != null || target.property != null);
|
|
225
|
-
|
|
226
|
-
if (shaped) {
|
|
227
|
-
const Ctor = target.constructor;
|
|
228
|
-
if (typeof Ctor !== "function")
|
|
229
|
-
return NOT_FOUND(); // fail closed: cannot re-read unshaped
|
|
230
|
-
unshaped = new Ctor();
|
|
231
|
-
unshaped.id = targetId;
|
|
232
|
-
}
|
|
233
|
-
const record = await superGet(unshaped);
|
|
230
|
+
const record = await superGet(targetId != null ? { id: targetId } : {});
|
|
234
231
|
if (!record) {
|
|
235
232
|
// Row did not load: either it genuinely does not exist, OR — the #1181
|
|
236
233
|
// failure — a by-id read reached here on an unloaded instance and
|
|
@@ -101,9 +101,9 @@
|
|
|
101
101
|
* explicitly deferred by Flint's post-slice-1 comment on #520 ("Sherlock
|
|
102
102
|
* flagging stamp-default → stamp-strict convergence... Registry slice
|
|
103
103
|
* follows" — convergence is a FUTURE decision, not made here). Each
|
|
104
|
-
* sub-field is optional because
|
|
105
|
-
* `stampAttribution` on both methods
|
|
106
|
-
*
|
|
104
|
+
* sub-field is optional because a table's write path need not call
|
|
105
|
+
* `stampAttribution` on both methods; an absent sub-field is not a
|
|
106
|
+
* placeholder.
|
|
107
107
|
* The stamped attribute name is always `ownerField` above — no type uses a
|
|
108
108
|
* different field for attribution vs. ownership scoping.
|
|
109
109
|
*
|
|
@@ -291,9 +291,9 @@ export const RECORD_TYPES = {
|
|
|
291
291
|
ownerField: "agentId",
|
|
292
292
|
identity: "gated",
|
|
293
293
|
readScope: "owner-only",
|
|
294
|
-
//
|
|
295
|
-
//
|
|
296
|
-
attribution: { put: "stamp-strict" },
|
|
294
|
+
// post() (a collection create) and put() (upsert) share one preparation
|
|
295
|
+
// (Relationship.ts's prepareRelationshipWrite), with the same mode.
|
|
296
|
+
attribution: { post: "stamp-strict", put: "stamp-strict" },
|
|
297
297
|
provenance: true,
|
|
298
298
|
remEligible: false,
|
|
299
299
|
federation: "included",
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* All authorization decisions are made here against an already-resolved auth
|
|
10
10
|
* verdict; the resource layer only resolves the verdict and forwards the call.
|
|
11
11
|
*/
|
|
12
|
+
import { isForbiddenOwnerMutation, ownerMutationRefusal, OWNER_FIELDS } from "./record-owner-guard.js";
|
|
12
13
|
import { capDecision, computeContentHash, isUnconsumed, LOCAL_ORG_SENTINEL, reconcileState, sweepDecision, verifyMessageSignature, } from "./relay-lib.js";
|
|
13
14
|
// ─── HTTP responses (Response is a web global, not a Harper import) ──────────
|
|
14
15
|
const json = (status, obj) => new Response(JSON.stringify(obj), { status, headers: { "Content-Type": "application/json" } });
|
|
@@ -70,7 +71,11 @@ function acceptedView(row) {
|
|
|
70
71
|
* per-sender sub-cap, and delivers. Returns the accepted envelope — the SAME
|
|
71
72
|
* shape regardless of whether `to` exists (no existence oracle): the only
|
|
72
73
|
* principal ever looked up is the sender (needed for its public key), which is
|
|
73
|
-
* the authenticated caller and therefore always present.
|
|
74
|
+
* the authenticated caller and therefore always present. A send that reuses a
|
|
75
|
+
* stored message id is answered with that message's accepted view only when
|
|
76
|
+
* it has the same sender; any other sender gets the owner-guard 403
|
|
77
|
+
* (record-owner-guard.ts's ownerMutationRefusal), which carries no field of
|
|
78
|
+
* the stored message.
|
|
74
79
|
*/
|
|
75
80
|
export async function relaySend(deps, auth, content) {
|
|
76
81
|
if (auth.kind === "anonymous")
|
|
@@ -120,9 +125,29 @@ export async function relaySend(deps, auth, content) {
|
|
|
120
125
|
// Retry-dedup: an identical resend — same primary id, or the same content
|
|
121
126
|
// hash from this sender to this recipient — returns the already-accepted
|
|
122
127
|
// envelope. No second row, and (critically) no second charge against the cap.
|
|
123
|
-
|
|
124
|
-
|
|
128
|
+
//
|
|
129
|
+
// The same-id answer is for the ORIGINAL SENDER only. A stored message is
|
|
130
|
+
// owned by its `from` (OWNER_FIELDS.Message), and this send's `from` is the
|
|
131
|
+
// verified signer. When the id is held by another sender, the send is
|
|
132
|
+
// refused with the owner-guard refusal — the same response the auth
|
|
133
|
+
// middleware gives a write to `/Message/<id>` for a message the caller does
|
|
134
|
+
// not own — and nothing from the stored row is returned. The rule is about
|
|
135
|
+
// the message, not the caller's role: an admin sending as X gets the same
|
|
136
|
+
// refusal for an id held by Y. The lookup fails CLOSED: if the stored row
|
|
137
|
+
// cannot be read, the send is refused the same way, never written over it.
|
|
138
|
+
let existingById;
|
|
139
|
+
try {
|
|
140
|
+
existingById = (await Promise.resolve(deps.messages.get(String(content.id)))) ?? null;
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
return ownerMutationRefusal("Message");
|
|
144
|
+
}
|
|
145
|
+
if (existingById) {
|
|
146
|
+
if (isForbiddenOwnerMutation(existingById, OWNER_FIELDS.Message, String(content.from))) {
|
|
147
|
+
return ownerMutationRefusal("Message");
|
|
148
|
+
}
|
|
125
149
|
return acceptedView(existingById);
|
|
150
|
+
}
|
|
126
151
|
// The recipient's inbox — queried by the @indexed `to`, never the whole table
|
|
127
152
|
// (Sherlock P0). Serves both dedup (same content from this sender) and the cap.
|
|
128
153
|
const recipientRows = await queryRows(deps.messages, [{ attribute: "to", value: content.to }]);
|
|
@@ -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.
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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
|
|
24
|
-
* and searchReady:false names the lag. We do
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
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.
|
|
84
|
-
// index means
|
|
85
|
-
//
|
|
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
|
-
//
|
|
90
|
-
//
|
|
91
|
-
// a node that is already
|
|
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(
|
|
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
|
-
|
|
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",
|