@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
@@ -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).
@@ -47,13 +52,37 @@ the schema section so the catalog is complete.
47
52
  | **Public** | none | Discovery, health, OAuth well-known. `GET /Presence` is public only when the instance opts in to a public roster (`PRESENCE_PUBLIC_ROSTER=true`) — by default it needs a verified reader. See [Presence for API consumers](#presence-for-api-consumers). |
48
53
  | **Ed25519 agent** | `TPS-Ed25519` header | Default agent path. Writes as self only. Reads follow the resource's read-scope (below). |
49
54
  | **Admin Basic** | Harper `HDB_ADMIN_PASSWORD` / `FLAIR_ADMIN_PASSWORD` | Whole-instance operator. Bypasses agent scoping, including `private` memory. Used by the web admin and `n8n-nodes-flair`. |
50
- | **Operator / internal** | Admin Basic, or a deliberate `internalContext()` call inside the process | Soul mutations and `AgentSeed`. Agent Ed25519 keys — including admin-agent keys — cannot author Soul. |
55
+ | **Operator / internal** | Admin Basic, or a deliberate `internalContext()` call inside the process | Soul mutations, `OrgSkillAssignment` writes and `AgentSeed`. Agent Ed25519 keys — including admin-agent keys — cannot author Soul. |
51
56
  | **Federation body-sig** | Ed25519 over the request body + timestamp/nonce; pairing uses a one-time token | `/FederationPair`, `/FederationSync`. Harper role gate is open; the handler is the auth boundary. |
52
57
  | **OAuth bearer** | Access token from Flair's AS or `@harperfast/oauth` | `/mcp` only, and only when `FLAIR_MCP_OAUTH=true` plus a public issuer. Off by default (path 404s). |
53
58
 
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`:
@@ -62,7 +91,7 @@ From `RECORD_TYPES` in `resources/record-types.ts`:
62
91
  |-------|---------|--------|
63
92
  | **open-within-org** | Own rows (any visibility) plus every other agent's non-private rows | Memory |
64
93
  | **owner-only** | Only the owning agent (plus admin / internal) | Relationship, WorkspaceState, Asset, MemoryCandidate |
65
- | **none** | Any verified agent reads every row; no visibility field | Soul, OrgEvent |
94
+ | **none** | Any verified agent reads every row; no visibility field | Soul, OrgEvent, OrgSkillAssignment |
66
95
 
67
96
  These three scopes are **not** in `RECORD_TYPES`. Each is hand-implemented on its
68
97
  own resource:
@@ -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. |
@@ -142,6 +171,8 @@ the same identity plane.
142
171
  | POST | `/MemoryReflect` | Ed25519 | REM distill → MemoryCandidate. |
143
172
  | POST | `/MemoryDedupStats` | Admin Basic | Dedup diagnostics. Fleet-wide sweep; `allowCreate` is `allowAdmin`. |
144
173
  | POST | `/SkillScan` | Ed25519 | Skill-tag scan on Memory writes. |
174
+ | GET | `/OrgSkillAssignment`, `/OrgSkillAssignment/<id>` | Ed25519 | Any verified agent. Org-scope skill assignments; see the `skills` paragraph in [docs/mcp-clients.md](mcp-clients.md). Not federated. |
175
+ | POST / PUT / PATCH / DELETE | `/OrgSkillAssignment/` (POST), `/OrgSkillAssignment/<id>` (PUT / PATCH / DELETE) | **Operator / internal** | Not Ed25519, admin-agent keys included. Each accepted write appends an `OrgSkillAssignmentHistory` row. |
145
176
 
146
177
  Skill-tagged Memory rows embed from `trigger` (the recall signal), not
147
178
  `content`. MCP tools: `skill_store`, `skill_search`, `skill_get`.
@@ -183,7 +214,7 @@ The remedy is `flair upgrade` (the adapter), not a server upgrade alone.
183
214
 
184
215
  | Method | Path | Auth | Read / write |
185
216
  |--------|------|------|--------------|
186
- | GET / PUT | `/Relationship` | Ed25519 | Owner-only. Upsert via PUT; provenance stamped server-side. |
217
+ | 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
218
  | GET / POST / PUT | `/WorkspaceState` | Ed25519 | Owner-only. POST stamps `agentId`; PUT rejects a mismatch. |
188
219
  | GET | `/WorkspaceLatest` | Ed25519 | Latest workspace row for the caller. |
189
220
  | GET / POST / PUT | `/OrgEvent` | Ed25519 | Any verified agent reads every event. Writes stamp `authorId`. |
@@ -204,14 +235,15 @@ The remedy is `flair upgrade` (the adapter), not a server upgrade alone.
204
235
  | GET / write | `/Peer` | Admin Basic | Pinned peer keys and sync cursors. |
205
236
  | GET / write | `/PairingToken` | Admin Basic | One-time tokens; default TTL 1 hour. |
206
237
 
207
- `Nonce` and `SyncLog` are **not** `@export` — no agent REST. Nonce is the
208
- anti-replay store; SyncLog is the operator audit trail.
238
+ `ReplayNonce` and `SyncLog` are **not** `@export` — no agent REST.
239
+ ReplayNonce is the anti-replay store (shared with agent auth); SyncLog is the
240
+ operator audit trail.
209
241
 
210
242
  ### Messaging (Flair Relay)
211
243
 
212
244
  | Method | Path | Auth | Notes |
213
245
  |--------|------|------|-------|
214
- | GET / POST | `/Message` | Ed25519 | POST sends (signed envelope). GET is party-scoped (`from` or `to`). Direct PUT is admin/internal. |
246
+ | 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
247
  | GET | `/MessageInbox` | Ed25519 | Inbox for the caller. |
216
248
  | POST | `/MessageAck` | Ed25519 | Consume a delivered message. |
217
249
  | GET | `/MessageDeadLetter` | Ed25519 | Visible failures for the sender (`deadline`, `inbox_full`, …). |
@@ -349,11 +381,45 @@ A peer can therefore show `presenceStatus: "offline"`, `activity: "idle"`, `last
349
381
  | `subject` / `summary` | String | Compression: subject → summary → content |
350
382
  | `validFrom` / `validTo` | String | Temporal validity; expired rows drop out of search |
351
383
  | `_safetyFlags` | [String] | Content-safety scan |
352
- | `provenance` | String | Server JSON `{ v, verified, claimed? }` |
353
- | `originatorInstanceId` | String | Write-time instance id; preserved across sync |
384
+ | `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. |
385
+ | `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
386
  | `metadata` | String | Client JSON blob; opaque to the server |
355
387
  | `entities` | [String] | Attention-plane `type:value` strings |
356
388
 
389
+ > 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`.
390
+
391
+ #### Memory host pointer (`MemoryHostSource`, #1940 A1'-A5)
392
+
393
+ 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.**
394
+
395
+ `MemoryHostSource` fields:
396
+
397
+ | Field | Type | Notes |
398
+ |-------|------|-------|
399
+ | `memoryId` | ID (primary key) | The `Memory.id` this pointer belongs to. |
400
+ | `hostSource` | String | The canonical pointer JSON (fixed key order, NFC). |
401
+ | `scopeAtWrite` | String | The record's visibility at write when the write opted in (`hostSourceScope: "record"`); `null` = author-only. |
402
+ | `authorId` | String | The authenticated principal, server-stamped — never the body. |
403
+ | `memoryInstanceToken` | String | The Memory row’s server-stamped `instanceToken` at pointer-write time; the join binds on it (see below). |
404
+ | `receivedAt` | String | Server receipt time. |
405
+
406
+ 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.
407
+
408
+ **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.
409
+
410
+ - **A1'** — the pointer is its own table; the Memory schema declares no `hostSource`. Additive with no data migration.
411
+ - **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.
412
+ - **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.
413
+ - **A5** — the pointer is NOT inside `provenance`; `provenance` stays never-client-writable.
414
+
415
+ **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.
416
+
417
+ **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.
418
+
419
+ **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.
420
+
421
+ 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).
422
+
357
423
  ### Soul
358
424
 
359
425
  | Field | Type | Notes |
@@ -366,7 +432,7 @@ A peer can therefore show `presenceStatus: "offline"`, `activity: "idle"`, `last
366
432
  | `provenance` | String | Operator/internal author + `sourceClass` |
367
433
  | `durability` | String | Default `permanent` |
368
434
  | `createdAt` / `updatedAt` | String | |
369
- | `originatorInstanceId` | String | Federation origin |
435
+ | `originatorInstanceId` | String | Server-stamped write-time instance id; not client-writable through a resource write |
370
436
 
371
437
  ### Agent (Principal)
372
438
 
@@ -387,7 +453,7 @@ agents.
387
453
  | `runtime` / `runtimeEndpoint` | String | How to reach the principal |
388
454
  | `subjects` | [String] | Soul-level interests |
389
455
  | `createdAt` / `updatedAt` | String | |
390
- | `originatorInstanceId` | String | Federation origin |
456
+ | `originatorInstanceId` | String | Server-stamped write-time instance id; not client-writable through a resource write |
391
457
 
392
458
  Related: **Credential** (`principalId`, `kind` webauthn / bearer-token /
393
459
  ed25519 / idp) and **Integration** (legacy platform connection).
@@ -399,7 +465,7 @@ ed25519 / idp) and **Integration** (legacy platform connection).
399
465
  | **Instance** | yes | One row per Flair instance (`id`, `publicKey`, `role` hub/spoke, `fabricEndpoint`, `status`) |
400
466
  | **PairingToken** | yes | One-time token (`expiresAt`, `consumedBy`) |
401
467
  | **Peer** | yes | Pinned peer (`publicKey`, `endpoint`, `status`, `lastSyncAt` / `lastMergeAt`, `lastSyncCursor`, `relayOnly`) |
402
- | **Nonce** | no | Body-sig anti-replay; PK is the nonce string |
468
+ | **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
469
  | **SyncLog** | no | Per-sync audit (`peerId`, `direction`, counts, `skippedReasons`, `status`) |
404
470
 
405
471
  ### Other tables
@@ -412,6 +478,8 @@ ed25519 / idp) and **Integration** (legacy platform connection).
412
478
  | **MemoryHitStat** | memory.graphql | no | Search-hit ledger (`retrievalCount`, `lastRetrieved`); overlaid onto Memory reads |
413
479
  | **MemoryCandidate** | memory.graphql | yes | REM draft (`claim`, `status`, `scopeTag`, visibility ruling) |
414
480
  | **Asset** | memory.graphql | yes | Blob (`contentType`, `data`) owned by `agentId`, linked by `memoryId` |
481
+ | **OrgSkillAssignment** | memory.graphql | yes | Org-scope skill assignment (`skillName`, `skillRef`, `priority`, server-stamped `writer` / `sourceClass`) |
482
+ | **OrgSkillAssignmentHistory** | memory.graphql | no | One row per accepted OrgSkillAssignment resource write (`assignmentId`, `op`, `actor`, `sourceClass`, `previousHash`) |
415
483
  | **WorkspaceState** | workspace.graphql | yes | Current work (`ref`, `provider`, `phase`, `entities`) |
416
484
  | **OrgEvent** | event.graphql | yes | Org-visible event (`authorId`, `kind`, `summary`, `entities`) |
417
485
  | **AgentReadPosition** | agent.graphql | no | Per-agent watermark (`agentId`, `stream`, `position`). HTTP via `/AgentReadPosition`, not raw-table REST. |
package/docs/auth.md CHANGED
@@ -66,6 +66,8 @@ The native `/mcp` OAuth surface (see below) doesn't need any client-side wiring
66
66
 
67
67
  Flair includes a built-in OAuth 2.1 authorization server for client integrations (e.g., Claude connecting to Flair as an MCP server).
68
68
 
69
+ The native `/mcp` endpoint is guarded by the `@harperfast/oauth` authorization server instead; who can connect through it, and how to revoke that access, is in [access-control.md](access-control.md).
70
+
69
71
  ### Dynamic Client Registration
70
72
 
71
73
  **Registration is off by default.** `POST /OAuthRegister` answers `403
@@ -232,6 +234,8 @@ For organizations using an Identity Provider (IdP), XAA lets the IdP control who
232
234
  3. Client sends the ID token to Flair's token endpoint using the `jwt-bearer` grant type
233
235
  4. Flair validates the JWT signature, checks issuer/domain, maps to a Principal, and issues a scoped access token
234
236
 
237
+ A `jti` claim, when present, must be a nonempty string, and the assertion must then carry an `exp` no more than 24 hours (plus 30 seconds of clock skew) ahead. Flair records the `jti` before it issues tokens, and refuses the assertion if it is presented to this Harper instance again.
238
+
235
239
  ```
236
240
  POST /OAuthToken
237
241
  Content-Type: application/x-www-form-urlencoded
@@ -84,6 +84,66 @@ Copy this into your project's `CLAUDE.md` (or `.claude/settings.md`, `AGENTS.md`
84
84
 
85
85
  This is a prompt-driven CLI setup: Claude must choose to run these commands. For MCP tools and automatic startup recall, run `flair init --agent my-project --client claude-code`, restart Claude Code, and verify the hook with `flair hook status --harness claude-code`; these prompt instructions do not guarantee automatic capture.
86
86
 
87
+ ## Hooks
88
+
89
+ `@tpsdev-ai/flair-mcp` ships four Claude Code hooks. Each is a separate binary and each is optional. Each exits 0 on every failure it handles, but a hook can still delay the session start, the prompt or the compaction it runs for; the time budgets and limits of prompt recall and of the PreCompact hook are described below.
90
+
91
+ | Hook | Claude Code event | What it does | Install |
92
+ |---|---|---|---|
93
+ | `flair-session-start` | `SessionStart` | Loads bootstrap context (soul plus relevant memories) when a session opens. | `flair hook install` ([details](mcp-clients.md#auto-recall-on-session-start-optional-hook)) |
94
+ | `flair-continuity-capture` | `PostToolUse` and `Stop` | Journals the agent's working state into the ephemeral memory tier, so the next session start can point at it with a one-line resume hint. | `flair hook install --continuity` |
95
+ | `flair-prompt-recall` | `UserPromptSubmit` | Searches memory with each prompt and adds the relevant memories as context before the model answers. | By hand, below |
96
+ | `flair-precompact` | `PreCompact` | Saves a bounded continuity record just before a compaction, for `flair-session-start` to show first afterwards. | By hand, [below](#continuity-across-compaction-flair-precompact-optional) |
97
+
98
+ ### Per-prompt recall (`flair-prompt-recall`)
99
+
100
+ Session-start recall runs once. Later in the session a prompt can bring up something the agent's memory already covers, such as a user's direction on a named technique or an earlier decision, and unless something searches at that moment the agent answers without it. `flair-prompt-recall` searches on every prompt:
101
+
102
+ 1. It builds a search query from the prompt, with markup, URLs and noise such as long ids stripped, bounded to 500 characters.
103
+ 2. It runs the same hybrid search as the MCP `memory_search` tool, signed with the agent's own Ed25519 key, so the results are limited to what that agent may read.
104
+ 3. It adds the hits whose score meets a relevance threshold (at most 4 by default), each with its id, date, score and a snippet, under a header that frames them as a signal, not an instruction, and tells the model to read the full memory before acting on it. The whole block is at most 2,000 characters. A memory that Flair's content scan flagged as possible prompt injection is shown with a fixed warning line ahead of its quoted text; cutting the text to fit never cuts the warning, so such a memory appears with its whole warning or not at all.
105
+
106
+ It can delay a prompt until its time budget runs out, and a response that has fully arrived within the budget can take longer to process (see below). It skips two kinds of prompt: background task notifications, and prompts too short to search once cleaned ("ok, thanks"). Every other prompt is searched, question or not. It exits 0 on every failure it handles. When Flair is unreachable, slow or refuses the request, it adds no memories, only one line saying recall was unavailable for that prompt.
107
+
108
+ The time budget (3 seconds by default) runs from the moment the hook process starts: reading the prompt, reading the config file and the search all count against it. When it runs out during asynchronous work (waiting for the prompt on stdin, reading the config file, connecting to Flair or downloading its response), the hook prints the one "unavailable" line and exits 0 at once. The prompt payload is read up to 1 MiB (a larger one is not searched), and the config file is read only if it is a regular file of at most 256 KiB. Once a response has arrived in full, the Flair client parses it and converts every result in it before returning, synchronously; the deadline cannot interrupt that work, and there is no cap on the size of a response that arrives within the budget. After the client returns, the hook's own processing looks at no more than the requested number of results and the first 4,096 characters of each memory. What happens before the process starts is outside the budget: the launcher and node's own start-up.
109
+
110
+ `flair hook install` does not write this hook, so wire it by hand. The hook runs on every prompt, so its launcher's start-up is added to every turn. Install the pinned package once into a directory of its own, and point the hook at its binary:
111
+
112
+ ```bash
113
+ npm install --prefix ~/.flair-hooks @tpsdev-ai/flair-mcp@<version>
114
+ ```
115
+
116
+ Then add the hook to `~/.claude/settings.json`:
117
+
118
+ ```json
119
+ {
120
+ "hooks": {
121
+ "UserPromptSubmit": [
122
+ {
123
+ "hooks": [
124
+ {
125
+ "type": "command",
126
+ "command": "sh -c 'out=$(FLAIR_AGENT_ID=my-project \"$HOME/.flair-hooks/node_modules/.bin/flair-prompt-recall\" 2>/dev/null) && printf %s \"$out\" || true'"
127
+ }
128
+ ]
129
+ }
130
+ ]
131
+ }
132
+ }
133
+ ```
134
+
135
+ Swap `my-project` for your agent ID and `<version>` for `flair --version`. The binary runs with the `node` found on the hook's `PATH`, which must be Node 22 or later. The `sh -c ... || true` wrapper is the same one the SessionStart hook uses: if the command cannot run at all, the prompt goes through with no output. Nothing in the CLI rewrites this entry or that directory, so re-run the `npm install` with the new version after an upgrade.
136
+
137
+ The same `npx -y -p @tpsdev-ai/flair-mcp@<version> flair-prompt-recall` invocation the SessionStart hook uses also works in place of the binary path, at a cost: npx resolves the package before the hook process starts, on every prompt, outside the hook's budget. That adds npm's own start-up to every turn even when the package is cached, and a download when the pinned version is not in npx's cache.
138
+
139
+ | Setting | Environment variable | `~/.flair/config.yaml` key | Default |
140
+ |---|---|---|---|
141
+ | Relevance threshold, 0 to 1, on the search's absolute score | `FLAIR_PROMPT_RECALL_MIN_SCORE` | `promptRecallMinScore` | `0.62` |
142
+ | Most memories added per prompt, 1 to 10 | `FLAIR_PROMPT_RECALL_MAX_HITS` | `promptRecallMaxHits` | `4` |
143
+ | Time budget in milliseconds, from the hook's start, 250 to 15000 | `FLAIR_PROMPT_RECALL_TIMEOUT_MS` | `promptRecallTimeoutMs` | `3000` |
144
+
145
+ The environment wins over the config file, where the keys are top-level entries; a value that is missing or out of range falls through to the next source. Until the config file has been read, the hook's deadline uses the environment's budget or the default; a budget set in the config file applies from then on, still measured from the start. The hook reads `FLAIR_AGENT_ID`, `FLAIR_URL` and `FLAIR_KEY_PATH` like the other hooks. It never uses `FLAIR_ADMIN_USER` or `FLAIR_ADMIN_PASSWORD`: without an agent key the request goes out unsigned, Flair refuses it, and the prompt gets the one "unavailable" line.
146
+
87
147
  ## Multiple Projects
88
148
 
89
149
  Create a separate agent per project:
@@ -131,6 +191,78 @@ Then the CLAUDE.md simplifies to:
131
191
 
132
192
  Use `flair bootstrap` when MCP is not wired.
133
193
 
194
+ ## Continuity across compaction (`flair-precompact`, optional)
195
+
196
+ When Claude Code compacts a conversation, it replaces the history with a summary, and whatever the summary leaves out is gone from the agent's context: a rule the user gave an hour ago, the open task list, the work in flight. `flair-precompact` is a `PreCompact` hook that saves one bounded record just before that happens (when the end of the transcript holds something to record and the write succeeds), and `flair-session-start` can show the saved record the local marker file names first, when Flair returns it as an eligible live row: when the session continues after the compaction, or when the next session starts after a restart and the marker still names the previous session (see the limits below).
197
+
198
+ It needs `flair-session-start` installed (`flair hook install`): that hook creates the per-session continuity state the record belongs to, and it is the one that shows the record, when the marker matches and Flair returns an eligible live row. `flair hook install` does not write the PreCompact entry, so add it to `~/.claude/settings.json` by hand:
199
+
200
+ ```json
201
+ {
202
+ "hooks": {
203
+ "PreCompact": [
204
+ {
205
+ "hooks": [
206
+ {
207
+ "type": "command",
208
+ "command": "sh -c 'out=$(FLAIR_AGENT_ID=my-project npx -y -p @tpsdev-ai/flair-mcp@<version> flair-precompact 2>/dev/null) && printf %s \"$out\" || true'",
209
+ "timeout": 30
210
+ }
211
+ ]
212
+ }
213
+ ]
214
+ }
215
+ }
216
+ ```
217
+
218
+ Swap `my-project` for your agent ID and `<version>` for `flair --version`. With no `matcher`, the hook runs for both `/compact` (`manual`) and automatic (`auto`) compaction. A PreCompact hook that exits 2 blocks compaction; this command exits 0 whenever it runs to completion (the `|| true` covers a launcher that fails before the hook runs), and `timeout` bounds the launcher, whose start-up happens before the hook's own budget begins.
219
+
220
+ What the record holds: text copied from the end of the transcript (no model call, no summary), under fixed section headings, with a status label on each task (taken from the transcript only when it looks like one, at most 20 lowercase letters and underscores, and is not credential-shaped; else `open`) and a tool label (`bash:`, `write:`, `edit:` or `notebook-edit:`) on each in-flight line:
221
+
222
+ - **Standing instructions**: sentences from the turns the transcript labels as user turns (once the harness markup described below is removed) that start with a rule-giving phrase (don't, do not, never, always, stop, avoid, make sure, remember to, from now on, going forward) or contain always, never, from now on, going forward or in (the) future. Extracted sentences that end in `?` are skipped. At most 6, the newest, 200 characters each.
223
+ - **Open tasks**: the task tools' list (`TaskCreate`/`TaskUpdate`, and `TodoWrite` when a session has it enabled), minus completed and deleted tasks. At most 8.
224
+ - **In-flight work**: the last 5 file edits and shell commands, one line each (a repeated one included), recorded the way `flair-continuity-capture` records them: a file's path, a shell command's description, never the command itself.
225
+ - **The last assistant message**: its text blocks joined in order, cut to 300 characters.
226
+
227
+ A section with nothing in it is left out, and when nothing at all was found no record is written. The whole record is at most 2,000 characters. The hook reads at most the last 1 MiB of the transcript and keeps up to the last 2,000 nonblank lines of it. From tool results it reads only two identifiers, to keep the task list straight: the id `TaskCreate` assigned, and which tool call a result answers. It never copies result content, thinking or subagent turns into the record. Of the messages the harness writes into the transcript, it skips user turns that carry a marker it recognizes (`<task-notification>`; a slash command's `<command-name>`, `<command-message>` or `<command-args>`; `<local-command-…>` output), meta entries and compaction summaries, and it drops system-reminder blocks, all before it redacts the text that is left; a harness message with none of these markers is treated as a user turn, since the hook cannot tell it from your own words.
228
+
229
+ Before the record's content is stored, strings in it that match these patterns are replaced with `[redacted]` (a task status label that redaction would change is shown as `open` instead): private key blocks, `user:password@` in URLs, Authorization-style values (everything after an `Authorization:` or `Proxy-Authorization:` label in any case, or after the word `Bearer` in any case or `Basic` capitalized or in capitals, through the end of that line, whatever its characters, where a line ends at a line feed, carriage return, vertical tab, form feed, U+0085, U+2028 or U+2029, the same breaks the displayed record is split on, so the line after the value is kept; this also cuts short a line of prose such as "use Bearer tokens here", while the lower-case word "basic" is left alone), `name=value` and `name: value` pairs whose name contains password, secret, token, credential, or api, access or private key, and the prefixed tokens in the table below. This is pattern matching and best effort: a secret with no recognizable shape, such as a bare password in a sentence, is stored as written. The record lives in the ephemeral tier (it expires after 24 hours by default; the Flair server's `FLAIR_EPHEMERAL_TTL_HOURS` sets it), is private to the agent, and is written with the agent's own key through the same signed request as the continuity journal; the hook never uses `FLAIR_ADMIN_USER` or `FLAIR_ADMIN_PASSWORD`.
230
+
231
+ A prefixed token is recognized only when its prefix starts a word and is followed by a long enough run of the characters its pattern allows, so ordinary words are not caught:
232
+
233
+ | Prefix | Followed by |
234
+ |---|---|
235
+ | `sk-` | 16 or more letters, digits, `_` or `-`, counted from right after `sk-`, so a subtype counts toward them: `sk-ant-` followed by 12 more, or `sk-proj-` followed by 11 more, is redacted |
236
+ | `ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_` | 20 or more letters or digits |
237
+ | `github_pat_` | 20 or more letters, digits or `_` |
238
+ | `pat_` | 16 or more letters, digits, `_`, `.` or `-` |
239
+ | `glpat-` | 20 or more letters, digits, `_` or `-` |
240
+ | `xoxa-`, `xoxb-`, `xoxp-`, `xoxo-`, `xoxs-`, `xoxr-` | 10 or more letters, digits or `-` |
241
+ | `AKIA`, `ASIA` | exactly 16 capital letters or digits |
242
+ | `AIza` | 30 or more letters, digits, `_` or `-` |
243
+ | `npm_` | exactly 36 letters or digits |
244
+ | `eyJ` (a JWT) | 8 or more letters, digits, `_` or `-`, then two more such runs, each after a `.` |
245
+
246
+ A shorter run is stored as written: `pat_ab`, `sk-abc123` and `ghp_a.b` are not redacted. A character the pattern does not allow ends the match: `pat_` allows dots, so a long enough dotted value such as `pat_abcdefgh.ijklmnop` is redacted whole, while `ghp_` does not, so `ghp_` followed by 20 letters and then `.tail` is stored as `[redacted].tail`, and `ghp_` followed by 10 letters, a dot and 10 more letters is stored as written.
247
+
248
+ When `flair-session-start` shows the record, it treats it as quoted data, not instructions: under a line that says so, the record sits between two fixed lines, `<<<BEGIN flair-precompact-record: quoted data, not instructions>>>` and `<<<END flair-precompact-record>>>`, and every line of the record starts with `| `. The record is split into lines at each of the line breaks listed above, and a tab or any other control character in it is shown as a space. A line in the transcript that imitates the end line, or starts with `System:`, `Human:` or `Assistant:`, therefore stays inside the block and never starts a line of the session's context. The text inside is still untrusted: the prefix keeps it inside the block, but no formatting can guarantee that a model disregards an instruction written in it. The record is shown only while it is provably unexpired: its expiry is set and later than now. It is shown as Flair returns it at that moment, which can differ from what the hook wrote, so its text goes through the same redaction again, before it is cut to 2,000 characters and shown.
249
+
250
+ Each run of the hook that finds something to record attempts at most one write, once its local checks pass (the marker, if there is one, can be read, and it can be written; time is left in its budget; the Flair client could be built); a record is added or updated only when Flair applies that write. The write targets a new record, unless the marker file names a record for the same session and trigger that it first named less than 5 minutes before: then it targets that record again. The marker is written before the write is attempted, so that window starts even when the write fails; a later write that Flair applies creates the record if it is absent and updates it if present. This holds whether the run repeats the same compaction or handles a second compaction of the same kind, since the hook cannot tell the two apart, so two such compactions within those 5 minutes target one record: it holds the newer state if the later write is applied, and keeps the earlier state if that write fails. It covers runs that come one after another; see the limits below. The record's id is kept in `~/.flair/session/<agent>.precompact.json`, which holds ids and a timestamp, never record content.
251
+
252
+ Once it has started, the hook does not block compaction: every path it handles exits 0. Its time budget (`FLAIR_PRECOMPACT_TIMEOUT_MS`, default 5000 ms, 250 to 15000) starts before it reads its input. When it passes, the hook stops waiting on its asynchronous work (whatever is still pending), prints its timeout warning when `FLAIR_AGENT_ID` is set (without it, nothing), and exits 0 once that output drains, waiting at most one more second. It cannot interrupt synchronous work, and one such step is not the hook's own: the Flair client reads the agent's key file synchronously. The `timeout` in the hook entry, Claude Code's own limit for the command, is the outer bound. The hook reads its own files asynchronously. Of the transcript it reads only the end, within the limits above. The session's continuity state file and the marker file are a few hundred bytes when Flair wrote them, and the hook checks their size before reading either: one larger than 16 KiB, or anything at those paths that is not a regular file, is refused unread, with a warning naming it, and one that grows past 16 KiB while it is read is refused after at most 16 KiB and 1 byte. When Flair is unreachable, slow or refuses the write, or the transcript or the hook's own files cannot be read, Claude Code shows one short warning naming the reason, and compaction goes ahead either way. When a write is not confirmed, the warning says the save did not finish in time (after a timeout) or could not be confirmed (after any other error), and that the record may be missing: Flair can still finish a write the hook stopped waiting for, or may already have applied one whose answer could not be read. A warning that names the state file or the marker shows its path with these changes, each only where it applies: a path inside your home directory (`HOME`, else the system's) starts with `~` (a home directory of `/` collapses nothing), each control character is shown as `?`, strings that match the credential patterns are redacted, and a path longer than 200 characters is cut. A path outside your home directory that none of these touch is shown as it is.
253
+
254
+ Limits worth knowing:
255
+
256
+ - The instruction heuristic is simple. It misses a rule phrased any other way ("I'd rather you ask first", other languages), and it can pick up a sentence that only mentions the words ("I never said that").
257
+ - Claude Code writes the transcript asynchronously, so the newest messages may not be in it yet when the hook runs.
258
+ - Only the end of the transcript is read: a task created before that part has no name there and is left out, and an instruction given before it is not seen.
259
+ - The transcript's format is Claude Code's own, not a documented interface; a field the hook does not recognize is skipped, never guessed.
260
+ - After a restart, a record is shown only when the marker file still names the previous session, and the record shown is the saved record the marker still names, which can predate a later compaction of that session whose record was not saved, and can be older than that session's final state. The block shows the row's `createdAt`, which the hook sets to the time of the run that wrote it (a row changed since can carry another value); treat it as a signal to check, not an instruction.
261
+ - The marker file remembers only the newest record per agent ID. When two sessions share one agent ID and both compact, the session that compacted first no longer finds its record through the marker.
262
+ - Two runs of the hook at the same moment for one agent ID can both find no marker and each write a record: nothing locks the marker across processes.
263
+ - In-flight lines are not merged: five edits of one file fill that section with five identical lines.
264
+ - A Flair server older than 0.47.0 stamps no expiry on the write, so a record saved there is not shown unless a later write gives it an expiry.
265
+
134
266
  ## Soul (Personality / Context)
135
267
 
136
268
  Want Claude Code to have consistent personality or project context? Set soul entries:
@@ -105,6 +105,6 @@ Field names verified against DSH `master` 2026-08-20; [their table](https://gith
105
105
 
106
106
  **Tools never appear.** DSH logs initial connection and discovery failures; by default a failed startup registers no tools rather than failing the plugin. Check `flair status` on the Flair side, and check the DSH logs for the `flair` server's connect errors. A duplicate `serverName: flair` across live instances fails the later instance at load.
107
107
 
108
- **`auth_error` on every call.** Identity/key mismatch — and remember that an exported `FLAIR_KEY_PATH` never reaches the server (caveat 1). Re-run `flair agent add <id>` (idempotent) or set `FLAIR_KEY_PATH` in `config.env`.
108
+ **`auth_error` on every call.** Read the reported cause. An exported `FLAIR_KEY_PATH` never reaches the server (caveat 1). For `unknown_agent`, no Agent row exists: run `flair agent add <id>`. For `invalid_signature`, the signature did not verify against the stored public key. Check the signing key and the signed request first. For a confirmed key mismatch, `agent add` refuses a well-formed existing row. Run `flair agent rotate-key <id>` on the Flair host; that writes the new private key on the Flair host. Copy that file to the harness host and set `FLAIR_KEY_PATH` in `config.env` to it, then restart. Other auth errors follow the cause they name.
109
109
 
110
110
  For everything else: [troubleshooting.md](troubleshooting.md).
@@ -216,7 +216,7 @@ These are read by the Harper process at boot (same places as the table above: la
216
216
  | Variable | Default | What it does |
217
217
  |----------|---------|--------------|
218
218
  | `FLAIR_EMBED_THREADS` | `max(1, availableParallelism() − 1)` | CPU threads for in-process embedding (harper-fabric-embeddings / llama.cpp). Host-aware so a 4-core box does not inherit HFE's fixed 6, and an 8-vCPU ingest host is not stuck at 6 idle cores. One core is left for Harper's event loop and the OS. `availableParallelism()` respects a container CPU quota. Set a positive integer to pin. Invalid values fall back to the default. |
219
- | `FLAIR_EMBED_GPU_LAYERS` | derived: `99` when a usable Metal backend is present (darwin-arm64 + resolvable `@node-llama-cpp/mac-arm64-metal`), else `0` | Layers to offload to the GPU. Unset **derives** the default and states it on the boot log and `/Health` (`embedding.backend` / `gpuLayers` / `source`). `0` = pin CPU; `99` = full offload. Invalid values fall through to the derived default. If offload is requested and Metal does not engage, Health and the log state the CPU fallback — they never claim GPU for a CPU run. |
219
+ | `FLAIR_EMBED_GPU_LAYERS` | derived: `99` when a usable Metal backend is present (darwin-arm64 + resolvable `@node-llama-cpp/mac-arm64-metal`), else `0` | Layers to offload to the GPU. Unset **derives** the default and states it on the boot log and `/Health` (`embedding.backend` / `gpuLayers` / `source`). `0` = pin CPU; `99` = full offload. Invalid values fall through to the derived default. `0` reports `cpu` / `gpuLayers: 0` without a readback. For an offload request, Health reports after warmup the GPU type from the native binding that warmup already opened (not a second addon): `metal` with the requested layer count when that binding says Metal, `cpu` / `gpuLayers: 0` only when that binding says no GPU, and `unconfirmed` / `gpuLayers: null` when it exposes no readback. While warmup is running, Health reports the unconfirmed preview with `pending: true`; HealthDetail calls it "pending (warmup in progress)", and `flair doctor` treats it as advisory even when `source=env`. The pending field disappears when warmup finishes. Health does not infer CPU from an empty log capture or from a different binary, and it does not claim GPU for a run the engine says is on CPU. A finished `source=detected` miss stays advisory in `flair doctor`; a finished `source=env` miss stays blocking. |
220
220
  | `FLAIR_HYBRID_RETRIEVAL` | `true` | Hybrid BM25 + vector retrieval. Set `false` / `0` / `off` to revert to the legacy HNSW + keyword-bump path. |
221
221
  | `FLAIR_MODELS_DIR` | `<data-dir>/models` | Directory the embedding GGUF is loaded from (and downloaded into on first boot). Point this at a pre-seeded directory to skip the HuggingFace download; see [troubleshooting.md](troubleshooting.md). |
222
222
 
@@ -316,7 +316,7 @@ flair federation unpin <instanceId>
316
316
  ```
317
317
 
318
318
  HTTP paths (`/FederationPair`, `/FederationSync`, `/FederationInstance`,
319
- `/FederationPeers`) and the Instance / Peer / PairingToken / Nonce / SyncLog
319
+ `/FederationPeers`) and the Instance / Peer / PairingToken / SyncLog / ReplayNonce
320
320
  schemas: **[docs/api-reference.md](api-reference.md#federation)**.
321
321
 
322
322
  ## Limitations (1.0)
@@ -26,7 +26,7 @@ Where Flair already runs. Each integration can reach one shared Flair memory sto
26
26
  | **Google ADK** (Python) | [`adk-flair`](../packages/adk-flair/README.md) | Ed25519 | `BaseMemoryService`; see [hosted auth](#hosted-flair-auth--your-agent-got-a-404) if you just got a 404 |
27
27
  | **Google ADK** (JS/TS) | [`@tpsdev-ai/adk-flair`](../packages/adk-flair-js/README.md) | Ed25519 | Same identity model as the Python package |
28
28
 
29
- Don't see your harness? If it speaks **MCP** — Flair already works with `flair-mcp`. If it has a **custom memory protocol** like LangGraph's `BaseStore` or CrewAI's `RAGStorage`, an adapter is a ~200-line package; [open an issue](https://github.com/tpsdev-ai/flair/issues) or [send a PR](https://github.com/tpsdev-ai/flair).
29
+ Don't see your harness? If it speaks **MCP** — Flair already works with `flair-mcp`. For a custom memory protocol such as LangGraph's `BaseStore` or CrewAI's `RAGStorage`, an adapter must translate that protocol's operations to Flair; [open an issue](https://github.com/tpsdev-ai/flair/issues) or [send a PR](https://github.com/tpsdev-ai/flair).
30
30
 
31
31
  **Already running on Harper?** Every surface above reaches Flair over HTTP. If your application is itself a Harper app, you can skip the network entirely — load Flair as a component of the same instance and call its resources in-process. See [embedding-in-a-harper-app.md](embedding-in-a-harper-app.md), which also covers the table-vs-resource distinction that decides whether your memories are scoped.
32
32
 
@@ -57,7 +57,7 @@ Do not "fix" a 401 or 404 by pasting the Harper admin password into the agent's
57
57
  | Shape | What is true | What you see | What to do |
58
58
  |---|---|---|---|
59
59
  | **Record missing** | No `Agent` row for this id on **this** instance | `401 {"error":"unknown_agent"}` on every signed route | Register against the hosted URL: `flair agent add <id> --target "$FLAIR_URL" --ops-target <ops-url> --admin-pass-file <path>`. Fabric ops is not `data-port − 1` — see [quickstart-fabric.md](quickstart-fabric.md). |
60
- | **Key mismatch** | The id exists; the public key on the server is not the one in your keyfile | `401 {"error":"invalid_signature"}` | Same id, wrong key — copied from another host, rotated on one side only, or the env pointing at a different agent's file. Point the env at the key that matches **this** instance, or re-seed the hosted `Agent` row from the key on this machine: `flair agent add <id> --target "$FLAIR_URL" --ops-target <ops-url> --admin-pass-file <path>` (reuses the local keyfile). `flair agent rotate-key` is localhost-only. Restart the adapter so it reloads the key. |
60
+ | **Key mismatch** | The id exists; the public key on the server is not the one in your keyfile | `401 {"error":"invalid_signature"}` | Same id, wrong key — copied from another host, rotated on one side only, or the env pointing at a different agent's file. Point the env at the key that matches **this** instance. `flair agent add` refuses an id that already exists and does not replace the stored key. On the Flair host, `flair agent rotate-key <id>` replaces the stored public key and writes the new private key on that host (it is localhost-only). The new key file must be on the adapter host before that process can sign with it. Configure that signing process to use the local file, then restart it. |
61
61
  | **Config wrong** | Identity may be fine; you are not talking to the Flair you think | Timeouts, connection errors, or **404 from Harper's catch-all** | `FLAIR_URL` must be the origin the **signing process** can open (cloud-agent localhost is the VM, not your laptop). adk-flair also needs `FLAIR_ALLOW_REMOTE_URL=1` and a raised `FLAIR_HTTP_TIMEOUT` (defaults are localhost fail-fast). A `FLAIR_URL` with a path prefix sends every request to a route that does not exist. `/Health` can be 200 while `/Memory` is still 404 if the Flair app is not loaded yet. |
62
62
 
63
63
  Clock skew is a fourth, rarer 401: `timestamp_out_of_window`.
@@ -159,7 +159,7 @@ Full per-tool walkthrough including troubleshooting: [`docs/mcp-clients.md`](mcp
159
159
 
160
160
  ## LangGraph (TypeScript)
161
161
 
162
- [`@tpsdev-ai/langgraph-flair`](https://www.npmjs.com/package/@tpsdev-ai/langgraph-flair) implements LangGraph's `BaseStore`. FlairStore provides get, put, delete, search, and batch, with the limitations below.
162
+ [`@tpsdev-ai/langgraph-flair`](https://www.npmjs.com/package/@tpsdev-ai/langgraph-flair) implements LangGraph's `BaseStore` interface. FlairStore provides get, put, delete, search, batch, listNamespaces, start, and stop; see the package README for its API and retrieval limitations.
163
163
 
164
164
  ```bash
165
165
  npm install @tpsdev-ai/langgraph-flair
@@ -173,9 +173,9 @@ const store = new FlairStore({ agentId: "my-langgraph-agent" });
173
173
  const agent = createReactAgent({ llm, tools, store });
174
174
  ```
175
175
 
176
- Maps LangGraph namespaces to Flair tags, keys to ids, values to JSON content. Search delegates to Flair's HNSW. Filter operators applied client-side. Full mapping table: [`packages/langgraph-flair/README.md`](../packages/langgraph-flair/README.md).
176
+ Maps LangGraph namespaces to Flair tags, keys to ids, values to JSON content. Non-empty search queries call Flair's `/SemanticSearch` endpoint. The server selects hybrid (BM25 plus vector), vector-only, or BM25-only retrieval; embedding availability affects whether the vector leg can run. Filter operators applied client-side. Full mapping table: [`packages/langgraph-flair/README.md`](../packages/langgraph-flair/README.md).
177
177
 
178
- LangGraph **Python** support is on the roadmap (same `BaseStore` shape, Python adapter).
178
+ This package contains the TypeScript adapter; it does not include a Python implementation.
179
179
 
180
180
  ---
181
181
 
@@ -264,7 +264,7 @@ Full details (tools, env reference, auto-recall/auto-capture flags, security not
264
264
 
265
265
  If it speaks MCP, you're already covered — every MCP client works through `flair-mcp` (the section above lists 6 we've explicitly tested).
266
266
 
267
- If it has a custom memory protocol, the adapter pattern is small (~200 lines). LangGraph and Hermes are the reference implementations. **Adapters we'd love to see:**
267
+ If it has a custom memory protocol, an adapter must translate its operations, identity, and retrieval semantics to Flair. LangGraph and Hermes are the reference implementations. **Adapters we'd love to see:**
268
268
 
269
269
  - LangGraph Python (mirror of our TS adapter)
270
270
  - CrewAI (Python `BaseRAGStorage` protocol)