@tpsdev-ai/flair 0.58.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 (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -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 +1030 -343
  10. package/dist/commands/agent.js +384 -45
  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 +601 -163
  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 +146 -53
  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 +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  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 +120 -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 +27 -2
  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 +1775 -338
  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 +103 -7
  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 +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  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 +227 -64
  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/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -17,6 +17,7 @@
17
17
  * to gate auth correctly.
18
18
  */
19
19
  import { Resource, databases } from "harper";
20
+ import { isDeepStrictEqual } from "node:util";
20
21
  import { MEMORY_HOST_SOURCE_TABLE } from "./memory-host-source.js";
21
22
  /** Maintenance creates an owned transaction for each expiry or archive item;
22
23
  * the Memory and pointer operations join that owned transaction (both tables
@@ -34,6 +35,8 @@ import { isAdmin } from "./agent-auth.js";
34
35
  import { noteMemoryUpsert, noteMemoryDelete } from "./bm25-index-service.js";
35
36
  import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
36
37
  import { withOwnedTransaction } from "./request-transaction.js";
38
+ import { recordMemoryDeletion } from "./memory-deletion-history.js";
39
+ import { txnPausePoint } from "./txn-pause-point.js";
37
40
  export class MemoryMaintenance extends Resource {
38
41
  /** POST requires auth — either an agent acting on its own memories, or admin. */
39
42
  allowCreate() {
@@ -63,7 +66,7 @@ export class MemoryMaintenance extends Resource {
63
66
  });
64
67
  }
65
68
  const now = new Date();
66
- const stats = { expired: 0, archived: 0, total: 0, errors: 0, orphans: 0, agent: targetAgent || "all" };
69
+ const stats = { expired: 0, archived: 0, total: 0, errors: 0, orphans: 0, skipped: 0, agent: targetAgent || "all" };
67
70
  try {
68
71
  for await (const record of databases.flair.Memory.search()) {
69
72
  // Skip records not belonging to target agent (unless admin running fleet-wide).
@@ -80,13 +83,52 @@ export class MemoryMaintenance extends Resource {
80
83
  new Date(record.expiresAt) < now) {
81
84
  if (!dryRun) {
82
85
  try {
83
- // A1'' item 2 (0c): the raw expiry delete runs in its OWN
84
- // transaction together with the pointer delete, so a failed
85
- // pointer delete aborts both and nothing is deleted.
86
+ // flair#2275: another writer may open its transaction first and
87
+ // commit a change to this row before OUR transaction opens. This
88
+ // pause (inert unless the fault-injection opt-in is armed) holds
89
+ // the scan-selected row still while that writer runs; the owned
90
+ // transaction below then sees the change and skips.
91
+ const beforeAct = txnPausePoint("maintenance-expiry-pre");
92
+ if (beforeAct)
93
+ await beforeAct;
94
+ // A1'' item 2 (0c) + flair#2275: the delete runs in a transaction
95
+ // this call OWNS, re-reads the row inside it, and acts only when
96
+ // the row is STILL the one the scan selected. A change seen by that
97
+ // re-read or the confirmation read below is a SKIP (recorded as
98
+ // skipped); a change committed between the confirmation read and
99
+ // the commit is not checked.
100
+ let deleted = false;
86
101
  await withOwnedTransaction(ctx, async (c) => {
87
- await databases.flair.Memory.delete(record.id, c);
102
+ const stored = await databases.flair.Memory.get(record.id, c);
103
+ if (!isDeepStrictEqual(stored, record))
104
+ return;
105
+ // The transaction pauses here, between its read and its act.
106
+ const pause = txnPausePoint("maintenance-expiry");
107
+ if (pause)
108
+ await pause;
109
+ // Confirmation read: the committed row in an EXPLICIT fresh
110
+ // context (never contextless — a contextless read joins the
111
+ // request transaction and sees its old snapshot).
112
+ const confirmed = await databases.flair.Memory.get(record.id, {});
113
+ if (!isDeepStrictEqual(confirmed, stored))
114
+ return;
115
+ const result = await databases.flair.Memory.delete(record.id, c);
116
+ if (result !== true)
117
+ throw new Error("Memory row delete was not confirmed");
88
118
  await deletePointerRowOrThrow(record.id, c);
119
+ await recordMemoryDeletion({
120
+ memoryId: record.id,
121
+ memoryInstanceToken: stored.instanceToken ?? null,
122
+ durability: stored.durability ?? null,
123
+ actor: actorId ?? null,
124
+ sourceClass: callerIsAdmin ? "admin" : "agent",
125
+ }, c);
126
+ deleted = true;
89
127
  });
128
+ if (!deleted) {
129
+ stats.skipped++;
130
+ continue;
131
+ }
90
132
  // flair#1357 — ephemeral expiry removes the row from what the
91
133
  // lexical leg may score.
92
134
  noteMemoryDelete(record.id);
@@ -113,19 +155,50 @@ export class MemoryMaintenance extends Resource {
113
155
  if (!record.archived && (validToExpired || oldSession)) {
114
156
  if (!dryRun) {
115
157
  try {
116
- const archivedRow = {
117
- ...record,
118
- archived: true,
119
- archivedAt: now.toISOString(),
120
- };
121
- stripUndeclaredMemoryAttributes(archivedRow);
122
- // A1'' item 2 (0c): the archive write and its pointer delete
123
- // share ONE OWNED transaction; a failed pointer delete cannot
124
- // still commit the archived row.
158
+ // flair#2275: as for expiry, hold the scan-selected row still so
159
+ // another writer can commit first, then let the owned transaction
160
+ // below see the change and skip.
161
+ const beforeAct = txnPausePoint("maintenance-archive-pre");
162
+ if (beforeAct)
163
+ await beforeAct;
164
+ // A1'' item 2 (0c) + flair#2275: the write is built from the row
165
+ // read INSIDE the transaction (never from the scan copy), and the
166
+ // action runs only when the row is still the one the scan
167
+ // selected. A change seen by that read or the confirmation read is
168
+ // a SKIP; a change committed between the confirmation read and the
169
+ // commit is not checked.
170
+ let archivedRow;
125
171
  await withOwnedTransaction(ctx, async (c) => {
126
- await databases.flair.Memory.update(record.id, archivedRow, c);
172
+ const stored = await databases.flair.Memory.get(record.id, c);
173
+ if (!isDeepStrictEqual(stored, record))
174
+ return;
175
+ const pause = txnPausePoint("maintenance-archive");
176
+ if (pause)
177
+ await pause;
178
+ const confirmed = await databases.flair.Memory.get(record.id, {});
179
+ if (!isDeepStrictEqual(confirmed, stored))
180
+ return;
181
+ // flair#2470: the archive flip is written as an INCREMENTAL update of
182
+ // exactly `archived` and
183
+ // `archivedAt` — never a full-row put of the row read above. A
184
+ // full-row write would carry every field the read saw and could
185
+ // revert an owner PUT that started earlier and commits after this
186
+ // one (Harper orders the two by transaction timestamp) while that
187
+ // PUT still answered 200. The merged row marks a non-skipped
188
+ // operation and supplies the lexical-index note below.
189
+ const archivePatch = { archived: true, archivedAt: now.toISOString() };
190
+ archivedRow = { ...stored, ...archivePatch };
191
+ stripUndeclaredMemoryAttributes(archivedRow);
192
+ // A1'' item 2 (0c): the archive write and its pointer delete
193
+ // share ONE OWNED transaction; a failed pointer delete cannot
194
+ // still commit the archived row.
195
+ await databases.flair.Memory.update(record.id, archivePatch, c);
127
196
  await deletePointerRowOrThrow(record.id, c);
128
197
  });
198
+ if (!archivedRow) {
199
+ stats.skipped++;
200
+ continue;
201
+ }
129
202
  // flair#1357 — an `archived` flip changes what the retrieval
130
203
  // conditions (`archived not_equal true`) admit, so the lexical
131
204
  // index has to see it, not just content writes.
@@ -158,14 +231,21 @@ export class MemoryMaintenance extends Resource {
158
231
  if (typeof memoryId !== "string" || memoryId.length === 0)
159
232
  continue;
160
233
  try {
161
- const mem = await databases.flair.Memory.get(memoryId, ctx);
234
+ // flair#2275: read the pointed Memory in an EXPLICIT fresh context
235
+ // (never contextless). Is this pointer an orphan — its Memory
236
+ // missing or archived?
237
+ const mem = await databases.flair.Memory.get(memoryId, {});
162
238
  if (mem && mem.archived !== true)
163
239
  continue;
164
- // 0d: RE-CHECK inside an OWNED transaction before deleting. The
165
- // first read is outside it, so a new row reusing this id in
166
- // between must not be orphan-deleted; the conditional re-read
167
- // inside the transaction closes that read-to-delete gap. The
168
- // re-read is passed the owned transaction `c` (Gauge pass-5 item 2).
240
+ // 0d + flair#2275: a new row reusing this id, a promotion out of
241
+ // archived, or a replaced pointer may land before we open the owned
242
+ // transaction. Hold the row still so that writer can commit first,
243
+ // then re-check the Memory row AND the pointer row inside the
244
+ // transaction and at the confirmation read, and act only when both
245
+ // are STILL the ones the selection read saw; otherwise SKIP.
246
+ const beforeAct = txnPausePoint("maintenance-orphan-pre");
247
+ if (beforeAct)
248
+ await beforeAct;
169
249
  //
170
250
  // Round 22: one orphan's failure must abort only THAT orphan, not
171
251
  // the whole sweep — catch it, count stats.errors, and continue (the
@@ -174,15 +254,38 @@ export class MemoryMaintenance extends Resource {
174
254
  // of the callback). Pinned by test/unit/memory-host-source.test.ts
175
255
  // (r22-orphan-continues) — RED if the try/catch is removed.
176
256
  let committed = false;
257
+ let skipped = false;
177
258
  await withOwnedTransaction(ctx, async (c) => {
178
259
  const again = await databases.flair.Memory.get(memoryId, c);
179
- if (!again || again.archived === true) {
180
- await deletePointerRowOrThrow(memoryId, c);
181
- committed = true;
260
+ if (!isDeepStrictEqual(again, mem)) {
261
+ skipped = true;
262
+ return;
263
+ }
264
+ const ptrAgain = await pointerTable.get(memoryId, c);
265
+ if (!isDeepStrictEqual(ptrAgain, ptr)) {
266
+ skipped = true;
267
+ return;
268
+ }
269
+ const pause = txnPausePoint("maintenance-orphan");
270
+ if (pause)
271
+ await pause;
272
+ const confirmed = await databases.flair.Memory.get(memoryId, {});
273
+ if (!isDeepStrictEqual(confirmed, again)) {
274
+ skipped = true;
275
+ return;
276
+ }
277
+ const ptrConfirmed = await pointerTable.get(memoryId, {});
278
+ if (!isDeepStrictEqual(ptrConfirmed, ptrAgain)) {
279
+ skipped = true;
280
+ return;
182
281
  }
282
+ await deletePointerRowOrThrow(memoryId, c);
283
+ committed = true;
183
284
  });
184
285
  if (committed)
185
286
  stats.orphans++;
287
+ else if (skipped)
288
+ stats.skipped++;
186
289
  }
187
290
  catch (err) {
188
291
  stats.errors++;
@@ -203,7 +306,7 @@ export class MemoryMaintenance extends Resource {
203
306
  error: "maintenance_incomplete",
204
307
  message: `${stats.errors} cleanup error(s); see counts`,
205
308
  stats, expired: stats.expired, archived: stats.archived, total: stats.total,
206
- errors: stats.errors, orphans: stats.orphans,
309
+ errors: stats.errors, orphans: stats.orphans, skipped: stats.skipped,
207
310
  }), { status: 500, headers: { "content-type": "application/json" } });
208
311
  }
209
312
  // Flatten the historical { stats } wrapper into the top level so callers
@@ -217,6 +320,7 @@ export class MemoryMaintenance extends Resource {
217
320
  total: stats.total,
218
321
  errors: stats.errors,
219
322
  orphans: stats.orphans,
323
+ skipped: stats.skipped,
220
324
  };
221
325
  }
222
326
  }
@@ -0,0 +1,232 @@
1
+ /**
2
+ * MemoryPurge.ts — operator-triggered PHYSICAL removal of Memory rows.
3
+ *
4
+ * POST /MemoryPurge { ids: string[] } targets named Memory rows for physical
5
+ * deletion. A skill-tagged row (or any row carrying a `skillSubjectId`) expands
6
+ * to every row in its skill lineage, including superseded versions.
7
+ *
8
+ * Authority: the operator source (`soulWriteSource`): verified Basic
9
+ * administrator credentials, or a deliberate internal call. Agent keys, admin
10
+ * agent keys included, are refused.
11
+ *
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:
14
+ *
15
+ * 1. One owned transaction holds each target's row delete and, for a
16
+ * permanent or persistent row, its deletion-history record (other rows get
17
+ * none); a failed history write aborts it. A target that is not stored when
18
+ * the call reads it before deleting fails the call before anything commits
19
+ * (404 memory_purge_target_missing).
20
+ * 2. A read after the commit sorts the targets: `removedIds` lists the ones it
21
+ * finds gone; the others are still stored.
22
+ * 3. For a target still stored, the call attempts deletion of the history
23
+ * record step 1 wrote for it and checks for absence after that commit.
24
+ * 4. Host-pointer rows are deleted only for targets step 2 found gone, so a
25
+ * row that is still stored keeps its pointer row. One owned transaction
26
+ * re-reads each such row and deletes its pointer row through the
27
+ * pointer-table adapter while the row is still absent; a read after that
28
+ * commit looks for pointer rows left for rows that are still absent.
29
+ *
30
+ * Reply, checked in this order: unconfirmed history cleanup fails the call
31
+ * (500 memory_purge_history_cleanup_unconfirmed, with the record ids); a failed
32
+ * pointer delete or confirmation read, or a pointer row left after step 4,
33
+ * fails it (500 memory_purge_pointer_cleanup_failed). A later successful maintenance sweep
34
+ * can remove leftover pointers while their Memory rows remain absent. A target
35
+ * still stored fails it (409 memory_purge_unconfirmed). Otherwise the reply is
36
+ * `{ removed, removedIds }`.
37
+ *
38
+ * This is a separate path from the user-facing `DELETE /Memory/<id>` route.
39
+ * An accepted DELETE of a non-reserved skill closes its head; the reserved
40
+ * `using-flair` seed is physically deleted.
41
+ */
42
+ import { Resource, databases } from "harper";
43
+ import { resolveAgentAuth } from "./agent-auth.js";
44
+ import { soulWriteSource } from "./soul-write-policy.js";
45
+ import { recordMemoryDeletion, removeMemoryDeletionRecords } from "./memory-deletion-history.js";
46
+ import { withOwnedTransaction } from "./request-transaction.js";
47
+ import { deletePointerRowViaTable } from "./host-pointer-adapter.js";
48
+ import { storedPointerIds } from "./memory-host-source.js";
49
+ function reply(status, body) {
50
+ return new Response(JSON.stringify(body), {
51
+ status,
52
+ headers: { "content-type": "application/json" },
53
+ });
54
+ }
55
+ function errorText(err) {
56
+ return err instanceof Error ? err.message : String(err);
57
+ }
58
+ /** A target that is not stored when the call reads it before deleting. */
59
+ class MissingTarget extends Error {
60
+ ids;
61
+ constructor(ids) {
62
+ super("memory_purge_target_missing");
63
+ this.ids = ids;
64
+ }
65
+ }
66
+ export class MemoryPurge extends Resource {
67
+ /** The operator source only (`soulWriteSource`). */
68
+ async allowCreate() {
69
+ const context = this.getContext?.();
70
+ return soulWriteSource(context, await resolveAgentAuth(context)) !== null;
71
+ }
72
+ async post(data) {
73
+ const ids = data?.ids;
74
+ if (!Array.isArray(ids) || ids.length === 0 || !ids.every((x) => typeof x === "string" && x.length > 0)) {
75
+ return reply(400, { error: "memory_purge_ids_invalid", message: "ids must be a non-empty array of non-empty strings" });
76
+ }
77
+ const ctx = this.getContext?.();
78
+ const memory = databases.flair?.Memory;
79
+ if (!memory || typeof memory.get !== "function" || typeof memory.search !== "function" || typeof memory.delete !== "function") {
80
+ return reply(500, { error: "Memory table unavailable" });
81
+ }
82
+ // Resolve the full target set before mutating: every named row plus, for a
83
+ // skill row, every row in its skill lineage (superseded version rows
84
+ // 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;
92
+ }
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)
99
+ 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
+ }
106
+ }
107
+ if (missing.length > 0) {
108
+ return reply(404, { error: "memory_purge_target_missing", ids: missing });
109
+ }
110
+ // 1. ONE owned transaction per call: a failed read or history write aborts
111
+ // every write in it. No pointer row is touched here (step 4).
112
+ const historyIds = new Map();
113
+ try {
114
+ await withOwnedTransaction(ctx, async (c) => {
115
+ for (const id of targets.keys()) {
116
+ const stored = await memory.get(id, c);
117
+ if (!stored)
118
+ throw new MissingTarget([id]);
119
+ await memory.delete(id, c);
120
+ const historyId = await recordMemoryDeletion({
121
+ memoryId: id,
122
+ memoryInstanceToken: stored.instanceToken ?? null,
123
+ durability: stored.durability ?? null,
124
+ actor: null,
125
+ sourceClass: "admin",
126
+ }, c);
127
+ if (historyId)
128
+ historyIds.set(id, historyId);
129
+ }
130
+ });
131
+ }
132
+ catch (err) {
133
+ if (err instanceof MissingTarget)
134
+ return reply(404, { error: "memory_purge_target_missing", ids: err.ids });
135
+ throw err;
136
+ }
137
+ // 2. Confirm against the committed store: a target counts as removed only
138
+ // if a read after the commit finds it gone.
139
+ const removedIds = [];
140
+ const stillStored = [];
141
+ await withOwnedTransaction(ctx, async (c) => {
142
+ for (const id of targets.keys()) {
143
+ if (await memory.get(id, c))
144
+ stillStored.push(id);
145
+ else
146
+ removedIds.push(id);
147
+ }
148
+ });
149
+ // 3. Attempt cleanup of history for rows still stored; confirm absence
150
+ // after the cleanup commit. Failed cleanup is reported below.
151
+ const staleHistory = stillStored.flatMap((id) => {
152
+ const historyId = historyIds.get(id);
153
+ return historyId ? [{ memoryId: id, historyId }] : [];
154
+ });
155
+ let historyError = null;
156
+ let historyLeft;
157
+ try {
158
+ historyLeft = new Set(await removeMemoryDeletionRecords(staleHistory.map((h) => h.historyId), ctx));
159
+ }
160
+ catch (err) {
161
+ historyError = err;
162
+ historyLeft = new Set(staleHistory.map((h) => h.historyId));
163
+ }
164
+ // 4. Pointer rows of the rows step 2 found gone. A row stored again under
165
+ // the same id before this transaction keeps its pointer row.
166
+ let pointerError = null;
167
+ if (removedIds.length > 0) {
168
+ try {
169
+ await withOwnedTransaction(ctx, async (c) => {
170
+ for (const id of removedIds) {
171
+ if (!(await memory.get(id, c)))
172
+ await deletePointerRowViaTable(id, c);
173
+ }
174
+ });
175
+ }
176
+ catch (err) {
177
+ pointerError = errorText(err);
178
+ }
179
+ }
180
+ const pointerLeft = [];
181
+ let pointerConfirmationError = null;
182
+ try {
183
+ const pointers = await withOwnedTransaction(ctx, (c) => storedPointerIds(removedIds, c));
184
+ if (pointers.size > 0) {
185
+ await withOwnedTransaction(ctx, async (c) => {
186
+ for (const id of removedIds) {
187
+ if (pointers.has(id) && !(await memory.get(id, c)))
188
+ pointerLeft.push(id);
189
+ }
190
+ });
191
+ }
192
+ }
193
+ catch (err) {
194
+ pointerConfirmationError = errorText(err);
195
+ }
196
+ if (historyLeft.size > 0) {
197
+ const left = staleHistory.filter((h) => historyLeft.has(h.historyId));
198
+ return reply(500, {
199
+ error: "memory_purge_history_cleanup_unconfirmed",
200
+ message: `these rows are still stored after the commit; ${historyError !== null
201
+ ? `could not confirm deletion of their deletion-history records (${errorText(historyError)})`
202
+ : "their deletion-history records were not deleted and are still stored"}`,
203
+ ids: left.map((h) => h.memoryId),
204
+ historyIds: left.map((h) => h.historyId),
205
+ stillStoredIds: stillStored,
206
+ removedIds,
207
+ });
208
+ }
209
+ if (pointerError !== null || pointerConfirmationError !== null || pointerLeft.length > 0) {
210
+ return reply(500, {
211
+ error: "memory_purge_pointer_cleanup_failed",
212
+ message: `${pointerError !== null
213
+ ? `the pointer-row delete for rows in removedIds failed (${pointerError})`
214
+ : pointerConfirmationError !== null
215
+ ? `could not confirm pointer-row deletion for rows in removedIds (${pointerConfirmationError})`
216
+ : "rows in removedIds still have a pointer row after its delete"}`,
217
+ ids: pointerLeft,
218
+ stillStoredIds: stillStored,
219
+ removedIds,
220
+ });
221
+ }
222
+ if (stillStored.length > 0) {
223
+ return reply(409, {
224
+ error: "memory_purge_unconfirmed",
225
+ message: "these rows are still stored after the commit; retry the purge",
226
+ ids: stillStored,
227
+ removedIds,
228
+ });
229
+ }
230
+ return { removed: removedIds.length, removedIds };
231
+ }
232
+ }
@@ -45,6 +45,7 @@
45
45
  * Harper's 30s open-transaction 422 (flair#1263).
46
46
  */
47
47
  import { Resource, databases, logger } from "harper";
48
+ import { isDeepStrictEqual } from "node:util";
48
49
  import { randomBytes } from "node:crypto";
49
50
  import { existsSync } from "node:fs";
50
51
  import { resolve } from "node:path";
@@ -52,6 +53,7 @@ import { homedir } from "node:os";
52
53
  import { setImmediate as yieldToRequests } from "node:timers/promises";
53
54
  import { isAdmin, allowVerified } from "./agent-auth.js";
54
55
  import { patchRecordSilent } from "./table-helpers.js";
56
+ import { txnPausePoint } from "./txn-pause-point.js";
55
57
  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";
56
58
  import { reflectModelsGenerate } from "./memory-reflect-models.js";
57
59
  import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
@@ -59,7 +61,7 @@ import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js
59
61
  const REM_PAUSE_FLAG = resolve(homedir(), ".flair", "rem.paused");
60
62
  const GATHER_SELECT = [
61
63
  "id", "agentId", "archived", "durability", "expiresAt", "tags",
62
- "createdAt", "lastReflected", "content",
64
+ "createdAt", "lastReflected", "content", "instanceToken", "contentHash",
63
65
  ];
64
66
  export class ReflectMemories extends Resource {
65
67
  // Self-authorize via the Ed25519 agent verify (auth reshape removes the gate's
@@ -295,7 +297,10 @@ export class ReflectMemories extends Resource {
295
297
  for (const memory of memories) {
296
298
  const reflectPatch = { lastReflected: now };
297
299
  stripUndeclaredMemoryAttributes(reflectPatch);
298
- patchRecordSilent(databases.flair.Memory, memory.id, 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
+ });
299
304
  }
300
305
  }
301
306
  return {
@@ -10,10 +10,11 @@
10
10
  * Scans the Memory primary store (unfiltered, via the base table class) and
11
11
  * compares per-agent primary counts against per-agent secondary-index counts
12
12
  * (an equals lookup on agentId). Any agent whose secondary count is below
13
- * its primary count has unindexed records. Re-PUT every record with the
14
- * _reindex escape hatch: Memory.put() retains declared and named allowed
15
- * fields, restores stored provenance and preserves an existing incarnation
16
- * token (or generates an absent one). Other undeclared fields are stripped.
13
+ * its primary count has unindexed records. Re-PUT every record with the row
14
+ * built by buildReindexRow (the path Memory.put()'s _reindex branch also
15
+ * uses): it retains declared and named allowed fields, restores stored
16
+ * provenance and preserves an existing incarnation token (or generates an
17
+ * absent one). Other undeclared fields are stripped.
17
18
  * No updatedAt bump, embedding regeneration or safety rescan is performed.
18
19
  *
19
20
  * Why this exists: Harper's background runIndexing() pass populates secondary
@@ -27,6 +28,9 @@
27
28
  */
28
29
  import { Resource, databases } from "harper";
29
30
  import { isAdmin, allowAdmin } from "./agent-auth.js";
31
+ import { writeBackCommittedRow, writeBackIdentity } from "./write-back.js";
32
+ import { txnPausePoint } from "./txn-pause-point.js";
33
+ import { buildReindexRow } from "./Memory.js";
30
34
  export class MemoryReindex extends Resource {
31
35
  // Admin-only: permit verified ADMIN agents (Basic-admin is super_user and
32
36
  // bypasses allow*); non-admin agents denied. Mirrors the handler's admin gate
@@ -62,6 +66,7 @@ export class MemoryReindex extends Resource {
62
66
  // Pass 1: primary-store scan. Count records per agent.
63
67
  const primaryByAgent = new Map();
64
68
  const recordsToReindex = [];
69
+ const selectedRows = new Map();
65
70
  for await (const record of Memory.search()) {
66
71
  if (agentFilter && record.agentId !== agentFilter)
67
72
  continue;
@@ -69,6 +74,9 @@ export class MemoryReindex extends Resource {
69
74
  continue;
70
75
  primaryByAgent.set(record.agentId, (primaryByAgent.get(record.agentId) ?? 0) + 1);
71
76
  recordsToReindex.push(record.id);
77
+ // Only the identity fields the write-back compares (never the
78
+ // embedding): the full row is re-read inside each owned write.
79
+ selectedRows.set(record.id, writeBackIdentity(record));
72
80
  }
73
81
  stats.scanned = recordsToReindex.length;
74
82
  // Pass 2: for each agent, probe the secondary index via an agentId-only equals
@@ -104,7 +112,7 @@ export class MemoryReindex extends Resource {
104
112
  stats,
105
113
  };
106
114
  }
107
- // Pass 3: re-PUT every primary-store record with _reindex=true, retaining
115
+ // Pass 3: re-PUT every primary-store record through buildReindexRow, retaining
108
116
  // declared/named fields and stored provenance, stripping other undeclared
109
117
  // fields and generating an absent token. The re-PUT forces Harper to re-insert
110
118
  // into all secondary indices. Cheaper-than-sound variants (only re-PUT records
@@ -114,12 +122,20 @@ export class MemoryReindex extends Resource {
114
122
  const chunk = recordsToReindex.slice(i, i + batchSize);
115
123
  for (const id of chunk) {
116
124
  try {
117
- const record = await Memory.get(id);
118
- if (!record) {
125
+ const outcome = await writeBackCommittedRow(Memory, id, (record) => {
126
+ if (!record)
127
+ return { skip: true };
128
+ // Built by the function Memory.put()'s `_reindex` branch uses,
129
+ // from this transaction's read.
130
+ const built = buildReindexRow({ ...record, _reindex: true }, record);
131
+ if (!("row" in built))
132
+ 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) });
135
+ if ("skip" in outcome) {
119
136
  stats.errors++;
120
137
  continue;
121
138
  }
122
- await Memory.put({ ...record, _reindex: true });
123
139
  stats.reindexed++;
124
140
  }
125
141
  catch (err) {
@@ -20,11 +20,12 @@ 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
22
  import { relaySend, relayInbox, relayConsume, relayDeadLetters, relaySweepDeadlines, } from "./relay-ops.js";
23
- function relayDeps() {
23
+ function relayDeps(ctx) {
24
24
  return {
25
25
  messages: databases.flair.Message,
26
26
  agents: databases.flair.Agent,
27
27
  resolveOrg: localInstanceId,
28
+ ctx,
28
29
  };
29
30
  }
30
31
  function ctxOf(self) {
@@ -66,8 +67,9 @@ export class Message extends databases.flair.Message {
66
67
  return allowVerified(ctxOf(this));
67
68
  }
68
69
  async post(content) {
69
- const auth = await resolveAgentAuth(ctxOf(this));
70
- return relaySend(relayDeps(), auth, content ?? {});
70
+ const ctx = ctxOf(this);
71
+ const auth = await resolveAgentAuth(ctx);
72
+ return relaySend(relayDeps(ctx), auth, content ?? {});
71
73
  }
72
74
  /** Scope a non-admin agent's collection read to the messages it is a party
73
75
  * to (from/to === self); admin/internal unfiltered; anonymous denied. Reached