@tpsdev-ai/flair 0.59.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 (359) hide show
  1. package/README.md +10 -10
  2. package/SECURITY.md +49 -5
  3. package/config.yaml +23 -12
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/execute.js +1 -0
  6. package/dist/bridges/runtime/import-runner.js +12 -0
  7. package/dist/bridges/runtime/load-plugin.js +42 -13
  8. package/dist/bridges/runtime/yaml-loader.js +4 -2
  9. package/dist/bridges/types.js +1 -0
  10. package/dist/build-info.json +3 -3
  11. package/dist/cli.js +1054 -367
  12. package/dist/commands/agent.js +233 -90
  13. package/dist/commands/attention.js +4 -3
  14. package/dist/commands/backup-approval.js +218 -0
  15. package/dist/commands/backup.js +211 -39
  16. package/dist/commands/bootstrap.js +3 -1
  17. package/dist/commands/bridge.js +172 -119
  18. package/dist/commands/deploy.js +71 -8
  19. package/dist/commands/doctor.js +711 -146
  20. package/dist/commands/export.js +57 -23
  21. package/dist/commands/federation.js +787 -82
  22. package/dist/commands/grant.js +5 -6
  23. package/dist/commands/help.js +25 -0
  24. package/dist/commands/hook.js +155 -2
  25. package/dist/commands/idp.js +27 -19
  26. package/dist/commands/import.js +136 -20
  27. package/dist/commands/init.js +469 -200
  28. package/dist/commands/integrity.js +387 -0
  29. package/dist/commands/keys.js +247 -58
  30. package/dist/commands/mcp.js +108 -52
  31. package/dist/commands/memory.js +203 -35
  32. package/dist/commands/migrate-harness-memory.js +3 -2
  33. package/dist/commands/orgevent.js +51 -47
  34. package/dist/commands/presence.js +4 -3
  35. package/dist/commands/principal.js +428 -62
  36. package/dist/commands/quality.js +13 -1
  37. package/dist/commands/reembed.js +141 -17
  38. package/dist/commands/relationship.js +2 -1
  39. package/dist/commands/rem.js +537 -80
  40. package/dist/commands/restore.js +413 -65
  41. package/dist/commands/search.js +6 -4
  42. package/dist/commands/service.js +235 -40
  43. package/dist/commands/soul.js +4 -9
  44. package/dist/commands/status.js +94 -38
  45. package/dist/commands/test.js +7 -3
  46. package/dist/commands/upgrade.js +77 -23
  47. package/dist/commands/workspace.js +13 -11
  48. package/dist/component-env.js +31 -41
  49. package/dist/deploy.js +136 -4
  50. package/dist/doctor-client.js +534 -92
  51. package/dist/engine-version-contract.js +1 -0
  52. package/dist/engine-version.js +23 -3
  53. package/dist/fabric-upgrade.js +12 -2
  54. package/dist/federation/presence-send.js +139 -0
  55. package/dist/federation-verify.js +273 -180
  56. package/dist/hook-install.js +670 -6
  57. package/dist/install/clients.js +171 -35
  58. package/dist/keystore.js +72 -0
  59. package/dist/lib/action-recall-runtime.js +328 -0
  60. package/dist/lib/agent-home-fields.js +132 -0
  61. package/dist/lib/agent-home.js +427 -0
  62. package/dist/lib/agent-id-rule.js +88 -0
  63. package/dist/lib/agent-roster.js +33 -0
  64. package/dist/lib/atomic-write.js +1 -1
  65. package/dist/lib/auth-resolve.js +1069 -60
  66. package/dist/lib/backup-approval-store.js +612 -0
  67. package/dist/lib/backup-artifact.js +343 -0
  68. package/dist/lib/capture-runtime.js +124 -0
  69. package/dist/lib/config-critical-section.js +212 -25
  70. package/dist/lib/connect-phase.js +33 -0
  71. package/dist/lib/credential-status-rule.js +78 -0
  72. package/dist/lib/daemon-liveness.js +43 -11
  73. package/dist/lib/doctor-run.js +75 -37
  74. package/dist/lib/durability-copy.js +10 -0
  75. package/dist/lib/embedding-space-doctor.js +75 -0
  76. package/dist/lib/federation-pair-access.js +4 -0
  77. package/dist/lib/federation-retry-queue.js +283 -0
  78. package/dist/lib/federation-retry-row.js +101 -0
  79. package/dist/lib/flair-agent-role.js +4 -0
  80. package/dist/lib/hub-url.js +12 -0
  81. package/dist/lib/init-admin-pass.js +88 -12
  82. package/dist/lib/init-listener-environ.js +1 -2
  83. package/dist/lib/init-occupied-listener.js +15 -111
  84. package/dist/lib/init-spawn-attribution.js +73 -0
  85. package/dist/lib/init-tcp-probe.js +33 -0
  86. package/dist/lib/instance-identity-row.js +20 -0
  87. package/dist/lib/instruction-event-contract.js +17 -0
  88. package/dist/lib/instruction-event-doctor.js +102 -0
  89. package/dist/lib/launchd-management.js +38 -3
  90. package/dist/lib/listener-table.js +268 -0
  91. package/dist/lib/local-delete-instance.js +27 -0
  92. package/dist/lib/local-instance-pair.js +256 -0
  93. package/dist/lib/mcp-enable.js +1182 -341
  94. package/dist/lib/mcp-oauth-env-core.js +133 -0
  95. package/dist/lib/mcp-oauth-env.js +125 -0
  96. package/dist/lib/mcp-spec.js +17 -1
  97. package/dist/lib/memory-attributes.js +4 -0
  98. package/dist/lib/memory-id-policy.js +46 -0
  99. package/dist/lib/memory-integrity.js +309 -0
  100. package/dist/lib/memory-provider-timeout.js +33 -0
  101. package/dist/lib/memory-purge-response.js +20 -0
  102. package/dist/lib/mqtt-config.js +132 -0
  103. package/dist/lib/mqtt-listener-doctor.js +104 -0
  104. package/dist/lib/open-live-row.js +20 -0
  105. package/dist/lib/ops-table-count.js +25 -0
  106. package/dist/lib/ops-url.js +52 -0
  107. package/dist/lib/owned-pins.js +67 -10
  108. package/dist/lib/peer-status.js +27 -0
  109. package/dist/lib/principal-status.js +29 -0
  110. package/dist/lib/process-start-time.js +76 -12
  111. package/dist/lib/promotion-content-hash.js +20 -0
  112. package/dist/lib/proto-safe-record.js +42 -0
  113. package/dist/lib/record-id-path.js +25 -0
  114. package/dist/lib/reembed-server-support.js +66 -0
  115. package/dist/lib/restore-archive.js +760 -0
  116. package/dist/lib/restore-verify.js +104 -0
  117. package/dist/lib/scheduler-platform.js +10 -6
  118. package/dist/lib/secret-keys.js +25 -0
  119. package/dist/lib/secrets-push.js +50 -22
  120. package/dist/lib/skill-assignment-preflight.js +159 -0
  121. package/dist/lib/skill-seed-pending.js +24 -0
  122. package/dist/lib/skill-seed.js +448 -0
  123. package/dist/lib/skill-tombstone-doctor.js +133 -0
  124. package/dist/lib/soul-scope-fields.js +26 -0
  125. package/dist/lib/stop-start-recovery.js +54 -0
  126. package/dist/lib/uninstall-purge.js +266 -11
  127. package/dist/lib/upgrade-prior-liveness.js +2 -1
  128. package/dist/lib/using-flair-skill.js +87 -0
  129. package/dist/mcp-client-assertion.js +114 -14
  130. package/dist/memory-id-checkpoint.js +347 -0
  131. package/dist/memory-node-compare.js +207 -0
  132. package/dist/mqtt-off-deploy.js +550 -0
  133. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  134. package/dist/rem/promote-policy.js +3 -3
  135. package/dist/rem/restore.js +303 -26
  136. package/dist/rem/runner.js +317 -96
  137. package/dist/rem/scheduler.js +21 -4
  138. package/dist/resources/A2AAdapter.js +131 -178
  139. package/dist/resources/AdminMemory.js +2 -0
  140. package/dist/resources/AdminMemoryCandidates.js +116 -0
  141. package/dist/resources/Agent.js +463 -33
  142. package/dist/resources/AgentCard.js +4 -0
  143. package/dist/resources/AgentKeyRegister.js +248 -0
  144. package/dist/resources/AgentKeyRegistration.js +28 -0
  145. package/dist/resources/AgentReadPosition.js +7 -0
  146. package/dist/resources/AgentSeed.js +238 -107
  147. package/dist/resources/AutoPromoteCandidates.js +413 -78
  148. package/dist/resources/Credential.js +183 -10
  149. package/dist/resources/Federation.js +915 -145
  150. package/dist/resources/FederationRetry.js +140 -0
  151. package/dist/resources/InstructionVersion.js +220 -0
  152. package/dist/resources/Integration.js +300 -25
  153. package/dist/resources/MCPClientMetadata.js +6 -3
  154. package/dist/resources/Memory.js +3300 -758
  155. package/dist/resources/MemoryArchive.js +171 -53
  156. package/dist/resources/MemoryBootstrap.js +122 -61
  157. package/dist/resources/MemoryCandidate.js +37 -3
  158. package/dist/resources/MemoryConsolidate.js +2 -2
  159. package/dist/resources/MemoryDedupStats.js +30 -1
  160. package/dist/resources/MemoryFeed.js +545 -50
  161. package/dist/resources/MemoryGrant.js +21 -1
  162. package/dist/resources/MemoryMaintenance.js +368 -46
  163. package/dist/resources/MemoryPurge.js +348 -0
  164. package/dist/resources/MemoryReflect.js +71 -12
  165. package/dist/resources/MemoryReindex.js +111 -17
  166. package/dist/resources/Message.js +16 -5
  167. package/dist/resources/OAuth.js +342 -48
  168. package/dist/resources/OAuthClient.js +1 -1
  169. package/dist/resources/OrgEvent.js +405 -19
  170. package/dist/resources/OrgEventCatchup.js +7 -0
  171. package/dist/resources/OrgEventMaintenance.js +48 -10
  172. package/dist/resources/PairingToken.js +1 -1
  173. package/dist/resources/Presence.js +166 -51
  174. package/dist/resources/PromoteMemoryCandidate.js +24 -7
  175. package/dist/resources/RecordUsage.js +2 -4
  176. package/dist/resources/Relationship.js +23 -0
  177. package/dist/resources/SemanticSearch.js +63 -32
  178. package/dist/resources/Soul.js +191 -76
  179. package/dist/resources/SoulFeed.js +2 -1
  180. package/dist/resources/TeamDirectory.js +35 -0
  181. package/dist/resources/WorkspaceLatest.js +4 -0
  182. package/dist/resources/WorkspaceState.js +21 -1
  183. package/dist/resources/XAA.js +207 -63
  184. package/dist/resources/a2a-stream.js +313 -0
  185. package/dist/resources/a2a-url.js +4 -5
  186. package/dist/resources/agent-admin.js +10 -1
  187. package/dist/resources/agent-auth.js +138 -83
  188. package/dist/resources/agent-read-position-lib.js +4 -1
  189. package/dist/resources/agent-status-guard.js +9 -7
  190. package/dist/resources/auth-middleware.js +534 -171
  191. package/dist/resources/authority-field-guard.js +9 -11
  192. package/dist/resources/auto-promote-lib.js +8 -5
  193. package/dist/resources/basic-auth-header.js +21 -0
  194. package/dist/resources/bm25-index-service.js +4 -5
  195. package/dist/resources/dedup-cluster.js +6 -1
  196. package/dist/resources/ed25519-auth.js +1 -1
  197. package/dist/resources/embedding-space-guard.js +366 -72
  198. package/dist/resources/embeddings-provider.js +25 -0
  199. package/dist/resources/engine-version-stamp-boot.js +53 -0
  200. package/dist/resources/federation-classify.js +161 -0
  201. package/dist/resources/federation-crypto.js +5 -5
  202. package/dist/resources/federation-retry-lib.js +60 -0
  203. package/dist/resources/grant-visibility.js +135 -0
  204. package/dist/resources/harper-routing.js +83 -0
  205. package/dist/resources/health.js +163 -22
  206. package/dist/resources/host-pointer/registry.js +29 -0
  207. package/dist/resources/host-pointer-adapter.js +1 -0
  208. package/dist/resources/host-source-citation.js +49 -0
  209. package/dist/resources/host-source-visibility.js +7 -6
  210. package/dist/resources/in-process.js +24 -22
  211. package/dist/resources/instance-create-lock.js +17 -0
  212. package/dist/resources/instance-identity.js +23 -0
  213. package/dist/resources/instruction-version-record.js +587 -0
  214. package/dist/resources/internal-authority.js +13 -0
  215. package/dist/resources/key-lock.js +3 -3
  216. package/dist/resources/mcp-handler.js +141 -19
  217. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  218. package/dist/resources/mcp-oauth-flag.js +12 -14
  219. package/dist/resources/mcp-oauth.js +450 -56
  220. package/dist/resources/mcp-tool-arguments.js +4 -6
  221. package/dist/resources/mcp-tools.js +187 -40
  222. package/dist/resources/memory-bootstrap-lib.js +5 -15
  223. package/dist/resources/memory-declared-attributes.js +4 -1
  224. package/dist/resources/memory-deletion-history.js +55 -0
  225. package/dist/resources/memory-durability.js +54 -0
  226. package/dist/resources/memory-embed-hash.js +144 -0
  227. package/dist/resources/memory-embedding-value.js +8 -0
  228. package/dist/resources/memory-host-source.js +32 -7
  229. package/dist/resources/memory-id-guard.js +75 -0
  230. package/dist/resources/memory-redaction.js +236 -0
  231. package/dist/resources/memory-reflect-lib.js +1 -1
  232. package/dist/resources/memory-supplied-vector.js +72 -0
  233. package/dist/resources/memory-write-lock.js +489 -0
  234. package/dist/resources/memory-write-response.js +139 -0
  235. package/dist/resources/memory-write-transaction.js +243 -0
  236. package/dist/resources/migration-boot.js +17 -12
  237. package/dist/resources/migrations/boot-progress.js +25 -0
  238. package/dist/resources/migrations/data-dir.js +90 -19
  239. package/dist/resources/migrations/dir-safety.js +61 -3
  240. package/dist/resources/migrations/embedding-stamp.js +462 -82
  241. package/dist/resources/migrations/export.js +1 -0
  242. package/dist/resources/migrations/graph-heal.js +27 -27
  243. package/dist/resources/migrations/ledger.js +5 -2
  244. package/dist/resources/migrations/lock.js +870 -77
  245. package/dist/resources/migrations/progress.js +71 -10
  246. package/dist/resources/migrations/runner.js +212 -18
  247. package/dist/resources/migrations/snapshot.js +1 -0
  248. package/dist/resources/migrations/source-fields.js +5 -5
  249. package/dist/resources/migrations/state.js +36 -1
  250. package/dist/resources/migrations/status.js +2 -13
  251. package/dist/resources/migrations/synthetic-test-migration.js +81 -12
  252. package/dist/resources/migrations/types.js +26 -1
  253. package/dist/resources/migrations/visibility-backfill.js +113 -72
  254. package/dist/resources/oauth-discovery.js +0 -5
  255. package/dist/resources/object-body-guard.js +40 -0
  256. package/dist/resources/org-event-created-at.js +133 -0
  257. package/dist/resources/org-event-reserved.js +92 -0
  258. package/dist/resources/org-event-write-fault.js +19 -0
  259. package/dist/resources/originator-instance.js +39 -7
  260. package/dist/resources/owner-delete-recheck.js +78 -0
  261. package/dist/resources/owner-field-guard.js +39 -5
  262. package/dist/resources/owner-scoped-write-policy.js +256 -0
  263. package/dist/resources/owner-scoped-writes.js +89 -0
  264. package/dist/resources/path-id-rewrite.js +76 -0
  265. package/dist/resources/presence-internal.js +5 -5
  266. package/dist/resources/presence-receipt.js +236 -0
  267. package/dist/resources/promotion-binding.js +43 -0
  268. package/dist/resources/promotion-stamp.js +143 -17
  269. package/dist/resources/protocol-context.js +189 -0
  270. package/dist/resources/record-owner-guard.js +74 -26
  271. package/dist/resources/record-type-kit.js +2 -4
  272. package/dist/resources/record-types.js +1 -1
  273. package/dist/resources/relay-ops.js +78 -6
  274. package/dist/resources/replay-store.js +96 -19
  275. package/dist/resources/request-target.js +163 -0
  276. package/dist/resources/request-transaction.js +46 -1
  277. package/dist/resources/search-readiness.js +4 -1
  278. package/dist/resources/seed-ids.js +9 -0
  279. package/dist/resources/seed-reservation.js +116 -0
  280. package/dist/resources/semantic-retrieval-core.js +27 -15
  281. package/dist/resources/server-row-validation.js +71 -0
  282. package/dist/resources/skill-manifest.js +24 -14
  283. package/dist/resources/skill-subject.js +53 -0
  284. package/dist/resources/skill-version-write.js +789 -0
  285. package/dist/resources/skill-write-fault.js +20 -0
  286. package/dist/resources/skill-write-policy.js +68 -0
  287. package/dist/resources/skill-write.js +67 -7
  288. package/dist/resources/soul-write-policy.js +26 -7
  289. package/dist/resources/table-helpers.js +10 -7
  290. package/dist/resources/table-subscription-policy.js +518 -85
  291. package/dist/resources/table-subscriptions.js +20 -7
  292. package/dist/resources/team-directory.js +248 -0
  293. package/dist/resources/tool-descriptors/index.js +69 -8
  294. package/dist/resources/txn-pause-point.js +235 -0
  295. package/dist/resources/usage-recording.js +186 -70
  296. package/dist/resources/write-back.js +383 -0
  297. package/dist/resources/write-journal-context.js +5 -0
  298. package/dist/resources/write-journal.js +289 -0
  299. package/dist/src/engine-version-contract.js +1 -0
  300. package/dist/src/keystore.js +72 -0
  301. package/dist/src/lib/agent-home-fields.js +132 -0
  302. package/dist/src/lib/agent-id-rule.js +88 -0
  303. package/dist/src/lib/agent-key-register.js +80 -0
  304. package/dist/src/lib/atomic-write.js +256 -0
  305. package/dist/src/lib/credential-status-rule.js +78 -0
  306. package/dist/src/lib/expired-by-agent.js +37 -0
  307. package/dist/src/lib/federation-retry-row.js +101 -0
  308. package/dist/src/lib/flair-agent-role.js +4 -0
  309. package/dist/src/lib/idp-mapping-rule.js +81 -0
  310. package/dist/src/lib/instance-identity-row.js +20 -0
  311. package/dist/src/lib/instruction-event-contract.js +17 -0
  312. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  313. package/dist/src/lib/memory-attributes.js +4 -0
  314. package/dist/src/lib/memory-id-policy.js +46 -0
  315. package/dist/src/lib/open-live-row.js +20 -0
  316. package/dist/src/lib/principal-status.js +29 -0
  317. package/dist/src/lib/proto-safe-record.js +42 -0
  318. package/dist/src/lib/reembed-server-support.js +66 -0
  319. package/dist/src/lib/scheduler-platform.js +10 -6
  320. package/dist/src/lib/soul-scope-fields.js +26 -0
  321. package/dist/src/lib/systemd-agent-id.js +38 -0
  322. package/dist/src/rem/promote-policy.js +3 -3
  323. package/dist/src/rem/scheduler.js +21 -4
  324. package/docs/access-control.md +164 -54
  325. package/docs/api-reference.md +165 -32
  326. package/docs/auth.md +46 -30
  327. package/docs/bridges.md +11 -0
  328. package/docs/claude-code.md +37 -7
  329. package/docs/deploying-on-fabric.md +178 -0
  330. package/docs/deployment.md +19 -0
  331. package/docs/embedding-in-a-harper-app.md +17 -15
  332. package/docs/entity-vocabulary.md +3 -6
  333. package/docs/federation.md +61 -3
  334. package/docs/hosted-on-fabric.md +43 -36
  335. package/docs/integrations.md +14 -14
  336. package/docs/mcp-clients.md +12 -7
  337. package/docs/n8n.md +17 -11
  338. package/docs/notes/mcp-agent-auth-consumer.md +16 -13
  339. package/docs/notes/mcp-oauth-model2.md +40 -11
  340. package/docs/openclaw.md +1 -1
  341. package/docs/quickstart-fabric.md +4 -4
  342. package/docs/quickstart.md +12 -4
  343. package/docs/releasing.md +25 -19
  344. package/docs/rem.md +32 -3
  345. package/docs/secrets-and-keys.md +21 -4
  346. package/docs/standalone-local.md +30 -2
  347. package/docs/supply-chain-policy.md +34 -16
  348. package/docs/the-team.md +2 -2
  349. package/docs/upgrade.md +46 -6
  350. package/package.json +24 -12
  351. package/schemas/agent-key-registration.graphql +22 -0
  352. package/schemas/agent.graphql +6 -3
  353. package/schemas/federation.graphql +41 -1
  354. package/schemas/memory.graphql +91 -7
  355. package/schemas/oauth.graphql +19 -0
  356. package/schemas/schema.graphql +2 -0
  357. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  358. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  359. package/dist/resources/soul-adk-guard.js +0 -68
@@ -1,18 +1,50 @@
1
+ import { normalizeEmptyEmbedding } from "./memory-embedding-value.js";
1
2
  import { randomUUID } from "node:crypto";
3
+ import { isDeepStrictEqual } from "node:util";
2
4
  import { Resource, databases } from "harper";
3
5
  import { allowVerified, resolveAgentAuth } from "./agent-auth.js";
6
+ import { subscribeInProcess } from "./table-subscription-policy.js";
4
7
  import { computeContentHash, findExistingMemoryByContentHash } from "./memory-feed-lib.js";
5
8
  import { FORBIDDEN, UNAUTH, stampAttribution } from "./record-type-kit.js";
6
9
  import { guardAuthorityFields, stripAuthorityFields } from "./authority-field-guard.js";
7
10
  import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
8
- import { assertValidDurability } from "./memory-durability.js";
9
- import { enforceSkillDurability, refuseSkillWriteSource, skillScanGate } from "./skill-write.js";
10
- import { noteMemoryUpsert } from "./bm25-index-service.js";
11
+ import { assertValidDurability, stampEphemeralExpiry } from "./memory-durability.js";
12
+ import { enforceSkillDurability, isSkillWrite, refuseSkillWriteSource, skillScanGate } from "./skill-write.js";
13
+ import { buildSkillSuccessorRow, closedSkillPayloadReadable, defaultSkillHooks, grantedSkillClose, resolveSkillHead, runSkillVersionWrite, skillVersionVisibility, prepareSkillBody, validateSkillSnapshots, authorizeSkillOwners, skillWriteConflict } from "./skill-version-write.js";
14
+ import { deriveSkillSubjectId } from "./skill-subject.js";
15
+ import { noteMemoryUpsert, noteMemoryDelete } from "./bm25-index-service.js";
11
16
  import { extractPointerInputs } from "./memory-host-source.js";
17
+ import { deletePointerRowViaTable } from "./host-pointer-adapter.js";
12
18
  import { stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
13
19
  import { buildProvenance } from "./provenance.js";
14
- import { applyFederationBookkeeping, applyOriginatorInstanceId } from "./originator-instance.js";
20
+ import { redactMemoryWrite, redactSkillWrite } from "./memory-redaction.js";
21
+ import { REDACTION_RULES, WRITE_RESPONSE_WITHHELD, buildFromAllowlist, feedResponseFields, storageResult, suppliedMemoryFields } from "./memory-write-response.js";
22
+ import { applyFederationBookkeeping, applyOriginatorInstanceId, resolveStoredRow } from "./originator-instance.js";
15
23
  import { resolveReadScope } from "./memory-read-scope.js";
24
+ import { reservedSeedFeedWriteDenial, reservedSeedSubjectDenial, writeTargetIds } from "./seed-reservation.js";
25
+ import { refuseContentSuffixId } from "./memory-id-guard.js";
26
+ import { WriteBackConflictError, writeBackCommittedRow } from "./write-back.js";
27
+ import { withOwnedTransaction } from "./request-transaction.js";
28
+ import { txnPausePoint } from "./txn-pause-point.js";
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
+ }
16
48
  export class FeedMemories extends Resource {
17
49
  // Self-authorize via the Ed25519 agent verify (the auth reshape removes the
18
50
  // gate's admin elevation).
@@ -26,6 +58,16 @@ export class FeedMemories extends Resource {
26
58
  if (auth.kind === "anonymous") {
27
59
  return UNAUTH();
28
60
  }
61
+ // flair#2561: the non-null-valued fields this request supplies, read from
62
+ // the body as sent, before anything is merged into it; the response
63
+ // reports only named primitive fields (feedWriteResponse).
64
+ const supplied = suppliedMemoryFields(content);
65
+ const seedDenial = reservedSeedFeedWriteDenial("Memory", [...writeTargetIds(this, content), content?.supersedes]);
66
+ if (seedDenial)
67
+ return seedDenial;
68
+ const contentSuffixDenial = refuseContentSuffixId(writeTargetIds(this, content));
69
+ if (contentSuffixDenial)
70
+ return contentSuffixDenial;
29
71
  // No-forge attribution: use the kit's stampAttribution to stamp agentId
30
72
  // from the authenticated principal, never from the body.
31
73
  //
@@ -49,9 +91,31 @@ export class FeedMemories extends Resource {
49
91
  const attr = stampAttribution(auth, content, 'agentId', 'stamp-strict', 'forbidden: cannot attribute a feed memory to another agent');
50
92
  if (attr.denied)
51
93
  return attr.denied;
94
+ // The feed writes the raw table without the embedding-space latch, so a
95
+ // body may not supply the embedding stamp. flair#2465: nor
96
+ // `embeddedContentHash`; a Feed skill successor may only retain the stored
97
+ // row's value (prepareSkillBody).
98
+ if (content?.embedding !== undefined || content?.embeddingModel !== undefined || content?.embeddedContentHash !== undefined) {
99
+ return Response.json({
100
+ error: "feed_embedding_not_writable",
101
+ message: "a feed write may not set embedding, embeddingModel or embeddedContentHash; omit these fields",
102
+ }, { status: 400 });
103
+ }
52
104
  // Guard against body-supplied id targeting another agent's record.
105
+ const resolvedExisting = await resolveStoredRow(this, "Memory", content, () => null);
106
+ if (resolvedExisting.denial)
107
+ return resolvedExisting.denial;
108
+ const existingRecord = resolvedExisting.row;
109
+ const urlTargetId = this.getId?.();
110
+ if (content && typeof content === "object" && content.id == null &&
111
+ (typeof urlTargetId === "string" || typeof urlTargetId === "number")) {
112
+ content.id = urlTargetId;
113
+ }
114
+ // An omitted visibility keeps the stored row's private/shared value: copied
115
+ // here for the checks below, and taken again for the write itself from the
116
+ // row the write-back reads inside its transaction.
117
+ const visibilityOmitted = content?.visibility === undefined || content?.visibility === null;
53
118
  if (content?.id) {
54
- const existingRecord = await databases.flair.Memory.get(content.id);
55
119
  if (existingRecord && existingRecord.agentId !== content.agentId) {
56
120
  return FORBIDDEN("forbidden: cannot write a feed memory owned by another agent");
57
121
  }
@@ -63,6 +127,13 @@ export class FeedMemories extends Resource {
63
127
  content.visibility = existingRecord.visibility;
64
128
  }
65
129
  }
130
+ const preparedSkill = await prepareSkillBody(content, existingRecord, auth);
131
+ if (preparedSkill instanceof Response)
132
+ return preparedSkill;
133
+ content = preparedSkill.content;
134
+ let redactedValues = redactMemoryWrite(content).count;
135
+ // Duplicate top-level metadata keys are refused; otherwise redact name/description and tags.
136
+ redactedValues += redactSkillWrite(content);
66
137
  const agentId = content.agentId;
67
138
  const body = String(content?.content ?? "");
68
139
  if (!agentId || !body) {
@@ -141,11 +212,165 @@ export class FeedMemories extends Resource {
141
212
  if (authorityDenial)
142
213
  return authorityDenial;
143
214
  }
215
+ if (isSkillWrite(content)) {
216
+ const now = new Date().toISOString();
217
+ const addressed = existingRecord;
218
+ const predecessor = preparedSkill.predecessor;
219
+ const successorId = addressed
220
+ ? `${agentId}-${randomUUID()}`
221
+ : String(content.id ?? `${agentId}-${Date.now()}-${randomUUID()}`);
222
+ const subjectId = deriveSkillSubjectId({ newPhysicalId: successorId, storedHead: addressed, predecessor });
223
+ const seedLineageDenial = reservedSeedSubjectDenial("Memory", [subjectId], ctx, auth);
224
+ if (seedLineageDenial)
225
+ return seedLineageDenial;
226
+ const addressedId = addressed ? String(addressed.id) : predecessor ? String(predecessor.id) : null;
227
+ const captured = { row: null, closed: null };
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
+ },
329
+ });
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;
363
+ }
144
364
  const now = new Date().toISOString();
145
365
  const contentHash = computeContentHash(agentId, body);
146
366
  const existing = await findExistingMemoryByContentHash(databases.flair.Memory.search(), agentId, contentHash);
147
- if (existing)
148
- return existing;
367
+ if (existing) {
368
+ if (existing.durability === "ephemeral" && existing.expiresAt == null) {
369
+ const repaired = await repairDeduplicatedExpiry(ctx, existing);
370
+ return repaired instanceof Response ? repaired : feedWriteResponse(repaired, redactedValues, supplied);
371
+ }
372
+ return feedWriteResponse(existing, redactedValues, supplied);
373
+ }
149
374
  const record = {
150
375
  ...content,
151
376
  id: content.id ?? `${agentId}-${Date.now()}-${randomUUID()}`,
@@ -182,37 +407,144 @@ export class FeedMemories extends Resource {
182
407
  // caller-supplied server-stamped field (instanceToken, provenance), then
183
408
  // PRESERVE the existing row's incarnation token, else generate one.
184
409
  stripServerStampedFields(record);
185
- // flair#1940 A1-iv item 1: a failed existing-row lookup must FAIL the write,
186
- // not fall back to a fresh token — rotating the token would hide a still-
187
- // stored pointer row that is bound to the stored token (the same fail-closed
188
- // rule #1956 applies to put()). No `.catch`: the rejection propagates.
189
- const priorById = await databases.flair.Memory.get(record.id);
190
- record.instanceToken = priorById?.instanceToken ?? randomUUID();
191
- // Feed ingest is a full-row write: it REPLACES the stored row, so a
192
- // re-ingest with new content is a semantic re-authoring. Re-stamp
193
- // provenance from the resolved (trusted) identity and ONE server clock read
194
- // (inside buildProvenance) rather than carrying the stored blob forward — a
195
- // legacy row whose `verified.timestamp` came from a client `createdAt` must
196
- // not keep presenting that value after a new write (flair#1960 r2). The feed
197
- // body's own `createdAt` is recorded only as the CLAIM
198
- // `provenance.claimed.createdAt`, never as a verified timestamp. The
199
- // incarnation token is still preserved above (a re-ingest is not a
200
- // reincarnation), so only `provenance` is re-derived.
201
- record.provenance = buildProvenance(auth, record.createdAt, content);
202
- // flair#1965 r2: this raw table put REPLACES the row, bypassing the Memory
203
- // resource's write methods, so the create/update rule is applied here
204
- // explicitly: a CREATE (no stored row) stamps this instance's own id and
205
- // ignores any body value; an UPDATE keeps the STORED value (a body value
206
- // neither replaces nor clears it). The receiver-side federation bookkeeping
207
- // (`_originatorInstanceId` et al.) is likewise unsettable from a body — it
208
- // stands as stored, or is dropped on a create. See
209
- // resources/originator-instance.ts.
210
- await applyOriginatorInstanceId(record, priorById);
211
- applyFederationBookkeeping(record, priorById);
212
- await databases.flair.Memory.put(record);
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");
443
+ return { skip: true };
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
+ };
521
+ }
522
+ throw err;
523
+ }
524
+ if (refusal)
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;
213
545
  // flair#1357 — raw-table write: hook it explicitly (see bm25-index-service).
214
- noteMemoryUpsert(record);
215
- return record;
546
+ noteMemoryUpsert(written);
547
+ return feedWriteResponse(written, redactedValues, supplied);
216
548
  }
217
549
  // Subscription admission: verified agents, admins and trusted internal
218
550
  // calls; anonymous HTTP is refused (the same gate as FeedSouls). Admission is
@@ -236,7 +568,7 @@ export class FeedMemories extends Resource {
236
568
  * Two layers decide what a non-admin subscriber receives:
237
569
  *
238
570
  * 1. Harper's synchronous `SubscriptionRequest.rowFilter`, set to the
239
- * 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
240
572
  * full stored row for the rows replayed when the subscription opens, for
241
573
  * every live change (an update is re-read from the primary store and
242
574
  * delivered as a full-row `put`) and for reload re-deliveries; a history
@@ -265,12 +597,12 @@ export class FeedMemories extends Resource {
265
597
  throw Object.assign(new Error("authentication required"), { statusCode: 401 });
266
598
  }
267
599
  if (auth.kind === "internal" || auth.isAdmin) {
268
- const subscription = await databases.flair.Memory.subscribe(target);
600
+ const subscription = await subscribeInProcess(databases.flair.Memory, target);
269
601
  if (!incomingMessages) {
270
602
  return subscription;
271
603
  }
272
604
  for await (const event of subscription) {
273
- yield event;
605
+ yield promotionBoundEvent(event);
274
606
  }
275
607
  return;
276
608
  }
@@ -280,15 +612,15 @@ export class FeedMemories extends Resource {
280
612
  // Harper's own Resource.connect() makes.
281
613
  const callerRequest = this.constructor.loadAsInstance === false ? target : incomingMessages;
282
614
  const request = scopedSubscriptionRequest(callerRequest, (record) => scope.isAllowed(record));
283
- const subscription = await databases.flair.Memory.subscribe(request);
615
+ const subscription = await subscribeInProcess(databases.flair.Memory, request);
284
616
  const readStored = (id) => databases.flair.Memory.get(id);
285
617
  const replaysHistory = request.startTime !== undefined || request.previousCount !== undefined;
286
618
  for await (const event of subscription) {
287
- if (!(await readableRowEvent(event, scope.isAllowed, readStored)))
619
+ if (!(await readableRowEvent(event, auth.agentId, scope.isAllowed, readStored)))
288
620
  continue;
289
- if (replaysHistory && !(await storedRowReadable(event?.id, scope.isAllowed, readStored)))
621
+ if (replaysHistory && !(await storedRowReadable(event?.id, auth.agentId, scope.isAllowed, readStored)))
290
622
  continue;
291
- yield event;
623
+ yield promotionBoundEvent(event);
292
624
  }
293
625
  }
294
626
  }
@@ -346,15 +678,20 @@ function scopedSubscriptionRequest(callerRequest, rowFilter) {
346
678
  * The event itself is what is delivered; the stored row is only the input to
347
679
  * the decision.
348
680
  */
349
- async function readableRowEvent(event, isAllowed, readStored) {
681
+ async function readableRowEvent(event, readerId, isAllowed, readStored) {
350
682
  if (!event || (event.type !== "put" && event.type !== "invalidate"))
351
683
  return false;
352
684
  const row = event.value;
353
685
  if (row == null || typeof row !== "object")
354
686
  return false;
355
- if (typeof row.agentId === "string" && row.visibility !== undefined)
356
- return isAllowed(row);
357
- return storedRowReadable(event.id, isAllowed, readStored);
687
+ if (typeof row.agentId === "string" && row.visibility !== undefined) {
688
+ if (!isAllowed(row))
689
+ return false;
690
+ }
691
+ else if (!(await storedRowReadable(event.id, readerId, isAllowed, readStored))) {
692
+ return false;
693
+ }
694
+ return closedSkillPayloadReadable(row, readerId);
358
695
  }
359
696
  /**
360
697
  * Re-read the stored row by id and apply the read predicate to it. An absent
@@ -368,7 +705,7 @@ async function readableRowEvent(event, isAllowed, readStored) {
368
705
  * too, so a record that is private or deleted now is not replayed from its
369
706
  * earlier versions.
370
707
  */
371
- async function storedRowReadable(id, isAllowed, readStored) {
708
+ async function storedRowReadable(id, readerId, isAllowed, readStored) {
372
709
  if (id == null)
373
710
  return false;
374
711
  let stored;
@@ -380,5 +717,163 @@ async function storedRowReadable(id, isAllowed, readStored) {
380
717
  }
381
718
  if (stored == null || typeof stored !== "object" || typeof stored.agentId !== "string")
382
719
  return false;
383
- return isAllowed(stored);
720
+ if (!isAllowed(stored))
721
+ return false;
722
+ return closedSkillPayloadReadable(stored, readerId);
723
+ }
724
+ /** The named error for a dedup expiry repair whose matched row changed during the request (flair#2358). */
725
+ export const FEED_DEDUP_TARGET_CHANGED_ERROR = "feed_dedup_target_changed";
726
+ /** Attempts of the dedup expiry repair before it gives up on a row that keeps changing. */
727
+ const FEED_DEDUP_REPAIR_ATTEMPTS = 3;
728
+ export const FEED_TARGET_CHANGED_ERROR = "feed_target_changed";
729
+ function feedTargetChanged(id) {
730
+ return Response.json({
731
+ error: FEED_TARGET_CHANGED_ERROR,
732
+ outcome: "conflict",
733
+ message: `the stored row ${JSON.stringify(id)} this write targets changed during the request; write not applied; retry the write`,
734
+ }, { status: 409 });
735
+ }
736
+ function feedDedupTargetChanged(id) {
737
+ return Response.json({
738
+ error: FEED_DEDUP_TARGET_CHANGED_ERROR,
739
+ message: `the stored row ${JSON.stringify(id)} this write matched changed during the request; retry the write`,
740
+ }, { status: 409 });
741
+ }
742
+ /** The row is still the dedup match: the same id, owner and content hash. */
743
+ function isDedupMatch(row, match) {
744
+ return row != null && typeof row === "object" && String(row.id) === String(match.id) &&
745
+ row.agentId === match.agentId && row.contentHash === match.contentHash;
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
+ }
758
+ function feedWriteResponse(result, redactedValues, supplied) {
759
+ const response = feedResponseFields(result, supplied);
760
+ if (response instanceof Response || redactedValues <= 0)
761
+ return response;
762
+ const redaction = buildFromAllowlist({ redactedValues }, REDACTION_RULES);
763
+ return redaction instanceof Response ? redaction : Object.assign(response, redaction);
764
+ }
765
+ /**
766
+ * flair#2358: stamp the tier expiry (stampEphemeralExpiry) on the ephemeral
767
+ * row the content-hash dedup matched by agentId + contentHash. The match's id
768
+ * is refused first when it is a reserved seed id or ends in `.content`. In a
769
+ * transaction this call owns, the row is re-read; unless its id, agentId and
770
+ * contentHash equal the match's, the request is refused (409
771
+ * FEED_DEDUP_TARGET_CHANGED_ERROR). A matching row that is no longer
772
+ * ephemeral, or already has an expiry, is returned from that read. Otherwise a
773
+ * committed read must equal the transaction's read before the write, else the
774
+ * repair starts over (FEED_DEDUP_REPAIR_ATTEMPTS attempts, then the 409). A
775
+ * change committed after that read and before the commit follows Harper's
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).
783
+ */
784
+ async function repairDeduplicatedExpiry(ctx, match) {
785
+ const id = String(match.id);
786
+ const idDenial = reservedSeedFeedWriteDenial("Memory", [id]) ?? refuseContentSuffixId([id]);
787
+ if (idDenial)
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) {
803
+ for (let attempt = 1; attempt <= FEED_DEDUP_REPAIR_ATTEMPTS; attempt++) {
804
+ const outcome = await withOwnedTransaction(ctx, async (c) => {
805
+ const stored = await databases.flair.Memory.get(id, c);
806
+ if (!isDedupMatch(stored, match))
807
+ return { kind: "changed" };
808
+ if (stored.durability !== "ephemeral" || stored.expiresAt != null)
809
+ return { kind: "current", row: stored };
810
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
811
+ const pause = txnPausePoint("feed-dedup-repair");
812
+ if (pause)
813
+ await pause;
814
+ // The committed row, in an explicit fresh context (not this transaction's snapshot).
815
+ const committed = await databases.flair.Memory.get(id, {});
816
+ if (!isDeepStrictEqual(committed, stored))
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;
823
+ const row = { ...stored };
824
+ // A stored null is "no expiry": drop it so the shared rule stamps a fresh
825
+ // tier TTL rather than refusing the null as malformed.
826
+ delete row.expiresAt;
827
+ const error = stampEphemeralExpiry(row);
828
+ if (error)
829
+ throw new Error(`flair: deduplicated ephemeral row ${id} could not be repaired (${error})`);
830
+ // Only `expiresAt`: an incremental update, never a
831
+ // full-row put of the row read above (flair#2470).
832
+ const result = storageResult(await databases.flair.Memory.update(id, { expiresAt: row.expiresAt }, c));
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);
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;
845
+ return { kind: "written", row };
846
+ });
847
+ if (outcome.kind === "withheld")
848
+ return outcome.response;
849
+ if (outcome.kind === "retry")
850
+ continue;
851
+ if (outcome.kind === "changed")
852
+ return feedDedupTargetChanged(id);
853
+ if (outcome.kind === "current")
854
+ return stripInlinePointerFields(outcome.row);
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);
874
+ return feedDedupTargetChanged(id);
875
+ }
876
+ return stripInlinePointerFields(confirmed);
877
+ }
878
+ return feedDedupTargetChanged(id);
384
879
  }