@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
@@ -16,8 +16,8 @@
16
16
  *
17
17
  * `recordUsageContribution()` is the one (agentId, memoryId) ledger write —
18
18
  * see its doc below for the read-scope gate it applies, the ledger-then-count
19
- * ordering, the individually-wrapped `withDetachedTxn` discipline, and the
20
- * accepted best-effort race on the final read-modify-write.
19
+ * ordering, and the owned read-modify-write that confirms the stored row before
20
+ * the count bump.
21
21
  *
22
22
  * `recordCitations()` is the NEW batch helper citation-on-write uses: the
23
23
  * same agent-required / cap / dedup / per-id failure-isolation shape as
@@ -54,8 +54,12 @@
54
54
  * unfiltered.
55
55
  */
56
56
  import { databases } from "harper";
57
- import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
57
+ import { withKeyLock } from "./key-lock.js";
58
58
  import { withDetachedTxn } from "./table-helpers.js";
59
+ import { withOwnedTransaction } from "./request-transaction.js";
60
+ import { WriteBackConflictError, writeBackCommittedRow } from "./write-back.js";
61
+ import { withMemoryWriteLockOnce } from "./memory-write-lock.js";
62
+ import { txnPausePoint } from "./txn-pause-point.js";
59
63
  import { resolveReadScope } from "./memory-read-scope.js";
60
64
  /**
61
65
  * Per-call cap on ids credited in one batch — shared by RecordUsage.post()'s
@@ -64,6 +68,22 @@ import { resolveReadScope } from "./memory-read-scope.js";
64
68
  * see that function's doc for why the two differ here).
65
69
  */
66
70
  export const MAX_USAGE_IDS_PER_CALL = 20;
71
+ /**
72
+ * The named refusal of a contribution whose ledger READ failed. The read is the
73
+ * decision "does this (agent, memory) pair already have a row?" — an error is
74
+ * NOT evidence there is none. Treating it as "no row" would upsert over whatever
75
+ * row is stored and bump the count a second time, so this contribution is
76
+ * aborted instead (no ledger write, no count change) and the batch logs the
77
+ * failure; the other ids in the batch are unaffected.
78
+ */
79
+ export class UsageLedgerReadError extends Error {
80
+ ledgerId;
81
+ constructor(ledgerId, cause) {
82
+ super(`usage ledger row read failed for ${ledgerId}: ${cause instanceof Error ? cause.message : String(cause)}`);
83
+ this.name = "UsageLedgerReadError";
84
+ this.ledgerId = ledgerId;
85
+ }
86
+ }
67
87
  /**
68
88
  * One (agentId, memoryId) contribution — the shared ledger-write core.
69
89
  *
@@ -79,75 +99,154 @@ export const MAX_USAGE_IDS_PER_CALL = 20;
79
99
  * Ledger-row-create FIRST, THEN the Memory.usageCount bump — so a crash
80
100
  * between the two leaves the SAFE failure state (ledger row exists, count
81
101
  * not yet bumped: a later retry just re-checks and no-ops) rather than the
82
- * reverse (count bumped, no ledger row → a retry would double-count).
102
+ * reverse (count bumped, no ledger row → a retry would double-count). The
103
+ * ledger READ that decides all this FAILS CLOSED: an error is not "no row", so
104
+ * that contribution aborts (named UsageLedgerReadError, no ledger write, no
105
+ * count change) rather than upsert over the stored row and bump again.
106
+ *
107
+ * The ledger read and any create share an owned transaction. The count bump
108
+ * uses a separate owned transaction through writeBackCommittedRow.
83
109
  *
84
- * Every discrete Harper call is wrapped INDIVIDUALLY in its own
85
- * withDetachedTxn — never one wrap around a multi-step helper. A request
86
- * that reads/writes MULTIPLE tables (or the same table twice) in sequence
87
- * can otherwise inherit a closed transaction from a prior call's drained
88
- * chain (table-helpers.ts's withDetachedTxn doc); resources/Memory.ts's
89
- * closeSupersededRecord documents exactly why a single wrap around a
90
- * multi-await async function does NOT protect a later call inside it —
91
- * this mirrors that function's literal shape (get wrapped, then a
92
- * SEPARATE put wrapped) rather than delegating to the generic
93
- * patchRecord() helper, which would combine both into one un-safe wrap.
110
+ * flair#2478: the whole contribution runs under the memory id's per-id write
111
+ * lock (resources/memory-write-lock.ts), taken before the ledger lock and once
112
+ * without waiting. The count bump is then decided on a committed row that an
113
+ * ordinary owner PUT, PATCH or DELETE in the same Harper process, which holds
114
+ * the lock until it commits, cannot change under it. Not serialized with it: a
115
+ * composed PUT that commits after releasing its lock, and a raw operations
116
+ * write. A contribution that cannot take that lock, or the ledger lock,
117
+ * writes nothing for that id and is logged as skipped.
94
118
  *
95
- * The final get-then-put for the increment is a best-effort (non-atomic)
96
- * read-modify-write — a concurrent contribution from a DIFFERENT agent
97
- * landing between this call's read and write could lose one increment.
98
- * Search hit-tracking is no longer this class of race (flair#1528;
99
- * resources/hit-tracking.ts coalesces MemoryHitStat increments).
100
- * Re-fetching immediately before the write (rather than reusing the
101
- * earlier existence-check read) narrows, without eliminating, that
102
- * window. Not solved here: bounded, low-severity (an undercount, never an
103
- * inflation), and orthogonal to the anti-gaming properties the cap/floor
104
- * and dedup ledger actually defend.
119
+ * The count bump is the shared write-back helper (write-back.ts): the row is
120
+ * read inside a transaction this call OWNS, the bump is built from THAT read,
121
+ * and the committed row is re-read before commit. The plan skips an absent
122
+ * row or one outside the agent's read scope before any identity comparison.
123
+ * For a row the plan does not skip, an identity change the in-transaction read
124
+ * already sees throws WriteBackConflictError at once (no retry). Only a
125
+ * pre-commit conflict retries. A post-commit mismatch is terminal and
126
+ * unconfirmed. The earlier read only decides
127
+ * the read-scope gate above; it never authorizes the count write on its own.
105
128
  *
106
129
  * Called by recordUsageBatch() (POST /RecordUsage, explicit usage feedback)
107
130
  * and by recordCitations() below (citation-on-write) — identical ledger
108
131
  * semantics regardless of which surface triggered the contribution.
109
132
  */
110
133
  export async function recordUsageContribution(ctx, agentId, memoryId, attribution, now, canRead) {
111
- const ledgerId = `${agentId}:${memoryId}`;
112
- // Bypasses resources/MemoryUsage.ts's own auth wrapper by design — this
113
- // IS the trusted internal caller that resource's module doc describes
114
- // (same "raw table object" pattern resources/Memory.ts uses for
115
- // MemoryGrant).
116
- const existingContribution = await withDetachedTxn(ctx, () => databases.flair.MemoryUsage.get(ledgerId)).catch(() => null);
117
- if (existingContribution)
118
- return; // already counted by this agent — silent no-op
119
- // Absent, unreadable, or a failed read: ONE silent no-op branch (no
120
- // enumeration). A read failure is never evidence the memory is readable.
121
- const memory = await withDetachedTxn(ctx, () => databases.flair.Memory.get(memoryId)).catch(() => null);
122
- if (!memory || !canRead(memory))
134
+ // Global lock order (flair#2478): the sorted Memory id locks first, then the
135
+ // usage ledger. Memory.put() records its citations after releasing its target
136
+ // id's lock, so a citation holds no other Memory id lock when it tries this
137
+ // one. The whole contribution — the ledger check, any ledger create
138
+ // and the count bump — runs under the memory id's write lock, taken once with
139
+ // no wait: the count bump's decision is then made on a committed row an
140
+ // ordinary owner PUT or PATCH cannot change under it (the writes it does not
141
+ // serialize are named above).
142
+ // Test-only: before this contribution tries the memory id's lock.
143
+ const beforeLock = txnPausePoint("usage-contribution-lock");
144
+ if (beforeLock)
145
+ await beforeLock;
146
+ const memoryOutcome = await withMemoryWriteLockOnce(databases?.flair?.Memory?.primaryStore, [memoryId], async () => {
147
+ // Within one Harper process, the per-(agentId, memoryId) lock serializes
148
+ // contributions across the ledger check, any create and any count bump.
149
+ const store = databases?.flair?.MemoryUsage?.primaryStore;
150
+ return withKeyLock(store, [USAGE_LEDGER_LOCK_NAMESPACE, agentId, memoryId], () => recordUsageContributionLocked(ctx, agentId, memoryId, attribution, now, canRead), USAGE_LOCK_ATTEMPTS, USAGE_LOCK_WAIT_MS);
151
+ }, { phase: "usage-count" });
152
+ // The memory lock could not be acquired (a held id, an outcome-unknown
153
+ // marker, or a store with no lock): this contribution writes nothing and is
154
+ // skipped, never written unserialized over an owner's write. It is reported
155
+ // here; the caller still gets its recorded response. Other ids in the same
156
+ // batch may already have been credited.
157
+ if (memoryOutcome.kind !== "done") {
158
+ console.warn("[usage-recording] contribution skipped: %s for memory %s", memoryOutcome.kind, memoryId);
159
+ return;
160
+ }
161
+ // The ledger lock could not be acquired: same skip, same report.
162
+ if (memoryOutcome.value.kind !== "done") {
163
+ console.warn("[usage-recording] contribution skipped: usage_ledger_%s for memory %s", memoryOutcome.value.kind, memoryId);
123
164
  return;
124
- const ledgerRecord = { id: ledgerId, agentId, memoryId, createdAt: now };
125
- if (attribution)
126
- ledgerRecord.attribution = attribution;
127
- // .put(), not .post(): Harper's raw TableResource has no default post()
128
- // implementation for a static-style (non-`isCollection`-instantiated)
129
- // call — confirmed live ("The MemoryUsage does not have a post method
130
- // implemented", statusCode 405) — the SAME class of gotcha
131
- // resources/Memory.ts documents for HTTP POST, but here it bites even
132
- // this in-process call. Irrelevant anyway: ledgerId is already a
133
- // deterministic composite key, so this is a create-with-explicit-id —
134
- // exactly what PUT (upsert) is for, not an auto-generated-id insert.
135
- await withDetachedTxn(ctx, () => databases.flair.MemoryUsage.put(ledgerRecord));
136
- // Targeted usageCount-ONLY bump: read-full-record, merge just this one
137
- // field, write — against the RAW Memory table, NEVER Memory.put() (the
138
- // resource class): that would 403 this cross-agent write via its
139
- // ownership check, and bypassing that check directly would risk letting
140
- // this write path smuggle OTHER field changes through instead of just the
141
- // count (RecordUsage.ts module doc's "WHY THIS IS ITS OWN ENDPOINT").
142
- const fresh = await withDetachedTxn(ctx, () => databases.flair.Memory.get(memoryId)).catch(() => null);
143
- // Deleted, or moved out of the agent's read scope, between the check above
144
- // and now — the count is not bumped (the ledger row written above stays).
145
- // The count is only ever bumped on a row in the agent's read scope.
146
- if (!fresh || !canRead(fresh))
165
+ }
166
+ // Test-only: pause after the ledger lock releases and the owned transaction
167
+ // commits, before this request's transaction commits (flair#2333).
168
+ const committed = txnPausePoint("usage-ledger-lock-released");
169
+ if (committed)
170
+ await committed;
171
+ }
172
+ /** The per-(agentId, memoryId) lock namespace and wait (resources/key-lock.ts). */
173
+ const USAGE_LEDGER_LOCK_NAMESPACE = "flair-usage-ledger";
174
+ const USAGE_LOCK_ATTEMPTS = 200;
175
+ const USAGE_LOCK_WAIT_MS = 10;
176
+ /**
177
+ * The ledger check, the ledger create and the count bump, run while holding the
178
+ * (agentId, memoryId) lock: see `recordUsageContribution` for the whole contract.
179
+ * Split out so the whole check-and-write runs under the lock; it is never called
180
+ * outside it.
181
+ */
182
+ async function recordUsageContributionLocked(ctx, agentId, memoryId, attribution, now, canRead) {
183
+ const ledgerId = `${agentId}:${memoryId}`;
184
+ // Within one Harper process, the ledger check and any create share an owned
185
+ // transaction that commits before the contribution lock releases. The count
186
+ // bump uses a separate owned transaction.
187
+ const prepared = await withOwnedTransaction(ctx, async (owned) => {
188
+ // Bypasses resources/MemoryUsage.ts's own auth wrapper by design — this
189
+ // IS the trusted internal caller that resource's module doc describes
190
+ // (same "raw table object" pattern resources/Memory.ts uses for
191
+ // MemoryGrant). The read DECIDES whether a row is already there, so a
192
+ // failed read is not "no row": abort this contribution (fail closed,
193
+ // named) rather than upsert over the stored row and bump the count again.
194
+ let existingContribution;
195
+ try {
196
+ existingContribution = await databases.flair.MemoryUsage.get(ledgerId, owned);
197
+ }
198
+ catch (err) {
199
+ throw new UsageLedgerReadError(ledgerId, err);
200
+ }
201
+ if (existingContribution)
202
+ return null; // already counted by this agent — silent no-op
203
+ // Test-only: pause after finding no ledger row. Creation and the count bump
204
+ // still require their read-scope gates and successful writes.
205
+ const pause = txnPausePoint("usage-contribution-claim");
206
+ if (pause)
207
+ await pause;
208
+ // Absent, unreadable, or a failed read: ONE silent no-op branch (no
209
+ // enumeration). A read failure is never evidence the memory is readable.
210
+ const memory = await databases.flair.Memory.get(memoryId, owned).catch(() => null);
211
+ if (!memory || !canRead(memory))
212
+ return null;
213
+ const ledgerRecord = { id: ledgerId, agentId, memoryId, createdAt: now };
214
+ if (attribution)
215
+ ledgerRecord.attribution = attribution;
216
+ // .put(), not .post(): Harper's raw TableResource has no default post()
217
+ // implementation for a static-style (non-`isCollection`-instantiated)
218
+ // call — confirmed live ("The MemoryUsage does not have a post method
219
+ // implemented", statusCode 405) — the SAME class of gotcha
220
+ // resources/Memory.ts documents for HTTP POST, but here it bites even
221
+ // this in-process call. Irrelevant anyway: ledgerId is already a
222
+ // deterministic composite key, so this is a create-with-explicit-id —
223
+ // exactly what PUT (upsert) is for, not an auto-generated-id insert.
224
+ await databases.flair.MemoryUsage.put(ledgerRecord, owned);
225
+ return memory;
226
+ });
227
+ if (!prepared)
147
228
  return;
148
- const usageRow = { ...fresh, usageCount: (fresh.usageCount ?? 0) + 1 };
149
- stripUndeclaredMemoryAttributes(usageRow);
150
- await withDetachedTxn(ctx, () => databases.flair.Memory.put(usageRow));
229
+ await writeBackCommittedRow(databases.flair.Memory, memoryId, (row) => {
230
+ // Deleted, or moved out of the agent's read scope, between the check
231
+ // above and this read — the count is not bumped (the ledger row written
232
+ // above stays). The count is only ever bumped on a row in the agent's
233
+ // read scope.
234
+ if (!row || !canRead(row))
235
+ return { skip: true };
236
+ return { idempotent: false, commitMarkerField: "writeBackWriteId", update: { usageCount: (row.usageCount ?? 0) + 1 } };
237
+ }, {
238
+ ctx,
239
+ label: "usage-recording",
240
+ // The row the contribution was checked against is the basis: the helper
241
+ // refuses when the stored row is no longer it (a delete, a purge, or a
242
+ // same-id replace with a new token).
243
+ expectedRow: prepared,
244
+ pausePre: () => txnPausePoint("usage-count-pre"),
245
+ pausePoint: () => txnPausePoint("usage-count"),
246
+ pauseAfterStage: () => txnPausePoint("usage-count-staged"),
247
+ pauseBeforeCommit: () => txnPausePoint("usage-count-commit"),
248
+ pauseBeforeVerify: () => txnPausePoint("usage-count-verify"),
249
+ });
151
250
  }
152
251
  /**
153
252
  * Default record fetch for the read-scope gates in this module
@@ -243,9 +342,19 @@ export async function recordCitations(ctx, auth, usedMemoryIds, now, recordFn =
243
342
  await recordFn(ctx, auth.agentId, id, undefined, now, scope.isAllowed);
244
343
  }
245
344
  catch (err) {
246
- // Never let one bad id stop the batch — same no-op-on-error discipline
247
- // as RecordUsage.post()'s loop, log server-side only.
248
- console.error("recordCitations: failed to credit (no-op)", { memoryId: id, err });
345
+ // Log per-id failures without stopping the batch.
346
+ if (err instanceof WriteBackConflictError) {
347
+ console.error("recordCitations: %s, %s", err.outcome === "conflict" ? "contribution count write aborted" : "usage count unconfirmed", err.outcome === "conflict" ? "stored_row_changed" : "write_unconfirmed", { memoryId: id, reason: err.outcome === "conflict" ? "stored_row_changed" : "write_unconfirmed", outcome: err.outcome, err });
348
+ }
349
+ else if (err instanceof UsageLedgerReadError) {
350
+ // flair#2333: the ledger read that decides whether this pair already
351
+ // has a row failed — not "no row". This contribution is aborted (no
352
+ // ledger write, no count bump); the other ids stand.
353
+ console.error("recordCitations: not credited, ledger read failed (no-op)", { memoryId: id, ledgerId: err.ledgerId, reason: "ledger_read_failed", err });
354
+ }
355
+ else {
356
+ console.error("recordCitations: failed to credit", { memoryId: id, err });
357
+ }
249
358
  }
250
359
  }
251
360
  }
@@ -284,11 +393,18 @@ export async function recordUsageBatch(ctx, agentId, memoryIds, attribution, now
284
393
  await recordFn(ctx, agentId, memoryId, attribution, now, scope.isAllowed);
285
394
  }
286
395
  catch (err) {
287
- // Never let one bad id fail the whole batch, and never let an internal
288
- // error leak existence information either — log server-side, collapse
289
- // to the same no-op the response already returns for every other
290
- // outcome.
291
- console.error("RecordUsage.post: failed to record usage (treated as no-op)", { memoryId, err });
396
+ // Log per-id failures without changing the response.
397
+ if (err instanceof WriteBackConflictError) {
398
+ console.error("RecordUsage.post: %s, %s", err.outcome === "conflict" ? "contribution count write aborted" : "usage count unconfirmed", err.outcome === "conflict" ? "stored_row_changed" : "write_unconfirmed", { memoryId, reason: err.outcome === "conflict" ? "stored_row_changed" : "write_unconfirmed", outcome: err.outcome, err });
399
+ }
400
+ else if (err instanceof UsageLedgerReadError) {
401
+ // flair#2333: the ledger read failed — not "no row". This contribution
402
+ // is aborted (no ledger write, no count bump); the other ids stand.
403
+ console.error("RecordUsage.post: not recorded, ledger read failed (treated as no-op)", { memoryId, ledgerId: err.ledgerId, reason: "ledger_read_failed", err });
404
+ }
405
+ else {
406
+ console.error("RecordUsage.post: failed to record usage", { memoryId, err });
407
+ }
292
408
  }
293
409
  }
294
410
  }