@tpsdev-ai/flair 0.62.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 (232) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +18 -10
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/types.js +1 -0
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli.js +66 -122
  8. package/dist/commands/agent.js +27 -65
  9. package/dist/commands/backup-approval.js +218 -0
  10. package/dist/commands/backup.js +37 -33
  11. package/dist/commands/bootstrap.js +3 -1
  12. package/dist/commands/deploy.js +37 -7
  13. package/dist/commands/doctor.js +119 -0
  14. package/dist/commands/export.js +3 -4
  15. package/dist/commands/federation.js +653 -68
  16. package/dist/commands/grant.js +5 -6
  17. package/dist/commands/help.js +25 -0
  18. package/dist/commands/idp.js +14 -19
  19. package/dist/commands/import.js +131 -19
  20. package/dist/commands/init.js +7 -7
  21. package/dist/commands/integrity.js +5 -6
  22. package/dist/commands/mcp.js +11 -17
  23. package/dist/commands/memory.js +33 -15
  24. package/dist/commands/orgevent.js +5 -10
  25. package/dist/commands/principal.js +13 -25
  26. package/dist/commands/quality.js +3 -0
  27. package/dist/commands/rem.js +484 -65
  28. package/dist/commands/restore.js +352 -44
  29. package/dist/commands/service.js +84 -2
  30. package/dist/commands/soul.js +0 -6
  31. package/dist/commands/status.js +51 -33
  32. package/dist/commands/test.js +4 -1
  33. package/dist/commands/upgrade.js +53 -22
  34. package/dist/commands/workspace.js +7 -8
  35. package/dist/deploy.js +59 -3
  36. package/dist/doctor-client.js +7 -2
  37. package/dist/fabric-upgrade.js +12 -2
  38. package/dist/federation/presence-send.js +139 -0
  39. package/dist/federation-verify.js +269 -177
  40. package/dist/install/clients.js +171 -35
  41. package/dist/lib/agent-id-rule.js +44 -2
  42. package/dist/lib/atomic-write.js +1 -1
  43. package/dist/lib/auth-resolve.js +1028 -52
  44. package/dist/lib/backup-approval-store.js +612 -0
  45. package/dist/lib/backup-artifact.js +343 -0
  46. package/dist/lib/config-critical-section.js +212 -25
  47. package/dist/lib/connect-phase.js +33 -0
  48. package/dist/lib/daemon-liveness.js +2 -1
  49. package/dist/lib/federation-pair-access.js +4 -0
  50. package/dist/lib/federation-retry-queue.js +283 -0
  51. package/dist/lib/federation-retry-row.js +101 -0
  52. package/dist/lib/instruction-event-contract.js +17 -0
  53. package/dist/lib/instruction-event-doctor.js +102 -0
  54. package/dist/lib/launchd-management.js +14 -3
  55. package/dist/lib/mcp-enable.js +14 -15
  56. package/dist/lib/memory-attributes.js +2 -0
  57. package/dist/lib/memory-provider-timeout.js +33 -0
  58. package/dist/lib/mqtt-config.js +132 -0
  59. package/dist/lib/mqtt-listener-doctor.js +104 -0
  60. package/dist/lib/open-live-row.js +20 -0
  61. package/dist/lib/ops-url.js +52 -0
  62. package/dist/lib/promotion-content-hash.js +20 -0
  63. package/dist/lib/restore-archive.js +760 -0
  64. package/dist/lib/restore-verify.js +1 -1
  65. package/dist/lib/skill-assignment-preflight.js +159 -0
  66. package/dist/lib/skill-seed.js +91 -8
  67. package/dist/lib/skill-tombstone-doctor.js +133 -0
  68. package/dist/lib/soul-scope-fields.js +26 -0
  69. package/dist/lib/uninstall-purge.js +266 -11
  70. package/dist/lib/upgrade-prior-liveness.js +2 -1
  71. package/dist/mcp-client-assertion.js +2 -10
  72. package/dist/memory-id-checkpoint.js +28 -7
  73. package/dist/mqtt-off-deploy.js +550 -0
  74. package/dist/rem/promote-policy.js +3 -3
  75. package/dist/rem/restore.js +302 -26
  76. package/dist/rem/runner.js +220 -58
  77. package/dist/rem/scheduler.js +21 -4
  78. package/dist/resources/A2AAdapter.js +131 -178
  79. package/dist/resources/AdminMemory.js +2 -0
  80. package/dist/resources/AdminMemoryCandidates.js +116 -0
  81. package/dist/resources/Agent.js +155 -45
  82. package/dist/resources/AgentCard.js +4 -0
  83. package/dist/resources/AgentKeyRegister.js +56 -22
  84. package/dist/resources/AgentReadPosition.js +7 -0
  85. package/dist/resources/AgentSeed.js +232 -107
  86. package/dist/resources/AutoPromoteCandidates.js +413 -84
  87. package/dist/resources/Credential.js +6 -8
  88. package/dist/resources/Federation.js +219 -57
  89. package/dist/resources/FederationRetry.js +4 -4
  90. package/dist/resources/InstructionVersion.js +1 -1
  91. package/dist/resources/MCPClientMetadata.js +6 -3
  92. package/dist/resources/Memory.js +1303 -270
  93. package/dist/resources/MemoryArchive.js +149 -64
  94. package/dist/resources/MemoryBootstrap.js +12 -22
  95. package/dist/resources/MemoryCandidate.js +16 -2
  96. package/dist/resources/MemoryConsolidate.js +2 -2
  97. package/dist/resources/MemoryFeed.js +360 -147
  98. package/dist/resources/MemoryMaintenance.js +290 -72
  99. package/dist/resources/MemoryPurge.js +138 -22
  100. package/dist/resources/MemoryReflect.js +68 -14
  101. package/dist/resources/MemoryReindex.js +91 -13
  102. package/dist/resources/Message.js +11 -2
  103. package/dist/resources/OAuth.js +156 -39
  104. package/dist/resources/OAuthClient.js +1 -1
  105. package/dist/resources/OrgEvent.js +292 -29
  106. package/dist/resources/OrgEventCatchup.js +7 -0
  107. package/dist/resources/OrgEventMaintenance.js +48 -10
  108. package/dist/resources/PairingToken.js +1 -1
  109. package/dist/resources/Presence.js +31 -11
  110. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  111. package/dist/resources/RecordUsage.js +2 -4
  112. package/dist/resources/Soul.js +2 -0
  113. package/dist/resources/SoulFeed.js +2 -1
  114. package/dist/resources/WorkspaceLatest.js +4 -0
  115. package/dist/resources/XAA.js +36 -10
  116. package/dist/resources/a2a-stream.js +313 -0
  117. package/dist/resources/a2a-url.js +4 -5
  118. package/dist/resources/agent-admin.js +10 -1
  119. package/dist/resources/agent-auth.js +98 -68
  120. package/dist/resources/agent-read-position-lib.js +4 -1
  121. package/dist/resources/agent-status-guard.js +9 -7
  122. package/dist/resources/auth-middleware.js +166 -42
  123. package/dist/resources/authority-field-guard.js +9 -11
  124. package/dist/resources/auto-promote-lib.js +8 -5
  125. package/dist/resources/basic-auth-header.js +21 -0
  126. package/dist/resources/bm25-index-service.js +4 -5
  127. package/dist/resources/dedup-cluster.js +6 -1
  128. package/dist/resources/embeddings-provider.js +25 -0
  129. package/dist/resources/federation-classify.js +89 -0
  130. package/dist/resources/federation-retry-lib.js +6 -81
  131. package/dist/resources/health.js +43 -4
  132. package/dist/resources/host-pointer/registry.js +29 -0
  133. package/dist/resources/host-pointer-adapter.js +1 -0
  134. package/dist/resources/in-process.js +24 -22
  135. package/dist/resources/instruction-version-record.js +251 -7
  136. package/dist/resources/internal-authority.js +13 -0
  137. package/dist/resources/mcp-handler.js +106 -12
  138. package/dist/resources/mcp-oauth-flag.js +12 -14
  139. package/dist/resources/mcp-oauth.js +430 -53
  140. package/dist/resources/mcp-tools.js +60 -22
  141. package/dist/resources/memory-declared-attributes.js +1 -0
  142. package/dist/resources/memory-embed-hash.js +56 -0
  143. package/dist/resources/memory-host-source.js +5 -2
  144. package/dist/resources/memory-reflect-lib.js +1 -1
  145. package/dist/resources/memory-write-lock.js +202 -23
  146. package/dist/resources/memory-write-response.js +1 -1
  147. package/dist/resources/memory-write-transaction.js +243 -0
  148. package/dist/resources/migration-boot.js +17 -12
  149. package/dist/resources/migrations/boot-progress.js +25 -0
  150. package/dist/resources/migrations/data-dir.js +16 -3
  151. package/dist/resources/migrations/dir-safety.js +60 -2
  152. package/dist/resources/migrations/embedding-stamp.js +315 -49
  153. package/dist/resources/migrations/graph-heal.js +9 -2
  154. package/dist/resources/migrations/ledger.js +5 -2
  155. package/dist/resources/migrations/lock.js +867 -80
  156. package/dist/resources/migrations/progress.js +71 -10
  157. package/dist/resources/migrations/runner.js +212 -18
  158. package/dist/resources/migrations/state.js +36 -1
  159. package/dist/resources/migrations/status.js +2 -13
  160. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  161. package/dist/resources/migrations/types.js +26 -1
  162. package/dist/resources/migrations/visibility-backfill.js +111 -70
  163. package/dist/resources/oauth-discovery.js +0 -5
  164. package/dist/resources/object-body-guard.js +12 -5
  165. package/dist/resources/org-event-reserved.js +92 -0
  166. package/dist/resources/org-event-write-fault.js +19 -0
  167. package/dist/resources/owner-field-guard.js +1 -1
  168. package/dist/resources/owner-scoped-write-policy.js +65 -21
  169. package/dist/resources/owner-scoped-writes.js +37 -6
  170. package/dist/resources/path-id-rewrite.js +76 -0
  171. package/dist/resources/presence-internal.js +5 -5
  172. package/dist/resources/promotion-binding.js +43 -0
  173. package/dist/resources/promotion-stamp.js +124 -33
  174. package/dist/resources/protocol-context.js +189 -0
  175. package/dist/resources/record-type-kit.js +2 -4
  176. package/dist/resources/request-target.js +28 -1
  177. package/dist/resources/request-transaction.js +11 -1
  178. package/dist/resources/seed-reservation.js +1 -2
  179. package/dist/resources/semantic-retrieval-core.js +7 -6
  180. package/dist/resources/server-row-validation.js +71 -0
  181. package/dist/resources/skill-manifest.js +4 -3
  182. package/dist/resources/skill-version-write.js +384 -27
  183. package/dist/resources/skill-write-fault.js +6 -3
  184. package/dist/resources/skill-write-policy.js +2 -1
  185. package/dist/resources/soul-write-policy.js +26 -7
  186. package/dist/resources/table-helpers.js +1 -1
  187. package/dist/resources/table-subscription-policy.js +518 -85
  188. package/dist/resources/table-subscriptions.js +20 -7
  189. package/dist/resources/txn-pause-point.js +122 -5
  190. package/dist/resources/usage-recording.js +54 -46
  191. package/dist/resources/write-back.js +176 -11
  192. package/dist/resources/write-journal-context.js +5 -0
  193. package/dist/resources/write-journal.js +289 -0
  194. package/dist/src/lib/agent-id-rule.js +44 -2
  195. package/dist/src/lib/atomic-write.js +1 -1
  196. package/dist/src/lib/federation-retry-row.js +101 -0
  197. package/dist/src/lib/instruction-event-contract.js +17 -0
  198. package/dist/src/lib/memory-attributes.js +2 -0
  199. package/dist/src/lib/open-live-row.js +20 -0
  200. package/dist/src/lib/soul-scope-fields.js +26 -0
  201. package/dist/src/rem/promote-policy.js +3 -3
  202. package/dist/src/rem/scheduler.js +21 -4
  203. package/docs/access-control.md +18 -9
  204. package/docs/api-reference.md +126 -28
  205. package/docs/auth.md +40 -18
  206. package/docs/claude-code.md +3 -3
  207. package/docs/deploying-on-fabric.md +108 -0
  208. package/docs/deployment.md +17 -0
  209. package/docs/embedding-in-a-harper-app.md +16 -14
  210. package/docs/entity-vocabulary.md +3 -6
  211. package/docs/federation.md +29 -2
  212. package/docs/integrations.md +11 -11
  213. package/docs/mcp-clients.md +7 -5
  214. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  215. package/docs/notes/mcp-oauth-model2.md +6 -6
  216. package/docs/openclaw.md +1 -1
  217. package/docs/quickstart-fabric.md +2 -2
  218. package/docs/quickstart.md +3 -3
  219. package/docs/releasing.md +13 -13
  220. package/docs/rem.md +24 -3
  221. package/docs/secrets-and-keys.md +2 -2
  222. package/docs/standalone-local.md +29 -2
  223. package/docs/supply-chain-policy.md +28 -20
  224. package/docs/the-team.md +2 -2
  225. package/docs/upgrade.md +14 -0
  226. package/package.json +18 -11
  227. package/schemas/agent.graphql +3 -3
  228. package/schemas/federation.graphql +10 -7
  229. package/schemas/memory.graphql +7 -2
  230. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  231. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  232. package/dist/resources/soul-adk-guard.js +0 -68
@@ -1,11 +1,24 @@
1
1
  /**
2
- * Installs the table-subscription guard (resources/table-subscription-policy.ts)
3
- * on every table class in the flair database's table registry when the
4
- * component loads: the static `connect()` of each table class — the entry
5
- * Harper uses for an exported table's SSE and WebSocket subscription routes —
6
- * admits only administrators and trusted internal calls. The tables are read
7
- * from the registry, so the class of a table added to the schema gets the guard
8
- * without being named here.
2
+ * Installs the table-subscription guard
3
+ * (resources/table-subscription-policy.ts) on every table class in the flair
4
+ * database's table registry when the component loads: the static `connect()`
5
+ * (the entry Harper uses for an exported table's SSE and WebSocket subscription
6
+ * routes), `subscribe()` (an MQTT SUBSCRIBE, and Harper's native MCP
7
+ * `resources/subscribe` when that component is configured) and `publish()` (an
8
+ * MQTT PUBLISH) of each table class admit only administrators and trusted
9
+ * internal calls, and so do its static `put()` and `delete()` for a call where
10
+ * an argument Harper may take as the context carries the markers of an MQTT
11
+ * session's context or of a copy of a stored will record Harper replays (a
12
+ * retained MQTT PUBLISH or last-will); every other put()/delete() call passes
13
+ * through with the same arguments and no caller resolved. Each guarded static
14
+ * decides the contexts Harper may take from the call's arguments (every listed
15
+ * reading, or for put()/delete() every marked candidate; see the policy module
16
+ * for what is read and what is listed); the guard's boundary is protocol-layer
17
+ * callers, whose contexts Harper constructs, and in-process code is trusted.
18
+ * Harper's native MCP route resolves every caller as anonymous, so it refuses
19
+ * administrators too (see the policy module). The tables are read from the
20
+ * registry, so the class of a table added to the schema gets the guard without
21
+ * being named here.
9
22
  *
10
23
  * This module deliberately exports nothing: Harper registers exported values of
11
24
  * a resource module as routes.
@@ -24,9 +24,8 @@ const POLL_MS = 20;
24
24
  * (after the pre-existing ownership read, before the delete's transactional
25
25
  * re-read or staging) and an in-transaction point (between that transaction's
26
26
  * ownership re-read and its delete), so both interleavings of a concurrent
27
- * owner change can be exercised. The write transaction is one the delete
28
- * owns, except Memory's ordinary delete: withSharedWriteTransaction JOINS a
29
- * request-owned transaction when one exists and creates one otherwise.
27
+ * owner change can be exercised. The write transaction is one the delete owns
28
+ * (Memory's ordinary delete included, since flair#2632).
30
29
  */
31
30
  export const PAUSE_POINT_PATTERN = /^[a-z]+(?:-[a-z]+)*$/;
32
31
  /** The named error a pause-point name that does not match `PAUSE_POINT_PATTERN` is refused with (flair#2382). */
@@ -47,7 +46,125 @@ function logRefusal() {
47
46
  refusalLogged = true;
48
47
  console.warn("txn-pause-point: filesystem check failed; hook inert");
49
48
  }
50
- export function txnPausePoint(point, env = process.env, limitMs = PAUSE_LIMIT_MS) {
49
+ /**
50
+ * A test-only failure switch, gated and path-checked like {@link txnPausePoint}:
51
+ * true when the caller armed `fail.<point>`. The caller turns it into the
52
+ * failure its branch handles (a thrown read, a skipped write). Inert unless
53
+ * the fault-injection opt-in is set.
54
+ */
55
+ export function txnFault(point, env = process.env) {
56
+ if (!PAUSE_POINT_PATTERN.test(point))
57
+ throw new InvalidPausePointError(point);
58
+ if (env[TEST_FAULT_INJECTION_ENV] !== "1")
59
+ return false;
60
+ let armPath;
61
+ try {
62
+ const configured = env[TEST_PAUSE_DIR_ENV];
63
+ if (!configured || !isAbsolute(configured) || !process.getuid || !constants.O_NOFOLLOW)
64
+ throw new Error();
65
+ const dir = realpathSync(configured);
66
+ const info = statSync(dir);
67
+ if (lstatSync(configured).isSymbolicLink() || !isInside(realpathSync(tmpdir()), dir) ||
68
+ !info.isDirectory() || info.uid !== process.getuid() || (info.mode & 0o022) !== 0)
69
+ throw new Error();
70
+ armPath = join(dir, `fail.${point}`);
71
+ }
72
+ catch {
73
+ logRefusal();
74
+ return false;
75
+ }
76
+ try {
77
+ const fd = openSync(armPath, constants.O_RDONLY | constants.O_NOFOLLOW);
78
+ if (!fstatSync(fd).isFile()) {
79
+ closeSync(fd);
80
+ return false;
81
+ }
82
+ closeSync(fd);
83
+ unlinkSync(armPath);
84
+ return true;
85
+ }
86
+ catch (error) {
87
+ if (error.code === "ENOENT")
88
+ return false;
89
+ logRefusal();
90
+ return false;
91
+ }
92
+ }
93
+ /**
94
+ * Synchronous form of {@link txnPausePoint} for callers that cannot await
95
+ * (migration-lock acquisition is synchronous). It claims the same
96
+ * `arm.<point>` / `paused.<point>` / `released.<point>` / `go.<point>` marker
97
+ * files and blocks the calling thread in bounded sleeps until the go file
98
+ * appears or `limitMs` expires. Inert unless the fault-injection opt-in is
99
+ * set (flair#2866).
100
+ */
101
+ export function txnPausePointSync(point, env = process.env, limitMs = PAUSE_LIMIT_MS, snapshot) {
102
+ if (!PAUSE_POINT_PATTERN.test(point))
103
+ throw new InvalidPausePointError(point);
104
+ if (env[TEST_FAULT_INJECTION_ENV] !== "1")
105
+ return;
106
+ let armFd;
107
+ let pausedFd;
108
+ let releasedFd;
109
+ let dir;
110
+ try {
111
+ const configured = env[TEST_PAUSE_DIR_ENV];
112
+ if (!configured || !isAbsolute(configured) || !process.getuid || !constants.O_NOFOLLOW)
113
+ throw new Error();
114
+ dir = realpathSync(configured);
115
+ const info = statSync(dir);
116
+ if (lstatSync(configured).isSymbolicLink() || !isInside(realpathSync(tmpdir()), dir) ||
117
+ !info.isDirectory() || info.uid !== process.getuid() || (info.mode & 0o022) !== 0)
118
+ throw new Error();
119
+ const armPath = join(dir, `arm.${point}`);
120
+ try {
121
+ armFd = openSync(armPath, constants.O_RDONLY | constants.O_NOFOLLOW);
122
+ }
123
+ catch (error) {
124
+ if (error.code === "ENOENT")
125
+ return;
126
+ throw error;
127
+ }
128
+ if (!fstatSync(armFd).isFile())
129
+ throw new Error();
130
+ const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
131
+ closeSync(openSync(join(dir, `claimed.${point}`), flags, 0o600));
132
+ pausedFd = openSync(join(dir, `paused.${point}`), flags, 0o600);
133
+ releasedFd = openSync(join(dir, `released.${point}`), flags, 0o600);
134
+ writeFileSync(pausedFd, snapshot === undefined ? String(Date.now()) : JSON.stringify(snapshot));
135
+ unlinkSync(armPath);
136
+ }
137
+ catch {
138
+ if (pausedFd !== undefined)
139
+ closeSync(pausedFd);
140
+ if (releasedFd !== undefined)
141
+ closeSync(releasedFd);
142
+ logRefusal();
143
+ return;
144
+ }
145
+ finally {
146
+ if (armFd !== undefined)
147
+ closeSync(armFd);
148
+ }
149
+ const paused = pausedFd;
150
+ const released = releasedFd;
151
+ try {
152
+ const go = join(dir, `go.${point}`);
153
+ const deadline = Date.now() + limitMs;
154
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
155
+ while (!existsSync(go) && Date.now() < deadline)
156
+ Atomics.wait(sleeper, 0, 0, POLL_MS);
157
+ writeFileSync(released, existsSync(go) ? "go" : "timeout");
158
+ }
159
+ catch {
160
+ logRefusal();
161
+ }
162
+ finally {
163
+ closeSync(paused);
164
+ closeSync(released);
165
+ }
166
+ }
167
+ export function txnPausePoint(point, env = process.env, limitMs = PAUSE_LIMIT_MS, snapshot) {
51
168
  if (!PAUSE_POINT_PATTERN.test(point))
52
169
  throw new InvalidPausePointError(point);
53
170
  if (env[TEST_FAULT_INJECTION_ENV] !== "1")
@@ -81,7 +198,7 @@ export function txnPausePoint(point, env = process.env, limitMs = PAUSE_LIMIT_MS
81
198
  closeSync(claimedFd);
82
199
  pausedFd = openSync(join(dir, `paused.${point}`), flags, 0o600);
83
200
  releasedFd = openSync(join(dir, `released.${point}`), flags, 0o600);
84
- writeFileSync(pausedFd, String(Date.now()));
201
+ writeFileSync(pausedFd, snapshot === undefined ? String(Date.now()) : JSON.stringify(snapshot));
85
202
  unlinkSync(armPath);
86
203
  }
87
204
  catch {
@@ -58,6 +58,7 @@ import { withKeyLock } from "./key-lock.js";
58
58
  import { withDetachedTxn } from "./table-helpers.js";
59
59
  import { withOwnedTransaction } from "./request-transaction.js";
60
60
  import { WriteBackConflictError, writeBackCommittedRow } from "./write-back.js";
61
+ import { withMemoryWriteLockOnce } from "./memory-write-lock.js";
61
62
  import { txnPausePoint } from "./txn-pause-point.js";
62
63
  import { resolveReadScope } from "./memory-read-scope.js";
63
64
  /**
@@ -106,16 +107,23 @@ export class UsageLedgerReadError extends Error {
106
107
  * The ledger read and any create share an owned transaction. The count bump
107
108
  * uses a separate owned transaction through writeBackCommittedRow.
108
109
  *
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.
118
+ *
109
119
  * The count bump is the shared write-back helper (write-back.ts): the row is
110
120
  * read inside a transaction this call OWNS, the bump is built from THAT read,
111
121
  * and the committed row is re-read before commit. The plan skips an absent
112
122
  * row or one outside the agent's read scope before any identity comparison.
113
123
  * 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
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
119
127
  * the read-scope gate above; it never authorizes the count write on its own.
120
128
  *
121
129
  * Called by recordUsageBatch() (POST /RecordUsage, explicit usage feedback)
@@ -123,15 +131,38 @@ export class UsageLedgerReadError extends Error {
123
131
  * semantics regardless of which surface triggered the contribution.
124
132
  */
125
133
  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
+ // 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);
134
164
  return;
165
+ }
135
166
  // Test-only: pause after the ledger lock releases and the owned transaction
136
167
  // commits, before this request's transaction commits (flair#2333).
137
168
  const committed = txnPausePoint("usage-ledger-lock-released");
@@ -195,18 +226,6 @@ async function recordUsageContributionLocked(ctx, agentId, memoryId, attribution
195
226
  });
196
227
  if (!prepared)
197
228
  return;
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
202
- // this write path smuggle OTHER field changes through instead of just the
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
229
  await writeBackCommittedRow(databases.flair.Memory, memoryId, (row) => {
211
230
  // Deleted, or moved out of the agent's read scope, between the check
212
231
  // above and this read — the count is not bumped (the ledger row written
@@ -214,9 +233,7 @@ async function recordUsageContributionLocked(ctx, agentId, memoryId, attribution
214
233
  // read scope.
215
234
  if (!row || !canRead(row))
216
235
  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 } };
236
+ return { idempotent: false, commitMarkerField: "writeBackWriteId", update: { usageCount: (row.usageCount ?? 0) + 1 } };
220
237
  }, {
221
238
  ctx,
222
239
  label: "usage-recording",
@@ -226,6 +243,9 @@ async function recordUsageContributionLocked(ctx, agentId, memoryId, attribution
226
243
  expectedRow: prepared,
227
244
  pausePre: () => txnPausePoint("usage-count-pre"),
228
245
  pausePoint: () => txnPausePoint("usage-count"),
246
+ pauseAfterStage: () => txnPausePoint("usage-count-staged"),
247
+ pauseBeforeCommit: () => txnPausePoint("usage-count-commit"),
248
+ pauseBeforeVerify: () => txnPausePoint("usage-count-verify"),
229
249
  });
230
250
  }
231
251
  /**
@@ -322,14 +342,9 @@ export async function recordCitations(ctx, auth, usedMemoryIds, now, recordFn =
322
342
  await recordFn(ctx, auth.agentId, id, undefined, now, scope.isAllowed);
323
343
  }
324
344
  catch (err) {
325
- // Never let one bad id stop the batch — same no-op-on-error discipline
326
- // as RecordUsage.post()'s loop, log server-side only.
345
+ // Log per-id failures without stopping the batch.
327
346
  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 });
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 });
333
348
  }
334
349
  else if (err instanceof UsageLedgerReadError) {
335
350
  // flair#2333: the ledger read that decides whether this pair already
@@ -338,7 +353,7 @@ export async function recordCitations(ctx, auth, usedMemoryIds, now, recordFn =
338
353
  console.error("recordCitations: not credited, ledger read failed (no-op)", { memoryId: id, ledgerId: err.ledgerId, reason: "ledger_read_failed", err });
339
354
  }
340
355
  else {
341
- console.error("recordCitations: failed to credit (no-op)", { memoryId: id, err });
356
+ console.error("recordCitations: failed to credit", { memoryId: id, err });
342
357
  }
343
358
  }
344
359
  }
@@ -378,16 +393,9 @@ export async function recordUsageBatch(ctx, agentId, memoryIds, attribution, now
378
393
  await recordFn(ctx, agentId, memoryId, attribution, now, scope.isAllowed);
379
394
  }
380
395
  catch (err) {
381
- // Never let one bad id fail the whole batch, and never let an internal
382
- // error leak existence information either — log server-side, collapse
383
- // to the same no-op the response already returns for every other
384
- // outcome.
396
+ // Log per-id failures without changing the response.
385
397
  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 });
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 });
391
399
  }
392
400
  else if (err instanceof UsageLedgerReadError) {
393
401
  // flair#2333: the ledger read failed — not "no row". This contribution
@@ -395,7 +403,7 @@ export async function recordUsageBatch(ctx, agentId, memoryIds, attribution, now
395
403
  console.error("RecordUsage.post: not recorded, ledger read failed (treated as no-op)", { memoryId, ledgerId: err.ledgerId, reason: "ledger_read_failed", err });
396
404
  }
397
405
  else {
398
- console.error("RecordUsage.post: failed to record usage (treated as no-op)", { memoryId, err });
406
+ console.error("RecordUsage.post: failed to record usage", { memoryId, err });
399
407
  }
400
408
  }
401
409
  }
@@ -1,4 +1,7 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { isDeepStrictEqual } from "node:util";
3
+ import { appendFileSync } from "node:fs";
4
+ import { join } from "node:path";
2
5
  import { withOwnedTransaction } from "./request-transaction.js";
3
6
  /** The fields of `expectedRow` (or of the helper's own first read) it compares
4
7
  * with the row read inside its transaction, besides `matchFields`. */
@@ -43,17 +46,35 @@ export function writeBackIdentity(row) {
43
46
  /** Attempts of a write-back before it gives up on a row that keeps changing. */
44
47
  export const WRITE_BACK_ATTEMPTS = 3;
45
48
  /**
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.
49
+ * Test-only: record attempt starts and settled outcomes when fault injection
50
+ * is armed and a pause directory is configured.
51
+ */
52
+ function noteTestAttempt(label, id, attempt, outcome) {
53
+ if (process.env.FLAIR_ENABLE_TEST_FAULT_INJECTION !== "1")
54
+ return;
55
+ const dir = process.env.FLAIR_TEST_PAUSE_DIR;
56
+ if (!dir)
57
+ return;
58
+ try {
59
+ appendFileSync(join(dir, "attempts.write-back"), `${label}\t${id}\t${attempt}${outcome ? `\t${outcome}` : ""}\n`);
60
+ }
61
+ catch {
62
+ // Append errors are ignored.
63
+ }
64
+ }
65
+ /**
66
+ * The helper's named failure. `outcome: "conflict"`: a check before the commit
67
+ * aborted the transaction, so this attempt committed no write. `outcome:
68
+ * "unconfirmed"`: the transaction's commit resolved, but a fresh committed read
69
+ * did not show the staged values (or could not be read), so whether the write
70
+ * landed is unknown.
52
71
  */
53
72
  export class WriteBackConflictError extends Error {
73
+ outcome;
54
74
  id;
55
- constructor(label, id, attempts) {
56
- super(`${label}: row ${id} changed; write not applied (${attempts} attempts)`);
75
+ constructor(label, id, attempts, outcome = "conflict") {
76
+ super(`${label}: row ${id}; ${outcome}: ${outcome === "conflict" ? "write aborted; no write committed by this attempt" : "staged values unconfirmed after commit"} (${attempts} attempts)`);
77
+ this.outcome = outcome;
57
78
  this.name = "WriteBackConflictError";
58
79
  this.id = id;
59
80
  }
@@ -184,8 +205,11 @@ export async function writeBackCommittedRow(table, id, plan, opts) {
184
205
  await pre;
185
206
  }
186
207
  for (let attempt = 1;; attempt++) {
208
+ noteTestAttempt(opts.label, id, attempt);
209
+ let decision;
210
+ let writeId;
187
211
  try {
188
- return await withOwnedTransaction(opts.ctx, async (c) => {
212
+ decision = await withOwnedTransaction(opts.ctx, async (c) => {
189
213
  const row = await table.get(id, c);
190
214
  if (opts.matches && !opts.matches(row))
191
215
  return { skip: true };
@@ -200,19 +224,160 @@ export async function writeBackCommittedRow(table, id, plan, opts) {
200
224
  if (pause)
201
225
  await pause;
202
226
  }
227
+ let values = "update" in decision ? decision.update : decision.write;
228
+ if (!decision.idempotent) {
229
+ if (!decision.commitMarkerField)
230
+ throw new Error("write-back: non-idempotent plans require a commit marker field");
231
+ writeId = randomUUID();
232
+ values = { ...values, [decision.commitMarkerField]: writeId };
233
+ }
203
234
  if ("update" in decision)
204
- await applyFieldUpdate(table, id, decision.update, c);
235
+ await applyFieldUpdate(table, id, values, c);
205
236
  else
206
- await table.put(decision.write, c);
237
+ await table.put(values, c);
238
+ if (opts.pauseAfterStage) {
239
+ const staged = opts.pauseAfterStage();
240
+ if (staged)
241
+ await staged;
242
+ }
207
243
  await confirmCommittedRow(table, id, (committed) => isDeepStrictEqual(committed, row));
244
+ if (opts.confirmPoint) {
245
+ const confirmed = opts.confirmPoint();
246
+ if (confirmed)
247
+ await confirmed;
248
+ }
249
+ // Test-only: holds this write after its last pre-commit confirmation,
250
+ // before the transaction commits (flair#2653).
251
+ if (opts.pauseBeforeCommit) {
252
+ const pause = opts.pauseBeforeCommit();
253
+ if (pause)
254
+ await pause;
255
+ }
208
256
  return decision;
209
257
  });
210
258
  }
211
259
  catch (err) {
260
+ noteTestAttempt(opts.label, id, attempt, "refused");
212
261
  if (!(err instanceof CommittedRowChanged))
213
262
  throw err;
214
263
  if (attempt >= attempts)
215
264
  throw new WriteBackConflictError(opts.label, id, attempts);
265
+ continue;
266
+ }
267
+ if ("skip" in decision) {
268
+ noteTestAttempt(opts.label, id, attempt, "skipped");
269
+ return decision;
270
+ }
271
+ // flair#2653: the transaction's commit is not proof that the write landed.
272
+ // A newer write committing in the window above can make Harper resolve the
273
+ // commit while discarding this write. Re-read the committed store in a
274
+ // fresh context; an unreadable read is a failure, never a pass.
275
+ if (opts.pauseBeforeVerify) {
276
+ const pause = opts.pauseBeforeVerify();
277
+ if (pause)
278
+ await pause;
279
+ }
280
+ let committed;
281
+ try {
282
+ committed = await table.get(id, {});
283
+ }
284
+ catch (err) {
285
+ opts.onUnconfirmed?.();
286
+ noteTestAttempt(opts.label, id, attempt, "unconfirmed");
287
+ if (!decision.idempotent)
288
+ throw new WriteBackConflictError(opts.label, id, attempt, "unconfirmed");
289
+ throw err;
290
+ }
291
+ if (!committedShowsWrite(committed, basis, decision, writeId) || (opts.verifyAlso !== undefined && !opts.verifyAlso(committed))) {
292
+ opts.onUnconfirmed?.();
293
+ noteTestAttempt(opts.label, id, attempt, "unconfirmed");
294
+ if (!decision.idempotent)
295
+ throw new WriteBackConflictError(opts.label, id, attempt, "unconfirmed");
296
+ if (attempt >= attempts)
297
+ throw new WriteBackConflictError(opts.label, id, attempts, "unconfirmed");
298
+ continue;
299
+ }
300
+ noteTestAttempt(opts.label, id, attempt, "applied");
301
+ return decision;
302
+ }
303
+ }
304
+ /**
305
+ * Does `committed` show the write `identity` describes with every `fields`
306
+ * entry at its staged value? The identity check is {@link sameStoredRow}.
307
+ */
308
+ export function committedShowsFields(committed, identity, fields) {
309
+ return sameStoredRow(committed, identity) &&
310
+ Object.entries(fields).every(([field, value]) => isDeepStrictEqual(committed?.[field], value));
311
+ }
312
+ /**
313
+ * Read `id` in a fresh committed context (never contextless) and report whether
314
+ * it shows the write: the row is still `identity`'s row and every named field
315
+ * holds its staged value. A failed read is `unreadable`, never `shown`.
316
+ *
317
+ * The post-commit shape a writer outside {@link writeBackCommittedRow} uses:
318
+ * after its owned transaction resolves, a newer write that committed in the
319
+ * final-confirmation-to-commit window may have discarded this write's effect
320
+ * while the commit still resolved (flair#2653, flair#2656).
321
+ *
322
+ * `also` re-checks a fact the decision depended on that is not one of the
323
+ * written fields — a re-embed's text basis, for instance.
324
+ */
325
+ export async function verifyCommittedFields(table, id, identity, fields, also) {
326
+ let committed;
327
+ try {
328
+ committed = await table.get(id, {});
329
+ }
330
+ catch {
331
+ return "unreadable";
332
+ }
333
+ if (committed == null)
334
+ return "mismatch";
335
+ return (also === undefined || also(committed)) && committedShowsFields(committed, identity, fields) ? "shown" : "mismatch";
336
+ }
337
+ // Harper assigns these timestamps; they are not staged application fields.
338
+ export const HARPER_MANAGED_FIELDS = ["__createdtime__", "__updatedtime__"];
339
+ /**
340
+ * A copy of `row` without {@link HARPER_MANAGED_FIELDS}: the application fields
341
+ * of a row staged by spreading a stored row, as the `fields` a caller hands
342
+ * {@link verifyCommittedFields}. Every other field is kept; `row` is unchanged.
343
+ */
344
+ export function withoutHarperManagedFields(row) {
345
+ const fields = { ...row };
346
+ for (const field of HARPER_MANAGED_FIELDS)
347
+ delete fields[field];
348
+ return fields;
349
+ }
350
+ /**
351
+ * Does the committed row show this attempt's write? Its identity is the row
352
+ * this attempt wrote — for an update, the basis with every identity field the
353
+ * update itself stages replaced by the staged value; each field the plan wrote
354
+ * holds its staged value, and a non-idempotent plan is confirmed by this
355
+ * attempt's commit marker (`writeId`), not by value equality.
356
+ */
357
+ function committedShowsWrite(committed, basis, decision, writeId) {
358
+ if ("skip" in decision)
359
+ return true;
360
+ if (!decision.idempotent && committed?.[decision.commitMarkerField] !== writeId)
361
+ return false;
362
+ if ("update" in decision) {
363
+ // An update may change an identity field (the federation merge carries the
364
+ // inbound contentHash). The committed row must then show the staged value
365
+ // of every identity field the update names, and the basis value of the
366
+ // others.
367
+ const identity = basis == null ? basis : { ...basis };
368
+ if (identity != null) {
369
+ for (const field of WRITE_BACK_IDENTITY_FIELDS) {
370
+ if (Object.hasOwn(decision.update, field))
371
+ identity[field] = decision.update[field];
372
+ }
216
373
  }
374
+ if (!sameStoredRow(committed, identity))
375
+ return false;
376
+ return Object.entries(decision.update).every(([field, value]) => (!decision.idempotent && field === decision.commitMarkerField) || isDeepStrictEqual(committed?.[field], value));
217
377
  }
378
+ if (!sameStoredRow(committed, decision.write))
379
+ return false;
380
+ const managed = new Set(HARPER_MANAGED_FIELDS);
381
+ return Object.entries(decision.write).every(([field, value]) => managed.has(field) || (!decision.idempotent && field === decision.commitMarkerField) || isDeepStrictEqual(committed?.[field], value)) &&
382
+ Object.keys(committed).every((field) => managed.has(field) || Object.hasOwn(decision.write, field) || (!decision.idempotent && field === decision.commitMarkerField));
218
383
  }
@@ -0,0 +1,5 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ export const writeJournalScope = new AsyncLocalStorage();
3
+ export function currentWriteJournal() {
4
+ return writeJournalScope.getStore() ?? undefined;
5
+ }