@tpsdev-ai/flair 0.62.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +18 -10
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/types.js +1 -0
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli.js +66 -122
  8. package/dist/commands/agent.js +27 -65
  9. package/dist/commands/backup-approval.js +218 -0
  10. package/dist/commands/backup.js +37 -33
  11. package/dist/commands/bootstrap.js +3 -1
  12. package/dist/commands/deploy.js +37 -7
  13. package/dist/commands/doctor.js +119 -0
  14. package/dist/commands/export.js +3 -4
  15. package/dist/commands/federation.js +653 -68
  16. package/dist/commands/grant.js +5 -6
  17. package/dist/commands/help.js +25 -0
  18. package/dist/commands/idp.js +14 -19
  19. package/dist/commands/import.js +131 -19
  20. package/dist/commands/init.js +7 -7
  21. package/dist/commands/integrity.js +5 -6
  22. package/dist/commands/mcp.js +11 -17
  23. package/dist/commands/memory.js +33 -15
  24. package/dist/commands/orgevent.js +5 -10
  25. package/dist/commands/principal.js +13 -25
  26. package/dist/commands/quality.js +3 -0
  27. package/dist/commands/rem.js +484 -65
  28. package/dist/commands/restore.js +352 -44
  29. package/dist/commands/service.js +84 -2
  30. package/dist/commands/soul.js +0 -6
  31. package/dist/commands/status.js +51 -33
  32. package/dist/commands/test.js +4 -1
  33. package/dist/commands/upgrade.js +53 -22
  34. package/dist/commands/workspace.js +7 -8
  35. package/dist/deploy.js +59 -3
  36. package/dist/doctor-client.js +7 -2
  37. package/dist/fabric-upgrade.js +12 -2
  38. package/dist/federation/presence-send.js +139 -0
  39. package/dist/federation-verify.js +269 -177
  40. package/dist/install/clients.js +171 -35
  41. package/dist/lib/agent-id-rule.js +44 -2
  42. package/dist/lib/atomic-write.js +1 -1
  43. package/dist/lib/auth-resolve.js +1028 -52
  44. package/dist/lib/backup-approval-store.js +612 -0
  45. package/dist/lib/backup-artifact.js +343 -0
  46. package/dist/lib/config-critical-section.js +212 -25
  47. package/dist/lib/connect-phase.js +33 -0
  48. package/dist/lib/daemon-liveness.js +2 -1
  49. package/dist/lib/federation-pair-access.js +4 -0
  50. package/dist/lib/federation-retry-queue.js +283 -0
  51. package/dist/lib/federation-retry-row.js +101 -0
  52. package/dist/lib/instruction-event-contract.js +17 -0
  53. package/dist/lib/instruction-event-doctor.js +102 -0
  54. package/dist/lib/launchd-management.js +14 -3
  55. package/dist/lib/mcp-enable.js +14 -15
  56. package/dist/lib/memory-attributes.js +2 -0
  57. package/dist/lib/memory-provider-timeout.js +33 -0
  58. package/dist/lib/mqtt-config.js +132 -0
  59. package/dist/lib/mqtt-listener-doctor.js +104 -0
  60. package/dist/lib/open-live-row.js +20 -0
  61. package/dist/lib/ops-url.js +52 -0
  62. package/dist/lib/promotion-content-hash.js +20 -0
  63. package/dist/lib/restore-archive.js +760 -0
  64. package/dist/lib/restore-verify.js +1 -1
  65. package/dist/lib/skill-assignment-preflight.js +159 -0
  66. package/dist/lib/skill-seed.js +91 -8
  67. package/dist/lib/skill-tombstone-doctor.js +133 -0
  68. package/dist/lib/soul-scope-fields.js +26 -0
  69. package/dist/lib/uninstall-purge.js +266 -11
  70. package/dist/lib/upgrade-prior-liveness.js +2 -1
  71. package/dist/mcp-client-assertion.js +2 -10
  72. package/dist/memory-id-checkpoint.js +28 -7
  73. package/dist/mqtt-off-deploy.js +550 -0
  74. package/dist/rem/promote-policy.js +3 -3
  75. package/dist/rem/restore.js +302 -26
  76. package/dist/rem/runner.js +220 -58
  77. package/dist/rem/scheduler.js +21 -4
  78. package/dist/resources/A2AAdapter.js +131 -178
  79. package/dist/resources/AdminMemory.js +2 -0
  80. package/dist/resources/AdminMemoryCandidates.js +116 -0
  81. package/dist/resources/Agent.js +155 -45
  82. package/dist/resources/AgentCard.js +4 -0
  83. package/dist/resources/AgentKeyRegister.js +56 -22
  84. package/dist/resources/AgentReadPosition.js +7 -0
  85. package/dist/resources/AgentSeed.js +232 -107
  86. package/dist/resources/AutoPromoteCandidates.js +413 -84
  87. package/dist/resources/Credential.js +6 -8
  88. package/dist/resources/Federation.js +219 -57
  89. package/dist/resources/FederationRetry.js +4 -4
  90. package/dist/resources/InstructionVersion.js +1 -1
  91. package/dist/resources/MCPClientMetadata.js +6 -3
  92. package/dist/resources/Memory.js +1303 -270
  93. package/dist/resources/MemoryArchive.js +149 -64
  94. package/dist/resources/MemoryBootstrap.js +12 -22
  95. package/dist/resources/MemoryCandidate.js +16 -2
  96. package/dist/resources/MemoryConsolidate.js +2 -2
  97. package/dist/resources/MemoryFeed.js +360 -147
  98. package/dist/resources/MemoryMaintenance.js +290 -72
  99. package/dist/resources/MemoryPurge.js +138 -22
  100. package/dist/resources/MemoryReflect.js +68 -14
  101. package/dist/resources/MemoryReindex.js +91 -13
  102. package/dist/resources/Message.js +11 -2
  103. package/dist/resources/OAuth.js +156 -39
  104. package/dist/resources/OAuthClient.js +1 -1
  105. package/dist/resources/OrgEvent.js +292 -29
  106. package/dist/resources/OrgEventCatchup.js +7 -0
  107. package/dist/resources/OrgEventMaintenance.js +48 -10
  108. package/dist/resources/PairingToken.js +1 -1
  109. package/dist/resources/Presence.js +31 -11
  110. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  111. package/dist/resources/RecordUsage.js +2 -4
  112. package/dist/resources/Soul.js +2 -0
  113. package/dist/resources/SoulFeed.js +2 -1
  114. package/dist/resources/WorkspaceLatest.js +4 -0
  115. package/dist/resources/XAA.js +36 -10
  116. package/dist/resources/a2a-stream.js +313 -0
  117. package/dist/resources/a2a-url.js +4 -5
  118. package/dist/resources/agent-admin.js +10 -1
  119. package/dist/resources/agent-auth.js +98 -68
  120. package/dist/resources/agent-read-position-lib.js +4 -1
  121. package/dist/resources/agent-status-guard.js +9 -7
  122. package/dist/resources/auth-middleware.js +166 -42
  123. package/dist/resources/authority-field-guard.js +9 -11
  124. package/dist/resources/auto-promote-lib.js +8 -5
  125. package/dist/resources/basic-auth-header.js +21 -0
  126. package/dist/resources/bm25-index-service.js +4 -5
  127. package/dist/resources/dedup-cluster.js +6 -1
  128. package/dist/resources/embeddings-provider.js +25 -0
  129. package/dist/resources/federation-classify.js +89 -0
  130. package/dist/resources/federation-retry-lib.js +6 -81
  131. package/dist/resources/health.js +43 -4
  132. package/dist/resources/host-pointer/registry.js +29 -0
  133. package/dist/resources/host-pointer-adapter.js +1 -0
  134. package/dist/resources/in-process.js +24 -22
  135. package/dist/resources/instruction-version-record.js +251 -7
  136. package/dist/resources/internal-authority.js +13 -0
  137. package/dist/resources/mcp-handler.js +106 -12
  138. package/dist/resources/mcp-oauth-flag.js +12 -14
  139. package/dist/resources/mcp-oauth.js +430 -53
  140. package/dist/resources/mcp-tools.js +60 -22
  141. package/dist/resources/memory-declared-attributes.js +1 -0
  142. package/dist/resources/memory-embed-hash.js +56 -0
  143. package/dist/resources/memory-host-source.js +5 -2
  144. package/dist/resources/memory-reflect-lib.js +1 -1
  145. package/dist/resources/memory-write-lock.js +202 -23
  146. package/dist/resources/memory-write-response.js +1 -1
  147. package/dist/resources/memory-write-transaction.js +243 -0
  148. package/dist/resources/migration-boot.js +17 -12
  149. package/dist/resources/migrations/boot-progress.js +25 -0
  150. package/dist/resources/migrations/data-dir.js +16 -3
  151. package/dist/resources/migrations/dir-safety.js +60 -2
  152. package/dist/resources/migrations/embedding-stamp.js +315 -49
  153. package/dist/resources/migrations/graph-heal.js +9 -2
  154. package/dist/resources/migrations/ledger.js +5 -2
  155. package/dist/resources/migrations/lock.js +867 -80
  156. package/dist/resources/migrations/progress.js +71 -10
  157. package/dist/resources/migrations/runner.js +212 -18
  158. package/dist/resources/migrations/state.js +36 -1
  159. package/dist/resources/migrations/status.js +2 -13
  160. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  161. package/dist/resources/migrations/types.js +26 -1
  162. package/dist/resources/migrations/visibility-backfill.js +111 -70
  163. package/dist/resources/oauth-discovery.js +0 -5
  164. package/dist/resources/object-body-guard.js +12 -5
  165. package/dist/resources/org-event-reserved.js +92 -0
  166. package/dist/resources/org-event-write-fault.js +19 -0
  167. package/dist/resources/owner-field-guard.js +1 -1
  168. package/dist/resources/owner-scoped-write-policy.js +65 -21
  169. package/dist/resources/owner-scoped-writes.js +37 -6
  170. package/dist/resources/path-id-rewrite.js +76 -0
  171. package/dist/resources/presence-internal.js +5 -5
  172. package/dist/resources/promotion-binding.js +43 -0
  173. package/dist/resources/promotion-stamp.js +124 -33
  174. package/dist/resources/protocol-context.js +189 -0
  175. package/dist/resources/record-type-kit.js +2 -4
  176. package/dist/resources/request-target.js +28 -1
  177. package/dist/resources/request-transaction.js +11 -1
  178. package/dist/resources/seed-reservation.js +1 -2
  179. package/dist/resources/semantic-retrieval-core.js +7 -6
  180. package/dist/resources/server-row-validation.js +71 -0
  181. package/dist/resources/skill-manifest.js +4 -3
  182. package/dist/resources/skill-version-write.js +384 -27
  183. package/dist/resources/skill-write-fault.js +6 -3
  184. package/dist/resources/skill-write-policy.js +2 -1
  185. package/dist/resources/soul-write-policy.js +26 -7
  186. package/dist/resources/table-helpers.js +1 -1
  187. package/dist/resources/table-subscription-policy.js +518 -85
  188. package/dist/resources/table-subscriptions.js +20 -7
  189. package/dist/resources/txn-pause-point.js +122 -5
  190. package/dist/resources/usage-recording.js +54 -46
  191. package/dist/resources/write-back.js +176 -11
  192. package/dist/resources/write-journal-context.js +5 -0
  193. package/dist/resources/write-journal.js +289 -0
  194. package/dist/src/lib/agent-id-rule.js +44 -2
  195. package/dist/src/lib/atomic-write.js +1 -1
  196. package/dist/src/lib/federation-retry-row.js +101 -0
  197. package/dist/src/lib/instruction-event-contract.js +17 -0
  198. package/dist/src/lib/memory-attributes.js +2 -0
  199. package/dist/src/lib/open-live-row.js +20 -0
  200. package/dist/src/lib/soul-scope-fields.js +26 -0
  201. package/dist/src/rem/promote-policy.js +3 -3
  202. package/dist/src/rem/scheduler.js +21 -4
  203. package/docs/access-control.md +18 -9
  204. package/docs/api-reference.md +126 -28
  205. package/docs/auth.md +40 -18
  206. package/docs/claude-code.md +3 -3
  207. package/docs/deploying-on-fabric.md +108 -0
  208. package/docs/deployment.md +17 -0
  209. package/docs/embedding-in-a-harper-app.md +16 -14
  210. package/docs/entity-vocabulary.md +3 -6
  211. package/docs/federation.md +29 -2
  212. package/docs/integrations.md +11 -11
  213. package/docs/mcp-clients.md +7 -5
  214. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  215. package/docs/notes/mcp-oauth-model2.md +6 -6
  216. package/docs/openclaw.md +1 -1
  217. package/docs/quickstart-fabric.md +2 -2
  218. package/docs/quickstart.md +3 -3
  219. package/docs/releasing.md +13 -13
  220. package/docs/rem.md +24 -3
  221. package/docs/secrets-and-keys.md +2 -2
  222. package/docs/standalone-local.md +29 -2
  223. package/docs/supply-chain-policy.md +28 -20
  224. package/docs/the-team.md +2 -2
  225. package/docs/upgrade.md +14 -0
  226. package/package.json +18 -11
  227. package/schemas/agent.graphql +3 -3
  228. package/schemas/federation.graphql +10 -7
  229. package/schemas/memory.graphql +7 -2
  230. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  231. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  232. package/dist/resources/soul-adk-guard.js +0 -68
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  import { Resource, databases } from "harper";
5
5
  import { allowVerified, resolveAgentAuth } from "./agent-auth.js";
6
+ import { subscribeInProcess } from "./table-subscription-policy.js";
6
7
  import { computeContentHash, findExistingMemoryByContentHash } from "./memory-feed-lib.js";
7
8
  import { FORBIDDEN, UNAUTH, stampAttribution } from "./record-type-kit.js";
8
9
  import { guardAuthorityFields, stripAuthorityFields } from "./authority-field-guard.js";
@@ -17,7 +18,7 @@ import { deletePointerRowViaTable } from "./host-pointer-adapter.js";
17
18
  import { stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
18
19
  import { buildProvenance } from "./provenance.js";
19
20
  import { redactMemoryWrite, redactSkillWrite } from "./memory-redaction.js";
20
- import { REDACTION_RULES, buildFromAllowlist, feedResponseFields, storageResult, suppliedMemoryFields } from "./memory-write-response.js";
21
+ import { REDACTION_RULES, WRITE_RESPONSE_WITHHELD, buildFromAllowlist, feedResponseFields, storageResult, suppliedMemoryFields } from "./memory-write-response.js";
21
22
  import { applyFederationBookkeeping, applyOriginatorInstanceId, resolveStoredRow } from "./originator-instance.js";
22
23
  import { resolveReadScope } from "./memory-read-scope.js";
23
24
  import { reservedSeedFeedWriteDenial, reservedSeedSubjectDenial, writeTargetIds } from "./seed-reservation.js";
@@ -26,6 +27,24 @@ import { WriteBackConflictError, writeBackCommittedRow } from "./write-back.js";
26
27
  import { withOwnedTransaction } from "./request-transaction.js";
27
28
  import { txnPausePoint } from "./txn-pause-point.js";
28
29
  import { stripInlinePointerFields } from "./host-source-visibility.js";
30
+ import { applyPromotionBinding } from "./promotion-binding.js";
31
+ import { markMemoryWriteOutcomeUnknown, memoryLockRefusal, memoryBusyResponse, memoryLockUnavailableResponse, withMemoryWriteLock, withMemoryWriteLockOnce, writeOutcomeUnknownResponse } from "./memory-write-lock.js";
32
+ /** The per-id Memory write-lock store (flair#2478). */
33
+ function memoryLockStore() {
34
+ return databases?.flair?.Memory?.primaryStore;
35
+ }
36
+ /** How many times a skill feed write re-resolves its live head and acquires the
37
+ * per-id locks with the new head included (flair#2927). */
38
+ const SKILL_HEAD_LOCK_ATTEMPTS = 3;
39
+ /** Suppress an absent or mismatched promotion binding on a fed event's row
40
+ * value (flair#2478 slice 2). Non-object values and events pass through. */
41
+ function promotionBoundEvent(event) {
42
+ const value = event?.value;
43
+ if (value == null || typeof value !== "object")
44
+ return event;
45
+ const bound = applyPromotionBinding(value);
46
+ return bound === value ? event : { ...event, value: bound };
47
+ }
29
48
  export class FeedMemories extends Resource {
30
49
  // Self-authorize via the Ed25519 agent verify (the auth reshape removes the
31
50
  // gate's admin elevation).
@@ -206,61 +225,141 @@ export class FeedMemories extends Resource {
206
225
  return seedLineageDenial;
207
226
  const addressedId = addressed ? String(addressed.id) : predecessor ? String(predecessor.id) : null;
208
227
  const captured = { row: null, closed: null };
209
- const outcome = await runSkillVersionWrite({
210
- ctx,
211
- subjectId,
212
- agentId,
213
- head: (shared) => resolveSkillHead(subjectId, addressedId, shared),
214
- plan: async (head, shared) => {
215
- const stale = await validateSkillSnapshots(addressed, predecessor, content.id ?? null, shared);
216
- if (stale)
217
- return stale;
218
- const denied = await authorizeSkillOwners(ctx, auth, [addressed, predecessor, head ?? content], shared);
219
- if (denied)
220
- return denied;
221
- if ((addressed || predecessor) && !head)
222
- return skillWriteConflict("skill_head_missing");
223
- if (predecessor && (!addressed || content.supersedes !== addressed.supersedes) && head?.id !== predecessor.id)
224
- return skillWriteConflict("skill_predecessor_stale");
225
- if (addressed && head?.id !== addressed.id)
226
- return skillWriteConflict("skill_target_stale");
227
- const successor = buildSkillSuccessorRow({
228
- auth,
229
- base: { ...content, agentId: head?.agentId ?? agentId }, predecessorRow: head, successorId, subjectId,
230
- supersedes: head ? String(head.id) : null, now,
228
+ // flair#2927: a skill-tagged feed write writes Memory rows too — the
229
+ // successor, the row it addresses and the row it closes — so it takes
230
+ // the same per-id Memory write lock (and marker check) as the ordinary
231
+ // write-back below. Locking the successor id as well keeps one rule
232
+ // for the branch: every Memory row this write writes is held.
233
+ // The live head is resolved before the acquisition and its id joins the
234
+ // lock set, because it is the row the write closes when the addressed id
235
+ // is absent. The addressed row and the predecessor are pre-lock reads
236
+ // too; validateSkillSnapshots makes both fresh under the locks. Under the
237
+ // locks the head is resolved again; a head that is not one of the held
238
+ // ids releases and retries with the new head. The write is refused
239
+ // skill_head_moved only if the resolved head stays outside the held set
240
+ // through the final attempt.
241
+ // One acquisition per attempt, taken before the version writer's
242
+ // instruction lock.
243
+ const baseLockIds = [successorId, addressedId, predecessor ? String(predecessor.id) : null]
244
+ .filter((id) => typeof id === "string" && id.length > 0);
245
+ const HEAD_MOVED = Symbol("skill-head-moved");
246
+ let locked;
247
+ let preLockDenial = null;
248
+ for (let attempt = 0; attempt < SKILL_HEAD_LOCK_ATTEMPTS; attempt++) {
249
+ const preHead = await resolveSkillHead(subjectId, addressedId, {});
250
+ const resolvedPause = txnPausePoint("skill-head-resolved");
251
+ if (resolvedPause)
252
+ await resolvedPause;
253
+ // flair#2927: a head or predecessor this request does not own is
254
+ // authorized before any lock or marker is checked on it, so a caller
255
+ // without a write grant gets the ownership refusal whether that row is
256
+ // free, held or marked; the plan re-checks authority under the locks.
257
+ const preDenied = await authorizeSkillOwners(ctx, auth, [preHead, predecessor], {});
258
+ if (preDenied) {
259
+ preLockDenial = preDenied;
260
+ break;
261
+ }
262
+ const attemptIds = preHead && !baseLockIds.includes(String(preHead.id))
263
+ ? [...baseLockIds, String(preHead.id)]
264
+ : [...baseLockIds];
265
+ const heldIds = new Set(attemptIds);
266
+ locked = await withMemoryWriteLock(memoryLockStore(), attemptIds, async () => {
267
+ const attemptedWriteIds = new Set();
268
+ let headMoved = false;
269
+ const outcome = await runSkillVersionWrite({
270
+ ctx,
271
+ subjectId,
272
+ agentId,
273
+ heldMemoryIds: attemptIds,
274
+ head: (shared) => resolveSkillHead(subjectId, addressedId, shared),
275
+ plan: async (head, shared) => {
276
+ if (head && !heldIds.has(String(head.id))) {
277
+ headMoved = true;
278
+ return skillWriteConflict("skill_head_moved");
279
+ }
280
+ const stale = await validateSkillSnapshots(addressed, predecessor, content.id ?? null, shared);
281
+ if (stale)
282
+ return stale;
283
+ const denied = await authorizeSkillOwners(ctx, auth, [addressed, predecessor, head ?? content], shared);
284
+ if (denied)
285
+ return denied;
286
+ if ((addressed || predecessor) && !head)
287
+ return skillWriteConflict("skill_head_missing");
288
+ if (predecessor && (!addressed || content.supersedes !== addressed.supersedes) && head?.id !== predecessor.id)
289
+ return skillWriteConflict("skill_predecessor_stale");
290
+ if (addressed && head?.id !== addressed.id)
291
+ return skillWriteConflict("skill_target_stale");
292
+ const successor = buildSkillSuccessorRow({
293
+ auth,
294
+ base: { ...content, agentId: head?.agentId ?? agentId }, predecessorRow: head, successorId, subjectId,
295
+ supersedes: head ? String(head.id) : null, now,
296
+ });
297
+ successor.provenance = buildProvenance(auth, successor.createdAt, content);
298
+ stripAuthorityFields(successor, "Memory");
299
+ await applyOriginatorInstanceId(successor, head);
300
+ applyFederationBookkeeping(successor, head);
301
+ captured.row = successor;
302
+ captured.closed = head;
303
+ const value = typeof successor.content === "string" ? successor.content : null;
304
+ const visibility = skillVersionVisibility(successor);
305
+ if (!head)
306
+ return { kind: "create", predecessor: null, successor, closePatch: {}, value, visibility, grantedClose: null };
307
+ // flair#2511: a grant-authorized cross-agent close of `head` stands on the "write" grant
308
+ // authorizeSkillOwners read above; the writer re-checks it after the
309
+ // close is staged.
310
+ return { kind: "update", predecessor: head, successor, closePatch: { skillSubjectId: subjectId, validTo: now, updatedAt: now }, value, visibility, grantedClose: grantedSkillClose(head, ctx, auth) };
311
+ },
312
+ hooks: {
313
+ ...defaultSkillHooks,
314
+ createSuccessor: (successor, shared) => {
315
+ attemptedWriteIds.add(String(successor.id));
316
+ return defaultSkillHooks.createSuccessor(successor, shared);
317
+ },
318
+ closePredecessor: (predecessor, patch, shared) => {
319
+ attemptedWriteIds.add(String(predecessor.id));
320
+ return defaultSkillHooks.closePredecessor(predecessor, patch, shared);
321
+ },
322
+ authorizeClose: (row, shared) => authorizeSkillOwners(ctx, auth, [row], shared),
323
+ pointer: async (shared) => {
324
+ if (captured.closed)
325
+ await deletePointerRowViaTable(String(captured.closed.id), shared);
326
+ return null;
327
+ },
328
+ },
231
329
  });
232
- successor.provenance = buildProvenance(auth, successor.createdAt, content);
233
- stripAuthorityFields(successor, "Memory");
234
- await applyOriginatorInstanceId(successor, head);
235
- applyFederationBookkeeping(successor, head);
236
- captured.row = successor;
237
- captured.closed = head;
238
- const value = typeof successor.content === "string" ? successor.content : null;
239
- const visibility = skillVersionVisibility(successor);
240
- if (!head)
241
- return { kind: "create", predecessor: null, successor, closePatch: {}, value, visibility, grantedClose: null };
242
- // flair#2511: a grant-authorized cross-agent close of `head` stands on the "write" grant
243
- // authorizeSkillOwners read above; the writer re-checks it after the
244
- // close is staged.
245
- return { kind: "update", predecessor: head, successor, closePatch: { skillSubjectId: subjectId, validTo: now, updatedAt: now }, value, visibility, grantedClose: grantedSkillClose(head, ctx, auth) };
246
- },
247
- hooks: {
248
- ...defaultSkillHooks,
249
- pointer: async (shared) => {
250
- if (captured.closed)
251
- await deletePointerRowViaTable(String(captured.closed.id), shared);
252
- return null;
253
- },
254
- },
255
- });
256
- if (!outcome.ok)
257
- return outcome.response;
258
- const written = captured.row;
259
- if (captured.closed)
260
- noteMemoryDelete(String(captured.closed.id));
261
- if (written)
262
- noteMemoryUpsert(written);
263
- return feedWriteResponse(written ?? { id: successorId, written: true, durability: "persistent" }, redactedValues, supplied);
330
+ if (!outcome.ok) {
331
+ if (headMoved)
332
+ return HEAD_MOVED;
333
+ // flair#2927: record the attempted ids outcome-unknown when storage
334
+ // withheld the write result, when the skill writer could not confirm
335
+ // its undo (`skill_update_compensation_failed`), or when the refusal
336
+ // body has no readable error code.
337
+ const code = await responseErrorCode(outcome.response);
338
+ if (code === null || code === WRITE_RESPONSE_WITHHELD || code === "skill_update_compensation_failed") {
339
+ for (const id of attemptedWriteIds)
340
+ markMemoryWriteOutcomeUnknown(id);
341
+ }
342
+ return { response: outcome.response };
343
+ }
344
+ const written = captured.row;
345
+ if (captured.closed)
346
+ noteMemoryDelete(String(captured.closed.id));
347
+ if (written)
348
+ noteMemoryUpsert(written);
349
+ return { response: feedWriteResponse(written ?? { id: successorId, written: true, durability: "persistent" }, redactedValues, supplied) };
350
+ }, { phase: "feed-skill-ingest" });
351
+ if (locked.kind !== "done" || locked.value !== HEAD_MOVED)
352
+ break;
353
+ }
354
+ if (preLockDenial)
355
+ return preLockDenial;
356
+ if (!locked)
357
+ return memoryLockUnavailableResponse();
358
+ if (locked.kind !== "done")
359
+ return memoryLockRefusal(locked, agentId);
360
+ if (locked.value === HEAD_MOVED)
361
+ return skillWriteConflict("skill_head_moved");
362
+ return locked.value.response;
264
363
  }
265
364
  const now = new Date().toISOString();
266
365
  const contentHash = computeContentHash(agentId, body);
@@ -308,88 +407,141 @@ export class FeedMemories extends Resource {
308
407
  // caller-supplied server-stamped field (instanceToken, provenance), then
309
408
  // PRESERVE the existing row's incarnation token, else generate one.
310
409
  stripServerStampedFields(record);
311
- let refusal;
312
- let outcome;
313
- const table = databases.flair.Memory;
314
- try {
315
- outcome = await writeBackCommittedRow({
316
- get: (id, shared) => table.get(id, shared),
317
- put: async (row, shared) => {
318
- normalizeEmptyEmbedding(row);
319
- const result = storageResult(await table.put(row, shared));
320
- if (result instanceof Response)
321
- refusal = result;
322
- },
323
- }, record.id, async (priorById) => {
324
- if (priorById && priorById.agentId !== agentId) {
325
- refusal = FORBIDDEN("forbidden: cannot write a feed memory owned by another agent");
326
- return { skip: true };
327
- }
328
- const written = { ...record };
329
- if (visibilityOmitted) {
330
- const stored = priorById?.visibility;
331
- if (stored === PRIVATE_VISIBILITY || stored === SHARED_VISIBILITY)
332
- written.visibility = stored;
333
- else if (durability === "ephemeral")
334
- written.visibility = PRIVATE_VISIBILITY;
335
- else
336
- delete written.visibility;
337
- const tierError = assertVisibilityAllowedForDurability(durability, written.visibility);
338
- if (tierError) {
339
- refusal = Response.json({ error: "invalid_visibility_for_durability", message: tierError }, { status: 400 });
410
+ // flair#2478 slice 3b: the ordinary (non-skill) write-back runs under the
411
+ // id's per-id Memory write lock, so its read, decision and commit sit on one
412
+ // committed basis. The feed write is a foreground client write: a held key
413
+ // waits its budget and can answer `503 memory_busy`; a marked id answers
414
+ // `503 write_outcome_unknown` at once; a store with no lock answers
415
+ // `503 memory_lock_unavailable`. The write-back confirms its committed row
416
+ // as before; when storage withholds the write result (flair#2857), or its
417
+ // read-back of that row fails or does not show the write (409
418
+ // `feed_write_unconfirmed`), it records the id outcome-unknown before the
419
+ // lock is released (flair#2806). An omitted id is generated; a
420
+ // caller-supplied id can contend.
421
+ const locked = await withMemoryWriteLock(memoryLockStore(), [String(record.id)], async () => {
422
+ let refusal;
423
+ let outcome;
424
+ const table = databases.flair.Memory;
425
+ try {
426
+ outcome = await writeBackCommittedRow({
427
+ get: (id, shared) => table.get(id, shared),
428
+ put: async (row, shared) => {
429
+ normalizeEmptyEmbedding(row);
430
+ const result = storageResult(await table.put(row, shared));
431
+ if (result instanceof Response) {
432
+ // flair#2857: storage withheld this write's result (a Response
433
+ // instead of the row), so whether the row holds the write is
434
+ // unconfirmed. Record the id's outcome-unknown marker inside
435
+ // its lock, as the failed or mismatching read-back below does.
436
+ markMemoryWriteOutcomeUnknown(record.id);
437
+ refusal = result;
438
+ }
439
+ },
440
+ }, record.id, async (priorById) => {
441
+ if (priorById && priorById.agentId !== agentId) {
442
+ refusal = FORBIDDEN("forbidden: cannot write a feed memory owned by another agent");
340
443
  return { skip: true };
341
444
  }
445
+ const written = { ...record };
446
+ if (visibilityOmitted) {
447
+ const stored = priorById?.visibility;
448
+ if (stored === PRIVATE_VISIBILITY || stored === SHARED_VISIBILITY)
449
+ written.visibility = stored;
450
+ else if (durability === "ephemeral")
451
+ written.visibility = PRIVATE_VISIBILITY;
452
+ else
453
+ delete written.visibility;
454
+ const tierError = assertVisibilityAllowedForDurability(durability, written.visibility);
455
+ if (tierError) {
456
+ refusal = Response.json({ error: "invalid_visibility_for_durability", message: tierError }, { status: 400 });
457
+ return { skip: true };
458
+ }
459
+ }
460
+ written.instanceToken = priorById?.instanceToken ?? randomUUID();
461
+ // Feed ingest writes the INCOMING authored record as a full row (a
462
+ // semantic re-authoring on POST /FeedMemories): the stored row is
463
+ // REPLACED, not patched, and provenance is re-stamped from the resolved
464
+ // (trusted) identity and ONE server clock read (inside buildProvenance)
465
+ // rather than carrying the stored blob forward — a legacy row whose
466
+ // `verified.timestamp` came from a client `createdAt` must not keep
467
+ // presenting that value after a new write (flair#1960 r2). The feed
468
+ // body's own `createdAt` is recorded only as the CLAIM
469
+ // `provenance.claimed.createdAt`, never as a verified timestamp. The
470
+ // values this re-authoring derives from the stored row (the incarnation
471
+ // token, an omitted visibility, a carried expiry, the originator-instance and
472
+ // federation bookkeeping) are carried across; it never writes back a
473
+ // stale echo of the content it read, and it is a foreground client
474
+ // write, so the field-only rule for background stamps (flair#2470) does
475
+ // not apply to it.
476
+ written.provenance = buildProvenance(auth, written.createdAt, content);
477
+ // flair#1965 r2: this raw table write REPLACES the row, bypassing the
478
+ // Memory resource's write methods, so the create/update rule is
479
+ // applied here explicitly: a CREATE (no stored row) stamps this
480
+ // instance's own id and ignores any body value; an UPDATE keeps the
481
+ // STORED value (a body value neither replaces nor clears it). The
482
+ // receiver-side federation bookkeeping (`_originatorInstanceId` et al.)
483
+ // is likewise unsettable from a body — it stands as stored, or is
484
+ // dropped on a create. See resources/originator-instance.ts.
485
+ await applyOriginatorInstanceId(written, priorById);
486
+ applyFederationBookkeeping(written, priorById);
487
+ const expiryError = stampEphemeralExpiry(written, priorById);
488
+ if (expiryError) {
489
+ refusal = Response.json({ error: "invalid_expiry", message: expiryError }, { status: 400 });
490
+ return { skip: true };
491
+ }
492
+ return { idempotent: false, commitMarkerField: "writeBackWriteId", write: written };
493
+ }, {
494
+ ctx, label: "MemoryFeed.ingest",
495
+ pausePre: () => txnPausePoint("feed-ingest-pre"),
496
+ pausePoint: () => txnPausePoint("feed-ingest"),
497
+ pauseAfterStage: () => txnPausePoint("feed-ingest-staged"),
498
+ pauseBeforeCommit: () => txnPausePoint("feed-ingest-commit"),
499
+ // Test-only: after the commit, before the read-back.
500
+ pauseBeforeVerify: () => txnPausePoint("feed-ingest-verify"),
501
+ expectedRow: existingRecord,
502
+ });
503
+ }
504
+ catch (err) {
505
+ if (refusal)
506
+ return { response: refusal };
507
+ if (err instanceof WriteBackConflictError) {
508
+ if (err.outcome === "conflict")
509
+ return { response: feedTargetChanged(record.id) };
510
+ // flair#2806: the commit resolved and the read-back does not show the
511
+ // write, so the row may hold it. Record the id's outcome-unknown
512
+ // marker here, inside the id's lock, as the owner PUT and PATCH do
513
+ // (writeOutcomeUnknownFor), so a later write to the id answers
514
+ // 503 write_outcome_unknown until restart.
515
+ markMemoryWriteOutcomeUnknown(record.id);
516
+ return {
517
+ response: Response.json({
518
+ error: "feed_write_unconfirmed", outcome: err.outcome, message: err.message,
519
+ }, { status: 409 }),
520
+ };
342
521
  }
343
- written.instanceToken = priorById?.instanceToken ?? randomUUID();
344
- // Feed ingest writes the INCOMING authored record as a full row (a
345
- // semantic re-authoring on POST /FeedMemories): the stored row is
346
- // REPLACED, not patched, and provenance is re-stamped from the resolved
347
- // (trusted) identity and ONE server clock read (inside buildProvenance)
348
- // rather than carrying the stored blob forward — a legacy row whose
349
- // `verified.timestamp` came from a client `createdAt` must not keep
350
- // presenting that value after a new write (flair#1960 r2). The feed
351
- // body's own `createdAt` is recorded only as the CLAIM
352
- // `provenance.claimed.createdAt`, never as a verified timestamp. The
353
- // values this re-authoring derives from the stored row (the incarnation
354
- // token, an omitted visibility, a carried expiry, the originator-instance and
355
- // federation bookkeeping) are carried across; it never writes back a
356
- // stale echo of the content it read, and it is a foreground client
357
- // write, so the field-only rule for background stamps (flair#2470) does
358
- // not apply to it.
359
- written.provenance = buildProvenance(auth, written.createdAt, content);
360
- // flair#1965 r2: this raw table write REPLACES the row, bypassing the
361
- // Memory resource's write methods, so the create/update rule is
362
- // applied here explicitly: a CREATE (no stored row) stamps this
363
- // instance's own id and ignores any body value; an UPDATE keeps the
364
- // STORED value (a body value neither replaces nor clears it). The
365
- // receiver-side federation bookkeeping (`_originatorInstanceId` et al.)
366
- // is likewise unsettable from a body — it stands as stored, or is
367
- // dropped on a create. See resources/originator-instance.ts.
368
- await applyOriginatorInstanceId(written, priorById);
369
- applyFederationBookkeeping(written, priorById);
370
- const expiryError = stampEphemeralExpiry(written, priorById);
371
- if (expiryError) {
372
- refusal = Response.json({ error: "invalid_expiry", message: expiryError }, { status: 400 });
373
- return { skip: true };
374
- }
375
- return { write: written };
376
- }, { ctx, label: "MemoryFeed.ingest", pausePre: () => txnPausePoint("feed-ingest-pre"), pausePoint: () => txnPausePoint("feed-ingest"), expectedRow: existingRecord });
377
- }
378
- catch (err) {
522
+ throw err;
523
+ }
379
524
  if (refusal)
380
- return refusal;
381
- // The target row was replaced, or kept changing: nothing was written.
382
- if (err instanceof WriteBackConflictError)
383
- return feedTargetChanged(record.id);
384
- throw err;
385
- }
386
- if (refusal)
387
- return refusal;
388
- if ("skip" in outcome)
389
- return feedTargetChanged(record.id);
390
- if (!("write" in outcome))
391
- throw new Error("MemoryFeed.ingest: expected a full-record write plan");
392
- const written = outcome.write;
525
+ return { response: refusal };
526
+ if ("skip" in outcome)
527
+ return { response: feedTargetChanged(record.id) };
528
+ if (!("write" in outcome))
529
+ throw new Error("MemoryFeed.ingest: expected a full-record write plan");
530
+ // Test-only: the write committed and the lock is still held.
531
+ const committed = txnPausePoint("feed-ingest-committed");
532
+ if (committed)
533
+ await committed;
534
+ return { written: outcome.write };
535
+ }, { phase: "feed-ingest" });
536
+ if (locked.kind === "busy")
537
+ return memoryBusyResponse(agentId);
538
+ if (locked.kind === "unknown")
539
+ return writeOutcomeUnknownResponse();
540
+ if (locked.kind === "unavailable")
541
+ return memoryLockUnavailableResponse();
542
+ if ("response" in locked.value)
543
+ return locked.value.response;
544
+ const written = locked.value.written;
393
545
  // flair#1357 — raw-table write: hook it explicitly (see bm25-index-service).
394
546
  noteMemoryUpsert(written);
395
547
  return feedWriteResponse(written, redactedValues, supplied);
@@ -416,7 +568,7 @@ export class FeedMemories extends Resource {
416
568
  * Two layers decide what a non-admin subscriber receives:
417
569
  *
418
570
  * 1. Harper's synchronous `SubscriptionRequest.rowFilter`, set to the
419
- * predicate. In the pinned Harper (5.2.8) the filter is evaluated on the
571
+ * predicate. In Harper 5.2.8 the filter is evaluated on the
420
572
  * full stored row for the rows replayed when the subscription opens, for
421
573
  * every live change (an update is re-read from the primary store and
422
574
  * delivered as a full-row `put`) and for reload re-deliveries; a history
@@ -445,12 +597,12 @@ export class FeedMemories extends Resource {
445
597
  throw Object.assign(new Error("authentication required"), { statusCode: 401 });
446
598
  }
447
599
  if (auth.kind === "internal" || auth.isAdmin) {
448
- const subscription = await databases.flair.Memory.subscribe(target);
600
+ const subscription = await subscribeInProcess(databases.flair.Memory, target);
449
601
  if (!incomingMessages) {
450
602
  return subscription;
451
603
  }
452
604
  for await (const event of subscription) {
453
- yield event;
605
+ yield promotionBoundEvent(event);
454
606
  }
455
607
  return;
456
608
  }
@@ -460,7 +612,7 @@ export class FeedMemories extends Resource {
460
612
  // Harper's own Resource.connect() makes.
461
613
  const callerRequest = this.constructor.loadAsInstance === false ? target : incomingMessages;
462
614
  const request = scopedSubscriptionRequest(callerRequest, (record) => scope.isAllowed(record));
463
- const subscription = await databases.flair.Memory.subscribe(request);
615
+ const subscription = await subscribeInProcess(databases.flair.Memory, request);
464
616
  const readStored = (id) => databases.flair.Memory.get(id);
465
617
  const replaysHistory = request.startTime !== undefined || request.previousCount !== undefined;
466
618
  for await (const event of subscription) {
@@ -468,7 +620,7 @@ export class FeedMemories extends Resource {
468
620
  continue;
469
621
  if (replaysHistory && !(await storedRowReadable(event?.id, auth.agentId, scope.isAllowed, readStored)))
470
622
  continue;
471
- yield event;
623
+ yield promotionBoundEvent(event);
472
624
  }
473
625
  }
474
626
  }
@@ -574,12 +726,11 @@ export const FEED_DEDUP_TARGET_CHANGED_ERROR = "feed_dedup_target_changed";
574
726
  /** Attempts of the dedup expiry repair before it gives up on a row that keeps changing. */
575
727
  const FEED_DEDUP_REPAIR_ATTEMPTS = 3;
576
728
  export const FEED_TARGET_CHANGED_ERROR = "feed_target_changed";
577
- /** A retryable 409: the row a feed write targets changed during the request,
578
- * so nothing was written. */
579
729
  function feedTargetChanged(id) {
580
730
  return Response.json({
581
731
  error: FEED_TARGET_CHANGED_ERROR,
582
- message: `the stored row ${JSON.stringify(id)} this write targets changed during the request; retry the write`,
732
+ outcome: "conflict",
733
+ message: `the stored row ${JSON.stringify(id)} this write targets changed during the request; write not applied; retry the write`,
583
734
  }, { status: 409 });
584
735
  }
585
736
  function feedDedupTargetChanged(id) {
@@ -593,6 +744,17 @@ function isDedupMatch(row, match) {
593
744
  return row != null && typeof row === "object" && String(row.id) === String(match.id) &&
594
745
  row.agentId === match.agentId && row.contentHash === match.contentHash;
595
746
  }
747
+ /** The `error` code of a refused write's JSON body, or null (never a pass:
748
+ * the caller treats an unreadable body as an unknown outcome). */
749
+ async function responseErrorCode(response) {
750
+ try {
751
+ const body = await response.clone().json();
752
+ return typeof body?.error === "string" ? body.error : null;
753
+ }
754
+ catch {
755
+ return null;
756
+ }
757
+ }
596
758
  function feedWriteResponse(result, redactedValues, supplied) {
597
759
  const response = feedResponseFields(result, supplied);
598
760
  if (response instanceof Response || redactedValues <= 0)
@@ -611,15 +773,33 @@ function feedWriteResponse(result, redactedValues, supplied) {
611
773
  * committed read must equal the transaction's read before the write, else the
612
774
  * repair starts over (FEED_DEDUP_REPAIR_ATTEMPTS attempts, then the 409). A
613
775
  * change committed after that read and before the commit follows Harper's
614
- * timestamp order. After the commit, an owned read must show the match with
615
- * the written expiry (else the 409); that row is returned. Returned rows carry
616
- * no inline pointer fields (stripInlinePointerFields).
776
+ * timestamp order. A storage result that withholds the update's result records
777
+ * the id outcome-unknown and returns that result (500 write_response_withheld)
778
+ * (flair#2857). After the commit, an owned read that shows the match with the
779
+ * written expiry returns that row; a read that does not show it is refused
780
+ * (409 FEED_DEDUP_TARGET_CHANGED_ERROR), and a read that fails rethrows, so the
781
+ * request answers 500. Returned rows carry no inline pointer fields
782
+ * (stripInlinePointerFields).
617
783
  */
618
784
  async function repairDeduplicatedExpiry(ctx, match) {
619
785
  const id = String(match.id);
620
786
  const idDenial = reservedSeedFeedWriteDenial("Memory", [id]) ?? refuseContentSuffixId([id]);
621
787
  if (idDenial)
622
788
  return idDenial;
789
+ // flair#2478 slice 3b: the repair is an automatic writer. It takes the id's
790
+ // per-id Memory write lock once and without waiting; a held id, an
791
+ // outcome-unknown marker or a store with no lock skips the repair and
792
+ // reports it, and returns the matched, unrepaired row with its inline
793
+ // pointer fields removed, from which the caller builds the normal
794
+ // allowlisted feed response. A later feed write repairs it only if the row
795
+ // still matches and still lacks an expiry.
796
+ const locked = await withMemoryWriteLockOnce(memoryLockStore(), [id], () => repairDeduplicatedExpiryLocked(ctx, match, id), { phase: "feed-dedup-repair" });
797
+ if (locked.kind === "done")
798
+ return locked.value;
799
+ console.warn("[MemoryFeed] dedup expiry repair skipped: %s (id %s)", locked.kind, id);
800
+ return stripInlinePointerFields(match);
801
+ }
802
+ async function repairDeduplicatedExpiryLocked(ctx, match, id) {
623
803
  for (let attempt = 1; attempt <= FEED_DEDUP_REPAIR_ATTEMPTS; attempt++) {
624
804
  const outcome = await withOwnedTransaction(ctx, async (c) => {
625
805
  const stored = await databases.flair.Memory.get(id, c);
@@ -635,6 +815,11 @@ async function repairDeduplicatedExpiry(ctx, match) {
635
815
  const committed = await databases.flair.Memory.get(id, {});
636
816
  if (!isDeepStrictEqual(committed, stored))
637
817
  return { kind: "retry" };
818
+ // Test-only: the last confirmation passed and the transaction has not
819
+ // committed yet.
820
+ const commitPoint = txnPausePoint("feed-dedup-repair-commit");
821
+ if (commitPoint)
822
+ await commitPoint;
638
823
  const row = { ...stored };
639
824
  // A stored null is "no expiry": drop it so the shared rule stamps a fresh
640
825
  // tier TTL rather than refusing the null as malformed.
@@ -645,8 +830,18 @@ async function repairDeduplicatedExpiry(ctx, match) {
645
830
  // Only `expiresAt`: an incremental update, never a
646
831
  // full-row put of the row read above (flair#2470).
647
832
  const result = storageResult(await databases.flair.Memory.update(id, { expiresAt: row.expiresAt }, c));
648
- if (result instanceof Response)
833
+ if (result instanceof Response) {
834
+ // flair#2857: storage withheld the update's result (a Response instead
835
+ // of the row), so whether the row holds the expiry is unconfirmed.
836
+ // Record the id's outcome-unknown marker inside its lock, as the
837
+ // confirmation branches below do.
838
+ markMemoryWriteOutcomeUnknown(id);
649
839
  return { kind: "withheld", response: result };
840
+ }
841
+ // Test-only: the update is staged and the lock is still held.
842
+ const staged = txnPausePoint("feed-dedup-repair-staged");
843
+ if (staged)
844
+ await staged;
650
845
  return { kind: "written", row };
651
846
  });
652
847
  if (outcome.kind === "withheld")
@@ -657,9 +852,27 @@ async function repairDeduplicatedExpiry(ctx, match) {
657
852
  return feedDedupTargetChanged(id);
658
853
  if (outcome.kind === "current")
659
854
  return stripInlinePointerFields(outcome.row);
660
- const confirmed = await withOwnedTransaction(ctx, async (c) => databases.flair.Memory.get(id, c));
661
- if (!isDedupMatch(confirmed, match) || confirmed.expiresAt !== outcome.row.expiresAt)
855
+ // Test-only: the update committed and the lock is still held.
856
+ const committedPoint = txnPausePoint("feed-dedup-repair-committed");
857
+ if (committedPoint)
858
+ await committedPoint;
859
+ let confirmed;
860
+ try {
861
+ confirmed = await withOwnedTransaction(ctx, async (c) => databases.flair.Memory.get(id, c));
862
+ }
863
+ catch (err) {
864
+ // flair#2806: the update committed and this confirmation read failed, so
865
+ // the row may hold the expiry. Record the id's outcome-unknown marker
866
+ // inside the lock, as the ordinary feed write-back and the owner writes do.
867
+ markMemoryWriteOutcomeUnknown(id);
868
+ throw err;
869
+ }
870
+ if (!isDedupMatch(confirmed, match) || confirmed.expiresAt !== outcome.row.expiresAt) {
871
+ // flair#2806: the update committed and this read does not show it on the
872
+ // matched row. Record the marker inside the lock, as for a failed read.
873
+ markMemoryWriteOutcomeUnknown(id);
662
874
  return feedDedupTargetChanged(id);
875
+ }
663
876
  return stripInlinePointerFields(confirmed);
664
877
  }
665
878
  return feedDedupTargetChanged(id);