@tpsdev-ai/flair 0.56.0 → 0.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -20
- package/SECURITY.md +4 -1
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1800 -293
- package/dist/commands/agent.js +22 -15
- package/dist/commands/bridge.js +40 -3
- package/dist/commands/doctor.js +214 -4
- package/dist/commands/federation.js +265 -38
- package/dist/commands/hook.js +10 -2
- package/dist/commands/init.js +179 -48
- 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/auth-resolve.js +46 -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/instance-identity-row.js +580 -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/redact-token-id.js +197 -0
- 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 +39 -2
- package/dist/resources/Asset.js +3 -11
- package/dist/resources/Credential.js +4 -10
- package/dist/resources/Federation.js +299 -127
- package/dist/resources/Integration.js +8 -32
- package/dist/resources/Memory.js +623 -86
- package/dist/resources/MemoryArchive.js +9 -0
- package/dist/resources/MemoryBootstrap.js +23 -12
- package/dist/resources/MemoryCandidate.js +3 -11
- package/dist/resources/MemoryDedupStats.js +1 -1
- package/dist/resources/MemoryFeed.js +214 -5
- package/dist/resources/MemoryGrant.js +19 -40
- 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 +55 -18
- package/dist/resources/Presence.js +18 -10
- package/dist/resources/RecordUsage.js +30 -40
- package/dist/resources/Relationship.js +170 -89
- package/dist/resources/SemanticSearch.js +44 -19
- 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 +164 -50
- 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/bm25.js +13 -14
- 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-cleanup.js +289 -51
- package/dist/resources/federation-crypto.js +65 -19
- package/dist/resources/health.js +105 -22
- 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/in-process-api.js +2 -1
- package/dist/resources/instance-create-lock.js +363 -0
- package/dist/resources/instance-identity-rows.js +43 -0
- package/dist/resources/instance-identity.js +97 -12
- package/dist/resources/mcp-handler.js +155 -51
- package/dist/resources/mcp-tool-arguments.js +83 -0
- package/dist/resources/mcp-tools.js +28 -25
- 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/memory-visibility.js +10 -7
- 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/rate-limit.js +6 -4
- package/dist/resources/record-owner-guard.js +19 -0
- package/dist/resources/record-type-kit.js +44 -23
- 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 +26 -22
- package/dist/resources/semantic-retrieval-core.js +103 -4
- package/dist/resources/table-helpers.js +33 -0
- 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/instance-identity-row.js +580 -0
- package/dist/src/lib/memory-attributes.js +77 -0
- package/dist/src/lib/redact-token-id.js +197 -0
- package/docs/api-reference.md +80 -16
- package/docs/auth.md +5 -5
- package/docs/claude-code.md +137 -6
- package/docs/deploying-on-fabric.md +6 -3
- package/docs/deployment.md +1 -1
- package/docs/embedding-in-a-harper-app.md +3 -3
- package/docs/federation.md +17 -10
- package/docs/hosted-on-fabric.md +4 -3
- package/docs/integrations.md +28 -19
- package/docs/mcp-clients.md +26 -32
- package/docs/n8n.md +8 -8
- package/docs/notes/mcp-oauth-model2.md +27 -18
- package/docs/openclaw.md +29 -28
- package/docs/quickstart.md +5 -0
- package/docs/releasing.md +134 -2
- package/docs/spoke-bringup.md +14 -11
- package/docs/standalone-local.md +2 -2
- package/docs/supply-chain-policy.md +28 -10
- package/docs/system-requirements.md +1 -1
- package/docs/troubleshooting.md +11 -0
- package/docs/upgrade.md +189 -63
- 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
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* POST /MemoryMaintenance — runs cleanup tasks:
|
|
5
5
|
* 1. Delete expired ephemeral memories (expiresAt < now)
|
|
6
|
-
* 2. Archive old session memories (> 30 days, standard durability)
|
|
6
|
+
* 2. Archive validTo-expired memories and old session memories (> 30 days, standard durability)
|
|
7
7
|
* 3. Report stats
|
|
8
8
|
*
|
|
9
9
|
* Designed to run periodically (daily cron, scheduler, or REM nightly cycle).
|
|
@@ -17,8 +17,23 @@
|
|
|
17
17
|
* to gate auth correctly.
|
|
18
18
|
*/
|
|
19
19
|
import { Resource, databases } from "harper";
|
|
20
|
+
import { MEMORY_HOST_SOURCE_TABLE } from "./memory-host-source.js";
|
|
21
|
+
/** Maintenance creates an owned transaction for each expiry or archive item;
|
|
22
|
+
* the Memory and pointer operations join that owned transaction (both tables
|
|
23
|
+
* in database flair). Failures are NOT swallowed: a throw propagates to the
|
|
24
|
+
* caller's error path. A missing pointer table is REPORTED (throws), never
|
|
25
|
+
* silently skipped — cleanup is hygiene, so its failure must be visible. */
|
|
26
|
+
async function deletePointerRowOrThrow(memoryId, ctx) {
|
|
27
|
+
const table = databases.flair?.[MEMORY_HOST_SOURCE_TABLE];
|
|
28
|
+
if (!table?.delete) {
|
|
29
|
+
throw new Error("MemoryHostSource table unavailable");
|
|
30
|
+
}
|
|
31
|
+
await table.delete(memoryId, ctx);
|
|
32
|
+
}
|
|
20
33
|
import { isAdmin } from "./agent-auth.js";
|
|
21
34
|
import { noteMemoryUpsert, noteMemoryDelete } from "./bm25-index-service.js";
|
|
35
|
+
import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
|
|
36
|
+
import { withOwnedTransaction } from "./request-transaction.js";
|
|
22
37
|
export class MemoryMaintenance extends Resource {
|
|
23
38
|
/** POST requires auth — either an agent acting on its own memories, or admin. */
|
|
24
39
|
allowCreate() {
|
|
@@ -48,7 +63,7 @@ export class MemoryMaintenance extends Resource {
|
|
|
48
63
|
});
|
|
49
64
|
}
|
|
50
65
|
const now = new Date();
|
|
51
|
-
const stats = { expired: 0, archived: 0, total: 0, errors: 0, agent: targetAgent || "all" };
|
|
66
|
+
const stats = { expired: 0, archived: 0, total: 0, errors: 0, orphans: 0, agent: targetAgent || "all" };
|
|
52
67
|
try {
|
|
53
68
|
for await (const record of databases.flair.Memory.search()) {
|
|
54
69
|
// Skip records not belonging to target agent (unless admin running fleet-wide).
|
|
@@ -65,14 +80,21 @@ export class MemoryMaintenance extends Resource {
|
|
|
65
80
|
new Date(record.expiresAt) < now) {
|
|
66
81
|
if (!dryRun) {
|
|
67
82
|
try {
|
|
68
|
-
|
|
83
|
+
// A1'' item 2 (0c): the raw expiry delete runs in its OWN
|
|
84
|
+
// transaction together with the pointer delete, so a failed
|
|
85
|
+
// pointer delete aborts both and nothing is deleted.
|
|
86
|
+
await withOwnedTransaction(ctx, async (c) => {
|
|
87
|
+
await databases.flair.Memory.delete(record.id, c);
|
|
88
|
+
await deletePointerRowOrThrow(record.id, c);
|
|
89
|
+
});
|
|
69
90
|
// flair#1357 — ephemeral expiry removes the row from what the
|
|
70
91
|
// lexical leg may score.
|
|
71
92
|
noteMemoryDelete(record.id);
|
|
72
93
|
stats.expired++;
|
|
73
94
|
}
|
|
74
|
-
catch {
|
|
95
|
+
catch (err) {
|
|
75
96
|
stats.errors++;
|
|
97
|
+
console.error("MemoryMaintenance: expiry delete failed (aborted, nothing deleted)", err);
|
|
76
98
|
}
|
|
77
99
|
}
|
|
78
100
|
else {
|
|
@@ -80,37 +102,91 @@ export class MemoryMaintenance extends Resource {
|
|
|
80
102
|
}
|
|
81
103
|
continue;
|
|
82
104
|
}
|
|
83
|
-
// 2. Archive
|
|
84
|
-
//
|
|
105
|
+
// 2. Archive memories whose validity ended, plus old standard session
|
|
106
|
+
// notes (> 30 days) that weren't promoted to persistent. Use one
|
|
107
|
+
// archive path so a row meeting both criteria is counted only once.
|
|
85
108
|
// Soft-archive removes them from search results but keeps the data.
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
record.createdAt)
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
}
|
|
111
|
-
else {
|
|
109
|
+
const validToExpired = record.validTo && new Date(record.validTo) < now;
|
|
110
|
+
const oldSession = record.durability === "standard" &&
|
|
111
|
+
record.type === "session" && record.createdAt &&
|
|
112
|
+
now.getTime() - new Date(record.createdAt).getTime() > 30 * 24 * 3600_000;
|
|
113
|
+
if (!record.archived && (validToExpired || oldSession)) {
|
|
114
|
+
if (!dryRun) {
|
|
115
|
+
try {
|
|
116
|
+
const archivedRow = {
|
|
117
|
+
...record,
|
|
118
|
+
archived: true,
|
|
119
|
+
archivedAt: now.toISOString(),
|
|
120
|
+
};
|
|
121
|
+
stripUndeclaredMemoryAttributes(archivedRow);
|
|
122
|
+
// A1'' item 2 (0c): the archive write and its pointer delete
|
|
123
|
+
// share ONE OWNED transaction; a failed pointer delete cannot
|
|
124
|
+
// still commit the archived row.
|
|
125
|
+
await withOwnedTransaction(ctx, async (c) => {
|
|
126
|
+
await databases.flair.Memory.update(record.id, archivedRow, c);
|
|
127
|
+
await deletePointerRowOrThrow(record.id, c);
|
|
128
|
+
});
|
|
129
|
+
// flair#1357 — an `archived` flip changes what the retrieval
|
|
130
|
+
// conditions (`archived not_equal true`) admit, so the lexical
|
|
131
|
+
// index has to see it, not just content writes.
|
|
132
|
+
noteMemoryUpsert(archivedRow);
|
|
112
133
|
stats.archived++;
|
|
113
134
|
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
stats.errors++;
|
|
137
|
+
console.error("MemoryMaintenance: archive failed (aborted, nothing archived)", err);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
stats.archived++;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// 3. Orphan sweep: pointer rows whose Memory is MISSING or ARCHIVED. An
|
|
146
|
+
// orphan is unreadable by construction (the only read path joins pointers
|
|
147
|
+
// INTO Memory results), but it should not be left behind either. A
|
|
148
|
+
// failed row read or delete is counted and the sweep continues; the
|
|
149
|
+
// incomplete run is reported below (HTTP 500), never silently ignored.
|
|
150
|
+
const pointerTable = databases.flair?.[MEMORY_HOST_SOURCE_TABLE];
|
|
151
|
+
if (!dryRun && !pointerTable?.search) {
|
|
152
|
+
// Hygiene: a missing sweep table is REPORTED, never silently skipped.
|
|
153
|
+
throw new Error("MemoryHostSource table unavailable (orphan sweep)");
|
|
154
|
+
}
|
|
155
|
+
if (pointerTable?.search && !dryRun) {
|
|
156
|
+
for await (const ptr of pointerTable.search()) {
|
|
157
|
+
const memoryId = ptr?.memoryId;
|
|
158
|
+
if (typeof memoryId !== "string" || memoryId.length === 0)
|
|
159
|
+
continue;
|
|
160
|
+
try {
|
|
161
|
+
const mem = await databases.flair.Memory.get(memoryId, ctx);
|
|
162
|
+
if (mem && mem.archived !== true)
|
|
163
|
+
continue;
|
|
164
|
+
// 0d: RE-CHECK inside an OWNED transaction before deleting. The
|
|
165
|
+
// first read is outside it, so a new row reusing this id in
|
|
166
|
+
// between must not be orphan-deleted; the conditional re-read
|
|
167
|
+
// inside the transaction closes that read-to-delete gap. The
|
|
168
|
+
// re-read is passed the owned transaction `c` (Gauge pass-5 item 2).
|
|
169
|
+
//
|
|
170
|
+
// Round 22: one orphan's failure must abort only THAT orphan, not
|
|
171
|
+
// the whole sweep — catch it, count stats.errors, and continue (the
|
|
172
|
+
// item loops above already work this way). stats.orphans counts a
|
|
173
|
+
// row only AFTER its owned transaction COMMITS (the count moves out
|
|
174
|
+
// of the callback). Pinned by test/unit/memory-host-source.test.ts
|
|
175
|
+
// (r22-orphan-continues) — RED if the try/catch is removed.
|
|
176
|
+
let committed = false;
|
|
177
|
+
await withOwnedTransaction(ctx, async (c) => {
|
|
178
|
+
const again = await databases.flair.Memory.get(memoryId, c);
|
|
179
|
+
if (!again || again.archived === true) {
|
|
180
|
+
await deletePointerRowOrThrow(memoryId, c);
|
|
181
|
+
committed = true;
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
if (committed)
|
|
185
|
+
stats.orphans++;
|
|
186
|
+
}
|
|
187
|
+
catch (err) {
|
|
188
|
+
stats.errors++;
|
|
189
|
+
console.error("MemoryMaintenance: orphan sweep failed (continuing)", err);
|
|
114
190
|
}
|
|
115
191
|
}
|
|
116
192
|
}
|
|
@@ -118,6 +194,18 @@ export class MemoryMaintenance extends Resource {
|
|
|
118
194
|
catch (err) {
|
|
119
195
|
return new Response(JSON.stringify({ error: err.message, stats }), { status: 500, headers: { "content-type": "application/json" } });
|
|
120
196
|
}
|
|
197
|
+
// A1-iv item 4 (cleanup is hygiene): if any item's cleanup FAILED, the run
|
|
198
|
+
// is NOT complete — report a failure naming the counts, never a
|
|
199
|
+
// "Maintenance complete" success. The work already committed stands; the
|
|
200
|
+
// response is about the run's honesty.
|
|
201
|
+
if (stats.errors > 0) {
|
|
202
|
+
return new Response(JSON.stringify({
|
|
203
|
+
error: "maintenance_incomplete",
|
|
204
|
+
message: `${stats.errors} cleanup error(s); see counts`,
|
|
205
|
+
stats, expired: stats.expired, archived: stats.archived, total: stats.total,
|
|
206
|
+
errors: stats.errors, orphans: stats.orphans,
|
|
207
|
+
}), { status: 500, headers: { "content-type": "application/json" } });
|
|
208
|
+
}
|
|
121
209
|
// Flatten the historical { stats } wrapper into the top level so callers
|
|
122
210
|
// can read `.expired` / `.archived` directly. The wrapper shape is kept
|
|
123
211
|
// for backward compatibility with `flair rem light`.
|
|
@@ -128,6 +216,7 @@ export class MemoryMaintenance extends Resource {
|
|
|
128
216
|
archived: stats.archived,
|
|
129
217
|
total: stats.total,
|
|
130
218
|
errors: stats.errors,
|
|
219
|
+
orphans: stats.orphans,
|
|
131
220
|
};
|
|
132
221
|
}
|
|
133
222
|
}
|
|
@@ -54,6 +54,7 @@ import { isAdmin, allowVerified } from "./agent-auth.js";
|
|
|
54
54
|
import { patchRecordSilent } from "./table-helpers.js";
|
|
55
55
|
import { buildReflectionPrompt, buildExecutePrompt, resolveReflectActor, generateCandidates, releaseRequestTransaction, runExecuteDistillation, dedupeCandidates, memoryMatchesReflectScope, buildStagedCandidateRow, isContinuityScopeTag, filterStaleSessionIntentCandidates, resolveCandidateVisibilityRuling, considerForOldestUnreflectedCap, isRemAbortRequested, resolveMaxMemoriesPerRun, shouldStampLastReflected, DEFAULT_STALE_INTENT_HORIZON_MS, REM_GATHER_YIELD_BUDGET_MS, } from "./memory-reflect-lib.js";
|
|
56
56
|
import { reflectModelsGenerate } from "./memory-reflect-models.js";
|
|
57
|
+
import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
|
|
57
58
|
/** Same path `flair rem pause` writes. Duplicated across the src/ boundary. */
|
|
58
59
|
const REM_PAUSE_FLAG = resolve(homedir(), ".flair", "rem.paused");
|
|
59
60
|
const GATHER_SELECT = [
|
|
@@ -292,7 +293,9 @@ export class ReflectMemories extends Resource {
|
|
|
292
293
|
if (shouldStampLastReflected({ execute, generateSucceeded: true })) {
|
|
293
294
|
const now = new Date().toISOString();
|
|
294
295
|
for (const memory of memories) {
|
|
295
|
-
|
|
296
|
+
const reflectPatch = { lastReflected: now };
|
|
297
|
+
stripUndeclaredMemoryAttributes(reflectPatch);
|
|
298
|
+
patchRecordSilent(databases.flair.Memory, memory.id, reflectPatch);
|
|
296
299
|
}
|
|
297
300
|
}
|
|
298
301
|
return {
|
|
@@ -11,8 +11,10 @@
|
|
|
11
11
|
* compares per-agent primary counts against per-agent secondary-index counts
|
|
12
12
|
* (an equals lookup on agentId). Any agent whose secondary count is below
|
|
13
13
|
* its primary count has unindexed records. Re-PUT every record with the
|
|
14
|
-
* _reindex escape hatch
|
|
15
|
-
*
|
|
14
|
+
* _reindex escape hatch: Memory.put() retains declared and named allowed
|
|
15
|
+
* fields, restores stored provenance and preserves an existing incarnation
|
|
16
|
+
* token (or generates an absent one). Other undeclared fields are stripped.
|
|
17
|
+
* No updatedAt bump, embedding regeneration or safety rescan is performed.
|
|
16
18
|
*
|
|
17
19
|
* Why this exists: Harper's background runIndexing() pass populates secondary
|
|
18
20
|
* indices only on schema changes that add a new indexed attribute. If that
|
|
@@ -102,8 +104,9 @@ export class MemoryReindex extends Resource {
|
|
|
102
104
|
stats,
|
|
103
105
|
};
|
|
104
106
|
}
|
|
105
|
-
// Pass 3: re-PUT every primary-store record with _reindex=true
|
|
106
|
-
//
|
|
107
|
+
// Pass 3: re-PUT every primary-store record with _reindex=true, retaining
|
|
108
|
+
// declared/named fields and stored provenance, stripping other undeclared
|
|
109
|
+
// fields and generating an absent token. The re-PUT forces Harper to re-insert
|
|
107
110
|
// into all secondary indices. Cheaper-than-sound variants (only re-PUT records
|
|
108
111
|
// that appear missing) would miss rows the primary scan sees fine but that
|
|
109
112
|
// Harper's read path can't locate via any index path.
|
|
@@ -40,45 +40,82 @@
|
|
|
40
40
|
* ledger is an audit trail, not a shared surface — there is no product need
|
|
41
41
|
* to expose "which agent used which memory" cross-agent, and narrowing this
|
|
42
42
|
* costs nothing.
|
|
43
|
+
*
|
|
44
|
+
* And within its own contributions, a non-admin agent sees a row only while
|
|
45
|
+
* the memory the row names exists and is in its Memory read scope
|
|
46
|
+
* (resolveReadScope — the rule Memory.get() applies to a non-admin reader).
|
|
47
|
+
* A row about a memory the reader cannot read reads exactly like a row that
|
|
48
|
+
* does not exist: 404 by id, absent from a collection read. A ledger row is
|
|
49
|
+
* therefore never evidence, to a non-admin reader, about a memory it cannot
|
|
50
|
+
* otherwise see. Admin and trusted internal reads are unfiltered (get() and
|
|
51
|
+
* search() below). The rule lives in
|
|
52
|
+
* ./usage-recording.ts (isLedgerRowVisible / readableLedgerRows), next to the
|
|
53
|
+
* write-side gate. Like Memory's reads, a non-admin read here ignores the
|
|
54
|
+
* caller's `select`/`property`, so the decision always sees the stored
|
|
55
|
+
* `memoryId`. A collection read filters after the owner-scoped query, so a
|
|
56
|
+
* `limit` can return fewer rows than it names.
|
|
43
57
|
*/
|
|
44
58
|
import { databases } from "harper";
|
|
45
59
|
import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
|
|
60
|
+
import { makeByIdReadGate, makeReadScope, makeScopedSearch } from "./record-type-kit.js";
|
|
61
|
+
import { isLedgerRowVisible, readableLedgerRows } from "./usage-recording.js";
|
|
62
|
+
// Owner-only read scope through the shared by-id gate and scoped search.
|
|
63
|
+
const usageReadScope = makeReadScope("owner-only", "agentId");
|
|
64
|
+
const usageByIdReadGate = makeByIdReadGate(usageReadScope);
|
|
65
|
+
const usageScopedSearch = makeScopedSearch(usageReadScope);
|
|
46
66
|
const FORBIDDEN = (msg) => new Response(JSON.stringify({ error: msg }), { status: 403, headers: { "Content-Type": "application/json" } });
|
|
47
67
|
const UNAUTH = () => new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
|
|
48
68
|
const NOT_FOUND = () => new Response(JSON.stringify({ error: "not found" }), { status: 404, headers: { "Content-Type": "application/json" } });
|
|
69
|
+
/** The caller's query without its `select`/`property` (a key deletion, not a
|
|
70
|
+
* selection parser — the same rule resources/Memory.ts applies to a
|
|
71
|
+
* non-admin read, so the read decision sees the stored row). */
|
|
72
|
+
function withoutCallerSelection(query) {
|
|
73
|
+
if (!query || typeof query !== "object")
|
|
74
|
+
return query;
|
|
75
|
+
if (query.select === undefined && query.property === undefined)
|
|
76
|
+
return query;
|
|
77
|
+
const copy = Array.isArray(query) ? query.slice() : { ...query };
|
|
78
|
+
delete copy.select;
|
|
79
|
+
delete copy.property;
|
|
80
|
+
return copy;
|
|
81
|
+
}
|
|
49
82
|
export class MemoryUsage extends databases.flair.MemoryUsage {
|
|
50
83
|
/** Self-authorize now that the global gate is non-rejecting — same pattern
|
|
51
84
|
* as every other table resource in this codebase (Memory.ts/MemoryGrant.ts
|
|
52
85
|
* etc.). Per-record scoping happens in get()/search() below. */
|
|
53
86
|
allowRead() { return allowVerified(this.getContext?.()); }
|
|
54
87
|
async get(target) {
|
|
88
|
+
// Collection / query reads are governed by search() below.
|
|
55
89
|
if (!target || (typeof target === "object" && target.isCollection)) {
|
|
56
90
|
return this.search(target);
|
|
57
91
|
}
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
if (auth.kind
|
|
62
|
-
return super.get(
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
92
|
+
const ctx = this.getContext?.();
|
|
93
|
+
const auth = await resolveAgentAuth(ctx);
|
|
94
|
+
// Anonymous (404), trusted internal and admin (unfiltered): the shared gate.
|
|
95
|
+
if (auth.kind !== "agent" || auth.isAdmin) {
|
|
96
|
+
return usageByIdReadGate.call(this, target, (t) => super.get(t));
|
|
97
|
+
}
|
|
98
|
+
// Non-admin agent: the owner-only gate on the stored row (read by a plain
|
|
99
|
+
// id-only target, so the caller's select/property never shapes it), then
|
|
100
|
+
// the memory that row names must be readable by this agent. Both denials
|
|
101
|
+
// are the same 404 as a missing row.
|
|
102
|
+
const targetId = typeof target === "string" ? target : target?.id;
|
|
103
|
+
const row = await usageByIdReadGate.call(this, targetId != null ? { id: targetId } : {}, (t) => super.get(t));
|
|
104
|
+
if (!row || row instanceof Response)
|
|
105
|
+
return row ?? NOT_FOUND();
|
|
106
|
+
return (await isLedgerRowVisible(ctx, auth.agentId, row)) ? row : NOT_FOUND();
|
|
67
107
|
}
|
|
68
108
|
async search(query) {
|
|
69
|
-
const
|
|
109
|
+
const ctx = this.getContext?.();
|
|
110
|
+
const auth = await resolveAgentAuth(ctx);
|
|
70
111
|
if (auth.kind === "anonymous")
|
|
71
112
|
return UNAUTH();
|
|
72
113
|
if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin))
|
|
73
114
|
return super.search(query);
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
return super.search(query);
|
|
79
|
-
}
|
|
80
|
-
const conditions = Array.isArray(query) && query.length > 0 ? [scope, ...query] : [scope];
|
|
81
|
-
return super.search(conditions);
|
|
115
|
+
// Owner-only query (outermost AND), then only the rows about memories this
|
|
116
|
+
// agent can read — see the module doc.
|
|
117
|
+
const rows = await usageScopedSearch(auth.agentId, withoutCallerSelection(query), (q) => super.search(q));
|
|
118
|
+
return readableLedgerRows(ctx, auth.agentId, rows);
|
|
82
119
|
}
|
|
83
120
|
// Append-only ledger: rows are created via RecordUsage's RAW table call
|
|
84
121
|
// (bypasses this class entirely — see module doc), never via this
|
|
@@ -39,7 +39,8 @@ import { fileURLToPath } from "node:url";
|
|
|
39
39
|
import { createRequire } from "node:module";
|
|
40
40
|
import { resolveAgentAuth, isPrincipalDeactivated } from "./agent-auth.js";
|
|
41
41
|
import { agentRecordIsAdmin } from "./agent-admin.js";
|
|
42
|
-
import { WINDOW_MS,
|
|
42
|
+
import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
|
|
43
|
+
import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
|
|
43
44
|
// ─── Constants ────────────────────────────────────────────────────────────────
|
|
44
45
|
const CURRENT_TASK_MAX_LENGTH = 200;
|
|
45
46
|
const VALID_ACTIVITIES = new Set(["coding", "reviewing", "planning", "debugging", "idle"]);
|
|
@@ -83,10 +84,10 @@ export function publicRosterEnabled() {
|
|
|
83
84
|
*
|
|
84
85
|
* GET /Presence/<id> is NOT on auth-middleware.ts's short-circuit list (only
|
|
85
86
|
* the exact "/Presence" collection GET is). The middleware verifies the
|
|
86
|
-
* TPS-Ed25519 signature and records the nonce in the ONE shared
|
|
87
|
+
* TPS-Ed25519 signature and records the nonce in the ONE shared replay store,
|
|
87
88
|
* annotating request.tpsAgent but NOT verifyAgentRequest's per-request memo.
|
|
88
89
|
* Calling verifyAgentRequest() again would re-consume that same nonce, read as
|
|
89
|
-
* a replay (
|
|
90
|
+
* a replay (claimAgentNonce) and deny a legitimate agent. resolveAgentAuth()
|
|
90
91
|
* consults the middleware's tpsAgent/tpsAnonymous annotations FIRST, and only
|
|
91
92
|
* falls back to a header verify when the middleware never ran (the
|
|
92
93
|
* short-circuited collection GET) — so it reuses the established verdict
|
|
@@ -200,11 +201,11 @@ export function buildPresenceRecord(agentId, now, currentTask, activity, existin
|
|
|
200
201
|
};
|
|
201
202
|
}
|
|
202
203
|
// ─── Nonce replay + crypto helpers ─────────────────────────────────────────────
|
|
203
|
-
// WINDOW_MS
|
|
204
|
-
//
|
|
205
|
-
//
|
|
206
|
-
//
|
|
207
|
-
//
|
|
204
|
+
// WINDOW_MS and importEd25519Key live in ./ed25519-auth.ts, and the replay
|
|
205
|
+
// guard (isKnownAgentReplay / claimAgentNonce) in ./replay-store.ts — shared by
|
|
206
|
+
// auth-middleware.ts, agent-auth.ts and Presence.ts, so a nonce recorded via
|
|
207
|
+
// any one of the three call sites, on any worker thread, is refused by all of
|
|
208
|
+
// them, and the crypto/decoder logic can't drift.
|
|
208
209
|
// ─── Status derivation (pure — exported for unit testing) ─────────────────────
|
|
209
210
|
export function derivePresenceStatus(now, lastHeartbeatAt, idleMs, offlineMs) {
|
|
210
211
|
const idle = idleMs ?? idleThresholdMs();
|
|
@@ -514,7 +515,9 @@ export class Presence extends databases.flair.Presence {
|
|
|
514
515
|
if (!Number.isFinite(ts) || Math.abs(now - ts) > WINDOW_MS) {
|
|
515
516
|
return new Response(JSON.stringify({ error: "timestamp_out_of_window" }), { status: 401, headers: { "Content-Type": "application/json" } });
|
|
516
517
|
}
|
|
517
|
-
|
|
518
|
+
// A nonce this thread already saw recorded is refused before any lookup.
|
|
519
|
+
// A miss proves nothing: claimAgentNonce below is the authoritative check.
|
|
520
|
+
if (isKnownAgentReplay(headerAgentId, nonce, now)) {
|
|
518
521
|
return new Response(JSON.stringify({ error: "nonce_replay_detected" }), { status: 401, headers: { "Content-Type": "application/json" } });
|
|
519
522
|
}
|
|
520
523
|
const agent = await databases.flair.Agent.get(headerAgentId).catch(() => null);
|
|
@@ -536,7 +539,12 @@ export class Presence extends databases.flair.Presence {
|
|
|
536
539
|
catch (e) {
|
|
537
540
|
return new Response(JSON.stringify({ error: "signature_verification_failed", detail: e?.message }), { status: 401, headers: { "Content-Type": "application/json" } });
|
|
538
541
|
}
|
|
539
|
-
|
|
542
|
+
// Record the nonce instance-wide now that the signature has verified, and
|
|
543
|
+
// before the heartbeat is written. A replay or an unusable store refuses.
|
|
544
|
+
const claim = await claimAgentNonce(headerAgentId, nonce);
|
|
545
|
+
if (!claim.ok) {
|
|
546
|
+
return new Response(JSON.stringify({ error: claim.error }), { status: claim.status, headers: { "Content-Type": "application/json" } });
|
|
547
|
+
}
|
|
540
548
|
// Deactivation guard — same predicate as the middleware Basic branches.
|
|
541
549
|
// A deactivated principal must not be allowed to heartbeat, even when
|
|
542
550
|
// the Ed25519 signature is valid.
|
|
@@ -11,13 +11,13 @@
|
|
|
11
11
|
* REPLACES `retrievalBoost` in `compositeScore` outright (see that
|
|
12
12
|
* function's doc).
|
|
13
13
|
*
|
|
14
|
-
* flair#744 slice A: the
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
14
|
+
* flair#744 slice A: the ledger-write core lives in ./usage-recording.ts's
|
|
15
|
+
* `recordUsageContribution()` — one implementation shared with
|
|
16
|
+
* citation-on-write (resources/Memory.ts's post()/put()) so there is exactly
|
|
17
|
+
* ONE place the (agentId, memoryId) ledger logic lives. This endpoint owns
|
|
18
|
+
* its request handling (auth, rate limit, batch validation, the
|
|
19
|
+
* no-enumeration response) and hands the validated batch to
|
|
20
|
+
* ./usage-recording.ts's `recordUsageBatch()`.
|
|
21
21
|
*
|
|
22
22
|
* WHY THIS IS ITS OWN ENDPOINT, NOT `Memory.put()` (Sherlock, K&S verdict —
|
|
23
23
|
* FLAIR-USAGE-FEEDBACK-SIGNAL.md): usage feedback is fundamentally a
|
|
@@ -32,18 +32,22 @@
|
|
|
32
32
|
* ./usage-recording.ts's recordUsageContribution()) against the RAW
|
|
33
33
|
* `Memory` table object, entirely bypassing the `Memory` RESOURCE class
|
|
34
34
|
* (and its ownership gate) — its own auth model is verified-agent +
|
|
35
|
-
* within-org + explicitly NO ownership requirement.
|
|
35
|
+
* within-org + the caller's READ SCOPE + explicitly NO ownership requirement.
|
|
36
36
|
*
|
|
37
|
-
*
|
|
38
|
-
* (
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
37
|
+
* READ SCOPE: usage is recorded only for a memory in the caller's read scope
|
|
38
|
+
* — `resolveReadScope(caller).isAllowed(record)`: the caller's own memories
|
|
39
|
+
* at any visibility, and every other agent's non-private memories. That is
|
|
40
|
+
* the scope Memory.get() applies to a NON-ADMIN by-id read; here it applies
|
|
41
|
+
* to admin callers too, although an admin's Memory reads are unfiltered.
|
|
42
|
+
* Agent B can report using agent A's shared memory; a memory outside B's
|
|
43
|
+
* scope is treated like an id that does not exist: the same response, and
|
|
44
|
+
* no change to that memory's counters. The ledger core checks the scope on
|
|
45
|
+
* its first read of the memory, before it writes B's ledger row, so a memory
|
|
46
|
+
* outside the scope there gets no row; a memory that leaves the scope before
|
|
47
|
+
* the re-read that precedes the count bump keeps the row already written,
|
|
48
|
+
* and the count is not bumped. The scope is resolved once per call and fails
|
|
49
|
+
* CLOSED (nothing is recorded if it cannot be resolved). Citation-on-write
|
|
50
|
+
* applies the same rule (./usage-recording.ts's module doc).
|
|
47
51
|
*
|
|
48
52
|
* WHY THIS ISN'T A @table-BACKED RESOURCE: the actual dedup ledger (one row
|
|
49
53
|
* per (agentId, memoryId) contribution) lives in the `MemoryUsage` table
|
|
@@ -82,7 +86,8 @@
|
|
|
82
86
|
* NO ID ENUMERATION (Sherlock): the response is IDENTICAL — `{ recorded:
|
|
83
87
|
* true }` — for every syntactically-valid input, regardless of whether a
|
|
84
88
|
* given id was a fresh increment, an already-counted no-op (this agent
|
|
85
|
-
* already contributed), or a not-found no-op (no such memory
|
|
89
|
+
* already contributed), or a not-found no-op (no such memory, or one outside
|
|
90
|
+
* the caller's read scope — see READ SCOPE above). A caller
|
|
86
91
|
* cannot distinguish "that id doesn't exist" from "you already used it" by
|
|
87
92
|
* inspecting the response; per-id/per-batch success is deliberately never
|
|
88
93
|
* reported (see RECORDED_RESPONSE's doc below for why even partial-batch
|
|
@@ -96,7 +101,7 @@
|
|
|
96
101
|
import { Resource } from "harper";
|
|
97
102
|
import { resolveAgentAuth } from "./agent-auth.js";
|
|
98
103
|
import { checkRateLimit, rateLimitResponse } from "./rate-limiter.js";
|
|
99
|
-
import {
|
|
104
|
+
import { recordUsageBatch, MAX_USAGE_IDS_PER_CALL } from "./usage-recording.js";
|
|
100
105
|
import { resolveRecordUsageIds } from "./usage-ids.js";
|
|
101
106
|
const UNAUTH = () => new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
|
|
102
107
|
const BAD_REQUEST = (msg) => new Response(JSON.stringify({ error: msg }), { status: 400, headers: { "Content-Type": "application/json" } });
|
|
@@ -176,26 +181,11 @@ export class RecordUsage extends Resource {
|
|
|
176
181
|
const memoryIds = resolved.ids;
|
|
177
182
|
const attribution = sanitizeAttribution(data?.attribution);
|
|
178
183
|
const now = new Date().toISOString();
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
// resources/Memory.ts's post()/put()). Byte-identical behavior to
|
|
185
|
-
// the former private _recordOne() this replaced. Deliberately NO
|
|
186
|
-
// read-scope check on memoryId here (flair#775 asymmetry — see the
|
|
187
|
-
// module doc's NO READ-SCOPE GATE paragraph; citation-on-write's
|
|
188
|
-
// recordCitations() is the surface that scope-gates).
|
|
189
|
-
await recordUsageContribution(ctx, agentId, memoryId, attribution, now);
|
|
190
|
-
}
|
|
191
|
-
catch (err) {
|
|
192
|
-
// Never let one bad id fail the whole batch, and never let an
|
|
193
|
-
// internal error leak existence information either — log
|
|
194
|
-
// server-side, collapse to the same no-op the response already
|
|
195
|
-
// returns for every other outcome.
|
|
196
|
-
console.error("RecordUsage.post: failed to record usage (treated as no-op)", { memoryId, err });
|
|
197
|
-
}
|
|
198
|
-
}
|
|
184
|
+
// Resolves the caller's read scope once, fails closed, and credits each id
|
|
185
|
+
// through the shared ledger core under that scope; per-id failures are
|
|
186
|
+
// logged server-side only (see the module doc's READ SCOPE paragraph and
|
|
187
|
+
// ./usage-recording.ts's recordUsageBatch()). Never throws.
|
|
188
|
+
await recordUsageBatch(ctx, agentId, memoryIds, attribution, now);
|
|
199
189
|
// Deliberately does NOT report which ids succeeded / were already
|
|
200
190
|
// counted / were not found — see RECORDED_RESPONSE's doc.
|
|
201
191
|
return RECORDED_RESPONSE;
|