@tpsdev-ai/flair 0.62.0 → 0.63.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 (232) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +18 -10
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/types.js +1 -0
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli.js +66 -122
  8. package/dist/commands/agent.js +27 -65
  9. package/dist/commands/backup-approval.js +218 -0
  10. package/dist/commands/backup.js +37 -33
  11. package/dist/commands/bootstrap.js +3 -1
  12. package/dist/commands/deploy.js +37 -7
  13. package/dist/commands/doctor.js +119 -0
  14. package/dist/commands/export.js +3 -4
  15. package/dist/commands/federation.js +653 -68
  16. package/dist/commands/grant.js +5 -6
  17. package/dist/commands/help.js +25 -0
  18. package/dist/commands/idp.js +14 -19
  19. package/dist/commands/import.js +131 -19
  20. package/dist/commands/init.js +7 -7
  21. package/dist/commands/integrity.js +5 -6
  22. package/dist/commands/mcp.js +11 -17
  23. package/dist/commands/memory.js +33 -15
  24. package/dist/commands/orgevent.js +5 -10
  25. package/dist/commands/principal.js +13 -25
  26. package/dist/commands/quality.js +3 -0
  27. package/dist/commands/rem.js +484 -65
  28. package/dist/commands/restore.js +352 -44
  29. package/dist/commands/service.js +84 -2
  30. package/dist/commands/soul.js +0 -6
  31. package/dist/commands/status.js +51 -33
  32. package/dist/commands/test.js +4 -1
  33. package/dist/commands/upgrade.js +53 -22
  34. package/dist/commands/workspace.js +7 -8
  35. package/dist/deploy.js +59 -3
  36. package/dist/doctor-client.js +7 -2
  37. package/dist/fabric-upgrade.js +12 -2
  38. package/dist/federation/presence-send.js +139 -0
  39. package/dist/federation-verify.js +269 -177
  40. package/dist/install/clients.js +171 -35
  41. package/dist/lib/agent-id-rule.js +44 -2
  42. package/dist/lib/atomic-write.js +1 -1
  43. package/dist/lib/auth-resolve.js +1028 -52
  44. package/dist/lib/backup-approval-store.js +612 -0
  45. package/dist/lib/backup-artifact.js +343 -0
  46. package/dist/lib/config-critical-section.js +212 -25
  47. package/dist/lib/connect-phase.js +33 -0
  48. package/dist/lib/daemon-liveness.js +2 -1
  49. package/dist/lib/federation-pair-access.js +4 -0
  50. package/dist/lib/federation-retry-queue.js +283 -0
  51. package/dist/lib/federation-retry-row.js +101 -0
  52. package/dist/lib/instruction-event-contract.js +17 -0
  53. package/dist/lib/instruction-event-doctor.js +102 -0
  54. package/dist/lib/launchd-management.js +14 -3
  55. package/dist/lib/mcp-enable.js +14 -15
  56. package/dist/lib/memory-attributes.js +2 -0
  57. package/dist/lib/memory-provider-timeout.js +33 -0
  58. package/dist/lib/mqtt-config.js +132 -0
  59. package/dist/lib/mqtt-listener-doctor.js +104 -0
  60. package/dist/lib/open-live-row.js +20 -0
  61. package/dist/lib/ops-url.js +52 -0
  62. package/dist/lib/promotion-content-hash.js +20 -0
  63. package/dist/lib/restore-archive.js +760 -0
  64. package/dist/lib/restore-verify.js +1 -1
  65. package/dist/lib/skill-assignment-preflight.js +159 -0
  66. package/dist/lib/skill-seed.js +91 -8
  67. package/dist/lib/skill-tombstone-doctor.js +133 -0
  68. package/dist/lib/soul-scope-fields.js +26 -0
  69. package/dist/lib/uninstall-purge.js +266 -11
  70. package/dist/lib/upgrade-prior-liveness.js +2 -1
  71. package/dist/mcp-client-assertion.js +2 -10
  72. package/dist/memory-id-checkpoint.js +28 -7
  73. package/dist/mqtt-off-deploy.js +550 -0
  74. package/dist/rem/promote-policy.js +3 -3
  75. package/dist/rem/restore.js +302 -26
  76. package/dist/rem/runner.js +220 -58
  77. package/dist/rem/scheduler.js +21 -4
  78. package/dist/resources/A2AAdapter.js +131 -178
  79. package/dist/resources/AdminMemory.js +2 -0
  80. package/dist/resources/AdminMemoryCandidates.js +116 -0
  81. package/dist/resources/Agent.js +155 -45
  82. package/dist/resources/AgentCard.js +4 -0
  83. package/dist/resources/AgentKeyRegister.js +56 -22
  84. package/dist/resources/AgentReadPosition.js +7 -0
  85. package/dist/resources/AgentSeed.js +232 -107
  86. package/dist/resources/AutoPromoteCandidates.js +413 -84
  87. package/dist/resources/Credential.js +6 -8
  88. package/dist/resources/Federation.js +219 -57
  89. package/dist/resources/FederationRetry.js +4 -4
  90. package/dist/resources/InstructionVersion.js +1 -1
  91. package/dist/resources/MCPClientMetadata.js +6 -3
  92. package/dist/resources/Memory.js +1303 -270
  93. package/dist/resources/MemoryArchive.js +149 -64
  94. package/dist/resources/MemoryBootstrap.js +12 -22
  95. package/dist/resources/MemoryCandidate.js +16 -2
  96. package/dist/resources/MemoryConsolidate.js +2 -2
  97. package/dist/resources/MemoryFeed.js +360 -147
  98. package/dist/resources/MemoryMaintenance.js +290 -72
  99. package/dist/resources/MemoryPurge.js +138 -22
  100. package/dist/resources/MemoryReflect.js +68 -14
  101. package/dist/resources/MemoryReindex.js +91 -13
  102. package/dist/resources/Message.js +11 -2
  103. package/dist/resources/OAuth.js +156 -39
  104. package/dist/resources/OAuthClient.js +1 -1
  105. package/dist/resources/OrgEvent.js +292 -29
  106. package/dist/resources/OrgEventCatchup.js +7 -0
  107. package/dist/resources/OrgEventMaintenance.js +48 -10
  108. package/dist/resources/PairingToken.js +1 -1
  109. package/dist/resources/Presence.js +31 -11
  110. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  111. package/dist/resources/RecordUsage.js +2 -4
  112. package/dist/resources/Soul.js +2 -0
  113. package/dist/resources/SoulFeed.js +2 -1
  114. package/dist/resources/WorkspaceLatest.js +4 -0
  115. package/dist/resources/XAA.js +36 -10
  116. package/dist/resources/a2a-stream.js +313 -0
  117. package/dist/resources/a2a-url.js +4 -5
  118. package/dist/resources/agent-admin.js +10 -1
  119. package/dist/resources/agent-auth.js +98 -68
  120. package/dist/resources/agent-read-position-lib.js +4 -1
  121. package/dist/resources/agent-status-guard.js +9 -7
  122. package/dist/resources/auth-middleware.js +166 -42
  123. package/dist/resources/authority-field-guard.js +9 -11
  124. package/dist/resources/auto-promote-lib.js +8 -5
  125. package/dist/resources/basic-auth-header.js +21 -0
  126. package/dist/resources/bm25-index-service.js +4 -5
  127. package/dist/resources/dedup-cluster.js +6 -1
  128. package/dist/resources/embeddings-provider.js +25 -0
  129. package/dist/resources/federation-classify.js +89 -0
  130. package/dist/resources/federation-retry-lib.js +6 -81
  131. package/dist/resources/health.js +43 -4
  132. package/dist/resources/host-pointer/registry.js +29 -0
  133. package/dist/resources/host-pointer-adapter.js +1 -0
  134. package/dist/resources/in-process.js +24 -22
  135. package/dist/resources/instruction-version-record.js +251 -7
  136. package/dist/resources/internal-authority.js +13 -0
  137. package/dist/resources/mcp-handler.js +106 -12
  138. package/dist/resources/mcp-oauth-flag.js +12 -14
  139. package/dist/resources/mcp-oauth.js +430 -53
  140. package/dist/resources/mcp-tools.js +60 -22
  141. package/dist/resources/memory-declared-attributes.js +1 -0
  142. package/dist/resources/memory-embed-hash.js +56 -0
  143. package/dist/resources/memory-host-source.js +5 -2
  144. package/dist/resources/memory-reflect-lib.js +1 -1
  145. package/dist/resources/memory-write-lock.js +202 -23
  146. package/dist/resources/memory-write-response.js +1 -1
  147. package/dist/resources/memory-write-transaction.js +243 -0
  148. package/dist/resources/migration-boot.js +17 -12
  149. package/dist/resources/migrations/boot-progress.js +25 -0
  150. package/dist/resources/migrations/data-dir.js +16 -3
  151. package/dist/resources/migrations/dir-safety.js +60 -2
  152. package/dist/resources/migrations/embedding-stamp.js +315 -49
  153. package/dist/resources/migrations/graph-heal.js +9 -2
  154. package/dist/resources/migrations/ledger.js +5 -2
  155. package/dist/resources/migrations/lock.js +867 -80
  156. package/dist/resources/migrations/progress.js +71 -10
  157. package/dist/resources/migrations/runner.js +212 -18
  158. package/dist/resources/migrations/state.js +36 -1
  159. package/dist/resources/migrations/status.js +2 -13
  160. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  161. package/dist/resources/migrations/types.js +26 -1
  162. package/dist/resources/migrations/visibility-backfill.js +111 -70
  163. package/dist/resources/oauth-discovery.js +0 -5
  164. package/dist/resources/object-body-guard.js +12 -5
  165. package/dist/resources/org-event-reserved.js +92 -0
  166. package/dist/resources/org-event-write-fault.js +19 -0
  167. package/dist/resources/owner-field-guard.js +1 -1
  168. package/dist/resources/owner-scoped-write-policy.js +65 -21
  169. package/dist/resources/owner-scoped-writes.js +37 -6
  170. package/dist/resources/path-id-rewrite.js +76 -0
  171. package/dist/resources/presence-internal.js +5 -5
  172. package/dist/resources/promotion-binding.js +43 -0
  173. package/dist/resources/promotion-stamp.js +124 -33
  174. package/dist/resources/protocol-context.js +189 -0
  175. package/dist/resources/record-type-kit.js +2 -4
  176. package/dist/resources/request-target.js +28 -1
  177. package/dist/resources/request-transaction.js +11 -1
  178. package/dist/resources/seed-reservation.js +1 -2
  179. package/dist/resources/semantic-retrieval-core.js +7 -6
  180. package/dist/resources/server-row-validation.js +71 -0
  181. package/dist/resources/skill-manifest.js +4 -3
  182. package/dist/resources/skill-version-write.js +384 -27
  183. package/dist/resources/skill-write-fault.js +6 -3
  184. package/dist/resources/skill-write-policy.js +2 -1
  185. package/dist/resources/soul-write-policy.js +26 -7
  186. package/dist/resources/table-helpers.js +1 -1
  187. package/dist/resources/table-subscription-policy.js +518 -85
  188. package/dist/resources/table-subscriptions.js +20 -7
  189. package/dist/resources/txn-pause-point.js +122 -5
  190. package/dist/resources/usage-recording.js +54 -46
  191. package/dist/resources/write-back.js +176 -11
  192. package/dist/resources/write-journal-context.js +5 -0
  193. package/dist/resources/write-journal.js +289 -0
  194. package/dist/src/lib/agent-id-rule.js +44 -2
  195. package/dist/src/lib/atomic-write.js +1 -1
  196. package/dist/src/lib/federation-retry-row.js +101 -0
  197. package/dist/src/lib/instruction-event-contract.js +17 -0
  198. package/dist/src/lib/memory-attributes.js +2 -0
  199. package/dist/src/lib/open-live-row.js +20 -0
  200. package/dist/src/lib/soul-scope-fields.js +26 -0
  201. package/dist/src/rem/promote-policy.js +3 -3
  202. package/dist/src/rem/scheduler.js +21 -4
  203. package/docs/access-control.md +18 -9
  204. package/docs/api-reference.md +126 -28
  205. package/docs/auth.md +40 -18
  206. package/docs/claude-code.md +3 -3
  207. package/docs/deploying-on-fabric.md +108 -0
  208. package/docs/deployment.md +17 -0
  209. package/docs/embedding-in-a-harper-app.md +16 -14
  210. package/docs/entity-vocabulary.md +3 -6
  211. package/docs/federation.md +29 -2
  212. package/docs/integrations.md +11 -11
  213. package/docs/mcp-clients.md +7 -5
  214. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  215. package/docs/notes/mcp-oauth-model2.md +6 -6
  216. package/docs/openclaw.md +1 -1
  217. package/docs/quickstart-fabric.md +2 -2
  218. package/docs/quickstart.md +3 -3
  219. package/docs/releasing.md +13 -13
  220. package/docs/rem.md +24 -3
  221. package/docs/secrets-and-keys.md +2 -2
  222. package/docs/standalone-local.md +29 -2
  223. package/docs/supply-chain-policy.md +28 -20
  224. package/docs/the-team.md +2 -2
  225. package/docs/upgrade.md +14 -0
  226. package/package.json +18 -11
  227. package/schemas/agent.graphql +3 -3
  228. package/schemas/federation.graphql +10 -7
  229. package/schemas/memory.graphql +7 -2
  230. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  231. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  232. package/dist/resources/soul-adk-guard.js +0 -68
@@ -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
+ }
@@ -33,6 +33,7 @@ import { stampOriginatorOnCreate } from "./originator-instance.js";
33
33
  import { invalidAgentIdMessage, isValidAgentId } from "../src/lib/agent-id-rule.js";
34
34
  import { credentialMapsPrincipal, credentialPrincipalId, credentialRefusal } from "../src/lib/credential-status-rule.js";
35
35
  import { resolveVersion } from "./version.js";
36
+ import { TEST_FAULT_INJECTION_ENV } from "./txn-pause-point.js";
36
37
  // The MCP protocol revision we implement (initialize handshake).
37
38
  const PROTOCOL_VERSION = "2025-06-18";
38
39
  // ─── Body size cap ───────────────────────────────────────────────────────────
@@ -130,6 +131,54 @@ function rpcError(id, code, message, httpStatus = 200) {
130
131
  };
131
132
  }
132
133
  // ─── sub → Agent resolution ─────────────────────────────────────────────────
134
+ // Test-only read failures (flair#2794): the `Credential(kind:"idp",
135
+ // idpSubject=sub)` lookup and the mapped principal's `Agent` read, each failing
136
+ // for a token subject that contains its setting's value. A setting is read only
137
+ // when FLAIR_ENABLE_TEST_FAULT_INJECTION=1 (resources/txn-pause-point.ts), and
138
+ // each matching subject fails once, so the request after the failing one is
139
+ // answered normally. Nothing in a request can arm either hook.
140
+ //
141
+ // flair#2799 — the fired-subject state is process-lifetime: it lives here for as
142
+ // long as the server process does and never resets between requests. It holds
143
+ // at most TEST_READ_FAILURE_FIRED_LIMIT (setting, subject) pairs so that a
144
+ // long-lived process driven with many distinct subjects stops arming new faults
145
+ // instead of growing without limit. Once the set is full, the hook answers false
146
+ // (no fault) for every further pair and logs that once. An empty setting value
147
+ // is inert: it matches nothing and is never added to the set.
148
+ const TEST_CREDENTIAL_READ_FAIL_SUB_ENV = "FLAIR_TEST_MCP_CREDENTIAL_READ_FAIL_SUB";
149
+ const TEST_PRINCIPAL_READ_FAIL_SUB_ENV = "FLAIR_TEST_MCP_PRINCIPAL_READ_FAIL_SUB";
150
+ export const TEST_READ_FAILURE_FIRED_LIMIT = 1024;
151
+ const testReadFailuresFired = new Set();
152
+ let testReadFailuresFullLogged = false;
153
+ /**
154
+ * Should this subject's read fail once? Test-only; false unless
155
+ * FLAIR_ENABLE_TEST_FAULT_INJECTION=1 and the setting names a non-empty value
156
+ * the subject contains. Exported for the fired-state bound's unit test.
157
+ */
158
+ export function testReadFailure(setting, sub) {
159
+ if (process.env[TEST_FAULT_INJECTION_ENV] !== "1")
160
+ return false;
161
+ const match = process.env[setting];
162
+ if (!match || !sub.includes(match))
163
+ return false;
164
+ const key = `${setting}\n${sub}`;
165
+ if (testReadFailuresFired.has(key))
166
+ return false;
167
+ if (testReadFailuresFired.size >= TEST_READ_FAILURE_FIRED_LIMIT) {
168
+ if (!testReadFailuresFullLogged) {
169
+ testReadFailuresFullLogged = true;
170
+ console.warn(`[flair] test-only read-failure hook fired state reached its ${TEST_READ_FAILURE_FIRED_LIMIT}-pair limit; ` +
171
+ "no further test read failures will be injected in this process.");
172
+ }
173
+ return false;
174
+ }
175
+ testReadFailuresFired.add(key);
176
+ return true;
177
+ }
178
+ /** The fired-subject set's current size. Exported for the bound's unit test. */
179
+ export function testReadFailureFiredCount() {
180
+ return testReadFailuresFired.size;
181
+ }
133
182
  /**
134
183
  * Should an unknown IdP subject be JIT-provisioned into a new Principal+
135
184
  * Credential? Gated by an explicit, auditable trust anchor — an OPEN JIT-provision
@@ -163,6 +212,10 @@ function jitProvisionEnabled() {
163
212
  * `undefined` — so existing callers/tests that don't pass one see the exact
164
213
  * same `{ agentId, isAdmin }` shape as before this field existed.
165
214
  *
215
+ * `allowJitProvision` (default true) is false for a read-only caller such as
216
+ * `tools/list`: a subject with no matching credential resolves to null instead
217
+ * of creating a principal.
218
+ *
166
219
  * When a Credential maps the sub, the mapped principal must exist and be
167
220
  * active — the rule the Ed25519 path applies (resources/agent-auth.ts,
168
221
  * `isPrincipalDeactivated`) — and its record is read on every resolution, so a
@@ -190,10 +243,10 @@ function jitProvisionEnabled() {
190
243
  * the mapped principal is deactivated or missing, or when the credential or
191
244
  * principal could not be read.
192
245
  */
193
- export async function resolveAgentFromSub(sub, clientId) {
194
- return (await resolveMapping(sub, clientId))?.agent ?? null;
246
+ export async function resolveAgentFromSub(sub, clientId, allowJitProvision = true) {
247
+ return (await resolveMapping(sub, clientId, allowJitProvision))?.agent ?? null;
195
248
  }
196
- async function resolveMapping(sub, clientId) {
249
+ async function resolveMapping(sub, clientId, allowJitProvision = true) {
197
250
  if (!sub)
198
251
  return null;
199
252
  // 1. Existing IdP credential → its principalId is the Agent id.
@@ -208,6 +261,9 @@ async function resolveMapping(sub, clientId) {
208
261
  let mapped = null;
209
262
  let refused = null;
210
263
  try {
264
+ if (testReadFailure(TEST_CREDENTIAL_READ_FAIL_SUB_ENV, sub)) {
265
+ throw new Error("test-only fault: the IdP credential read failed");
266
+ }
211
267
  for await (const cred of databases.flair.Credential.search({
212
268
  conditions: [
213
269
  { attribute: "kind", comparator: "equals", value: "idp" },
@@ -228,7 +284,7 @@ async function resolveMapping(sub, clientId) {
228
284
  }
229
285
  if (mapped) {
230
286
  const principalId = credentialPrincipalId(mapped);
231
- const principal = await requireActivePrincipal(principalId);
287
+ const principal = await requireActivePrincipal(principalId, sub);
232
288
  const resolved = { agentId: principalId, isAdmin: agentRecordIsAdmin(principal) };
233
289
  if (clientId)
234
290
  resolved.clientId = clientId;
@@ -238,8 +294,10 @@ async function resolveMapping(sub, clientId) {
238
294
  throw new PrincipalRefusedError(-32001, credentialRefusal(`the IdP credential for this token's subject (id '${refused.id}')`, refused));
239
295
  }
240
296
  // 2. No matching Credential(kind:"idp", idpSubject:sub) row. JIT-provision
241
- // only behind the explicit trust anchor.
242
- if (!jitProvisionEnabled())
297
+ // only behind the explicit trust anchor, and only for a caller that may
298
+ // create a principal — `tools/list` passes allowJitProvision:false, since
299
+ // a listing must not write.
300
+ if (!allowJitProvision || !jitProvisionEnabled())
243
301
  return null;
244
302
  try {
245
303
  const { principalId, credential } = await jitProvisionPrincipal(sub);
@@ -328,9 +386,12 @@ export class PrincipalRefusedError extends Error {
328
386
  * never elevates on its own. This surface is gated behind FLAIR_MCP_OAUTH and is
329
387
  * default-OFF.
330
388
  */
331
- async function requireActivePrincipal(principalId) {
389
+ async function requireActivePrincipal(principalId, sub = "") {
332
390
  let principal;
333
391
  try {
392
+ if (testReadFailure(TEST_PRINCIPAL_READ_FAIL_SUB_ENV, sub)) {
393
+ throw new Error("test-only fault: the principal read failed");
394
+ }
334
395
  principal = await databases.flair.Agent.get(principalId);
335
396
  }
336
397
  catch {
@@ -395,13 +456,49 @@ export async function mcpHandler(request) {
395
456
  case "ping":
396
457
  return rpcResult(id, {});
397
458
  case "tools/list":
398
- return rpcResult(id, { tools: listToolDefs() });
459
+ return handleToolsList(request, id);
399
460
  case "tools/call":
400
461
  return handleToolCall(request, id, params);
401
462
  default:
402
463
  return rpcError(id, -32601, `method not found: ${rpcMethod}`);
403
464
  }
404
465
  }
466
+ /**
467
+ * tools/list: the tools advertised to this request's caller. The caller is
468
+ * resolved the way handleToolCall resolves it (same sub lookup, same
469
+ * active-principal rule), except that listing never JIT-provisions: for a
470
+ * mapped subject each tool's `tools/list` gate is decided for the agent the
471
+ * call would run as, while an unmapped subject lists with no principal even
472
+ * when JIT provisioning is on (a call by it may provision one), and gets no
473
+ * gated tool. A resolution that fails or is refused is answered with the
474
+ * JSON-RPC error a tools/call of a known tool by the same caller gets, and no
475
+ * list (flair#2760).
476
+ *
477
+ * JIT provisioning is off here: a listing is a read and must not create a
478
+ * principal.
479
+ */
480
+ async function handleToolsList(request, id) {
481
+ const clientId = typeof request?.mcp?.client_id === "string" ? request.mcp.client_id : undefined;
482
+ let agent;
483
+ try {
484
+ agent = await resolveAgentFromSub(String(request?.mcp?.sub ?? ""), clientId, false);
485
+ }
486
+ catch (err) {
487
+ return resolutionFailure(id, err);
488
+ }
489
+ return rpcResult(id, { tools: await listToolDefs(agent) });
490
+ }
491
+ /**
492
+ * The JSON-RPC error for a caller whose token subject could not be resolved to
493
+ * a principal: a refusal's own code and message, otherwise a generic
494
+ * `unavailable` error. tools/list and tools/call both answer with it.
495
+ */
496
+ function resolutionFailure(id, err) {
497
+ if (err instanceof PrincipalRefusedError)
498
+ return rpcError(id, err.rpcCode, err.message);
499
+ return rpcError(id, -32000, "unavailable: the token subject could not be resolved to a principal, so the call was refused. " +
500
+ "Retry; if this persists, an operator should check the flair server log.");
501
+ }
405
502
  /**
406
503
  * tools/call: resolve the token sub → flair Agent, then dispatch to the curated
407
504
  * tool. An unresolvable sub is DENIED (not silently run as anonymous or admin).
@@ -437,10 +534,7 @@ async function handleToolCall(request, id, params) {
437
534
  mapping = await resolveMapping(String(sub), clientId);
438
535
  }
439
536
  catch (err) {
440
- if (err instanceof PrincipalRefusedError)
441
- return rpcError(id, err.rpcCode, err.message);
442
- return rpcError(id, -32000, "unavailable: the token subject could not be resolved to a principal, so the call was refused. " +
443
- "Retry; if this persists, an operator should check the flair server log.");
537
+ return resolutionFailure(id, err);
444
538
  }
445
539
  if (!mapping) {
446
540
  // Sub verified by the AS but not mapped to a flair Agent (and JIT disabled /
@@ -29,17 +29,17 @@
29
29
  * Read from `FLAIR_MCP_OAUTH` — truthy values: "1", "true", "yes", "on"
30
30
  * (case-insensitive). Anything else (incl. unset / empty) → OFF.
31
31
  *
32
- * ASYMMETRY (load-bearing, flair#1152, measured on oauth 2.5.0): config.yaml's
33
- * `mcp.enabled: ${FLAIR_MCP_OAUTH}` hands the SAME env var to
32
+ * ASYMMETRY (load-bearing, flair#1152, measured on @harperfast/oauth 2.9.0):
33
+ * config.yaml's `mcp.enabled: ${FLAIR_MCP_OAUTH}` hands the SAME env var to
34
34
  * @harperfast/oauth, but the two readers accept DIFFERENT vocabularies. The
35
- * component's coerceConfigBoolean takes ONLY "true"/"false" and DELETES any
36
- * other string (unresolved placeholder, "1", "yes", garbage) so its disabled
37
- * default applies; this function takes 1/true/yes/on. Consequences:
38
- * - "true" is the ONE value that enables both sides (`flair mcp enable`
39
- * stages exactly that).
40
- * - "1"/"yes"/"on" turn flair's /mcp handler ON while the component AS
41
- * stays OFF — fail-closed broken-on (every request 401s, no AS
42
- * advertised).
35
+ * component's coerceConfigBoolean trims and lowercases, mapping "true"/"false"
36
+ * to a boolean, and normalizeBooleanField deletes strings it cannot coerce
37
+ * (unresolved placeholder, "1", "yes", garbage), so its disabled default
38
+ * applies (dist/lib/config.js); this function takes 1/true/yes/on.
39
+ * Consequences:
40
+ * - "true" is accepted by both readers.
41
+ * - "1"/"yes"/"on" make this reader true while the component deletes the
42
+ * value and stays off; /mcp is not mounted.
43
43
  * - garbage (e.g. "maybe") disables BOTH: the component deletes it, this
44
44
  * stays false, no /mcp handler exists — no data path (flair's own
45
45
  * discovery documents still serve whenever this flag is off, by design).
@@ -60,12 +60,10 @@ export function mcpOAuthEnabled() {
60
60
  * the client-controlled Host header) is the audience-confusion defense called
61
61
  * out in the plugin's production checklist.
62
62
  *
63
- * Configurable via `FLAIR_MCP_ISSUER` (fall back to `FLAIR_PUBLIC_URL`, which the
64
- * XAA token path already uses as the canonical public base). No hardcoded
65
- * default — an operator turning the flag on MUST set the public origin.
63
+ * Configured via `FLAIR_MCP_ISSUER`.
66
64
  */
67
65
  export function mcpIssuer() {
68
- const raw = (process.env.FLAIR_MCP_ISSUER ?? process.env.FLAIR_PUBLIC_URL ?? "").trim();
66
+ const raw = (process.env.FLAIR_MCP_ISSUER ?? "").trim();
69
67
  return raw || undefined;
70
68
  }
71
69
  /**