@tpsdev-ai/flair 0.58.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 (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -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 +1030 -343
  10. package/dist/commands/agent.js +384 -45
  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 +601 -163
  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 +146 -53
  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 +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  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 +120 -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 +27 -2
  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 +1775 -338
  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 +103 -7
  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 +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  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 +227 -64
  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/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -75,6 +75,7 @@
75
75
  * nor exempted with a stated reason. A table added later enters that test's
76
76
  * scope the moment it declares the column — nobody has to know this file exists.
77
77
  */
78
+ import { routedRecordId } from "./request-target.js";
78
79
  /**
79
80
  * Table → the attribute naming the principal that owns a row.
80
81
  *
@@ -121,6 +122,15 @@ export const OWNER_GUARD_EXEMPT = Object.freeze({
121
122
  // writes stamp `authorId` from the authenticated principal; direct resource
122
123
  // reads permit admins and trusted internal callers.
123
124
  MemoryHostSource: "REST writes refused; application writes stamp authorId; direct reads limited to admins and trusted internal callers",
125
+ // Application append-only history; REST writes are refused.
126
+ InstructionVersion: "application append-only; REST writes refused",
127
+ // flair#2266: the private audit log of key registrations. Its `agentId` names
128
+ // the row whose key was registered (the AUDIT TARGET), not the caller — the
129
+ // caller is the admin in `actorId`. Its only application writer is
130
+ // resources/AgentKeyRegister.ts; the Flair resource route
131
+ // (resources/AgentKeyRegistration.ts) admits admin reads and refuses every
132
+ // write. The Harper operations API is a separate raw-table trust root.
133
+ AgentKeyRegistration: "admin-read-only audit log; Flair resource-route writes refused; the registration operation is its only application writer",
124
134
  });
125
135
  /** The verbs that can mutate a record, and therefore need the rule applied. */
126
136
  export const MUTATING_METHODS = Object.freeze(["POST", "PUT", "PATCH", "DELETE"]);
@@ -128,33 +138,41 @@ export function isMutatingMethod(method) {
128
138
  return MUTATING_METHODS.includes(method.toUpperCase());
129
139
  }
130
140
  /**
131
- * Resolve a request path to the guarded table and record id it addresses, or
132
- * null when the path is not a guarded single-record route.
133
- *
134
- * Matches `/<Table>/<id>` ONLY. A collection path (`/<Table>`) addresses no
135
- * existing record, so there is nothing to own and nothing to check — that is the
136
- * "creation is untouched" property, expressed as a parse rather than a special
137
- * case. The table segment is matched EXACTLY so `/SoulFeed/x` can never be read
138
- * as a `Soul` route.
141
+ * Resolve a raw request target to the guarded table and record id it
142
+ * addresses, or null when the target is not one this early check decides.
143
+ *
144
+ * `pathname` is the RAW request path (the target before its `?`). The id is the
145
+ * FULL decoded remainder after the table segment, so an id that itself contains
146
+ * `/`, raw or as `%2F`, resolves to the whole id rather than a shorter prefix.
147
+ *
148
+ * Matches `/<Table>/<id>` ONLY. A bare resource path has no record id; a
149
+ * trailing-slash path is a collection. The table segment is matched EXACTLY so
150
+ * `/SoulFeed/x` can never be read as a `Soul` route.
139
151
  */
140
152
  export function resolveGuardedRecord(pathname) {
141
- const parts = pathname.split("/").filter(Boolean);
142
- if (parts.length < 2)
153
+ const routed = routedRecordId(pathname);
154
+ if (!routed)
155
+ return null; // no record id, or malformed percent-encoding
156
+ return resolveGuardedRecordById(routed.resource, routed.id);
157
+ }
158
+ /**
159
+ * The guarded record for a resource and record id already resolved by Harper's
160
+ * own routing (resources/harper-routing.ts). Null when the resource is not a
161
+ * guarded table, or there is no record id. This is the form
162
+ * the middleware uses at request time, where the id has had Harper's
163
+ * content-type-suffix and property rules applied.
164
+ */
165
+ export function resolveGuardedRecordById(resource, id) {
166
+ if (id == null || id === "")
143
167
  return null;
144
- const table = parts[0];
145
- const ownerField = OWNER_FIELDS[table];
146
- if (!ownerField)
168
+ // Own property only: an inherited name (`constructor`, `__proto__`, …) is not
169
+ // a table with an owner field.
170
+ if (!Object.prototype.hasOwnProperty.call(OWNER_FIELDS, resource))
147
171
  return null;
148
- let id;
149
- try {
150
- id = decodeURIComponent(parts[1]);
151
- }
152
- catch {
153
- return null; // malformed percent-encoding addresses no record we can resolve
154
- }
155
- if (!id)
172
+ const ownerField = OWNER_FIELDS[resource];
173
+ if (!ownerField)
156
174
  return null;
157
- return { table, ownerField, id };
175
+ return { table: resource, ownerField, id };
158
176
  }
159
177
  /**
160
178
  * Decide whether a caller may mutate an already-stored record.
@@ -184,16 +202,46 @@ export function isForbiddenOwnerMutation(record, ownerField, callerAgentId) {
184
202
  * principal: 403 with a body that names only the table.
185
203
  *
186
204
  * One constructor for every place the rule is enforced — the auth middleware
187
- * for `/<Table>/<id>` routes, and resources/relay-ops.ts for a Message POST to
188
- * the collection that reuses an existing message id — so a refused caller gets
189
- * the same response on either route, and it carries nothing from the stored
190
- * row.
205
+ * for `/<Table>/<id>` routes, resources/owner-scoped-write-policy.ts for a
206
+ * non-admin addressed write (POST/PUT/PATCH/DELETE to `/<Table>/<id>`) to an
207
+ * owner-scoped table, and resources/relay-ops.ts for a Message POST to the
208
+ * collection that reuses an existing message id. Carries no stored-row content.
191
209
  */
192
210
  export function ownerMutationRefusal(table) {
193
211
  return new Response(JSON.stringify({
194
212
  error: `forbidden: cannot modify ${table} owned by another principal`,
195
213
  }), { status: 403, headers: { "Content-Type": "application/json" } });
196
214
  }
215
+ /**
216
+ * The refusal for a non-admin PUT, PATCH or DELETE that addresses an
217
+ * owner-scoped table's collection rather than one record: 403 with a body that
218
+ * names only the table (resources/owner-scoped-write-policy.ts).
219
+ */
220
+ export function collectionWriteRefusal(table) {
221
+ return new Response(JSON.stringify({
222
+ error: `forbidden: a non-admin write to ${table} must address one record by its id`,
223
+ }), { status: 403, headers: { "Content-Type": "application/json" } });
224
+ }
225
+ /** The named refusal when a non-admin agent's stored-record read for an owner check fails. */
226
+ export const OWNER_CHECK_UNAVAILABLE_ERROR = "owner_check_unavailable";
227
+ /**
228
+ * Refuse a non-admin agent's write when the stored record its owner check
229
+ * needs cannot be read (resources/owner-field-guard.ts's guard thunk, and the
230
+ * owner-scoped write guard's stored-record read). A numeric 4xx `statusCode`
231
+ * maps to 400; anything else maps to 503. It logs the failure and has no
232
+ * authentication-module dependency, so the owner-scoped write guard can use it
233
+ * without importing that module graph; re-exported by
234
+ * resources/owner-field-guard.ts.
235
+ */
236
+ export function ownerCheckUnavailable(err) {
237
+ console.error("owner-field-guard: the stored record could not be read, so the write was refused", { err });
238
+ const code = err?.statusCode;
239
+ const status = typeof code === "number" && code >= 400 && code < 500 ? 400 : 503;
240
+ return new Response(JSON.stringify({
241
+ error: OWNER_CHECK_UNAVAILABLE_ERROR,
242
+ message: "the stored record could not be read; the write was refused",
243
+ }), { status, headers: { "content-type": "application/json" } });
244
+ }
197
245
  /**
198
246
  * Decide whether a caller may CHANGE the owner field of an already-stored record.
199
247
  *
@@ -363,6 +363,22 @@ export const RECORD_TYPES = {
363
363
  // same reasoning, not by omission.
364
364
  federation: "excluded",
365
365
  },
366
+ // OrgSkillAssignment — flair#2141 S1. Org-scope skill assignments, readable
367
+ // by any verified agent. resources/OrgSkillAssignment.ts gates each write
368
+ // verb itself on the operator or internal source (no record-type-kit
369
+ // attribution idiom). No principal owns a row: `ownerField` names the
370
+ // server-stamped `writer`, which no read scope or attribution mode uses.
371
+ // Instance-local.
372
+ OrgSkillAssignment: {
373
+ table: "OrgSkillAssignment",
374
+ ownerField: "writer",
375
+ identity: "gated",
376
+ readScope: "none",
377
+ attribution: {},
378
+ provenance: false,
379
+ remEligible: false,
380
+ federation: "excluded",
381
+ },
366
382
  };
367
383
  // ─── Composite MCP tools (the second, and only other, reviewed chokepoint) ─
368
384
  //
@@ -387,7 +403,7 @@ export const RECORD_TYPES = {
387
403
  // skill_search — skill-tagged Memory recall (flair#1546), rides SemanticSearch
388
404
  // skill_get — full skill read by id (flair#1546), rides Memory.get
389
405
  //
390
- export const COMPOSITE_MCP_TOOLS = ["bootstrap", "attention", "record_usage", "memory_basement", "memory_restore", "skill_store", "skill_search", "skill_get"];
406
+ export const COMPOSITE_MCP_TOOLS = ["bootstrap", "attention", "record_usage", "memory_basement", "memory_restore", "skill_store", "skill_search", "skill_get", "team_directory"];
391
407
  // ─── Runtime immutability ───────────────────────────────────────────────────
392
408
  // Belt-and-suspenders backstop for the "static, compiled" invariant (see
393
409
  // header doc). TypeScript's `as const satisfies` already gives compile-time
@@ -9,7 +9,10 @@
9
9
  * All authorization decisions are made here against an already-resolved auth
10
10
  * verdict; the resource layer only resolves the verdict and forwards the call.
11
11
  */
12
+ import { withKeyLock } from "./key-lock.js";
13
+ import { withOwnedTransaction } from "./request-transaction.js";
12
14
  import { isForbiddenOwnerMutation, ownerMutationRefusal, OWNER_FIELDS } from "./record-owner-guard.js";
15
+ import { txnPausePoint } from "./txn-pause-point.js";
13
16
  import { capDecision, computeContentHash, isUnconsumed, LOCAL_ORG_SENTINEL, reconcileState, sweepDecision, verifyMessageSignature, } from "./relay-lib.js";
14
17
  // ─── HTTP responses (Response is a web global, not a Harper import) ──────────
15
18
  const json = (status, obj) => new Response(JSON.stringify(obj), { status, headers: { "Content-Type": "application/json" } });
@@ -22,6 +25,37 @@ const BAD_REQUEST = (error) => json(400, { error });
22
25
  const CONFLICT = (error) => json(409, { error, reason: "seq_conflict" });
23
26
  /** Over-cap: a synchronous 4xx that names the reason — backpressure that fails loud. */
24
27
  const INBOX_FULL = (scope) => json(429, { error: "inbox full", reason: "inbox_full", scope });
28
+ /** The message-id or sender lock could not be acquired: the send is refused. */
29
+ const SEND_BUSY = () => json(409, { error: "send in progress", reason: "send_contended" });
30
+ /** Without a per-key lock, serialization within one Harper process is
31
+ * unavailable: the send is refused. */
32
+ const SEND_LOCK_UNAVAILABLE = () => json(503, { error: "send lock unavailable", message: "the Message store has no per-key lock; the send was refused" });
33
+ // ─── send-time serialization ────────────────────────────────────────────────
34
+ /** First element of every relay-send lock key (resources/key-lock.ts), so a send
35
+ * lock never collides with another lock on the database. */
36
+ const SEND_LOCK_NAMESPACE = "flair-relay-send";
37
+ /** Per-lock retry schedule: SEND_LOCK_ATTEMPTS attempts, SEND_LOCK_WAIT_MS apart. */
38
+ const SEND_LOCK_ATTEMPTS = 200;
39
+ const SEND_LOCK_WAIT_MS = 10;
40
+ /**
41
+ * Run `fn` while holding every key in `keys`, acquired in the array's order
42
+ * (resources/key-lock.ts). A send holds its locks in ONE fixed order — message
43
+ * id, then recipient, then sender — and only ever waits for a lock later in
44
+ * that order than every lock it already holds, so no wait-for cycle (deadlock)
45
+ * is possible. Returns the innermost outcome: `{kind:"done", value}` when every
46
+ * lock was held and `fn` ran, `{kind:"busy"}` if any lock stayed held, or
47
+ * `{kind:"unavailable"}` if the store has no lock — in the last two cases `fn`
48
+ * never runs.
49
+ */
50
+ async function withKeyLocks(store, keys, fn, attempts, waitMs) {
51
+ const run = async (i) => {
52
+ if (i >= keys.length)
53
+ return { kind: "done", value: await fn() };
54
+ const held = await withKeyLock(store, keys[i], () => run(i + 1), attempts, waitMs);
55
+ return held.kind === "done" ? held.value : held;
56
+ };
57
+ return run(0);
58
+ }
25
59
  // ─── Helpers ────────────────────────────────────────────────────────────────
26
60
  /**
27
61
  * Materialize a table.search() result (async iterable | iterable | promise) to
@@ -32,11 +66,11 @@ const INBOX_FULL = (scope) => json(429, { error: "inbox full", reason: "inbox_fu
32
66
  * call site remain the correctness guarantee (the unit-test table double ignores
33
67
  * the query and returns every row); the conditions are the production index hint.
34
68
  */
35
- async function queryRows(table, conditions = []) {
69
+ async function queryRows(table, conditions = [], ctx) {
36
70
  const query = conditions.length > 0
37
71
  ? { operator: "and", conditions: conditions.map((c) => ({ attribute: c.attribute, comparator: "equals", value: c.value })) }
38
72
  : undefined;
39
- const res = table.search(query);
73
+ const res = table.search(query, ctx);
40
74
  const iter = res && typeof res.then === "function" ? await res : res;
41
75
  const out = [];
42
76
  for await (const row of iter)
@@ -122,6 +156,40 @@ export async function relaySend(deps, auth, content) {
122
156
  return BAD_REQUEST(`signature: ${verdict.reason}`);
123
157
  // Store the server-recomputed canonical hash (verified equal above).
124
158
  content.contentHash = computeContentHash(content);
159
+ // Within one Harper process, three per-key locks serialize a send's
160
+ // check-and-write, and are always acquired in ONE fixed order — message id,
161
+ // then recipient, then sender — so two sends can never deadlock: a send only
162
+ // ever waits for a lock that comes AFTER every lock it already holds, so no
163
+ // wait-for cycle exists. The id lock serializes id ownership; the recipient
164
+ // lock serializes the recipient-wide inbox cap; the sender lock serializes
165
+ // content dedup, thread sequence and the per-sender sub-cap. Cross-process
166
+ // coordination is out of scope: the lock is ONE Harper process's
167
+ // primary-store lock (flair#2333/#2461/#2462).
168
+ const store = deps.messages?.primaryStore;
169
+ const outcome = await withKeyLocks(store, [
170
+ [SEND_LOCK_NAMESPACE, "id", String(content.id)],
171
+ [SEND_LOCK_NAMESPACE, "recipient", String(content.to)],
172
+ [SEND_LOCK_NAMESPACE, "from", String(content.from)],
173
+ ], () => withOwnedTransaction(deps.ctx, (owned) => storeAndDeliver(deps, content, owned)), SEND_LOCK_ATTEMPTS, SEND_LOCK_WAIT_MS);
174
+ if (outcome.kind === "busy")
175
+ return SEND_BUSY();
176
+ if (outcome.kind === "unavailable")
177
+ return SEND_LOCK_UNAVAILABLE();
178
+ // Test-only: pause after the send locks release and the owned transaction
179
+ // commits, before this request's transaction commits (flair#2333).
180
+ const committed = txnPausePoint("relay-send-lock-released");
181
+ if (committed)
182
+ await committed;
183
+ return outcome.value;
184
+ }
185
+ /**
186
+ * The delivery half of relaySend, run while holding the send locks (the
187
+ * message id's, the recipient's and the sender's): the id-ownership answer, the
188
+ * content dedup, the per-thread seq check, the recipient-wide cap check and the
189
+ * store. Extracted so the whole check-and-write runs under those locks; it is
190
+ * never called outside them.
191
+ */
192
+ async function storeAndDeliver(deps, content, ctx) {
125
193
  // Retry-dedup: an identical resend — same primary id, or the same content
126
194
  // hash from this sender to this recipient — returns the already-accepted
127
195
  // envelope. No second row, and (critically) no second charge against the cap.
@@ -137,7 +205,7 @@ export async function relaySend(deps, auth, content) {
137
205
  // cannot be read, the send is refused the same way, never written over it.
138
206
  let existingById;
139
207
  try {
140
- existingById = (await Promise.resolve(deps.messages.get(String(content.id)))) ?? null;
208
+ existingById = (await Promise.resolve(deps.messages.get(String(content.id), ctx))) ?? null;
141
209
  }
142
210
  catch {
143
211
  return ownerMutationRefusal("Message");
@@ -150,7 +218,7 @@ export async function relaySend(deps, auth, content) {
150
218
  }
151
219
  // The recipient's inbox — queried by the @indexed `to`, never the whole table
152
220
  // (Sherlock P0). Serves both dedup (same content from this sender) and the cap.
153
- const recipientRows = await queryRows(deps.messages, [{ attribute: "to", value: content.to }]);
221
+ const recipientRows = await queryRows(deps.messages, [{ attribute: "to", value: content.to }], ctx);
154
222
  const dup = recipientRows.find((r) => r.from === content.from && r.to === content.to && r.contentHash === content.contentHash);
155
223
  if (dup)
156
224
  return acceptedView(dup);
@@ -158,7 +226,7 @@ export async function relaySend(deps, auth, content) {
158
226
  // STRICTLY ahead of the thread's last seq (Sherlock P1). Checked AFTER dedup so
159
227
  // a legitimate retry (same content, caught above) is never rejected. Queried by
160
228
  // the @indexed `threadId`, then filtered to this sender in-code.
161
- const threadRows = await queryRows(deps.messages, [{ attribute: "threadId", value: content.threadId }]);
229
+ const threadRows = await queryRows(deps.messages, [{ attribute: "threadId", value: content.threadId }], ctx);
162
230
  let prevMaxSeq = -1;
163
231
  for (const r of threadRows) {
164
232
  if (r.from !== content.from || r.threadId !== content.threadId)
@@ -194,7 +262,11 @@ export async function relaySend(deps, auth, content) {
194
262
  state: "delivered",
195
263
  deliveredAt: now,
196
264
  };
197
- await deps.messages.put(row);
265
+ // Test-only: pause between the checks above and the store below.
266
+ const pause = txnPausePoint("relay-send-write");
267
+ if (pause)
268
+ await pause;
269
+ await deps.messages.put(row, ctx);
198
270
  return acceptedView(row);
199
271
  }
200
272
  // ─── inbox ──────────────────────────────────────────────────────────────────
@@ -8,6 +8,11 @@
8
8
  * - federation body signatures, key `f:<nonce>` — FederationPair and
9
9
  * FederationSync (Federation.ts, via verifyFederationRequestBody).
10
10
  *
11
+ * The XAA ID-JAG `jti` record (flair#2073) uses the same `recordOnce` on its
12
+ * own table; see `claimIdJagJti` below. The OAuth single-use record (flair#2145)
13
+ * uses it on one more, for claims to redeem an authorization code (`c:<sha256>`)
14
+ * or rotate a refresh token (`r:<sha256>`); see `claimOAuthSingleUse` below.
15
+ *
11
16
  * The record of truth is the local `ReplayNonce` table (schemas/replay.graphql:
12
17
  * `replicate: false`, `expiration: 120`). Every Harper thread of this instance
13
18
  * reads and writes the same rows. Per-thread memory holds only keys this thread
@@ -81,24 +86,25 @@ const STORE_METHODS = ["tryLock", "unlock", "getEntry"];
81
86
  * outlive twice `windowMs`.
82
87
  */
83
88
  export function replayStoreContractGap(deps, windowMs) {
89
+ const name = deps?.name ?? REPLAY_TABLE;
84
90
  const table = deps?.table;
85
91
  if (!table)
86
- return `table flair.${REPLAY_TABLE} is not defined`;
92
+ return `table flair.${name} is not defined`;
87
93
  const store = table.primaryStore;
88
94
  if (!store)
89
- return `flair.${REPLAY_TABLE} has no primaryStore`;
95
+ return `flair.${name} has no primaryStore`;
90
96
  for (const m of STORE_METHODS) {
91
97
  if (typeof store[m] !== "function")
92
- return `flair.${REPLAY_TABLE}.primaryStore.${m} is not a function`;
98
+ return `flair.${name}.primaryStore.${m} is not a function`;
93
99
  }
94
100
  if (typeof table.put !== "function")
95
- return `flair.${REPLAY_TABLE}.put is not a function`;
101
+ return `flair.${name}.put is not a function`;
96
102
  if (typeof deps.transaction !== "function")
97
103
  return "Harper's transaction() is not available";
98
104
  if (windowMs !== undefined) {
99
105
  const expirationMs = table.expirationMS;
100
106
  if (typeof expirationMs === "number" && expirationMs > 0 && expirationMs <= 2 * windowMs) {
101
- return `flair.${REPLAY_TABLE} keeps rows ${expirationMs} ms, not longer than twice the ${windowMs} ms window`;
107
+ return `flair.${name} keeps rows ${expirationMs} ms, not longer than twice the ${windowMs} ms window`;
102
108
  }
103
109
  }
104
110
  return null;
@@ -129,7 +135,7 @@ export async function recordOnce(key, seenAt, deps) {
129
135
  throw new ReplayStoreUnavailable(gap);
130
136
  const { table, transaction } = deps;
131
137
  const store = table.primaryStore;
132
- const lockKey = [REPLAY_LOCK_NAMESPACE, key];
138
+ const lockKey = [deps.lockNamespace ?? REPLAY_LOCK_NAMESPACE, key];
133
139
  if (!store.tryLock(lockKey))
134
140
  return "contended";
135
141
  try {
@@ -146,7 +152,13 @@ export async function recordOnce(key, seenAt, deps) {
146
152
  // ─── Refusal logging (bounded) ─────────────────────────────────────────────
147
153
  const LOG_INTERVAL_MS = 10_000;
148
154
  const lastLogged = new Map();
149
- function noteUnavailable(scope, err) {
155
+ const REFUSED = {
156
+ a: "TPS-Ed25519 signed request",
157
+ f: "federation signed request",
158
+ x: "XAA jwt-bearer grant whose assertion carries a jti",
159
+ o: "OAuth request that redeems an authorization code or rotates a refresh token",
160
+ };
161
+ function noteUnavailable(scope, err, table = REPLAY_TABLE) {
150
162
  const reason = err instanceof ReplayStoreUnavailable
151
163
  ? err.message
152
164
  : `ReplayStoreUnavailable: store error (${err?.constructor?.name ?? "Error"}: ${String(err?.message ?? err).slice(0, 200)})`;
@@ -157,8 +169,8 @@ function noteUnavailable(scope, err) {
157
169
  if (lastLogged.size > 64)
158
170
  lastLogged.clear();
159
171
  lastLogged.set(tag, now);
160
- console.error(`[flair-replay] ${reason}. Every ${scope === "a" ? "TPS-Ed25519" : "federation"} signed request is refused until the ` +
161
- `flair.${REPLAY_TABLE} store is usable (see resources/replay-store.ts).`);
172
+ console.error(`[flair-replay] ${reason}. Every ${REFUSED[scope]} is refused until the ` +
173
+ `flair.${table} store is usable (see resources/replay-store.ts).`);
162
174
  }
163
175
  export function createReplayGuard(opts) {
164
176
  const { scope, windowMs, windowSource } = opts;
@@ -262,6 +274,91 @@ export function verifyFederationRequestBody(body, publicKeyB64url) {
262
274
  replay: federationReplayGuard,
263
275
  });
264
276
  }
277
+ // ─── XAA ID-JAG jti (flair#2073) ───────────────────────────────────────────
278
+ /** Used ID-JAG `jti` values (schemas/oauth.graphql), one row per jti, keyed by the jti. */
279
+ export const ID_JAG_REPLAY_TABLE = "IdJagReplay";
280
+ /** First element of every jti lock key, so a jti never shares a lock key with a nonce. */
281
+ export const ID_JAG_LOCK_NAMESPACE = "flair-replay-id-jag";
282
+ export function idJagReplayDeps() {
283
+ return {
284
+ table: databases?.flair?.[ID_JAG_REPLAY_TABLE],
285
+ transaction: globalThis.transaction,
286
+ name: ID_JAG_REPLAY_TABLE,
287
+ lockNamespace: ID_JAG_LOCK_NAMESPACE,
288
+ };
289
+ }
290
+ /**
291
+ * The reason `deps`' table cannot remember a key for `minRetentionMs`, or null.
292
+ * `basis` completes the sentence that says what the minimum covers.
293
+ */
294
+ export function storeRetentionGap(deps, minRetentionMs, basis) {
295
+ const gap = replayStoreContractGap(deps);
296
+ if (gap)
297
+ return gap;
298
+ const expirationMs = deps.table.expirationMS;
299
+ if (typeof expirationMs === "number" && expirationMs > 0 && expirationMs <= minRetentionMs) {
300
+ return `flair.${deps.name ?? REPLAY_TABLE} keeps rows ${expirationMs} ms, not longer than the ${minRetentionMs} ms ${basis}`;
301
+ }
302
+ return null;
303
+ }
304
+ /**
305
+ * Claim an ID-JAG's `jti` once per instance, through `recordOnce`. Call it after
306
+ * the assertion has validated and before the grant has any effect; refuse on
307
+ * anything but "recorded". `minRetentionMs` is the longest an accepted
308
+ * assertion can stay acceptable after its jti is recorded: a table whose rows
309
+ * do not outlive it is unavailable.
310
+ */
311
+ export async function claimIdJagJti(jti, minRetentionMs, now = Date.now()) {
312
+ try {
313
+ const deps = idJagReplayDeps();
314
+ const gap = storeRetentionGap(deps, minRetentionMs, "an assertion can stay acceptable");
315
+ if (gap)
316
+ throw new ReplayStoreUnavailable(gap);
317
+ // A lock miss ("contended") is refused like a stored row.
318
+ return (await recordOnce(jti, now, deps)) === "recorded" ? "recorded" : "replay";
319
+ }
320
+ catch (err) {
321
+ noteUnavailable("x", err, ID_JAG_REPLAY_TABLE);
322
+ return "unavailable";
323
+ }
324
+ }
325
+ // ─── OAuth single-use records (flair#2145) ─────────────────────────────────
326
+ /** One row per claim to redeem a code or rotate a refresh token (schemas/oauth.graphql). */
327
+ export const OAUTH_SINGLE_USE_TABLE = "OAuthSingleUse";
328
+ /** First element of every single-use lock key, so it never collides with a nonce or a jti lock. */
329
+ export const OAUTH_SINGLE_USE_LOCK_NAMESPACE = "flair-replay-oauth";
330
+ export function oauthSingleUseDeps() {
331
+ return {
332
+ table: databases?.flair?.[OAUTH_SINGLE_USE_TABLE],
333
+ transaction: globalThis.transaction,
334
+ name: OAUTH_SINGLE_USE_TABLE,
335
+ lockNamespace: OAUTH_SINGLE_USE_LOCK_NAMESPACE,
336
+ };
337
+ }
338
+ /**
339
+ * Claim an authorization code presented for redemption (`c:<sha256>`) or a
340
+ * refresh token presented for rotation (`r:<sha256>`) once per instance,
341
+ * through `recordOnce`. Call it after the request has been validated and before
342
+ * the handler attempts its later write or token issuance; refuse on anything
343
+ * but "recorded". `sha256Hex` is the SHA-256 of the code or token, so the
344
+ * record holds no redeemable secret. `minRetentionMs` is the longest the code
345
+ * or token can be presented after its row is recorded: a table whose rows do
346
+ * not outlive it is unavailable.
347
+ */
348
+ export async function claimOAuthSingleUse(kind, sha256Hex, minRetentionMs, now = Date.now()) {
349
+ try {
350
+ const deps = oauthSingleUseDeps();
351
+ const gap = storeRetentionGap(deps, minRetentionMs, "a redeemed authorization code or refresh token can be presented");
352
+ if (gap)
353
+ throw new ReplayStoreUnavailable(gap);
354
+ // A lock miss ("contended") is refused like a stored row.
355
+ return (await recordOnce(`${kind === "refresh" ? "r" : "c"}:${sha256Hex}`, now, deps)) === "recorded" ? "recorded" : "replay";
356
+ }
357
+ catch (err) {
358
+ noteUnavailable("o", err, OAUTH_SINGLE_USE_TABLE);
359
+ return "unavailable";
360
+ }
361
+ }
265
362
  // ─── Boot report ───────────────────────────────────────────────────────────
266
363
  /** Every gap that would refuse requests on this thread, or an empty list. */
267
364
  export function replayStoreBootGaps(deps = harperReplayDeps()) {
@@ -273,17 +370,44 @@ export function replayStoreBootGaps(deps = harperReplayDeps()) {
273
370
  }
274
371
  return gaps;
275
372
  }
276
- // Once per worker thread, after the schema's tables are bound. Harper defines
277
- // `server.workerCount` on worker threads; unit tests and the CLI never reach it.
278
- if (typeof setTimeout !== "undefined" && typeof globalThis.server?.workerCount === "number") {
279
- setTimeout(() => {
280
- try {
281
- for (const gap of replayStoreBootGaps()) {
282
- console.error(`[flair-replay] ReplayStoreUnavailable at boot (${gap}). Signed requests on this path are refused.`);
283
- }
284
- }
285
- catch (err) {
286
- console.error(`[flair-replay] ReplayStoreUnavailable at boot: ${err?.message ?? err}`);
373
+ /** Run during the awaited resource-module import, after graphqlSchema loads. */
374
+ function reportAtBoot(fn) {
375
+ // Harper defines `server.workerCount` on worker threads; unit tests and the
376
+ // CLI never reach this. The jsResource initial load awaits module imports,
377
+ // and the worker waits for that load before it starts listening.
378
+ if (typeof globalThis.server?.workerCount !== "number")
379
+ return;
380
+ try {
381
+ fn();
382
+ }
383
+ catch (err) {
384
+ console.error(`[flair-replay] ReplayStoreUnavailable at boot: ${err?.message ?? err}`);
385
+ }
386
+ }
387
+ // Once per worker thread, after the schema's tables are bound.
388
+ reportAtBoot(() => {
389
+ for (const gap of replayStoreBootGaps()) {
390
+ console.error(`[flair-replay] ReplayStoreUnavailable at boot (${gap}). Signed requests on this path are refused.`);
391
+ }
392
+ });
393
+ /**
394
+ * Every gap that would refuse a request through `store` on this thread, each
395
+ * labelled with the store's name, or an empty list.
396
+ */
397
+ export function replayStoreStoreGaps(store) {
398
+ const gap = storeRetentionGap(store.deps(), store.minRetentionMs, store.retentionBasis);
399
+ return gap ? [`${store.label}: ${gap}`] : [];
400
+ }
401
+ /**
402
+ * Print `store`'s gaps once per worker thread at boot, beside the replay
403
+ * guards' (`replayStoreBootGaps`): a misconfigured table is named before the
404
+ * first request instead of on the first claim. Call it at module load, from the
405
+ * module that owns the store, while Harper awaits that resource import.
406
+ */
407
+ export function reportReplayStoreGapsAtBoot(store) {
408
+ reportAtBoot(() => {
409
+ for (const gap of replayStoreStoreGaps(store)) {
410
+ console.error(`[flair-replay] ReplayStoreUnavailable at boot (${gap}). Requests through that store are refused until it is usable (see resources/replay-store.ts).`);
287
411
  }
288
- }, 0);
412
+ });
289
413
  }