@tpsdev-ai/flair 0.62.0 → 0.63.1

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 (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -33,6 +33,27 @@ import { agentContext, adminContext, internalContext, collectionResource, InProc
33
33
  // ─── Re-export for the "./server" entry point ────────────────────────────────
34
34
  export { agentContext, adminContext, internalContext, collectionResource, InProcessContextError };
35
35
  // ─── Resource resolution ─────────────────────────────────────────────────────
36
+ /**
37
+ * A by-id read through the resource's static `get(id, context)` form, which
38
+ * binds the id before `get()` runs. Resolves to the stored row, or `null` when
39
+ * the resource reports the id absent: a 404 `Response` from a scoped read, or an
40
+ * absent row for an unfiltered one. Any other failure throws rather than
41
+ * resolving to a value a caller could mistake for a missing record.
42
+ */
43
+ async function readMemoryById(Cls, id, context) {
44
+ const result = await Cls.get(id, context);
45
+ if (result instanceof Response) {
46
+ if (result.status === 404)
47
+ return null;
48
+ throw new Error(`Memory.get(${id}) failed with HTTP ${result.status}`);
49
+ }
50
+ if (result && typeof result === "object" && "error" in result && "status" in result) {
51
+ if (result.status === 404)
52
+ return null;
53
+ throw new Error(`Memory.get(${id}) failed with HTTP ${result.status}: ${result.error}`);
54
+ }
55
+ return result ?? null;
56
+ }
36
57
  /**
37
58
  * Resolve a Flair resource class from the Harper server registry.
38
59
  * Throws with a helpful message listing available resources if not found.
@@ -105,7 +126,15 @@ export class AgentHandle {
105
126
  body.subject = opts.subject;
106
127
  if (opts?.subjects)
107
128
  body.subjects = opts.subjects;
108
- return unwrap(await h.post(body));
129
+ const result = await unwrap(await h.post(body));
130
+ if (isFailureEnvelope(result)) {
131
+ throw new Error(`recall() failed: ${result.error} (HTTP ${result.status})`);
132
+ }
133
+ if (Array.isArray(result))
134
+ return result;
135
+ if (result && Array.isArray(result.results))
136
+ return result.results;
137
+ throw new Error(`recall() failed: ${result?.error ?? "unexpected response"}${result?.status ? ` (HTTP ${result.status})` : ""}`);
109
138
  }
110
139
  }
111
140
  // ─── AgentMemory (per-agent memory operations) ───────────────────────────────
@@ -144,11 +173,10 @@ class AgentMemory {
144
173
  body.id = opts.id;
145
174
  return unwrap(await h.post(body));
146
175
  }
147
- /** Get a memory by id, scoped to this agent. */
176
+ /** Get a memory by id, scoped to this agent. Resolves to `null` when the record is absent or not readable by this agent. */
148
177
  async get(id) {
149
178
  const Cls = resolveResource(this.#server, "Memory");
150
- const h = new Cls(undefined, this.#ctx);
151
- return unwrap(await h.get(id));
179
+ return readMemoryById(Cls, id, this.#ctx);
152
180
  }
153
181
  /**
154
182
  * Search memories scoped to this agent.
@@ -175,8 +203,26 @@ class AgentMemory {
175
203
  if (opts?.visibility) {
176
204
  conditions.push({ search_attribute: "visibility", search_type: "equals", search_value: opts.visibility });
177
205
  }
178
- const query = conditions.length > 0 ? { conditions, operator: "and" } : undefined;
179
- return unwrap(await h.search(query));
206
+ const limit = opts?.limit;
207
+ if (limit !== undefined && limit <= 0)
208
+ return [];
209
+ const query = conditions.length > 0 ? { conditions, operator: "and" } : {};
210
+ if (limit !== undefined)
211
+ query.limit = limit;
212
+ const source = await unwrap(await h.search(conditions.length > 0 || limit !== undefined ? query : undefined));
213
+ if (Array.isArray(source)) {
214
+ return limit !== undefined ? source.slice(0, limit) : source;
215
+ }
216
+ if (source && typeof source[Symbol.asyncIterator] === "function") {
217
+ const rows = [];
218
+ for await (const row of source) {
219
+ rows.push(row);
220
+ if (limit !== undefined && rows.length >= limit)
221
+ break;
222
+ }
223
+ return rows;
224
+ }
225
+ throw new Error(`memory.search() failed: ${source?.error ?? "unexpected response"}${source?.status ? ` (HTTP ${source.status})` : ""}`);
180
226
  }
181
227
  }
182
228
  // ─── AdminHandle ─────────────────────────────────────────────────────────────
@@ -235,11 +281,10 @@ class AdminMemory {
235
281
  this.#ctx = ctx;
236
282
  this.#agentId = agentId;
237
283
  }
238
- /** Read any memory by id, unfiltered. */
284
+ /** Read any memory by id, unfiltered. Resolves to `null` for an absent id. */
239
285
  async get(id) {
240
286
  const Cls = resolveResource(this.#server, "Memory");
241
- const h = new Cls(undefined, this.#ctx);
242
- return unwrap(await h.get(id));
287
+ return readMemoryById(Cls, id, this.#ctx);
243
288
  }
244
289
  /**
245
290
  * Write a memory attributed to another agent.
@@ -368,19 +413,37 @@ export class Flair {
368
413
  }
369
414
  }
370
415
  // ─── Helpers ─────────────────────────────────────────────────────────────────
416
+ /**
417
+ * A structured failure: an object carrying an `error` and a numeric
418
+ * `status` >= 400. Only these are rejected before results are extracted.
419
+ */
420
+ function isFailureEnvelope(value) {
421
+ return (value !== null &&
422
+ typeof value === "object" &&
423
+ !Array.isArray(value) &&
424
+ "error" in value &&
425
+ typeof value.status === "number" &&
426
+ value.status >= 400);
427
+ }
371
428
  /**
372
429
  * Unwrap a handler return value into a plain object.
373
430
  * Handlers may return a `Response` (the 401/403/400 guards) — surface its
374
431
  * JSON body so the caller sees the structured error rather than an opaque object.
432
+ * A 2xx `Response` resolves to its parsed body unchanged; a non-2xx one becomes
433
+ * `{ ...body, error, status }` with the response's own status winning.
375
434
  */
376
435
  async function unwrap(value) {
377
436
  if (value && typeof value === "object" && typeof value.json === "function" && "status" in value) {
437
+ const status = value.status;
438
+ const ok = typeof status === "number" && status >= 200 && status < 300;
378
439
  try {
379
440
  const body = await value.json();
380
- return { error: body?.error ?? "request failed", status: value.status, ...body };
441
+ if (ok)
442
+ return body;
443
+ return { ...body, error: body?.error ?? "request failed", status };
381
444
  }
382
445
  catch {
383
- return { error: "request failed", status: value.status };
446
+ return { error: "request failed", status };
384
447
  }
385
448
  }
386
449
  return value;
@@ -44,15 +44,17 @@
44
44
  *
45
45
  * resolveAgentAuth({ request: { tpsAgent: undefined } }) -> { kind: "internal" }
46
46
  * resolveAgentAuth({ request: { tpsAgent: "" } }) -> { kind: "internal" }
47
- * allowAdmin({ request: { tpsAgent: undefined } }) -> true
47
+ * allowAdmin({ request: { tpsAgent: undefined } }) -> false
48
48
  *
49
49
  * `resolveAgentAuth` tests `tpsAgent` for TRUTHINESS, so a missing or empty id
50
50
  * is indistinguishable from "no identity was supplied at all" — and that is the
51
51
  * trusted verdict. The consequence is that the most ordinary application bug
52
52
  * there is — `agentContext(session.agentId)` where the field is undefined, a
53
- * typo'd property, a lookup that found nothing — would not fail closed. It
54
- * would silently grant unfiltered cross-agent reads and writes, and pass the
55
- * admin-only gate on admin-only resources. No error, no 403, no log line.
53
+ * typo'd property, a lookup that found nothing — would not fail closed: the
54
+ * agent-facing gate (`allowVerified`) admits the `internal` verdict, and a
55
+ * `Memory` read with it is unfiltered. The admin-only gate refuses it:
56
+ * `allowAdmin` admits the `internal` verdict only for a call that carries
57
+ * `internalContext()`'s marker and no request headers.
56
58
  *
57
59
  * That is the same defect class as a check that cannot fail: **the failure mode
58
60
  * of "I forgot the id" must never be "you are now an administrator."** So:
@@ -73,7 +75,7 @@
73
75
  *
74
76
  * These guards are runtime, not types, on purpose: an embedding application may
75
77
  * be plain JavaScript, where a `string` parameter annotation buys exactly
76
- * nothing. test/integration/in-process-agents.test.ts pins both the guards and
78
+ * nothing. test/integration-heavy/in-process-agents.test.ts pins both the guards and
77
79
  * the hazard they exist for, against a real Harper.
78
80
  *
79
81
  * ── Deliberately dependency-free ─────────────────────────────────────────────
@@ -103,9 +105,8 @@ function requireAgentId(agentId, fnName) {
103
105
  : "a blank string";
104
106
  throw new InProcessContextError(`${fnName}() requires a non-empty agent id, but received ${got}. ` +
105
107
  "This is refused rather than defaulted because flair resolves a missing or empty " +
106
- "tpsAgent to its trusted `internal` verdict, which reads and writes UNFILTERED across " +
107
- "every agent and passes the admin-only gate — so returning a context here would have " +
108
- "turned a missing id into silent administrator access. Resolve the agent id from your " +
108
+ "tpsAgent to its trusted `internal` verdict, which can keep UNFILTERED access on " +
109
+ "agent-facing paths. Resolve the agent id from your " +
109
110
  "own server-side state before calling, and never from request data.");
110
111
  }
111
112
  return agentId;
@@ -175,15 +176,14 @@ export function adminContext(agentId) {
175
176
  *
176
177
  * This exists for work that is genuinely infrastructure rather than an agent's:
177
178
  * provisioning a principal, a migration, a maintenance sweep. It is the same
178
- * verdict a context-less call used to fall into by accident; naming it means an
179
- * application can no longer reach it by forgetting an argument, and means
180
- * `git grep internalContext` enumerates every place flair or an embedder took
181
- * that authority deliberately.
179
+ * `internal` verdict that `resolveAgentAuth(undefined)` returns, and
180
+ * `git grep internalContext` finds textual references to this helper's name in
181
+ * tracked files.
182
182
  *
183
183
  * There is no id to validate: the verdict comes precisely from the ABSENCE of
184
- * an identity annotation, so the returned object carries none. The marker field
185
- * is inert — it documents intent at a debugger breakpoint and is read by
186
- * nothing.
184
+ * an identity annotation, so the returned object carries none. The admin-only
185
+ * gate reads its marker: `allowAdmin` admits the `internal` verdict only for a
186
+ * call that carries it and no request headers.
187
187
  *
188
188
  * ```ts
189
189
  * // Registering a principal — infrastructure, not an agent's own write.
@@ -210,13 +210,15 @@ export function internalContext() {
210
210
  * start their own transaction.
211
211
  *
212
212
  * **They do still need the CONTEXT.** Only the collection binding is
213
- * unnecessary for a read, not the identity. `Cls.search(query)` with the second
214
- * argument left off does not read "as nobody" — outside a Harper request scope
215
- * (a boot hook, a timer, a queue worker, a detached promise) it resolves to the
216
- * same trusted `internal` verdict this module exists to keep out of reach, and
217
- * returns every agent's private records unfiltered. On that path the resource's
218
- * own `allow*` gate is not consulted at all, so nothing else stands in the way.
219
- * Pass the context to every call, read or write (flair#936).
213
+ * unnecessary for a read, not the identity. `Cls.search(query)` with no explicit
214
+ * or ambient context resolves to the trusted `internal` verdict. The query's
215
+ * conditions still narrow the rows, but no agent scope applies: every agent's
216
+ * matching records, `private` included, are returned. With the resulting `{}`
217
+ * context and no `query.checkPermission`, no permission check is requested
218
+ * (no `context.authorize`), so `allowRead` is never consulted. Memory's
219
+ * `allowRead` -> `memoryAuthGate` -> `allowVerified` would admit this `internal`
220
+ * call even if consulted. Pass the context to every call, read or write
221
+ * (flair#936).
220
222
  */
221
223
  export async function collectionResource(Cls, context) {
222
224
  if (context == null || typeof context !== "object") {
@@ -2,14 +2,139 @@
2
2
  * Transaction helper for single-row Soul resource history (flair#2139 slice 1).
3
3
  */
4
4
  import { createHash } from "node:crypto";
5
+ import { createRequire } from "node:module";
6
+ import { dirname, join } from "node:path";
5
7
  import { databases } from "harper";
6
8
  import { authorizeSoulWrite } from "./soul-write-policy.js";
7
9
  import { authorizeSkillVersionWrite } from "./skill-write-policy.js";
8
10
  import { withKeyLock } from "./key-lock.js";
9
- import { withOwnedTransaction } from "./request-transaction.js";
11
+ import { isJoinableTransaction, withOwnedTransaction, withSharedWriteTransaction } from "./request-transaction.js";
12
+ import { txnFault, txnPausePoint } from "./txn-pause-point.js";
10
13
  import { maybeThrowSkillWriteFault } from "./skill-write-fault.js";
14
+ import { validateServerRow } from "./server-row-validation.js";
11
15
  import { PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
12
16
  export const INSTRUCTION_VERSION_TABLE = "InstructionVersion";
17
+ /** flair#2139 S3b — an instruction event is reserved to the internal appender. */
18
+ export const INSTRUCTION_EVENT_ID_PREFIX = "instruction-change:";
19
+ /** The ten allowlisted detail fields, in this order (Sherlock 4). */
20
+ export const INSTRUCTION_EVENT_DETAIL_FIELDS = [
21
+ "subjectType",
22
+ "subjectId",
23
+ "key",
24
+ "changeKind",
25
+ "actorKind",
26
+ "actorId",
27
+ "sourceClass",
28
+ "valueHash",
29
+ "previousVersionHash",
30
+ "recordHash",
31
+ ];
32
+ /** The three value-derived hashes D1 omits for a private skill's event. */
33
+ const PRIVATE_SKILL_EVENT_OMITTED = ["valueHash", "previousVersionHash", "recordHash"];
34
+ /**
35
+ * flair#2139 S3b — the event for one appended version, built by explicit field
36
+ * enumeration of selected row fields. The three
37
+ * value-derived hashes are absent for a private skill (D1), gated on the
38
+ * version's stored visibility (which a tombstone carries as the closed head's
39
+ * last state).
40
+ */
41
+ export function instructionEventFor(record) {
42
+ const subjectType = record.subjectType === "soul" ? "soul" : "skill";
43
+ const detail = {
44
+ subjectType,
45
+ subjectId: record.subjectId,
46
+ key: subjectType === "soul" ? (record.key ?? null) : null,
47
+ changeKind: record.kind,
48
+ actorKind: record.actorKind,
49
+ actorId: record.actorId ?? null,
50
+ sourceClass: record.sourceClass,
51
+ valueHash: record.valueHash ?? null,
52
+ previousVersionHash: record.previousVersionHash ?? null,
53
+ recordHash: record.recordHash ?? null,
54
+ };
55
+ if (subjectType === "skill" && record.visibility === PRIVATE_VISIBILITY) {
56
+ for (const field of PRIVATE_SKILL_EVENT_OMITTED)
57
+ delete detail[field];
58
+ }
59
+ return {
60
+ id: `${INSTRUCTION_EVENT_ID_PREFIX}${record.id}`,
61
+ authorId: "flair:internal",
62
+ kind: `${subjectType}.changed`,
63
+ scope: record.agentId,
64
+ summary: `${subjectType === "soul" ? "Soul entry" : "Skill"} ${record.kind}d`,
65
+ detail: JSON.stringify(detail),
66
+ targetIds: [],
67
+ refId: record.id,
68
+ createdAt: record.createdAt,
69
+ };
70
+ }
71
+ /** Append the event in the caller's transaction; a failure aborts the write (D2). */
72
+ async function appendInstructionEvent(record, shared) {
73
+ const events = databases.flair?.OrgEvent;
74
+ if (!isTableLike(events))
75
+ throw new Error("flair: the OrgEvent table is unavailable");
76
+ const event = instructionEventFor(record);
77
+ // Test-only: the hook may inspect the exact row about to be staged (inert
78
+ // unless a fixture installs one).
79
+ maybeThrowSkillWriteFault("event", record.agentId, event);
80
+ validateServerRow(events, event);
81
+ await events.create(event, shared);
82
+ }
83
+ /**
84
+ * flair#2645 / flair#2642 — remove the version record this request appended, when
85
+ * it is still the subject's head. A close that a newer write made Harper skip can
86
+ * commit its version row (an update's successor version or a delete's tombstone)
87
+ * while leaving the row open; undoing that write must
88
+ * not leave a gap in the chain, so a record followed by a later version is left
89
+ * in place and reported as `superseded`.
90
+ */
91
+ export async function removeAppendedVersion(ctx, subjectType, subjectId, versionRecordId) {
92
+ const store = databases.flair?.InstructionVersion?.primaryStore;
93
+ const outcome = await withKeyLock(store, [LOCK_NAMESPACE, subjectType], async () => {
94
+ const staged = await withOwnedTransaction(ctx, async (shared) => {
95
+ const head = await readHead(subjectType, subjectId, shared);
96
+ if (!head)
97
+ return "removed";
98
+ if (String(head.id) !== versionRecordId)
99
+ return "superseded";
100
+ const table = databases.flair.InstructionVersion;
101
+ // The resource class overrides `delete` and `get` for REST authority; the
102
+ // append helper's own table is its base prototype, which exposes the raw
103
+ // writer this in-process undo needs.
104
+ const raw = Object.getPrototypeOf(table);
105
+ if (typeof raw?.delete !== "function" || typeof raw?.get !== "function")
106
+ return "unavailable";
107
+ await raw.delete.call(table, versionRecordId, shared);
108
+ // Remove this record's event in the same transaction.
109
+ const events = databases.flair?.OrgEvent;
110
+ if (!isTableLike(events))
111
+ throw new Error("flair: the OrgEvent table is unavailable");
112
+ await events.delete(`${INSTRUCTION_EVENT_ID_PREFIX}${versionRecordId}`, shared);
113
+ const pause = txnPausePoint("skill-version-rollback-staged");
114
+ if (pause)
115
+ await pause;
116
+ return "deleted";
117
+ });
118
+ if (staged !== "deleted" && staged !== "removed")
119
+ return staged;
120
+ const table = databases.flair.InstructionVersion;
121
+ const raw = Object.getPrototypeOf(table);
122
+ if (typeof raw?.get !== "function")
123
+ return "unavailable";
124
+ const pause = txnPausePoint("skill-version-rollback-committed");
125
+ if (pause)
126
+ await pause;
127
+ const left = await raw.get.call(table, versionRecordId, {});
128
+ if (left != null)
129
+ return "unavailable";
130
+ return await raw.get.call(table, versionRecordId, {}) == null ? "removed" : "unavailable";
131
+ }, LOCK_ATTEMPTS, LOCK_WAIT_MS);
132
+ if (outcome.kind === "busy")
133
+ return "busy";
134
+ if (outcome.kind === "unavailable")
135
+ return "unavailable";
136
+ return outcome.value;
137
+ }
13
138
  /**
14
139
  * The fields the record digest covers, in this exact order. `recordHash` is
15
140
  * excluded (it is the digest), and every other field is included, including
@@ -95,6 +220,69 @@ export function expectedVersionOf(input) {
95
220
  function jsonResponse(status, body) {
96
221
  return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
97
222
  }
223
+ let harperValidationErrorCtor;
224
+ /**
225
+ * Read and memoize Harper's cached `ValidationError` constructor. `harper`
226
+ * exports only ".", so resolve the main entry to locate hdbError.js.
227
+ * An uncached load can execute globals.js and clear `global.transaction`;
228
+ * this helper never requires the module. Eviction/reload can leave the memoized
229
+ * constructor stale. A missing constructor reports no match.
230
+ */
231
+ function harperValidationError() {
232
+ if (harperValidationErrorCtor)
233
+ return harperValidationErrorCtor;
234
+ try {
235
+ const req = createRequire(import.meta.url);
236
+ const mainPath = req.resolve("harper");
237
+ const errorPath = join(dirname(mainPath), "utility", "errors", "hdbError.js");
238
+ const loaded = req.cache[errorPath];
239
+ const ctor = loaded?.exports?.ValidationError;
240
+ if (typeof ctor === "function")
241
+ harperValidationErrorCtor = ctor;
242
+ }
243
+ catch { /* no class: fail closed below */ }
244
+ return harperValidationErrorCtor ?? null;
245
+ }
246
+ /**
247
+ * The validator's own client error, rendered with the problem-details fields
248
+ * Harper's REST responder uses for it (harper@5.3.1 dist/server/REST.js:498).
249
+ * The class is declared at dist/utility/errors/hdbError.js:243; in that
250
+ * version's dist it is constructed only at the two schema-validation sites,
251
+ * dist/resources/Table.js:6459 and dist/resources/defineResource.js:432, both
252
+ * with a non-empty issue list. Its constructor sets `name` and `code` to
253
+ * "ValidationError", a 400 `statusCode`, and the `errors` array. The status
254
+ * check refuses any 5xx.
255
+ */
256
+ function validationErrorResponse(err) {
257
+ if (!err || typeof err !== "object")
258
+ return null;
259
+ const candidate = err;
260
+ if (candidate.name !== "ValidationError" || candidate.code !== "ValidationError" || candidate.statusCode !== 400)
261
+ return null;
262
+ const issues = candidate.errors;
263
+ // Only errors passing the shape checks reach the constructor lookup.
264
+ if (!Array.isArray(issues) || issues.length === 0)
265
+ return null;
266
+ const wellFormed = issues.every((issue) => {
267
+ if (!issue || typeof issue !== "object")
268
+ return false;
269
+ const fields = issue;
270
+ return typeof fields.path === "string" && typeof fields.code === "string" && typeof fields.message === "string";
271
+ });
272
+ if (!wellFormed)
273
+ return null;
274
+ const ValidationError = harperValidationError();
275
+ if (!ValidationError || !(err instanceof ValidationError))
276
+ return null;
277
+ return jsonResponse(400, {
278
+ error: "ValidationError",
279
+ type: "error:ValidationError",
280
+ code: "ValidationError",
281
+ title: typeof candidate.message === "string" ? candidate.message : "invalid request body",
282
+ status: 400,
283
+ detail: issues,
284
+ });
285
+ }
98
286
  function staleHeadResponse(expected, head) {
99
287
  return jsonResponse(409, {
100
288
  error: "instruction_version_head_mismatch",
@@ -120,9 +308,7 @@ function isTableLike(table) {
120
308
  * the cached read snapshot; the read resource uses the same raw handle without a lock.
121
309
  */
122
310
  export async function readHead(subjectType, subjectId, shared, soulIdentity) {
123
- const table = databases.flair?.InstructionVersion;
124
- if (!isTableLike(table))
125
- throw new Error("flair: the InstructionVersion table is unavailable");
311
+ const table = instructionVersionTable();
126
312
  for await (const row of table.search({
127
313
  conditions: [
128
314
  { attribute: "subjectType", comparator: "equals", value: subjectType },
@@ -139,6 +325,41 @@ export async function readHead(subjectType, subjectId, shared, soulIdentity) {
139
325
  }
140
326
  return null;
141
327
  }
328
+ function instructionVersionTable() {
329
+ const table = databases.flair?.InstructionVersion;
330
+ if (!isTableLike(table))
331
+ throw new Error("flair: the InstructionVersion table is unavailable");
332
+ return table;
333
+ }
334
+ /** One version record of a subject's chain, by its addressable id, or null. */
335
+ export async function readVersionRecord(subjectType, subjectId, recordId, shared) {
336
+ const table = instructionVersionTable();
337
+ for await (const row of table.search({
338
+ conditions: [
339
+ { attribute: "subjectType", comparator: "equals", value: subjectType },
340
+ { attribute: "subjectId", comparator: "equals", value: subjectId },
341
+ ],
342
+ }, shared)) {
343
+ if (String(row.id) === recordId)
344
+ return row;
345
+ }
346
+ return null;
347
+ }
348
+ /** The record with the next sequence number after `version` for this subject, or null. */
349
+ export async function readVersionRecordAfter(subjectType, subjectId, version, shared) {
350
+ const table = instructionVersionTable();
351
+ const next = BigInt(version) + 1n;
352
+ for await (const row of table.search({
353
+ conditions: [
354
+ { attribute: "subjectType", comparator: "equals", value: subjectType },
355
+ { attribute: "subjectId", comparator: "equals", value: subjectId },
356
+ ],
357
+ }, shared)) {
358
+ if (BigInt(row.version) === next)
359
+ return row;
360
+ }
361
+ return null;
362
+ }
142
363
  async function readSoulHead(agentId, key, shared) {
143
364
  const identity = { agentId, key };
144
365
  const subjectId = soulSubjectId(agentId, key);
@@ -188,11 +409,13 @@ const LOCK_NAMESPACE = "flair-instruction-version";
188
409
  /** Bounded lock wait. */
189
410
  const LOCK_ATTEMPTS = 200;
190
411
  const LOCK_WAIT_MS = 10;
191
- export async function recordVersion(ctx, request, mutateRow) {
412
+ export async function recordVersion(ctx, request, mutateRow, joinCallerTransaction = false) {
192
413
  const store = databases.flair?.InstructionVersion?.primaryStore;
414
+ const joinsCaller = joinCallerTransaction && isJoinableTransaction(ctx);
415
+ const callerTransaction = joinsCaller ? ctx.transaction : null;
193
416
  let outcome;
194
417
  try {
195
- outcome = await withKeyLock(store, [LOCK_NAMESPACE, request.subjectType], () => withOwnedTransaction(ctx, async (shared) => {
418
+ outcome = await withKeyLock(store, [LOCK_NAMESPACE, request.subjectType], () => (joinsCaller ? withSharedWriteTransaction : withOwnedTransaction)(ctx, async (shared) => {
196
419
  const authorization = await resolveVersionAuthorization(request.subjectType, shared);
197
420
  if (authorization.denied)
198
421
  return { ok: false, response: authorization.denied };
@@ -270,7 +493,9 @@ export async function recordVersion(ctx, request, mutateRow) {
270
493
  expectedVersion: null,
271
494
  };
272
495
  oldRecord.recordHash = recordDigest(oldRecord);
496
+ validateServerRow(table, oldRecord);
273
497
  await table.create(oldRecord, shared);
498
+ await appendInstructionEvent(oldRecord, shared);
274
499
  }
275
500
  const sequence = head ? BigInt(head.version) + 1n : 1n;
276
501
  const id = versionId(input.subjectType, input.subjectId, sequence);
@@ -296,19 +521,38 @@ export async function recordVersion(ctx, request, mutateRow) {
296
521
  expectedVersion: expected,
297
522
  };
298
523
  record.recordHash = recordDigest(record);
524
+ // Test-only pause after the append id is computed, inside the locked
525
+ // transaction (flair#2645 audit). Inert unless fault injection is armed.
526
+ await txnPausePoint("instruction-version-append");
299
527
  // flair#2139 S2 — test-only per-step fault injection (see
300
528
  // skill-write-fault.ts). Fires after the Memory-side successor/close
301
529
  // writes rode this same transaction, so the append failure aborts them
302
530
  // too: no successor, no close, no version.
303
531
  if (input.subjectType === "skill")
304
- maybeThrowSkillWriteFault("append", input.agentId);
532
+ maybeThrowSkillWriteFault("append", input.agentId, record);
533
+ validateServerRow(table, record);
305
534
  await table.create(record, shared);
535
+ // Test-only: fail after the version row is staged so a test can prove
536
+ // the abort rolls both it and the caller's staged row back. Inert
537
+ // unless the fault-injection opt-in is armed.
538
+ if (txnFault("instruction-version-append-fail"))
539
+ throw new Error("test-only instruction version append failure");
540
+ await appendInstructionEvent(record, shared);
306
541
  return { ok: true, result, version: id };
307
542
  }), LOCK_ATTEMPTS, LOCK_WAIT_MS);
308
543
  }
309
544
  catch (err) {
545
+ if (callerTransaction)
546
+ callerTransaction.abort();
310
547
  if (err instanceof RowMutationDenied)
311
548
  return { ok: false, response: err.response };
549
+ // Rows this append builds are validated before staging: their caller-derived
550
+ // fields are coerced to the schema's types where they are assigned, so a
551
+ // schema failure on one is a server defect. A Harper ValidationError that
552
+ // reaches here is the caller's row: report it as 400.
553
+ const validation = validationErrorResponse(err);
554
+ if (validation)
555
+ return { ok: false, response: validation };
312
556
  // A head-read, append or commit failure aborts the whole transaction; report
313
557
  // unavailable rather than a success, so no caller reads a missing version as
314
558
  // "nothing happened" (fail-closed).
@@ -0,0 +1,13 @@
1
+ /**
2
+ * True when `auth` is the `internal` verdict, `context` carries the
3
+ * `__flairInternal` marker (which `internalContext()` sets), and
4
+ * `context.request ?? context` has no `headers`.
5
+ *
6
+ * Called by allowAdmin (resources/agent-auth.ts), soulWriteSource
7
+ * (resources/soul-write-policy.ts) and skillWriteSource
8
+ * (resources/skill-write-policy.ts).
9
+ */
10
+ export function isDeliberateInternalVerdict(context, auth) {
11
+ const request = context?.request ?? context;
12
+ return auth.kind === "internal" && context?.__flairInternal === true && !request?.headers;
13
+ }
@@ -42,6 +42,7 @@
42
42
  * Kept free of any harper import (mirrors agentcard-fields.ts)
43
43
  * so the document shape is unit-testable without spinning up Harper.
44
44
  */
45
+ import { MCP_REQUESTED_SCOPES } from "./mcp-tool-scopes.js";
45
46
  /** The grant this agent's CIMD document targets — formalized by oauth#161, accepted by the published 2.2.0 validator. See module header. */
46
47
  export const CIMD_TARGET_GRANT_TYPES = ["client_credentials"];
47
48
  /** The auth method this agent's CIMD document targets — formalized by oauth#161, accepted by the published 2.2.0 validator. See module header. */
@@ -78,6 +79,9 @@ export function buildCimdDocument(params) {
78
79
  // pending oauth#161 — rejected by today's open-draft #167 validator; see module header.
79
80
  token_endpoint_auth_method: CIMD_TARGET_AUTH_METHOD,
80
81
  grant_types: [...CIMD_TARGET_GRANT_TYPES],
82
+ // flair#3076: @harperfast/oauth 2.9.0 mints a client_credentials token with
83
+ // this document's `scope` (test/unit-isolated/mcp-machine-token-scope-3076.test.ts).
84
+ scope: MCP_REQUESTED_SCOPES.join(" "),
81
85
  // redirect_uris AND response_types are both deliberately omitted — #161
82
86
  // blesses this explicitly for client_credentials-only CIMD clients (no
83
87
  // redirect-based flow is ever possible for a headless agent). Neither