@tpsdev-ai/flair 0.58.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +1030 -343
  10. package/dist/commands/agent.js +384 -45
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +601 -163
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +146 -53
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +120 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +27 -2
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1775 -338
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +103 -7
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +227 -64
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -1,18 +1,31 @@
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";
4
6
  import { computeContentHash, findExistingMemoryByContentHash } from "./memory-feed-lib.js";
5
7
  import { FORBIDDEN, UNAUTH, stampAttribution } from "./record-type-kit.js";
6
8
  import { guardAuthorityFields, stripAuthorityFields } from "./authority-field-guard.js";
7
9
  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";
10
+ import { assertValidDurability, stampEphemeralExpiry } from "./memory-durability.js";
11
+ import { enforceSkillDurability, isSkillWrite, refuseSkillWriteSource, skillScanGate } from "./skill-write.js";
12
+ import { buildSkillSuccessorRow, closedSkillPayloadReadable, defaultSkillHooks, grantedSkillClose, resolveSkillHead, runSkillVersionWrite, skillVersionVisibility, prepareSkillBody, validateSkillSnapshots, authorizeSkillOwners, skillWriteConflict } from "./skill-version-write.js";
13
+ import { deriveSkillSubjectId } from "./skill-subject.js";
14
+ import { noteMemoryUpsert, noteMemoryDelete } from "./bm25-index-service.js";
11
15
  import { extractPointerInputs } from "./memory-host-source.js";
16
+ import { deletePointerRowViaTable } from "./host-pointer-adapter.js";
12
17
  import { stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
13
18
  import { buildProvenance } from "./provenance.js";
14
- import { applyFederationBookkeeping, applyOriginatorInstanceId } from "./originator-instance.js";
19
+ import { redactMemoryWrite, redactSkillWrite } from "./memory-redaction.js";
20
+ import { REDACTION_RULES, buildFromAllowlist, feedResponseFields, storageResult, suppliedMemoryFields } from "./memory-write-response.js";
21
+ import { applyFederationBookkeeping, applyOriginatorInstanceId, resolveStoredRow } from "./originator-instance.js";
15
22
  import { resolveReadScope } from "./memory-read-scope.js";
23
+ import { reservedSeedFeedWriteDenial, reservedSeedSubjectDenial, writeTargetIds } from "./seed-reservation.js";
24
+ import { refuseContentSuffixId } from "./memory-id-guard.js";
25
+ import { WriteBackConflictError, writeBackCommittedRow } from "./write-back.js";
26
+ import { withOwnedTransaction } from "./request-transaction.js";
27
+ import { txnPausePoint } from "./txn-pause-point.js";
28
+ import { stripInlinePointerFields } from "./host-source-visibility.js";
16
29
  export class FeedMemories extends Resource {
17
30
  // Self-authorize via the Ed25519 agent verify (the auth reshape removes the
18
31
  // gate's admin elevation).
@@ -26,6 +39,16 @@ export class FeedMemories extends Resource {
26
39
  if (auth.kind === "anonymous") {
27
40
  return UNAUTH();
28
41
  }
42
+ // flair#2561: the non-null-valued fields this request supplies, read from
43
+ // the body as sent, before anything is merged into it; the response
44
+ // reports only named primitive fields (feedWriteResponse).
45
+ const supplied = suppliedMemoryFields(content);
46
+ const seedDenial = reservedSeedFeedWriteDenial("Memory", [...writeTargetIds(this, content), content?.supersedes]);
47
+ if (seedDenial)
48
+ return seedDenial;
49
+ const contentSuffixDenial = refuseContentSuffixId(writeTargetIds(this, content));
50
+ if (contentSuffixDenial)
51
+ return contentSuffixDenial;
29
52
  // No-forge attribution: use the kit's stampAttribution to stamp agentId
30
53
  // from the authenticated principal, never from the body.
31
54
  //
@@ -49,9 +72,31 @@ export class FeedMemories extends Resource {
49
72
  const attr = stampAttribution(auth, content, 'agentId', 'stamp-strict', 'forbidden: cannot attribute a feed memory to another agent');
50
73
  if (attr.denied)
51
74
  return attr.denied;
75
+ // The feed writes the raw table without the embedding-space latch, so a
76
+ // body may not supply the embedding stamp. flair#2465: nor
77
+ // `embeddedContentHash`; a Feed skill successor may only retain the stored
78
+ // row's value (prepareSkillBody).
79
+ if (content?.embedding !== undefined || content?.embeddingModel !== undefined || content?.embeddedContentHash !== undefined) {
80
+ return Response.json({
81
+ error: "feed_embedding_not_writable",
82
+ message: "a feed write may not set embedding, embeddingModel or embeddedContentHash; omit these fields",
83
+ }, { status: 400 });
84
+ }
52
85
  // Guard against body-supplied id targeting another agent's record.
86
+ const resolvedExisting = await resolveStoredRow(this, "Memory", content, () => null);
87
+ if (resolvedExisting.denial)
88
+ return resolvedExisting.denial;
89
+ const existingRecord = resolvedExisting.row;
90
+ const urlTargetId = this.getId?.();
91
+ if (content && typeof content === "object" && content.id == null &&
92
+ (typeof urlTargetId === "string" || typeof urlTargetId === "number")) {
93
+ content.id = urlTargetId;
94
+ }
95
+ // An omitted visibility keeps the stored row's private/shared value: copied
96
+ // here for the checks below, and taken again for the write itself from the
97
+ // row the write-back reads inside its transaction.
98
+ const visibilityOmitted = content?.visibility === undefined || content?.visibility === null;
53
99
  if (content?.id) {
54
- const existingRecord = await databases.flair.Memory.get(content.id);
55
100
  if (existingRecord && existingRecord.agentId !== content.agentId) {
56
101
  return FORBIDDEN("forbidden: cannot write a feed memory owned by another agent");
57
102
  }
@@ -63,6 +108,13 @@ export class FeedMemories extends Resource {
63
108
  content.visibility = existingRecord.visibility;
64
109
  }
65
110
  }
111
+ const preparedSkill = await prepareSkillBody(content, existingRecord, auth);
112
+ if (preparedSkill instanceof Response)
113
+ return preparedSkill;
114
+ content = preparedSkill.content;
115
+ let redactedValues = redactMemoryWrite(content).count;
116
+ // Duplicate top-level metadata keys are refused; otherwise redact name/description and tags.
117
+ redactedValues += redactSkillWrite(content);
66
118
  const agentId = content.agentId;
67
119
  const body = String(content?.content ?? "");
68
120
  if (!agentId || !body) {
@@ -141,11 +193,85 @@ export class FeedMemories extends Resource {
141
193
  if (authorityDenial)
142
194
  return authorityDenial;
143
195
  }
196
+ if (isSkillWrite(content)) {
197
+ const now = new Date().toISOString();
198
+ const addressed = existingRecord;
199
+ const predecessor = preparedSkill.predecessor;
200
+ const successorId = addressed
201
+ ? `${agentId}-${randomUUID()}`
202
+ : String(content.id ?? `${agentId}-${Date.now()}-${randomUUID()}`);
203
+ const subjectId = deriveSkillSubjectId({ newPhysicalId: successorId, storedHead: addressed, predecessor });
204
+ const seedLineageDenial = reservedSeedSubjectDenial("Memory", [subjectId], ctx, auth);
205
+ if (seedLineageDenial)
206
+ return seedLineageDenial;
207
+ const addressedId = addressed ? String(addressed.id) : predecessor ? String(predecessor.id) : null;
208
+ 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,
231
+ });
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);
264
+ }
144
265
  const now = new Date().toISOString();
145
266
  const contentHash = computeContentHash(agentId, body);
146
267
  const existing = await findExistingMemoryByContentHash(databases.flair.Memory.search(), agentId, contentHash);
147
- if (existing)
148
- return existing;
268
+ if (existing) {
269
+ if (existing.durability === "ephemeral" && existing.expiresAt == null) {
270
+ const repaired = await repairDeduplicatedExpiry(ctx, existing);
271
+ return repaired instanceof Response ? repaired : feedWriteResponse(repaired, redactedValues, supplied);
272
+ }
273
+ return feedWriteResponse(existing, redactedValues, supplied);
274
+ }
149
275
  const record = {
150
276
  ...content,
151
277
  id: content.id ?? `${agentId}-${Date.now()}-${randomUUID()}`,
@@ -182,37 +308,91 @@ export class FeedMemories extends Resource {
182
308
  // caller-supplied server-stamped field (instanceToken, provenance), then
183
309
  // PRESERVE the existing row's incarnation token, else generate one.
184
310
  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);
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 });
340
+ return { skip: true };
341
+ }
342
+ }
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) {
379
+ 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;
213
393
  // flair#1357 — raw-table write: hook it explicitly (see bm25-index-service).
214
- noteMemoryUpsert(record);
215
- return record;
394
+ noteMemoryUpsert(written);
395
+ return feedWriteResponse(written, redactedValues, supplied);
216
396
  }
217
397
  // Subscription admission: verified agents, admins and trusted internal
218
398
  // calls; anonymous HTTP is refused (the same gate as FeedSouls). Admission is
@@ -284,9 +464,9 @@ export class FeedMemories extends Resource {
284
464
  const readStored = (id) => databases.flair.Memory.get(id);
285
465
  const replaysHistory = request.startTime !== undefined || request.previousCount !== undefined;
286
466
  for await (const event of subscription) {
287
- if (!(await readableRowEvent(event, scope.isAllowed, readStored)))
467
+ if (!(await readableRowEvent(event, auth.agentId, scope.isAllowed, readStored)))
288
468
  continue;
289
- if (replaysHistory && !(await storedRowReadable(event?.id, scope.isAllowed, readStored)))
469
+ if (replaysHistory && !(await storedRowReadable(event?.id, auth.agentId, scope.isAllowed, readStored)))
290
470
  continue;
291
471
  yield event;
292
472
  }
@@ -346,15 +526,20 @@ function scopedSubscriptionRequest(callerRequest, rowFilter) {
346
526
  * The event itself is what is delivered; the stored row is only the input to
347
527
  * the decision.
348
528
  */
349
- async function readableRowEvent(event, isAllowed, readStored) {
529
+ async function readableRowEvent(event, readerId, isAllowed, readStored) {
350
530
  if (!event || (event.type !== "put" && event.type !== "invalidate"))
351
531
  return false;
352
532
  const row = event.value;
353
533
  if (row == null || typeof row !== "object")
354
534
  return false;
355
- if (typeof row.agentId === "string" && row.visibility !== undefined)
356
- return isAllowed(row);
357
- return storedRowReadable(event.id, isAllowed, readStored);
535
+ if (typeof row.agentId === "string" && row.visibility !== undefined) {
536
+ if (!isAllowed(row))
537
+ return false;
538
+ }
539
+ else if (!(await storedRowReadable(event.id, readerId, isAllowed, readStored))) {
540
+ return false;
541
+ }
542
+ return closedSkillPayloadReadable(row, readerId);
358
543
  }
359
544
  /**
360
545
  * Re-read the stored row by id and apply the read predicate to it. An absent
@@ -368,7 +553,7 @@ async function readableRowEvent(event, isAllowed, readStored) {
368
553
  * too, so a record that is private or deleted now is not replayed from its
369
554
  * earlier versions.
370
555
  */
371
- async function storedRowReadable(id, isAllowed, readStored) {
556
+ async function storedRowReadable(id, readerId, isAllowed, readStored) {
372
557
  if (id == null)
373
558
  return false;
374
559
  let stored;
@@ -380,5 +565,102 @@ async function storedRowReadable(id, isAllowed, readStored) {
380
565
  }
381
566
  if (stored == null || typeof stored !== "object" || typeof stored.agentId !== "string")
382
567
  return false;
383
- return isAllowed(stored);
568
+ if (!isAllowed(stored))
569
+ return false;
570
+ return closedSkillPayloadReadable(stored, readerId);
571
+ }
572
+ /** The named error for a dedup expiry repair whose matched row changed during the request (flair#2358). */
573
+ export const FEED_DEDUP_TARGET_CHANGED_ERROR = "feed_dedup_target_changed";
574
+ /** Attempts of the dedup expiry repair before it gives up on a row that keeps changing. */
575
+ const FEED_DEDUP_REPAIR_ATTEMPTS = 3;
576
+ 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
+ function feedTargetChanged(id) {
580
+ return Response.json({
581
+ error: FEED_TARGET_CHANGED_ERROR,
582
+ message: `the stored row ${JSON.stringify(id)} this write targets changed during the request; retry the write`,
583
+ }, { status: 409 });
584
+ }
585
+ function feedDedupTargetChanged(id) {
586
+ return Response.json({
587
+ error: FEED_DEDUP_TARGET_CHANGED_ERROR,
588
+ message: `the stored row ${JSON.stringify(id)} this write matched changed during the request; retry the write`,
589
+ }, { status: 409 });
590
+ }
591
+ /** The row is still the dedup match: the same id, owner and content hash. */
592
+ function isDedupMatch(row, match) {
593
+ return row != null && typeof row === "object" && String(row.id) === String(match.id) &&
594
+ row.agentId === match.agentId && row.contentHash === match.contentHash;
595
+ }
596
+ function feedWriteResponse(result, redactedValues, supplied) {
597
+ const response = feedResponseFields(result, supplied);
598
+ if (response instanceof Response || redactedValues <= 0)
599
+ return response;
600
+ const redaction = buildFromAllowlist({ redactedValues }, REDACTION_RULES);
601
+ return redaction instanceof Response ? redaction : Object.assign(response, redaction);
602
+ }
603
+ /**
604
+ * flair#2358: stamp the tier expiry (stampEphemeralExpiry) on the ephemeral
605
+ * row the content-hash dedup matched by agentId + contentHash. The match's id
606
+ * is refused first when it is a reserved seed id or ends in `.content`. In a
607
+ * transaction this call owns, the row is re-read; unless its id, agentId and
608
+ * contentHash equal the match's, the request is refused (409
609
+ * FEED_DEDUP_TARGET_CHANGED_ERROR). A matching row that is no longer
610
+ * ephemeral, or already has an expiry, is returned from that read. Otherwise a
611
+ * committed read must equal the transaction's read before the write, else the
612
+ * repair starts over (FEED_DEDUP_REPAIR_ATTEMPTS attempts, then the 409). A
613
+ * 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).
617
+ */
618
+ async function repairDeduplicatedExpiry(ctx, match) {
619
+ const id = String(match.id);
620
+ const idDenial = reservedSeedFeedWriteDenial("Memory", [id]) ?? refuseContentSuffixId([id]);
621
+ if (idDenial)
622
+ return idDenial;
623
+ for (let attempt = 1; attempt <= FEED_DEDUP_REPAIR_ATTEMPTS; attempt++) {
624
+ const outcome = await withOwnedTransaction(ctx, async (c) => {
625
+ const stored = await databases.flair.Memory.get(id, c);
626
+ if (!isDedupMatch(stored, match))
627
+ return { kind: "changed" };
628
+ if (stored.durability !== "ephemeral" || stored.expiresAt != null)
629
+ return { kind: "current", row: stored };
630
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
631
+ const pause = txnPausePoint("feed-dedup-repair");
632
+ if (pause)
633
+ await pause;
634
+ // The committed row, in an explicit fresh context (not this transaction's snapshot).
635
+ const committed = await databases.flair.Memory.get(id, {});
636
+ if (!isDeepStrictEqual(committed, stored))
637
+ return { kind: "retry" };
638
+ const row = { ...stored };
639
+ // A stored null is "no expiry": drop it so the shared rule stamps a fresh
640
+ // tier TTL rather than refusing the null as malformed.
641
+ delete row.expiresAt;
642
+ const error = stampEphemeralExpiry(row);
643
+ if (error)
644
+ throw new Error(`flair: deduplicated ephemeral row ${id} could not be repaired (${error})`);
645
+ // Only `expiresAt`: an incremental update, never a
646
+ // full-row put of the row read above (flair#2470).
647
+ const result = storageResult(await databases.flair.Memory.update(id, { expiresAt: row.expiresAt }, c));
648
+ if (result instanceof Response)
649
+ return { kind: "withheld", response: result };
650
+ return { kind: "written", row };
651
+ });
652
+ if (outcome.kind === "withheld")
653
+ return outcome.response;
654
+ if (outcome.kind === "retry")
655
+ continue;
656
+ if (outcome.kind === "changed")
657
+ return feedDedupTargetChanged(id);
658
+ if (outcome.kind === "current")
659
+ 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)
662
+ return feedDedupTargetChanged(id);
663
+ return stripInlinePointerFields(confirmed);
664
+ }
665
+ return feedDedupTargetChanged(id);
384
666
  }
@@ -1,6 +1,8 @@
1
1
  import { databases } from "harper";
2
2
  import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
+ import { deleteOwnedRow } from "./owner-delete-recheck.js";
5
+ import { txnPausePoint } from "./txn-pause-point.js";
4
6
  import { makeByIdReadGate, makeScopedSearch } from "./record-type-kit.js";
5
7
  // A grant is readable by either party: owner OR grantee. One scope object feeds
6
8
  // both the shared by-id gate and the scoped search, so the collection scope is
@@ -111,7 +113,25 @@ export class MemoryGrant extends databases.flair.MemoryGrant {
111
113
  if (record.ownerId !== auth.agentId) {
112
114
  return FORBIDDEN("forbidden: cannot delete a grant owned by another agent");
113
115
  }
114
- return super.delete(id, context);
116
+ // flair#2355: a row that is no longer the caller's at the delete's re-read
117
+ // or confirmation read is refused, not deleted
118
+ // (resources/owner-delete-recheck.ts).
119
+ const beforeDelete = txnPausePoint("grant-delete-pre");
120
+ if (beforeDelete)
121
+ await beforeDelete;
122
+ const outcome = await deleteOwnedRow(this.getContext?.(), {
123
+ table: databases.flair.MemoryGrant,
124
+ tableName: "MemoryGrant",
125
+ id: typeof id === "string" ? id : record.id,
126
+ ownerField: "ownerId",
127
+ callerId: auth.agentId,
128
+ point: "grant-delete",
129
+ });
130
+ if (outcome.kind === "refused")
131
+ return outcome.response;
132
+ if (outcome.kind === "absent")
133
+ return super.delete(id, context);
134
+ return outcome.result;
115
135
  }
116
136
  async _enforceOwnerWrite(content) {
117
137
  const auth = await this._auth();