@tpsdev-ai/flair 0.62.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +18 -10
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/types.js +1 -0
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli.js +66 -122
  8. package/dist/commands/agent.js +27 -65
  9. package/dist/commands/backup-approval.js +218 -0
  10. package/dist/commands/backup.js +37 -33
  11. package/dist/commands/bootstrap.js +3 -1
  12. package/dist/commands/deploy.js +37 -7
  13. package/dist/commands/doctor.js +119 -0
  14. package/dist/commands/export.js +3 -4
  15. package/dist/commands/federation.js +653 -68
  16. package/dist/commands/grant.js +5 -6
  17. package/dist/commands/help.js +25 -0
  18. package/dist/commands/idp.js +14 -19
  19. package/dist/commands/import.js +131 -19
  20. package/dist/commands/init.js +7 -7
  21. package/dist/commands/integrity.js +5 -6
  22. package/dist/commands/mcp.js +11 -17
  23. package/dist/commands/memory.js +33 -15
  24. package/dist/commands/orgevent.js +5 -10
  25. package/dist/commands/principal.js +13 -25
  26. package/dist/commands/quality.js +3 -0
  27. package/dist/commands/rem.js +484 -65
  28. package/dist/commands/restore.js +352 -44
  29. package/dist/commands/service.js +84 -2
  30. package/dist/commands/soul.js +0 -6
  31. package/dist/commands/status.js +51 -33
  32. package/dist/commands/test.js +4 -1
  33. package/dist/commands/upgrade.js +53 -22
  34. package/dist/commands/workspace.js +7 -8
  35. package/dist/deploy.js +59 -3
  36. package/dist/doctor-client.js +7 -2
  37. package/dist/fabric-upgrade.js +12 -2
  38. package/dist/federation/presence-send.js +139 -0
  39. package/dist/federation-verify.js +269 -177
  40. package/dist/install/clients.js +171 -35
  41. package/dist/lib/agent-id-rule.js +44 -2
  42. package/dist/lib/atomic-write.js +1 -1
  43. package/dist/lib/auth-resolve.js +1028 -52
  44. package/dist/lib/backup-approval-store.js +612 -0
  45. package/dist/lib/backup-artifact.js +343 -0
  46. package/dist/lib/config-critical-section.js +212 -25
  47. package/dist/lib/connect-phase.js +33 -0
  48. package/dist/lib/daemon-liveness.js +2 -1
  49. package/dist/lib/federation-pair-access.js +4 -0
  50. package/dist/lib/federation-retry-queue.js +283 -0
  51. package/dist/lib/federation-retry-row.js +101 -0
  52. package/dist/lib/instruction-event-contract.js +17 -0
  53. package/dist/lib/instruction-event-doctor.js +102 -0
  54. package/dist/lib/launchd-management.js +14 -3
  55. package/dist/lib/mcp-enable.js +14 -15
  56. package/dist/lib/memory-attributes.js +2 -0
  57. package/dist/lib/memory-provider-timeout.js +33 -0
  58. package/dist/lib/mqtt-config.js +132 -0
  59. package/dist/lib/mqtt-listener-doctor.js +104 -0
  60. package/dist/lib/open-live-row.js +20 -0
  61. package/dist/lib/ops-url.js +52 -0
  62. package/dist/lib/promotion-content-hash.js +20 -0
  63. package/dist/lib/restore-archive.js +760 -0
  64. package/dist/lib/restore-verify.js +1 -1
  65. package/dist/lib/skill-assignment-preflight.js +159 -0
  66. package/dist/lib/skill-seed.js +91 -8
  67. package/dist/lib/skill-tombstone-doctor.js +133 -0
  68. package/dist/lib/soul-scope-fields.js +26 -0
  69. package/dist/lib/uninstall-purge.js +266 -11
  70. package/dist/lib/upgrade-prior-liveness.js +2 -1
  71. package/dist/mcp-client-assertion.js +2 -10
  72. package/dist/memory-id-checkpoint.js +28 -7
  73. package/dist/mqtt-off-deploy.js +550 -0
  74. package/dist/rem/promote-policy.js +3 -3
  75. package/dist/rem/restore.js +302 -26
  76. package/dist/rem/runner.js +220 -58
  77. package/dist/rem/scheduler.js +21 -4
  78. package/dist/resources/A2AAdapter.js +131 -178
  79. package/dist/resources/AdminMemory.js +2 -0
  80. package/dist/resources/AdminMemoryCandidates.js +116 -0
  81. package/dist/resources/Agent.js +155 -45
  82. package/dist/resources/AgentCard.js +4 -0
  83. package/dist/resources/AgentKeyRegister.js +56 -22
  84. package/dist/resources/AgentReadPosition.js +7 -0
  85. package/dist/resources/AgentSeed.js +232 -107
  86. package/dist/resources/AutoPromoteCandidates.js +413 -84
  87. package/dist/resources/Credential.js +6 -8
  88. package/dist/resources/Federation.js +219 -57
  89. package/dist/resources/FederationRetry.js +4 -4
  90. package/dist/resources/InstructionVersion.js +1 -1
  91. package/dist/resources/MCPClientMetadata.js +6 -3
  92. package/dist/resources/Memory.js +1303 -270
  93. package/dist/resources/MemoryArchive.js +149 -64
  94. package/dist/resources/MemoryBootstrap.js +12 -22
  95. package/dist/resources/MemoryCandidate.js +16 -2
  96. package/dist/resources/MemoryConsolidate.js +2 -2
  97. package/dist/resources/MemoryFeed.js +360 -147
  98. package/dist/resources/MemoryMaintenance.js +290 -72
  99. package/dist/resources/MemoryPurge.js +138 -22
  100. package/dist/resources/MemoryReflect.js +68 -14
  101. package/dist/resources/MemoryReindex.js +91 -13
  102. package/dist/resources/Message.js +11 -2
  103. package/dist/resources/OAuth.js +156 -39
  104. package/dist/resources/OAuthClient.js +1 -1
  105. package/dist/resources/OrgEvent.js +292 -29
  106. package/dist/resources/OrgEventCatchup.js +7 -0
  107. package/dist/resources/OrgEventMaintenance.js +48 -10
  108. package/dist/resources/PairingToken.js +1 -1
  109. package/dist/resources/Presence.js +31 -11
  110. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  111. package/dist/resources/RecordUsage.js +2 -4
  112. package/dist/resources/Soul.js +2 -0
  113. package/dist/resources/SoulFeed.js +2 -1
  114. package/dist/resources/WorkspaceLatest.js +4 -0
  115. package/dist/resources/XAA.js +36 -10
  116. package/dist/resources/a2a-stream.js +313 -0
  117. package/dist/resources/a2a-url.js +4 -5
  118. package/dist/resources/agent-admin.js +10 -1
  119. package/dist/resources/agent-auth.js +98 -68
  120. package/dist/resources/agent-read-position-lib.js +4 -1
  121. package/dist/resources/agent-status-guard.js +9 -7
  122. package/dist/resources/auth-middleware.js +166 -42
  123. package/dist/resources/authority-field-guard.js +9 -11
  124. package/dist/resources/auto-promote-lib.js +8 -5
  125. package/dist/resources/basic-auth-header.js +21 -0
  126. package/dist/resources/bm25-index-service.js +4 -5
  127. package/dist/resources/dedup-cluster.js +6 -1
  128. package/dist/resources/embeddings-provider.js +25 -0
  129. package/dist/resources/federation-classify.js +89 -0
  130. package/dist/resources/federation-retry-lib.js +6 -81
  131. package/dist/resources/health.js +43 -4
  132. package/dist/resources/host-pointer/registry.js +29 -0
  133. package/dist/resources/host-pointer-adapter.js +1 -0
  134. package/dist/resources/in-process.js +24 -22
  135. package/dist/resources/instruction-version-record.js +251 -7
  136. package/dist/resources/internal-authority.js +13 -0
  137. package/dist/resources/mcp-handler.js +106 -12
  138. package/dist/resources/mcp-oauth-flag.js +12 -14
  139. package/dist/resources/mcp-oauth.js +430 -53
  140. package/dist/resources/mcp-tools.js +60 -22
  141. package/dist/resources/memory-declared-attributes.js +1 -0
  142. package/dist/resources/memory-embed-hash.js +56 -0
  143. package/dist/resources/memory-host-source.js +5 -2
  144. package/dist/resources/memory-reflect-lib.js +1 -1
  145. package/dist/resources/memory-write-lock.js +202 -23
  146. package/dist/resources/memory-write-response.js +1 -1
  147. package/dist/resources/memory-write-transaction.js +243 -0
  148. package/dist/resources/migration-boot.js +17 -12
  149. package/dist/resources/migrations/boot-progress.js +25 -0
  150. package/dist/resources/migrations/data-dir.js +16 -3
  151. package/dist/resources/migrations/dir-safety.js +60 -2
  152. package/dist/resources/migrations/embedding-stamp.js +315 -49
  153. package/dist/resources/migrations/graph-heal.js +9 -2
  154. package/dist/resources/migrations/ledger.js +5 -2
  155. package/dist/resources/migrations/lock.js +867 -80
  156. package/dist/resources/migrations/progress.js +71 -10
  157. package/dist/resources/migrations/runner.js +212 -18
  158. package/dist/resources/migrations/state.js +36 -1
  159. package/dist/resources/migrations/status.js +2 -13
  160. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  161. package/dist/resources/migrations/types.js +26 -1
  162. package/dist/resources/migrations/visibility-backfill.js +111 -70
  163. package/dist/resources/oauth-discovery.js +0 -5
  164. package/dist/resources/object-body-guard.js +12 -5
  165. package/dist/resources/org-event-reserved.js +92 -0
  166. package/dist/resources/org-event-write-fault.js +19 -0
  167. package/dist/resources/owner-field-guard.js +1 -1
  168. package/dist/resources/owner-scoped-write-policy.js +65 -21
  169. package/dist/resources/owner-scoped-writes.js +37 -6
  170. package/dist/resources/path-id-rewrite.js +76 -0
  171. package/dist/resources/presence-internal.js +5 -5
  172. package/dist/resources/promotion-binding.js +43 -0
  173. package/dist/resources/promotion-stamp.js +124 -33
  174. package/dist/resources/protocol-context.js +189 -0
  175. package/dist/resources/record-type-kit.js +2 -4
  176. package/dist/resources/request-target.js +28 -1
  177. package/dist/resources/request-transaction.js +11 -1
  178. package/dist/resources/seed-reservation.js +1 -2
  179. package/dist/resources/semantic-retrieval-core.js +7 -6
  180. package/dist/resources/server-row-validation.js +71 -0
  181. package/dist/resources/skill-manifest.js +4 -3
  182. package/dist/resources/skill-version-write.js +384 -27
  183. package/dist/resources/skill-write-fault.js +6 -3
  184. package/dist/resources/skill-write-policy.js +2 -1
  185. package/dist/resources/soul-write-policy.js +26 -7
  186. package/dist/resources/table-helpers.js +1 -1
  187. package/dist/resources/table-subscription-policy.js +518 -85
  188. package/dist/resources/table-subscriptions.js +20 -7
  189. package/dist/resources/txn-pause-point.js +122 -5
  190. package/dist/resources/usage-recording.js +54 -46
  191. package/dist/resources/write-back.js +176 -11
  192. package/dist/resources/write-journal-context.js +5 -0
  193. package/dist/resources/write-journal.js +289 -0
  194. package/dist/src/lib/agent-id-rule.js +44 -2
  195. package/dist/src/lib/atomic-write.js +1 -1
  196. package/dist/src/lib/federation-retry-row.js +101 -0
  197. package/dist/src/lib/instruction-event-contract.js +17 -0
  198. package/dist/src/lib/memory-attributes.js +2 -0
  199. package/dist/src/lib/open-live-row.js +20 -0
  200. package/dist/src/lib/soul-scope-fields.js +26 -0
  201. package/dist/src/rem/promote-policy.js +3 -3
  202. package/dist/src/rem/scheduler.js +21 -4
  203. package/docs/access-control.md +18 -9
  204. package/docs/api-reference.md +126 -28
  205. package/docs/auth.md +40 -18
  206. package/docs/claude-code.md +3 -3
  207. package/docs/deploying-on-fabric.md +108 -0
  208. package/docs/deployment.md +17 -0
  209. package/docs/embedding-in-a-harper-app.md +16 -14
  210. package/docs/entity-vocabulary.md +3 -6
  211. package/docs/federation.md +29 -2
  212. package/docs/integrations.md +11 -11
  213. package/docs/mcp-clients.md +7 -5
  214. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  215. package/docs/notes/mcp-oauth-model2.md +6 -6
  216. package/docs/openclaw.md +1 -1
  217. package/docs/quickstart-fabric.md +2 -2
  218. package/docs/quickstart.md +3 -3
  219. package/docs/releasing.md +13 -13
  220. package/docs/rem.md +24 -3
  221. package/docs/secrets-and-keys.md +2 -2
  222. package/docs/standalone-local.md +29 -2
  223. package/docs/supply-chain-policy.md +28 -20
  224. package/docs/the-team.md +2 -2
  225. package/docs/upgrade.md +14 -0
  226. package/package.json +18 -11
  227. package/schemas/agent.graphql +3 -3
  228. package/schemas/federation.graphql +10 -7
  229. package/schemas/memory.graphql +7 -2
  230. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  231. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  232. package/dist/resources/soul-adk-guard.js +0 -68
@@ -474,8 +474,11 @@ async function skillSearch(agent, args) {
474
474
  * A thin wrapper over Memory.get() — the SAME by-id read as memory_get, under
475
475
  * the SAME read-scope gate (makeByIdReadGate → resolveReadScope): a non-admin
476
476
  * caller cannot read another agent's private skill; administrators retain
477
- * access, exactly as a private memory does. skill_get is the disclosure step after skill_search's catalog:
478
- * it returns the full procedure (`content`) + trigger + metadata.
477
+ * access, exactly as a private memory does. Non-admin reads of retained closed
478
+ * skill payloads also apply `closedSkillPayloadReadable`; a failed check
479
+ * returns 404 by id or omits the collection row. skill_get is the disclosure
480
+ * step after skill_search's catalog: it returns the full procedure
481
+ * (`content`) + trigger + metadata.
479
482
  *
480
483
  * It is a SKILL tool, not a general reader: a readable id that is NOT a skill
481
484
  * returns the same 404 as an unreadable id. Returning it would (a) make
@@ -614,13 +617,18 @@ async function memoryUpdate(agent, args) {
614
617
  }
615
618
  // ── flair#1472 memory_basement / memory_restore ──────────────────────────────
616
619
  // The user-facing archive action. `archived` is a VISIBILITY flag, not a
617
- // deletion: basementing a memory removes it from bootstrap + default search
618
- // but leaves the row, its provenance, and its history fully intact (still
619
- // retrievable via memory_get and memory_search(includeArchived:true)). Restore
620
- // is the deliberate, GLOBAL inverse — it un-retires the memory for EVERY
621
- // session, not a session-local view (that is drawers, Deliverable B, which does
622
- // not exist yet). Non-admin agent reads use Memory.get()'s owner-and-
623
- // visibility scope; administrator and trusted internal reads are unfiltered.
620
+ // deletion. Basementing retains the row and excludes it from bootstrap and
621
+ // default semantic search; the write still applies Memory.put()'s validation,
622
+ // redaction and provenance stamping. By-id retrieval remains subject to
623
+ // Memory's read checks; `includeArchived: true` removes the semantic-search
624
+ // archive filter while retaining the other retrieval filters. Restore is the
625
+ // deliberate inverse: it clears the archive state globally, not in a
626
+ // session-local view (that is drawers, Deliverable B, which does not exist
627
+ // yet); other read and retrieval conditions still apply. Non-admin agent reads
628
+ // use Memory.get()'s owner-and-visibility scope; administrator and trusted
629
+ // internal reads are unfiltered. Non-admin reads of retained closed skill
630
+ // payloads also apply `closedSkillPayloadReadable`; a failed check returns 404
631
+ // by id or omits the collection row.
624
632
  // Mutating another agent's record requires administrator or trusted internal
625
633
  // authority (Memory.put()'s stampAttribution gate).
626
634
  async function memoryBasement(agent, args) {
@@ -637,9 +645,10 @@ async function memoryBasement(agent, args) {
637
645
  updatedAt: new Date().toISOString(),
638
646
  };
639
647
  // Memory.put() stamps archivedAt when archived===true (see Memory.ts). The
640
- // content is unchanged, so the existing embedding stays valid — do NOT clear
641
- // it (clearing would force a needless re-embed and, if the embedding engine
642
- // is unavailable, would silently drop the vector).
648
+ // archive request retains the existing embedding and delegates text
649
+ // redaction and embedding handling to Memory.put() — do NOT clear it
650
+ // (clearing would force a needless re-embed and, if the embedding engine is
651
+ // unavailable, would silently drop the vector).
643
652
  if (agent.clientId)
644
653
  merged.claimedClient = agent.clientId;
645
654
  // flair#2541 — the write path redacts the row it re-puts; report the stored
@@ -679,7 +688,9 @@ async function memoryGet(agent, args) {
679
688
  // `RequestTarget` (never a bare string), and still dispatches through
680
689
  // Memory.get() → makeByIdReadGate → resolveReadScope, so the scope model is
681
690
  // unchanged: non-admin agents can read their own and other agents'
682
- // non-private records; administrator reads are unfiltered. See
691
+ // non-private records; administrator reads are unfiltered. Non-admin reads of
692
+ // retained closed skill payloads also apply `closedSkillPayloadReadable`; a
693
+ // failed check returns 404 by id or omits the collection row. See
683
694
  // resources/in-process.ts:223.
684
695
  //
685
696
  // flair#744 slice 1 — opt-in inline trust block. The instance call passed
@@ -736,10 +747,8 @@ async function bootstrap(agent, args) {
736
747
  // ONLY when requested so a plain bootstrap delegates a byte-identical body.
737
748
  if (args?.abstain === true)
738
749
  body.abstain = true;
739
- // flair#1199 — org-event knobs. `includeEventDetail` opts the verbose per-event
740
- // `detail` JSON back in (default OFF: a connector reads lean events); `maxEvents`
741
- // overrides the default cap. Both forwarded ONLY when set, so a plain bootstrap
742
- // delegates a byte-identical body.
750
+ // flair#1199 — `includeEventDetail` opts ordinary event detail in;
751
+ // `maxEvents` overrides the default cap.
743
752
  if (args?.includeEventDetail === true)
744
753
  body.includeEventDetail = true;
745
754
  if (args?.maxEvents !== undefined)
@@ -1148,8 +1157,7 @@ export const TOOLS = bindNativeTools({
1148
1157
  { path: "events", type: "array" }, { path: "sections", type: "object" },
1149
1158
  { path: "skills", type: "array" }, { path: "skillDiagnostics", type: "array" }, // #2141
1150
1159
  ],
1151
- // #1200 — dedup by the SEMANTIC content key (excludes id/createdAt, which
1152
- // vary across physical duplicate rows). See ToolInvariants.dedupSignature.
1160
+ // #1200 — content dedup; instruction events use refId in the checker.
1153
1161
  dedupSignature: { container: "events", signatureFields: ["kind", "summary", "detail", "targetIds"] },
1154
1162
  // #1199 — tokenEstimate via the wrapper's own estimator over the delivered
1155
1163
  // payload (minus the two fields added after it was measured).
@@ -1296,7 +1304,37 @@ export const TOOLS = bindNativeTools({
1296
1304
  },
1297
1305
  },
1298
1306
  });
1299
- /** The tool definitions for a tools/list response (exactly the 18 curated tools). */
1300
- export function listToolDefs() {
1301
- return Object.values(TOOLS).map((t) => t.def);
1307
+ /**
1308
+ * `tools/list` gates: a tool named here is advertised only to a caller this
1309
+ * predicate admits. `soul_set`'s predicate is the soul write policy's
1310
+ * source-authorization step (resources/soul-write-policy.ts), evaluated on the
1311
+ * same delegation context `soulSet` builds; `Soul.post` applies its content
1312
+ * guards after that step. The policy module links harper's `databases` at module
1313
+ * top, so it is imported lazily — same reason as the handlers above.
1314
+ */
1315
+ const LIST_GATES = {
1316
+ soul_set: async (agent) => {
1317
+ const { soulWriteAllowed } = await import("./soul-write-policy.js");
1318
+ return soulWriteAllowed(delegationContext(agent));
1319
+ },
1320
+ };
1321
+ for (const name of Object.keys(LIST_GATES)) {
1322
+ if (!Object.prototype.hasOwnProperty.call(TOOLS, name)) {
1323
+ throw new Error(`tools/list gate names a tool that is not in TOOLS: ${name}`);
1324
+ }
1325
+ }
1326
+ /**
1327
+ * The tool defs `tools/list` returns for `agent`: every `TOOLS` entry whose gate
1328
+ * (if any) admits this caller. `agent` is null for a caller whose token subject
1329
+ * resolved to no principal; that caller gets no gated tool.
1330
+ */
1331
+ export async function listToolDefs(agent) {
1332
+ const defs = [];
1333
+ for (const [name, entry] of Object.entries(TOOLS)) {
1334
+ const gate = LIST_GATES[name];
1335
+ if (gate && !(agent && (await gate(agent))))
1336
+ continue;
1337
+ defs.push(entry.def);
1338
+ }
1339
+ return defs;
1302
1340
  }
@@ -73,6 +73,7 @@ export function stripUndeclaredMemoryAttributes(content) {
73
73
  * originator's value.
74
74
  */
75
75
  export const SERVER_STAMPED_MEMORY_FIELDS = Object.freeze([
76
+ "writeBackWriteId",
76
77
  "instanceToken",
77
78
  "provenance",
78
79
  "skillSubjectId",
@@ -86,3 +86,59 @@ export function embeddedHashMatches(row) {
86
86
  const expected = embeddedTextHash(row);
87
87
  return typeof expected === "string" && recorded === expected;
88
88
  }
89
+ /** Relative element-wise tolerance for {@link holdsOwnStaleVector}. The staged
90
+ * vector is the embedding provider's output as `getEmbedding` returns it; no
91
+ * code here bounds or normalizes its components, so the comparison scales
92
+ * with magnitude: two finite components match when
93
+ * `|stored - staged| <= 1e-6 * max(1, |stored|, |staged|)`.
94
+ * - At magnitude 1 and above the relative term applies. Rounding a
95
+ * normal-range float32 value changes it by at most 2^-24 (about 6e-8) of
96
+ * its magnitude, so a stored copy that went through float32 matches.
97
+ * - Below magnitude 1 the absolute floor of 1e-6 applies, and that floor is
98
+ * what accepts the round trip there: a subnormal float32 value such as
99
+ * 1e-45 rounds with a large relative error (about 40%) but an absolute
100
+ * error far inside 1e-6.
101
+ * - A non-finite component on either side never matches: a value beyond
102
+ * float32 range rounds to Infinity, and NaN equals nothing. */
103
+ const STAGED_VECTOR_RELATIVE_TOLERANCE = 1e-6;
104
+ /** One component of {@link holdsOwnStaleVector}'s comparison: both components
105
+ * finite, and within the tolerance above. */
106
+ function matchesStagedComponent(stored, staged) {
107
+ if (!Number.isFinite(stored) || !Number.isFinite(staged))
108
+ return false;
109
+ return Math.abs(stored - staged) <= STAGED_VECTOR_RELATIVE_TOLERANCE * Math.max(1, Math.abs(stored), Math.abs(staged));
110
+ }
111
+ /**
112
+ * True when the row's stored vector matches `staged.embedding` element by
113
+ * element within {@link STAGED_VECTOR_RELATIVE_TOLERANCE} while the row's current
114
+ * embedding text (`skillEmbedText`) is not `staged.text`. A match means the row
115
+ * holds a vector equal, within that tolerance, to the one this writer computed
116
+ * for `staged.text`, a text the row no longer has, so the caller re-embeds the
117
+ * current text. It is evidence that the stored vector matches this writer's
118
+ * computation, not proof of which writer stored it, and it assumes nothing
119
+ * about how far apart the vectors of different texts are. The stored
120
+ * `embeddedContentHash` is not consulted: it is null for a row with an empty
121
+ * owner and so would match any text. Returns false when nothing was staged,
122
+ * when the row's text is still `staged.text`, or when the stored vector does
123
+ * not match. A non-match says nothing about the vector's provenance; it only
124
+ * means this staged-vector exception does not apply, and the caller's normal
125
+ * eligibility decides whether the row is written: the embedding backfill writes
126
+ * a missing vector or one of at most 100 entries and skips a longer one; the
127
+ * embedding-stamp migration re-embeds a row whose stamp is not current or whose
128
+ * stored hash does not match its text, whatever vector it holds.
129
+ */
130
+ export function holdsOwnStaleVector(row, staged) {
131
+ if (!staged || !row || typeof row !== "object")
132
+ return false;
133
+ if (skillEmbedText(row) === staged.text)
134
+ return false;
135
+ const stored = row.embedding;
136
+ if (stored == null || typeof stored.length !== "number" || stored.length !== staged.embedding.length)
137
+ return false;
138
+ for (let i = 0; i < staged.embedding.length; i++) {
139
+ const value = stored[i];
140
+ if (typeof value !== "number" || !matchesStagedComponent(value, staged.embedding[i]))
141
+ return false;
142
+ }
143
+ return true;
144
+ }
@@ -65,6 +65,9 @@ export function buildPointerRow(args) {
65
65
  function pointerTable() {
66
66
  return databases.flair?.[MEMORY_HOST_SOURCE_TABLE];
67
67
  }
68
+ export function isMemoryHostSourceStore(store) {
69
+ return store != null && pointerTable()?.primaryStore === store;
70
+ }
68
71
  /**
69
72
  * flair#1940 A1'' item 6 (adjudication B, hardened in round 5/adjudication 0e)
70
73
  * — is an incoming hostSource an ECHO of the STORED pointer? Preservation (do
@@ -171,8 +174,8 @@ export async function projectRowsThroughPointers(rows, readerAgentId) {
171
174
  }
172
175
  /** Read ONE stored pointer row (the write path's echo check). Kept here so the
173
176
  * MemoryHostSource table is touched ONLY by this module. */
174
- export async function loadStoredPointer(memoryId) {
175
- return (await loadPointerRows([memoryId])).get(memoryId) ?? null;
177
+ export async function loadStoredPointer(memoryId, context) {
178
+ return (await loadPointerRows([memoryId], context)).get(memoryId) ?? null;
176
179
  }
177
180
  /** The Memory attributes that would carry a pointer into an inbound federated
178
181
  * row (A1' item 5). A record carrying any of these is refused, not merged. */
@@ -168,7 +168,7 @@ export function resolveCandidateVisibilityRuling(candidate) {
168
168
  //
169
169
  // Passed as `responseFormat: { schema: CANDIDATES_SCHEMA }` to models.generate()
170
170
  // so backends that honor structured output (Ollama, OpenAI — verified against
171
- // the pinned harper 5.1.17's bundled backends) return conformant
171
+ // harper 5.1.17's bundled backends) return conformant
172
172
  // JSON directly. Not every backend enforces it (Anthropic's Messages API has
173
173
  // no equivalent and Harper documents that it silently ignores the option) —
174
174
  // this module never trusts the backend to have enforced the schema; every
@@ -1,19 +1,38 @@
1
1
  /**
2
2
  * memory-write-lock.ts — the per-memory-id write serialization protocol
3
- * (flair#2478 slice 1). The ordinary owner PUT and PATCH (resources/Memory.ts)
4
- * run under it; the other Memory writers convert in part 2.
3
+ * (flair#2478 slice 1). The ordinary owner PUT and PATCH (resources/Memory.ts,
4
+ * the HTTP re-embed PATCH included), the owner DELETE (with a skill row's live
5
+ * head) and an untagged owner POST naming an id or a `supersedes` target
6
+ * (slice 1 part 2) run under it, and so do the automatic
7
+ * writers converted so far: the visibility backfill and the promotion stamps
8
+ * (slice 2), the embedding backfill that follows a Memory write signed by a
9
+ * verified Ed25519 agent (resources/auth-middleware.ts), the embedding-stamp
10
+ * migration's `.content`-suffix fallback (slice 3), the synthetic CI
11
+ * migration's re-stamp of its own rows, and the operator purge
12
+ * (resources/MemoryPurge.ts, whole target set) (slice 3b); the maintenance
13
+ * archive/expiry action (resources/MemoryMaintenance.ts) and the usage-count
14
+ * writer (resources/usage-recording.ts) (slice 3b part 1); the ordinary
15
+ * (non-skill) feed write-back and the feed dedup repair
16
+ * (resources/MemoryFeed.ts), skill-tagged `POST /FeedMemories` writes
17
+ * and both `lastReflected` stamps
18
+ * (resources/Memory.ts's derivedFrom sources and resources/MemoryReflect.ts's
19
+ * gathered sources) (slice 3b part 2); and the federation merge of an
20
+ * incoming Memory row (resources/Federation.ts) and the batch reindex writer
21
+ * (resources/MemoryReindex.ts) (slice 3c); and basement/restore of a
22
+ * non-skill row (resources/MemoryArchive.ts, through the checked write below)
23
+ * (slice 1 part 3a); and the Memory skill-version create/update writes
24
+ * (flair#2950); a fresh skill POST with a server-allocated id takes no per-id
25
+ * lock. The other Memory writers convert in later parts.
5
26
  *
6
27
  * A writer that must make its read, decision and write on one committed basis
7
28
  * runs under one key per ID of `Memory.primaryStore`'s lock: `["memory", fullStoredId]`.
8
29
  * Within one Harper process the lock is per key and shared by its threads
9
30
  * (resources/key-lock.ts). A caller opens and settles its owned transaction
10
- * inside the callback, so the key is held across the commit. Two PUT paths can
11
- * join a transaction they do not own, which then commits after the put returns
12
- * and so after the key is released: a put composed into its caller's
13
- * transaction (manual promotion, via withComposedWriteTransaction in
14
- * resources/request-transaction.ts), and the admin `_reindex` re-PUT when the
15
- * request carries an open transaction, which it joins as it did before the lock
16
- * (with none open, it owns its transaction and commits before the release).
31
+ * inside the callback, so the key is held across the commit. A put composed
32
+ * into its caller's transaction (manual promotion, via
33
+ * withComposedWriteTransaction in resources/request-transaction.ts) joins a
34
+ * transaction it does not own, which then commits after the put returns and so
35
+ * after the key is released.
17
36
  *
18
37
  * A same-id writer that finds the key held waits and retries within its budget
19
38
  * ({@link MEMORY_LOCK_ATTEMPTS} attempts with a {@link MEMORY_LOCK_WAIT_MS} ms
@@ -24,10 +43,10 @@
24
43
  * below, even while the key is held). A writer that then opens a new owned
25
44
  * transaction (the ordinary PUT and PATCH) reads the row as stored at that
26
45
  * moment: the holder's committed row when the holder owned its transaction (a
27
- * composed or `_reindex` holder that joined another transaction may release
28
- * before that transaction commits). A composed or `_reindex` writer that joins
29
- * an already-open request transaction reads from that transaction's snapshot
30
- * instead, which can predate the acquisition. Otherwise it is refused:
46
+ * composed holder that joined another transaction may release before that
47
+ * transaction commits). A composed writer that joins an already-open request
48
+ * transaction reads from that transaction's snapshot instead, which can
49
+ * predate the acquisition. Otherwise it is refused:
31
50
  *
32
51
  * - `503 memory_busy` — the key stayed held for the whole budget. Nothing was
33
52
  * written, so the request can be sent again unchanged. The body carries the
@@ -45,7 +64,19 @@
45
64
  * row that already holds it as written. {@link markMemoryWriteOutcomeUnknown}
46
65
  * records the marker; until a process restart clears it (the fencing step),
47
66
  * PUT/PATCH check the addressed id; DELETE also checks the resolved skill
48
- * head. POST and background/nested writers do not check the marker.
67
+ * head. An automatic writer that takes the lock through
68
+ * {@link withMemoryWriteLockOnce} writes nothing to a marked id; the feed
69
+ * write-back and the feed dedup repair record the marker when storage
70
+ * withholds their write result, the skill-tagged feed write when storage
71
+ * withholds its write result, its rollback could not be confirmed or its
72
+ * refusal body has no readable error code, and the dedup
73
+ * repair also when its committed
74
+ * update's confirmation read fails or does not show the update, while the
75
+ * other automatic writers do not set it for their own unconfirmed write,
76
+ * which they report or log. A marker names only an id the attempt attempted
77
+ * to write (`attemptedWriteIds`), not every id its acquisition held.
78
+ * A POST that takes the lock checks the ids it locks; a POST that takes
79
+ * none, and the writers that take no per-id lock, do not check the marker.
49
80
  *
50
81
  * The marker is module state, so it is per Harper worker thread. That covers
51
82
  * the whole instance only in the supported single-worker mode: flair refuses to
@@ -56,13 +87,15 @@
56
87
  * worker is not seen by another.
57
88
  *
58
89
  * The critical section contains the write paths' embedding calls — the ordinary
59
- * PUT's regen (and its create-path dedup probe), the re-embed PATCH's compute
60
- * and its recompute, and the PATCH embedding refresh — and each is bounded by
90
+ * PUT's regen (and its create-path dedup probe), a locked POST's dedup probe
91
+ * and embedding, the re-embed PATCH's compute and its recompute, and the PATCH
92
+ * embedding refresh — and each is bounded by
61
93
  * {@link MEMORY_LOCKED_PROVIDER_TIMEOUT_MS} through {@link boundLockedProviderCall};
62
94
  * a call still pending when the timeout callback runs, or one that settles after
63
95
  * the bound, is refused with `503 memory_provider_timeout` and nothing is
64
96
  * written. An in-process timeout cannot preempt a provider that never yields the
65
- * event loop. A hold longer than
97
+ * event loop. The automatic embedding writers compute their vector before they
98
+ * take the lock, so they make no provider call while holding it. A hold longer than
66
99
  * {@link MEMORY_LOCK_HOLD_WATCHDOG_MS} is logged — the lock keys and the phase
67
100
  * named in {@link MemoryWriteLockOptions.phase}, and elapsed time — when the
68
101
  * timer runs or the callback settles. The watchdog never releases a key.
@@ -76,6 +109,17 @@
76
109
  * Acquisition is sorted and deduplicated, so two writers that share ids take
77
110
  * them in the same order. A partial acquisition is released before the wait, so
78
111
  * a writer never blocks on the next key while holding one.
112
+ *
113
+ * The lock token (flair#2478 part 3a). The callback receives a
114
+ * {@link MemoryWriteLockToken}, minted after every key of the call is held. Its
115
+ * state lives in a registry private to this module: the store it was acquired
116
+ * on, the sorted ids, the acquisition and whether it is live. A copied or
117
+ * fabricated object is not in the registry, so it is refused. A checked Memory
118
+ * write (resources/Memory.ts `putMemoryWithLock` / `patchMemoryWithLock`)
119
+ * requires a live token for the store and every id it writes, and runs inside
120
+ * the locked transaction scope of resources/memory-write-transaction.ts. When
121
+ * the callback settles, the acquisition closes to new scopes, waits for a scope
122
+ * still open to settle, revokes the token, and only then releases the keys.
79
123
  */
80
124
  import { TEST_FAULT_INJECTION_ENV } from "./txn-pause-point.js";
81
125
  /** The `Memory.primaryStore` key namespace (flair#2478). */
@@ -179,6 +223,108 @@ export function memoryWriteOutcomeUnknown(id) {
179
223
  export function resetMemoryWriteOutcomeUnknownForTest(id) {
180
224
  outcomeUnknown.delete(String(id));
181
225
  }
226
+ /** A checked write or a locked transaction scope was refused its capability. */
227
+ export class MemoryWriteCapabilityError extends Error {
228
+ reason;
229
+ constructor(reason, message) {
230
+ super(`memory write capability refused (${reason}): ${message}`);
231
+ this.reason = reason;
232
+ this.name = "MemoryWriteCapabilityError";
233
+ }
234
+ }
235
+ /** The registry: the authoritative state of every token this module minted. */
236
+ const tokens = new WeakMap();
237
+ function mintToken(store, ids) {
238
+ const token = Object.freeze(Object.create(null));
239
+ const frozen = Object.freeze([...ids]);
240
+ tokens.set(token, {
241
+ store, ids: frozen, idSet: new Set(frozen), acquisition: Object.freeze({}), live: true, admitting: true, open: null,
242
+ });
243
+ return token;
244
+ }
245
+ function tokenState(held) {
246
+ const state = held !== null && typeof held === "object" ? tokens.get(held) : undefined;
247
+ if (!state)
248
+ throw new MemoryWriteCapabilityError("not_a_token", "not a lock token issued by this registry");
249
+ return state;
250
+ }
251
+ /**
252
+ * Refuse `held` unless it is a live token from this registry, acquired on
253
+ * `expected.store` (when given) and covering every id in `expected.ids` (when
254
+ * given). Throws {@link MemoryWriteCapabilityError}.
255
+ */
256
+ export function assertMemoryWriteLockToken(held, expected = {}) {
257
+ const state = tokenState(held);
258
+ if (!state.live)
259
+ throw new MemoryWriteCapabilityError("revoked", "the lock token's acquisition has been released");
260
+ if ("store" in expected && expected.store !== state.store) {
261
+ throw new MemoryWriteCapabilityError("wrong_store", "the lock token was acquired on another store");
262
+ }
263
+ for (const id of expected.ids ?? []) {
264
+ if (!state.idSet.has(String(id))) {
265
+ throw new MemoryWriteCapabilityError("id_not_covered", "the write names an id the lock token does not hold");
266
+ }
267
+ }
268
+ }
269
+ /** The sorted ids a token holds (read from the registry). Throws for a non-token. */
270
+ export function memoryWriteLockTokenIds(held) {
271
+ return tokenState(held).ids;
272
+ }
273
+ /** The identity of the acquisition a token belongs to (read from the registry). */
274
+ export function memoryWriteLockAcquisition(held) {
275
+ return tokenState(held).acquisition;
276
+ }
277
+ /**
278
+ * Admit one locked transaction scope on a live token's acquisition
279
+ * (resources/memory-write-transaction.ts). Synchronous, so the acquisition
280
+ * knows about the scope before the scope's first suspension. One scope is open
281
+ * at a time; none is admitted after the callback has settled. The returned
282
+ * `settle` reports how the scope ended.
283
+ */
284
+ export function admitLockedScope(held) {
285
+ assertMemoryWriteLockToken(held);
286
+ const state = tokenState(held);
287
+ if (!state.admitting)
288
+ throw new MemoryWriteCapabilityError("revoked", "the lock callback has settled");
289
+ if (state.open)
290
+ throw new MemoryWriteCapabilityError("scope_open", "a locked transaction is already open on this acquisition");
291
+ let settle;
292
+ const open = new Promise((resolve) => { settle = resolve; });
293
+ state.open = open;
294
+ let settled = false;
295
+ return {
296
+ settle(failure) {
297
+ if (settled)
298
+ return;
299
+ settled = true;
300
+ if (state.open === open)
301
+ state.open = null;
302
+ settle(failure ? { ok: false, error: failure.error } : { ok: true });
303
+ },
304
+ };
305
+ }
306
+ /**
307
+ * Close the acquisition to new scopes, wait for a scope still open to settle,
308
+ * then revoke the token. With `propagate`, a failure or refusal of a scope
309
+ * that was still open when the callback settled is thrown (the callback did
310
+ * not await it); a refusal arrives as a `LockedScopeRefusedError`.
311
+ */
312
+ async function settleAcquisition(held, propagate) {
313
+ const state = tokens.get(held);
314
+ state.admitting = false;
315
+ const open = state.open;
316
+ const settlement = open ? await open : { ok: true };
317
+ state.live = false;
318
+ if (propagate && !settlement.ok)
319
+ throw settlement.error;
320
+ }
321
+ function revokeToken(held) {
322
+ const state = tokens.get(held);
323
+ if (state) {
324
+ state.admitting = false;
325
+ state.live = false;
326
+ }
327
+ }
182
328
  /** The sorted, deduplicated ids and their lock keys. */
183
329
  function normalizeIds(ids) {
184
330
  const seen = new Set();
@@ -214,9 +360,22 @@ function releaseAll(lock, acquired) {
214
360
  export async function withMemoryWriteLock(store, ids, fn, options = {}) {
215
361
  return acquire(lockStore(store), normalizeIds(ids), MEMORY_LOCK_ATTEMPTS, MEMORY_LOCK_WAIT_MS, fn, options);
216
362
  }
217
- /** One attempt, no wait. No writer calls it yet: it is the shape part 2's
218
- * automatic writers take (flair#2478). A held lock or a marker answers
219
- * `busy`/`unknown`. */
363
+ /** One attempt, no wait, per call; a writer that retries calls it again and
364
+ * acquires again. Used by the automatic writers: the visibility
365
+ * backfill, the automatic promotion stamp, the embedding backfill, the
366
+ * embedding-stamp migration's `.content`-suffix fallback, the synthetic CI
367
+ * migration's re-stamp, the maintenance archive/expiry action, the
368
+ * usage-count writer, the feed dedup repair, both `lastReflected` stamps,
369
+ * the federation merge of a Memory row and the batch
370
+ * reindex writer. A held lock or a
371
+ * marker answers `busy`/`unknown`; that attempt of the writer writes nothing
372
+ * (an earlier attempt of the same call may have; each writer logs that).
373
+ * Whether the id is visited again is each writer's own rule (a later scan
374
+ * decides whether a migration row is still stale; the embedding backfill runs
375
+ * again only after the id's next successful HTTP Memory POST, PUT or PATCH
376
+ * signed by a verified Ed25519 agent, the requests that reach the auth
377
+ * middleware's post-response hook; a Basic-admin write starts none; a later
378
+ * federation re-offer or reindex run retries the row). */
220
379
  export async function withMemoryWriteLockOnce(store, ids, fn, options = {}) {
221
380
  return acquire(lockStore(store), normalizeIds(ids), 1, 0, fn, options);
222
381
  }
@@ -242,7 +401,6 @@ function startHoldWatchdog(keys, phase) {
242
401
  async function acquire(lock, normalized, attempts, waitMs, fn, options = {}) {
243
402
  if (!lock || normalized.keys.length === 0)
244
403
  return { kind: "unavailable" };
245
- const scope = { keys: normalized.keys, ids: normalized.ids };
246
404
  const acquired = [];
247
405
  for (let attempt = 0; attempt < attempts; attempt++) {
248
406
  const marked = normalized.ids.find((id) => memoryWriteOutcomeUnknown(id));
@@ -259,15 +417,25 @@ async function acquire(lock, normalized, attempts, waitMs, fn, options = {}) {
259
417
  }
260
418
  if (gotAll) {
261
419
  const watchdog = startHoldWatchdog(normalized.keys, options.phase ?? "unknown");
420
+ // The token is minted only now, with every key of the call held.
421
+ const scope = mintToken(lock, normalized.ids);
422
+ let settled = false;
262
423
  try {
263
424
  lock.resetReadTxn?.();
264
425
  // The marker was checked at the top of this attempt; nothing between
265
426
  // that check and here yields, so it cannot have changed.
266
- return { kind: "done", value: await fn(scope) };
427
+ const outcome = { kind: "done", value: await fn(scope) };
428
+ settled = true;
429
+ await settleAcquisition(scope, true);
430
+ return outcome;
267
431
  }
268
432
  finally {
433
+ if (!settled)
434
+ await settleAcquisition(scope, false);
435
+ revokeToken(scope);
269
436
  watchdog();
270
- // Release only after `fn` returns. A callback that owns its transaction
437
+ // Release only after `fn` returns and any locked transaction scope on
438
+ // this acquisition has settled. A callback that owns its transaction
271
439
  // has settled it by then, so the lock spans that commit; a transaction
272
440
  // the callback only joined commits later, after this release.
273
441
  releaseAll(lock, acquired);
@@ -291,6 +459,7 @@ export function memoryBusyResponse(callerId) {
291
459
  export function writeOutcomeUnknownResponse() {
292
460
  return new Response(JSON.stringify({
293
461
  error: WRITE_OUTCOME_UNKNOWN_ERROR,
462
+ outcome: "unconfirmed",
294
463
  message: "the write outcome is unknown. Read the affected row before writing again.",
295
464
  }), { status: 503, headers: { "content-type": "application/json" } });
296
465
  }
@@ -308,3 +477,13 @@ export function memoryLockUnavailableResponse() {
308
477
  message: "this instance's Memory store has no per-id write lock, so the write was refused; nothing was written",
309
478
  }), { status: 503, headers: { "content-type": "application/json" } });
310
479
  }
480
+ /** Map a lock outcome to its refusal `Response`, or `null` when the verb ran. */
481
+ export function memoryLockRefusal(outcome, callerId) {
482
+ if (outcome.kind === "busy")
483
+ return memoryBusyResponse(callerId);
484
+ if (outcome.kind === "unknown")
485
+ return writeOutcomeUnknownResponse();
486
+ if (outcome.kind === "unavailable")
487
+ return memoryLockUnavailableResponse();
488
+ return null;
489
+ }
@@ -110,7 +110,7 @@ export const FEED_FIELD_RULES = Object.freeze({
110
110
  agentId: STRING, content: STRING, contentHash: STRING, trigger: STRING, visibility: STRING,
111
111
  durability: STRING, source: STRING, type: STRING, createdAt: STRING, updatedAt: STRING,
112
112
  instanceToken: STRING, expiresAt: STRING, retrievalCount: INTEGER, lastRetrieved: STRING, usageCount: INTEGER,
113
- promotionStatus: STRING, promotedAt: STRING, promotedBy: STRING, archived: BOOLEAN, archivedAt: STRING,
113
+ promotionStatus: STRING, promotedAt: STRING, promotedBy: STRING, promotionContentHash: STRING, archived: BOOLEAN, archivedAt: STRING,
114
114
  archivedBy: STRING, parentId: STRING, sessionId: STRING, lastReflected: STRING,
115
115
  supersedes: STRING, subject: STRING, summary: STRING, validFrom: STRING, validTo: STRING,
116
116
  provenance: STRING, originatorInstanceId: STRING, metadata: STRING, skillSubjectId: STRING,