@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
@@ -2,10 +2,10 @@ import { Resource, databases } from "harper";
2
2
  import { allowVerified, resolveAgentAuth } from "./agent-auth.js";
3
3
  import { getEmbedding } from "./embeddings-provider.js";
4
4
  import { wrapUntrusted } from "./content-safety.js";
5
- import { isTeammate, formatTeamLine, isZeroRowNoOpEvent } from "./memory-bootstrap-lib.js";
5
+ import { isTeammate, directoryHint, isZeroRowNoOpEvent } from "./memory-bootstrap-lib.js";
6
6
  import { resolveReadScope } from "./memory-read-scope.js";
7
7
  import { isValidEntity } from "./entity-vocab.js";
8
- import { withDetachedTxn } from "./table-helpers.js";
8
+ import { withDetachedTxn, withDetachedTxnAsync } from "./table-helpers.js";
9
9
  import { getPresenceRoster } from "./presence-internal.js";
10
10
  import { buildCollisionEntries, buildEntityMatchCondition, freshPresenceByAgent, } from "./collision-lib.js";
11
11
  // The bounded HNSW candidate-pool retrieval for the task-relevant/teammate/
@@ -16,13 +16,19 @@ import { buildCollisionEntries, buildEntityMatchCondition, freshPresenceByAgent,
16
16
  // semantic-retrieval-core.ts's module doc for the full boundary).
17
17
  import { retrieveCandidates, DEFAULT_SELECT } from "./semantic-retrieval-core.js";
18
18
  import { retrievalMode } from "./bm25.js";
19
+ import { embeddingSpaceVerdict, spaceGuardWarning } from "./embedding-space-guard.js";
19
20
  import { buildTrustBlock } from "./trust-block.js";
21
+ import { projectRowsThroughPointers } from "./memory-host-source.js";
22
+ import { formatHostSourceCitation } from "./host-source-citation.js";
20
23
  import { bestSemanticSimilarity, evaluateAbstention } from "./abstention.js";
21
24
  import { estimateTokens } from "./token-estimate.js";
22
25
  import { initialPosition, ORG_EVENT_STREAM } from "./agent-read-position-lib.js";
23
26
  import { defaultReadPositionTable, ensureReadPosition } from "./agent-read-position.js";
24
27
  import { catchupSeekTimestamp, isCatchupEligible } from "./org-event-catchup-lib.js";
25
- import { resolveActiveSkills } from "./skill-provenance.js";
28
+ import { SKILL_ASSIGNMENT_KEY } from "./skill-provenance.js";
29
+ import { SKILL_TAG } from "./skill-write.js";
30
+ import { SKILL_ROW_SELECT, receivesOrgSkills, resolvableSkillRows, resolveSkillManifest, skillLine, } from "./skill-manifest.js";
31
+ import { localInstanceId } from "./instance-identity.js";
26
32
  /**
27
33
  * POST /MemoryBootstrap
28
34
  *
@@ -82,13 +88,15 @@ import { resolveActiveSkills } from "./skill-provenance.js";
82
88
  * { context, sections, tokenEstimate, maxTokens, memoriesIncluded, memoriesAvailable,
83
89
  * memoriesTruncated, teammateFindingsIncluded, teammateFindingsTruncated,
84
90
  * teammateFindingsMatched, agentId, scope, soul, memories, predicted,
85
- * teammateFindings, events, soulTokens, memoryTokens, trustTokens,
86
- * eventsTokens, scaffoldTokens[, currentTaskHint][, taskRetrievalHint][, predictedHint] }
91
+ * teammateFindings, events, skills, skillDiagnostics, skillsTruncated,
92
+ * skillDiagnosticsTruncated, soulTokens, memoryTokens, trustTokens,
93
+ * eventsTokens, skillsTokens, skillDiagnosticsTokens, scaffoldTokens
94
+ * [, currentTaskHint][, taskRetrievalHint][, predictedHint] }
87
95
  *
88
96
  * TOKEN LEDGER (flair#1270): the counters decompose `tokenEstimate` from the
89
97
  * payload alone —
90
98
  * tokenEstimate ≈ scaffoldTokens + soulTokens + memoryTokens + trustTokens
91
- * + eventsTokens
99
+ * + eventsTokens + skillsTokens + skillDiagnosticsTokens
92
100
  * Each figure is measured from what SHIPS (never derived as a residual), so
93
101
  * a section that ships uncounted content breaks the identity visibly instead
94
102
  * of hiding in an unexplained gap. See the ledger block in the response tail
@@ -262,16 +270,14 @@ const MAX_CANDIDATE_POOL = 100;
262
270
  // record's own agentId differs from the bootstrapping agent), so
263
271
  // `m._source !== agentId` is the "is this a teammate's finding" check; own
264
272
  // memories never carry `_source` at all.
265
- function formatMemory(m, agentId) {
266
- // flair#1940 A1' item 5: bootstrap does NOT render pointers in this slice.
267
- // The pointer lives in MemoryHostSource and is joined only into Memory.get/
268
- // search/SemanticSearch results; the bootstrap citation (A6) arrives in slice
269
- // 4. So this surface leaves the record unchanged.
273
+ export function formatMemory(m, agentId) {
274
+ // flair#1940 A6: when the gated pointer join ran, `m.hostSource` is its output.
270
275
  const tag = m.durability === "permanent" ? "🔒" : m.durability === "persistent" ? "📌" : "📝";
271
276
  const date = m.createdAt ? ` (${m.createdAt.slice(0, 10)})` : "";
272
277
  const chain = m.supersedes ? " [supersedes earlier decision]" : "";
273
278
  const attribution = m._source && m._source !== agentId ? `[via ${m._source}] ` : "";
274
- const base = `${tag} ${attribution}${m.content}${date}${chain}`;
279
+ const citation = formatHostSourceCitation(m.hostSource);
280
+ const base = `${tag} ${attribution}${m.content}${date}${chain}${citation ? ` ${citation}` : ""}`;
275
281
  // Wrap flagged memories in safety delimiters — composes with attribution
276
282
  // above (attribution is baked into `base` before wrapping, so a flagged
277
283
  // teammate memory renders with BOTH the "[via <agent>]" tag and the
@@ -454,6 +460,17 @@ export class BootstrapMemories extends Resource {
454
460
  let eventWatermark = null;
455
461
  let eventsHasMore = false;
456
462
  let eventsRemaining = 0;
463
+ // flair#2448 item 3 (decision) — the STRUCTURED container deliberately
464
+ // carries NO host-source pointer: no `hostSource`, `hostSourceScope` or
465
+ // `hostSourceVisibility`. The pointer is a citation aid for the agent-facing
466
+ // RENDERED bootstrap (formatMemory's prose line); a non-admin structured
467
+ // consumer that needs the pointer reads the memory back through the gated
468
+ // Memory read (memory_get by id), which renders the pointer that caller may
469
+ // see. An admin Memory read takes no pointer join (Memory.ts), so it does not
470
+ // render the pointer either. The admin
471
+ // bootstrap's containers fall under the same rule (see hostSourceReader
472
+ // below). A test pins those three pointer fields absent here, so adding one
473
+ // is a deliberate change.
457
474
  const leanMemory = (m, section) => ({
458
475
  id: m.id,
459
476
  content: m.content,
@@ -494,6 +511,34 @@ export class BootstrapMemories extends Resource {
494
511
  // selector tests against maxTokens is now the figure that becomes
495
512
  // `tokenEstimate` on each path.
496
513
  const contentCost = (structured, proseLine) => includeContext ? estimateTokens(proseLine) : estimateTokens(JSON.stringify(structured));
514
+ // flair#1940 A3/A6 (slice 2b) — the gated pointer join for the prose surface.
515
+ // A non-admin caller sees a bound pointer only through the join: their OWN
516
+ // records render their pointer, a teammate's author-only pointer renders
517
+ // `"withheld"` (A3), and everything else is unchanged. An admin/operator
518
+ // bootstrap stays unfiltered and takes no join — the same exception the
519
+ // named read surfaces take. ONE batched pointer query per row set, never
520
+ // one per row. The retrieved rows (DEFAULT_SELECT) carry every binding field
521
+ // (`agentId`, `instanceToken`, `visibility`, `archived`). The own-record
522
+ // sections (OWN_SELECT) carry `agentId` and `instanceToken` only: their query
523
+ // already excludes archived rows, and the reader is the author, so the author
524
+ // outcome never reads `visibility`.
525
+ // flair#2448 item 3 (decision) — an admin bootstrap takes no join, and the
526
+ // structured containers are built without the pointer (see leanMemory), so
527
+ // neither the admin prose nor any structured container carries the host
528
+ // source. A non-admin structured consumer that needs the pointer reads the
529
+ // memory back through the gated Memory read (memory_get by id); an admin
530
+ // Memory read takes no pointer join, so it does not render the pointer.
531
+ const hostSourceReader = authenticatedAgent && !callerIsAdmin ? authenticatedAgent : undefined;
532
+ const pointerRenders = async (rows) => {
533
+ const map = new Map();
534
+ if (!hostSourceReader || rows.length === 0)
535
+ return map;
536
+ for (const row of await projectRowsThroughPointers(rows, hostSourceReader)) {
537
+ if (row && typeof row.id === "string")
538
+ map.set(row.id, row);
539
+ }
540
+ return map;
541
+ };
497
542
  // --- 1. Soul records (budgeted — prioritized by key importance) ---
498
543
  // Soul is who you are, but we still need to respect token budgets.
499
544
  // Workspace files (SOUL.md, AGENTS.md) can be massive — they're already
@@ -505,23 +550,28 @@ export class BootstrapMemories extends Resource {
505
550
  // Full workspace files — lowest priority (runtime already injects these)
506
551
  soul: 90, "workspace-rules": 91,
507
552
  };
553
+ // flair#2141 — `skill-assignment` rows are read whatever includeSoul says
554
+ // (the skills manifest in 1b is always present); the other soul entries
555
+ // only when includeSoul is on.
508
556
  const skillAssignments = [];
557
+ const soulEntries = [];
558
+ for await (const record of databases.flair.Soul.search()) {
559
+ if (record.agentId !== agentId)
560
+ continue;
561
+ if (record.key === SKILL_ASSIGNMENT_KEY) {
562
+ skillAssignments.push(record);
563
+ continue;
564
+ }
565
+ if (!includeSoul)
566
+ continue;
567
+ const line = `**${record.key}:** ${record.value}`;
568
+ const tokens = estimateTokens(line);
569
+ const priority = SOUL_KEY_PRIORITY[record.key] ?? 50;
570
+ soulEntries.push({ key: record.key, value: record.value, line, tokens, priority });
571
+ }
509
572
  const soulMaxTokens = Math.floor(maxTokens * 0.4); // 40% of budget for soul
510
573
  if (includeSoul) {
511
574
  let soulTokens = 0;
512
- const soulEntries = [];
513
- for await (const record of databases.flair.Soul.search()) {
514
- if (record.agentId !== agentId)
515
- continue;
516
- if (record.key === "skill-assignment") {
517
- skillAssignments.push(record);
518
- continue;
519
- }
520
- const line = `**${record.key}:** ${record.value}`;
521
- const tokens = estimateTokens(line);
522
- const priority = SOUL_KEY_PRIORITY[record.key] ?? 50;
523
- soulEntries.push({ key: record.key, value: record.value, line, tokens, priority });
524
- }
525
575
  // Sort by priority (lower = more important)
526
576
  soulEntries.sort((a, b) => a.priority - b.priority);
527
577
  // flair#1431 — collapse VERBATIM duplicates. The live payload shipped the
@@ -567,13 +617,90 @@ export class BootstrapMemories extends Resource {
567
617
  tokenBudget -= entry.tokens; // #1199 — soul draws from the shared budget
568
618
  }
569
619
  }
570
- // --- 1b. Skill assignments (durable source + stated conflict outcome) ---
571
- // flair#1433: do not report-and-load-both. resolveActiveSkills decides
572
- // (unique priority wins; equal-priority same-name tie refuses) and
573
- // states the decision on the line. Non-durable sources are refused.
574
- if (skillAssignments.length > 0) {
575
- const resolved = resolveActiveSkills(skillAssignments);
576
- sections.skills.push(...resolved.lines);
620
+ // The read scope (see the "Read-scope" block below), resolved here because
621
+ // the skills manifest (1b) re-checks its skill rows against it.
622
+ const scope = await resolveReadScope(agentId);
623
+ // --- 1b. Skills manifest (flair#2141 S1b and S1; conflict rules flair#1433) ---
624
+ // Present whatever includeSoul and includeContext say. resolveSkillManifest
625
+ // (resources/skill-manifest.ts) splits the agent's own and org-scope
626
+ // assignments into winners, each with the skill row `skill_get` reads,
627
+ // and diagnostics. Entries are
628
+ // admitted while they fit the shared budget, right after the soul, at
629
+ // their serialized size; an entry that does not fit is counted in
630
+ // skillsTruncated / skillDiagnosticsTruncated instead.
631
+ const includedSkills = [];
632
+ const includedSkillDiagnostics = [];
633
+ let skillsTruncated = 0;
634
+ let skillDiagnosticsTruncated = 0;
635
+ // flair#2141 S1 — when org rows exist, the target's Agent record is read on
636
+ // this call, and org assignments apply only when it says the target
637
+ // receives org skills.
638
+ const orgRows = [];
639
+ const orgQuery = withDetachedTxn(ctx, () => databases.flair.OrgSkillAssignment.search());
640
+ for await (const row of orgQuery)
641
+ orgRows.push(row);
642
+ const org = { assignments: [], rows: [], instanceId: null };
643
+ if (orgRows.length > 0
644
+ && receivesOrgSkills(await withDetachedTxnAsync(ctx, () => databases.flair.Agent.get(agentId)))) {
645
+ const refRows = new Map();
646
+ org.refSubjects = new Map();
647
+ for (const ref of new Set(orgRows.map((row) => row.skillRef).filter((ref) => typeof ref === "string"))) {
648
+ const referenced = await withDetachedTxnAsync(ctx, () => databases.flair.Memory.get(ref));
649
+ const subject = referenced && Array.isArray(referenced.tags) && referenced.tags.includes(SKILL_TAG)
650
+ && typeof referenced.skillSubjectId === "string" && referenced.skillSubjectId.length > 0
651
+ ? referenced.skillSubjectId : ref;
652
+ org.refSubjects.set(ref, subject);
653
+ const refQuery = withDetachedTxn(ctx, () => databases.flair.Memory.search({
654
+ conditions: [{
655
+ operator: "or",
656
+ conditions: [
657
+ { attribute: "id", comparator: "equals", value: ref },
658
+ { attribute: "skillSubjectId", comparator: "equals", value: subject },
659
+ ],
660
+ }],
661
+ select: SKILL_ROW_SELECT,
662
+ }));
663
+ for await (const record of refQuery)
664
+ refRows.set(record.id, record);
665
+ }
666
+ org.assignments = orgRows;
667
+ org.rows = resolvableSkillRows([...refRows.values()], scope.isAllowed);
668
+ org.instanceId = await localInstanceId();
669
+ }
670
+ if (skillAssignments.length > 0 || org.assignments.length > 0) {
671
+ const skillRows = [];
672
+ if (skillAssignments.length > 0) {
673
+ const skillQuery = withDetachedTxn(ctx, () => databases.flair.Memory.search({
674
+ conditions: [
675
+ { attribute: "agentId", comparator: "equals", value: agentId },
676
+ { attribute: "tags", comparator: "equals", value: SKILL_TAG },
677
+ { attribute: "archived", comparator: "not_equal", value: true },
678
+ ],
679
+ select: SKILL_ROW_SELECT,
680
+ }));
681
+ for await (const record of skillQuery)
682
+ skillRows.push(record);
683
+ }
684
+ const manifest = resolveSkillManifest(skillAssignments, resolvableSkillRows(skillRows, scope.isAllowed), agentId, org);
685
+ for (const entry of manifest.skills) {
686
+ const cost = estimateTokens(JSON.stringify(entry));
687
+ if (cost > tokenBudget) {
688
+ skillsTruncated++;
689
+ continue;
690
+ }
691
+ includedSkills.push(entry);
692
+ sections.skills.push(skillLine(entry));
693
+ tokenBudget -= cost;
694
+ }
695
+ for (const diagnostic of manifest.diagnostics) {
696
+ const cost = estimateTokens(JSON.stringify(diagnostic));
697
+ if (cost > tokenBudget) {
698
+ skillDiagnosticsTruncated++;
699
+ continue;
700
+ }
701
+ includedSkillDiagnostics.push(diagnostic);
702
+ tokenBudget -= cost;
703
+ }
577
704
  }
578
705
  // --- 1c. Team roster + cross-agent search nudge ---
579
706
  // Soul is still caller-own-only (unaffected here). Memory loading below
@@ -601,8 +728,8 @@ export class BootstrapMemories extends Resource {
601
728
  if (isTeammate(record, agentId))
602
729
  teammateIds.push(record.id);
603
730
  }
604
- const line = formatTeamLine(teammateIds);
605
- if (line)
731
+ const line = directoryHint();
732
+ if (teammateIds.length > 0)
606
733
  sections.team.push(line);
607
734
  }
608
735
  catch {
@@ -634,8 +761,8 @@ export class BootstrapMemories extends Resource {
634
761
  // spans the org. Each bounded query still re-checks `scope.isAllowed()`
635
762
  // on every record even where it's provably a no-op (e.g. an
636
763
  // agentId==self-only query) — uniform defense-in-depth, never skipped
637
- // because "the filter already pushed down."
638
- const scope = await resolveReadScope(agentId);
764
+ // because "the filter already pushed down." (`scope` is resolved above,
765
+ // before the skills manifest.)
639
766
  // `memoriesAvailable`: dropped the org-wide exact count (computing it
640
767
  // exactly WAS the scan being removed — `visibility != private` isn't
641
768
  // index-seekable, so even a bare count would scan). Replaced with the
@@ -668,9 +795,13 @@ export class BootstrapMemories extends Resource {
668
795
  // #1201 — `updatedAt` is projected on BOTH paths (not just the trust path):
669
796
  // the structured `memories`/`predicted` containers carry it so a consumer
670
797
  // can compute freshness, and the trust block's ageDays keys off it.
798
+ // flair#1940 A3 (slice 2b): `instanceToken` is projected on BOTH branches so
799
+ // the gated pointer join can bind a pointer to the row's current
800
+ // incarnation; it is a join input only (leanMemory/formatMemory never emit
801
+ // it), so the response bytes are unchanged.
671
802
  const OWN_SELECT = includeTrust
672
- ? ["id", "agentId", "content", "durability", "createdAt", "updatedAt", "supersedes", "subject", "validTo", "expiresAt", "_safetyFlags", "provenance", "usageCount", "validFrom"]
673
- : ["id", "agentId", "content", "durability", "createdAt", "updatedAt", "supersedes", "subject", "validTo", "expiresAt", "_safetyFlags"];
803
+ ? ["id", "agentId", "content", "durability", "createdAt", "updatedAt", "supersedes", "subject", "validTo", "expiresAt", "_safetyFlags", "instanceToken", "provenance", "usageCount", "validFrom"]
804
+ : ["id", "agentId", "content", "durability", "createdAt", "updatedAt", "supersedes", "subject", "validTo", "expiresAt", "_safetyFlags", "instanceToken"];
674
805
  // flair#744 slice 1 — the Memory records that became visible lines in the
675
806
  // memory-bearing sections (permanent/recent/predicted/relevant/teammate),
676
807
  // collected as they're added so the opt-in `trust` array below can carry a
@@ -697,6 +828,11 @@ export class BootstrapMemories extends Resource {
697
828
  : 0;
698
829
  tokenBudget -= taskReserve;
699
830
  let taskRetrievalHint;
831
+ // flair#2559 — the guard verdict when the task-relevant selection's
832
+ // embedding leg was refused (a non-uniform verdict). Declared here so the
833
+ // response tail can surface the state-named warning; set inside the
834
+ // task-relevant block below.
835
+ let spaceGuardVerdict = null;
700
836
  // --- 2. Permanent memories ---
701
837
  // Own-scoped pushdown: `agentId==self` + `durability==permanent`, both
702
838
  // @indexed (a seek, not a scan) — strictly narrower than the prior
@@ -743,8 +879,9 @@ export class BootstrapMemories extends Resource {
743
879
  if (m.supersedes)
744
880
  permanentSupersededIds.add(m.supersedes);
745
881
  const permanent = permanentRows.filter((m) => !permanentSupersededIds.has(m.id));
882
+ const permanentPtr = await pointerRenders(permanent);
746
883
  const admitPermanent = (m) => {
747
- const line = formatMemory(m, agentId);
884
+ const line = formatMemory(permanentPtr.get(m.id) ?? m, agentId);
748
885
  const struct = leanMemory(m, "permanent");
749
886
  // #1199 (0.44.11) — charge what SHIPS (structured on the /mcp path, prose
750
887
  // on the REST path); see contentCost. #1207 stays honored: on the prose
@@ -827,8 +964,9 @@ export class BootstrapMemories extends Resource {
827
964
  // Budget: up to 40% of remaining for recent
828
965
  const recentBudget = Math.floor(tokenBudget * 0.4);
829
966
  let recentSpent = 0;
967
+ const recentPtr = await pointerRenders(recent);
830
968
  for (const m of recent) {
831
- const line = formatMemory(m, agentId);
969
+ const line = formatMemory(recentPtr.get(m.id) ?? m, agentId);
832
970
  const struct = leanMemory(m, "recent");
833
971
  const cost = contentCost(struct, line); // #1199 (0.44.11) — charge what ships; see contentCost
834
972
  // flair#1199 trust-admission — charge the trust block's real serialized
@@ -875,8 +1013,9 @@ export class BootstrapMemories extends Resource {
875
1013
  .sort((a, b) => (b.createdAt || "").localeCompare(a.createdAt || ""));
876
1014
  const predictedBudget = Math.floor(tokenBudget * 0.3);
877
1015
  let predictedSpent = 0;
1016
+ const predictedPtr = await pointerRenders(subjectMemories);
878
1017
  for (const m of subjectMemories) {
879
- const line = formatMemory(m, agentId);
1018
+ const line = formatMemory(predictedPtr.get(m.id) ?? m, agentId);
880
1019
  const struct = leanMemory(m, "predicted");
881
1020
  const cost = contentCost(struct, line); // #1199 (0.44.11) — charge what ships; see contentCost
882
1021
  // flair#1199 trust-admission — charge the trust block's real serialized
@@ -943,7 +1082,6 @@ export class BootstrapMemories extends Resource {
943
1082
  if (currentTask && tokenBudget <= 0)
944
1083
  taskRetrievalHint = "Task retrieval skipped: no content budget remains.";
945
1084
  if (currentTask && tokenBudget > 0) {
946
- // Resolve the mode ONCE here so the embedding guard and the core agree.
947
1085
  // The bm25-only arm ranks on the lexical leg alone and needs NO query
948
1086
  // embedding — gating it on one being available would skip the lexical
949
1087
  // search entirely and lose task-relevant memories for no reason.
@@ -957,9 +1095,26 @@ export class BootstrapMemories extends Resource {
957
1095
  }
958
1096
  catch { }
959
1097
  }
960
- if (mode !== "bm25-only" && !queryEmbedding)
1098
+ // ─── Vector-space uniformity guard (flair#2559) ────────────────────
1099
+ // Consult the SAME chokepoint SemanticSearch uses (embeddingSpaceVerdict()):
1100
+ // when the store's model stamps are not KNOWN uniform in the current
1101
+ // embedding space — a non-current stamp observed, or an unknown verdict
1102
+ // (before the first scan, or after a scan error) — cosining the task
1103
+ // embedding against stored vectors could cross spaces. Fails CLOSED: the
1104
+ // embedding leg is refused and the selection degrades to its non-vector
1105
+ // (lexical) path, with the SAME state-named warning SemanticSearch emits.
1106
+ // Consulted only when a query embedding is available (outside bm25-only,
1107
+ // which ignores any query embedding).
1108
+ if (queryEmbedding) {
1109
+ const verdict = await embeddingSpaceVerdict();
1110
+ if (!verdict.uniform) {
1111
+ queryEmbedding = null;
1112
+ spaceGuardVerdict = verdict;
1113
+ }
1114
+ }
1115
+ if (mode !== "bm25-only" && !queryEmbedding && !spaceGuardVerdict)
961
1116
  taskRetrievalHint = "Task retrieval skipped: query embedding unavailable.";
962
- if (mode === "bm25-only" || queryEmbedding) {
1117
+ if (mode === "bm25-only" || queryEmbedding || spaceGuardVerdict) {
963
1118
  // flair#1207 — exclude own memories ALREADY placed via the authoritative
964
1119
  // set (permanent + recent + predicted actually admitted). The old set was
965
1120
  // built positionally (recent.filter by index) AND omitted `predicted`, so
@@ -982,23 +1137,7 @@ export class BootstrapMemories extends Resource {
982
1137
  queryEmbedding,
983
1138
  conditions: [scope.condition, { attribute: "archived", comparator: "not_equal", value: true }],
984
1139
  limit: candidatePoolK,
985
- // flair#1246 — ONE RANKER, ONE SCALE: this pass now invokes the
986
- // core in the SAME mode memory_search does (hybrid + q via the
987
- // shared retrievalMode() selector, so the FLAIR_RETRIEVAL_MODE /
988
- // FLAIR_HYBRID_RETRIEVAL kill-switch moves BOTH surfaces together —
989
- // a split mode IS the #1246 bug). HNSW-only here was an accident of early code, and it
990
- // made bootstrap's teammate picks diverge from search on the same
991
- // store+query: a record whose task-relevance is LEXICAL (exact task
992
- // terms in semantically-atypical prose) ranks BELOW bland-generic
993
- // noise on pure cosine (measured at N=21: on-task 0.5656 vs noise
994
- // 0.6086 — HNSW rank 6 while search fused it to rank 1), and at
995
- // field scale (corpus >> candidatePoolK) that inversion becomes
996
- // exclusion from the K-bounded pool entirely. The BM25 leg is the
997
- // rescue: it admits the record at lexical rank 1 and union-RRF
998
- // fusion carries it to the top, same as search. Perf (Kern-ratified
999
- // trade): the BM25 corpus scan this adds to the bootstrap path is
1000
- // the same per-call scan every memory_search request already runs.
1001
- mode,
1140
+ mode: spaceGuardVerdict && mode === "vector-only" ? "bm25-only" : mode,
1002
1141
  // The lexical leg — same query text the embedding was computed
1003
1142
  // from, so both legs rank the same question (parity with search,
1004
1143
  // where `q` drives BM25 and the keyword bump).
@@ -1064,6 +1203,7 @@ export class BootstrapMemories extends Resource {
1064
1203
  const scored = candidates
1065
1204
  .filter((m) => !includedIds.has(m.id))
1066
1205
  .map((m) => ({ memory: m, score: m._score }));
1206
+ const retrievedPtr = await pointerRenders(scored.map((s) => s.memory));
1067
1207
  // flair#681: the collision block's semantic surface — one candidate
1068
1208
  // per teammate (`scored` is sorted best-first by the fused retrieval
1069
1209
  // rank, so the first occurrence of a given `_source` IS that
@@ -1089,7 +1229,7 @@ export class BootstrapMemories extends Resource {
1089
1229
  // budget regardless of which section they land in, so neither
1090
1230
  // section double-spends.
1091
1231
  for (const { memory: m } of scored) {
1092
- const line = formatMemory(m, agentId);
1232
+ const line = formatMemory(retrievedPtr.get(m.id) ?? m, agentId);
1093
1233
  // flair#1199 (0.44.11) — build the STRUCTURED container object BEFORE
1094
1234
  // the budget check so the finding is charged the cost of what actually
1095
1235
  // ships (structured on the /mcp path), not its cheaper prose line. A
@@ -1454,7 +1594,9 @@ export class BootstrapMemories extends Resource {
1454
1594
  if (sections.soul.length > 0) {
1455
1595
  parts.push("## Identity\n" + sections.soul.join("\n"));
1456
1596
  }
1457
- if (sections.skills.length > 0) {
1597
+ // flair#2141 — rendered from the admitted `skills` entries, and only with
1598
+ // includeSoul.
1599
+ if (includeSoul && sections.skills.length > 0) {
1458
1600
  parts.push("## Active Skills\n" + sections.skills.join("\n"));
1459
1601
  }
1460
1602
  if (sections.team.length > 0) {
@@ -1513,7 +1655,8 @@ export class BootstrapMemories extends Resource {
1513
1655
  // counter doesn't prevent silent regression, per Kern's #1270 ruling):
1514
1656
  //
1515
1657
  // tokenEstimate ≈ scaffoldTokens + soulTokens + memoryTokens
1516
- // + trustTokens + eventsTokens
1658
+ // + trustTokens + eventsTokens + skillsTokens
1659
+ // + skillDiagnosticsTokens
1517
1660
  //
1518
1661
  // Every token-charged content class has a named counter, so a consumer can
1519
1662
  // decompose `tokenEstimate` FROM THE PAYLOAD ALONE and any future section
@@ -1553,6 +1696,10 @@ export class BootstrapMemories extends Resource {
1553
1696
  // events admission loop charged (#1199). Same reporting hole-class as
1554
1697
  // trust: charged content with no counter would be invisible in the ledger.
1555
1698
  const eventsTokens = includedEvents.reduce((sum, evt) => sum + estimateTokens(JSON.stringify(evt)), 0);
1699
+ // flair#2141 — the skills manifest and its diagnostics: Σ estimateTokens
1700
+ // (JSON) over the shipped entries, the same per-entry cost 1b charged.
1701
+ const skillsTokens = includedSkills.reduce((sum, entry) => sum + estimateTokens(JSON.stringify(entry)), 0);
1702
+ const skillDiagnosticsTokens = includedSkillDiagnostics.reduce((sum, entry) => sum + estimateTokens(JSON.stringify(entry)), 0);
1556
1703
  // flair#744 slice 1 — opt-in per-memory trust block. Bootstrap renders
1557
1704
  // memories as text lines rather than result objects, so the block is
1558
1705
  // surfaced as a `trust` array of self-contained entries (each carries its
@@ -1657,8 +1804,19 @@ export class BootstrapMemories extends Resource {
1657
1804
  // never absent, so "empty" is distinguishable from "unsupported").
1658
1805
  agentId,
1659
1806
  ...(taskRetrievalHint ? { taskRetrievalHint } : {}),
1807
+ // flair#2559 — the task-relevant selection refused its embedding leg for a
1808
+ // non-uniform verdict; the warning names the guard state (same wording as
1809
+ // SemanticSearch's `_warning`).
1810
+ ...(spaceGuardVerdict ? { _warning: spaceGuardWarning(spaceGuardVerdict, "keyword") } : {}),
1811
+ directoryHint: directoryHint(),
1660
1812
  scope: scopeInfo,
1661
1813
  soul: soulMap,
1814
+ // flair#2141 S1b — always present (`[]` when none), whatever includeSoul
1815
+ // and includeContext say; see 1b.
1816
+ skills: includedSkills,
1817
+ skillDiagnostics: includedSkillDiagnostics,
1818
+ skillsTruncated,
1819
+ skillDiagnosticsTruncated,
1662
1820
  memories: includedOwnMemories,
1663
1821
  predicted: includedPredicted,
1664
1822
  // flair#1199 — cross-agent teammate findings as a structured container
@@ -1687,6 +1845,7 @@ export class BootstrapMemories extends Resource {
1687
1845
  sections: {
1688
1846
  soul: sections.soul.length,
1689
1847
  skills: sections.skills.length,
1848
+ // Fixed directory hint when a roster exists.
1690
1849
  team: sections.team.length,
1691
1850
  permanent: sections.permanent.length,
1692
1851
  recent: sections.recent.length,
@@ -1704,6 +1863,8 @@ export class BootstrapMemories extends Resource {
1704
1863
  // token-charged content class is decomposable from the payload alone.
1705
1864
  trustTokens,
1706
1865
  eventsTokens,
1866
+ skillsTokens,
1867
+ skillDiagnosticsTokens,
1707
1868
  // flair#1199 — the content-selection budget this response was built
1708
1869
  // against (echoed so a connector can relate tokenEstimate to the budget it
1709
1870
  // asked for — and so the conformance tokenEstimate<=maxTokens invariant is
@@ -1769,6 +1930,8 @@ export class BootstrapMemories extends Resource {
1769
1930
  ...responseBody,
1770
1931
  context: "",
1771
1932
  soul: {},
1933
+ skills: [],
1934
+ skillDiagnostics: [],
1772
1935
  memories: [],
1773
1936
  predicted: [],
1774
1937
  teammateFindings: [],
@@ -1,6 +1,8 @@
1
1
  import { databases } from "harper";
2
2
  import { resolveAgentAuth } 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 { makeAuthGate, makeReadScope, makeScopedSearch, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
5
7
  import { RECORD_TYPES } from "./record-types.js";
6
8
  // Parameterized from RECORD_TYPES.MemoryCandidate (record-types slice 2,
@@ -166,6 +168,24 @@ export class MemoryCandidate extends databases.flair.MemoryCandidate {
166
168
  if (record[RECORD_TYPES.MemoryCandidate.ownerField] !== gate.agentId) {
167
169
  return FORBIDDEN("forbidden: cannot delete a memory candidate owned by another agent");
168
170
  }
169
- return super.delete(id, context);
171
+ // flair#2355: a row that is no longer the caller's at the delete's re-read
172
+ // or confirmation read is refused, not deleted
173
+ // (resources/owner-delete-recheck.ts).
174
+ const beforeDelete = txnPausePoint("candidate-delete-pre");
175
+ if (beforeDelete)
176
+ await beforeDelete;
177
+ const outcome = await deleteOwnedRow(ctx, {
178
+ table: databases.flair.MemoryCandidate,
179
+ tableName: "MemoryCandidate",
180
+ id: typeof id === "string" ? id : record.id,
181
+ ownerField: RECORD_TYPES.MemoryCandidate.ownerField,
182
+ callerId: gate.agentId,
183
+ point: "candidate-delete",
184
+ });
185
+ if (outcome.kind === "refused")
186
+ return outcome.response;
187
+ if (outcome.kind === "absent")
188
+ return super.delete(id, context);
189
+ return outcome.result;
170
190
  }
171
191
  }
@@ -57,7 +57,9 @@ import { mkdirSync, writeFileSync } from "node:fs";
57
57
  import { setImmediate as yieldToRequests } from "node:timers/promises";
58
58
  import { dirname } from "node:path";
59
59
  import { allowAdmin } from "./agent-auth.js";
60
+ import { txnPausePoint } from "./txn-pause-point.js";
60
61
  import { retrieveCandidates } from "./semantic-retrieval-core.js";
62
+ import { embeddingSpaceVerdict, spaceGuardState } from "./embedding-space-guard.js";
61
63
  import { DEDUP_COSINE_THRESHOLD_DEFAULT } from "./dedup.js";
62
64
  import { countDedupClusters, DEDUP_CLUSTER_ANN_K_DEFAULT, DEDUP_CLUSTER_MAX_MEMORIES_DEFAULT, REM_DEDUP_STATS_PATH, } from "./dedup-cluster.js";
63
65
  const NOT_ARCHIVED = [{ attribute: "archived", comparator: "not_equal", value: true }];
@@ -67,6 +69,18 @@ function persistStat(stat, pathOverride) {
67
69
  mkdirSync(dir, { recursive: true, mode: 0o700 });
68
70
  writeFileSync(path, JSON.stringify(stat, null, 2) + "\n", { mode: 0o600 });
69
71
  }
72
+ /** The refusal body when uniformity is not established: no vector-derived counts, the
73
+ * guard's named state instead. Shared by the opening consult and the pre-persist
74
+ * re-check (flair#2596). */
75
+ function guardRefusal(v, computedAt) {
76
+ return {
77
+ clusterCount: null,
78
+ largestClusterSize: null,
79
+ totalMemoriesInClusters: null,
80
+ computedAt,
81
+ embeddingSpace: { state: v.state, reason: v.reason },
82
+ };
83
+ }
70
84
  /**
71
85
  * The DB-touching sweep, factored out of post() so it takes an explicit
72
86
  * `ctx` and `nowOverride`/`pathOverride` rather than reaching for Resource
@@ -156,7 +170,17 @@ async function computeAndPersist(ctx, opts) {
156
170
  const clusters = countDedupClusters(edges);
157
171
  const computedAt = (opts?.nowOverride ?? new Date()).toISOString();
158
172
  const result = { ...clusters, computedAt };
159
- // ── 4. Persist server-side ONLY the aggregate (never per-memory edges).
173
+ // ── 4. Re-check the guard (flair#2596). The opening consult ran before any
174
+ // of the ANN work above; a guarded write carrying a foreign stamp can trip
175
+ // the latch during the sweep. Refuse new counts unless uniformity still holds.
176
+ const pause = txnPausePoint("dedup-sweep-persist");
177
+ if (pause)
178
+ await pause;
179
+ await embeddingSpaceVerdict();
180
+ const finalVerdict = spaceGuardState();
181
+ if (finalVerdict.state !== "uniform")
182
+ return guardRefusal(finalVerdict, computedAt);
183
+ // ── 5. Persist server-side ONLY the aggregate (never per-memory edges).
160
184
  persistStat(result, opts?.pathOverride);
161
185
  return result;
162
186
  }
@@ -167,6 +191,11 @@ export class MemoryDedupStats extends Resource {
167
191
  async post(_data) {
168
192
  const ctx = this.getContext?.();
169
193
  try {
194
+ // ─── Vector-space uniformity guard (flair#2559) ──────────────────────
195
+ // Consult the shared guard at the start of the sweep.
196
+ const verdict = await embeddingSpaceVerdict();
197
+ if (!verdict.uniform)
198
+ return guardRefusal(verdict, new Date().toISOString());
170
199
  return await computeAndPersist(ctx);
171
200
  }
172
201
  catch (err) {