@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
@@ -31,12 +31,65 @@ async function deletePointerRowOrThrow(memoryId, ctx) {
31
31
  }
32
32
  await table.delete(memoryId, ctx);
33
33
  }
34
- import { isAdmin } from "./agent-auth.js";
34
+ import { annotatedCallerIsAdmin } from "./agent-auth.js";
35
35
  import { noteMemoryUpsert, noteMemoryDelete } from "./bm25-index-service.js";
36
36
  import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
37
37
  import { withOwnedTransaction } from "./request-transaction.js";
38
38
  import { recordMemoryDeletion } from "./memory-deletion-history.js";
39
39
  import { txnPausePoint } from "./txn-pause-point.js";
40
+ import { withMemoryWriteLockOnce } from "./memory-write-lock.js";
41
+ import { verifyCommittedFields } from "./write-back.js";
42
+ import { AGENT_ID_RULE, isValidAgentId } from "../src/lib/agent-id-rule.js";
43
+ /** The 400 an admin run's refused `agentId` is answered with. */
44
+ const INVALID_AGENT_ID_ERROR = `agentId must be a string matching ${AGENT_ID_RULE}`;
45
+ /** The `remedy` the same 400 carries: what an operator can do today for a
46
+ * legacy stored id outside the rule. An admin-scoped run needs a conforming
47
+ * id. The agent's own authenticated run reaches its rows only when the stored
48
+ * id can authenticate: the signed TPS-Ed25519 header cannot carry a colon or
49
+ * whitespace. For an id the header cannot represent, a fleet-wide run reaches
50
+ * its rows and also acts on other agents' eligible rows. */
51
+ const INVALID_AGENT_ID_REMEDY = "for a legacy stored agent id outside this rule, run that agent's own authenticated non-admin " +
52
+ "maintenance (POST /MemoryMaintenance with that agent's credential), which reaches its rows, when the " +
53
+ "stored id can authenticate: the signed TPS-Ed25519 header cannot carry a colon or whitespace. For an " +
54
+ "id the header cannot represent, omit agentId to run fleet-wide, which reaches that agent's rows and " +
55
+ "also expires and archives other agents' eligible rows. A run scoped to an admin agentId needs an id " +
56
+ "that matches the rule.";
57
+ /** The per-id Memory write lock store (flair#2478 slice 3b). */
58
+ function memoryLockStore() {
59
+ return databases?.flair?.Memory?.primaryStore;
60
+ }
61
+ /** Report a per-row action this run did not apply, and why. An automatic
62
+ * writer's lock miss is a skip that is reported, never a row written
63
+ * unserialized over an owner's write. */
64
+ function noteSkipped(stats, id, reason) {
65
+ stats.skipped++;
66
+ console.warn("[MemoryMaintenance] row skipped: %s (id %s)", reason, String(id));
67
+ }
68
+ /** This parser accepts only a non-blank string that equals its trimmed form;
69
+ * any other value names no target. */
70
+ function parseAgentIdValue(value) {
71
+ if (typeof value !== "string" || value.trim().length === 0)
72
+ return { kind: "invalid" };
73
+ if (value !== value.trim())
74
+ return { kind: "invalid" };
75
+ return { kind: "named", agentId: value };
76
+ }
77
+ /** Classify a request body's `agentId`. Presence is decided on the body itself,
78
+ * before its value is parsed: the field is absent only when the body has no own
79
+ * `agentId` property and reading `agentId` yields `undefined`. A present field
80
+ * is parsed by value, so a supplied `undefined`, `null`, non-string, empty or
81
+ * blank value is invalid rather than read as absent. A value parseAgentIdValue
82
+ * accepts is then held to the shared agent-id rule. */
83
+ function parseRequestedAgent(body) {
84
+ const present = body != null && Object.prototype.hasOwnProperty.call(body, "agentId");
85
+ const value = body == null ? undefined : body.agentId;
86
+ if (!present && value === undefined)
87
+ return { kind: "absent" };
88
+ const parsed = parseAgentIdValue(value);
89
+ if (parsed.kind === "named" && !isValidAgentId(parsed.agentId))
90
+ return { kind: "invalid" };
91
+ return parsed;
92
+ }
40
93
  export class MemoryMaintenance extends Resource {
41
94
  /** POST requires auth — either an agent acting on its own memories, or admin. */
42
95
  allowCreate() {
@@ -45,19 +98,29 @@ export class MemoryMaintenance extends Resource {
45
98
  return !!(request?.tpsAgent || request?.tpsAgentIsAdmin);
46
99
  }
47
100
  async post(data) {
48
- const { dryRun = false, agentId: bodyAgentId } = data || {};
101
+ const body = data || {};
102
+ const { dryRun = false } = body;
49
103
  const ctx = this.getContext?.();
50
104
  const request = ctx?.request ?? ctx;
51
105
  const actorId = request?.tpsAgent;
52
106
  const callerIsAdmin = request?.tpsAgentIsAdmin === true
53
- || (actorId ? await isAdmin(actorId) : false);
107
+ || (await annotatedCallerIsAdmin(request));
54
108
  // Scope rules:
55
- // - Admin can pass agentId to maintain a specific agent (or omit it
56
- // for fleet-wide maintenance).
57
- // - Non-admin agents are scoped to their own memories — bodyAgentId
109
+ // - Admin can pass agentId to maintain a specific agent (or omit the
110
+ // field for fleet-wide maintenance). An admin request whose body has
111
+ // the field with a value that is not a string the shared agent-id rule
112
+ // accepts — `undefined` included — is refused, dry run or not.
113
+ // - Non-admin agents are scoped to their own memories — a body agentId
58
114
  // either matches the authenticated agent or is ignored.
115
+ const requestedAgent = parseRequestedAgent(body);
116
+ if (callerIsAdmin && requestedAgent.kind === "invalid") {
117
+ return new Response(JSON.stringify({ error: INVALID_AGENT_ID_ERROR, remedy: INVALID_AGENT_ID_REMEDY }), {
118
+ status: 400,
119
+ headers: { "content-type": "application/json" },
120
+ });
121
+ }
59
122
  const targetAgent = callerIsAdmin
60
- ? bodyAgentId
123
+ ? (requestedAgent.kind === "named" ? requestedAgent.agentId : undefined)
61
124
  : actorId;
62
125
  if (!targetAgent && !callerIsAdmin) {
63
126
  return new Response(JSON.stringify({ error: "agentId required" }), {
@@ -68,7 +131,15 @@ export class MemoryMaintenance extends Resource {
68
131
  const now = new Date();
69
132
  const stats = { expired: 0, archived: 0, total: 0, errors: 0, orphans: 0, skipped: 0, agent: targetAgent || "all" };
70
133
  try {
71
- for await (const record of databases.flair.Memory.search()) {
134
+ // A scoped run supplies the target agent as an indexed agentId condition
135
+ // (agentId is @indexed in schemas/memory.graphql), rather than scanning
136
+ // the whole table and filtering in process. The per-row check below still
137
+ // decides every row. No target means fleet-wide admin maintenance, which
138
+ // scans every row.
139
+ const memorySearch = targetAgent
140
+ ? databases.flair.Memory.search({ conditions: [{ attribute: "agentId", comparator: "equals", value: targetAgent }] })
141
+ : databases.flair.Memory.search();
142
+ for await (const record of memorySearch) {
72
143
  // Skip records not belonging to target agent (unless admin running fleet-wide).
73
144
  if (targetAgent && record.agentId !== targetAgent)
74
145
  continue;
@@ -97,38 +168,80 @@ export class MemoryMaintenance extends Resource {
97
168
  // re-read or the confirmation read below is a SKIP (recorded as
98
169
  // skipped); a change committed between the confirmation read and
99
170
  // the commit is not checked.
100
- let deleted = false;
101
- await withOwnedTransaction(ctx, async (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");
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;
127
- });
128
- if (!deleted) {
171
+ // flair#2478 slice 3b: the whole read-decide-write runs under the
172
+ // id's per-id Memory write lock, taken once with no wait. A held
173
+ // id (or one carrying an outcome-unknown marker) is skipped and
174
+ // reported, never deleted over an owner's write.
175
+ const outcome = await withMemoryWriteLockOnce(memoryLockStore(), [record.id], async () => {
176
+ let deleted = false;
177
+ await withOwnedTransaction(ctx, async (c) => {
178
+ const stored = await databases.flair.Memory.get(record.id, c);
179
+ if (!isDeepStrictEqual(stored, record))
180
+ return;
181
+ // The transaction pauses here, between its read and its act.
182
+ const pause = txnPausePoint("maintenance-expiry");
183
+ if (pause)
184
+ await pause;
185
+ // Confirmation read: the committed row in an EXPLICIT fresh
186
+ // context (never contextless — a contextless read joins the
187
+ // request transaction and sees its old snapshot).
188
+ const confirmed = await databases.flair.Memory.get(record.id, {});
189
+ if (!isDeepStrictEqual(confirmed, stored))
190
+ return;
191
+ const result = await databases.flair.Memory.delete(record.id, c);
192
+ if (result !== true)
193
+ throw new Error("Memory row delete was not confirmed");
194
+ await deletePointerRowOrThrow(record.id, c);
195
+ await recordMemoryDeletion({
196
+ memoryId: record.id,
197
+ memoryInstanceToken: stored.instanceToken ?? null,
198
+ durability: stored.durability ?? null,
199
+ actor: actorId ?? null,
200
+ sourceClass: callerIsAdmin ? "admin" : "agent",
201
+ }, c);
202
+ // Test-only: the delete is staged and the lock is still held.
203
+ const staged = txnPausePoint("maintenance-expiry-staged");
204
+ if (staged)
205
+ await staged;
206
+ // Test-only: the last confirmation has passed and the
207
+ // transaction has not committed yet.
208
+ const commitPoint = txnPausePoint("maintenance-expiry-commit");
209
+ if (commitPoint)
210
+ await commitPoint;
211
+ deleted = true;
212
+ });
213
+ if (!deleted)
214
+ return { kind: "skipped" };
215
+ // Test-only: the delete committed and the lock is still held.
216
+ const committed = txnPausePoint("maintenance-expiry-committed");
217
+ if (committed)
218
+ await committed;
219
+ return { kind: "deleted" };
220
+ }, { phase: "maintenance-expiry" });
221
+ if (outcome.kind !== "done") {
222
+ noteSkipped(stats, record.id, outcome.kind);
223
+ continue;
224
+ }
225
+ if (outcome.value.kind !== "deleted") {
129
226
  stats.skipped++;
130
227
  continue;
131
228
  }
229
+ // The committed row must be gone: a row still present after the
230
+ // commit is not counted as expired. An unreadable read is reported
231
+ // as a failed item, never as a success.
232
+ let after;
233
+ try {
234
+ after = await databases.flair.Memory.get(record.id, {});
235
+ }
236
+ catch (err) {
237
+ stats.errors++;
238
+ console.error("MemoryMaintenance: expiry outcome unconfirmed (committed row unreadable)", err);
239
+ continue;
240
+ }
241
+ if (after != null) {
242
+ noteSkipped(stats, record.id, "unconfirmed_delete");
243
+ continue;
244
+ }
132
245
  // flair#1357 — ephemeral expiry removes the row from what the
133
246
  // lexical leg may score.
134
247
  noteMemoryDelete(record.id);
@@ -167,38 +280,82 @@ export class MemoryMaintenance extends Resource {
167
280
  // selected. A change seen by that read or the confirmation read is
168
281
  // a SKIP; a change committed between the confirmation read and the
169
282
  // commit is not checked.
283
+ // flair#2478 slice 3b: the whole read-decide-write runs under the
284
+ // id's per-id Memory write lock, taken once with no wait. A held
285
+ // id (or one carrying an outcome-unknown marker) is skipped and
286
+ // reported, never archived over an owner's write.
170
287
  let archivedRow;
171
- await withOwnedTransaction(ctx, async (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);
196
- await deletePointerRowOrThrow(record.id, c);
197
- });
198
- if (!archivedRow) {
288
+ let archiveBasis;
289
+ let archivePatch;
290
+ const outcome = await withMemoryWriteLockOnce(memoryLockStore(), [record.id], async () => {
291
+ await withOwnedTransaction(ctx, async (c) => {
292
+ const stored = await databases.flair.Memory.get(record.id, c);
293
+ if (!isDeepStrictEqual(stored, record))
294
+ return;
295
+ const pause = txnPausePoint("maintenance-archive");
296
+ if (pause)
297
+ await pause;
298
+ const confirmed = await databases.flair.Memory.get(record.id, {});
299
+ if (!isDeepStrictEqual(confirmed, stored))
300
+ return;
301
+ // flair#2470: the archive flip is written as an INCREMENTAL update of
302
+ // exactly `archived` and
303
+ // `archivedAt` — never a full-row put of the row read above. A
304
+ // full-row write would carry every field the read saw and could
305
+ // revert an owner PUT that started earlier and commits after this
306
+ // one (Harper orders the two by transaction timestamp) while that
307
+ // PUT still answered 200. The merged row marks a non-skipped
308
+ // operation and supplies the lexical-index note below.
309
+ archivePatch = { archived: true, archivedAt: now.toISOString() };
310
+ archivedRow = { ...stored, ...archivePatch };
311
+ stripUndeclaredMemoryAttributes(archivedRow);
312
+ // A1'' item 2 (0c): the archive write and its pointer delete
313
+ // share ONE OWNED transaction; a failed pointer delete cannot
314
+ // still commit the archived row.
315
+ await databases.flair.Memory.update(record.id, archivePatch, c);
316
+ await deletePointerRowOrThrow(record.id, c);
317
+ archiveBasis = stored;
318
+ // Test-only: the update and its pointer delete are staged and
319
+ // the lock is still held.
320
+ const staged = txnPausePoint("maintenance-archive-staged");
321
+ if (staged)
322
+ await staged;
323
+ // Test-only: the last confirmation has passed and the
324
+ // transaction has not committed yet.
325
+ const commitPoint = txnPausePoint("maintenance-archive-commit");
326
+ if (commitPoint)
327
+ await commitPoint;
328
+ });
329
+ if (!archivedRow)
330
+ return { kind: "skipped" };
331
+ // Test-only: the archive committed and the lock is still held.
332
+ const committed = txnPausePoint("maintenance-archive-committed");
333
+ if (committed)
334
+ await committed;
335
+ return { kind: "archived" };
336
+ }, { phase: "maintenance-archive" });
337
+ if (outcome.kind !== "done") {
338
+ noteSkipped(stats, record.id, outcome.kind);
339
+ continue;
340
+ }
341
+ if (outcome.value.kind !== "archived") {
199
342
  stats.skipped++;
200
343
  continue;
201
344
  }
345
+ // The committed row must still show the staged archive fields. On
346
+ // a mismatch the row read now does not show this run's write, so
347
+ // the archive is unconfirmed; it is reported as skipped. An
348
+ // unreadable read is reported as a failed item.
349
+ const verdict = await verifyCommittedFields(databases.flair.Memory, record.id, archiveBasis, archivePatch ?? {});
350
+ if (verdict === "unreadable") {
351
+ stats.errors++;
352
+ console.error("MemoryMaintenance: archive outcome unconfirmed (committed row unreadable)");
353
+ continue;
354
+ }
355
+ if (verdict === "mismatch") {
356
+ noteSkipped(stats, record.id, "unconfirmed_archive");
357
+ continue;
358
+ }
202
359
  // flair#1357 — an `archived` flip changes what the retrieval
203
360
  // conditions (`archived not_equal true`) admit, so the lexical
204
361
  // index has to see it, not just content writes.
@@ -220,13 +377,39 @@ export class MemoryMaintenance extends Resource {
220
377
  // INTO Memory results), but it should not be left behind either. A
221
378
  // failed row read or delete is counted and the sweep continues; the
222
379
  // incomplete run is reported below (HTTP 500), never silently ignored.
380
+ // A dry run skips the sweep entirely and reports no orphans.
223
381
  const pointerTable = databases.flair?.[MEMORY_HOST_SOURCE_TABLE];
224
382
  if (!dryRun && !pointerTable?.search) {
225
383
  // Hygiene: a missing sweep table is REPORTED, never silently skipped.
226
384
  throw new Error("MemoryHostSource table unavailable (orphan sweep)");
227
385
  }
228
386
  if (pointerTable?.search && !dryRun) {
229
- for await (const ptr of pointerTable.search()) {
387
+ // Scope the sweep by the same rule as the Memory loop above: a run
388
+ // that names an agent searches the pointer table by its indexed
389
+ // `authorId`, so that agent's rows are the rows supplied; a fleet-wide
390
+ // run scans every row. The in-process check applies the same rule to
391
+ // each row before the pointed Memory read and every later per-row effect
392
+ // (count, error, delete). A pointer's owner is the `authorId` the write
393
+ // path stamped on the row; a pointer with an empty author has no owner
394
+ // and is outside an owner-targeted run.
395
+ // How a pointer replaced after this selection is handled, and the bound
396
+ // on that, is stated at the owned transaction below.
397
+ const pointerInScope = (pointer) => {
398
+ if (!targetAgent)
399
+ return true;
400
+ const author = parseAgentIdValue(pointer?.authorId);
401
+ return author.kind === "named" && author.agentId === targetAgent;
402
+ };
403
+ // A scoped run's pointer search reads only the target agent's rows:
404
+ // authorId is @indexed in schemas/memory.graphql, so the search is an
405
+ // indexed condition rather than a table-wide scan filtered in process.
406
+ // No target means fleet-wide admin maintenance, which scans every row.
407
+ const pointerSearch = targetAgent
408
+ ? pointerTable.search({ conditions: [{ attribute: "authorId", comparator: "equals", value: targetAgent }] })
409
+ : pointerTable.search();
410
+ for await (const ptr of pointerSearch) {
411
+ if (!pointerInScope(ptr))
412
+ continue;
230
413
  const memoryId = ptr?.memoryId;
231
414
  if (typeof memoryId !== "string" || memoryId.length === 0)
232
415
  continue;
@@ -249,10 +432,35 @@ export class MemoryMaintenance extends Resource {
249
432
  //
250
433
  // Round 22: one orphan's failure must abort only THAT orphan, not
251
434
  // the whole sweep — catch it, count stats.errors, and continue (the
252
- // item loops above already work this way). stats.orphans counts a
253
- // row only AFTER its owned transaction COMMITS (the count moves out
254
- // of the callback). Pinned by test/unit/memory-host-source.test.ts
255
- // (r22-orphan-continues) — RED if the try/catch is removed.
435
+ // item loops above already work this way). Pinned by
436
+ // test/unit-isolated/memory-host-source.test.ts (r22-orphan-continues) — RED
437
+ // if the try/catch is removed.
438
+ //
439
+ // The candidate re-reads and the staged delete run in ONE owned
440
+ // transaction (`c`); the confirmation reads run inside its callback
441
+ // but through fresh contexts, so they see committed state. Harper
442
+ // has no compare-and-delete on a row's contents:
443
+ // the delete carries no condition on the pointer row it removes.
444
+ // Harper stamps the transaction's writes with one time,
445
+ // taken at its first read (the in-transaction Memory re-read below,
446
+ // before the confirmation reads), and applies a row's writes in the
447
+ // order of those times:
448
+ // - a replacement committed before the confirmation read is SEEN
449
+ // by it, and the pointer is skipped;
450
+ // - a replacement whose own transaction takes its time after this
451
+ // transaction's first read carries a later time, so Harper
452
+ // applies it after this delete and it stays stored
453
+ // (test/integration/memory-maintenance-owner-scope-2084.test.ts
454
+ // commits one at the `maintenance-orphan-commit` pause).
455
+ // Not covered: a write whose own transaction took its time before
456
+ // this transaction's first read and commits after the confirmation
457
+ // read. There is no compare-and-set; per-id serialization is
458
+ // tracked in flair#2478.
459
+ //
460
+ // Harper can skip a staged delete at commit (a newer write wins), so
461
+ // stats.orphans counts a pointer only when a read AFTER the commit
462
+ // finds no row for its memoryId; a row found there is counted as
463
+ // skipped, never as removed.
256
464
  let committed = false;
257
465
  let skipped = false;
258
466
  await withOwnedTransaction(ctx, async (c) => {
@@ -280,10 +488,20 @@ export class MemoryMaintenance extends Resource {
280
488
  return;
281
489
  }
282
490
  await deletePointerRowOrThrow(memoryId, c);
491
+ // Held after the final confirmation and the staged delete, before
492
+ // the commit, so a replacement can commit in that window.
493
+ const beforeCommit = txnPausePoint("maintenance-orphan-commit");
494
+ if (beforeCommit)
495
+ await beforeCommit;
283
496
  committed = true;
284
497
  });
285
- if (committed)
286
- stats.orphans++;
498
+ if (committed) {
499
+ const afterCommit = await pointerTable.get(memoryId, {});
500
+ if (afterCommit == null)
501
+ stats.orphans++;
502
+ else
503
+ stats.skipped++;
504
+ }
287
505
  else if (skipped)
288
506
  stats.skipped++;
289
507
  }