@tpsdev-ai/flair 0.56.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
@@ -0,0 +1,109 @@
1
+ /**
2
+ * PATCH updates an existing row. For a caller that is not an administrator or a
3
+ * trusted internal call, a PATCH never creates one; where a resource permits
4
+ * creation, rows are created with POST or PUT under the resource's own create
5
+ * rules.
6
+ *
7
+ * Harper's PATCH writes to the row its URL names and, when that row does not
8
+ * exist, would create it from the request body alone. So each guarded table's
9
+ * own `patch()` refuses a PATCH whose target row does not exist unless the
10
+ * caller is an administrator or a trusted internal call: the caller gets 404.
11
+ * A resource or authorization check that refuses the request before the
12
+ * table's `patch()` runs answers with its own status instead. A PATCH to an
13
+ * existing row is unchanged — the resources' own rules (ownership, the
14
+ * immutable owner field, validation) still decide it.
15
+ *
16
+ * ── The seam ────────────────────────────────────────────────────────────────
17
+ * `guardTablePatches` gives every table class in the flair database's table
18
+ * registry its own instance `patch()`, read from that registry at load
19
+ * (resources/table-patches.ts), not from a list someone maintains:
20
+ * - a table added to the schema is in that registry, so its class gets the
21
+ * guard without anyone naming it;
22
+ * - Harper has already resolved the target id and loaded the row when the
23
+ * instance `patch()` runs, so the guard decides on the row Harper will
24
+ * write (`doesExist()`), never on a re-parse of the URL;
25
+ * - a resource class without a `patch()` override inherits the guarded
26
+ * method, and an override reaches it only through `super.patch()`. Every
27
+ * flair override today either ends in `super.patch()` for the callers it
28
+ * admits or refuses the request itself: MemoryHostSource refuses every REST
29
+ * write, and MemoryUsage refuses a non-admin PATCH. A future override must
30
+ * do one or the other; an override that writes the row another way would
31
+ * not be covered by this guard.
32
+ * test/integration/patch-updates-existing-rows.test.ts enumerates every table in
33
+ * the database at runtime and fails if a non-admin PATCH creates a row in any.
34
+ *
35
+ * This module has no imports, so it is unit-tested directly
36
+ * (test/unit/table-patch-policy.test.ts); the dependencies it needs are passed
37
+ * in by resources/table-patches.ts.
38
+ */
39
+ /** Marks a table class whose `patch()` has been guarded. */
40
+ export const TABLE_PATCH_GUARD = Symbol.for("flair.tablePatchGuard");
41
+ /**
42
+ * Whether the row a resource instance addresses exists: true or false as the
43
+ * instance reports it, or undefined when the instance cannot say (the guard
44
+ * then treats the PATCH as a create).
45
+ */
46
+ export function rowExists(resource) {
47
+ const doesExist = resource?.doesExist;
48
+ if (typeof doesExist !== "function")
49
+ return undefined;
50
+ const answer = doesExist.call(resource);
51
+ return typeof answer === "boolean" ? answer : undefined;
52
+ }
53
+ /** The refusal for a PATCH whose target row does not exist; null for an administrator or a trusted internal call. */
54
+ export function patchCreateRefusal(table, caller) {
55
+ if (caller.kind === "internal")
56
+ return null;
57
+ if (caller.kind === "agent" && caller.isAdmin === true)
58
+ return null;
59
+ return Object.assign(new Error(`not found: PATCH updates an existing ${table} row and does not create one; where ${table} permits creation, use POST or PUT`), { statusCode: 404 });
60
+ }
61
+ /** The refusal when the caller of a PATCH that would create a row cannot be resolved. */
62
+ export function unverifiedPatchCallerRefusal(table) {
63
+ return Object.assign(new Error(`the caller of this ${table} PATCH could not be verified, so it was refused; retry`), { statusCode: 500 });
64
+ }
65
+ /**
66
+ * Give every table class in `tables` its own instance `patch()` that refuses to
67
+ * create a row for a caller who is not an administrator or a trusted internal
68
+ * call, then delegates to the inherited `patch()` unchanged. A PATCH to an
69
+ * existing row goes straight through. Idempotent. Returns the names of the
70
+ * guarded tables.
71
+ */
72
+ export function guardTablePatches(tables, deps) {
73
+ const guarded = [];
74
+ for (const name of Object.keys(tables ?? {})) {
75
+ const table = tables[name];
76
+ if (typeof table !== "function" || table.prototype == null)
77
+ continue;
78
+ if (Object.prototype.hasOwnProperty.call(table, TABLE_PATCH_GUARD)) {
79
+ guarded.push(name);
80
+ continue;
81
+ }
82
+ const inherited = table.prototype.patch;
83
+ if (typeof inherited !== "function")
84
+ continue; // no PATCH to guard
85
+ Object.defineProperty(table.prototype, "patch", {
86
+ configurable: true,
87
+ writable: true,
88
+ enumerable: false,
89
+ value: async function patch(...args) {
90
+ if (rowExists(this) !== true) {
91
+ let caller;
92
+ try {
93
+ caller = await deps.resolveAuth(this.getContext?.());
94
+ }
95
+ catch {
96
+ throw unverifiedPatchCallerRefusal(name);
97
+ }
98
+ const refusal = patchCreateRefusal(name, caller);
99
+ if (refusal)
100
+ throw refusal;
101
+ }
102
+ return inherited.apply(this, args);
103
+ },
104
+ });
105
+ Object.defineProperty(table, TABLE_PATCH_GUARD, { value: true });
106
+ guarded.push(name);
107
+ }
108
+ return guarded;
109
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Installs the PATCH guard (resources/table-patch-policy.ts) on every table
3
+ * class in the flair database's table registry when the component loads: a
4
+ * PATCH whose target row does not exist does not create or modify its target
5
+ * row unless the caller is an administrator or a trusted internal call. The
6
+ * tables are read from the registry, so the class of a table added to the
7
+ * schema gets the guard without being named here. A resource that overrides
8
+ * `patch()` reaches the guard only by ending in `super.patch()`; an override
9
+ * that does not must enforce the no-create rule itself by refusing.
10
+ *
11
+ * This module deliberately exports nothing: Harper registers exported values of
12
+ * a resource module as routes.
13
+ */
14
+ import { databases } from "harper";
15
+ import { resolveAgentAuth } from "./agent-auth.js";
16
+ import { guardTablePatches } from "./table-patch-policy.js";
17
+ guardTablePatches(databases.flair, { resolveAuth: resolveAgentAuth });
@@ -0,0 +1,138 @@
1
+ /**
2
+ * A non-admin HTTP collection POST is served only by a resource's own `post()`,
3
+ * which applies that resource's own write rules. On a table whose resource
4
+ * defines no `post()` of its own, a collection POST is refused unless the
5
+ * caller is an administrator or a trusted internal call. Harper runs the
6
+ * resource's `allowCreate()` check before `post()`, and that check can refuse
7
+ * the POST first; a POST that reaches the guard is answered 403 for a verified
8
+ * non-admin agent and 401 for a caller without a valid credential, and is
9
+ * refused when the caller cannot be resolved.
10
+ *
11
+ * ── The seam ────────────────────────────────────────────────────────────────
12
+ * `guardInheritedPosts` gives every table class in the flair database's table
13
+ * registry that has a `post()` its own instance `post()`, read from that
14
+ * registry at load
15
+ * (resources/table-posts.ts), not from a list someone maintains:
16
+ * - a table added to the schema is in that registry, so its class gets the
17
+ * guard without anyone naming it;
18
+ * - a resource class that defines `post()` keeps it: Harper calls the most
19
+ * derived `post()`, and when that override ends in `super.post()` the guard
20
+ * sees that the resource defines one and lets the call through;
21
+ * - on a resource class without a `post()` of its own, a POST that passes the
22
+ * resource's `allowCreate()` check reaches the guard, which refuses a
23
+ * non-admin caller before Harper's `create()` runs;
24
+ * - resources/table-posts.ts logs an error at load when the registry is
25
+ * missing or empty, or an entry could not be guarded (`tablePostGuardGaps`).
26
+ * test/integration/collection-post-attribution.test.ts reads every table in the
27
+ * database at runtime, sends a collection POST built from the table's declared
28
+ * attributes (plus a value a table's own validation requires) as a verified
29
+ * non-admin agent, and checks each candidate stored row of that POST (a new or
30
+ * changed row, or a row under the body id or a key the response names, found
31
+ * under the table's primary key): the table's registered owner field, if it
32
+ * has one, must be the caller. The body carries an `originatorInstanceId` and a
33
+ * `provenance` only where the table declares them, and only those declared
34
+ * fields are checked: `originatorInstanceId` must be this instance's id on a
35
+ * new row and the previous value on an existing one, and `provenance` must
36
+ * not contain the body's sentinel timestamp. The guard's non-admin refusals
37
+ * are unit-tested (test/unit/table-post-policy.test.ts,
38
+ * test/unit/table-posts.test.ts); the integration test covers an
39
+ * administrator's POST through the guard (Peer).
40
+ *
41
+ * This module has no imports, so it is unit-tested directly
42
+ * (test/unit/table-post-policy.test.ts); the dependencies it needs are passed in
43
+ * by resources/table-posts.ts.
44
+ */
45
+ /** Marks a table class whose `post()` has been guarded. */
46
+ export const TABLE_POST_GUARD = Symbol.for("flair.tablePostGuard");
47
+ /**
48
+ * Whether the resource class an instance belongs to defines its own `post()`
49
+ * below the table class (`tablePrototype`): true when any prototype between the
50
+ * instance's own and the table's carries a `post` of its own.
51
+ */
52
+ export function resourceDefinesPost(instance, tablePrototype) {
53
+ let proto = instance == null ? null : Object.getPrototypeOf(instance);
54
+ while (proto && proto !== tablePrototype) {
55
+ if (Object.prototype.hasOwnProperty.call(proto, "post"))
56
+ return true;
57
+ proto = Object.getPrototypeOf(proto);
58
+ }
59
+ return false;
60
+ }
61
+ /**
62
+ * The refusal for a collection POST on a table whose resource defines no
63
+ * `post()`; null for an administrator or a trusted internal call.
64
+ */
65
+ export function inheritedPostRefusal(table, caller) {
66
+ if (caller.kind === "internal")
67
+ return null;
68
+ if (caller.kind === "agent" && caller.isAdmin === true)
69
+ return null;
70
+ if (caller.kind === "agent") {
71
+ return Object.assign(new Error(`forbidden: a ${table} row is created through POST only by an administrator; where ${table} permits it, use PUT /${table}/<id>`), { statusCode: 403 });
72
+ }
73
+ return Object.assign(new Error(`creating a ${table} row through POST needs an administrator's credential`), { statusCode: 401 });
74
+ }
75
+ /** The refusal when the caller of such a POST cannot be resolved. */
76
+ export function unverifiedPostCallerRefusal(table) {
77
+ return Object.assign(new Error(`the caller of this ${table} POST could not be verified, so it was refused; retry`), { statusCode: 500 });
78
+ }
79
+ /**
80
+ * Give every table class in `tables` that has a `post()` its own instance
81
+ * `post()`. When the resource defines no `post()` of its own, that `post()`
82
+ * refuses a caller who is not an administrator or a trusted internal call; an
83
+ * admitted caller, and every call on a resource with its own `post()`, is
84
+ * delegated to the inherited `post()` unchanged. Idempotent. Returns the names
85
+ * of the guarded tables.
86
+ */
87
+ export function guardInheritedPosts(tables, deps) {
88
+ const guarded = [];
89
+ for (const name of Object.keys(tables ?? {})) {
90
+ const table = tables[name];
91
+ if (typeof table !== "function" || table.prototype == null)
92
+ continue;
93
+ if (Object.prototype.hasOwnProperty.call(table, TABLE_POST_GUARD)) {
94
+ guarded.push(name);
95
+ continue;
96
+ }
97
+ const tablePrototype = table.prototype;
98
+ const inherited = tablePrototype.post;
99
+ if (typeof inherited !== "function")
100
+ continue; // no POST to guard
101
+ Object.defineProperty(tablePrototype, "post", {
102
+ configurable: true,
103
+ writable: true,
104
+ enumerable: false,
105
+ value: async function post(...args) {
106
+ if (!resourceDefinesPost(this, tablePrototype)) {
107
+ let caller;
108
+ try {
109
+ caller = await deps.resolveAuth(this.getContext?.());
110
+ }
111
+ catch {
112
+ throw unverifiedPostCallerRefusal(name);
113
+ }
114
+ const refusal = inheritedPostRefusal(name, caller);
115
+ if (refusal)
116
+ throw refusal;
117
+ }
118
+ return inherited.apply(this, args);
119
+ },
120
+ });
121
+ Object.defineProperty(table, TABLE_POST_GUARD, { value: true });
122
+ guarded.push(name);
123
+ }
124
+ return guarded;
125
+ }
126
+ /**
127
+ * What an installation left unguarded, given the registry and the names
128
+ * `guardInheritedPosts` returned: a missing or empty registry, or each entry
129
+ * that is not a table class with a `post()` to guard. Empty when every entry
130
+ * is guarded.
131
+ */
132
+ export function tablePostGuardGaps(tables, guarded) {
133
+ const names = Object.keys(tables ?? {});
134
+ if (names.length === 0)
135
+ return ["the flair table registry is missing or empty"];
136
+ const done = new Set(guarded);
137
+ return names.filter((name) => !done.has(name)).map((name) => `${name} is not a table class with a post() to guard`);
138
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Installs the collection-POST guard (resources/table-post-policy.ts) on every
3
+ * table class in the flair database's table registry that has a `post()`, when
4
+ * the component loads:
5
+ * on a table whose resource defines no `post()` of its own, a collection POST
6
+ * creates a row only for an administrator or a trusted internal call. The
7
+ * tables are read from the registry, so the class of a table added to the
8
+ * schema gets the guard without being named here. An incomplete installation
9
+ * (a missing or empty registry, or an entry that could not be guarded) is
10
+ * logged as an error at load.
11
+ *
12
+ * This module deliberately exports nothing: Harper registers exported values of
13
+ * a resource module as routes.
14
+ */
15
+ import { databases } from "harper";
16
+ import { resolveAgentAuth } from "./agent-auth.js";
17
+ import { guardInheritedPosts, tablePostGuardGaps } from "./table-post-policy.js";
18
+ const registry = databases.flair;
19
+ const gaps = tablePostGuardGaps(registry, guardInheritedPosts(registry, { resolveAuth: resolveAgentAuth }));
20
+ if (gaps.length > 0) {
21
+ console.error(`[flair] the collection POST guard is incomplete: ${gaps.join("; ")}`);
22
+ }
@@ -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 + granted 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 + granted 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 {