@tpsdev-ai/flair 0.56.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
@@ -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
- await databases.flair.Memory.delete(record.id);
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 old standard session memories (> 30 days). These are
84
- // low-value session notes that weren't promoted to persistent.
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
- if (record.durability === "standard" &&
87
- record.type === "session" &&
88
- !record.archived &&
89
- record.createdAt) {
90
- const ageMs = now.getTime() - new Date(record.createdAt).getTime();
91
- const ageDays = ageMs / (24 * 3600_000);
92
- if (ageDays > 30) {
93
- if (!dryRun) {
94
- try {
95
- const archivedRow = {
96
- ...record,
97
- archived: true,
98
- archivedAt: now.toISOString(),
99
- };
100
- await databases.flair.Memory.update(record.id, archivedRow);
101
- // flair#1357 — an `archived` flip changes what the retrieval
102
- // conditions (`archived not_equal true`) admit, so the lexical
103
- // index has to see it, not just content writes.
104
- noteMemoryUpsert(archivedRow);
105
- stats.archived++;
106
- }
107
- catch {
108
- stats.errors++;
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
- patchRecordSilent(databases.flair.Memory, memory.id, { lastReflected: now });
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 so Memory.put() preserves every field byte-for-byte
15
- * (no updatedAt bump, no embedding regen, no safety rescan).
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 so Memory.put()
106
- // preserves every field byte-for-byte. The re-PUT forces Harper to re-insert
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 auth = await resolveAgentAuth(this.getContext?.());
59
- if (auth.kind === "anonymous")
60
- return NOT_FOUND();
61
- if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin))
62
- return super.get(target);
63
- const record = await super.get(target);
64
- if (!record || record.agentId !== auth.agentId)
65
- return NOT_FOUND();
66
- return record;
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 auth = await resolveAgentAuth(this.getContext?.());
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
- const scope = { attribute: "agentId", comparator: "equals", value: auth.agentId };
75
- if (query && typeof query === "object" && !Array.isArray(query)) {
76
- const existing = query.conditions ?? [];
77
- query.conditions = Array.isArray(existing) ? [scope, ...existing] : [scope, existing];
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, isNonceReplay, recordNonce, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
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 nonce store,
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 (isNonceReplay) and deny a legitimate agent. resolveAgentAuth()
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, isNonceReplay/recordNonce (the ONE shared nonce store), and
204
- // importEd25519Key all live in ./ed25519-auth.ts — the single
205
- // shared implementation imported by auth-middleware.ts, agent-auth.ts, and
206
- // Presence.ts so a nonce recorded via any one of the three call sites is
207
- // visible to the other two, and the crypto/decoder logic can't drift.
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
- if (isNonceReplay(headerAgentId, nonce, now)) {
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
- recordNonce(headerAgentId, nonce, ts);
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 actual ledger-write core below (formerly this
15
- * class's private `_recordOne()`) has moved to ./usage-recording.ts's
16
- * `recordUsageContribution()` — a shared, single-implementation extraction
17
- * also used by citation-on-write (resources/Memory.ts's post()/put()) so
18
- * there is exactly ONE place the (agentId, memoryId) ledger logic lives.
19
- * This endpoint's own request handling (auth, rate limit, batch validation,
20
- * the no-enumeration response) is unchanged.
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
- * NO READ-SCOPE GATE — INTENTIONAL ASYMMETRY with citation-on-write
38
- * (flair#775): this endpoint deliberately does NOT validate reported ids
39
- * against the caller's read scope. Usage feedback is the cross-agent
40
- * contract described above (agent B reports using agent A's memory
41
- * regardless of A's visibility setting), and the no-enumeration response
42
- * below already denies existence probing on this surface. Citation-on-write
43
- * (./usage-recording.ts's recordCitations()) DOES scope-gate each cited id —
44
- * it is a separate write surface with a narrower threat model; see that
45
- * module's doc. Do not "unify" the two: the difference is a K&S binding
46
- * condition on the flair#775 locked design, not drift.
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). A caller
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 { recordUsageContribution, MAX_USAGE_IDS_PER_CALL } from "./usage-recording.js";
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
- for (const memoryId of memoryIds) {
180
- try {
181
- // flair#744 slice A: the ledger-write core now lives in
182
- // ./usage-recording.ts's recordUsageContribution() — a shared,
183
- // single-implementation extraction (also used by citation-on-write,
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;