@tpsdev-ai/flair 0.59.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (359) hide show
  1. package/README.md +10 -10
  2. package/SECURITY.md +49 -5
  3. package/config.yaml +23 -12
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/execute.js +1 -0
  6. package/dist/bridges/runtime/import-runner.js +12 -0
  7. package/dist/bridges/runtime/load-plugin.js +42 -13
  8. package/dist/bridges/runtime/yaml-loader.js +4 -2
  9. package/dist/bridges/types.js +1 -0
  10. package/dist/build-info.json +3 -3
  11. package/dist/cli.js +1054 -367
  12. package/dist/commands/agent.js +233 -90
  13. package/dist/commands/attention.js +4 -3
  14. package/dist/commands/backup-approval.js +218 -0
  15. package/dist/commands/backup.js +211 -39
  16. package/dist/commands/bootstrap.js +3 -1
  17. package/dist/commands/bridge.js +172 -119
  18. package/dist/commands/deploy.js +71 -8
  19. package/dist/commands/doctor.js +711 -146
  20. package/dist/commands/export.js +57 -23
  21. package/dist/commands/federation.js +787 -82
  22. package/dist/commands/grant.js +5 -6
  23. package/dist/commands/help.js +25 -0
  24. package/dist/commands/hook.js +155 -2
  25. package/dist/commands/idp.js +27 -19
  26. package/dist/commands/import.js +136 -20
  27. package/dist/commands/init.js +469 -200
  28. package/dist/commands/integrity.js +387 -0
  29. package/dist/commands/keys.js +247 -58
  30. package/dist/commands/mcp.js +108 -52
  31. package/dist/commands/memory.js +203 -35
  32. package/dist/commands/migrate-harness-memory.js +3 -2
  33. package/dist/commands/orgevent.js +51 -47
  34. package/dist/commands/presence.js +4 -3
  35. package/dist/commands/principal.js +428 -62
  36. package/dist/commands/quality.js +13 -1
  37. package/dist/commands/reembed.js +141 -17
  38. package/dist/commands/relationship.js +2 -1
  39. package/dist/commands/rem.js +537 -80
  40. package/dist/commands/restore.js +413 -65
  41. package/dist/commands/search.js +6 -4
  42. package/dist/commands/service.js +235 -40
  43. package/dist/commands/soul.js +4 -9
  44. package/dist/commands/status.js +94 -38
  45. package/dist/commands/test.js +7 -3
  46. package/dist/commands/upgrade.js +77 -23
  47. package/dist/commands/workspace.js +13 -11
  48. package/dist/component-env.js +31 -41
  49. package/dist/deploy.js +136 -4
  50. package/dist/doctor-client.js +534 -92
  51. package/dist/engine-version-contract.js +1 -0
  52. package/dist/engine-version.js +23 -3
  53. package/dist/fabric-upgrade.js +12 -2
  54. package/dist/federation/presence-send.js +139 -0
  55. package/dist/federation-verify.js +273 -180
  56. package/dist/hook-install.js +670 -6
  57. package/dist/install/clients.js +171 -35
  58. package/dist/keystore.js +72 -0
  59. package/dist/lib/action-recall-runtime.js +328 -0
  60. package/dist/lib/agent-home-fields.js +132 -0
  61. package/dist/lib/agent-home.js +427 -0
  62. package/dist/lib/agent-id-rule.js +88 -0
  63. package/dist/lib/agent-roster.js +33 -0
  64. package/dist/lib/atomic-write.js +1 -1
  65. package/dist/lib/auth-resolve.js +1069 -60
  66. package/dist/lib/backup-approval-store.js +612 -0
  67. package/dist/lib/backup-artifact.js +343 -0
  68. package/dist/lib/capture-runtime.js +124 -0
  69. package/dist/lib/config-critical-section.js +212 -25
  70. package/dist/lib/connect-phase.js +33 -0
  71. package/dist/lib/credential-status-rule.js +78 -0
  72. package/dist/lib/daemon-liveness.js +43 -11
  73. package/dist/lib/doctor-run.js +75 -37
  74. package/dist/lib/durability-copy.js +10 -0
  75. package/dist/lib/embedding-space-doctor.js +75 -0
  76. package/dist/lib/federation-pair-access.js +4 -0
  77. package/dist/lib/federation-retry-queue.js +283 -0
  78. package/dist/lib/federation-retry-row.js +101 -0
  79. package/dist/lib/flair-agent-role.js +4 -0
  80. package/dist/lib/hub-url.js +12 -0
  81. package/dist/lib/init-admin-pass.js +88 -12
  82. package/dist/lib/init-listener-environ.js +1 -2
  83. package/dist/lib/init-occupied-listener.js +15 -111
  84. package/dist/lib/init-spawn-attribution.js +73 -0
  85. package/dist/lib/init-tcp-probe.js +33 -0
  86. package/dist/lib/instance-identity-row.js +20 -0
  87. package/dist/lib/instruction-event-contract.js +17 -0
  88. package/dist/lib/instruction-event-doctor.js +102 -0
  89. package/dist/lib/launchd-management.js +38 -3
  90. package/dist/lib/listener-table.js +268 -0
  91. package/dist/lib/local-delete-instance.js +27 -0
  92. package/dist/lib/local-instance-pair.js +256 -0
  93. package/dist/lib/mcp-enable.js +1182 -341
  94. package/dist/lib/mcp-oauth-env-core.js +133 -0
  95. package/dist/lib/mcp-oauth-env.js +125 -0
  96. package/dist/lib/mcp-spec.js +17 -1
  97. package/dist/lib/memory-attributes.js +4 -0
  98. package/dist/lib/memory-id-policy.js +46 -0
  99. package/dist/lib/memory-integrity.js +309 -0
  100. package/dist/lib/memory-provider-timeout.js +33 -0
  101. package/dist/lib/memory-purge-response.js +20 -0
  102. package/dist/lib/mqtt-config.js +132 -0
  103. package/dist/lib/mqtt-listener-doctor.js +104 -0
  104. package/dist/lib/open-live-row.js +20 -0
  105. package/dist/lib/ops-table-count.js +25 -0
  106. package/dist/lib/ops-url.js +52 -0
  107. package/dist/lib/owned-pins.js +67 -10
  108. package/dist/lib/peer-status.js +27 -0
  109. package/dist/lib/principal-status.js +29 -0
  110. package/dist/lib/process-start-time.js +76 -12
  111. package/dist/lib/promotion-content-hash.js +20 -0
  112. package/dist/lib/proto-safe-record.js +42 -0
  113. package/dist/lib/record-id-path.js +25 -0
  114. package/dist/lib/reembed-server-support.js +66 -0
  115. package/dist/lib/restore-archive.js +760 -0
  116. package/dist/lib/restore-verify.js +104 -0
  117. package/dist/lib/scheduler-platform.js +10 -6
  118. package/dist/lib/secret-keys.js +25 -0
  119. package/dist/lib/secrets-push.js +50 -22
  120. package/dist/lib/skill-assignment-preflight.js +159 -0
  121. package/dist/lib/skill-seed-pending.js +24 -0
  122. package/dist/lib/skill-seed.js +448 -0
  123. package/dist/lib/skill-tombstone-doctor.js +133 -0
  124. package/dist/lib/soul-scope-fields.js +26 -0
  125. package/dist/lib/stop-start-recovery.js +54 -0
  126. package/dist/lib/uninstall-purge.js +266 -11
  127. package/dist/lib/upgrade-prior-liveness.js +2 -1
  128. package/dist/lib/using-flair-skill.js +87 -0
  129. package/dist/mcp-client-assertion.js +114 -14
  130. package/dist/memory-id-checkpoint.js +347 -0
  131. package/dist/memory-node-compare.js +207 -0
  132. package/dist/mqtt-off-deploy.js +550 -0
  133. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  134. package/dist/rem/promote-policy.js +3 -3
  135. package/dist/rem/restore.js +303 -26
  136. package/dist/rem/runner.js +317 -96
  137. package/dist/rem/scheduler.js +21 -4
  138. package/dist/resources/A2AAdapter.js +131 -178
  139. package/dist/resources/AdminMemory.js +2 -0
  140. package/dist/resources/AdminMemoryCandidates.js +116 -0
  141. package/dist/resources/Agent.js +463 -33
  142. package/dist/resources/AgentCard.js +4 -0
  143. package/dist/resources/AgentKeyRegister.js +248 -0
  144. package/dist/resources/AgentKeyRegistration.js +28 -0
  145. package/dist/resources/AgentReadPosition.js +7 -0
  146. package/dist/resources/AgentSeed.js +238 -107
  147. package/dist/resources/AutoPromoteCandidates.js +413 -78
  148. package/dist/resources/Credential.js +183 -10
  149. package/dist/resources/Federation.js +915 -145
  150. package/dist/resources/FederationRetry.js +140 -0
  151. package/dist/resources/InstructionVersion.js +220 -0
  152. package/dist/resources/Integration.js +300 -25
  153. package/dist/resources/MCPClientMetadata.js +6 -3
  154. package/dist/resources/Memory.js +3300 -758
  155. package/dist/resources/MemoryArchive.js +171 -53
  156. package/dist/resources/MemoryBootstrap.js +122 -61
  157. package/dist/resources/MemoryCandidate.js +37 -3
  158. package/dist/resources/MemoryConsolidate.js +2 -2
  159. package/dist/resources/MemoryDedupStats.js +30 -1
  160. package/dist/resources/MemoryFeed.js +545 -50
  161. package/dist/resources/MemoryGrant.js +21 -1
  162. package/dist/resources/MemoryMaintenance.js +368 -46
  163. package/dist/resources/MemoryPurge.js +348 -0
  164. package/dist/resources/MemoryReflect.js +71 -12
  165. package/dist/resources/MemoryReindex.js +111 -17
  166. package/dist/resources/Message.js +16 -5
  167. package/dist/resources/OAuth.js +342 -48
  168. package/dist/resources/OAuthClient.js +1 -1
  169. package/dist/resources/OrgEvent.js +405 -19
  170. package/dist/resources/OrgEventCatchup.js +7 -0
  171. package/dist/resources/OrgEventMaintenance.js +48 -10
  172. package/dist/resources/PairingToken.js +1 -1
  173. package/dist/resources/Presence.js +166 -51
  174. package/dist/resources/PromoteMemoryCandidate.js +24 -7
  175. package/dist/resources/RecordUsage.js +2 -4
  176. package/dist/resources/Relationship.js +23 -0
  177. package/dist/resources/SemanticSearch.js +63 -32
  178. package/dist/resources/Soul.js +191 -76
  179. package/dist/resources/SoulFeed.js +2 -1
  180. package/dist/resources/TeamDirectory.js +35 -0
  181. package/dist/resources/WorkspaceLatest.js +4 -0
  182. package/dist/resources/WorkspaceState.js +21 -1
  183. package/dist/resources/XAA.js +207 -63
  184. package/dist/resources/a2a-stream.js +313 -0
  185. package/dist/resources/a2a-url.js +4 -5
  186. package/dist/resources/agent-admin.js +10 -1
  187. package/dist/resources/agent-auth.js +138 -83
  188. package/dist/resources/agent-read-position-lib.js +4 -1
  189. package/dist/resources/agent-status-guard.js +9 -7
  190. package/dist/resources/auth-middleware.js +534 -171
  191. package/dist/resources/authority-field-guard.js +9 -11
  192. package/dist/resources/auto-promote-lib.js +8 -5
  193. package/dist/resources/basic-auth-header.js +21 -0
  194. package/dist/resources/bm25-index-service.js +4 -5
  195. package/dist/resources/dedup-cluster.js +6 -1
  196. package/dist/resources/ed25519-auth.js +1 -1
  197. package/dist/resources/embedding-space-guard.js +366 -72
  198. package/dist/resources/embeddings-provider.js +25 -0
  199. package/dist/resources/engine-version-stamp-boot.js +53 -0
  200. package/dist/resources/federation-classify.js +161 -0
  201. package/dist/resources/federation-crypto.js +5 -5
  202. package/dist/resources/federation-retry-lib.js +60 -0
  203. package/dist/resources/grant-visibility.js +135 -0
  204. package/dist/resources/harper-routing.js +83 -0
  205. package/dist/resources/health.js +163 -22
  206. package/dist/resources/host-pointer/registry.js +29 -0
  207. package/dist/resources/host-pointer-adapter.js +1 -0
  208. package/dist/resources/host-source-citation.js +49 -0
  209. package/dist/resources/host-source-visibility.js +7 -6
  210. package/dist/resources/in-process.js +24 -22
  211. package/dist/resources/instance-create-lock.js +17 -0
  212. package/dist/resources/instance-identity.js +23 -0
  213. package/dist/resources/instruction-version-record.js +587 -0
  214. package/dist/resources/internal-authority.js +13 -0
  215. package/dist/resources/key-lock.js +3 -3
  216. package/dist/resources/mcp-handler.js +141 -19
  217. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  218. package/dist/resources/mcp-oauth-flag.js +12 -14
  219. package/dist/resources/mcp-oauth.js +450 -56
  220. package/dist/resources/mcp-tool-arguments.js +4 -6
  221. package/dist/resources/mcp-tools.js +187 -40
  222. package/dist/resources/memory-bootstrap-lib.js +5 -15
  223. package/dist/resources/memory-declared-attributes.js +4 -1
  224. package/dist/resources/memory-deletion-history.js +55 -0
  225. package/dist/resources/memory-durability.js +54 -0
  226. package/dist/resources/memory-embed-hash.js +144 -0
  227. package/dist/resources/memory-embedding-value.js +8 -0
  228. package/dist/resources/memory-host-source.js +32 -7
  229. package/dist/resources/memory-id-guard.js +75 -0
  230. package/dist/resources/memory-redaction.js +236 -0
  231. package/dist/resources/memory-reflect-lib.js +1 -1
  232. package/dist/resources/memory-supplied-vector.js +72 -0
  233. package/dist/resources/memory-write-lock.js +489 -0
  234. package/dist/resources/memory-write-response.js +139 -0
  235. package/dist/resources/memory-write-transaction.js +243 -0
  236. package/dist/resources/migration-boot.js +17 -12
  237. package/dist/resources/migrations/boot-progress.js +25 -0
  238. package/dist/resources/migrations/data-dir.js +90 -19
  239. package/dist/resources/migrations/dir-safety.js +61 -3
  240. package/dist/resources/migrations/embedding-stamp.js +462 -82
  241. package/dist/resources/migrations/export.js +1 -0
  242. package/dist/resources/migrations/graph-heal.js +27 -27
  243. package/dist/resources/migrations/ledger.js +5 -2
  244. package/dist/resources/migrations/lock.js +870 -77
  245. package/dist/resources/migrations/progress.js +71 -10
  246. package/dist/resources/migrations/runner.js +212 -18
  247. package/dist/resources/migrations/snapshot.js +1 -0
  248. package/dist/resources/migrations/source-fields.js +5 -5
  249. package/dist/resources/migrations/state.js +36 -1
  250. package/dist/resources/migrations/status.js +2 -13
  251. package/dist/resources/migrations/synthetic-test-migration.js +81 -12
  252. package/dist/resources/migrations/types.js +26 -1
  253. package/dist/resources/migrations/visibility-backfill.js +113 -72
  254. package/dist/resources/oauth-discovery.js +0 -5
  255. package/dist/resources/object-body-guard.js +40 -0
  256. package/dist/resources/org-event-created-at.js +133 -0
  257. package/dist/resources/org-event-reserved.js +92 -0
  258. package/dist/resources/org-event-write-fault.js +19 -0
  259. package/dist/resources/originator-instance.js +39 -7
  260. package/dist/resources/owner-delete-recheck.js +78 -0
  261. package/dist/resources/owner-field-guard.js +39 -5
  262. package/dist/resources/owner-scoped-write-policy.js +256 -0
  263. package/dist/resources/owner-scoped-writes.js +89 -0
  264. package/dist/resources/path-id-rewrite.js +76 -0
  265. package/dist/resources/presence-internal.js +5 -5
  266. package/dist/resources/presence-receipt.js +236 -0
  267. package/dist/resources/promotion-binding.js +43 -0
  268. package/dist/resources/promotion-stamp.js +143 -17
  269. package/dist/resources/protocol-context.js +189 -0
  270. package/dist/resources/record-owner-guard.js +74 -26
  271. package/dist/resources/record-type-kit.js +2 -4
  272. package/dist/resources/record-types.js +1 -1
  273. package/dist/resources/relay-ops.js +78 -6
  274. package/dist/resources/replay-store.js +96 -19
  275. package/dist/resources/request-target.js +163 -0
  276. package/dist/resources/request-transaction.js +46 -1
  277. package/dist/resources/search-readiness.js +4 -1
  278. package/dist/resources/seed-ids.js +9 -0
  279. package/dist/resources/seed-reservation.js +116 -0
  280. package/dist/resources/semantic-retrieval-core.js +27 -15
  281. package/dist/resources/server-row-validation.js +71 -0
  282. package/dist/resources/skill-manifest.js +24 -14
  283. package/dist/resources/skill-subject.js +53 -0
  284. package/dist/resources/skill-version-write.js +789 -0
  285. package/dist/resources/skill-write-fault.js +20 -0
  286. package/dist/resources/skill-write-policy.js +68 -0
  287. package/dist/resources/skill-write.js +67 -7
  288. package/dist/resources/soul-write-policy.js +26 -7
  289. package/dist/resources/table-helpers.js +10 -7
  290. package/dist/resources/table-subscription-policy.js +518 -85
  291. package/dist/resources/table-subscriptions.js +20 -7
  292. package/dist/resources/team-directory.js +248 -0
  293. package/dist/resources/tool-descriptors/index.js +69 -8
  294. package/dist/resources/txn-pause-point.js +235 -0
  295. package/dist/resources/usage-recording.js +186 -70
  296. package/dist/resources/write-back.js +383 -0
  297. package/dist/resources/write-journal-context.js +5 -0
  298. package/dist/resources/write-journal.js +289 -0
  299. package/dist/src/engine-version-contract.js +1 -0
  300. package/dist/src/keystore.js +72 -0
  301. package/dist/src/lib/agent-home-fields.js +132 -0
  302. package/dist/src/lib/agent-id-rule.js +88 -0
  303. package/dist/src/lib/agent-key-register.js +80 -0
  304. package/dist/src/lib/atomic-write.js +256 -0
  305. package/dist/src/lib/credential-status-rule.js +78 -0
  306. package/dist/src/lib/expired-by-agent.js +37 -0
  307. package/dist/src/lib/federation-retry-row.js +101 -0
  308. package/dist/src/lib/flair-agent-role.js +4 -0
  309. package/dist/src/lib/idp-mapping-rule.js +81 -0
  310. package/dist/src/lib/instance-identity-row.js +20 -0
  311. package/dist/src/lib/instruction-event-contract.js +17 -0
  312. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  313. package/dist/src/lib/memory-attributes.js +4 -0
  314. package/dist/src/lib/memory-id-policy.js +46 -0
  315. package/dist/src/lib/open-live-row.js +20 -0
  316. package/dist/src/lib/principal-status.js +29 -0
  317. package/dist/src/lib/proto-safe-record.js +42 -0
  318. package/dist/src/lib/reembed-server-support.js +66 -0
  319. package/dist/src/lib/scheduler-platform.js +10 -6
  320. package/dist/src/lib/soul-scope-fields.js +26 -0
  321. package/dist/src/lib/systemd-agent-id.js +38 -0
  322. package/dist/src/rem/promote-policy.js +3 -3
  323. package/dist/src/rem/scheduler.js +21 -4
  324. package/docs/access-control.md +164 -54
  325. package/docs/api-reference.md +165 -32
  326. package/docs/auth.md +46 -30
  327. package/docs/bridges.md +11 -0
  328. package/docs/claude-code.md +37 -7
  329. package/docs/deploying-on-fabric.md +178 -0
  330. package/docs/deployment.md +19 -0
  331. package/docs/embedding-in-a-harper-app.md +17 -15
  332. package/docs/entity-vocabulary.md +3 -6
  333. package/docs/federation.md +61 -3
  334. package/docs/hosted-on-fabric.md +43 -36
  335. package/docs/integrations.md +14 -14
  336. package/docs/mcp-clients.md +12 -7
  337. package/docs/n8n.md +17 -11
  338. package/docs/notes/mcp-agent-auth-consumer.md +16 -13
  339. package/docs/notes/mcp-oauth-model2.md +40 -11
  340. package/docs/openclaw.md +1 -1
  341. package/docs/quickstart-fabric.md +4 -4
  342. package/docs/quickstart.md +12 -4
  343. package/docs/releasing.md +25 -19
  344. package/docs/rem.md +32 -3
  345. package/docs/secrets-and-keys.md +21 -4
  346. package/docs/standalone-local.md +30 -2
  347. package/docs/supply-chain-policy.md +34 -16
  348. package/docs/the-team.md +2 -2
  349. package/docs/upgrade.md +46 -6
  350. package/package.json +24 -12
  351. package/schemas/agent-key-registration.graphql +22 -0
  352. package/schemas/agent.graphql +6 -3
  353. package/schemas/federation.graphql +41 -1
  354. package/schemas/memory.graphql +91 -7
  355. package/schemas/oauth.graphql +19 -0
  356. package/schemas/schema.graphql +2 -0
  357. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  358. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  359. package/dist/resources/soul-adk-guard.js +0 -68
@@ -10,25 +10,14 @@
10
10
  * completed/halted outcome is still genuinely useful in that window instead
11
11
  * of reporting nothing.
12
12
  */
13
- import { listMigrationProgress, getCycleStatus, getStateFileStatus } from "./progress.js";
13
+ import { listMigrationProgress, getCycleStatus, getStateFileStatus, progressFromStateEntry } from "./progress.js";
14
14
  import { readMigrationState, defaultStatePath } from "./state.js";
15
15
  export function getMigrationStatusSnapshot(dataDir) {
16
16
  const cycle = getCycleStatus();
17
17
  let migrations = listMigrationProgress();
18
18
  if (migrations.length === 0) {
19
19
  const state = readMigrationState(defaultStatePath(dataDir));
20
- migrations = Object.entries(state).map(([id, entry]) => {
21
- const derivedState = entry.lastOutcome === "success" ? "completed" : entry.lastOutcome === "halted" ? "halted" : "failed";
22
- const row = {
23
- id,
24
- rowsDone: entry.rowsProcessed ?? 0,
25
- rowsRemaining: entry.rowsRemaining ?? 0,
26
- state: derivedState,
27
- };
28
- if (entry.reason)
29
- row.reason = entry.reason;
30
- return row;
31
- });
20
+ migrations = Object.entries(state).map(([id, entry]) => progressFromStateEntry(id, entry));
32
21
  }
33
22
  return {
34
23
  cyclePhase: cycle.phase,
@@ -26,9 +26,18 @@
26
26
  * migration nullable String field — no new schema needed) to a value that
27
27
  * encodes the migration id, so "is this row done" is answered entirely by
28
28
  * re-reading the row itself (invariant IV: state lives IN the data).
29
+ *
30
+ * The write runs under the row's per-id Memory write lock (flair#2478 slice
31
+ * 3b): one non-waiting acquisition per row, around the write-back's read,
32
+ * decision, write and commit. A held row, an unresolved write outcome on it or
33
+ * a table with no lock writes nothing and is logged; the next scan decides
34
+ * whether the row is still pending.
29
35
  */
30
36
  import { databases } from "harper";
31
- import { stripUndeclaredMemoryAttributes } from "../memory-declared-attributes.js";
37
+ import { writeBackCommittedRow as writeBackCommittedRowImpl } from "../write-back.js";
38
+ import { txnPausePoint } from "../txn-pause-point.js";
39
+ import { withMemoryWriteLockOnce } from "../memory-write-lock.js";
40
+ import { BatchOutcomeError } from "./types.js";
32
41
  export const SYNTHETIC_MIGRATION_ID = "synthetic-ci-schema-stamp";
33
42
  export const RESERVED_TEST_AGENT_ID = "__flair_migration_synthetic_test_agent__";
34
43
  export const SYNTHETIC_TARGET_MARKER = `${SYNTHETIC_MIGRATION_ID}-done`;
@@ -44,7 +53,7 @@ export function shouldRegisterSyntheticMigration(env = process.env) {
44
53
  function defaultMemoryTable() {
45
54
  return databases.flair.Memory;
46
55
  }
47
- export function createSyntheticTestMigration(getTable = defaultMemoryTable) {
56
+ export function createSyntheticTestMigration(getTable = defaultMemoryTable, writeBackCommittedRow = writeBackCommittedRowImpl) {
48
57
  function pendingCondition() {
49
58
  return [
50
59
  { attribute: "agentId", comparator: "equals", value: RESERVED_TEST_AGENT_ID },
@@ -69,6 +78,12 @@ export function createSyntheticTestMigration(getTable = defaultMemoryTable) {
69
78
  n++;
70
79
  return n;
71
80
  },
81
+ async checkUnconfirmed(id) {
82
+ const row = await getTable().get(id);
83
+ if (!row)
84
+ return "no-row";
85
+ return row.source === SYNTHETIC_TARGET_MARKER ? "at-target" : "pending";
86
+ },
72
87
  async run(batchSize) {
73
88
  const table = getTable();
74
89
  const candidates = [];
@@ -76,21 +91,75 @@ export function createSyntheticTestMigration(getTable = defaultMemoryTable) {
76
91
  candidates.push(row);
77
92
  }
78
93
  const touchedIds = [];
94
+ const unconfirmedIds = [];
79
95
  for (const row of candidates) {
80
96
  const id = String(row.id ?? "");
81
97
  if (!id)
82
98
  continue;
83
- const existing = await table.get(id);
84
- if (!existing)
85
- continue;
86
- if (existing.source === SYNTHETIC_TARGET_MARKER)
87
- continue; // already stamped — idempotent skip
88
- const synthRow = { ...existing, source: SYNTHETIC_TARGET_MARKER };
89
- stripUndeclaredMemoryAttributes(synthRow);
90
- await table.put(synthRow);
91
- touchedIds.push(id);
99
+ // flair#2840: the write-back reports an attempt whose committed effect
100
+ // its post-commit verification read did not show. The row is counted as
101
+ // done only if a later attempt's write is verified; otherwise it is
102
+ // reported by id.
103
+ let ownUnconfirmed = false;
104
+ try {
105
+ // flair#2478 slice 3b: an automatic writer. It takes the id's per-id
106
+ // Memory write lock with one non-waiting acquisition, so its read,
107
+ // decision, write and commit sit on one committed basis while an owner
108
+ // write holds the id. When the lock is refused (a held id, an id with an
109
+ // unresolved write outcome, or a table with no lock), nothing is written
110
+ // here and the refusal is reported. A write this attempt made but could
111
+ // not confirm is reported as unconfirmed (above) and may have committed.
112
+ // Either way, the next scan decides whether the row is still pending.
113
+ const locked = await withMemoryWriteLockOnce(table.primaryStore, [id], async () => {
114
+ const result = await writeBackCommittedRow(table, id, (existing) => {
115
+ if (!existing || existing.agentId !== RESERVED_TEST_AGENT_ID)
116
+ return { skip: true };
117
+ if (existing.source === SYNTHETIC_TARGET_MARKER)
118
+ return { skip: true }; // already stamped — idempotent skip
119
+ // Only `source`: an incremental update, never a
120
+ // full-row put of the row read above (flair#2470).
121
+ return { idempotent: true, update: { source: SYNTHETIC_TARGET_MARKER } };
122
+ }, {
123
+ label: "synthetic-test-migration",
124
+ pausePre: () => txnPausePoint("synthetic-test-pre"),
125
+ pausePoint: () => txnPausePoint("synthetic-test"),
126
+ pauseAfterStage: () => txnPausePoint("synthetic-test-staged"),
127
+ confirmPoint: () => txnPausePoint("synthetic-test-confirm"),
128
+ expectedRow: row,
129
+ onUnconfirmed: () => { ownUnconfirmed = true; },
130
+ });
131
+ // Test-only: the write-back committed and the lock is still held.
132
+ const committed = txnPausePoint("synthetic-test-committed");
133
+ if (committed)
134
+ await committed;
135
+ return result;
136
+ }, { phase: "synthetic-test-migration" });
137
+ if (locked.kind !== "done") {
138
+ console.warn("[synthetic-test-migration] %s: the per-id write lock answered %s; the row is left for the next scan", id, locked.kind);
139
+ continue;
140
+ }
141
+ if ("skip" in locked.value) {
142
+ // A skip is not a write this run verified. If it follows an attempt
143
+ // whose committed effect was unconfirmed, the row is reported as
144
+ // unconfirmed; otherwise this run wrote nothing to the row
145
+ // (flair#2840).
146
+ if (ownUnconfirmed)
147
+ unconfirmedIds.push(id);
148
+ }
149
+ else
150
+ touchedIds.push(id);
151
+ }
152
+ catch (err) {
153
+ // flair#2840: carry this batch's outcomes on the error — the runner
154
+ // has no RunBatchResult to read when run() throws.
155
+ if (ownUnconfirmed)
156
+ unconfirmedIds.push(id);
157
+ throw new BatchOutcomeError({ touchedIds, unconfirmedIds }, err);
158
+ }
92
159
  }
93
- return { processed: touchedIds.length, touchedIds };
160
+ return unconfirmedIds.length > 0
161
+ ? { processed: touchedIds.length, touchedIds, unconfirmedIds }
162
+ : { processed: touchedIds.length, touchedIds };
94
163
  },
95
164
  };
96
165
  }
@@ -6,4 +6,29 @@
6
6
  * refinements). Every migration registered in resources/migrations/registry.ts
7
7
  * implements the `Migration` interface below.
8
8
  */
9
- export {};
9
+ /**
10
+ * How many of a run's unconfirmed row ids are reported. During a run the
11
+ * runner holds the ids recorded in this run, and the listed ids it carried in,
12
+ * in a Set; the list written to the progress record and the state file is
13
+ * capped at this many. The count is not capped (flair#2840).
14
+ */
15
+ export const UNCONFIRMED_IDS_LIMIT = 100;
16
+ /**
17
+ * Thrown by a migration's run() on the paths that wrap the failure ending a
18
+ * batch (flair#2840): the synthetic write-back, the visibility backfill and
19
+ * embedding-stamp's `.content`-suffix retry read. It carries that batch's
20
+ * outcomes so far — the rows it touched and the rows it recorded as
21
+ * unconfirmed — so the runner can merge them into the unconfirmed record even
22
+ * though no {@link RunBatchResult} is returned. A throw from a path that does
23
+ * not wrap its batch carries no outcomes.
24
+ */
25
+ export class BatchOutcomeError extends Error {
26
+ touchedIds;
27
+ unconfirmedIds;
28
+ constructor(outcome, cause) {
29
+ super(cause?.message ?? String(cause), { cause });
30
+ this.name = "BatchOutcomeError";
31
+ this.touchedIds = [...outcome.touchedIds];
32
+ this.unconfirmedIds = [...outcome.unconfirmedIds];
33
+ }
34
+ }
@@ -4,8 +4,7 @@
4
4
  * which never stamped `visibility` at all. riskClass 'derived-only':
5
5
  * `visibility` here is a derived stamp recomputable at any time from
6
6
  * `durability` (which remains on the row, untouched, forever) — never the
7
- * only copy of anything (invariant I) — and this migration only ever writes
8
- * into a field that is CURRENTLY EMPTY, so the cheapest posture applies:
7
+ * only copy of anything (invariant I). The plan requires an empty visibility:
9
8
  * metadata-only snapshot, no content-hash gate (row-count + stamp
10
9
  * convergence only, same as `embedding-stamp`/`graph-heal`).
11
10
  *
@@ -45,13 +44,8 @@
45
44
  * definition is the safer contract than a shared import with a landmine
46
45
  * behind it. If this rule ever changes, both copies must change together.
47
46
  *
48
- * NEVER OVERWRITES an existing `visibility` value — that is an explicit
49
- * author decision (their own call, even if it disagrees with what this
50
- * migration would have derived). Only rows where `visibility` is
51
- * null/undefined are eligible, and `run()` below re-verifies that on a
52
- * freshly-read record immediately before writing (the actual enforcement
53
- * of "never overwrite" — see the write-gate comment there), independent of
54
- * how precisely the candidate-selection query below narrowed things.
47
+ * The per-id Memory lock shared with owner PUT/PATCH protects the missing-
48
+ * visibility decision and write. Writers outside that lock are not serialized.
55
49
  *
56
50
  * THE CANDIDATE QUERY — why it looks different from `embedding-stamp`'s:
57
51
  * `visibility` is declared in `schemas/memory.graphql` but NOT `@indexed`
@@ -69,11 +63,11 @@
69
63
  * find. A NEGATED comparator does match them (`undefined !== "private"` is
70
64
  * true), so the pending condition here is `visibility not_equals "private"
71
65
  * AND visibility not_equals "shared"` — no separate `equals: null` leg
72
- * needed (unlike `embedding-stamp`, whose write path can leave an
73
- * intermediate explicit-null state on a failed HTTP regen; this migration's
74
- * write is a single in-process read-modify-write that either fully
75
- * succeeds or leaves the row in its exact prior state, so there is no
76
- * intermediate state to add a leg for). This exact `not_equal`-covers-
66
+ * needed (unlike `embedding-stamp`, whose pending condition carries an
67
+ * `equals: null` leg for rows whose `embeddingModel` is an explicit null; this
68
+ * migration's write stages only `{ visibility }` through an incremental
69
+ * `update`, so it creates no explicit-null state to add a leg for). This exact
70
+ * `not_equal`-covers-
77
71
  * absent-and-null-and-nothing-else-with-the-value-itself semantics is
78
72
  * already relied on, in production, by `resources/memory-read-scope.ts`'s
79
73
  * cross-agent read-scope condition on this SAME field (`visibility !=
@@ -100,29 +94,25 @@
100
94
  * don't-brick (invariant II), and worth surfacing loudly if it ever
101
95
  * happens, since a garbage `visibility` value is itself a bug worth seeing.
102
96
  *
103
- * THE WRITE PATH — deliberately NOT `embedding-stamp`'s loopback-HTTP
104
- * `PUT /Memory/:id` trick. That mechanism exists ONLY because
105
- * `embedding-stamp` needs `resources/Memory.ts`'s SUBCLASS override (the
106
- * `content.content && !content.embedding` regen branch) to actually fire,
107
- * and the raw `databases.flair.Memory` reference (what this migration and
108
- * that one both get via their table accessor) resolves to the RAW
109
- * underlying table, silently skipping every subclass override — see that
110
- * file's module doc for the full, empirically-confirmed mechanism. This
111
- * migration needs NO subclass business logic (no dedup, no regen, no
112
- * provenance stamping, no rate limiting) — it is a narrow, single-field
113
- * patch, which is exactly the shape `resources/table-helpers.ts`'s
114
- * `patchRecord` documents and this codebase already uses directly against
115
- * the RAW table for the same kind of narrow metadata write:
116
- * `resources/auth-middleware.ts`'s `backfillEmbedding()` (patches
117
- * `embedding`), `resources/MemoryReflect.ts` and `resources/Memory.ts`
118
- * itself (both patch `lastReflected` this exact way). Per that file's own
119
- * warning, Harper's raw `.put()` is FULL RECORD REPLACEMENT — a partial
120
- * object silently deletes every field not included — so `run()` below
121
- * always spreads the freshly-read `existing` record before adding
122
- * `visibility`, the same read-modify-write shape `patchRecord` implements
123
- * (inlined here rather than calling that helper directly only because
124
- * `run()` already needs its own `.get()` for the write-gate check above,
125
- * and re-using that same read avoids a second, redundant round-trip).
97
+ * THE WRITE PATH — a single-field incremental `update`, not
98
+ * `embedding-stamp`'s loopback HTTP request. For ordinary row ids,
99
+ * embedding-stamp sends a loopback `PATCH /Memory/:id` with
100
+ * `{ embedding: null, embeddingModel: null }`, invoking Memory.patch()'s
101
+ * re-embed path, because it needs `resources/Memory.ts`'s SUBCLASS logic: the raw
102
+ * `databases.flair.Memory` reference (what this migration and that one both
103
+ * get via their table accessor) resolves to the RAW underlying table, silently
104
+ * skipping every subclass override — see that file's module doc for the full,
105
+ * empirically-confirmed mechanism. This migration needs NO subclass business
106
+ * logic (no dedup, no regen, no provenance stamping, no rate limiting): it
107
+ * writes only `visibility`, through `writeBackCommittedRow`
108
+ * (`resources/write-back.ts`), whose `update` plan calls the table's
109
+ * incremental `update` with `{ visibility }` and refuses when the table has
110
+ * none (`applyFieldUpdate`). Nothing spreads the stored row into a full-record
111
+ * `put`, so the full-record-replacement hazard `resources/table-helpers.ts`'s
112
+ * `patchRecord` warns about does not arise here. `run()` hands the candidate
113
+ * from its search to the write-back as `expectedRow`; the write-back re-reads
114
+ * the row inside its owned transaction, requires the row's identity fields to
115
+ * still match that basis, and confirms the committed row after staging.
126
116
  *
127
117
  * NO `recheckPending()`: that hook exists specifically to catch a stale
128
118
  * SECONDARY INDEX diverging from live values (flair#807, `embedding-stamp`
@@ -134,10 +124,17 @@
134
124
  * omitting it.
135
125
  */
136
126
  import { databases } from "harper";
137
- import { stripUndeclaredMemoryAttributes } from "../memory-declared-attributes.js";
127
+ import { writeBackCommittedRow as writeBackCommittedRowImpl } from "../write-back.js";
128
+ import { txnPausePoint } from "../txn-pause-point.js";
129
+ import { withMemoryWriteLockOnce } from "../memory-write-lock.js";
130
+ import { BatchOutcomeError } from "./types.js";
138
131
  function defaultMemoryTable() {
139
132
  return databases.flair.Memory;
140
133
  }
134
+ /** The per-id lock the backfill's writes run under (flair#2478 slice 2). */
135
+ function defaultMemoryLockStore() {
136
+ return databases?.flair?.Memory?.primaryStore;
137
+ }
141
138
  export const VISIBILITY_BACKFILL_ID = "visibility-backfill";
142
139
  /**
143
140
  * flair#509's rule, reused verbatim (see module doc for why this is a
@@ -164,13 +161,13 @@ function pendingCondition() {
164
161
  ];
165
162
  }
166
163
  /**
167
- * `getTable` is injectable so unit tests exercise this migration's full
168
- * detect/countPending/run logic against an in-memory fake table (matching
169
- * `embedding-stamp.ts`'s DI style) — no real Harper needed. Unlike
170
- * `embedding-stamp`, there is no separate HTTP mechanism to inject: the
171
- * write IS the table's own `.put()`, already covered by the same fake.
164
+ * `getTable` and the write-back are injectable so unit tests exercise this
165
+ * migration's full detect/countPending/run logic against an in-memory fake
166
+ * table and a fake write-back (matching `embedding-stamp.ts`'s DI style) — no
167
+ * real Harper needed. The default write-back is the real helper; an `update`
168
+ * plan needs the table's incremental `update`.
172
169
  */
173
- export function createVisibilityBackfillMigration(getTable = defaultMemoryTable) {
170
+ export function createVisibilityBackfillMigration(getTable = defaultMemoryTable, writeBackCommittedRow = writeBackCommittedRowImpl, getLockStore = defaultMemoryLockStore) {
174
171
  return {
175
172
  id: VISIBILITY_BACKFILL_ID,
176
173
  riskClass: "derived-only",
@@ -189,6 +186,17 @@ export function createVisibilityBackfillMigration(getTable = defaultMemoryTable)
189
186
  n++;
190
187
  return n;
191
188
  },
189
+ async checkUnconfirmed(id) {
190
+ const row = await getTable().get(id);
191
+ if (!row)
192
+ return "no-row";
193
+ // This migration only fills an absent visibility (flair#2840): once any
194
+ // value is present, run() never writes the row again, so the unconfirmed
195
+ // record is cleared. An owner's later value supersedes the unconfirmed
196
+ // write.
197
+ const visibility = row.visibility;
198
+ return visibility !== undefined && visibility !== null ? "at-target" : "pending";
199
+ },
192
200
  async run(batchSize) {
193
201
  const table = getTable();
194
202
  const candidates = [];
@@ -196,40 +204,73 @@ export function createVisibilityBackfillMigration(getTable = defaultMemoryTable)
196
204
  candidates.push(row);
197
205
  }
198
206
  const touchedIds = [];
207
+ const unconfirmedIds = [];
199
208
  for (const row of candidates) {
200
209
  const id = String(row.id ?? "");
201
210
  if (!id)
202
211
  continue;
203
- const existing = await table.get(id);
204
- if (!existing)
205
- continue; // deleted since the search above — nothing to fix
206
- // The write-gate: this is what actually enforces "never overwrite an
207
- // existing visibility value", independent of how precisely the
208
- // candidate query above narrowed things (see module doc — a
209
- // garbage third value would still be pulled in as a candidate).
210
- // Re-checks the FRESHLY-READ record, not the (possibly stale)
211
- // search-result row, and doubles as the idempotency/concurrent-
212
- // writer guard `embedding-stamp.ts` gets from its own analogous
213
- // pre-write check.
214
- if (existing.visibility !== undefined && existing.visibility !== null)
215
- continue;
216
- const derived = deriveVisibilityFromDurability(existing.durability);
217
- // Never-widen invariant, asserted, not just tested: the only two
218
- // values `deriveVisibilityFromDurability` can ever produce are
219
- // "private"/"shared" (see its own doc), so this can never fire
220
- // today — it exists to fail loudly (halting this migration via the
221
- // runner's mid-batch-throw path, never a silent bad write) if a
222
- // future edit to that function ever widens its return type or is
223
- // bypassed via a type-unsafe call.
224
- if (derived !== "private" && derived !== "shared") {
225
- throw new Error(`visibility-backfill: derived an invalid visibility for row ${id} — refusing to write`);
212
+ // flair#2840: the write-back reports an attempt whose committed effect
213
+ // its post-commit verification read did not show. The row is counted as
214
+ // done only if a later attempt's write is verified; otherwise it is
215
+ // reported by id.
216
+ let ownUnconfirmed = false;
217
+ try {
218
+ // The decision and the write run under the per-id memory write lock
219
+ // (flair#2478 slice 2). One attempt: a held id is left for the next
220
+ // cycle, never written unserialized and never waited on unboundedly.
221
+ const outcome = await withMemoryWriteLockOnce(getLockStore(), [id], async () => {
222
+ const result = await writeBackCommittedRow(table, id, (existing) => {
223
+ if (!existing)
224
+ return { skip: true }; // deleted since the search above — nothing to fix
225
+ // Under the per-id Memory lock shared with owner PUT/PATCH,
226
+ // fill only an absent visibility.
227
+ if (existing.visibility !== undefined && existing.visibility !== null)
228
+ return { skip: true };
229
+ const derived = deriveVisibilityFromDurability(existing.durability);
230
+ // Never-widen invariant, asserted, not just tested: the only two
231
+ // values `deriveVisibilityFromDurability` can ever produce are
232
+ // "private"/"shared" (see its own doc), so this can never fire
233
+ // today — it exists to fail loudly (halting this migration via the
234
+ // runner's mid-batch-throw path, never a silent bad write) if a
235
+ // future edit to that function ever widens its return type or is
236
+ // bypassed via a type-unsafe call.
237
+ if (derived !== "private" && derived !== "shared") {
238
+ throw new Error(`visibility-backfill: derived an invalid visibility for row ${id} — refusing to write`);
239
+ }
240
+ // Idempotent: once visibility is committed, a fresh plan sees it
241
+ // present and skips, so re-applying leaves the same committed row.
242
+ return { idempotent: true, update: { visibility: derived } };
243
+ }, { label: "visibility-backfill", pausePre: () => txnPausePoint("visibility-backfill-pre"), pausePoint: () => txnPausePoint("visibility-backfill"), confirmPoint: () => txnPausePoint("visibility-backfill-confirmed"), expectedRow: row, onUnconfirmed: () => { ownUnconfirmed = true; } });
244
+ // Test-only: the write-back committed and the lock is still held.
245
+ const committed = txnPausePoint("visibility-backfill-committed");
246
+ if (committed)
247
+ await committed;
248
+ return result;
249
+ }, { phase: "visibility-backfill" });
250
+ if (outcome.kind !== "done")
251
+ continue;
252
+ if ("skip" in outcome.value) {
253
+ // A skip is not a write this run verified. If it follows an attempt
254
+ // whose committed effect was unconfirmed, the row is reported as
255
+ // unconfirmed; otherwise this run wrote nothing to the row
256
+ // (flair#2840).
257
+ if (ownUnconfirmed)
258
+ unconfirmedIds.push(id);
259
+ }
260
+ else if ("update" in outcome.value)
261
+ touchedIds.push(id);
262
+ }
263
+ catch (err) {
264
+ // flair#2840: carry this batch's outcomes on the error — the runner
265
+ // has no RunBatchResult to read when run() throws.
266
+ if (ownUnconfirmed)
267
+ unconfirmedIds.push(id);
268
+ throw new BatchOutcomeError({ touchedIds, unconfirmedIds }, err);
226
269
  }
227
- const backfillRow = { ...existing, visibility: derived };
228
- stripUndeclaredMemoryAttributes(backfillRow);
229
- await table.put(backfillRow);
230
- touchedIds.push(id);
231
270
  }
232
- return { processed: touchedIds.length, touchedIds };
271
+ return unconfirmedIds.length > 0
272
+ ? { processed: touchedIds.length, touchedIds, unconfirmedIds }
273
+ : { processed: touchedIds.length, touchedIds };
233
274
  },
234
275
  };
235
276
  }
@@ -47,11 +47,6 @@ export function oauthPublicBaseUrl() {
47
47
  /**
48
48
  * The RFC 8707 resource identifier of flair's MCP surface: `<base>/mcp`.
49
49
  *
50
- * Matches `mcpResource()` in resources/mcp-oauth-flag.ts by construction —
51
- * that is the URI `withMCPAuth` audience-binds tokens to when the Model-2
52
- * surface is enabled, so the protected-resource document must name the same
53
- * string or a client would audience-bind its token to something `/mcp` rejects.
54
- *
55
50
  * It names `/mcp` even when `FLAIR_MCP_OAUTH` is off and `/mcp` therefore
56
51
  * 404s. That is a coherent state, not a lie: RFC 9728 metadata describes how a
57
52
  * resource WOULD be authorized; a client that discovers the authorization
@@ -0,0 +1,40 @@
1
+ /**
2
+ * object-body-guard.ts — the shared write-body shape check.
3
+ *
4
+ * `content` must be a non-null, non-array object. Arrays of records are admitted
5
+ * when `allowArrayObjects` is enabled. Anything else reaching this guard is
6
+ * refused with `body_must_be_object` (400).
7
+ */
8
+ export const BODY_MUST_BE_OBJECT_ERROR = "body_must_be_object";
9
+ /** True for a write body that is one record: a non-null object that is not an array. */
10
+ function isObjectRecord(value) {
11
+ return value !== null && typeof value === "object" && !Array.isArray(value);
12
+ }
13
+ /**
14
+ * 400 for a write body that is neither a JSON object nor an allowed array of
15
+ * them. Echoes nothing. The message follows `allowArrayObjects`: an
16
+ * array-admitting caller is told arrays are allowed, a caller that refuses
17
+ * them is not.
18
+ */
19
+ export function bodyMustBeObject(allowArrayObjects = false) {
20
+ return new Response(JSON.stringify({
21
+ error: BODY_MUST_BE_OBJECT_ERROR,
22
+ message: allowArrayObjects
23
+ ? "the write body must be a JSON object, or an array of them for a collection write"
24
+ : "the write body must be a JSON object",
25
+ }), { status: 400, headers: { "Content-Type": "application/json" } });
26
+ }
27
+ /**
28
+ * Refuse a write body that is neither an object nor an allowed array of records.
29
+ *
30
+ * @param content the parsed request body
31
+ * @param opts `allowArrayObjects: true` admits arrays of records and says so in the message
32
+ * @returns the 400 `Response` to send, or null to proceed
33
+ */
34
+ export function guardObjectBody(content, opts = {}) {
35
+ if (isObjectRecord(content))
36
+ return null;
37
+ if (opts.allowArrayObjects && Array.isArray(content) && content.every(isObjectRecord))
38
+ return null;
39
+ return bodyMustBeObject(opts.allowArrayObjects === true);
40
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * org-event-created-at.ts — the createdAt check for OrgEvent writes: the server
3
+ * assigns an event's createdAt on create, and a write that reaches this check
4
+ * cannot change a stored row's createdAt.
5
+ *
6
+ * The check runs after the resource's earlier checks (authentication,
7
+ * ownership, attribution, entity validation), which answer first with their own
8
+ * responses, as Harper's own validation does for input it refuses before the
9
+ * resource runs. For each record that reaches it:
10
+ *
11
+ * - a record that is not an object, or whose id is not a non-empty string or
12
+ * a non-empty array of strings, is not read: it is refused with
13
+ * `invalid_event_id` (400) before any write. Before validation, an
14
+ * addressed POST binds a missing or null body id to the addressed id, and
15
+ * a string or number body id when its text matches the address; any other
16
+ * id type is left unchanged by this step. At the root collection, POST
17
+ * generates an id when the body's id is missing, null or empty. At the
18
+ * root collection, or an addressed path whose body id was not bound, a
19
+ * remaining id outside those shapes receives the same 400 before the
20
+ * ownership lookup;
21
+ * - otherwise the check reads the stored row under that id. With no stored
22
+ * row (a create), createdAt is the server's time, whatever the body says;
23
+ * - with a stored row, its createdAt is authoritative whatever its value, an
24
+ * empty string included. A body that omits createdAt keeps the stored
25
+ * value; a body whose createdAt differs from it is refused with
26
+ * `created_at_immutable` (409), and nothing is written.
27
+ *
28
+ * resources/OrgEvent.ts runs this check for writes from verified agents and
29
+ * administrators on POST, single-record PUT and PATCH, and for administrators
30
+ * on each element of a collection PUT. A non-admin agent's collection PUT or
31
+ * PATCH is refused before this check by the owner-scoped write guard
32
+ * (resources/owner-scoped-write-policy.ts), and a non-admin addressed
33
+ * array-body PUT that reaches the resource is refused before it by attribution. Trusted in-process
34
+ * writers that supply their own createdAt (the migration ledger, the graph-heal migration) write
35
+ * through the raw `databases.flair.OrgEvent` table, not the resource's verbs,
36
+ * and an `internal` verdict on the resource passes through unchanged.
37
+ *
38
+ * The stored row is read before the write and the two are not atomic: a row
39
+ * first written between the read and the write is treated as a create, so its
40
+ * createdAt becomes this write's server time.
41
+ *
42
+ * The decision is pure and has no Harper import, so it is unit-tested directly.
43
+ */
44
+ export const CREATED_AT_IMMUTABLE_ERROR = "created_at_immutable";
45
+ export const CREATED_AT_CHECK_UNAVAILABLE_ERROR = "created_at_check_unavailable";
46
+ export const INVALID_EVENT_ID_ERROR = "invalid_event_id";
47
+ /** 409 for a write that reaches the check and would change a stored event's createdAt. Echoes nothing. */
48
+ export function createdAtImmutable() {
49
+ return new Response(JSON.stringify({
50
+ error: CREATED_AT_IMMUTABLE_ERROR,
51
+ message: "this write would change the stored event's createdAt, which the server assigns on create",
52
+ }), { status: 409, headers: { "Content-Type": "application/json" } });
53
+ }
54
+ /**
55
+ * 503 when this check's own stored-event read fails, so the write was refused.
56
+ * Read failures in earlier checks keep their own responses.
57
+ */
58
+ export function createdAtCheckUnavailable(err) {
59
+ console.error("org-event-created-at: the stored event could not be read, so the write was refused", { err });
60
+ return new Response(JSON.stringify({
61
+ error: CREATED_AT_CHECK_UNAVAILABLE_ERROR,
62
+ message: "the stored event could not be read; the write was refused",
63
+ }), { status: 503, headers: { "Content-Type": "application/json" } });
64
+ }
65
+ /**
66
+ * 400 for a record the check does not read: one that is not an object, or whose
67
+ * id is not a key the check reads (see isReadableEventId). Echoes nothing.
68
+ */
69
+ export function invalidEventId() {
70
+ return new Response(JSON.stringify({
71
+ error: INVALID_EVENT_ID_ERROR,
72
+ message: "each OrgEvent a write stores must be an object whose id is a non-empty string or a non-empty array of strings",
73
+ }), { status: 400, headers: { "Content-Type": "application/json" } });
74
+ }
75
+ /**
76
+ * Whether the check reads the stored row under `id`: a non-empty string, or a
77
+ * non-empty array of strings (a composite key). The check refuses every other
78
+ * id with `invalid_event_id` before any write. Harper accepts some of those ids
79
+ * as keys (the empty string is one), so the refusal is this check's own rule,
80
+ * not something left to Harper's validation.
81
+ */
82
+ export function isReadableEventId(id) {
83
+ if (typeof id === "string")
84
+ return id !== "";
85
+ return Array.isArray(id) && id.length > 0 && id.every((part) => typeof part === "string");
86
+ }
87
+ /**
88
+ * Returns invalid_event_id (400) for anything but a non-empty string or a
89
+ * non-empty array of strings, or null. The refusal echoes no submitted value.
90
+ */
91
+ export function unreadableEventIdRefusal(id) {
92
+ return isReadableEventId(id) ? null : invalidEventId();
93
+ }
94
+ /**
95
+ * The same rule applied to a collection PUT's array body: the refusal for the
96
+ * first record element whose id it does not read, or null.
97
+ * The scan skips non-record elements.
98
+ */
99
+ export function collectionElementIdRefusal(body) {
100
+ if (!Array.isArray(body))
101
+ return null;
102
+ for (const element of body) {
103
+ if (element == null || typeof element !== "object" || Array.isArray(element))
104
+ continue;
105
+ const denial = unreadableEventIdRefusal(element.id);
106
+ if (denial)
107
+ return denial;
108
+ }
109
+ return null;
110
+ }
111
+ /**
112
+ * Assign or keep `content.createdAt` for one write, given the stored row the
113
+ * write lands on (`stored` null/undefined = no stored row, a create). Mutates
114
+ * `content`. Returns null to proceed, or the refusal to send.
115
+ *
116
+ * For a stored row, the stored createdAt is authoritative whatever its value,
117
+ * an empty string included: a body that names a different value is refused,
118
+ * and a body that omits it keeps the stored value.
119
+ */
120
+ export function applyServerCreatedAt(content, stored, mode, now = new Date()) {
121
+ if (stored == null) {
122
+ // No stored row: a create, so the server assigns createdAt.
123
+ content.createdAt = now.toISOString();
124
+ return null;
125
+ }
126
+ const storedAt = stored.createdAt;
127
+ if (Object.prototype.hasOwnProperty.call(content, "createdAt") && content.createdAt !== storedAt) {
128
+ return createdAtImmutable();
129
+ }
130
+ if (mode === "replace")
131
+ content.createdAt = storedAt;
132
+ return null;
133
+ }