@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
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Subscriptions on flair's table routes are served to administrators and
3
+ * trusted internal callers only.
4
+ *
5
+ * An exported table has a subscription route: SSE (`Accept:
6
+ * text/event-stream`, which Harper dispatches as CONNECT) and WebSocket on
7
+ * `/<Table>/` and `/<Table>/<id>`. A table subscription streams the table's
8
+ * stored rows, while flair's per-record read rules are applied by each
9
+ * resource's get()/search(). So the table route refuses every caller that is
10
+ * not an administrator or a trusted internal call: a verified non-admin agent
11
+ * gets 403, a caller without a valid credential 401. Resources that are not
12
+ * tables, such as the feed resources, decide their own subscribers and are not
13
+ * affected.
14
+ *
15
+ * ── The seam ────────────────────────────────────────────────────────────────
16
+ * Harper enters an exported table's subscription route — SSE and WebSocket
17
+ * alike — through the static `connect()` of the class registered for that
18
+ * route, and hands it the request as its context. `guardTableSubscriptions`
19
+ * replaces that static `connect()` on every table class in the flair
20
+ * database's table registry, read at load (resources/table-subscriptions.ts),
21
+ * not from a list someone maintains:
22
+ * - a table added to the schema is in that registry, so its class gets the
23
+ * guard without anyone naming it, and its route uses the guard once the
24
+ * table is exported;
25
+ * - a flair resource class that extends a table inherits the guarded static,
26
+ * and overriding an INSTANCE `connect()`/`subscribe()` does not bypass it,
27
+ * because the static runs first. A class that defines its own STATIC
28
+ * `connect()` replaces the guarded one; none does today, and one that does
29
+ * must apply the same check itself;
30
+ * - in-process callers (the feed resources, the BM25 index) subscribe
31
+ * through the table's `subscribe()`, not `connect()`, so they are
32
+ * unaffected.
33
+ * test/integration/table-subscription-default-deny.test.ts reads every table in
34
+ * the database at runtime and fails if a non-admin subscriber is admitted to a
35
+ * table's collection route (`/<Table>/`) or by-id route (`/<Table>/<id>`), over
36
+ * SSE or WebSocket.
37
+ *
38
+ * This module has no imports, so it is unit-tested directly
39
+ * (test/unit/table-subscription-policy.test.ts); the dependencies it needs are
40
+ * passed in by resources/table-subscriptions.ts.
41
+ */
42
+ /** Marks a table class whose static `connect()` has been guarded. */
43
+ export const TABLE_SUBSCRIPTION_GUARD = Symbol.for("flair.tableSubscriptionGuard");
44
+ function looksLikeContext(value) {
45
+ if (value == null || typeof value !== "object")
46
+ return false;
47
+ const v = value;
48
+ return (typeof v.getContext === "function" ||
49
+ "request" in v ||
50
+ "user" in v ||
51
+ "transaction" in v ||
52
+ "headers" in v ||
53
+ "tpsAgent" in v ||
54
+ "tpsAnonymous" in v);
55
+ }
56
+ /**
57
+ * The context a static `connect(target, data, context)` call runs under,
58
+ * resolved the way Harper resolves it: the explicit context argument (the
59
+ * request, for SSE and WebSocket), else a context passed in the data position
60
+ * (the two-argument in-process form), else the ambient context.
61
+ */
62
+ export function subscriptionCallerContext(data, context, ambientContext) {
63
+ if (context)
64
+ return context.getContext?.() || context;
65
+ if (looksLikeContext(data))
66
+ return data.getContext?.() || data;
67
+ return ambientContext();
68
+ }
69
+ /**
70
+ * The longest error text Harper can return for a refused subscription. Harper
71
+ * sends the error as the WebSocket close reason (`Error: <message>`), and a
72
+ * close reason is limited to 123 bytes; a longer one fails to close the socket.
73
+ * The messages below therefore do not include the table name.
74
+ */
75
+ export const MAX_REFUSAL_REASON_BYTES = 123;
76
+ /**
77
+ * Why `caller` may not subscribe to a table route, as the error the route
78
+ * returns; null for an administrator or a trusted internal call.
79
+ */
80
+ export function tableSubscriptionRefusal(caller) {
81
+ if (caller.kind === "internal")
82
+ return null;
83
+ if (caller.kind === "agent" && caller.isAdmin === true)
84
+ return null;
85
+ if (caller.kind === "agent") {
86
+ return Object.assign(new Error("table subscriptions are for administrators"), { statusCode: 403 });
87
+ }
88
+ return Object.assign(new Error("table subscriptions need an administrator credential"), { statusCode: 401 });
89
+ }
90
+ /** The error for a subscription whose caller could not be resolved. */
91
+ export function unverifiedSubscriberRefusal() {
92
+ return Object.assign(new Error("the subscriber could not be verified, so the table subscription was refused; retry"), { statusCode: 500 });
93
+ }
94
+ /**
95
+ * Replace the static `connect()` of every table class in `tables` with one that
96
+ * admits only administrators and trusted internal calls, then delegates to the
97
+ * inherited `connect()` unchanged. Idempotent. A failure to resolve the caller
98
+ * refuses the subscription. Returns the names of the guarded tables.
99
+ */
100
+ export function guardTableSubscriptions(tables, deps) {
101
+ const guarded = [];
102
+ for (const name of Object.keys(tables ?? {})) {
103
+ const table = tables[name];
104
+ if (typeof table !== "function")
105
+ continue;
106
+ if (Object.prototype.hasOwnProperty.call(table, TABLE_SUBSCRIPTION_GUARD)) {
107
+ guarded.push(name);
108
+ continue;
109
+ }
110
+ const inherited = table.connect;
111
+ if (typeof inherited !== "function")
112
+ continue; // no subscription entry point to guard
113
+ Object.defineProperty(table, "connect", {
114
+ configurable: true,
115
+ writable: true,
116
+ enumerable: false,
117
+ value: async function connect(target, data, context) {
118
+ let caller;
119
+ try {
120
+ caller = await deps.resolveAuth(subscriptionCallerContext(data, context, deps.ambientContext));
121
+ }
122
+ catch {
123
+ throw unverifiedSubscriberRefusal();
124
+ }
125
+ const refusal = tableSubscriptionRefusal(caller);
126
+ if (refusal)
127
+ throw refusal;
128
+ return inherited.call(this, target, data, context);
129
+ },
130
+ });
131
+ Object.defineProperty(table, TABLE_SUBSCRIPTION_GUARD, { value: true });
132
+ guarded.push(name);
133
+ }
134
+ return guarded;
135
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Installs the table-subscription guard (resources/table-subscription-policy.ts)
3
+ * on every table class in the flair database's table registry when the
4
+ * component loads: the static `connect()` of each table class — the entry
5
+ * Harper uses for an exported table's SSE and WebSocket subscription routes —
6
+ * admits only administrators and trusted internal calls. The tables are read
7
+ * from the registry, so the class of a table added to the schema gets the guard
8
+ * without being named here.
9
+ *
10
+ * This module deliberately exports nothing: Harper registers exported values of
11
+ * a resource module as routes.
12
+ */
13
+ import { databases, getContext } from "harper";
14
+ import { resolveAgentAuth } from "./agent-auth.js";
15
+ import { guardTableSubscriptions } from "./table-subscription-policy.js";
16
+ guardTableSubscriptions(databases.flair, {
17
+ resolveAuth: resolveAgentAuth,
18
+ ambientContext: () => getContext(),
19
+ });
@@ -51,7 +51,7 @@ export function descriptorNames(descriptors) {
51
51
  export const TOOL_DESCRIPTORS = [
52
52
  {
53
53
  "name": "memory_search",
54
- "description": "Search memories by meaning. Understands temporal queries like 'what happened today'. Scoped to your agent's own and other agents' non-private memories.",
54
+ "description": "Search memories by meaning. Understands temporal queries like 'what happened today'. Non-admin callers are scoped to their own and other agents' non-private memories; administrator requests may have broader access.",
55
55
  "inputSchema": {
56
56
  "type": "object",
57
57
  "properties": {
@@ -80,7 +80,7 @@ export const TOOL_DESCRIPTORS = [
80
80
  "query"
81
81
  ]
82
82
  },
83
- "outputShape": "{ results: MemoryRecord[] } — semantic hits scoped to the caller's own and other agents' non-private memories; each hit carries content, never the raw embedding.",
83
+ "outputShape": "{ results: MemoryRecord[] } — semantic hits subject to the caller's read scope; each hit carries content, never the raw embedding.",
84
84
  "annotations": {
85
85
  "readOnlyHint": true
86
86
  },
@@ -135,7 +135,7 @@ export const TOOL_DESCRIPTORS = [
135
135
  "private",
136
136
  "shared"
137
137
  ],
138
- "description": "Writer-controlled sharing intent. Omit to use the server's durability-keyed default: permanent/persistent -> shared, standard/ephemeral -> private. private — owner-only, never visible to another agent, even one holding a memory grant. shared — visible to the owner and every other agent on this instance. The visibility the write actually landed on is returned in the result."
138
+ "description": "Writer-controlled sharing intent. Omit to use the server's durability-keyed default: permanent/persistent -> shared, standard/ephemeral -> private. private — readable by its owner and administrators; other non-admin agents cannot read it, including through a memory grant. shared — visible to the owner and every other agent on this instance. The visibility the write actually landed on is returned in the result."
139
139
  },
140
140
  "usedMemoryIds": {
141
141
  "type": "array",
@@ -189,7 +189,7 @@ export const TOOL_DESCRIPTORS = [
189
189
  },
190
190
  {
191
191
  "name": "skill_search",
192
- "description": "Find skills (reusable capabilities/procedures) that apply to a task. Ranks skill-tagged memories by their `trigger` ('when to use') against your task text. Returns a lightweight CATALOG — id, name, trigger, description, tags, agentId — NOT the full procedure (fetch that with skill_get). Scoped to your own + shared skills; another agent's private skill is never returned.",
192
+ "description": "Find skills (reusable capabilities/procedures) that apply to a task. Ranks skill-tagged memories by their `trigger` ('when to use') against your task text. Returns a lightweight CATALOG — id, name, trigger, description, tags, agentId — NOT the full procedure (fetch that with skill_get). Non-admin callers can retrieve their own and other agents' non-private skills; administrators can also retrieve private skills.",
193
193
  "inputSchema": {
194
194
  "type": "object",
195
195
  "properties": {
@@ -206,14 +206,14 @@ export const TOOL_DESCRIPTORS = [
206
206
  "task"
207
207
  ]
208
208
  },
209
- "outputShape": "{ results: SkillCard[] } — the skill catalog (lightweight id/name/trigger/description/tags/agentId, ranked by trigger match); the full procedure and the raw embedding are never on a card. Scoped to the caller's own + non-private skills; another agent's private skill is never returned.",
209
+ "outputShape": "{ results: SkillCard[] } — the skill catalog (lightweight id/name/trigger/description/tags/agentId, ranked by trigger match); the full procedure and the raw embedding are never on a card. Non-admin callers can retrieve their own and other agents' non-private skills; administrators can also retrieve private skills.",
210
210
  "annotations": {
211
211
  "readOnlyHint": true
212
212
  }
213
213
  },
214
214
  {
215
215
  "name": "skill_get",
216
- "description": "Retrieve a full skill by ID — the complete procedure (`content`) plus trigger and metadata. The disclosure step after skill_search's catalog. Read-scoped: you can only get your own or a shared skill, never another agent's private skill. A non-skill id returns not-found. The raw embedding vector is never returned.",
216
+ "description": "Retrieve a full skill by ID — the complete procedure (`content`) plus trigger and metadata. The disclosure step after skill_search's catalog. Reads follow the caller's authorization: non-admin callers can retrieve their own and other agents' non-private skills; administrators can also retrieve private skills. A non-skill id returns not-found. The raw embedding vector is never returned.",
217
217
  "inputSchema": {
218
218
  "type": "object",
219
219
  "properties": {
@@ -226,7 +226,7 @@ export const TOOL_DESCRIPTORS = [
226
226
  "id"
227
227
  ]
228
228
  },
229
- "outputShape": "The full skill record { id, agentId, content, trigger, tags, durability, metadata, createdAt, ... } for a skill readable under the caller's read-scope — embedding + embeddingModel always stripped. A non-owner cannot read another agent's private skill, and a readable non-skill id is not found (both 404).",
229
+ "outputShape": "The full skill record { id, agentId, content, trigger, tags, durability, metadata, createdAt, ... } for a skill readable under the caller's read-scope — embedding + embeddingModel always stripped. A non-admin caller cannot read another agent's private skill; administrators retain access. A readable non-skill id is reported as not found.",
230
230
  "annotations": {
231
231
  "readOnlyHint": true
232
232
  }
@@ -268,7 +268,7 @@ export const TOOL_DESCRIPTORS = [
268
268
  },
269
269
  {
270
270
  "name": "memory_basement",
271
- "description": "Send a memory to the basement (archive it). Sets archived=true and stamps archivedAt. The memory is removed from bootstrap and default search but remains retrievable via memory_get and memory_search(includeArchived:true). Deliberate and GLOBAL — this is a visibility flag, not a deletion: provenance and history are untouched. Scoped to your own memories only.",
271
+ "description": "Send a memory to the basement (archive it). Sets archived=true and stamps archivedAt. The memory is removed from bootstrap and default search but remains retrievable via memory_get and memory_search(includeArchived:true). Deliberate and GLOBAL — this is a visibility flag, not a deletion: provenance and history are untouched. Non-admin callers can modify only their own memories; administrators can also modify other agents' memories.",
272
272
  "inputSchema": {
273
273
  "type": "object",
274
274
  "properties": {
@@ -286,7 +286,7 @@ export const TOOL_DESCRIPTORS = [
286
286
  },
287
287
  {
288
288
  "name": "memory_restore",
289
- "description": "Restore a basemented (archived) memory. Clears archived and archivedAt. Deliberate and GLOBAL — this un-retires the memory for EVERY session, not a session-local view (per-session reuse is drawers, which do not exist yet). Scoped to your own memories only.",
289
+ "description": "Restore a basemented (archived) memory. Clears archived and archivedAt. Deliberate and GLOBAL — this un-retires the memory for EVERY session, not a session-local view (per-session reuse is drawers, which do not exist yet). Non-admin callers can modify only their own memories; administrators can also modify other agents' memories.",
290
290
  "inputSchema": {
291
291
  "type": "object",
292
292
  "properties": {
@@ -325,7 +325,7 @@ export const TOOL_DESCRIPTORS = [
325
325
  "id"
326
326
  ]
327
327
  },
328
- "outputShape": "The full memory record { id, agentId, content, durability, createdAt, ... } for the caller's own id — embedding + embeddingModel stripped by default.",
328
+ "outputShape": "The full memory record { id, agentId, content, durability, createdAt, ... } for the requested ID, subject to the caller's read scope; embedding and embeddingModel are stripped by default.",
329
329
  "annotations": {
330
330
  "readOnlyHint": true
331
331
  },
@@ -336,7 +336,7 @@ export const TOOL_DESCRIPTORS = [
336
336
  },
337
337
  {
338
338
  "name": "memory_delete",
339
- "description": "Delete a memory by ID. You can only delete your own memories.",
339
+ "description": "Delete a memory by ID. Non-admin callers can delete only their own memories; administrators can also delete other agents' memories.",
340
340
  "inputSchema": {
341
341
  "type": "object",
342
342
  "properties": {
@@ -349,7 +349,7 @@ export const TOOL_DESCRIPTORS = [
349
349
  "id"
350
350
  ]
351
351
  },
352
- "outputShape": "Deletes the caller's own memory at any durability tier (success echo is thin). Cross-owner deletion returns { error, status:403 } for a non-admin; a deleted row round-trips as gone via memory_get.",
352
+ "outputShape": "Deletes a memory by ID when authorized, at any durability tier (success echo is thin). Cross-owner deletion returns { error, status:403 } for a non-admin; a deleted row round-trips as gone via memory_get.",
353
353
  "annotations": {
354
354
  "destructiveHint": true
355
355
  }
@@ -490,7 +490,7 @@ export const TOOL_DESCRIPTORS = [
490
490
  ]
491
491
  },
492
492
  "outputShape": "Refuses runtime Soul writes, including admin-agent delegation, with { error, status:403 }. Operators use the authenticated REST or CLI path.",
493
- "stdioDescription": "Set a personality or project context entry. Included in every bootstrap."
493
+ "stdioDescription": "Set a personality or project context entry, included in every bootstrap. Soul writes require verified administrator Basic credentials; Ed25519 agent requests are refused. Operators should use the REST API or CLI."
494
494
  },
495
495
  {
496
496
  "name": "soul_get",
@@ -588,7 +588,7 @@ export const TOOL_DESCRIPTORS = [
588
588
  },
589
589
  {
590
590
  "name": "flair_catchup",
591
- "description": "Drain YOUR OWN catch-up feed — org events directed to you (or broadcast) after your durable watermark. Returns a page plus a `nextAfter` cursor: page with `after`, then advance the watermark with `ack`. Owner-scoped: the participant is your signed identity, so you can only ever read your own feed — there is no agentId parameter and any other feed is refused (403). At-least-once: an event may arrive twice (re-delivery is safe), an acked event does not re-deliver, and an un-acked event survives a restart.",
591
+ "description": "Drain the catch-up feed for the configured `FLAIR_AGENT_ID`: directed or broadcast org events after the effective cursor. Omit `after` to start at that agent's durable watermark, or pass `after` to choose an exclusive cursor. Pass `ack` to advance the watermark before this call reads a page; the response includes `nextAfter` for paging. The tool has no argument to change the agent id. Agent requests are signed for the configured id; verified administrator Basic credentials may read that configured feed. Unacknowledged events remain eligible after restart; acknowledged events are skipped by default, but an explicit older `after` can replay them.",
592
592
  "inputSchema": {
593
593
  "type": "object",
594
594
  "properties": {
@@ -606,7 +606,7 @@ export const TOOL_DESCRIPTORS = [
606
606
  }
607
607
  }
608
608
  },
609
- "outputShape": "{ events: OrgEvent[], after, nextAfter, watermark, hasMore, pageSize, acked? } — the caller's own directed + broadcast events after its durable watermark, paged; `ack` advances the watermark monotonically (at-least-once — re-delivery is safe).",
609
+ "outputShape": "{ events: OrgEvent[], after, nextAfter, watermark, hasMore, pageSize, acked? } — the configured agent's directed and broadcast events after the effective cursor; `ack` advances that agent's durable watermark monotonically.",
610
610
  "native": false
611
611
  },
612
612
  {
@@ -32,8 +32,8 @@
32
32
  *
33
33
  * ─── `claimed.*` is surfaced as a BOOLEAN only ──────────────────────────────
34
34
  * `hasClaimedProvenance` reports only WHETHER the record carries a self-
35
- * reported `claimed` sub-object — never its content. Raw `claimed.model` /
36
- * `claimed.client` values are self-reported and unverified (resources/
35
+ * reported `claimed.model` / `claimed.client` — never its content. Raw
36
+ * `claimed.*` values are self-reported and unverified (resources/
37
37
  * provenance.ts); exposing them as authoritative trust evidence would defeat
38
38
  * the verified-vs-claimed distinction the block exists to draw. The advisory
39
39
  * "there is a self-report here" bit is enough for the reader to weight it.
@@ -130,7 +130,14 @@ export function buildTrustBlock(record, now = Date.now()) {
130
130
  verifiedAt = typeof p.verified.timestamp === "string" ? p.verified.timestamp : null;
131
131
  }
132
132
  // Boolean only — the self-reported content is deliberately NOT surfaced.
133
- hasClaimedProvenance = p.claimed != null && typeof p.claimed === "object";
133
+ // flair#1960: `claimed.createdAt` is on every new row, so it must not
134
+ // count here or the bit would always read true; it flags the optional
135
+ // model/client authorship claims only.
136
+ const claimed = p.claimed;
137
+ hasClaimedProvenance =
138
+ claimed != null &&
139
+ typeof claimed === "object" &&
140
+ (typeof claimed.model === "string" || typeof claimed.client === "string");
134
141
  }
135
142
  }
136
143
  catch {
@@ -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
+ }