@tpsdev-ai/flair 0.57.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1685 -279
  5. package/dist/commands/doctor.js +162 -4
  6. package/dist/commands/federation.js +2 -1
  7. package/dist/commands/hook.js +10 -2
  8. package/dist/commands/init.js +150 -44
  9. package/dist/commands/memory.js +24 -2
  10. package/dist/commands/quality.js +26 -18
  11. package/dist/commands/service.js +137 -22
  12. package/dist/commands/status.js +114 -3
  13. package/dist/commands/upgrade.js +204 -84
  14. package/dist/doctor-client.js +50 -4
  15. package/dist/federation/scheduler.js +253 -4
  16. package/dist/install/clients.js +89 -23
  17. package/dist/install/global-bin-path.js +26 -6
  18. package/dist/lib/atomic-write.js +256 -0
  19. package/dist/lib/daemon-liveness.js +61 -0
  20. package/dist/lib/doctor-run.js +5 -0
  21. package/dist/lib/embed-gpu-doctor.js +49 -26
  22. package/dist/lib/federation-memory-attributes.js +15 -0
  23. package/dist/lib/init-admin-pass.js +4 -2
  24. package/dist/lib/init-listener-environ.js +38 -0
  25. package/dist/lib/init-occupied-listener.js +165 -0
  26. package/dist/lib/launchd-domain-preflight.js +448 -0
  27. package/dist/lib/launchd-management.js +176 -6
  28. package/dist/lib/launchd-repair.js +95 -0
  29. package/dist/lib/memory-attributes.js +77 -0
  30. package/dist/lib/node-alias-path.js +95 -0
  31. package/dist/lib/npm-registry.js +119 -6
  32. package/dist/lib/owned-pins.js +20 -6
  33. package/dist/lib/service-repoint-apply.js +267 -0
  34. package/dist/lib/service-repoint.js +575 -0
  35. package/dist/lib/toml-string-array.js +104 -0
  36. package/dist/lib/tree-divergence.js +716 -0
  37. package/dist/lib/upgrade-plain-tree.js +18 -8
  38. package/dist/lib/upgrade-prior-liveness.js +69 -0
  39. package/dist/lib/upgrade-rollback.js +116 -0
  40. package/dist/rem/runner.js +11 -0
  41. package/dist/resources/Agent.js +27 -14
  42. package/dist/resources/AgentSeed.js +35 -1
  43. package/dist/resources/Federation.js +70 -52
  44. package/dist/resources/Memory.js +567 -72
  45. package/dist/resources/MemoryArchive.js +9 -0
  46. package/dist/resources/MemoryBootstrap.js +4 -0
  47. package/dist/resources/MemoryFeed.js +204 -3
  48. package/dist/resources/MemoryHostSource.js +90 -0
  49. package/dist/resources/MemoryMaintenance.js +121 -32
  50. package/dist/resources/MemoryReflect.js +4 -1
  51. package/dist/resources/MemoryReindex.js +7 -4
  52. package/dist/resources/MemoryUsage.js +53 -3
  53. package/dist/resources/Presence.js +18 -10
  54. package/dist/resources/RecordUsage.js +30 -40
  55. package/dist/resources/Relationship.js +167 -78
  56. package/dist/resources/SemanticSearch.js +19 -6
  57. package/dist/resources/Soul.js +31 -19
  58. package/dist/resources/XAA.js +7 -3
  59. package/dist/resources/agent-auth.js +16 -10
  60. package/dist/resources/auth-middleware.js +135 -48
  61. package/dist/resources/auto-promote-lib.js +4 -4
  62. package/dist/resources/bm25-index-service.js +246 -32
  63. package/dist/resources/bm25-status.js +132 -0
  64. package/dist/resources/ed25519-auth.js +11 -54
  65. package/dist/resources/embed-gpu.js +262 -47
  66. package/dist/resources/embeddings-boot.js +52 -17
  67. package/dist/resources/federation-classify.js +12 -0
  68. package/dist/resources/federation-crypto.js +65 -19
  69. package/dist/resources/health.js +57 -14
  70. package/dist/resources/host-pointer/registry.js +35 -0
  71. package/dist/resources/host-pointer-adapter.js +15 -0
  72. package/dist/resources/host-source-visibility.js +167 -0
  73. package/dist/resources/host-source.js +151 -0
  74. package/dist/resources/instance-identity.js +3 -2
  75. package/dist/resources/mcp-handler.js +147 -51
  76. package/dist/resources/mcp-tools.js +25 -21
  77. package/dist/resources/memory-consolidate-lib.js +3 -1
  78. package/dist/resources/memory-declared-attributes.js +103 -0
  79. package/dist/resources/memory-feed-lib.js +5 -1
  80. package/dist/resources/memory-host-source.js +163 -0
  81. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  82. package/dist/resources/migrations/visibility-backfill.js +4 -1
  83. package/dist/resources/originator-instance.js +235 -0
  84. package/dist/resources/promotion-stamp.js +2 -0
  85. package/dist/resources/provenance.js +111 -11
  86. package/dist/resources/record-owner-guard.js +19 -0
  87. package/dist/resources/record-type-kit.js +9 -12
  88. package/dist/resources/record-types.js +6 -6
  89. package/dist/resources/relay-ops.js +28 -3
  90. package/dist/resources/replay-store.js +289 -0
  91. package/dist/resources/request-transaction.js +78 -0
  92. package/dist/resources/search-readiness.js +19 -21
  93. package/dist/resources/semantic-retrieval-core.js +5 -1
  94. package/dist/resources/table-patch-policy.js +109 -0
  95. package/dist/resources/table-patches.js +17 -0
  96. package/dist/resources/table-post-policy.js +138 -0
  97. package/dist/resources/table-posts.js +22 -0
  98. package/dist/resources/table-subscription-policy.js +135 -0
  99. package/dist/resources/table-subscriptions.js +19 -0
  100. package/dist/resources/tool-descriptors/index.js +15 -15
  101. package/dist/resources/trust-block.js +10 -3
  102. package/dist/resources/usage-recording.js +169 -41
  103. package/dist/src/lib/memory-attributes.js +77 -0
  104. package/docs/api-reference.md +79 -15
  105. package/docs/claude-code.md +132 -0
  106. package/docs/deployment.md +1 -1
  107. package/docs/federation.md +1 -1
  108. package/docs/integrations.md +5 -5
  109. package/docs/mcp-clients.md +11 -21
  110. package/docs/notes/mcp-oauth-model2.md +15 -1
  111. package/docs/quickstart.md +5 -0
  112. package/docs/releasing.md +134 -2
  113. package/docs/supply-chain-policy.md +10 -5
  114. package/docs/troubleshooting.md +11 -0
  115. package/docs/upgrade.md +187 -61
  116. package/package.json +9 -5
  117. package/schemas/agent.graphql +9 -6
  118. package/schemas/federation.graphql +2 -11
  119. package/schemas/memory.graphql +106 -17
  120. package/schemas/replay.graphql +18 -0
  121. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  122. package/dist/resources/federation-nonce-store.js +0 -195
@@ -14,12 +14,10 @@
14
14
  * memory WRITE; each cited id is credited the same way, post-commit and
15
15
  * failure-isolated from the write itself.
16
16
  *
17
- * `recordUsageContribution()` is an EXACT extraction of what was
18
- * RecordUsage.ts's private `_recordOne()` — see its doc below for the
19
- * ledger-then-count ordering, the individually-wrapped `withDetachedTxn`
20
- * discipline, and the accepted best-effort race on the final
21
- * read-modify-write. This move changes WHERE the logic lives, not what it
22
- * does — behavior is byte-identical for RecordUsage.ts's existing callers.
17
+ * `recordUsageContribution()` is the one (agentId, memoryId) ledger write —
18
+ * see its doc below for the read-scope gate it applies, the ledger-then-count
19
+ * ordering, the individually-wrapped `withDetachedTxn` discipline, and the
20
+ * accepted best-effort race on the final read-modify-write.
23
21
  *
24
22
  * `recordCitations()` is the NEW batch helper citation-on-write uses: the
25
23
  * same agent-required / cap / dedup / per-id failure-isolation shape as
@@ -30,22 +28,33 @@
30
28
  * the flair#775 read-scope gate below is the REVERSE direction — the writer's
31
29
  * scope vets the cited ids, the cited ids never widen anything).
32
30
  *
33
- * recordCitations() additionally validates each cited id against the
34
- * WRITER's own read-scope before crediting (flair#775, a Kern+Sherlock
35
- * binding condition on the locked design): citing a memory the writer cannot
36
- * read is silently dropped, uniformly with a nonexistent id — never an
37
- * error, never a distinguishable code path (an error, or any response/shape
38
- * difference, would leak "that id exists but you can't see it").
39
- * POST /RecordUsage is DELIBERATELY not scope-gated — its module doc
40
- * establishes usage feedback as a cross-agent contract (agent B reports
41
- * using agent A's memory regardless of A's visibility setting);
42
- * citation-on-write is a separate write surface with a narrower threat
43
- * model (the ids ride along on the WRITER's own memory-creation call, so
44
- * crediting an unreadable id would let a writer both probe for and boost
45
- * memories it cannot see). So the scope gate lives HERE, not retrofitted
46
- * onto recordUsageContribution() — do not "unify" the two surfaces.
31
+ * READ SCOPE, ON BOTH SURFACES. A contribution is recorded only for a memory
32
+ * in the contributing agent's read scope: `resolveReadScope(agentId).isAllowed(record)`
33
+ * — the scope Memory.get() applies to a NON-ADMIN by-id read. It applies to
34
+ * admin agents here too, although an admin's Memory reads are unfiltered. A
35
+ * memory outside that scope takes the SAME branch as an id that does not
36
+ * exist: the caller gets the same response and the memory's counters do not
37
+ * change. Any difference between the two (an error, a response or shape
38
+ * difference, a ledger row the caller can read back) would tell the caller
39
+ * "that id exists but you can't see it".
40
+ * - recordUsageContribution() REQUIRES the predicate (`canRead`). It applies
41
+ * it to its first read of the memory, before the ledger row is written
42
+ * (out of scope there: no row), and again to the re-read before the count
43
+ * bump (out of scope there: the row already written stays, and the count
44
+ * is not bumped). No caller of the ledger core can credit a memory without
45
+ * a read-scope decision.
46
+ * - recordUsageBatch() (POST /RecordUsage) and recordCitations()
47
+ * (citation-on-write) each resolve the caller's scope ONCE per batch and
48
+ * fail CLOSED: if the scope cannot be resolved, nothing in the batch is
49
+ * credited. recordCitations() also pre-checks each cited id (flair#775).
50
+ * - The ledger's own read path (resources/MemoryUsage.ts) applies the same
51
+ * rule to NON-ADMIN reads through isLedgerRowVisible()/readableLedgerRows():
52
+ * a non-admin reader sees its own row only while the memory it names
53
+ * exists and is readable. Admin and trusted internal ledger reads are
54
+ * unfiltered.
47
55
  */
48
56
  import { databases } from "harper";
57
+ import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
49
58
  import { withDetachedTxn } from "./table-helpers.js";
50
59
  import { resolveReadScope } from "./memory-read-scope.js";
51
60
  /**
@@ -58,6 +67,15 @@ export const MAX_USAGE_IDS_PER_CALL = 20;
58
67
  /**
59
68
  * One (agentId, memoryId) contribution — the shared ledger-write core.
60
69
  *
70
+ * READ-SCOPE GATE: `canRead` is the contributing agent's read-scope predicate
71
+ * (`resolveReadScope(agentId).isAllowed`, resolved once per batch by the
72
+ * caller). The memory row is checked against it before the ledger row is
73
+ * written, and the re-fetched row is checked again before the count is
74
+ * bumped. At the first read, a memory that does not exist and a memory the
75
+ * agent cannot read end on the same silent no-op: no ledger row, no count
76
+ * change. At the re-read the ledger row is already written; a rejection there
77
+ * leaves the row in place and skips the count bump.
78
+ *
61
79
  * Ledger-row-create FIRST, THEN the Memory.usageCount bump — so a crash
62
80
  * between the two leaves the SAFE failure state (ledger row exists, count
63
81
  * not yet bumped: a later retry just re-checks and no-ops) rather than the
@@ -85,11 +103,11 @@ export const MAX_USAGE_IDS_PER_CALL = 20;
85
103
  * inflation), and orthogonal to the anti-gaming properties the cap/floor
86
104
  * and dedup ledger actually defend.
87
105
  *
88
- * Called by RecordUsage.post() (explicit usage feedback) and by
89
- * recordCitations() below (citation-on-write) — identical ledger semantics
90
- * regardless of which surface triggered the contribution.
106
+ * Called by recordUsageBatch() (POST /RecordUsage, explicit usage feedback)
107
+ * and by recordCitations() below (citation-on-write) — identical ledger
108
+ * semantics regardless of which surface triggered the contribution.
91
109
  */
92
- export async function recordUsageContribution(ctx, agentId, memoryId, attribution, now) {
110
+ export async function recordUsageContribution(ctx, agentId, memoryId, attribution, now, canRead) {
93
111
  const ledgerId = `${agentId}:${memoryId}`;
94
112
  // Bypasses resources/MemoryUsage.ts's own auth wrapper by design — this
95
113
  // IS the trusted internal caller that resource's module doc describes
@@ -98,9 +116,11 @@ export async function recordUsageContribution(ctx, agentId, memoryId, attributio
98
116
  const existingContribution = await withDetachedTxn(ctx, () => databases.flair.MemoryUsage.get(ledgerId)).catch(() => null);
99
117
  if (existingContribution)
100
118
  return; // already counted by this agent — silent no-op
101
- const memoryExists = await withDetachedTxn(ctx, () => databases.flair.Memory.get(memoryId)).catch(() => null);
102
- if (!memoryExists)
103
- return; // no such memory — silent no-op (no enumeration)
119
+ // Absent, unreadable, or a failed read: ONE silent no-op branch (no
120
+ // enumeration). A read failure is never evidence the memory is readable.
121
+ const memory = await withDetachedTxn(ctx, () => databases.flair.Memory.get(memoryId)).catch(() => null);
122
+ if (!memory || !canRead(memory))
123
+ return;
104
124
  const ledgerRecord = { id: ledgerId, agentId, memoryId, createdAt: now };
105
125
  if (attribution)
106
126
  ledgerRecord.attribution = attribution;
@@ -120,17 +140,23 @@ export async function recordUsageContribution(ctx, agentId, memoryId, attributio
120
140
  // this write path smuggle OTHER field changes through instead of just the
121
141
  // count (RecordUsage.ts module doc's "WHY THIS IS ITS OWN ENDPOINT").
122
142
  const fresh = await withDetachedTxn(ctx, () => databases.flair.Memory.get(memoryId)).catch(() => null);
123
- if (!fresh)
124
- return; // deleted between the checks above and now — no-op
125
- await withDetachedTxn(ctx, () => databases.flair.Memory.put({ ...fresh, usageCount: (fresh.usageCount ?? 0) + 1 }));
143
+ // Deleted, or moved out of the agent's read scope, between the check above
144
+ // and now — the count is not bumped (the ledger row written above stays).
145
+ // The count is only ever bumped on a row in the agent's read scope.
146
+ if (!fresh || !canRead(fresh))
147
+ return;
148
+ const usageRow = { ...fresh, usageCount: (fresh.usageCount ?? 0) + 1 };
149
+ stripUndeclaredMemoryAttributes(usageRow);
150
+ await withDetachedTxn(ctx, () => databases.flair.Memory.put(usageRow));
126
151
  }
127
152
  /**
128
- * Default record fetch for recordCitations()'s read-scope gate — the RAW
129
- * Memory table (bypassing the Memory RESOURCE class's own read wrapper; the
130
- * same trusted-internal-caller pattern recordUsageContribution() uses) so
153
+ * Default record fetch for the read-scope gates in this module
154
+ * (recordCitations() and the ledger read helpers below) — the RAW Memory
155
+ * table (bypassing the Memory RESOURCE class's own read wrapper; the same
156
+ * trusted-internal-caller pattern recordUsageContribution() uses) so
131
157
  * `scope.isAllowed` runs against the raw stored record. Never throws: a
132
- * fetch failure reads as "not found", which the gate silently drops —
133
- * identical to a nonexistent id.
158
+ * fetch failure reads as "not found", which every gate treats as not
159
+ * readable — identical to a nonexistent id.
134
160
  */
135
161
  async function fetchMemoryForScopeCheck(ctx, memoryId) {
136
162
  return withDetachedTxn(ctx, () => databases.flair.Memory.get(memoryId)).catch(() => null);
@@ -207,15 +233,14 @@ export async function recordCitations(ctx, auth, usedMemoryIds, now, recordFn =
207
233
  // flair#775 slice 1 read-scope gate. The raw fetch + in-process
208
234
  // predicate is deliberately ONE branch for both "doesn't exist" and
209
235
  // "exists but out of the writer's read scope" — uniform silent drop
210
- // (see the module doc). recordUsageContribution's own existence
211
- // re-check makes this a second point-lookup of the same record;
212
- // accepted — keeping the shared ledger core byte-identical for
213
- // RecordUsage.post() is worth two point-lookups on a ≤20-id advisory
214
- // batch.
236
+ // (see the module doc). recordUsageContribution applies the same
237
+ // predicate again to the rows it reads itself (it is passed
238
+ // `scope.isAllowed`), so this pre-check is a second point-lookup of
239
+ // the same record — accepted on a ≤20-id advisory batch.
215
240
  const record = await fetchFn(ctx, id);
216
241
  if (!record || !scope.isAllowed(record))
217
242
  continue;
218
- await recordFn(ctx, auth.agentId, id, undefined, now);
243
+ await recordFn(ctx, auth.agentId, id, undefined, now, scope.isAllowed);
219
244
  }
220
245
  catch (err) {
221
246
  // Never let one bad id stop the batch — same no-op-on-error discipline
@@ -224,3 +249,106 @@ export async function recordCitations(ctx, auth, usedMemoryIds, now, recordFn =
224
249
  }
225
250
  }
226
251
  }
252
+ /**
253
+ * POST /RecordUsage's batch (resources/RecordUsage.ts) — credits each id in
254
+ * `memoryIds` through `recordFn` (the real `recordUsageContribution` by
255
+ * default) under the CALLER's read scope.
256
+ *
257
+ * - The caller's scope is resolved ONCE per batch via resolveReadScope — the
258
+ * scope Memory.get() applies to non-admin readers, applied here to admin
259
+ * callers too — and its `isAllowed` predicate is handed to every
260
+ * contribution, which applies it to each Memory row it reads.
261
+ * - Fail CLOSED: if the scope cannot be resolved, nothing in the batch is
262
+ * credited. The endpoint's response does not change (RecordUsage.ts's
263
+ * "NO ID ENUMERATION"), so a failure is visible only in the server log.
264
+ * - Each id is credited independently: one id throwing never stops the
265
+ * rest, and the failure is logged server-side, never surfaced to the
266
+ * caller.
267
+ *
268
+ * Input validation, the per-call cap and the attribution sanitizer stay in
269
+ * RecordUsage.post(); `memoryIds` arrives here already validated and deduped.
270
+ * `recordFn` / `scopeFn` are unit-test injection seams
271
+ * (test/unit/usage-recording.test.ts) — the production caller passes neither.
272
+ */
273
+ export async function recordUsageBatch(ctx, agentId, memoryIds, attribution, now, recordFn = recordUsageContribution, scopeFn = resolveReadScope) {
274
+ let scope;
275
+ try {
276
+ scope = await scopeFn(agentId);
277
+ }
278
+ catch (err) {
279
+ console.error("RecordUsage.post: read-scope resolution failed — batch not recorded (no-op)", { err });
280
+ return;
281
+ }
282
+ for (const memoryId of memoryIds) {
283
+ try {
284
+ await recordFn(ctx, agentId, memoryId, attribution, now, scope.isAllowed);
285
+ }
286
+ catch (err) {
287
+ // Never let one bad id fail the whole batch, and never let an internal
288
+ // error leak existence information either — log server-side, collapse
289
+ // to the same no-op the response already returns for every other
290
+ // outcome.
291
+ console.error("RecordUsage.post: failed to record usage (treated as no-op)", { memoryId, err });
292
+ }
293
+ }
294
+ }
295
+ // ─── The ledger's read rule (resources/MemoryUsage.ts) ──────────────────────
296
+ //
297
+ // A non-admin reader sees its own MemoryUsage row only while the memory the row
298
+ // names exists and is in the reader's read scope. A row about a memory the
299
+ // reader cannot read reads exactly like a row that does not exist. A failed
300
+ // scope resolution or a failed Memory read hides the row: unknown evidence is
301
+ // never treated as readable. Admin and trusted internal ledger reads do not go
302
+ // through these helpers (resources/MemoryUsage.ts leaves them unfiltered).
303
+ /**
304
+ * Is this one ledger row about a memory `scope` can read? A row with no
305
+ * `memoryId`, a memory that does not exist, and a failed read are all `false`.
306
+ */
307
+ async function isLedgerRowAboutReadableMemory(ctx, row, scope, fetchFn) {
308
+ const memoryId = row?.memoryId;
309
+ if (typeof memoryId !== "string" || memoryId.length === 0)
310
+ return false;
311
+ try {
312
+ const memory = await fetchFn(ctx, memoryId);
313
+ return !!memory && scope.isAllowed(memory) === true;
314
+ }
315
+ catch {
316
+ return false;
317
+ }
318
+ }
319
+ /**
320
+ * By-id form of the ledger read rule, for MemoryUsage.get(): resolves the
321
+ * reader's scope and checks the one row. `false` on any failure.
322
+ * `scopeFn` / `fetchFn` are unit-test injection seams.
323
+ */
324
+ export async function isLedgerRowVisible(ctx, readerId, row, scopeFn = resolveReadScope, fetchFn = fetchMemoryForScopeCheck) {
325
+ let scope;
326
+ try {
327
+ scope = await scopeFn(readerId);
328
+ }
329
+ catch (err) {
330
+ console.error("MemoryUsage.get: read-scope resolution failed — row hidden", { err });
331
+ return false;
332
+ }
333
+ return isLedgerRowAboutReadableMemory(ctx, row, scope, fetchFn);
334
+ }
335
+ /**
336
+ * Collection form of the ledger read rule, for MemoryUsage.search(): yields
337
+ * only the rows of `rows` about memories the reader can read, in source
338
+ * order. The scope is resolved once; if that fails, nothing is yielded.
339
+ * `scopeFn` / `fetchFn` are unit-test injection seams.
340
+ */
341
+ export async function* readableLedgerRows(ctx, readerId, rows, scopeFn = resolveReadScope, fetchFn = fetchMemoryForScopeCheck) {
342
+ let scope;
343
+ try {
344
+ scope = await scopeFn(readerId);
345
+ }
346
+ catch (err) {
347
+ console.error("MemoryUsage.search: read-scope resolution failed — no rows returned", { err });
348
+ return;
349
+ }
350
+ for await (const row of rows) {
351
+ if (await isLedgerRowAboutReadableMemory(ctx, row, scope, fetchFn))
352
+ yield row;
353
+ }
354
+ }
@@ -0,0 +1,77 @@
1
+ /** Shared Memory field contract for resource writers and federation readers.
2
+ * Kept under src so the CLI build can include it within its rootDir; the
3
+ * server build also emits this dependency under dist/src/lib.
4
+ * Pure data: importing this contract never loads Harper.
5
+ */
6
+ /** Every DECLARED attribute of `type Memory` in schemas/memory.graphql, in
7
+ * schema order. Keep in sync with the schema (the drift test enforces it). */
8
+ export const DECLARED_MEMORY_ATTRIBUTES = Object.freeze([
9
+ "id",
10
+ "agentId",
11
+ "content",
12
+ "contentHash",
13
+ "trigger",
14
+ "visibility",
15
+ "embedding",
16
+ "embeddingModel",
17
+ "tags",
18
+ "durability",
19
+ "source",
20
+ "type",
21
+ "createdAt",
22
+ "updatedAt",
23
+ "instanceToken",
24
+ "expiresAt",
25
+ "retrievalCount",
26
+ "lastRetrieved",
27
+ "usageCount",
28
+ "promotionStatus",
29
+ "promotedAt",
30
+ "promotedBy",
31
+ "archived",
32
+ "archivedAt",
33
+ "archivedBy",
34
+ "parentId",
35
+ "derivedFrom",
36
+ "sessionId",
37
+ "lastReflected",
38
+ "supersedes",
39
+ "subject",
40
+ "summary",
41
+ "validFrom",
42
+ "validTo",
43
+ "_safetyFlags",
44
+ "provenance",
45
+ "originatorInstanceId",
46
+ "metadata",
47
+ "entities",
48
+ ]);
49
+ /** Pre-existing UNDECLARED attributes the codebase deliberately stores on a
50
+ * Memory row and must keep (the guard's job is the POINTER, not these).
51
+ * This is an EXPLICIT, NAMED list measured against a live store (A1'' item 1)
52
+ * — never derived from the schema, because the schema is not the source of
53
+ * truth for what is on disk:
54
+ * - `meta` — the continuity-journal payload {seq, processUUID, sessionId,
55
+ * hook} written by the capture path (PUT /Memory/<id>,
56
+ * flair#1257 slice 3); Kern's slice-2 ruling settled that it
57
+ * round-trips as an undeclared field, and
58
+ * test/integration/continuity-rem-promotion-1257.test.ts pins
59
+ * that. It is not a flat String, so declaring it would change
60
+ * the stored shape.
61
+ * - `kind` — carried on a couple of older rows.
62
+ * - `_originatorInstanceId`, `_syncedFrom`, `_syncedAt` — federation
63
+ * bookkeeping stamped by the RECEIVER at merge time
64
+ * (resources/Federation.ts's mergeRecord) on every synced row.
65
+ * Any OTHER undeclared key (in particular any pointer input) is stripped. */
66
+ export const UNDECLARED_ALLOWED = Object.freeze([
67
+ "meta",
68
+ "kind",
69
+ "_originatorInstanceId",
70
+ "_syncedFrom",
71
+ "_syncedAt",
72
+ ]);
73
+ /** Every field retained by Memory writers and the inbound federation guard. */
74
+ export const MEMORY_ATTRIBUTES = Object.freeze([
75
+ ...DECLARED_MEMORY_ATTRIBUTES,
76
+ ...UNDECLARED_ALLOWED,
77
+ ]);
@@ -29,7 +29,12 @@ Flair is a Harper application. Two things become HTTP paths:
29
29
  1. **`@table @export` in GraphQL** — Harper generates REST CRUD at
30
30
  `/<TypeName>` and `/<TypeName>/<id>` (GET collection / GET by id / POST /
31
31
  PUT / PATCH / DELETE). Flair resource classes override those verbs to add
32
- identity gates, read-scope, and write policy.
32
+ identity gates, read-scope, and write policy. A collection `POST
33
+ /<TypeName>/` from a non-admin HTTP caller is served only by a resource
34
+ class that defines `post()`; on a table without one it is refused. The
35
+ resource's `allowCreate()` check runs first and can refuse it; otherwise the
36
+ collection `POST` guard answers 403 for a verified agent, 401 without a valid
37
+ credential, and refuses a caller it cannot resolve.
33
38
  2. **`export class Foo extends Resource`** in `resources/` — Harper mounts the
34
39
  class name as `/Foo`. Custom verbs are whatever the class implements
35
40
  (`post()` for actions, `get()` for reads).
@@ -54,6 +59,30 @@ the schema section so the catalog is complete.
54
59
  Anonymous HTTP is denied on every agent-facing table (and on `GET /Presence`, which needs a verified reader unless the instance enables the public-roster opt-in). A by-id miss and a
55
60
  by-id deny both return **404**, never 403, so ids are not an existence oracle.
56
61
 
62
+ **PATCH updates existing rows.** On every table, a PATCH from a caller that is
63
+ not an administrator or a trusted internal call does not create or modify its
64
+ target row when that row does not exist. The table's guard answers **404**; a resource or
65
+ authorization check that refuses the request first answers with its own status
66
+ (MemoryHostSource and MemoryUsage refuse such a PATCH with 403). Where a
67
+ resource permits creation, create the row with POST or PUT, under the
68
+ resource's own create rules; PATCH then updates it.
69
+
70
+ **Subscriptions.** An exported table can also be subscribed to on its route:
71
+ SSE (`Accept: text/event-stream`) or WebSocket on `/<Table>/` or
72
+ `/<Table>/<id>`. Table subscriptions are served to administrators (Admin Basic
73
+ or an admin agent) and trusted internal callers only. A verified non-admin
74
+ agent is refused with **403** (WebSocket close code 3003), and a caller without
75
+ a valid credential with **401** (close code 3000). Verified agents receive
76
+ changes to the memories they can read through `/FeedMemories`, and soul changes
77
+ through `/FeedSouls`; neither is a table.
78
+
79
+ Every Ed25519-signed request and federation body carries a nonce, recorded
80
+ once per instance in the `ReplayNonce` table before the request takes effect.
81
+ A nonce already recorded, or being recorded by a concurrent request, is refused
82
+ as a replay (`401`, `nonce_replay_detected` at the auth gate). When the replay
83
+ store is unavailable or the write fails, the request is refused with
84
+ `503 replay_store_unavailable`, and the server log names the cause.
85
+
57
86
  ### Read-scope vocabulary
58
87
 
59
88
  From `RECORD_TYPES` in `resources/record-types.ts`:
@@ -70,7 +99,7 @@ own resource:
70
99
  | Scope | Meaning | Table | Enforced in |
71
100
  |-------|---------|-------|-------------|
72
101
  | **party** | Sender or recipient only | Message | `resources/Message.ts` |
73
- | **own-ledger** | Only the contributing agent's rows | MemoryUsage | `resources/MemoryUsage.ts` |
102
+ | **own-ledger** | Non-admin reads: only the contributing agent's rows, about memories it can read. Admin / internal reads: unfiltered | MemoryUsage | `resources/MemoryUsage.ts` |
74
103
  | **owner-or-grantee** | Either party on the grant | MemoryGrant | `resources/MemoryGrant.ts` |
75
104
 
76
105
  Writes stamp `agentId` (or `authorId` / `from`) from the authenticated
@@ -93,8 +122,8 @@ is `GET /Name/<id>` unless noted.
93
122
 
94
123
  | Method | Path | Auth | Notes |
95
124
  |--------|------|------|-------|
96
- | GET | `/Health`, `/health` | Public | Liveness. `searchReady` is always present; HTTP 503 / `ok: false` when search cannot be served. `embedding: { backend, gpuLayers, source }` states the resolved embed device (flair#1437); `fallback` is present when GPU was requested but Metal did not engage. |
97
- | GET | `/HealthDetail` | Ed25519 | Rich stats (counts, agents, migration). |
125
+ | GET | `/Health`, `/health` | Public | Liveness. `searchReady` is always present; HTTP 503 / `ok: false` when search cannot be served. `embedding: { backend, gpuLayers, source }` states the embed device (flair#1437, flair#2031). A CPU request (`FLAIR_EMBED_GPU_LAYERS=0`, or the `0` default on a host without a usable Metal backend) reports `backend: cpu` / `gpuLayers: 0` without a readback. For a GPU offload request, `backend` is read from the native binding the embedding engine opened during warmup: `metal` when that binding says Metal (`gpuLayers` is then the requested layer count; `99` = all layers), `cpu` with `gpuLayers: 0` only when that binding says no GPU, and `unconfirmed` with `gpuLayers: null` when the binding exposes no readback. During warmup, the preview has `backend: unconfirmed`, `gpuLayers: null`, and `pending: true` (warmup in progress); `pending` is absent after warmup. Doctor treats that pending preview as advisory and asks for a recheck after warmup. A second addon is not opened for this check. `fallback` is present only for the engine-reported CPU case. An empty boot log is not treated as CPU. |
126
+ | GET | `/HealthDetail` | Ed25519 | Rich stats (counts, agents, migration). `bm25.summary` is this worker's lexical index: `building N/M docs`, `ready · N docs`, or `disabled — reason`. |
98
127
  | GET | `/AgentCard/<agentId>` | Public | A2A agent-card; field-allowlisted. |
99
128
  | GET | `/a2a`, `/A2AAdapter` | Public | A2A discovery. |
100
129
  | POST | `/a2a`, `/A2AAdapter` | Ed25519 | JSON-RPC actions (writes OrgEvents, reads tasks). GET-only is public; POST is not. |
@@ -127,8 +156,8 @@ the same identity plane.
127
156
  | DELETE | `/Memory/<id>` | Ed25519 | Owner or admin. `permanent` owner-delete is allowed. |
128
157
  | POST | `/SemanticSearch` | Ed25519 | Hybrid semantic + lexical. Same read-scope as Memory. Default scoring is `raw`. |
129
158
  | POST | `/BootstrapMemories` | Ed25519 | Cold-start context (soul + predicted memories + optional org events). |
130
- | POST | `/RecordUsage` | Ed25519 | Cross-agent usage signal (`Memory.usageCount`). No ownership requirement; no existence oracle in the response. Prefer this over writing `/MemoryUsage` directly. |
131
- | GET | `/MemoryUsage` | Ed25519 | Own ledger rows only. PUT/DELETE are admin/internal — agents must not delete their row to re-count. |
159
+ | POST | `/RecordUsage` | Ed25519 | Cross-agent usage signal (`Memory.usageCount`). No ownership requirement; counts only memories in the caller's read scope (`resolveReadScope`: own at any visibility, others' non-private), admin callers included even though admin Memory reads are unfiltered; an out-of-scope id is handled like a missing one. No existence oracle in the response. Prefer this over writing `/MemoryUsage` directly. |
160
+ | GET | `/MemoryUsage` | Ed25519 | Non-admin reads: own ledger rows only, about memories the caller can currently read; any other row reads as not found. Admin and internal reads are unchanged. PUT/DELETE are admin/internal — agents must not delete their row to re-count. |
132
161
  | GET / write | `/MemoryGrant` | Ed25519 | Read: owner or grantee. Write/delete: owner only (you share your own memories). |
133
162
  | GET / write | `/Asset` | Ed25519 | Owner-only blobs linked by `memoryId`. No MCP and no federation in this slice. |
134
163
  | GET / write | `/MemoryCandidate` | Ed25519 | Owner-only REM drafts. Never auto-promoted except the narrow ADK path. |
@@ -183,7 +212,7 @@ The remedy is `flair upgrade` (the adapter), not a server upgrade alone.
183
212
 
184
213
  | Method | Path | Auth | Read / write |
185
214
  |--------|------|------|--------------|
186
- | GET / PUT | `/Relationship` | Ed25519 | Owner-only. Upsert via PUT; provenance stamped server-side. |
215
+ | GET / POST / PUT | `/Relationship` | Ed25519 / Admin Basic | Owner-only for non-admin agents; administrators can read across owners. POST creates; a create that is otherwise admitted, valid and within the rate limit is 409 when its id already exists. PUT upserts. For a verified non-admin agent both stamp the owner from the caller (a body naming another agent is 403); an administrator keeps the owner it supplies. A write that passes validation gets provenance built server-side. |
187
216
  | GET / POST / PUT | `/WorkspaceState` | Ed25519 | Owner-only. POST stamps `agentId`; PUT rejects a mismatch. |
188
217
  | GET | `/WorkspaceLatest` | Ed25519 | Latest workspace row for the caller. |
189
218
  | GET / POST / PUT | `/OrgEvent` | Ed25519 | Any verified agent reads every event. Writes stamp `authorId`. |
@@ -204,14 +233,15 @@ The remedy is `flair upgrade` (the adapter), not a server upgrade alone.
204
233
  | GET / write | `/Peer` | Admin Basic | Pinned peer keys and sync cursors. |
205
234
  | GET / write | `/PairingToken` | Admin Basic | One-time tokens; default TTL 1 hour. |
206
235
 
207
- `Nonce` and `SyncLog` are **not** `@export` — no agent REST. Nonce is the
208
- anti-replay store; SyncLog is the operator audit trail.
236
+ `ReplayNonce` and `SyncLog` are **not** `@export` — no agent REST.
237
+ ReplayNonce is the anti-replay store (shared with agent auth); SyncLog is the
238
+ operator audit trail.
209
239
 
210
240
  ### Messaging (Flair Relay)
211
241
 
212
242
  | Method | Path | Auth | Notes |
213
243
  |--------|------|------|-------|
214
- | GET / POST | `/Message` | Ed25519 | POST sends (signed envelope). GET is party-scoped (`from` or `to`). Direct PUT is admin/internal. |
244
+ | GET / POST | `/Message` | Ed25519 | POST sends (signed envelope). A POST that reuses a stored message id returns that message's accepted envelope only to its sender; any other sender gets **403** `forbidden: cannot modify Message owned by another principal`. GET is party-scoped (`from` or `to`). Direct PUT is admin/internal. |
215
245
  | GET | `/MessageInbox` | Ed25519 | Inbox for the caller. |
216
246
  | POST | `/MessageAck` | Ed25519 | Consume a delivered message. |
217
247
  | GET | `/MessageDeadLetter` | Ed25519 | Visible failures for the sender (`deadline`, `inbox_full`, …). |
@@ -349,11 +379,45 @@ A peer can therefore show `presenceStatus: "offline"`, `activity: "idle"`, `last
349
379
  | `subject` / `summary` | String | Compression: subject → summary → content |
350
380
  | `validFrom` / `validTo` | String | Temporal validity; expired rows drop out of search |
351
381
  | `_safetyFlags` | [String] | Content-safety scan |
352
- | `provenance` | String | Server JSON `{ v, verified, claimed? }` |
353
- | `originatorInstanceId` | String | Write-time instance id; preserved across sync |
382
+ | `provenance` | String | Server JSON `{ v, verified: { agentId, timestamp, receivedAt }, claimed? }`. On a freshly-stamped LOCAL write, every field under `verified` is server-derived: `timestamp` and `receivedAt` (A4 of #1940) are the server write instant, never client-writable. `claimed?` holds unverified caller claims — `createdAt` (the record's claimed creation time, #1960), `model`, `client`. There is no bulk rewrite of the stored blob: an untouched row keeps it until a later semantic local write re-stamps it. Rows NOT re-stamped — legacy rows (no `claimed.createdAt`, and pre-`receivedAt` rows lack that too), the `_reindex` maintenance re-PUT, a metadata-only PATCH (no content or creation-claim change), and federation-synced rows (which keep the ORIGINATOR's blob) — keep their stored `provenance` unchanged. |
383
+ | `originatorInstanceId` | String | Server-stamped write-time instance id, applied on every application write (Memory/Soul/Agent/Relationship `post()`/`put()`/`patch()`, Memory's `_reindex` re-PUT, the `POST /FeedMemories` ingest, `POST /AgentSeed` and the MCP/IdP principal provisioning). On create the local id is stamped and any request-body value is ignored; on update the stored value stands (a body value neither replaces nor clears it). Preserved across sync. Not client-writable through a resource write. Federation and the administrator ops API are exceptions to the stamping rule, not the field's only raw writers: the federation merge (`POST /FederationSync`, a signed HTTP body from a known, non-revoked peer) applies a verified peer's rows through the raw table handle, and the administrator ops API can set any column under admin auth. |
354
384
  | `metadata` | String | Client JSON blob; opaque to the server |
355
385
  | `entities` | [String] | Attention-plane `type:value` strings |
356
386
 
387
+ > The host pointer (`hostSource`) is **not** a Memory attribute — it lives in its own `MemoryHostSource` table (below). There is no `hostSource` / `hostSourceVisibility` field on `Memory`.
388
+
389
+ #### Memory host pointer (`MemoryHostSource`, #1940 A1'-A5)
390
+
391
+ The pointer is a host-object pointer — versioned JSON `{ v: 1, host, kind, id, url? }` — that records which host object the writer claims as the memory’s source. **Supported writes store host pointers only in `MemoryHostSource`. For non-admin `Memory.get`, `Memory.search`, and `SemanticSearch` results, the gated projection removes inline pointer fields and renders a pointer only from a bound `MemoryHostSource` row.**
392
+
393
+ `MemoryHostSource` fields:
394
+
395
+ | Field | Type | Notes |
396
+ |-------|------|-------|
397
+ | `memoryId` | ID (primary key) | The `Memory.id` this pointer belongs to. |
398
+ | `hostSource` | String | The canonical pointer JSON (fixed key order, NFC). |
399
+ | `scopeAtWrite` | String | The record's visibility at write when the write opted in (`hostSourceScope: "record"`); `null` = author-only. |
400
+ | `authorId` | String | The authenticated principal, server-stamped — never the body. |
401
+ | `memoryInstanceToken` | String | The Memory row’s server-stamped `instanceToken` at pointer-write time; the join binds on it (see below). |
402
+ | `receivedAt` | String | Server receipt time. |
403
+
404
+ The **binding** (A1-iv item 1): The named application create paths stamp a local `instanceToken`; existing legacy rows may have none. Memory's REST write paths remove client-supplied `instanceToken` and `provenance`. The named update paths retain a stored token when their existing-row read succeeds. The join returns a pointer (or `"withheld"`) only when `memoryId`, `authorId === memory.agentId`, `memoryInstanceToken === memory.instanceToken`, and “not archived” all hold (`b1`–`b5`), so a deleted-and-recreated id, a re-owned row and an archived row all show no pointer.
405
+
406
+ **Write (`POST /Memory`, `PUT /Memory/<id>`)** — the three pointer inputs (`hostSource`, `hostSourceScope`, `hostSourceVisibility`) are write-body-only and are stripped from the Memory row before persist; only `post()`/`put()` accept them. The Memory row and its pointer row commit together or not at all because they share ONE transaction: a request's open transaction when there is one, and a created one when an internal caller has no request context (`transaction(ctx, cb)`). A pointer that cannot be persisted aborts that transaction, so neither row commits (real-Harper rollback assertions `t1`/`t2`; the transaction helper throws rather than running unwrapped). A partial PUT that omits `visibility` carries the visibility read from the existing row into the written row, so it is preserved sequentially (`p2`); concurrent updates need a conflict check to guarantee preservation. The guard keeps declared Memory attributes and the explicit `UNDECLARED_ALLOWED` fields. Memory's REST write paths remove `instanceToken` and `provenance` from the request body. `originatorInstanceId` is server-stamped too (#1965): a create stamps the local instance id and ignores any body value, an update keeps the stored value, and an administrator's or trusted internal `PATCH` that creates a row is stamped as well (a `PATCH` from any other caller creates no row). The pre-existing row is resolved by the URL-bound target id (never a body `id`); a body id that disagrees with the address, or a stored-row read that fails, refuses the write. It is not client-writable through a resource write; see the `originatorInstanceId` field entry above for the write paths and their per-path stamping rules.
407
+
408
+ - **A1'** — the pointer is its own table; the Memory schema declares no `hostSource`. Additive with no data migration.
409
+ - **A2** — the server validates and REJECTS (never truncates): `host`/`kind` come from a closed set (`openclaw/run`, `cursor/launch`, `codex/turn`); `id` matches `^[A-Za-z0-9._:/@#-]{1,256}$`; `url` is https only, with NO userinfo (an empty userinfo `https://@host/` is refused), capped at 2048 characters; C0/DEL/C1 controls (U+0000-U+001F, U+007F-U+009F, including U+0085) and the FULL bidi set (U+200E, U+200F, U+202A-U+202E, U+2066-U+2069) are refused anywhere; values are NFC-normalised; unknown keys or any `v` other than 1 are refused. `hostSourceScope: "record"` opts the pointer into the record's own read scope (A3); any wider scope is refused.
410
+ - **A4** — the server stamps `receivedAt` inside `provenance`; it is server-stamped and never client-writable. `createdAt` stays the writer's claimed time, so `asOf`/valid-time queries use the writer's claim.
411
+ - **A5** — the pointer is NOT inside `provenance`; `provenance` stays never-client-writable.
412
+
413
+ **Read** — the pointer reaches a reader ONLY through a gated join into Memory results (search, by-ID, semantic search; semantic results carry the joined pointer to a permitted reader — test `(s5)`), which has three outcomes: the pointer, `"withheld"`, or nothing. A pointer is visible only to the record's author unless the write opted it into the record's scope, and it is never wider than its record: the effective visibility is the narrower of the record's write-time visibility (`scopeAtWrite`) and its current visibility (`narrower(scopeAtWrite, record.visibility)`). The join takes the narrower of the stored pointer scope and the Memory row's current visibility, so a later widening of the record does not widen the pointer. A reader who may read the record but not the pointer: On the three named non-admin reads, a bound pointer outside the reader's pointer scope renders as `"withheld"`; an unbound or archived pointer renders nothing. Wherever a URL is rendered, only scheme, host and path appear; query and fragment are stripped. Redaction is applied on the server, in the read projection — no client or MCP layer can un-redact. `Memory.get()`, `Memory.search()` and `SemanticSearch` render pointers through the pointer helper. Other Memory projections, bootstrap included, do not render pointers in this slice. The readers fetch pointers for the whole result set in ONE batched query.
414
+
415
+ **Direct access** — Direct resource reads permit admin agents and trusted in-process callers; non-admin agents cannot read this table directly. The author reads their own pointer only through the gated join. The table has **NO REST write verbs**: `POST`/`PUT`/`PATCH`/`DELETE` to the resource are refused for EVERY caller, non-admin and admin alike, with nothing written (`r4-http`), so no REST caller can plant a pointer. A superuser Harper operation against the table (an admin `export`, `backup`, `reseed`, or a hygiene/forensics read of orphaned or author-only pointers) is the named operator path and is not gated by the resource (`r4-http` proves only the resource refusal). This admin exception names `MemoryHostSource` explicitly.
416
+
417
+ **Federation** — `MemoryHostSource` is excluded from the sync's table set by mechanism (it is absent from the federation table policy), and an inbound row carrying a pointer field is refused. The outbound reader projects declared Memory attributes. The inbound merge removes undeclared attributes except the named bookkeeping fields (`f1-out`, `f1-in`). `Memory.delete` and maintenance expiry or age-based archival delete the pointer with their Memory operation. `MemoryArchive` basement/restore retains the pointer row; the join suppresses it while the Memory is archived. `Memory.delete` joins a request transaction when present; maintenance uses an owned transaction per item. An orphan sweep re-checks inside the transaction before deleting; a cleanup failure makes the maintenance run report a failure, not "complete". Orphaned pointers are absent from ordinary Memory joins but remain directly readable by administrators.
418
+
419
+ A `hostSource`, like a client-supplied `createdAt`, is a writer claim attributed to the authenticated agent on agent writes; it is a **claimed external source**. Flair does not verify the host object and does not cryptographically sign the pointer body (the Ed25519 request signature covers method and URL, not the body).
420
+
357
421
  ### Soul
358
422
 
359
423
  | Field | Type | Notes |
@@ -366,7 +430,7 @@ A peer can therefore show `presenceStatus: "offline"`, `activity: "idle"`, `last
366
430
  | `provenance` | String | Operator/internal author + `sourceClass` |
367
431
  | `durability` | String | Default `permanent` |
368
432
  | `createdAt` / `updatedAt` | String | |
369
- | `originatorInstanceId` | String | Federation origin |
433
+ | `originatorInstanceId` | String | Server-stamped write-time instance id; not client-writable through a resource write |
370
434
 
371
435
  ### Agent (Principal)
372
436
 
@@ -387,7 +451,7 @@ agents.
387
451
  | `runtime` / `runtimeEndpoint` | String | How to reach the principal |
388
452
  | `subjects` | [String] | Soul-level interests |
389
453
  | `createdAt` / `updatedAt` | String | |
390
- | `originatorInstanceId` | String | Federation origin |
454
+ | `originatorInstanceId` | String | Server-stamped write-time instance id; not client-writable through a resource write |
391
455
 
392
456
  Related: **Credential** (`principalId`, `kind` webauthn / bearer-token /
393
457
  ed25519 / idp) and **Integration** (legacy platform connection).
@@ -399,7 +463,7 @@ ed25519 / idp) and **Integration** (legacy platform connection).
399
463
  | **Instance** | yes | One row per Flair instance (`id`, `publicKey`, `role` hub/spoke, `fabricEndpoint`, `status`) |
400
464
  | **PairingToken** | yes | One-time token (`expiresAt`, `consumedBy`) |
401
465
  | **Peer** | yes | Pinned peer (`publicKey`, `endpoint`, `status`, `lastSyncAt` / `lastMergeAt`, `lastSyncCursor`, `relayOnly`) |
402
- | **Nonce** | no | Body-sig anti-replay; PK is the nonce string |
466
+ | **ReplayNonce** | no | `schemas/replay.graphql`. Anti-replay record shared by agent auth (`a:<agentId>:<nonce>`) and federation body signatures (`f:<nonce>`). Local to the instance (`replicate: false`); rows expire after 120 s |
403
467
  | **SyncLog** | no | Per-sync audit (`peerId`, `direction`, counts, `skippedReasons`, `status`) |
404
468
 
405
469
  ### Other tables