@tpsdev-ai/flair 0.57.0 → 0.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +4 -1
  3. package/config.yaml +3 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +1726 -376
  6. package/dist/commands/agent.js +160 -2
  7. package/dist/commands/doctor.js +177 -27
  8. package/dist/commands/federation.js +2 -1
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +150 -44
  11. package/dist/commands/mcp.js +53 -22
  12. package/dist/commands/memory.js +24 -2
  13. package/dist/commands/quality.js +26 -18
  14. package/dist/commands/service.js +137 -22
  15. package/dist/commands/status.js +114 -3
  16. package/dist/commands/upgrade.js +204 -84
  17. package/dist/doctor-client.js +50 -4
  18. package/dist/federation/scheduler.js +253 -4
  19. package/dist/install/clients.js +89 -23
  20. package/dist/install/global-bin-path.js +26 -6
  21. package/dist/lib/atomic-write.js +256 -0
  22. package/dist/lib/daemon-liveness.js +103 -0
  23. package/dist/lib/doctor-run.js +72 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/flair-agent-role.js +116 -0
  27. package/dist/lib/init-admin-pass.js +4 -2
  28. package/dist/lib/init-listener-environ.js +38 -0
  29. package/dist/lib/init-occupied-listener.js +165 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +179 -8
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/mcp-enable.js +667 -72
  34. package/dist/lib/memory-attributes.js +77 -0
  35. package/dist/lib/node-alias-path.js +95 -0
  36. package/dist/lib/npm-registry.js +119 -6
  37. package/dist/lib/owned-pins.js +20 -6
  38. package/dist/lib/process-start-time.js +32 -0
  39. package/dist/lib/service-repoint-apply.js +267 -0
  40. package/dist/lib/service-repoint.js +575 -0
  41. package/dist/lib/toml-string-array.js +104 -0
  42. package/dist/lib/tree-divergence.js +716 -0
  43. package/dist/lib/upgrade-plain-tree.js +18 -8
  44. package/dist/lib/upgrade-prior-liveness.js +69 -0
  45. package/dist/lib/upgrade-rollback.js +116 -0
  46. package/dist/rem/runner.js +11 -0
  47. package/dist/resources/Agent.js +54 -21
  48. package/dist/resources/AgentSeed.js +44 -1
  49. package/dist/resources/Federation.js +84 -54
  50. package/dist/resources/Memory.js +567 -72
  51. package/dist/resources/MemoryArchive.js +9 -0
  52. package/dist/resources/MemoryBootstrap.js +125 -29
  53. package/dist/resources/MemoryFeed.js +204 -3
  54. package/dist/resources/MemoryHostSource.js +90 -0
  55. package/dist/resources/MemoryMaintenance.js +121 -32
  56. package/dist/resources/MemoryReflect.js +4 -1
  57. package/dist/resources/MemoryReindex.js +7 -4
  58. package/dist/resources/MemoryUsage.js +53 -3
  59. package/dist/resources/OrgSkillAssignment.js +209 -0
  60. package/dist/resources/Presence.js +18 -10
  61. package/dist/resources/RecordUsage.js +30 -40
  62. package/dist/resources/Relationship.js +167 -78
  63. package/dist/resources/SemanticSearch.js +19 -6
  64. package/dist/resources/Soul.js +31 -19
  65. package/dist/resources/XAA.js +47 -14
  66. package/dist/resources/agent-auth.js +16 -10
  67. package/dist/resources/agent-status-guard.js +63 -0
  68. package/dist/resources/auth-middleware.js +137 -49
  69. package/dist/resources/auto-promote-lib.js +4 -4
  70. package/dist/resources/bm25-index-service.js +246 -32
  71. package/dist/resources/bm25-status.js +132 -0
  72. package/dist/resources/ed25519-auth.js +11 -54
  73. package/dist/resources/embed-gpu.js +262 -47
  74. package/dist/resources/embeddings-boot.js +52 -17
  75. package/dist/resources/federation-classify.js +34 -0
  76. package/dist/resources/federation-crypto.js +65 -19
  77. package/dist/resources/flair-agent-role-boot.js +26 -0
  78. package/dist/resources/health.js +67 -16
  79. package/dist/resources/host-pointer/registry.js +35 -0
  80. package/dist/resources/host-pointer-adapter.js +15 -0
  81. package/dist/resources/host-source-visibility.js +167 -0
  82. package/dist/resources/host-source.js +151 -0
  83. package/dist/resources/instance-identity.js +3 -2
  84. package/dist/resources/key-lock.js +31 -0
  85. package/dist/resources/mcp-handler.js +147 -51
  86. package/dist/resources/mcp-oauth.js +3 -6
  87. package/dist/resources/mcp-tools.js +47 -25
  88. package/dist/resources/memory-consolidate-lib.js +3 -1
  89. package/dist/resources/memory-declared-attributes.js +103 -0
  90. package/dist/resources/memory-feed-lib.js +5 -1
  91. package/dist/resources/memory-host-source.js +163 -0
  92. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  93. package/dist/resources/migrations/visibility-backfill.js +4 -1
  94. package/dist/resources/multi-worker-guard.js +121 -0
  95. package/dist/resources/oauth-discovery.js +1 -0
  96. package/dist/resources/oauth-wellknown.js +8 -4
  97. package/dist/resources/originator-instance.js +235 -0
  98. package/dist/resources/promotion-stamp.js +2 -0
  99. package/dist/resources/provenance.js +111 -11
  100. package/dist/resources/record-owner-guard.js +19 -0
  101. package/dist/resources/record-type-kit.js +9 -12
  102. package/dist/resources/record-types.js +22 -6
  103. package/dist/resources/relay-ops.js +28 -3
  104. package/dist/resources/replay-store.js +336 -0
  105. package/dist/resources/request-transaction.js +78 -0
  106. package/dist/resources/search-readiness.js +19 -21
  107. package/dist/resources/semantic-retrieval-core.js +5 -1
  108. package/dist/resources/skill-manifest.js +181 -0
  109. package/dist/resources/skill-provenance.js +15 -10
  110. package/dist/resources/table-patch-policy.js +109 -0
  111. package/dist/resources/table-patches.js +17 -0
  112. package/dist/resources/table-post-policy.js +138 -0
  113. package/dist/resources/table-posts.js +22 -0
  114. package/dist/resources/table-subscription-policy.js +135 -0
  115. package/dist/resources/table-subscriptions.js +19 -0
  116. package/dist/resources/tool-descriptors/index.js +15 -15
  117. package/dist/resources/trust-block.js +10 -3
  118. package/dist/resources/usage-recording.js +169 -41
  119. package/dist/src/lib/flair-agent-role.js +116 -0
  120. package/dist/src/lib/memory-attributes.js +77 -0
  121. package/docs/access-control.md +667 -0
  122. package/docs/api-reference.md +85 -17
  123. package/docs/auth.md +4 -0
  124. package/docs/claude-code.md +132 -0
  125. package/docs/deepseek-harness.md +1 -1
  126. package/docs/deployment.md +1 -1
  127. package/docs/federation.md +1 -1
  128. package/docs/integrations.md +6 -6
  129. package/docs/mcp-clients.md +16 -24
  130. package/docs/notes/mcp-oauth-model2.md +15 -1
  131. package/docs/quickstart.md +5 -0
  132. package/docs/releasing.md +152 -20
  133. package/docs/supply-chain-policy.md +10 -5
  134. package/docs/troubleshooting.md +11 -0
  135. package/docs/upgrade.md +187 -61
  136. package/package.json +10 -5
  137. package/schemas/agent.graphql +9 -6
  138. package/schemas/federation.graphql +2 -11
  139. package/schemas/memory.graphql +137 -17
  140. package/schemas/oauth.graphql +8 -4
  141. package/schemas/replay.graphql +18 -0
  142. package/templates/launchd/start-flair-with-admin-pass.sh +95 -0
  143. package/dist/resources/federation-nonce-store.js +0 -195
@@ -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,10 +40,25 @@
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";
46
60
  import { makeByIdReadGate, makeReadScope, makeScopedSearch } from "./record-type-kit.js";
61
+ import { isLedgerRowVisible, readableLedgerRows } from "./usage-recording.js";
47
62
  // Owner-only read scope through the shared by-id gate and scoped search.
48
63
  const usageReadScope = makeReadScope("owner-only", "agentId");
49
64
  const usageByIdReadGate = makeByIdReadGate(usageReadScope);
@@ -51,21 +66,56 @@ const usageScopedSearch = makeScopedSearch(usageReadScope);
51
66
  const FORBIDDEN = (msg) => new Response(JSON.stringify({ error: msg }), { status: 403, headers: { "Content-Type": "application/json" } });
52
67
  const UNAUTH = () => new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
53
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
+ }
54
82
  export class MemoryUsage extends databases.flair.MemoryUsage {
55
83
  /** Self-authorize now that the global gate is non-rejecting — same pattern
56
84
  * as every other table resource in this codebase (Memory.ts/MemoryGrant.ts
57
85
  * etc.). Per-record scoping happens in get()/search() below. */
58
86
  allowRead() { return allowVerified(this.getContext?.()); }
59
87
  async get(target) {
60
- return usageByIdReadGate.call(this, target, (t) => super.get(t));
88
+ // Collection / query reads are governed by search() below.
89
+ if (!target || (typeof target === "object" && target.isCollection)) {
90
+ return this.search(target);
91
+ }
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();
61
107
  }
62
108
  async search(query) {
63
- const auth = await resolveAgentAuth(this.getContext?.());
109
+ const ctx = this.getContext?.();
110
+ const auth = await resolveAgentAuth(ctx);
64
111
  if (auth.kind === "anonymous")
65
112
  return UNAUTH();
66
113
  if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin))
67
114
  return super.search(query);
68
- return usageScopedSearch(auth.agentId, query, (q) => super.search(q));
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);
69
119
  }
70
120
  // Append-only ledger: rows are created via RecordUsage's RAW table call
71
121
  // (bypasses this class entirely — see module doc), never via this
@@ -0,0 +1,209 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { databases } from "harper";
3
+ import { resolveAgentAuth } from "./agent-auth.js";
4
+ import { resolveStoredRow } from "./originator-instance.js";
5
+ import { FORBIDDEN, NOT_FOUND, UNAUTH, makeAuthGate } from "./record-type-kit.js";
6
+ import { withKeyLock } from "./key-lock.js";
7
+ import { withOwnedTransaction, withSharedWriteTransaction } from "./request-transaction.js";
8
+ import { PRIORITY_RANK } from "./skill-provenance.js";
9
+ import { soulWriteSource } from "./soul-write-policy.js";
10
+ /**
11
+ * OrgSkillAssignment — org-scope skill assignments (flair#2141 S1).
12
+ *
13
+ * A row assigns `skillRef` under `skillName` and `priority`;
14
+ * bootstrap's skills manifest resolves it for an agent that receives org
15
+ * skills (resources/skill-manifest.ts).
16
+ *
17
+ * Writes: post, put, patch and delete each require the operator source
18
+ * (`soulWriteSource`: verified Basic admin auth, or the deliberate internal
19
+ * marker). Agent keys, admin agent keys included, are refused. `writer`,
20
+ * `sourceClass`, `createdAt` and `updatedAt` are server-stamped; other body
21
+ * fields are not stored. Reads: any verified agent.
22
+ *
23
+ * History: each accepted write appends an OrgSkillAssignmentHistory row
24
+ * (actor, source class, a hash of the stored row before the write) in the
25
+ * write's transaction. put, patch and delete hold a per-assignment lock shared
26
+ * by the threads of this Harper process (`withAssignmentLock`) while they read
27
+ * the stored row and commit. Writes on other replicated nodes are not covered
28
+ * by that lock.
29
+ */
30
+ const TABLE = "OrgSkillAssignment";
31
+ /** The stored fields, in the order `previousHash` covers them. */
32
+ const HASHED_FIELDS = ["id", "skillName", "skillRef", "priority", "createdAt", "updatedAt", "writer", "sourceClass"];
33
+ /** sha256 over a stored row's fields (HASHED_FIELDS), for `previousHash`. */
34
+ export function assignmentHash(row) {
35
+ const canonical = JSON.stringify(HASHED_FIELDS.map((field) => [field, row[field] ?? null]));
36
+ return createHash("sha256").update(canonical).digest("hex");
37
+ }
38
+ function badRequest(error, message) {
39
+ return new Response(JSON.stringify({ error, message }), {
40
+ status: 400, headers: { "Content-Type": "application/json" },
41
+ });
42
+ }
43
+ async function authorizeOperator(self) {
44
+ const context = self.getContext?.();
45
+ const auth = await resolveAgentAuth(context);
46
+ if (auth.kind === "anonymous")
47
+ return UNAUTH();
48
+ const sourceClass = soulWriteSource(context, auth);
49
+ if (!sourceClass)
50
+ return FORBIDDEN("org_skill_assignment_requires_operator: use operator credentials");
51
+ return { writer: auth.kind === "agent" ? auth.agentId : null, sourceClass };
52
+ }
53
+ /** The URL-bound row id, or null on a collection address. */
54
+ function boundId(self) {
55
+ try {
56
+ const id = self.getId?.();
57
+ if (typeof id === "string" && id.length > 0)
58
+ return id;
59
+ if (typeof id === "number")
60
+ return String(id);
61
+ }
62
+ catch {
63
+ /* no bound id */
64
+ }
65
+ return null;
66
+ }
67
+ function isRecord(value) {
68
+ return !!value && typeof value === "object" && !Array.isArray(value);
69
+ }
70
+ function validFields(body) {
71
+ const { skillName, skillRef, priority = "standard" } = body;
72
+ if (typeof skillName !== "string" || skillName.trim() === "") {
73
+ return badRequest("skill_name_required", "skillName must be a non-empty string");
74
+ }
75
+ if (typeof skillRef !== "string" || skillRef.trim() === "") {
76
+ return badRequest("skill_ref_required", "skillRef must be a non-empty string");
77
+ }
78
+ if (typeof priority !== "string" || !Object.hasOwn(PRIORITY_RANK, priority)) {
79
+ return badRequest("invalid_priority", `priority must be one of ${Object.keys(PRIORITY_RANK).join(", ")}`);
80
+ }
81
+ return { skillName, skillRef, priority };
82
+ }
83
+ async function appendHistory(context, assignmentId, op, previous, who, at) {
84
+ await databases.flair.OrgSkillAssignmentHistory.put({
85
+ id: randomUUID(),
86
+ assignmentId,
87
+ op,
88
+ actor: who.writer,
89
+ sourceClass: who.sourceClass,
90
+ previousHash: previous ? assignmentHash(previous) : null,
91
+ at,
92
+ }, context);
93
+ }
94
+ const LOCK_NAMESPACE = "flair-org-skill-assignment";
95
+ /** The wait for another write to the same assignment: at most LOCK_ATTEMPTS × LOCK_WAIT_MS. */
96
+ const LOCK_ATTEMPTS = 200;
97
+ const LOCK_WAIT_MS = 10;
98
+ /**
99
+ * Run `fn` holding this process's lock on assignment `id` (resources/key-lock.ts).
100
+ * `fn` must commit before it returns. 409 when the lock stays held
101
+ * past the wait; 503 when the store has no lock.
102
+ */
103
+ async function withAssignmentLock(id, fn) {
104
+ const store = databases.flair.OrgSkillAssignment?.primaryStore;
105
+ const outcome = await withKeyLock(store, [LOCK_NAMESPACE, id], fn, LOCK_ATTEMPTS, LOCK_WAIT_MS);
106
+ if (outcome.kind === "done")
107
+ return outcome.value;
108
+ if (outcome.kind === "busy") {
109
+ return new Response(JSON.stringify({
110
+ error: "org_skill_assignment_busy",
111
+ message: "another write to this assignment is still in progress; retry",
112
+ }), { status: 409, headers: { "Content-Type": "application/json" } });
113
+ }
114
+ return new Response(JSON.stringify({
115
+ error: "org_skill_assignment_lock_unavailable",
116
+ message: "the OrgSkillAssignment store has no per-key lock, so the write was refused",
117
+ }), { status: 503, headers: { "Content-Type": "application/json" } });
118
+ }
119
+ const authGate = makeAuthGate();
120
+ export class OrgSkillAssignment extends databases.flair.OrgSkillAssignment {
121
+ allowRead() { return authGate.call(this); }
122
+ async post(content, context) {
123
+ const who = await authorizeOperator(this);
124
+ if (who instanceof Response)
125
+ return who;
126
+ if (boundId(this))
127
+ return badRequest("org_skill_assignment_post_to_collection", "create an assignment with POST /OrgSkillAssignment/");
128
+ if (!isRecord(content))
129
+ return badRequest("org_skill_assignment_requires_one_record", "send one assignment object");
130
+ const fields = validFields(content);
131
+ if (fields instanceof Response)
132
+ return fields;
133
+ const at = new Date().toISOString();
134
+ const record = { id: randomUUID(), ...fields, createdAt: at, updatedAt: at, writer: who.writer, sourceClass: who.sourceClass };
135
+ return withSharedWriteTransaction(this.getContext?.(), async (shared) => {
136
+ await appendHistory(shared, record.id, "create", null, who, at);
137
+ return super.post(record, context);
138
+ });
139
+ }
140
+ async put(content, context) {
141
+ const who = await authorizeOperator(this);
142
+ if (who instanceof Response)
143
+ return who;
144
+ const id = boundId(this);
145
+ if (!id)
146
+ return badRequest("org_skill_assignment_id_required", "address one assignment: PUT /OrgSkillAssignment/<id>");
147
+ if (!isRecord(content))
148
+ return badRequest("org_skill_assignment_requires_one_record", "send one assignment object");
149
+ const fields = validFields(content);
150
+ if (fields instanceof Response)
151
+ return fields;
152
+ return withAssignmentLock(id, () => withOwnedTransaction(this.getContext?.(), async (shared) => {
153
+ const stored = await resolveStoredRow(this, TABLE, content, () => super.get());
154
+ if (stored.denial)
155
+ return stored.denial;
156
+ const at = new Date().toISOString();
157
+ const createdAt = typeof stored.row?.createdAt === "string" ? stored.row.createdAt : at;
158
+ const record = { id, ...fields, createdAt, updatedAt: at, writer: who.writer, sourceClass: who.sourceClass };
159
+ await appendHistory(shared, id, stored.row ? "update" : "create", stored.row, who, at);
160
+ return super.put(record, context);
161
+ }));
162
+ }
163
+ async patch(content, query) {
164
+ const who = await authorizeOperator(this);
165
+ if (who instanceof Response)
166
+ return who;
167
+ const id = boundId(this);
168
+ if (!id)
169
+ return badRequest("org_skill_assignment_id_required", "address one assignment: PATCH /OrgSkillAssignment/<id>");
170
+ if (!isRecord(content))
171
+ return badRequest("org_skill_assignment_requires_one_record", "send one assignment object");
172
+ return withAssignmentLock(id, () => withOwnedTransaction(this.getContext?.(), async (shared) => {
173
+ const stored = await resolveStoredRow(this, TABLE, content, () => super.get());
174
+ if (stored.denial)
175
+ return stored.denial;
176
+ if (!stored.row)
177
+ return NOT_FOUND();
178
+ const merged = {};
179
+ for (const field of ["skillName", "skillRef", "priority"]) {
180
+ merged[field] = Object.hasOwn(content, field) ? content[field] : stored.row[field];
181
+ }
182
+ const fields = validFields(merged);
183
+ if (fields instanceof Response)
184
+ return fields;
185
+ const at = new Date().toISOString();
186
+ const changes = { ...fields, updatedAt: at, writer: who.writer, sourceClass: who.sourceClass };
187
+ await appendHistory(shared, id, "update", stored.row, who, at);
188
+ return super.patch(changes, query);
189
+ }));
190
+ }
191
+ async delete(target) {
192
+ const who = await authorizeOperator(this);
193
+ if (who instanceof Response)
194
+ return who;
195
+ const id = boundId(this);
196
+ if (!id)
197
+ return badRequest("org_skill_assignment_id_required", "address one assignment: DELETE /OrgSkillAssignment/<id>");
198
+ return withAssignmentLock(id, () => withOwnedTransaction(this.getContext?.(), async (shared) => {
199
+ const stored = await resolveStoredRow(this, TABLE, undefined, () => super.get());
200
+ if (stored.denial)
201
+ return stored.denial;
202
+ if (!stored.row)
203
+ return NOT_FOUND();
204
+ const at = new Date().toISOString();
205
+ await appendHistory(shared, id, "delete", stored.row, who, at);
206
+ return super.delete(target);
207
+ }));
208
+ }
209
+ }
@@ -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.