@tpsdev-ai/flair 0.59.0 → 0.62.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 (259) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +12 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +991 -248
  10. package/dist/commands/agent.js +224 -43
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +592 -146
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +97 -35
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +41 -10
  59. package/dist/lib/doctor-run.js +75 -37
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +4 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +24 -0
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1168 -326
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +76 -12
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +321 -1
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +10 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +751 -143
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +110 -39
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/Presence.js +144 -49
  129. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  130. package/dist/resources/Relationship.js +23 -0
  131. package/dist/resources/SemanticSearch.js +63 -32
  132. package/dist/resources/Soul.js +189 -76
  133. package/dist/resources/TeamDirectory.js +35 -0
  134. package/dist/resources/WorkspaceState.js +21 -1
  135. package/dist/resources/XAA.js +181 -63
  136. package/dist/resources/agent-auth.js +40 -15
  137. package/dist/resources/auth-middleware.js +400 -161
  138. package/dist/resources/ed25519-auth.js +1 -1
  139. package/dist/resources/embedding-space-guard.js +366 -72
  140. package/dist/resources/engine-version-stamp-boot.js +53 -0
  141. package/dist/resources/federation-classify.js +72 -0
  142. package/dist/resources/federation-crypto.js +5 -5
  143. package/dist/resources/federation-retry-lib.js +135 -0
  144. package/dist/resources/grant-visibility.js +135 -0
  145. package/dist/resources/harper-routing.js +83 -0
  146. package/dist/resources/health.js +120 -18
  147. package/dist/resources/host-source-citation.js +49 -0
  148. package/dist/resources/host-source-visibility.js +7 -6
  149. package/dist/resources/instance-create-lock.js +17 -0
  150. package/dist/resources/instance-identity.js +23 -0
  151. package/dist/resources/instruction-version-record.js +343 -0
  152. package/dist/resources/key-lock.js +3 -3
  153. package/dist/resources/mcp-handler.js +36 -8
  154. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  155. package/dist/resources/mcp-oauth.js +23 -6
  156. package/dist/resources/mcp-tool-arguments.js +4 -6
  157. package/dist/resources/mcp-tools.js +128 -19
  158. package/dist/resources/memory-bootstrap-lib.js +5 -15
  159. package/dist/resources/memory-declared-attributes.js +3 -1
  160. package/dist/resources/memory-deletion-history.js +55 -0
  161. package/dist/resources/memory-durability.js +54 -0
  162. package/dist/resources/memory-embed-hash.js +88 -0
  163. package/dist/resources/memory-embedding-value.js +8 -0
  164. package/dist/resources/memory-host-source.js +27 -5
  165. package/dist/resources/memory-id-guard.js +75 -0
  166. package/dist/resources/memory-redaction.js +236 -0
  167. package/dist/resources/memory-supplied-vector.js +72 -0
  168. package/dist/resources/memory-write-lock.js +310 -0
  169. package/dist/resources/memory-write-response.js +139 -0
  170. package/dist/resources/migrations/data-dir.js +74 -16
  171. package/dist/resources/migrations/dir-safety.js +1 -1
  172. package/dist/resources/migrations/embedding-stamp.js +193 -79
  173. package/dist/resources/migrations/export.js +1 -0
  174. package/dist/resources/migrations/graph-heal.js +18 -25
  175. package/dist/resources/migrations/lock.js +7 -1
  176. package/dist/resources/migrations/snapshot.js +1 -0
  177. package/dist/resources/migrations/source-fields.js +5 -5
  178. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  179. package/dist/resources/migrations/visibility-backfill.js +29 -29
  180. package/dist/resources/object-body-guard.js +33 -0
  181. package/dist/resources/org-event-created-at.js +133 -0
  182. package/dist/resources/originator-instance.js +39 -7
  183. package/dist/resources/owner-delete-recheck.js +78 -0
  184. package/dist/resources/owner-field-guard.js +39 -5
  185. package/dist/resources/owner-scoped-write-policy.js +212 -0
  186. package/dist/resources/owner-scoped-writes.js +58 -0
  187. package/dist/resources/presence-receipt.js +236 -0
  188. package/dist/resources/promotion-stamp.js +47 -12
  189. package/dist/resources/record-owner-guard.js +74 -26
  190. package/dist/resources/record-types.js +1 -1
  191. package/dist/resources/relay-ops.js +78 -6
  192. package/dist/resources/replay-store.js +96 -19
  193. package/dist/resources/request-target.js +136 -0
  194. package/dist/resources/request-transaction.js +35 -0
  195. package/dist/resources/search-readiness.js +4 -1
  196. package/dist/resources/seed-ids.js +9 -0
  197. package/dist/resources/seed-reservation.js +117 -0
  198. package/dist/resources/semantic-retrieval-core.js +20 -9
  199. package/dist/resources/skill-manifest.js +20 -11
  200. package/dist/resources/skill-subject.js +53 -0
  201. package/dist/resources/skill-version-write.js +432 -0
  202. package/dist/resources/skill-write-fault.js +17 -0
  203. package/dist/resources/skill-write-policy.js +67 -0
  204. package/dist/resources/skill-write.js +67 -7
  205. package/dist/resources/table-helpers.js +10 -7
  206. package/dist/resources/team-directory.js +248 -0
  207. package/dist/resources/tool-descriptors/index.js +69 -8
  208. package/dist/resources/txn-pause-point.js +118 -0
  209. package/dist/resources/usage-recording.js +171 -63
  210. package/dist/resources/write-back.js +218 -0
  211. package/dist/src/engine-version-contract.js +1 -0
  212. package/dist/src/keystore.js +72 -0
  213. package/dist/src/lib/agent-home-fields.js +132 -0
  214. package/dist/src/lib/agent-id-rule.js +46 -0
  215. package/dist/src/lib/agent-key-register.js +80 -0
  216. package/dist/src/lib/atomic-write.js +256 -0
  217. package/dist/src/lib/credential-status-rule.js +78 -0
  218. package/dist/src/lib/expired-by-agent.js +37 -0
  219. package/dist/src/lib/flair-agent-role.js +4 -0
  220. package/dist/src/lib/idp-mapping-rule.js +81 -0
  221. package/dist/src/lib/instance-identity-row.js +20 -0
  222. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  223. package/dist/src/lib/memory-attributes.js +2 -0
  224. package/dist/src/lib/memory-id-policy.js +46 -0
  225. package/dist/src/lib/principal-status.js +29 -0
  226. package/dist/src/lib/proto-safe-record.js +42 -0
  227. package/dist/src/lib/reembed-server-support.js +66 -0
  228. package/dist/src/lib/scheduler-platform.js +10 -6
  229. package/dist/src/lib/systemd-agent-id.js +38 -0
  230. package/docs/access-control.md +146 -45
  231. package/docs/api-reference.md +46 -11
  232. package/docs/auth.md +6 -12
  233. package/docs/bridges.md +11 -0
  234. package/docs/claude-code.md +34 -4
  235. package/docs/deploying-on-fabric.md +70 -0
  236. package/docs/deployment.md +2 -0
  237. package/docs/embedding-in-a-harper-app.md +1 -1
  238. package/docs/federation.md +33 -2
  239. package/docs/hosted-on-fabric.md +43 -36
  240. package/docs/integrations.md +5 -5
  241. package/docs/mcp-clients.md +5 -2
  242. package/docs/n8n.md +17 -11
  243. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  244. package/docs/notes/mcp-oauth-model2.md +34 -5
  245. package/docs/quickstart-fabric.md +2 -2
  246. package/docs/quickstart.md +9 -1
  247. package/docs/releasing.md +12 -6
  248. package/docs/rem.md +8 -0
  249. package/docs/secrets-and-keys.md +19 -2
  250. package/docs/standalone-local.md +1 -0
  251. package/docs/supply-chain-policy.md +13 -3
  252. package/docs/upgrade.md +32 -6
  253. package/package.json +10 -5
  254. package/schemas/agent-key-registration.graphql +22 -0
  255. package/schemas/agent.graphql +3 -0
  256. package/schemas/federation.graphql +38 -1
  257. package/schemas/memory.graphql +84 -5
  258. package/schemas/oauth.graphql +19 -0
  259. package/schemas/schema.graphql +2 -0
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Transaction helper for single-row Soul resource history (flair#2139 slice 1).
3
+ */
4
+ import { createHash } from "node:crypto";
5
+ import { databases } from "harper";
6
+ import { authorizeSoulWrite } from "./soul-write-policy.js";
7
+ import { authorizeSkillVersionWrite } from "./skill-write-policy.js";
8
+ import { withKeyLock } from "./key-lock.js";
9
+ import { withOwnedTransaction } from "./request-transaction.js";
10
+ import { maybeThrowSkillWriteFault } from "./skill-write-fault.js";
11
+ import { PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
12
+ export const INSTRUCTION_VERSION_TABLE = "InstructionVersion";
13
+ /**
14
+ * The fields the record digest covers, in this exact order. `recordHash` is
15
+ * excluded (it is the digest), and every other field is included, including
16
+ * the preceding record digest (`previousVersionHash`), so removing a field or
17
+ * reordering the list breaks every chain.
18
+ */
19
+ export const RECORD_HASH_FIELDS = [
20
+ "id",
21
+ "subjectType",
22
+ "subjectId",
23
+ "agentId",
24
+ "key",
25
+ "version",
26
+ "kind",
27
+ "rowId",
28
+ "valueHash",
29
+ "previousVersionHash",
30
+ "soulSnapshot",
31
+ "memoryId",
32
+ "visibility",
33
+ "actorKind",
34
+ "actorId",
35
+ "sourceClass",
36
+ "createdAt",
37
+ "guarded",
38
+ "expectedVersion",
39
+ ];
40
+ /** A field as it enters the canonical serialization: bigint → decimal string, undefined → null. */
41
+ function normalizeField(value) {
42
+ if (typeof value === "bigint")
43
+ return value.toString();
44
+ return value === undefined ? null : value;
45
+ }
46
+ /** sha256 of the deterministic canonical serialization of a version record, excluding recordHash. */
47
+ export function recordDigest(record) {
48
+ const canonical = JSON.stringify(RECORD_HASH_FIELDS.map((field) => [field, normalizeField(record[field])]));
49
+ return createHash("sha256").update(canonical, "utf8").digest("hex");
50
+ }
51
+ /** sha256 of the exact UTF-8 value bytes; null when there is no value (a tombstone). */
52
+ export function valueDigest(value) {
53
+ if (typeof value !== "string")
54
+ return null;
55
+ return createHash("sha256").update(value, "utf8").digest("hex");
56
+ }
57
+ /** The addressable version id: subjectType + subjectId + sequence. Never a content hash. */
58
+ export function versionId(subjectType, subjectId, sequence) {
59
+ return `${subjectType}:${subjectId}:${sequence.toString()}`;
60
+ }
61
+ /**
62
+ * Read authority by subject type, default-deny: slice 1 authorizes `soul` only
63
+ * (under Soul's verified-agent rule). A later skill slice adds `skill` here and
64
+ * resolves it from Memory's owner/non-private rule, never from Soul's.
65
+ */
66
+ export const AUTHORIZED_SUBJECT_TYPES = new Set(["soul"]);
67
+ /** Whether a version row's subjectType may be read. An unrecognized type is denied. */
68
+ export function subjectTypeReadable(subjectType) {
69
+ return typeof subjectType === "string" && AUTHORIZED_SUBJECT_TYPES.has(subjectType);
70
+ }
71
+ /** Canonical subject for a Soul row. */
72
+ export function soulSubjectId(agentId, key) {
73
+ return agentId.includes(":") || key.includes(":")
74
+ ? `:${JSON.stringify([agentId, key])}`
75
+ : `${agentId}:${key}`;
76
+ }
77
+ /** The subject type of a skill-tagged Memory row's version chain (flair#2139 S2). */
78
+ export const SKILL_SUBJECT_TYPE = "skill";
79
+ /**
80
+ * Skill references require a nonempty owner and explicit private/shared visibility.
81
+ */
82
+ export function skillRefReadable(ref, readerId) {
83
+ if (!ref || typeof ref !== "object")
84
+ return false;
85
+ if (typeof ref.agentId !== "string" || ref.agentId.length === 0)
86
+ return false;
87
+ if (ref.visibility !== PRIVATE_VISIBILITY && ref.visibility !== SHARED_VISIBILITY)
88
+ return false;
89
+ return ref.agentId === readerId || ref.visibility === SHARED_VISIBILITY;
90
+ }
91
+ /** A version row carries the expectedVersion it compared iff it is guarded; otherwise null. */
92
+ export function expectedVersionOf(input) {
93
+ return input.expectedVersion ?? null;
94
+ }
95
+ function jsonResponse(status, body) {
96
+ return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
97
+ }
98
+ function staleHeadResponse(expected, head) {
99
+ return jsonResponse(409, {
100
+ error: "instruction_version_head_mismatch",
101
+ message: "the subject's head has changed since the version you compared; re-read and retry",
102
+ expectedVersion: expected,
103
+ currentVersion: head ? head.id : null,
104
+ });
105
+ }
106
+ /** Thrown when the caller's row mutation returns a non-success Response, so the append aborts. */
107
+ class RowMutationDenied extends Error {
108
+ response;
109
+ constructor(response) {
110
+ super("instruction version: the row mutation failed, so the append was rolled back");
111
+ this.response = response;
112
+ }
113
+ }
114
+ function isTableLike(table) {
115
+ return !!table && typeof table.search === "function" && typeof table.create === "function";
116
+ }
117
+ /**
118
+ * The subject's current head, or null when it has no history yet.
119
+ * The append caller reads under its subject lock and transaction after resetting
120
+ * the cached read snapshot; the read resource uses the same raw handle without a lock.
121
+ */
122
+ 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");
126
+ for await (const row of table.search({
127
+ conditions: [
128
+ { attribute: "subjectType", comparator: "equals", value: subjectType },
129
+ { attribute: "subjectId", comparator: "equals", value: subjectId },
130
+ ...(soulIdentity ? [
131
+ { attribute: "agentId", comparator: "equals", value: soulIdentity.agentId },
132
+ { attribute: "key", comparator: "equals", value: soulIdentity.key },
133
+ ] : []),
134
+ ],
135
+ sort: { attribute: "version", descending: true },
136
+ limit: 1,
137
+ }, shared)) {
138
+ return row;
139
+ }
140
+ return null;
141
+ }
142
+ async function readSoulHead(agentId, key, shared) {
143
+ const identity = { agentId, key };
144
+ const subjectId = soulSubjectId(agentId, key);
145
+ const head = await readHead("soul", subjectId, shared, identity);
146
+ if (head || subjectId === `${agentId}:${key}`)
147
+ return head;
148
+ return readHead("soul", `${agentId}:${key}`, shared, identity);
149
+ }
150
+ /** Server-derived attribution for an authorization outcome; never from a body. */
151
+ const UNATTRIBUTED = { actorKind: "internal", actorId: null, sourceClass: "internal" };
152
+ /**
153
+ * Dispatch authorization and attribution by subject type (flair#2139 S2). Soul
154
+ * uses Soul's operator/internal rule; skill uses the shared skill-write
155
+ * credential class (operator / agent / internal). An unrecognized subject type
156
+ * is refused, not silently attributed.
157
+ */
158
+ export async function resolveVersionAuthorization(subjectType, context) {
159
+ if (subjectType === "soul") {
160
+ const { auth, source, denied } = await authorizeSoulWrite(context);
161
+ if (denied)
162
+ return { attribution: UNATTRIBUTED, denied };
163
+ return {
164
+ attribution: {
165
+ actorKind: source === "operator" ? "operator" : "internal",
166
+ actorId: auth.kind === "agent" ? auth.agentId : null,
167
+ sourceClass: source,
168
+ },
169
+ denied: null,
170
+ };
171
+ }
172
+ if (subjectType === "skill") {
173
+ const { auth, source, denied } = await authorizeSkillVersionWrite(context);
174
+ if (denied)
175
+ return { attribution: UNATTRIBUTED, denied };
176
+ return {
177
+ attribution: {
178
+ actorKind: source,
179
+ actorId: auth.kind === "agent" ? auth.agentId : null,
180
+ sourceClass: source,
181
+ },
182
+ denied: null,
183
+ };
184
+ }
185
+ throw new Error(`instruction version: unknown subject type: ${String(subjectType)}`);
186
+ }
187
+ const LOCK_NAMESPACE = "flair-instruction-version";
188
+ /** Bounded lock wait. */
189
+ const LOCK_ATTEMPTS = 200;
190
+ const LOCK_WAIT_MS = 10;
191
+ export async function recordVersion(ctx, request, mutateRow) {
192
+ const store = databases.flair?.InstructionVersion?.primaryStore;
193
+ let outcome;
194
+ try {
195
+ outcome = await withKeyLock(store, [LOCK_NAMESPACE, request.subjectType], () => withOwnedTransaction(ctx, async (shared) => {
196
+ const authorization = await resolveVersionAuthorization(request.subjectType, shared);
197
+ if (authorization.denied)
198
+ return { ok: false, response: authorization.denied };
199
+ const attribution = authorization.attribution;
200
+ const input = "prepare" in request ? await request.prepare(shared) : request;
201
+ if (input === null) {
202
+ const result = await mutateRow(shared);
203
+ if (result instanceof Response && result.status >= 300)
204
+ throw new RowMutationDenied(result);
205
+ return { ok: true, result, version: "" };
206
+ }
207
+ if (input instanceof Response)
208
+ return { ok: false, response: input };
209
+ if (input.subjectType !== request.subjectType)
210
+ throw new Error("instruction version: subject type changed during preparation");
211
+ const expected = expectedVersionOf(input);
212
+ const table = databases.flair?.InstructionVersion;
213
+ if (!isTableLike(table))
214
+ throw new Error("flair: the InstructionVersion table is unavailable");
215
+ const identityChanged = input.subjectType === "soul" && input.previousSubjectId != null && ((input.previousAgentId ?? input.agentId) !== input.agentId || input.previousKey !== input.key);
216
+ if (identityChanged) {
217
+ const souls = databases.flair?.Soul;
218
+ if (typeof souls?.search !== "function")
219
+ throw new Error("flair: the Soul table is unavailable");
220
+ for await (const row of souls.search({ conditions: [
221
+ { attribute: "agentId", comparator: "equals", value: input.agentId },
222
+ { attribute: "key", comparator: "equals", value: input.key },
223
+ ] }, shared)) {
224
+ if (String(row.id) !== input.rowId) {
225
+ return { ok: false, response: jsonResponse(409, { error: "soul_subject_occupied" }) };
226
+ }
227
+ }
228
+ }
229
+ const head = input.subjectType === "soul"
230
+ ? await readSoulHead(input.agentId, input.key ?? "", shared)
231
+ : await readHead(input.subjectType, input.subjectId, shared);
232
+ if (expected != null && (!head || head.id !== expected)) {
233
+ return { ok: false, response: staleHeadResponse(expected, head) };
234
+ }
235
+ const result = await mutateRow(shared);
236
+ if (result instanceof Response && result.status >= 300)
237
+ throw new RowMutationDenied(result);
238
+ // Only a Soul record carries a full stored snapshot; a skill record
239
+ // holds hashes and physical references, never a second content copy.
240
+ if (input.subjectType === "soul" && input.kind !== "delete" && input.snapshot) {
241
+ const row = input.snapshot();
242
+ if (!row)
243
+ throw new Error("instruction version: stored snapshot unavailable");
244
+ input.soulSnapshot = JSON.stringify(row);
245
+ input.value = typeof row.value === "string" ? row.value : null;
246
+ }
247
+ if (identityChanged) {
248
+ const previousSubjectId = soulSubjectId(input.previousAgentId ?? input.agentId, input.previousKey ?? "");
249
+ const oldHead = await readSoulHead(input.previousAgentId ?? input.agentId, input.previousKey ?? "", shared);
250
+ const oldSequence = oldHead ? BigInt(oldHead.version) + 1n : 1n;
251
+ const oldRecord = {
252
+ id: versionId(input.subjectType, previousSubjectId, oldSequence),
253
+ subjectType: input.subjectType,
254
+ subjectId: previousSubjectId,
255
+ agentId: input.previousAgentId ?? input.agentId,
256
+ key: input.previousKey ?? null,
257
+ version: oldSequence,
258
+ kind: "delete",
259
+ rowId: input.previousRowId ?? input.rowId,
260
+ valueHash: null,
261
+ previousVersionHash: oldHead ? (oldHead.recordHash ?? null) : null,
262
+ soulSnapshot: null,
263
+ memoryId: null,
264
+ visibility: null,
265
+ actorKind: attribution.actorKind,
266
+ actorId: attribution.actorId,
267
+ sourceClass: attribution.sourceClass,
268
+ createdAt: new Date().toISOString(),
269
+ guarded: false,
270
+ expectedVersion: null,
271
+ };
272
+ oldRecord.recordHash = recordDigest(oldRecord);
273
+ await table.create(oldRecord, shared);
274
+ }
275
+ const sequence = head ? BigInt(head.version) + 1n : 1n;
276
+ const id = versionId(input.subjectType, input.subjectId, sequence);
277
+ const record = {
278
+ id,
279
+ subjectType: input.subjectType,
280
+ subjectId: input.subjectId,
281
+ agentId: input.agentId,
282
+ key: input.key ?? null,
283
+ version: sequence,
284
+ kind: input.kind,
285
+ rowId: input.rowId,
286
+ valueHash: input.kind === "delete" ? null : valueDigest(input.value ?? ""),
287
+ previousVersionHash: head ? (head.recordHash ?? null) : null,
288
+ soulSnapshot: input.kind === "delete" ? null : (input.soulSnapshot ?? null),
289
+ memoryId: input.memoryId ?? null,
290
+ visibility: input.visibility ?? null,
291
+ actorKind: attribution.actorKind,
292
+ actorId: attribution.actorId,
293
+ sourceClass: attribution.sourceClass,
294
+ createdAt: new Date().toISOString(),
295
+ guarded: expected != null,
296
+ expectedVersion: expected,
297
+ };
298
+ record.recordHash = recordDigest(record);
299
+ // flair#2139 S2 — test-only per-step fault injection (see
300
+ // skill-write-fault.ts). Fires after the Memory-side successor/close
301
+ // writes rode this same transaction, so the append failure aborts them
302
+ // too: no successor, no close, no version.
303
+ if (input.subjectType === "skill")
304
+ maybeThrowSkillWriteFault("append", input.agentId);
305
+ await table.create(record, shared);
306
+ return { ok: true, result, version: id };
307
+ }), LOCK_ATTEMPTS, LOCK_WAIT_MS);
308
+ }
309
+ catch (err) {
310
+ if (err instanceof RowMutationDenied)
311
+ return { ok: false, response: err.response };
312
+ // A head-read, append or commit failure aborts the whole transaction; report
313
+ // unavailable rather than a success, so no caller reads a missing version as
314
+ // "nothing happened" (fail-closed).
315
+ console.error("instruction-version-record: the append transaction failed and was rolled back", { err });
316
+ return {
317
+ ok: false,
318
+ response: jsonResponse(500, {
319
+ error: "instruction_version_append_failed",
320
+ message: "the version history append failed and the write was rolled back",
321
+ }),
322
+ };
323
+ }
324
+ if (outcome.kind === "busy") {
325
+ return {
326
+ ok: false,
327
+ response: jsonResponse(409, {
328
+ error: "instruction_version_busy",
329
+ message: "another instruction write is still in progress; retry",
330
+ }),
331
+ };
332
+ }
333
+ if (outcome.kind === "unavailable") {
334
+ return {
335
+ ok: false,
336
+ response: jsonResponse(503, {
337
+ error: "instruction_version_lock_unavailable",
338
+ message: "the InstructionVersion store has no per-key lock, so the write was refused",
339
+ }),
340
+ };
341
+ }
342
+ return outcome.value;
343
+ }
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * key-lock.ts — run a function while holding one key of a Harper table's
3
- * primary-store lock (`tryLock` / `unlock`: per key, shared by the threads of
4
- * one Harper process; resources/replay-store.ts uses the same primitive).
5
- * No Harper imports.
3
+ * primary-store lock (`tryLock` / `unlock`). Within one Harper process,
4
+ * the lock is per key and shared by its threads
5
+ * (resources/replay-store.ts uses the same primitive). No Harper imports.
6
6
  */
7
7
  /**
8
8
  * Try the lock up to `attempts` times, `waitMs` apart. Holding it, drop the
@@ -30,6 +30,8 @@ import { checkToolArguments, withoutNullArguments } from "./mcp-tool-arguments.j
30
30
  import { agentRecordIsAdmin } from "./agent-admin.js";
31
31
  import { isPrincipalDeactivated } from "./agent-auth.js";
32
32
  import { stampOriginatorOnCreate } from "./originator-instance.js";
33
+ import { invalidAgentIdMessage, isValidAgentId } from "../src/lib/agent-id-rule.js";
34
+ import { credentialMapsPrincipal, credentialPrincipalId, credentialRefusal } from "../src/lib/credential-status-rule.js";
33
35
  import { resolveVersion } from "./version.js";
34
36
  // The MCP protocol revision we implement (initialize handshake).
35
37
  const PROTOCOL_VERSION = "2025-06-18";
@@ -168,17 +170,23 @@ function jitProvisionEnabled() {
168
170
  * principal is deactivated. If that read fails, or the credential lookup itself
169
171
  * fails, resolution is refused. An unreadable answer is never taken as
170
172
  * "allowed", and never as "no mapping": JIT provisioning runs only for a
171
- * subject the credential lookup answered for. Resolution writes nothing to an
172
- * existing credential; the handler updates its `lastUsedAt`, best effort, after
173
- * a tool has run (handleToolCall).
173
+ * subject with no matching `Credential(kind:"idp", idpSubject:sub)` row. Any
174
+ * matching IdP row prevents JIT fallback. The resolver scans the matching rows
175
+ * for one that maps the subject — its `status` is exactly "active" and it
176
+ * names a principal (src/lib/credential-status-rule.ts, shared with the linker
177
+ * and XAA) — and refuses the call by name only if none maps. Resolution writes
178
+ * nothing to an existing credential; the handler
179
+ * updates its `lastUsedAt`, best effort, after a tool has run (handleToolCall).
174
180
  *
175
181
  * Returns:
176
182
  * - `{ agentId, isAdmin, clientId? }` when a Credential maps the sub to an
177
183
  * existing, active Agent.
178
- * - null when no Credential maps the sub AND JIT-provisioning is disabled or
179
- * failed → the handler denies the tool call (sub is unresolvable).
184
+ * - null when NO matching `Credential(kind:"idp", idpSubject:sub)` row
185
+ * exists AND JIT-provisioning is disabled or failed → the handler denies
186
+ * the tool call (sub is unresolvable).
180
187
  *
181
188
  * Throws `PrincipalRefusedError` (the handler returns its JSON-RPC error) when
189
+ * Credential rows match the sub but none is active and names a principal, when
182
190
  * the mapped principal is deactivated or missing, or when the credential or
183
191
  * principal could not be read.
184
192
  */
@@ -189,7 +197,16 @@ async function resolveMapping(sub, clientId) {
189
197
  if (!sub)
190
198
  return null;
191
199
  // 1. Existing IdP credential → its principalId is the Agent id.
200
+ //
201
+ // flair#2503 — any matching IdP row prevents JIT fallback. A row maps the
202
+ // subject only when its `status` is exactly "active" and it names a principal
203
+ // (src/lib/credential-status-rule.ts, shared with the linker and XAA's
204
+ // jwt-bearer grant). The loop scans the matching rows and uses the first one
205
+ // that maps the subject; only if none maps is the call REFUSED by name below,
206
+ // naming the first row read, and JIT provisioning does not run. JIT runs only
207
+ // when no `Credential(kind:"idp", idpSubject:sub)` row matches.
192
208
  let mapped = null;
209
+ let refused = null;
193
210
  try {
194
211
  for await (const cred of databases.flair.Credential.search({
195
212
  conditions: [
@@ -197,10 +214,12 @@ async function resolveMapping(sub, clientId) {
197
214
  { attribute: "idpSubject", comparator: "equals", value: sub },
198
215
  ],
199
216
  })) {
200
- if (cred?.principalId && cred.status !== "revoked") {
217
+ if (credentialMapsPrincipal(cred)) {
201
218
  mapped = cred;
202
219
  break;
203
220
  }
221
+ if (!refused)
222
+ refused = cred;
204
223
  }
205
224
  }
206
225
  catch {
@@ -208,14 +227,18 @@ async function resolveMapping(sub, clientId) {
208
227
  "Retry; if this persists, an operator should check the flair server log.");
209
228
  }
210
229
  if (mapped) {
211
- const principalId = String(mapped.principalId);
230
+ const principalId = credentialPrincipalId(mapped);
212
231
  const principal = await requireActivePrincipal(principalId);
213
232
  const resolved = { agentId: principalId, isAdmin: agentRecordIsAdmin(principal) };
214
233
  if (clientId)
215
234
  resolved.clientId = clientId;
216
235
  return { agent: resolved, credential: mapped };
217
236
  }
218
- // 2. No mapping. JIT-provision only behind the explicit trust anchor.
237
+ if (refused) {
238
+ throw new PrincipalRefusedError(-32001, credentialRefusal(`the IdP credential for this token's subject (id '${refused.id}')`, refused));
239
+ }
240
+ // 2. No matching Credential(kind:"idp", idpSubject:sub) row. JIT-provision
241
+ // only behind the explicit trust anchor.
219
242
  if (!jitProvisionEnabled())
220
243
  return null;
221
244
  try {
@@ -241,6 +264,11 @@ async function resolveMapping(sub, clientId) {
241
264
  async function jitProvisionPrincipal(sub) {
242
265
  const now = new Date().toISOString();
243
266
  const principalId = `agt_mcp_${sub.replace(/[^a-zA-Z0-9]/g, "_").slice(0, 24)}_${randomBytes(4).toString("hex")}`;
267
+ // flair#2359 — the shared agent-ID rule. The id above is built to conform,
268
+ // but the rule is enforced on the value that is actually written, so a future
269
+ // change to this construction cannot store an id AgentSeed would refuse.
270
+ if (!isValidAgentId(principalId))
271
+ throw new Error(invalidAgentIdMessage(principalId));
244
272
  // flair#1965 r2: this is a raw Agent create (it bypasses the Agent resource's
245
273
  // post()), so stamp the local instance id here — every create path carries it.
246
274
  const principalRow = {
@@ -0,0 +1,36 @@
1
+ import { guardMcpOAuthEnv, readMcpProviderReadiness } from "../src/lib/mcp-oauth-env-core.js";
2
+ const GUARD_STATE = Symbol.for("flair.mcpOAuthEnvGuard");
3
+ const guardProcess = process;
4
+ const state = guardProcess[GUARD_STATE] ??= {
5
+ decision: { degraded: false, neutralizedVars: [] },
6
+ readiness: readMcpProviderReadiness(process.env),
7
+ decisions: new WeakMap(),
8
+ };
9
+ export function mcpOAuthProviderReadiness() {
10
+ return { ...state.readiness };
11
+ }
12
+ export function runMcpOAuthEnvGuard(env = process.env) {
13
+ const previous = state.decisions.get(env);
14
+ if (previous) {
15
+ state.readiness = previous.readiness;
16
+ state.decision = previous.decision;
17
+ return previous.decision;
18
+ }
19
+ state.readiness = readMcpProviderReadiness(env);
20
+ const decision = state.decision = guardMcpOAuthEnv(env);
21
+ state.decisions.set(env, { decision, readiness: state.readiness });
22
+ if (decision.degraded) {
23
+ console.error(`[mcp-oauth] MCP auth unavailable: ${decision.reason}. ` +
24
+ `The provider was left unconfigured for this process. ` +
25
+ `Set the variable (or re-run: flair mcp enable), then restart.`);
26
+ }
27
+ return decision;
28
+ }
29
+ /** The decision recorded at boot; read by `/mcp` route reporting. */
30
+ export function mcpOAuthDegraded() {
31
+ return state.decision;
32
+ }
33
+ // A unit test can set FLAIR_MCP_NO_AUTOSTART before import to avoid env mutation.
34
+ if (process.env.FLAIR_MCP_NO_AUTOSTART == null) {
35
+ runMcpOAuthEnvGuard();
36
+ }
@@ -6,11 +6,9 @@
6
6
  * urlPath subroute — its OWN dispatch chain, so flair's default auth-middleware
7
7
  * never runs for /mcp and can't clobber the Bearer challenge.
8
8
  *
9
- * ── Default-OFF (byte-identical when off) ───────────────────────────────────
10
- * The route is registered ONLY when `FLAIR_MCP_OAUTH` is truthy. When off, this
11
- * module does NOTHING at load — no `server.http` call, no `@harperfast/oauth`
12
- * import, no config injection. flair's default auth chain and prod behavior are
13
- * unchanged. This is the no-op contract the flag guarantees.
9
+ * With MCP disabled, registration does not mount `/mcp`. At load, the guard
10
+ * clears GitHub credentials when both are present and the redirect is missing,
11
+ * regardless of the flag (unless `FLAIR_MCP_NO_AUTOSTART` is set).
14
12
  *
15
13
  * The `@harperfast/oauth` authorization-server config itself (providers, mcp.*,
16
14
  * DCR gating) lives in `config.yaml` under the `@harperfast/oauth` key, but is
@@ -19,6 +17,11 @@
19
17
  */
20
18
  import * as harper from "harper";
21
19
  import { mcpOAuthEnabled, mcpAuthConfig } from "./mcp-oauth-flag.js";
20
+ // flair#2270: run the degraded-start guard BEFORE the @harperfast/oauth
21
+ // component resolves its config. Imported for its module-load side effect (this
22
+ // module is itself loaded during jsResource boot, ahead of the component);
23
+ // `mcpOAuthDegraded()` is read below to report the state by variable name.
24
+ import { mcpOAuthDegraded } from "./mcp-oauth-env-guard.js";
22
25
  import { checkMcpRateLimit } from "./rate-limit.js";
23
26
  import { MULTI_WORKER_GUARD_HTTP_NAME } from "./multi-worker-guard.js";
24
27
  /**
@@ -132,6 +135,18 @@ export async function registerMcpOAuthRoute(deps = {}) {
132
135
  reason: "Set FLAIR_MCP_OAUTH=true (and an issuer) to serve MCP over HTTP.",
133
136
  });
134
137
  }
138
+ // flair#2270: the install is enabled but a required OAuth variable is
139
+ // missing, so the auth server cannot serve this surface. Do NOT mount a
140
+ // guarded /mcp that could only fail closed against a provider that is not
141
+ // there — report MCP auth unavailable, by variable name.
142
+ const degraded = mcpOAuthDegraded();
143
+ if (degraded.degraded) {
144
+ return decide({
145
+ mounted: false,
146
+ status: "MCP auth unavailable",
147
+ reason: `${degraded.reason}. Set it (or re-run: flair mcp enable), then restart.`,
148
+ });
149
+ }
135
150
  // Boot guard (flair#1021): fail loudly if the operator enabled the flag but
136
151
  // the @harperfast/oauth component is absent from config.yaml. Without it the
137
152
  // authorization server's routes never mount — discovery, authorize, token,
@@ -184,7 +199,9 @@ export async function registerMcpOAuthRoute(deps = {}) {
184
199
  const srv = deps.server ?? (harper.server);
185
200
  // Mount /mcp after the guard.
186
201
  srv.http(withMCPAuth(rateLimitedMcpHandler(handler), {
187
- getConfig: () => mcpAuthConfig(),
202
+ getConfig: () => (deps.harper ?? harper).server?.resources?.get("oauth")?.Resource?.mcpConfig?.enabled === true
203
+ ? mcpAuthConfig()
204
+ : undefined,
188
205
  }), { urlPath: "/mcp", after: MULTI_WORKER_GUARD_HTTP_NAME });
189
206
  console.error(`[mcp-oauth] /mcp mounted (OAuth-guarded); issuer=${config.issuer}`);
190
207
  return decide({ mounted: true });
@@ -18,6 +18,7 @@
18
18
  * tool, as before. withoutNullArguments() then drops null-valued properties so
19
19
  * a tool never forwards a null where its schema declares a type.
20
20
  */
21
+ import { protoSafeRecord } from "../src/lib/proto-safe-record.js";
21
22
  function matches(value, type) {
22
23
  switch (type) {
23
24
  case "string": return typeof value === "string";
@@ -74,10 +75,7 @@ export function checkToolArguments(schema, args) {
74
75
  export function withoutNullArguments(args) {
75
76
  if (typeof args !== "object" || args === null || Array.isArray(args))
76
77
  return {};
77
- const out = {};
78
- for (const [k, v] of Object.entries(args)) {
79
- if (v !== null && v !== undefined)
80
- out[k] = v;
81
- }
82
- return out;
78
+ const src = args;
79
+ const keys = Object.keys(src).filter((k) => src[k] !== null && src[k] !== undefined);
80
+ return protoSafeRecord(src, { keys });
83
81
  }