@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
@@ -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
  *
@@ -403,7 +403,7 @@ export const RECORD_TYPES = {
403
403
  // skill_search — skill-tagged Memory recall (flair#1546), rides SemanticSearch
404
404
  // skill_get — full skill read by id (flair#1546), rides Memory.get
405
405
  //
406
- 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"];
407
407
  // ─── Runtime immutability ───────────────────────────────────────────────────
408
408
  // Belt-and-suspenders backstop for the "static, compiled" invariant (see
409
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 ──────────────────────────────────────────────────────────────────
@@ -9,7 +9,9 @@
9
9
  * FederationSync (Federation.ts, via verifyFederationRequestBody).
10
10
  *
11
11
  * The XAA ID-JAG `jti` record (flair#2073) uses the same `recordOnce` on its
12
- * own table; see `claimIdJagJti` below.
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.
13
15
  *
14
16
  * The record of truth is the local `ReplayNonce` table (schemas/replay.graphql:
15
17
  * `replicate: false`, `expiration: 120`). Every Harper thread of this instance
@@ -154,6 +156,7 @@ const REFUSED = {
154
156
  a: "TPS-Ed25519 signed request",
155
157
  f: "federation signed request",
156
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",
157
160
  };
158
161
  function noteUnavailable(scope, err, table = REPLAY_TABLE) {
159
162
  const reason = err instanceof ReplayStoreUnavailable
@@ -276,7 +279,7 @@ export function verifyFederationRequestBody(body, publicKeyB64url) {
276
279
  export const ID_JAG_REPLAY_TABLE = "IdJagReplay";
277
280
  /** First element of every jti lock key, so a jti never shares a lock key with a nonce. */
278
281
  export const ID_JAG_LOCK_NAMESPACE = "flair-replay-id-jag";
279
- function idJagReplayDeps() {
282
+ export function idJagReplayDeps() {
280
283
  return {
281
284
  table: databases?.flair?.[ID_JAG_REPLAY_TABLE],
282
285
  transaction: globalThis.transaction,
@@ -284,6 +287,20 @@ function idJagReplayDeps() {
284
287
  lockNamespace: ID_JAG_LOCK_NAMESPACE,
285
288
  };
286
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
+ }
287
304
  /**
288
305
  * Claim an ID-JAG's `jti` once per instance, through `recordOnce`. Call it after
289
306
  * the assertion has validated and before the grant has any effect; refuse on
@@ -294,13 +311,9 @@ function idJagReplayDeps() {
294
311
  export async function claimIdJagJti(jti, minRetentionMs, now = Date.now()) {
295
312
  try {
296
313
  const deps = idJagReplayDeps();
297
- const gap = replayStoreContractGap(deps);
314
+ const gap = storeRetentionGap(deps, minRetentionMs, "an assertion can stay acceptable");
298
315
  if (gap)
299
316
  throw new ReplayStoreUnavailable(gap);
300
- const expirationMs = deps.table.expirationMS;
301
- if (typeof expirationMs === "number" && expirationMs > 0 && expirationMs <= minRetentionMs) {
302
- throw new ReplayStoreUnavailable(`flair.${ID_JAG_REPLAY_TABLE} keeps rows ${expirationMs} ms, not longer than the ${minRetentionMs} ms an assertion can stay acceptable`);
303
- }
304
317
  // A lock miss ("contended") is refused like a stored row.
305
318
  return (await recordOnce(jti, now, deps)) === "recorded" ? "recorded" : "replay";
306
319
  }
@@ -309,6 +322,43 @@ export async function claimIdJagJti(jti, minRetentionMs, now = Date.now()) {
309
322
  return "unavailable";
310
323
  }
311
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
+ }
312
362
  // ─── Boot report ───────────────────────────────────────────────────────────
313
363
  /** Every gap that would refuse requests on this thread, or an empty list. */
314
364
  export function replayStoreBootGaps(deps = harperReplayDeps()) {
@@ -320,17 +370,44 @@ export function replayStoreBootGaps(deps = harperReplayDeps()) {
320
370
  }
321
371
  return gaps;
322
372
  }
323
- // Once per worker thread, after the schema's tables are bound. Harper defines
324
- // `server.workerCount` on worker threads; unit tests and the CLI never reach it.
325
- if (typeof setTimeout !== "undefined" && typeof globalThis.server?.workerCount === "number") {
326
- setTimeout(() => {
327
- try {
328
- for (const gap of replayStoreBootGaps()) {
329
- console.error(`[flair-replay] ReplayStoreUnavailable at boot (${gap}). Signed requests on this path are refused.`);
330
- }
331
- }
332
- catch (err) {
333
- 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).`);
334
411
  }
335
- }, 0);
412
+ });
336
413
  }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * request-target.ts — the raw request target the auth middleware decides on.
3
+ *
4
+ * Before any other request processing, the middleware answers a target that is not in
5
+ * canonical form with a named 400 (`non_canonical_request_target`). A raw
6
+ * target is canonical unless its path (the part before the first `?`) has:
7
+ *
8
+ * - a `.` or `..` segment, raw or percent-encoded as a whole segment
9
+ * (`%2e`, `%2E%2e`, `.%2e`, …);
10
+ * - repeated slashes (`//`) anywhere in the path;
11
+ * - a raw backslash.
12
+ *
13
+ * Everything else is canonical, including `%2F` and `%5C` inside a segment, a
14
+ * dot inside a segment (`a.b`), and any query string.
15
+ *
16
+ * PURE: string logic only, imports nothing.
17
+ */
18
+ /** The named error a non-canonical request target is refused with. */
19
+ export const NON_CANONICAL_REQUEST_TARGET_ERROR = "non_canonical_request_target";
20
+ /** A whole segment that is `.` or `..`, each dot raw or percent-encoded. */
21
+ const DOT_SEGMENT = /^(?:\.|%2e){1,2}$/i;
22
+ /**
23
+ * The path part of a raw request target: everything before the first `?`.
24
+ */
25
+ export function requestPath(rawTarget) {
26
+ const q = rawTarget.indexOf("?");
27
+ return q === -1 ? rawTarget : rawTarget.slice(0, q);
28
+ }
29
+ /** True when a raw request target is in canonical form (see the module header). */
30
+ export function isCanonicalRequestTarget(rawTarget) {
31
+ const path = requestPath(rawTarget);
32
+ if (path.includes("\\"))
33
+ return false;
34
+ if (path.includes("//"))
35
+ return false;
36
+ return !path.split("/").some((segment) => DOT_SEGMENT.test(segment));
37
+ }
38
+ /** The named 400 for a non-canonical request target. HEAD gets no body. */
39
+ export function nonCanonicalRequestTargetRefusal(method) {
40
+ const body = JSON.stringify({
41
+ error: NON_CANONICAL_REQUEST_TARGET_ERROR,
42
+ message: "the request target must be in canonical form: no '.' or '..' path segment, no repeated slashes (`//`), and no backslash",
43
+ });
44
+ return new Response(method === "HEAD" ? null : body, {
45
+ status: 400,
46
+ headers: { "content-type": "application/json" },
47
+ });
48
+ }
49
+ /**
50
+ * The raw path's segments, split on `/` FIRST and still percent-encoded.
51
+ * Empty segments are dropped.
52
+ */
53
+ export function rawPathSegments(path) {
54
+ return path.split("/").filter(Boolean);
55
+ }
56
+ /** The last raw segment of a path (still percent-encoded). */
57
+ export function lastRawPathSegment(path) {
58
+ return path.slice(path.lastIndexOf("/") + 1);
59
+ }
60
+ /** Decode one raw path segment; null when it is not valid percent-encoding. */
61
+ export function decodePathSegment(segment) {
62
+ try {
63
+ return decodeURIComponent(segment);
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ /**
70
+ * For a plain one-level resource path, return the first segment and the
71
+ * still-encoded remainder after it, removing one leading slash.
72
+ */
73
+ export function routedResourceAndRemainder(path) {
74
+ const p = path.startsWith("/") ? path.slice(1) : path;
75
+ const slash = p.indexOf("/");
76
+ if (slash === -1)
77
+ return { resource: p, remainder: "" };
78
+ return { resource: p.slice(0, slash), remainder: p.slice(slash + 1) };
79
+ }
80
+ /**
81
+ * Return the resource segment and fully decoded remainder (the initial
82
+ * RequestTarget id for a plain one-level resource path). `parsePath` can change
83
+ * the final row id. Null for an empty, trailing-slash or malformed remainder.
84
+ */
85
+ export function routedRecordId(path) {
86
+ const { resource, remainder } = routedResourceAndRemainder(path);
87
+ if (remainder === "" || remainder.endsWith("/"))
88
+ return null;
89
+ let id;
90
+ try {
91
+ id = decodeURIComponent(remainder);
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ if (id === "")
97
+ return null;
98
+ return { resource, id };
99
+ }
100
+ /**
101
+ * Return the prefix before the first dot when its suffix is in
102
+ * `declaredAttributes`; otherwise return the id unchanged.
103
+ */
104
+ export function routedIdAfterPropertyRule(id, declaredAttributes) {
105
+ const dot = id.indexOf(".");
106
+ if (dot > -1 && declaredAttributes.has(id.slice(dot + 1)))
107
+ return id.slice(0, dot);
108
+ return id;
109
+ }
110
+ /**
111
+ * Return the first nonempty segment if `isKnown` accepts it, otherwise its
112
+ * prefix before the first dot if accepted, otherwise the segment unchanged.
113
+ */
114
+ export function routedFirstResourceName(path, isKnown) {
115
+ const seg = rawPathSegments(path)[0] ?? "";
116
+ if (isKnown(seg))
117
+ return seg;
118
+ const dot = seg.indexOf(".");
119
+ if (dot > -1 && isKnown(seg.slice(0, dot)))
120
+ return seg.slice(0, dot);
121
+ return seg;
122
+ }
123
+ /**
124
+ * For a path with one leading slash, return it with the first segment replaced
125
+ * by `routedFirstResourceName`; unchanged when that name does not change.
126
+ */
127
+ export function routedResourcePath(path, known) {
128
+ const segs = rawPathSegments(path);
129
+ const first = segs[0];
130
+ if (first === undefined)
131
+ return path;
132
+ const name = routedFirstResourceName(path, (n) => known.has(n));
133
+ if (name === first)
134
+ return path;
135
+ return `/${name}${path.slice(1 + first.length)}`;
136
+ }
@@ -76,3 +76,38 @@ export async function withOwnedTransaction(ctx, fn) {
76
76
  ctx.transaction = saved;
77
77
  }
78
78
  }
79
+ /** Marks a context whose OPEN write transaction belongs to an in-process
80
+ * caller that composes a Memory write into it. A Symbol, so no request body
81
+ * or header can set it. */
82
+ const COMPOSED_WRITE = Symbol("flair.composedMemoryWrite");
83
+ /**
84
+ * Run `fn` in a shared write transaction ({@link withSharedWriteTransaction})
85
+ * and mark `shared` for the duration, so `Memory.put()` JOINS this transaction
86
+ * instead of owning one (flair#2478 slice 1, part 1). The caller owns the
87
+ * commit: its own writes in `fn` commit or abort with the Memory row. Manual
88
+ * promotion uses it, so its Memory write and verdict stamp stay one
89
+ * transaction (flair#2354). The per-id write lock orders the put's read and
90
+ * decision against other owner PUT/PATCH writers of that id, but this
91
+ * transaction commits after the lock is released, so its commit is not
92
+ * serialized with theirs; writers that take no lock are not serialized at all.
93
+ */
94
+ export async function withComposedWriteTransaction(ctx, fn) {
95
+ return withSharedWriteTransaction(ctx, async (shared) => {
96
+ const had = Object.prototype.hasOwnProperty.call(shared, COMPOSED_WRITE);
97
+ const prior = shared[COMPOSED_WRITE];
98
+ shared[COMPOSED_WRITE] = true;
99
+ try {
100
+ return await fn(shared);
101
+ }
102
+ finally {
103
+ if (had)
104
+ shared[COMPOSED_WRITE] = prior;
105
+ else
106
+ delete shared[COMPOSED_WRITE];
107
+ }
108
+ });
109
+ }
110
+ /** Is `ctx` inside {@link withComposedWriteTransaction} with its transaction still open? */
111
+ export function composesCallerWrite(ctx) {
112
+ return !!ctx && ctx[COMPOSED_WRITE] === true && isJoinableTransaction(ctx);
113
+ }
@@ -28,6 +28,7 @@
28
28
  * search) is what clears `empty`.
29
29
  */
30
30
  import { bm25SearchLagReason } from "./bm25-status.js";
31
+ import { MEMORY_REEMBED_PATCH_CAPABILITY } from "../src/lib/reembed-server-support.js";
31
32
  /**
32
33
  * How a ready result was verified. Constant strings — no interpolation
33
34
  * (flair#1411). Public /Health still omits this field when searchReady is
@@ -117,8 +118,10 @@ export function buildPublicHealthBody(readiness, identity) {
117
118
  version: identity.version,
118
119
  buildCommit: identity.buildCommit,
119
120
  searchReady: readiness.searchReady,
121
+ // flair#2337: this build advertises the re-embed PATCH token.
122
+ // The shared constant aligns this build's CLI and server literals.
123
+ capabilities: [MEMORY_REEMBED_PATCH_CAPABILITY],
120
124
  };
121
- // Public shape is unchanged: searchReadyReason is still present iff !searchReady.
122
125
  // Ready-path verification constants stay on the decision object (flair#1411).
123
126
  if (!readiness.searchReady && readiness.searchReadyReason) {
124
127
  body.searchReadyReason = readiness.searchReadyReason;