@tpsdev-ai/flair 0.62.0 → 0.63.1

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 (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -10,7 +10,9 @@
10
10
  * agent keys included, are refused.
11
11
  *
12
12
  * Harper queues a delete and can skip it at commit, so every delete below is
13
- * checked by a read after its commit, and the steps run in this order:
13
+ * checked by a read after its commit, and the steps run in this order, all of
14
+ * them while the call holds the per-id Memory write locks of its target set
15
+ * (flair#2478 slice 3b):
14
16
  *
15
17
  * 1. One owned transaction holds each target's row delete and, for a
16
18
  * permanent or persistent row, its deletion-history record (other rows get
@@ -27,6 +29,22 @@
27
29
  * pointer-table adapter while the row is still absent; a read after that
28
30
  * commit looks for pointer rows left for rows that are still absent.
29
31
  *
32
+ * The lock (flair#2478 slice 3b). The purge is an operator-initiated foreground
33
+ * writer, so it takes the sorted, deduplicated `["memory", id]` keys of its
34
+ * whole target set with the owner budget ({@link MEMORY_LOCK_ATTEMPTS}
35
+ * attempts, {@link MEMORY_LOCK_WAIT_MS} apart) and holds them across every
36
+ * commit above. A set that stayed held for the whole budget is refused `503
37
+ * memory_busy` with the caller id and nothing else; an unresolved write on one
38
+ * of the ids is refused `503 write_outcome_unknown`; a store with no lock is
39
+ * refused `503 memory_lock_unavailable`. Nothing is written in those cases.
40
+ * The set can only be named after a first read (a skill lineage is discovered
41
+ * by search), so the call resolves it, takes its locks, and re-resolves it
42
+ * under them: a set that changed in between is restarted, at most
43
+ * {@link PURGE_SET_ATTEMPTS} attempts, then refused `409
44
+ * memory_purge_targets_changed`. Inside the locks each target is re-read from
45
+ * the committed store before it is deleted, so the deletion is decided on the
46
+ * row the locks were taken for.
47
+ *
30
48
  * Reply, checked in this order: unconfirmed history cleanup fails the call
31
49
  * (500 memory_purge_history_cleanup_unconfirmed, with the record ids); a failed
32
50
  * pointer delete or confirmation read, or a pointer row left after step 4,
@@ -46,6 +64,11 @@ import { recordMemoryDeletion, removeMemoryDeletionRecords } from "./memory-dele
46
64
  import { withOwnedTransaction } from "./request-transaction.js";
47
65
  import { deletePointerRowViaTable } from "./host-pointer-adapter.js";
48
66
  import { storedPointerIds } from "./memory-host-source.js";
67
+ import { memoryBusyResponse, memoryLockUnavailableResponse, withMemoryWriteLock, writeOutcomeUnknownResponse, } from "./memory-write-lock.js";
68
+ import { txnPausePoint } from "./txn-pause-point.js";
69
+ import { withDetachedTxnAsync } from "./table-helpers.js";
70
+ /** Attempts at resolving a target set that keeps changing under the locks. */
71
+ const PURGE_SET_ATTEMPTS = 3;
49
72
  function reply(status, body) {
50
73
  return new Response(JSON.stringify(body), {
51
74
  status,
@@ -55,6 +78,17 @@ function reply(status, body) {
55
78
  function errorText(err) {
56
79
  return err instanceof Error ? err.message : String(err);
57
80
  }
81
+ /** The caller id a lock-miss refusal carries — the request's agent annotation,
82
+ * else `internal`/`anonymous` (the rule the owner verbs use, Sherlock S7).
83
+ * Never stored-row state. */
84
+ function purgeCallerId(ctx) {
85
+ const request = ctx?.request ?? ctx;
86
+ if (typeof request?.tpsAgent === "string" && request.tpsAgent.length > 0)
87
+ return request.tpsAgent;
88
+ if (request?.tpsAnonymous === true)
89
+ return "anonymous";
90
+ return "internal";
91
+ }
58
92
  /** A target that is not stored when the call reads it before deleting. */
59
93
  class MissingTarget extends Error {
60
94
  ids;
@@ -63,6 +97,46 @@ class MissingTarget extends Error {
63
97
  this.ids = ids;
64
98
  }
65
99
  }
100
+ /**
101
+ * Read the target set: every named row plus, for a skill row, every row in its
102
+ * skill lineage (superseded version rows included). A read that fails
103
+ * propagates — it never reads as "absent".
104
+ */
105
+ async function resolvePurgeTargets(ctx, memory, ids) {
106
+ const rows = new Map();
107
+ const missing = [];
108
+ for (const id of new Set(ids)) {
109
+ // Detach from the request's transaction: a lineage row committed by
110
+ // another request since this one started must be visible to the re-resolve
111
+ // under the locks.
112
+ const row = (await withDetachedTxnAsync(ctx, () => memory.get(id)));
113
+ if (!row) {
114
+ missing.push(id);
115
+ continue;
116
+ }
117
+ const rowId = String(row.id ?? id);
118
+ rows.set(rowId, row);
119
+ const subjectId = typeof row.skillSubjectId === "string" && row.skillSubjectId.length > 0
120
+ ? row.skillSubjectId
121
+ : Array.isArray(row.tags) && row.tags.includes("skill") ? rowId : null;
122
+ if (!subjectId)
123
+ continue;
124
+ const siblings = await withDetachedTxnAsync(ctx, async () => {
125
+ const found = [];
126
+ for await (const sibling of memory.search({
127
+ conditions: [{ attribute: "skillSubjectId", comparator: "equals", value: subjectId }],
128
+ })) {
129
+ found.push(sibling);
130
+ }
131
+ return found;
132
+ });
133
+ for (const sibling of siblings) {
134
+ if (sibling && typeof sibling.id === "string" && sibling.id.length > 0)
135
+ rows.set(sibling.id, sibling);
136
+ }
137
+ }
138
+ return { rows, missing };
139
+ }
66
140
  export class MemoryPurge extends Resource {
67
141
  /** The operator source only (`soulWriteSource`). */
68
142
  async allowCreate() {
@@ -82,31 +156,58 @@ export class MemoryPurge extends Resource {
82
156
  // Resolve the full target set before mutating: every named row plus, for a
83
157
  // skill row, every row in its skill lineage (superseded version rows
84
158
  // included). A read that fails propagates — it never reads as "absent".
85
- const targets = new Map();
86
- const missing = [];
87
- for (const id of new Set(ids)) {
88
- const row = await memory.get(id);
89
- if (!row) {
90
- missing.push(id);
91
- continue;
159
+ let targets = await resolvePurgeTargets(ctx, memory, ids);
160
+ if (targets.missing.length > 0) {
161
+ return reply(404, { error: "memory_purge_target_missing", ids: targets.missing });
162
+ }
163
+ // flair#2478 slice 3b: the whole purge runs under the target set's per-id
164
+ // Memory write locks, sorted, with the owner budget (a foreground operator
165
+ // write). The set is re-resolved under the locks so a lineage member added
166
+ // since the first read is locked too; a changed set restarts.
167
+ for (let attempt = 1; attempt <= PURGE_SET_ATTEMPTS; attempt++) {
168
+ // Test-only: one point per attempt, so a test can change the target set
169
+ // between this attempt's resolve and its locked re-resolve.
170
+ const resolvePause = attempt === 1
171
+ ? txnPausePoint("memory-purge-resolve-first")
172
+ : attempt === 2
173
+ ? txnPausePoint("memory-purge-resolve-second")
174
+ : txnPausePoint("memory-purge-resolve-last");
175
+ if (resolvePause)
176
+ await resolvePause;
177
+ const lockedIds = [...targets.rows.keys()].sort();
178
+ const locked = await withMemoryWriteLock(memory.primaryStore, lockedIds, async () => {
179
+ const current = await resolvePurgeTargets(ctx, memory, ids);
180
+ if (current.missing.length > 0)
181
+ return { kind: "missing", ids: current.missing };
182
+ const currentIds = [...current.rows.keys()].sort();
183
+ if (currentIds.length !== lockedIds.length || currentIds.some((id, i) => id !== lockedIds[i])) {
184
+ return { kind: "changed", rows: current.rows };
185
+ }
186
+ return { kind: "ran", value: await this.runPurge(ctx, memory, current.rows) };
187
+ }, { phase: "memory-purge" });
188
+ if (locked.kind === "busy")
189
+ return memoryBusyResponse(purgeCallerId(ctx));
190
+ if (locked.kind === "unknown")
191
+ return writeOutcomeUnknownResponse();
192
+ if (locked.kind === "unavailable")
193
+ return memoryLockUnavailableResponse();
194
+ if (locked.value.kind === "missing") {
195
+ return reply(404, { error: "memory_purge_target_missing", ids: locked.value.ids });
92
196
  }
93
- const rowId = String(row.id ?? id);
94
- targets.set(rowId, row);
95
- const subjectId = typeof row.skillSubjectId === "string" && row.skillSubjectId.length > 0
96
- ? row.skillSubjectId
97
- : Array.isArray(row.tags) && row.tags.includes("skill") ? rowId : null;
98
- if (!subjectId)
197
+ if (locked.value.kind === "changed") {
198
+ targets = { rows: locked.value.rows, missing: [] };
99
199
  continue;
100
- for await (const sibling of memory.search({
101
- conditions: [{ attribute: "skillSubjectId", comparator: "equals", value: subjectId }],
102
- })) {
103
- if (sibling && typeof sibling.id === "string" && sibling.id.length > 0)
104
- targets.set(sibling.id, sibling);
105
200
  }
201
+ return locked.value.value;
106
202
  }
107
- if (missing.length > 0) {
108
- return reply(404, { error: "memory_purge_target_missing", ids: missing });
109
- }
203
+ return reply(409, {
204
+ error: "memory_purge_targets_changed",
205
+ message: "the rows this purge targets changed while it held their locks; nothing was deleted; retry the purge",
206
+ ids: [...targets.rows.keys()].sort(),
207
+ });
208
+ }
209
+ /** Steps 1-4, run while the caller holds every target id's lock. */
210
+ async runPurge(ctx, memory, targets) {
110
211
  // 1. ONE owned transaction per call: a failed read or history write aborts
111
212
  // every write in it. No pointer row is touched here (step 4).
112
213
  const historyIds = new Map();
@@ -117,6 +218,11 @@ export class MemoryPurge extends Resource {
117
218
  if (!stored)
118
219
  throw new MissingTarget([id]);
119
220
  await memory.delete(id, c);
221
+ // Test-only: the row delete is staged and the transaction has not
222
+ // committed. The lock is held.
223
+ const staged = txnPausePoint("memory-purge-staged");
224
+ if (staged)
225
+ await staged;
120
226
  const historyId = await recordMemoryDeletion({
121
227
  memoryId: id,
122
228
  memoryInstanceToken: stored.instanceToken ?? null,
@@ -126,6 +232,11 @@ export class MemoryPurge extends Resource {
126
232
  }, c);
127
233
  if (historyId)
128
234
  historyIds.set(id, historyId);
235
+ // Test-only: every write of this target is staged and the transaction
236
+ // has not committed. The lock is held.
237
+ const commit = txnPausePoint("memory-purge-commit");
238
+ if (commit)
239
+ await commit;
129
240
  }
130
241
  });
131
242
  }
@@ -146,6 +257,11 @@ export class MemoryPurge extends Resource {
146
257
  removedIds.push(id);
147
258
  }
148
259
  });
260
+ // Test-only: the delete transaction has committed and been confirmed; the
261
+ // lock is still held.
262
+ const committed = txnPausePoint("memory-purge-committed");
263
+ if (committed)
264
+ await committed;
149
265
  // 3. Attempt cleanup of history for rows still stored; confirm absence
150
266
  // after the cleanup commit. Failed cleanup is reported below.
151
267
  const staleHistory = stillStored.flatMap((id) => {
@@ -51,8 +51,14 @@ import { existsSync } from "node:fs";
51
51
  import { resolve } from "node:path";
52
52
  import { homedir } from "node:os";
53
53
  import { setImmediate as yieldToRequests } from "node:timers/promises";
54
- import { isAdmin, allowVerified } from "./agent-auth.js";
55
- import { patchRecordSilent } from "./table-helpers.js";
54
+ import { annotatedCallerIsAdmin, allowVerified } from "./agent-auth.js";
55
+ import { patchRecord } from "./table-helpers.js";
56
+ import { withMemoryWriteLockOnce } from "./memory-write-lock.js";
57
+ import { verifyCommittedFields } from "./write-back.js";
58
+ /** The per-id Memory write-lock store (flair#2478). */
59
+ function memoryLockStore() {
60
+ return databases?.flair?.Memory?.primaryStore;
61
+ }
56
62
  import { txnPausePoint } from "./txn-pause-point.js";
57
63
  import { buildReflectionPrompt, buildExecutePrompt, resolveReflectActor, generateCandidates, releaseRequestTransaction, runExecuteDistillation, dedupeCandidates, memoryMatchesReflectScope, buildStagedCandidateRow, isContinuityScopeTag, filterStaleSessionIntentCandidates, resolveCandidateVisibilityRuling, considerForOldestUnreflectedCap, isRemAbortRequested, resolveMaxMemoriesPerRun, shouldStampLastReflected, DEFAULT_STALE_INTENT_HORIZON_MS, REM_GATHER_YIELD_BUDGET_MS, } from "./memory-reflect-lib.js";
58
64
  import { reflectModelsGenerate } from "./memory-reflect-models.js";
@@ -75,12 +81,12 @@ export class ReflectMemories extends Resource {
75
81
  // Authenticated identity comes from getContext().request, not this.request
76
82
  // (see SemanticSearch / MemoryBootstrap for the same bug class). The prior
77
83
  // check was silently bypassed — bob could reflect on alice's memories and
78
- // mutate alice's records via the lastReflected patchRecordSilent below.
84
+ // mutate alice's records through the lastReflected stamp below.
79
85
  const ctx = this.getContext?.();
80
86
  const request = ctx?.request ?? ctx;
81
87
  const actorId = request?.tpsAgent;
82
88
  const callerIsAdmin = request?.tpsAgentIsAdmin === true
83
- || (actorId ? await isAdmin(actorId) : false);
89
+ || (await annotatedCallerIsAdmin(request));
84
90
  // Same actor rules for both modes (spec §3A item 9) — resolved once via
85
91
  // the shared, tested helper before either branch runs.
86
92
  const actorResolution = resolveReflectActor({ bodyAgentId, actorId, callerIsAdmin });
@@ -251,17 +257,21 @@ export class ReflectMemories extends Resource {
251
257
  existingPendingClaims.push(c.claim);
252
258
  }
253
259
  const toStage = dedupeCandidates(staleIntentResult.kept, existingPendingClaims);
254
- // generatedBy: GenerateResult in the pinned harper 5.1.17 has
255
- // no model/backend-id field (content/finishReason/usage/toolCalls/trace
256
- // only) — the "from the generate result if available" branch is
257
- // unreachable in this version, so this always falls back to the
258
- // configured logical name, matching Harper's own default routing name.
260
+ // generatedBy: Harper's GenerateResult carries no model or backend id
261
+ // (content, toolCalls, finishReason, usage and trace only; re-checked
262
+ // against harper 5.3.1's types), so this uses the configured logical
263
+ // name, matching Harper's own default routing name.
259
264
  const resolvedModel = configuredModel ?? "default";
260
265
  const generatedAt = new Date().toISOString();
261
266
  // Write-window atomicity (#1263): generate has already succeeded.
262
267
  // Each MemoryCandidate.put is its own short commit. A throw mid-loop
263
268
  // leaves earlier puts durable and skips lastReflected (never reached).
264
- // lastReflected is patchRecordSilent — it cannot fail the request.
269
+ // The stamp runs patchRecord under withMemoryWriteLockOnce. A held lock
270
+ // is logged. After patchRecord returns, the explicit verification logs
271
+ // an unreadable or mismatching row as unconfirmed; an error from
272
+ // patchRecord's helper is logged as a write-back refusal. Either failure
273
+ // may follow a committed write. A stamp failure does not fail the
274
+ // request.
265
275
  // 502/503 stay generate-only (no_backend / distillation_failed).
266
276
  const staged = [];
267
277
  for (const c of toStage) {
@@ -292,15 +302,59 @@ export class ReflectMemories extends Resource {
292
302
  // Stamp after a successful generate on execute runs only. Prompt-only
293
303
  // and 502/503/abort leave lastReflected unset so the next night retries
294
304
  // the same sources instead of permanently skipping them (#1515 Bugbot).
305
+ //
306
+ // flair#2478 slice 3b: each source stamp takes that id's per-id Memory
307
+ // write lock, once and without waiting, and reads the committed row
308
+ // under it. A held id, an outcome-unknown marker or a store with no
309
+ // lock skips that source and reports it; a stamp is an automatic
310
+ // writer, and its incremental update preserves the owner's other
311
+ // fields while updating `lastReflected`. The patch is an
312
+ // incremental update of `lastReflected`, and its committed row is
313
+ // confirmed before the lock is released. A stamp failure cannot fail
314
+ // the request.
295
315
  if (shouldStampLastReflected({ execute, generateSucceeded: true })) {
296
316
  const now = new Date().toISOString();
317
+ const table = databases.flair.Memory;
297
318
  for (const memory of memories) {
298
319
  const reflectPatch = { lastReflected: now };
299
320
  stripUndeclaredMemoryAttributes(reflectPatch);
300
- patchRecordSilent(databases.flair.Memory, memory.id, reflectPatch, {
301
- pausePre: () => txnPausePoint("reflect-sources-pre"), pausePoint: () => txnPausePoint("reflect-sources"), expectedRow: memory,
302
- matches: (row) => row != null && GATHER_SELECT.every((key) => isDeepStrictEqual(row[key], memory[key])),
303
- });
321
+ try {
322
+ const outcome = await withMemoryWriteLockOnce(memoryLockStore(), [String(memory.id)], async () => {
323
+ const stored = await table.get(String(memory.id), {});
324
+ if (stored == null)
325
+ return { kind: "gone" };
326
+ try {
327
+ await patchRecord(databases.flair.Memory, String(memory.id), reflectPatch, {
328
+ pausePre: () => txnPausePoint("reflect-sources-pre"),
329
+ pausePoint: () => txnPausePoint("reflect-sources"),
330
+ pauseAfterStage: () => txnPausePoint("reflect-sources-staged"),
331
+ pauseBeforeCommit: () => txnPausePoint("reflect-sources-commit"),
332
+ expectedRow: stored,
333
+ matches: (row) => row != null && GATHER_SELECT.every((key) => isDeepStrictEqual(row[key], memory[key])),
334
+ });
335
+ }
336
+ catch (err) {
337
+ logger.warn?.(`MemoryReflect: lastReflected stamp skipped for ${memory.id} (write-back refused: ${err?.name ?? "error"})`);
338
+ return { kind: "failed" };
339
+ }
340
+ const verdict = await verifyCommittedFields(table, String(memory.id), stored, reflectPatch);
341
+ if (verdict !== "shown") {
342
+ logger.warn?.(`MemoryReflect: lastReflected stamp skipped for ${memory.id} (unconfirmed: ${verdict})`);
343
+ return { kind: "unconfirmed" };
344
+ }
345
+ // Test-only: the update committed and the lock is still held.
346
+ const committed = txnPausePoint("reflect-sources-committed");
347
+ if (committed)
348
+ await committed;
349
+ return { kind: "stamped" };
350
+ }, { phase: "reflect-sources" });
351
+ if (outcome.kind !== "done") {
352
+ logger.warn?.(`MemoryReflect: lastReflected stamp skipped for ${memory.id} (${outcome.kind})`);
353
+ }
354
+ }
355
+ catch (err) {
356
+ logger.warn?.(`MemoryReflect: lastReflected stamp skipped for ${memory.id} (${err?.name ?? "error"})`);
357
+ }
304
358
  }
305
359
  }
306
360
  return {
@@ -23,14 +23,23 @@
23
23
  * existing index, older records live in the primary store but never make it
24
24
  * into the secondary index. Scoped search() via RequestTarget.conditions —
25
25
  * which uses the agentId index — then returns empty for those agents.
26
- *
27
- * This endpoint is idempotent: running it again finds zero drift.
28
26
  */
29
27
  import { Resource, databases } from "harper";
30
- import { isAdmin, allowAdmin } from "./agent-auth.js";
31
- import { writeBackCommittedRow, writeBackIdentity } from "./write-back.js";
28
+ import { annotatedCallerIsAdmin, allowAdmin } from "./agent-auth.js";
29
+ import { WriteBackConflictError, writeBackCommittedRow, writeBackIdentity } from "./write-back.js";
30
+ /** The re-PUT's row was confirmed after its commit, but a later agentId-index
31
+ * query does not list it. The miss is reported without a cause: another
32
+ * writer may have changed or removed the row after the confirmation. */
33
+ class ReindexIndexUnconfirmed extends Error {
34
+ outcome = "unconfirmed";
35
+ constructor(id) {
36
+ super(`MemoryReindex: row ${id} was confirmed after commit but is now absent from the agentId index query (index unconfirmed)`);
37
+ this.name = "ReindexIndexUnconfirmed";
38
+ }
39
+ }
32
40
  import { txnPausePoint } from "./txn-pause-point.js";
33
41
  import { buildReindexRow } from "./Memory.js";
42
+ import { withMemoryWriteLockOnce } from "./memory-write-lock.js";
34
43
  export class MemoryReindex extends Resource {
35
44
  // Admin-only: permit verified ADMIN agents (Basic-admin is super_user and
36
45
  // bypasses allow*); non-admin agents denied. Mirrors the handler's admin gate
@@ -45,7 +54,7 @@ export class MemoryReindex extends Resource {
45
54
  const basicAgent = request?.headers?.get?.("x-tps-agent");
46
55
  const isBasicAdmin = basicAgent === "admin";
47
56
  const isEd25519Admin = Boolean(authAgent) && request?.tpsAgentIsAdmin === true;
48
- if (!isBasicAdmin && !(isEd25519Admin && (await isAdmin(authAgent)))) {
57
+ if (!isBasicAdmin && !(isEd25519Admin && (await annotatedCallerIsAdmin(request)))) {
49
58
  return new Response(JSON.stringify({ error: "forbidden: admin required" }), { status: 403, headers: { "Content-Type": "application/json" } });
50
59
  }
51
60
  const dryRun = data?.dryRun === true;
@@ -57,11 +66,13 @@ export class MemoryReindex extends Resource {
57
66
  agentsWithDrift: 0,
58
67
  totalMissing: 0,
59
68
  reindexed: 0,
69
+ skipped: 0,
60
70
  errors: 0,
61
71
  dryRun,
62
72
  agentFilter,
63
73
  drift: [],
64
74
  errorSamples: [],
75
+ skippedSamples: [],
65
76
  };
66
77
  // Pass 1: primary-store scan. Count records per agent.
67
78
  const primaryByAgent = new Map();
@@ -114,15 +125,22 @@ export class MemoryReindex extends Resource {
114
125
  }
115
126
  // Pass 3: re-PUT every primary-store record through buildReindexRow, retaining
116
127
  // declared/named fields and stored provenance, stripping other undeclared
117
- // fields and generating an absent token. The re-PUT forces Harper to re-insert
118
- // into all secondary indices. Cheaper-than-sound variants (only re-PUT records
119
- // that appear missing) would miss rows the primary scan sees fine but that
128
+ // fields and generating an absent token. Variants that only re-PUT records
129
+ // that appear missing would miss rows the primary scan sees fine but that
120
130
  // Harper's read path can't locate via any index path.
131
+ // Written ids are grouped by the agentId in their write plan; Pass 4
132
+ // confirms them against the index after every write has committed.
133
+ const writtenByAgent = new Map();
121
134
  for (let i = 0; i < recordsToReindex.length; i += batchSize) {
122
135
  const chunk = recordsToReindex.slice(i, i + batchSize);
123
136
  for (const id of chunk) {
124
137
  try {
125
- const outcome = await writeBackCommittedRow(Memory, id, (record) => {
138
+ let commitPauses = 0;
139
+ // flair#2478 slice 3c: an automatic writer takes the row's per-id
140
+ // Memory write lock once, without waiting. A held id, an unresolved
141
+ // earlier write or a store with no lock writes nothing for the row;
142
+ // the skip is reported in the result rather than dropped.
143
+ const locked = await withMemoryWriteLockOnce(databases?.flair?.Memory?.primaryStore, [id], () => writeBackCommittedRow(Memory, id, (record) => {
126
144
  if (!record)
127
145
  return { skip: true };
128
146
  // Built by the function Memory.put()'s `_reindex` branch uses,
@@ -130,24 +148,84 @@ export class MemoryReindex extends Resource {
130
148
  const built = buildReindexRow({ ...record, _reindex: true }, record);
131
149
  if (!("row" in built))
132
150
  throw new Error(`${built.error}: ${built.message}`);
133
- return { write: built.row };
134
- }, { ctx, label: "MemoryReindex", pausePre: () => txnPausePoint("reindex-put-pre"), pausePoint: () => txnPausePoint("reindex-put"), expectedRow: selectedRows.get(id) });
151
+ return { idempotent: true, write: built.row };
152
+ }, {
153
+ ctx, label: "MemoryReindex", expectedRow: selectedRows.get(id),
154
+ pausePre: () => txnPausePoint("reindex-put-pre"),
155
+ pausePoint: () => txnPausePoint("reindex-put"),
156
+ pauseAfterStage: () => txnPausePoint("reindex-put-staged"),
157
+ pauseBeforeCommit: () => {
158
+ switch (commitPauses++) {
159
+ case 0: return txnPausePoint("reindex-put-commit");
160
+ case 1: return txnPausePoint("reindex-put-commit-retry");
161
+ default: return txnPausePoint("reindex-put-commit-retry-retry");
162
+ }
163
+ },
164
+ }), { phase: "reindex-put" });
165
+ if (locked.kind !== "done") {
166
+ stats.skipped++;
167
+ if (stats.skippedSamples.length < 5) {
168
+ stats.skippedSamples.push({ id, reason: locked.kind });
169
+ }
170
+ continue;
171
+ }
172
+ const outcome = locked.value;
135
173
  if ("skip" in outcome) {
136
174
  stats.errors++;
137
175
  continue;
138
176
  }
139
- stats.reindexed++;
177
+ if (!("write" in outcome))
178
+ throw new Error("MemoryReindex: expected a full-row plan");
179
+ const written = writtenByAgent.get(outcome.write.agentId);
180
+ if (written)
181
+ written.push(id);
182
+ else
183
+ writtenByAgent.set(outcome.write.agentId, [id]);
140
184
  }
141
185
  catch (err) {
186
+ stats.errors++;
187
+ if (stats.errorSamples.length < 5) {
188
+ stats.errorSamples.push({ id, message: err?.message ?? String(err), ...(err instanceof WriteBackConflictError || err instanceof ReindexIndexUnconfirmed ? { outcome: err.outcome } : {}) });
189
+ }
190
+ }
191
+ }
192
+ }
193
+ // Pass 4: confirm the written ids against the agentId index. One index
194
+ // scan per agent builds the set of ids the committed index lists; each
195
+ // written id is then checked against that set. The scans run after every
196
+ // write above, so no written row is checked against a pre-write index.
197
+ for (const [agentId, writtenIds] of writtenByAgent) {
198
+ const indexedIds = new Set();
199
+ try {
200
+ for await (const row of Memory.search({
201
+ conditions: [{ attribute: "agentId", comparator: "equals", value: agentId }],
202
+ }, {})) {
203
+ indexedIds.add(String(row.id));
204
+ }
205
+ }
206
+ catch (err) {
207
+ for (const id of writtenIds) {
142
208
  stats.errors++;
143
209
  if (stats.errorSamples.length < 5) {
144
210
  stats.errorSamples.push({ id, message: err?.message ?? String(err) });
145
211
  }
146
212
  }
213
+ continue;
214
+ }
215
+ for (const id of writtenIds) {
216
+ if (indexedIds.has(id)) {
217
+ stats.reindexed++;
218
+ continue;
219
+ }
220
+ const err = new ReindexIndexUnconfirmed(id);
221
+ stats.errors++;
222
+ if (stats.errorSamples.length < 5) {
223
+ stats.errorSamples.push({ id, message: err.message, outcome: err.outcome });
224
+ }
147
225
  }
148
226
  }
149
227
  return {
150
- message: `reindex complete: ${stats.reindexed} re-indexed, ${stats.errors} errors, ${stats.totalMissing} pre-existing index gap${stats.totalMissing === 1 ? "" : "s"} healed`,
228
+ message: `reindex complete: ${stats.reindexed} re-indexed, ${stats.skipped} skipped, ${stats.errors} errors, ${stats.totalMissing} pre-existing index gap${stats.totalMissing === 1 ? "" : "s"}`,
151
229
  stats,
152
230
  };
153
231
  }
@@ -19,6 +19,7 @@ import { Resource, databases } from "harper";
19
19
  import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
20
20
  import { makeAuthGate, makeScopedSearch, FORBIDDEN, UNAUTH, NOT_FOUND } from "./record-type-kit.js";
21
21
  import { localInstanceId } from "./instance-identity.js";
22
+ import { refuseRewrittenAgentId } from "./path-id-rewrite.js";
22
23
  import { relaySend, relayInbox, relayConsume, relayDeadLetters, relaySweepDeadlines, } from "./relay-ops.js";
23
24
  function relayDeps(ctx) {
24
25
  return {
@@ -146,7 +147,11 @@ export class MessageInbox extends Resource {
146
147
  }
147
148
  async get(pathInfo) {
148
149
  const auth = await resolveAgentAuth(ctxOf(this));
149
- return relayInbox(relayDeps(), auth, pathId(pathInfo));
150
+ const to = pathId(pathInfo);
151
+ const rewritten = to === undefined ? null : refuseRewrittenAgentId(ctxOf(this), to);
152
+ if (rewritten)
153
+ return rewritten;
154
+ return relayInbox(relayDeps(), auth, to);
150
155
  }
151
156
  }
152
157
  // ─── /MessageAck (POST {id}) — recipient acks a message ────────────────────
@@ -176,7 +181,11 @@ export class MessageDeadLetter extends Resource {
176
181
  }
177
182
  async get(pathInfo) {
178
183
  const auth = await resolveAgentAuth(ctxOf(this));
179
- return relayDeadLetters(relayDeps(), auth, pathId(pathInfo));
184
+ const from = pathId(pathInfo);
185
+ const rewritten = from === undefined ? null : refuseRewrittenAgentId(ctxOf(this), from);
186
+ if (rewritten)
187
+ return rewritten;
188
+ return relayDeadLetters(relayDeps(), auth, from);
180
189
  }
181
190
  }
182
191
  // ─── /MessageSweep (POST) — admin/internal deadline sweep ───────────────────