@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,197 @@
1
+ /**
2
+ * redact-token-id.ts — the ONE pairing-token-id redactor (flair#1902).
3
+ *
4
+ * A pairing-token id IS the credential a spoke redeems, so only its 8-character
5
+ * prefix may ever reach a log line. Three sites grew their own copy of this rule
6
+ * in one day (the cleanup sweep's per-token lines, its table-level lines, and the
7
+ * rollback reporter), so the class is fixed here rather than at each site: one
8
+ * deep redactor every line that can carry a token id passes through.
9
+ *
10
+ * This is HYGIENE, not a security boundary — an operator holds admin credentials
11
+ * and can read the table directly. But a token id printed in full in a log is a
12
+ * credential handed to whoever reads the log, and the same gap reappearing at a
13
+ * new site is the failure this module exists to end.
14
+ *
15
+ * What "deep" means: a string (a message OR a string field at any depth, an array
16
+ * element, or an object KEY) has each secret replaced; numbers, booleans and null
17
+ * pass through untouched; a PLAIN object is rebuilt with redacted keys and values.
18
+ * Object keys are redacted too — a `{ "<token-id>": ... }` map is exactly as much
19
+ * a leak as one in a value. A NON-plain object — a Date, Error, Map, Set or class
20
+ * instance — passes through unchanged: rebuilding it through `Object.entries`
21
+ * would lose its message or entries, and its String form is what a caller should
22
+ * log. A cyclic value terminates: a container already on the path is returned
23
+ * as-is rather than recursed into (a log helper must never crash the sweep).
24
+ *
25
+ * Two properties the naive `split(secret).join(prefix)` gets wrong, and this
26
+ * module gets right:
27
+ *
28
+ * - LENGTH GUARD: a secret shorter than MIN_SECRET_LENGTH characters is
29
+ * replaced by "[redacted]" in full. Cutting an 11-character id to its
30
+ * 8-character prefix leaves most of the id visible, which is not a redaction.
31
+ * Empty secrets are ignored (never a replacement of "" that would splice the
32
+ * replacement between every character).
33
+ * - ONE PASS, LONGEST FIRST: the secrets are matched in a SINGLE pass over the
34
+ * original text, longest secret first. Sequential replaces let a short secret
35
+ * that is a prefix of a longer one match first and strand the longer id's
36
+ * suffix — and let a later secret match inside text a previous replacement
37
+ * just inserted. A single left-to-right scan avoids both, and it deliberately
38
+ * does NOT build a RegExp: a pattern assembled from the secrets would run on
39
+ * caller-supplied text, and a ReDoS there is a worse failure than the leak.
40
+ *
41
+ * `createTokenRedactor(secrets)` compiles the matcher once; the sweep reuses one
42
+ * per tick rather than rebuilding the replacement rules (or copying the id list)
43
+ * for every line it logs.
44
+ */
45
+ /** How many leading characters of a long secret are kept. */
46
+ export const TOKEN_ID_PREFIX_LENGTH = 8;
47
+ /**
48
+ * Below this length, a secret is replaced in full: its "prefix" would be most of
49
+ * it. Pairing-token ids are 32 characters (`randomBytes(24).toString("base64url")`),
50
+ * so this bound is an untested assumption made explicit, not a live path — the
51
+ * guard exists so a short id can never be printed whole by a prefix rule.
52
+ */
53
+ export const MIN_SECRET_LENGTH = 12;
54
+ /** What a secret too short to prefix-cut becomes. */
55
+ export const FULLY_REDACTED = "[redacted]";
56
+ /** The replacement text for one secret. */
57
+ function replacementFor(secret) {
58
+ return secret.length < MIN_SECRET_LENGTH
59
+ ? FULLY_REDACTED
60
+ : `${secret.slice(0, TOKEN_ID_PREFIX_LENGTH)}…`;
61
+ }
62
+ /** Non-empty, de-duplicated secrets paired with their replacement, longest first. */
63
+ function secretReplacements(secrets) {
64
+ const seen = new Set();
65
+ const out = [];
66
+ for (const secret of secrets) {
67
+ if (typeof secret !== "string" || secret.length === 0)
68
+ continue;
69
+ if (seen.has(secret))
70
+ continue;
71
+ seen.add(secret);
72
+ out.push([secret, replacementFor(secret)]);
73
+ }
74
+ // Longest-first: the scan takes the LONGEST secret that starts at a position,
75
+ // so where two secrets overlap the longer one wins and no suffix of it is left
76
+ // stranded by a shorter secret matching first.
77
+ out.sort((a, b) => b[0].length - a[0].length);
78
+ return out;
79
+ }
80
+ /**
81
+ * Compile `secrets` into a redactor. Build it ONCE for a batch of lines and reuse
82
+ * it — the sweep logs many lines per tick, and recompiling per line is the
83
+ * quadratic cost this avoids.
84
+ *
85
+ * The scan walks the ORIGINAL text once: at each position it takes the longest
86
+ * secret that starts there (the list is longest-first), emits that secret's
87
+ * replacement, and advances past it; otherwise it copies one character. Text a
88
+ * replacement inserts is never re-scanned, and no RegExp is built from the
89
+ * secrets (so a token id can never become a pattern).
90
+ */
91
+ export function createTokenRedactor(secrets) {
92
+ const replacements = secretReplacements(secrets);
93
+ const redactMessage = (message) => {
94
+ if (replacements.length === 0 || message.length === 0)
95
+ return message;
96
+ let out = "";
97
+ let i = 0;
98
+ while (i < message.length) {
99
+ let matched;
100
+ for (const pair of replacements) {
101
+ if (message.startsWith(pair[0], i)) {
102
+ matched = pair;
103
+ break;
104
+ }
105
+ }
106
+ if (matched) {
107
+ out += matched[1];
108
+ i += matched[0].length;
109
+ }
110
+ else {
111
+ out += message[i];
112
+ i += 1;
113
+ }
114
+ }
115
+ return out;
116
+ };
117
+ return {
118
+ redactMessage,
119
+ redactValue: (value) => (replacements.length === 0 ? value : walk(value, redactMessage)),
120
+ };
121
+ }
122
+ function walk(value, redact) {
123
+ return walkDeep(value, redact, new Map());
124
+ }
125
+ /**
126
+ * A plain object: its prototype is `Object.prototype` or null. A Date, Error,
127
+ * Map, Set or class instance is NOT a plain object, so it is not rebuilt — it
128
+ * passes through UNREDACTED, and its String form is what a caller should log
129
+ * (every call site stringifies an error before it reaches the redactor).
130
+ */
131
+ function isPlainObject(value) {
132
+ const proto = Object.getPrototypeOf(value);
133
+ return proto === Object.prototype || proto === null;
134
+ }
135
+ /**
136
+ * Rebuild `value` with every string redacted. `copies` maps each container
137
+ * already rebuilt to its REDACTED copy, and the copy is registered before its
138
+ * children are walked: a sub-object reached twice (an alias) is the same
139
+ * redacted copy both times, and a cyclic value terminates by pointing at its own
140
+ * redacted copy. Returning the original for a repeated reference would hand back
141
+ * the unredacted container — the leak flair#1905's review found.
142
+ */
143
+ function walkDeep(value, redact, copies) {
144
+ if (typeof value === "string")
145
+ return redact(value);
146
+ if (Array.isArray(value)) {
147
+ const known = copies.get(value);
148
+ if (known !== undefined)
149
+ return known;
150
+ const out = [];
151
+ copies.set(value, out);
152
+ for (const v of value)
153
+ out.push(walkDeep(v, redact, copies));
154
+ return out;
155
+ }
156
+ if (value && typeof value === "object") {
157
+ if (!isPlainObject(value))
158
+ return value;
159
+ const known = copies.get(value);
160
+ if (known !== undefined)
161
+ return known;
162
+ const out = {};
163
+ copies.set(value, out);
164
+ for (const [key, v] of Object.entries(value)) {
165
+ // Define each rebuilt key as an OWN property. A bracket assignment
166
+ // (`out[redact(key)] = …`) for the key `__proto__` would set the COPY's
167
+ // prototype instead of defining a key, dropping it and giving the copy an
168
+ // attacker-chosen prototype — reachable whenever the input came from
169
+ // JSON.parse or Object.defineProperty (flair#1907).
170
+ Object.defineProperty(out, redact(key), {
171
+ value: walkDeep(v, redact, copies),
172
+ enumerable: true,
173
+ writable: true,
174
+ configurable: true,
175
+ });
176
+ }
177
+ return out;
178
+ }
179
+ // Numbers, booleans, null, undefined, functions, symbols: untouched.
180
+ return value;
181
+ }
182
+ /**
183
+ * A string with every secret replaced by its prefix (or `[redacted]` when the
184
+ * secret is too short to cut). The string-only convenience over the same
185
+ * implementation the deep redactor uses.
186
+ */
187
+ export function redactTokenMessage(message, secrets) {
188
+ return createTokenRedactor(secrets).redactMessage(message);
189
+ }
190
+ /**
191
+ * `value` with every secret replaced in every string at any depth — a message, a
192
+ * string field, an array element, and an object KEY — rebuilt so keys and values
193
+ * are both redacted. Non-string scalars pass through untouched.
194
+ */
195
+ export function redactTokenIds(value, secrets) {
196
+ return createTokenRedactor(secrets).redactValue(value);
197
+ }
@@ -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`. |
@@ -197,21 +226,22 @@ The remedy is `flair upgrade` (the adapter), not a server upgrade alone.
197
226
  | Method | Path | Auth | Notes |
198
227
  |--------|------|------|-------|
199
228
  | GET | `/FederationInstance` | Admin Basic | Local instance identity (CLI / admin). Peers do not call this during pair. |
200
- | POST | `/FederationPair` | Pairing token + body-sig | Public at the Harper role gate. Handler validates token, signature, anti-replay. Response includes `instance {id, publicKey}` when this hub has an Instance row; `instance` is null if it does not (flair#839). The spoke CLI must not store an empty hub key (flair#822). Fabric uses the bootstrap-user triple from `flair federation token`. |
229
+ | POST | `/FederationPair` | Pairing token + body-sig | Public at the Harper role gate. Handler validates token, signature, anti-replay. Response includes `instance {id, publicKey}` when this hub has an Instance row; `instance` is null if it does not (flair#839). With several rows it answers `409 multiple_instance_rows` before the token is consumed, naming no row (the hub's log names them; flair#1883). The spoke CLI must not store an empty hub key (flair#822). Fabric uses the bootstrap-user triple from `flair federation token`. |
201
230
  | POST | `/FederationSync` | Peer body-sig | Public at the role gate. Merge Memory / Soul / Agent / Relationship (and classifier-ready Message). Originator + per-record signature checks. |
202
231
  | GET | `/FederationPeers` | Admin Basic | Known peers. |
203
232
  | GET / write | `/Instance` | Read: Ed25519. Write: admin | Instance row (`flair_…` id, role hub/spoke). |
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
package/docs/auth.md CHANGED
@@ -9,12 +9,12 @@ Different surfaces authenticate differently. The model in one place:
9
9
 
10
10
  | Surface | Auth | Scope | Notes |
11
11
  |---------|------|-------|-------|
12
- | **CLI / SDK clients** (`flair`, `flair-client`) | **Ed25519 per-agent** | Own writes; org-wide non-private reads | Default, recommended. Signs every request; an agent can never write as another, and reads are scoped to its own memories (any visibility) plus every other agent's **non-private** memories on the instance. |
13
- | **MCP server** (`@tpsdev-ai/flair-mcp`) | **Ed25519 per-agent** | Own writes; org-wide non-private reads | Same per-agent identity as the CLI — key auto-resolved from `~/.flair/keys/<agent>.key`. |
14
- | **OpenClaw / pi / Hermes plugins** | **Ed25519 per-agent** | Own writes; org-wide non-private reads | Same secure path; auto-detect agent identity. |
12
+ | **CLI / SDK clients** (`flair`, `flair-client`) | Ed25519 agent keys; administrator Basic on supported paths | Ordinary signed agents: own writes; own and org-wide non-private reads | Administrator agent roles and Basic credentials have broader authority. |
13
+ | **MCP server** (`@tpsdev-ai/flair-mcp`) | Ed25519 agent key; configured administrator Basic fallback | Ordinary signed agents: own writes; own and org-wide non-private reads | The key is auto-resolved from `~/.flair/keys/<agent>.key`; Basic is used when no key resolves and administrator credentials are configured. |
14
+ | **OpenClaw / pi / Hermes plugins** | Ed25519 agent keys; Pi can use configured administrator Basic fallback | Ordinary signed agents: own writes; own and org-wide non-private reads | OpenClaw identity comes from host context; Pi requires `FLAIR_AGENT_ID`; Hermes defaults to `hermes`. |
15
15
  | **`n8n-nodes-flair`** | **Harper admin-password Basic auth** | ⚠️ **Whole instance, read + write, including `private`** | The admin credential bypasses agent scoping entirely — every workflow gets read/write on the *entire* memory store, including other agents' `private`-marked memories, not just the org-wide non-private pool an Ed25519 identity would see. |
16
16
 
17
- **The default, secure path is Ed25519 per-agent** (see below): each agent holds its own key and signs every request. That guarantees **write isolation** — no agent can write as another — and identity-verified reads. It does **not** mean cross-agent reads are refused: within one Flair instance (one org), any verified agent can read any other agent's memory unless that memory is explicitly marked `visibility: private` (owner-only). The hard access boundary is the **federation edge** (a separate Flair instance / org), not reads within an instance. See [SECURITY.md](../SECURITY.md) for the full model. Use Ed25519 per-agent everywhere you can regardless — it's still what makes writes and identity trustworthy.
17
+ **The default, secure path is Ed25519 per-agent** (see below): each agent holds its own key and signs every request. For ordinary signed agents, this enforces write ownership: they can write only their own records and read their own plus other agents' non-private records. Administrator credentials and administrator agent roles have broader authority, including access to private records. The hard access boundary is the **federation edge** (a separate Flair instance / org), not reads within an instance. See [SECURITY.md](../SECURITY.md) for the full model. Use Ed25519 per-agent everywhere you can regardless — it's still what makes writes and identity trustworthy.
18
18
 
19
19
  ### Known limitation — n8n uses admin-password Basic auth
20
20
 
@@ -49,7 +49,7 @@ never an existence signal. The adapter write-up is
49
49
 
50
50
  Flair has no `mode`/`shape` config setting — the shape you get is emergent from *how you provision principals*, not something you declare:
51
51
 
52
- - **Personal (the default).** `flair init` mints ONE agent identity and wires that same `FLAIR_AGENT_ID` into every MCP client it configures (Claude Code, Codex, Gemini, Cursor). One human driving several AI clients ends up with one canonical principal and one Ed25519 keypair — all clients share ownership of the same memory. This is intentional, not a limitation: all clients see each other's private rows (one human's memory, one view), a fact re-asserted from two different clients dedups to one memory, and usage counting treats the principal as one contributor.
52
+ - **Personal.** `flair init --agent <id>` creates (or reuses) ONE agent identity and wires that same `FLAIR_AGENT_ID` into every MCP client it configures (Claude Code, Codex, Gemini, Cursor). One human driving several AI clients ends up with one canonical principal and one Ed25519 keypair — all clients share ownership of the same memory. This is intentional, not a limitation: all clients see each other's private rows (one human's memory, one view). Writes with fresh IDs create separate records even when the server reports a dedup match; writes that reuse an existing ID update that record. Usage counting treats the shared principal as one contributor.
53
53
  - **Org (multiple real agents).** `flair agent add <id>` mints a distinct principal — its own keypair, its own ownership boundary — for each real agent that should be a separate identity. Wire each principal's own `FLAIR_AGENT_ID` into its own client(s).
54
54
 
55
55
  Nothing in flair validates which shape you're in; a personal install that later grows into an org just runs `flair agent add` for the new distinct identities it needs.