@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
@@ -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,11 @@
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 { txnPausePoint } from "./txn-pause-point.js";
59
62
  import { resolveReadScope } from "./memory-read-scope.js";
60
63
  /**
61
64
  * Per-call cap on ids credited in one batch — shared by RecordUsage.post()'s
@@ -64,6 +67,22 @@ import { resolveReadScope } from "./memory-read-scope.js";
64
67
  * see that function's doc for why the two differ here).
65
68
  */
66
69
  export const MAX_USAGE_IDS_PER_CALL = 20;
70
+ /**
71
+ * The named refusal of a contribution whose ledger READ failed. The read is the
72
+ * decision "does this (agent, memory) pair already have a row?" — an error is
73
+ * NOT evidence there is none. Treating it as "no row" would upsert over whatever
74
+ * row is stored and bump the count a second time, so this contribution is
75
+ * aborted instead (no ledger write, no count change) and the batch logs the
76
+ * failure; the other ids in the batch are unaffected.
77
+ */
78
+ export class UsageLedgerReadError extends Error {
79
+ ledgerId;
80
+ constructor(ledgerId, cause) {
81
+ super(`usage ledger row read failed for ${ledgerId}: ${cause instanceof Error ? cause.message : String(cause)}`);
82
+ this.name = "UsageLedgerReadError";
83
+ this.ledgerId = ledgerId;
84
+ }
85
+ }
67
86
  /**
68
87
  * One (agentId, memoryId) contribution — the shared ledger-write core.
69
88
  *
@@ -79,75 +98,135 @@ export const MAX_USAGE_IDS_PER_CALL = 20;
79
98
  * Ledger-row-create FIRST, THEN the Memory.usageCount bump — so a crash
80
99
  * between the two leaves the SAFE failure state (ledger row exists, count
81
100
  * 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).
101
+ * reverse (count bumped, no ledger row → a retry would double-count). The
102
+ * ledger READ that decides all this FAILS CLOSED: an error is not "no row", so
103
+ * that contribution aborts (named UsageLedgerReadError, no ledger write, no
104
+ * count change) rather than upsert over the stored row and bump again.
83
105
  *
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.
106
+ * The ledger read and any create share an owned transaction. The count bump
107
+ * uses a separate owned transaction through writeBackCommittedRow.
94
108
  *
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.
109
+ * The count bump is the shared write-back helper (write-back.ts): the row is
110
+ * read inside a transaction this call OWNS, the bump is built from THAT read,
111
+ * and the committed row is re-read before commit. The plan skips an absent
112
+ * row or one outside the agent's read scope before any identity comparison.
113
+ * For a row the plan does not skip, an identity change the in-transaction read
114
+ * already sees throws WriteBackConflictError at once (no retry). Only a change to the committed
115
+ * row found by the re-read after the bump is staged retries, from a fresh
116
+ * read, at most WRITE_BACK_ATTEMPTS attempts in all (then
117
+ * WriteBackConflictError). recordUsageBatch / recordCitations log either
118
+ * refusal with the reason `stored_row_changed`. The earlier read only decides
119
+ * the read-scope gate above; it never authorizes the count write on its own.
105
120
  *
106
121
  * Called by recordUsageBatch() (POST /RecordUsage, explicit usage feedback)
107
122
  * and by recordCitations() below (citation-on-write) — identical ledger
108
123
  * semantics regardless of which surface triggered the contribution.
109
124
  */
110
125
  export async function recordUsageContribution(ctx, agentId, memoryId, attribution, now, canRead) {
126
+ // Within one Harper process, the per-(agentId, memoryId) lock serializes
127
+ // contributions across the ledger check, any create and any count bump.
128
+ const store = databases?.flair?.MemoryUsage?.primaryStore;
129
+ const outcome = await withKeyLock(store, [USAGE_LEDGER_LOCK_NAMESPACE, agentId, memoryId], () => recordUsageContributionLocked(ctx, agentId, memoryId, attribution, now, canRead), USAGE_LOCK_ATTEMPTS, USAGE_LOCK_WAIT_MS);
130
+ // The lock could not be acquired (or the store has none): this contribution
131
+ // writes no ledger row and makes no count change; the caller still gets its
132
+ // recorded response. Other ids in the same batch may already have been credited.
133
+ if (outcome.kind !== "done")
134
+ return;
135
+ // Test-only: pause after the ledger lock releases and the owned transaction
136
+ // commits, before this request's transaction commits (flair#2333).
137
+ const committed = txnPausePoint("usage-ledger-lock-released");
138
+ if (committed)
139
+ await committed;
140
+ }
141
+ /** The per-(agentId, memoryId) lock namespace and wait (resources/key-lock.ts). */
142
+ const USAGE_LEDGER_LOCK_NAMESPACE = "flair-usage-ledger";
143
+ const USAGE_LOCK_ATTEMPTS = 200;
144
+ const USAGE_LOCK_WAIT_MS = 10;
145
+ /**
146
+ * The ledger check, the ledger create and the count bump, run while holding the
147
+ * (agentId, memoryId) lock: see `recordUsageContribution` for the whole contract.
148
+ * Split out so the whole check-and-write runs under the lock; it is never called
149
+ * outside it.
150
+ */
151
+ async function recordUsageContributionLocked(ctx, agentId, memoryId, attribution, now, canRead) {
111
152
  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))
153
+ // Within one Harper process, the ledger check and any create share an owned
154
+ // transaction that commits before the contribution lock releases. The count
155
+ // bump uses a separate owned transaction.
156
+ const prepared = await withOwnedTransaction(ctx, async (owned) => {
157
+ // Bypasses resources/MemoryUsage.ts's own auth wrapper by design — this
158
+ // IS the trusted internal caller that resource's module doc describes
159
+ // (same "raw table object" pattern resources/Memory.ts uses for
160
+ // MemoryGrant). The read DECIDES whether a row is already there, so a
161
+ // failed read is not "no row": abort this contribution (fail closed,
162
+ // named) rather than upsert over the stored row and bump the count again.
163
+ let existingContribution;
164
+ try {
165
+ existingContribution = await databases.flair.MemoryUsage.get(ledgerId, owned);
166
+ }
167
+ catch (err) {
168
+ throw new UsageLedgerReadError(ledgerId, err);
169
+ }
170
+ if (existingContribution)
171
+ return null; // already counted by this agent — silent no-op
172
+ // Test-only: pause after finding no ledger row. Creation and the count bump
173
+ // still require their read-scope gates and successful writes.
174
+ const pause = txnPausePoint("usage-contribution-claim");
175
+ if (pause)
176
+ await pause;
177
+ // Absent, unreadable, or a failed read: ONE silent no-op branch (no
178
+ // enumeration). A read failure is never evidence the memory is readable.
179
+ const memory = await databases.flair.Memory.get(memoryId, owned).catch(() => null);
180
+ if (!memory || !canRead(memory))
181
+ return null;
182
+ const ledgerRecord = { id: ledgerId, agentId, memoryId, createdAt: now };
183
+ if (attribution)
184
+ ledgerRecord.attribution = attribution;
185
+ // .put(), not .post(): Harper's raw TableResource has no default post()
186
+ // implementation for a static-style (non-`isCollection`-instantiated)
187
+ // call — confirmed live ("The MemoryUsage does not have a post method
188
+ // implemented", statusCode 405) — the SAME class of gotcha
189
+ // resources/Memory.ts documents for HTTP POST, but here it bites even
190
+ // this in-process call. Irrelevant anyway: ledgerId is already a
191
+ // deterministic composite key, so this is a create-with-explicit-id —
192
+ // exactly what PUT (upsert) is for, not an auto-generated-id insert.
193
+ await databases.flair.MemoryUsage.put(ledgerRecord, owned);
194
+ return memory;
195
+ });
196
+ if (!prepared)
123
197
  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
198
+ // Targeted usageCount-ONLY bump: an INCREMENTAL update of exactly this one
199
+ // field through the shared helper, against the RAW Memory table, NEVER
200
+ // Memory.put() (the resource class): that would 403 this cross-agent write via
201
+ // its ownership check, and bypassing that check directly would risk letting
140
202
  // 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))
147
- return;
148
- const usageRow = { ...fresh, usageCount: (fresh.usageCount ?? 0) + 1 };
149
- stripUndeclaredMemoryAttributes(usageRow);
150
- await withDetachedTxn(ctx, () => databases.flair.Memory.put(usageRow));
203
+ // count (RecordUsage.ts module doc's "WHY THIS IS ITS OWN ENDPOINT"). The helper
204
+ // confirms, inside its own transaction, that the stored row is still the one
205
+ // this contribution was checked against (flair#2441): a row deleted or purged
206
+ // before the in-transaction read is skipped by the plan (absent row), as is a
207
+ // row outside the agent's read scope; for any other row an identity mismatch
208
+ // seen by the check is refused. An error from the transactional read is not
209
+ // caught here: it propagates to the caller.
210
+ await writeBackCommittedRow(databases.flair.Memory, memoryId, (row) => {
211
+ // Deleted, or moved out of the agent's read scope, between the check
212
+ // above and this read — the count is not bumped (the ledger row written
213
+ // above stays). The count is only ever bumped on a row in the agent's
214
+ // read scope.
215
+ if (!row || !canRead(row))
216
+ return { skip: true };
217
+ // Only `usageCount`: an incremental update, never a
218
+ // full-row put of the row read above (flair#2470).
219
+ return { update: { usageCount: (row.usageCount ?? 0) + 1 } };
220
+ }, {
221
+ ctx,
222
+ label: "usage-recording",
223
+ // The row the contribution was checked against is the basis: the helper
224
+ // refuses when the stored row is no longer it (a delete, a purge, or a
225
+ // same-id replace with a new token).
226
+ expectedRow: prepared,
227
+ pausePre: () => txnPausePoint("usage-count-pre"),
228
+ pausePoint: () => txnPausePoint("usage-count"),
229
+ });
151
230
  }
152
231
  /**
153
232
  * Default record fetch for the read-scope gates in this module
@@ -245,7 +324,22 @@ export async function recordCitations(ctx, auth, usedMemoryIds, now, recordFn =
245
324
  catch (err) {
246
325
  // Never let one bad id stop the batch — same no-op-on-error discipline
247
326
  // as RecordUsage.post()'s loop, log server-side only.
248
- console.error("recordCitations: failed to credit (no-op)", { memoryId: id, err });
327
+ if (err instanceof WriteBackConflictError) {
328
+ // flair#2441: the stored row is no longer the one read (a same-id
329
+ // replace, or a change found on every attempt); the count bump was
330
+ // refused. The ledger row was already written and committed before the
331
+ // bump, so it stays, and the count is not bumped.
332
+ console.error("recordCitations: not credited, stored_row_changed (no-op)", { memoryId: id, reason: "stored_row_changed", err });
333
+ }
334
+ else if (err instanceof UsageLedgerReadError) {
335
+ // flair#2333: the ledger read that decides whether this pair already
336
+ // has a row failed — not "no row". This contribution is aborted (no
337
+ // ledger write, no count bump); the other ids stand.
338
+ console.error("recordCitations: not credited, ledger read failed (no-op)", { memoryId: id, ledgerId: err.ledgerId, reason: "ledger_read_failed", err });
339
+ }
340
+ else {
341
+ console.error("recordCitations: failed to credit (no-op)", { memoryId: id, err });
342
+ }
249
343
  }
250
344
  }
251
345
  }
@@ -288,7 +382,21 @@ export async function recordUsageBatch(ctx, agentId, memoryIds, attribution, now
288
382
  // error leak existence information either — log server-side, collapse
289
383
  // to the same no-op the response already returns for every other
290
384
  // outcome.
291
- console.error("RecordUsage.post: failed to record usage (treated as no-op)", { memoryId, err });
385
+ if (err instanceof WriteBackConflictError) {
386
+ // flair#2441: the stored row is no longer the one read (a same-id
387
+ // replace, or a change found on every attempt); the count bump was
388
+ // refused. The ledger row was already written and committed before the
389
+ // bump, so it stays, and the count is not bumped.
390
+ console.error("RecordUsage.post: not recorded, stored_row_changed (treated as no-op)", { memoryId, reason: "stored_row_changed", err });
391
+ }
392
+ else if (err instanceof UsageLedgerReadError) {
393
+ // flair#2333: the ledger read failed — not "no row". This contribution
394
+ // is aborted (no ledger write, no count bump); the other ids stand.
395
+ console.error("RecordUsage.post: not recorded, ledger read failed (treated as no-op)", { memoryId, ledgerId: err.ledgerId, reason: "ledger_read_failed", err });
396
+ }
397
+ else {
398
+ console.error("RecordUsage.post: failed to record usage (treated as no-op)", { memoryId, err });
399
+ }
292
400
  }
293
401
  }
294
402
  }
@@ -0,0 +1,218 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { withOwnedTransaction } from "./request-transaction.js";
3
+ /** The fields of `expectedRow` (or of the helper's own first read) it compares
4
+ * with the row read inside its transaction, besides `matchFields`. */
5
+ export const WRITE_BACK_IDENTITY_FIELDS = ["id", "agentId", "instanceToken", "contentHash", "createdAt"];
6
+ /**
7
+ * Is `row` still the stored row `basis` describes? Compares the fields in
8
+ * {@link WRITE_BACK_IDENTITY_FIELDS} — the row's id and agent, and the
9
+ * server-stamped incarnation token, content hash and creation time. A `basis`
10
+ * of `null` requires `row` to still be absent.
11
+ *
12
+ * This is the identity check the write-back helper applies, exposed so a
13
+ * writer that cannot hand its write to the helper (one that joins a
14
+ * request-owned transaction, e.g. Memory.put) confirms the SAME facts: before
15
+ * it stages its write, and against the committed row after (through
16
+ * {@link confirmCommittedRow}).
17
+ */
18
+ export function sameStoredRow(row, basis) {
19
+ return row == null ? basis == null : basis != null &&
20
+ String(row.id) === String(basis.id) && row.agentId === basis.agentId &&
21
+ row.instanceToken === basis.instanceToken && row.contentHash === basis.contentHash && row.createdAt === basis.createdAt;
22
+ }
23
+ /**
24
+ * The named 409 for a write refused because the row it read is no longer the
25
+ * stored one: the row is gone (a delete or a purge committed) or its identity
26
+ * changed (a same-id replace committed: a field {@link sameStoredRow} compares,
27
+ * such as the incarnation token, differs). Nothing was written.
28
+ */
29
+ export function storedRowChangedRefusal(tableName) {
30
+ return new Response(JSON.stringify({
31
+ error: "stored_row_changed",
32
+ message: `${tableName} row changed since it was read; not written`,
33
+ }), { status: 409, headers: { "content-type": "application/json" } });
34
+ }
35
+ /** Only the identity fields of `row`: an `expectedRow` for a caller that
36
+ * selects many rows before writing each back, so it need not hold them whole. */
37
+ export function writeBackIdentity(row) {
38
+ const identity = {};
39
+ for (const field of WRITE_BACK_IDENTITY_FIELDS)
40
+ identity[field] = row[field];
41
+ return identity;
42
+ }
43
+ /** Attempts of a write-back before it gives up on a row that keeps changing. */
44
+ export const WRITE_BACK_ATTEMPTS = 3;
45
+ /**
46
+ * The helper's named refusal: the row changed and nothing was written. Both
47
+ * checks that lead to it (the in-transaction comparison, and the committed-row
48
+ * confirmation after the write is staged) run inside the owned transaction
49
+ * before any commit is submitted, and their throw aborts that transaction, so
50
+ * its staged write is discarded. Whichever check fails, the outcome is known:
51
+ * not written.
52
+ */
53
+ export class WriteBackConflictError extends Error {
54
+ id;
55
+ constructor(label, id, attempts) {
56
+ super(`${label}: row ${id} changed; write not applied (${attempts} attempts)`);
57
+ this.name = "WriteBackConflictError";
58
+ this.id = id;
59
+ }
60
+ }
61
+ /** Aborts the write's transaction: the COMMITTED row, re-read after the write
62
+ * was staged, is no longer the one the write is over. Inside the helper it
63
+ * never escapes (it is retried, then named by {@link WriteBackConflictError});
64
+ * a writer that runs {@link confirmCommittedRow} itself (Memory.put) catches it
65
+ * outside its transaction and answers with {@link storedRowChangedRefusal}. */
66
+ export class CommittedRowChanged extends Error {
67
+ constructor() {
68
+ super("committed row changed after the write was staged");
69
+ this.name = "CommittedRowChanged";
70
+ }
71
+ }
72
+ /**
73
+ * The committed-row confirmation the write-back helper runs once its write is
74
+ * staged and before its transaction commits: re-read the COMMITTED row and
75
+ * throw {@link CommittedRowChanged} unless `same(committed)` holds. The
76
+ * transaction must then abort so the staged write is discarded: an owned
77
+ * transaction aborts when the throw leaves its callback; a caller that joined
78
+ * a request-owned transaction aborts it itself (Memory.put does).
79
+ *
80
+ * The read is an EXPLICIT fresh context, never contextless: a contextless read
81
+ * joins the caller's transaction and sees its old snapshot or its staged write.
82
+ * Harper has no compare-and-set on a table write, so a change committed after
83
+ * this read and before the commit is not seen by it.
84
+ *
85
+ * Exported so a writer that cannot hand its write to the helper (Memory.put,
86
+ * which joins a request-owned transaction) runs the same re-read, with its own
87
+ * predicate (the helper compares the whole row; Memory.put, sameStoredRow).
88
+ */
89
+ export async function confirmCommittedRow(table, id, same) {
90
+ const committed = await table.get(id, {});
91
+ if (!same(committed))
92
+ throw new CommittedRowChanged();
93
+ }
94
+ /**
95
+ * The name for a close whose authorizing "write" grant is gone at the
96
+ * committed-state re-check (flair#2333 H10 / flair#2511). The two closes share
97
+ * the re-check ({@link writeGrantHeld}) and this name, but only the
98
+ * skill-version close answers its caller with it. The skill-version close
99
+ * (skill-version-write.ts) returns {@link grantedCloseRevokedRefusal}, a 409
100
+ * carrying this code. The non-skill close (Memory.ts closeSupersededRecord) runs
101
+ * after its successor is written and throws {@link GrantedCloseRevoked}, which
102
+ * its caller logs: the predecessor stays open, the successor stays written, and
103
+ * the caller's response is a success.
104
+ */
105
+ export const GRANTED_CLOSE_REVOKED = "granted_close_revoked";
106
+ /** The skill-version close's named 409 for a close whose authorizing "write"
107
+ * grant is gone at the committed-state re-check. Returned from inside the
108
+ * version transaction, which then rolls back: nothing is written. */
109
+ export function grantedCloseRevokedRefusal() {
110
+ return new Response(JSON.stringify({
111
+ error: GRANTED_CLOSE_REVOKED,
112
+ message: "the write grant authorizing this close was revoked; not written",
113
+ }), { status: 409, headers: { "content-type": "application/json" } });
114
+ }
115
+ /** Aborts the non-skill close's owned transaction (Memory.ts
116
+ * closeSupersededRecord): the "write" grant that authorized a cross-agent close
117
+ * is gone on committed state (flair#2333 H10). The predecessor is not closed;
118
+ * the caller logs this after its successor is already written. */
119
+ export class GrantedCloseRevoked extends Error {
120
+ constructor() {
121
+ super(`${GRANTED_CLOSE_REVOKED}: the write grant authorizing the close was revoked`);
122
+ this.name = "GrantedCloseRevoked";
123
+ }
124
+ }
125
+ /**
126
+ * Does `table` hold a "write" grant from `ownerId` to `granteeId`? A caller that
127
+ * re-checks on committed state passes an explicit fresh context (`{}`) rather
128
+ * than its own transaction — the same discipline {@link confirmCommittedRow}
129
+ * applies to a row. Fail-closed: a search that rejects reads as no grant, so an
130
+ * unreadable grant does not close the owner's row.
131
+ *
132
+ * The committed-state grant re-check both closes run after staging a
133
+ * grant-authorized cross-agent close: the non-skill close (Memory.ts
134
+ * closeSupersededRecord, flair#2333 H10) and the shared skill-version writer
135
+ * (skill-version-write.ts, flair#2511), whose every caller passes the grant a
136
+ * cross-agent close stands on.
137
+ */
138
+ export async function writeGrantHeld(table, granteeId, ownerId, ctx) {
139
+ try {
140
+ for await (const grant of table.search({
141
+ conditions: [
142
+ { attribute: "granteeId", comparator: "equals", value: granteeId },
143
+ { attribute: "ownerId", comparator: "equals", value: ownerId },
144
+ ],
145
+ }, ctx)) {
146
+ if (grant?.scope === "write")
147
+ return true;
148
+ }
149
+ }
150
+ catch {
151
+ return false;
152
+ }
153
+ return false;
154
+ }
155
+ /**
156
+ * Write an incremental update of exactly `patch`'s fields, in the caller's
157
+ * transaction. Refuses by name when the table cannot write incrementally
158
+ * (a fake or a stub without `update`): falling back to a full-row `put` here
159
+ * would reintroduce the very full-row write this helper's `update` plan exists
160
+ * to avoid.
161
+ */
162
+ async function applyFieldUpdate(table, id, patch, ctx) {
163
+ if (typeof table.update !== "function") {
164
+ throw new Error("write-back: the table has no incremental update; refusing to fall back to a full-row put");
165
+ }
166
+ await table.update(id, patch, ctx);
167
+ }
168
+ export async function writeBackCommittedRow(table, id, plan, opts) {
169
+ const attempts = opts.attempts ?? WRITE_BACK_ATTEMPTS;
170
+ const selected = "expectedRow" in opts ? opts.expectedRow : await table.get(id, {});
171
+ const basis = selected == null ? selected : { ...selected };
172
+ const sameTarget = (row) => {
173
+ if (row == null)
174
+ return basis == null;
175
+ if (basis == null)
176
+ return false;
177
+ return sameStoredRow(row, basis) &&
178
+ (!opts.wholeRow || isDeepStrictEqual({ ...row }, basis)) &&
179
+ (opts.matchFields ?? []).every((field) => isDeepStrictEqual(row[field], basis[field]));
180
+ };
181
+ if (opts.pausePre) {
182
+ const pre = opts.pausePre();
183
+ if (pre)
184
+ await pre;
185
+ }
186
+ for (let attempt = 1;; attempt++) {
187
+ try {
188
+ return await withOwnedTransaction(opts.ctx, async (c) => {
189
+ const row = await table.get(id, c);
190
+ if (opts.matches && !opts.matches(row))
191
+ return { skip: true };
192
+ const decision = await plan(row);
193
+ if ("skip" in decision)
194
+ return decision;
195
+ if (!sameTarget(row))
196
+ throw new WriteBackConflictError(opts.label, id, attempt);
197
+ // Test-only: inert unless the fault-injection opt-in is armed.
198
+ if (opts.pausePoint) {
199
+ const pause = opts.pausePoint();
200
+ if (pause)
201
+ await pause;
202
+ }
203
+ if ("update" in decision)
204
+ await applyFieldUpdate(table, id, decision.update, c);
205
+ else
206
+ await table.put(decision.write, c);
207
+ await confirmCommittedRow(table, id, (committed) => isDeepStrictEqual(committed, row));
208
+ return decision;
209
+ });
210
+ }
211
+ catch (err) {
212
+ if (!(err instanceof CommittedRowChanged))
213
+ throw err;
214
+ if (attempt >= attempts)
215
+ throw new WriteBackConflictError(opts.label, id, attempts);
216
+ }
217
+ }
218
+ }
@@ -0,0 +1 @@
1
+ export const ENGINE_VERSION_STAMP = "engine-version.txt";
@@ -11,6 +11,7 @@
11
11
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
12
  import { join } from "node:path";
13
13
  import { resolveHome } from "./lib/home.js";
14
+ import { writeFilesAtomically } from "./lib/atomic-write.js";
14
15
  import { randomBytes, createCipheriv, createDecipheriv, hkdfSync, } from "node:crypto";
15
16
  // ─── Helpers ────────────────────────────────────────────────────────────────
16
17
  /**
@@ -120,5 +121,76 @@ class FileKeyStore {
120
121
  }
121
122
  /** Singleton keystore instance. */
122
123
  export const keystore = new FileKeyStore();
124
+ // ─── Seed ownership sidecars (flair#2200) ───────────────────────────────────
125
+ /** File name suffix of a seed's ownership sidecar, appended to the seed path. */
126
+ export const SEED_OWNER_SUFFIX = ".owner.json";
127
+ /** The sidecar's schema version. */
128
+ export const SEED_OWNER_VERSION = 1;
129
+ /** The sidecar path for `instanceId` — the seed path plus the owner suffix. */
130
+ export function seedOwnerPath(instanceId) {
131
+ return `${keyPath(instanceId)}${SEED_OWNER_SUFFIX}`;
132
+ }
133
+ /** Serialize an ownership record to the exact bytes the sidecar holds. */
134
+ export function serializeSeedOwner(record) {
135
+ return `${JSON.stringify(record)}\n`;
136
+ }
137
+ /** Parse sidecar bytes into a read result. Pure — no filesystem access. */
138
+ export function parseSeedOwner(raw) {
139
+ let value;
140
+ try {
141
+ value = JSON.parse(raw);
142
+ }
143
+ catch (err) {
144
+ return { state: "malformed", reason: `not valid JSON (${err instanceof Error ? err.message : String(err)})` };
145
+ }
146
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
147
+ return { state: "malformed", reason: "not a JSON object" };
148
+ }
149
+ const rec = value;
150
+ if (rec.v !== SEED_OWNER_VERSION) {
151
+ return { state: "malformed", reason: `unsupported owner-record version ${JSON.stringify(rec.v)}` };
152
+ }
153
+ if (typeof rec.instanceId !== "string" || rec.instanceId.trim() === "") {
154
+ return { state: "malformed", reason: "no instance id" };
155
+ }
156
+ if (typeof rec.dataDir !== "string" || rec.dataDir.trim() === "") {
157
+ return { state: "malformed", reason: "no data directory" };
158
+ }
159
+ return { state: "ok", instanceId: rec.instanceId, dataDir: rec.dataDir };
160
+ }
161
+ /** Read a sidecar from its path, distinguishing absent / unreadable / malformed. */
162
+ export function readSeedOwnerAt(ownerPath) {
163
+ if (!existsSync(ownerPath))
164
+ return { state: "absent" };
165
+ let raw;
166
+ try {
167
+ raw = readFileSync(ownerPath, "utf-8");
168
+ }
169
+ catch (err) {
170
+ return { state: "unreadable", reason: err instanceof Error ? err.message : String(err) };
171
+ }
172
+ return parseSeedOwner(raw);
173
+ }
174
+ /** Read the ownership sidecar for `instanceId`, if any. */
175
+ export function readSeedOwner(instanceId) {
176
+ return readSeedOwnerAt(seedOwnerPath(instanceId));
177
+ }
178
+ /**
179
+ * Record an instance seed's owner: write the sidecar atomically (owner-only,
180
+ * mode 0600) beside the seed. The writer is the mint; a reader never invents
181
+ * one. Throws on a write failure — the caller decides whether that is fatal.
182
+ */
183
+ export function recordSeedOwner(instanceId, dataDir) {
184
+ const dir = keysDir();
185
+ if (!existsSync(dir))
186
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
187
+ writeFilesAtomically([
188
+ {
189
+ path: seedOwnerPath(instanceId),
190
+ content: serializeSeedOwner({ v: SEED_OWNER_VERSION, instanceId, dataDir }),
191
+ mode: 0o600,
192
+ },
193
+ ]);
194
+ }
123
195
  // Export helpers for testing
124
196
  export { encryptSeed, decryptSeed, deriveKey, keyPath, keysDir };