@tpsdev-ai/flair 0.59.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 (259) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +12 -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 +991 -248
  10. package/dist/commands/agent.js +224 -43
  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 +592 -146
  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 +97 -35
  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 +41 -10
  59. package/dist/lib/doctor-run.js +75 -37
  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 +4 -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 +24 -0
  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 +1168 -326
  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 +76 -12
  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 +321 -1
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +10 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +751 -143
  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 +110 -39
  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/Presence.js +144 -49
  129. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  130. package/dist/resources/Relationship.js +23 -0
  131. package/dist/resources/SemanticSearch.js +63 -32
  132. package/dist/resources/Soul.js +189 -76
  133. package/dist/resources/TeamDirectory.js +35 -0
  134. package/dist/resources/WorkspaceState.js +21 -1
  135. package/dist/resources/XAA.js +181 -63
  136. package/dist/resources/agent-auth.js +40 -15
  137. package/dist/resources/auth-middleware.js +400 -161
  138. package/dist/resources/ed25519-auth.js +1 -1
  139. package/dist/resources/embedding-space-guard.js +366 -72
  140. package/dist/resources/engine-version-stamp-boot.js +53 -0
  141. package/dist/resources/federation-classify.js +72 -0
  142. package/dist/resources/federation-crypto.js +5 -5
  143. package/dist/resources/federation-retry-lib.js +135 -0
  144. package/dist/resources/grant-visibility.js +135 -0
  145. package/dist/resources/harper-routing.js +83 -0
  146. package/dist/resources/health.js +120 -18
  147. package/dist/resources/host-source-citation.js +49 -0
  148. package/dist/resources/host-source-visibility.js +7 -6
  149. package/dist/resources/instance-create-lock.js +17 -0
  150. package/dist/resources/instance-identity.js +23 -0
  151. package/dist/resources/instruction-version-record.js +343 -0
  152. package/dist/resources/key-lock.js +3 -3
  153. package/dist/resources/mcp-handler.js +36 -8
  154. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  155. package/dist/resources/mcp-oauth.js +23 -6
  156. package/dist/resources/mcp-tool-arguments.js +4 -6
  157. package/dist/resources/mcp-tools.js +128 -19
  158. package/dist/resources/memory-bootstrap-lib.js +5 -15
  159. package/dist/resources/memory-declared-attributes.js +3 -1
  160. package/dist/resources/memory-deletion-history.js +55 -0
  161. package/dist/resources/memory-durability.js +54 -0
  162. package/dist/resources/memory-embed-hash.js +88 -0
  163. package/dist/resources/memory-embedding-value.js +8 -0
  164. package/dist/resources/memory-host-source.js +27 -5
  165. package/dist/resources/memory-id-guard.js +75 -0
  166. package/dist/resources/memory-redaction.js +236 -0
  167. package/dist/resources/memory-supplied-vector.js +72 -0
  168. package/dist/resources/memory-write-lock.js +310 -0
  169. package/dist/resources/memory-write-response.js +139 -0
  170. package/dist/resources/migrations/data-dir.js +74 -16
  171. package/dist/resources/migrations/dir-safety.js +1 -1
  172. package/dist/resources/migrations/embedding-stamp.js +193 -79
  173. package/dist/resources/migrations/export.js +1 -0
  174. package/dist/resources/migrations/graph-heal.js +18 -25
  175. package/dist/resources/migrations/lock.js +7 -1
  176. package/dist/resources/migrations/snapshot.js +1 -0
  177. package/dist/resources/migrations/source-fields.js +5 -5
  178. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  179. package/dist/resources/migrations/visibility-backfill.js +29 -29
  180. package/dist/resources/object-body-guard.js +33 -0
  181. package/dist/resources/org-event-created-at.js +133 -0
  182. package/dist/resources/originator-instance.js +39 -7
  183. package/dist/resources/owner-delete-recheck.js +78 -0
  184. package/dist/resources/owner-field-guard.js +39 -5
  185. package/dist/resources/owner-scoped-write-policy.js +212 -0
  186. package/dist/resources/owner-scoped-writes.js +58 -0
  187. package/dist/resources/presence-receipt.js +236 -0
  188. package/dist/resources/promotion-stamp.js +47 -12
  189. package/dist/resources/record-owner-guard.js +74 -26
  190. package/dist/resources/record-types.js +1 -1
  191. package/dist/resources/relay-ops.js +78 -6
  192. package/dist/resources/replay-store.js +96 -19
  193. package/dist/resources/request-target.js +136 -0
  194. package/dist/resources/request-transaction.js +35 -0
  195. package/dist/resources/search-readiness.js +4 -1
  196. package/dist/resources/seed-ids.js +9 -0
  197. package/dist/resources/seed-reservation.js +117 -0
  198. package/dist/resources/semantic-retrieval-core.js +20 -9
  199. package/dist/resources/skill-manifest.js +20 -11
  200. package/dist/resources/skill-subject.js +53 -0
  201. package/dist/resources/skill-version-write.js +432 -0
  202. package/dist/resources/skill-write-fault.js +17 -0
  203. package/dist/resources/skill-write-policy.js +67 -0
  204. package/dist/resources/skill-write.js +67 -7
  205. package/dist/resources/table-helpers.js +10 -7
  206. package/dist/resources/team-directory.js +248 -0
  207. package/dist/resources/tool-descriptors/index.js +69 -8
  208. package/dist/resources/txn-pause-point.js +118 -0
  209. package/dist/resources/usage-recording.js +171 -63
  210. package/dist/resources/write-back.js +218 -0
  211. package/dist/src/engine-version-contract.js +1 -0
  212. package/dist/src/keystore.js +72 -0
  213. package/dist/src/lib/agent-home-fields.js +132 -0
  214. package/dist/src/lib/agent-id-rule.js +46 -0
  215. package/dist/src/lib/agent-key-register.js +80 -0
  216. package/dist/src/lib/atomic-write.js +256 -0
  217. package/dist/src/lib/credential-status-rule.js +78 -0
  218. package/dist/src/lib/expired-by-agent.js +37 -0
  219. package/dist/src/lib/flair-agent-role.js +4 -0
  220. package/dist/src/lib/idp-mapping-rule.js +81 -0
  221. package/dist/src/lib/instance-identity-row.js +20 -0
  222. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  223. package/dist/src/lib/memory-attributes.js +2 -0
  224. package/dist/src/lib/memory-id-policy.js +46 -0
  225. package/dist/src/lib/principal-status.js +29 -0
  226. package/dist/src/lib/proto-safe-record.js +42 -0
  227. package/dist/src/lib/reembed-server-support.js +66 -0
  228. package/dist/src/lib/scheduler-platform.js +10 -6
  229. package/dist/src/lib/systemd-agent-id.js +38 -0
  230. package/docs/access-control.md +146 -45
  231. package/docs/api-reference.md +46 -11
  232. package/docs/auth.md +6 -12
  233. package/docs/bridges.md +11 -0
  234. package/docs/claude-code.md +34 -4
  235. package/docs/deploying-on-fabric.md +70 -0
  236. package/docs/deployment.md +2 -0
  237. package/docs/embedding-in-a-harper-app.md +1 -1
  238. package/docs/federation.md +33 -2
  239. package/docs/hosted-on-fabric.md +43 -36
  240. package/docs/integrations.md +5 -5
  241. package/docs/mcp-clients.md +5 -2
  242. package/docs/n8n.md +17 -11
  243. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  244. package/docs/notes/mcp-oauth-model2.md +34 -5
  245. package/docs/quickstart-fabric.md +2 -2
  246. package/docs/quickstart.md +9 -1
  247. package/docs/releasing.md +12 -6
  248. package/docs/rem.md +8 -0
  249. package/docs/secrets-and-keys.md +19 -2
  250. package/docs/standalone-local.md +1 -0
  251. package/docs/supply-chain-policy.md +13 -3
  252. package/docs/upgrade.md +32 -6
  253. package/package.json +10 -5
  254. package/schemas/agent-key-registration.graphql +22 -0
  255. package/schemas/agent.graphql +3 -0
  256. package/schemas/federation.graphql +38 -1
  257. package/schemas/memory.graphql +84 -5
  258. package/schemas/oauth.graphql +19 -0
  259. package/schemas/schema.graphql +2 -0
@@ -22,27 +22,31 @@
22
22
  * Registered automatically at /MemoryArchive via config.yaml's
23
23
  * `jsResource: files: dist/resources/*.js` (named export → export name).
24
24
  */
25
- import { Resource } from "harper";
25
+ import { Resource, databases } from "harper";
26
+ import { isDeepStrictEqual } from "node:util";
26
27
  import { Memory } from "./Memory.js";
27
28
  import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
29
+ import { withOwnedTransaction } from "./request-transaction.js";
30
+ import { txnPausePoint } from "./txn-pause-point.js";
28
31
  function json(status, body) {
29
32
  return new Response(JSON.stringify(body), {
30
33
  status,
31
34
  headers: { "content-type": "application/json" },
32
35
  });
33
36
  }
34
- /** Unwrap a Harper Response (has .json() + .status) into a plain object, else pass through. */
35
- async function unwrap(value) {
37
+ /**
38
+ * A refusal or failure from Memory.get()/Memory.put() is a Harper `Response`
39
+ * (it carries `.status` + `.json`); a successful read/write is a plain record.
40
+ * Return the Response as-is so the endpoint answers with THAT HTTP status and
41
+ * its named error, and pass a record through unchanged.
42
+ * Returning an unwrapped write refusal would serialize it as HTTP 200;
43
+ * unwrapping a read refusal would replace it with the generic 404 below.
44
+ */
45
+ function asResponse(value) {
36
46
  if (value && typeof value === "object" && typeof value.json === "function" && "status" in value) {
37
- try {
38
- const body = await value.json();
39
- return { ...body, status: value.status };
40
- }
41
- catch {
42
- return { error: "request failed", status: value.status };
43
- }
47
+ return value;
44
48
  }
45
- return value;
49
+ return null;
46
50
  }
47
51
  export class MemoryArchive extends Resource {
48
52
  /** POST requires auth — an agent acting on its own memories (or admin). */
@@ -65,39 +69,68 @@ export class MemoryArchive extends Resource {
65
69
  // Read the existing record — Memory.get()'s read-scope gate applies (own +
66
70
  // org-non-private only). A non-readable id returns a 404 Response.
67
71
  const existing = await Memory.get(id, ctx);
68
- const record = await unwrap(existing);
69
- if (!record || typeof record !== "object" || !record.id) {
72
+ const readRefusal = asResponse(existing);
73
+ if (readRefusal)
74
+ return readRefusal;
75
+ const basis = existing;
76
+ if (!basis || typeof basis !== "object" || !basis.id) {
70
77
  return json(404, { error: "memory not found" });
71
78
  }
79
+ const persistedBasis = await databases.flair.Memory.get(id, ctx);
80
+ if (!persistedBasis)
81
+ return json(404, { error: "memory not found" });
72
82
  const archived = action === "basement";
73
- const merged = {
74
- ...record,
75
- archived,
76
- updatedAt: new Date().toISOString(),
77
- };
78
- if (archived) {
79
- // archivedBy is set by the caller (Memory.put() stamps archivedAt when
80
- // archived===true). The content is unchanged, so the existing embedding
81
- // stays valid — do NOT clear it (clearing would force a needless re-embed
82
- // and, if the embedding engine is unavailable, silently drop the vector).
83
- merged.archivedBy = auth.agentId;
84
- }
85
- else {
86
- delete merged.archivedAt;
87
- delete merged.archivedBy;
88
- }
89
- // flair#1940 A3 (item 9): the record we read was PROJECTED — for the author
90
- // it carries the canonical pointer with the URL query/fragment STRIPPED,
91
- // and for a non-author it may read "withheld". Writing any of that back
92
- // would replace the stored pointer (losing the full URL) or store a bogus
93
- // value, and would re-derive the scope. Omit every pointer field from the
94
- // write-back so the stored pointer row, its full URL and its scope stand.
95
- delete merged.hostSource;
96
- delete merged.hostSourceScope;
97
- delete merged.hostSourceVisibility;
98
- // Write back — Memory.put()'s ownership gate applies (stampAttribution), so
99
- // a non-admin caller cannot flip another agent's memory (403).
100
- const result = await Memory.put(merged, ctx);
101
- return unwrap(result);
83
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
84
+ const beforeReread = txnPausePoint("memory-archive-pre");
85
+ if (beforeReread)
86
+ await beforeReread;
87
+ // flair#2275: re-read the row INSIDE a transaction this call OWNS and build
88
+ // the write from THAT read — never from the basis above, which another
89
+ // writer may have changed before the write. Unequal persisted rows are
90
+ // refused (409); a non-readable row returns 404. Changes after the re-read
91
+ // are not checked.
92
+ return await withOwnedTransaction(ctx, async (c) => {
93
+ const reread = await Memory.get(id, c);
94
+ const rereadRefusal = asResponse(reread);
95
+ if (rereadRefusal)
96
+ return rereadRefusal;
97
+ if (!reread || typeof reread !== "object" || !reread.id) {
98
+ return json(404, { error: "memory not found" });
99
+ }
100
+ const persistedReread = await databases.flair.Memory.get(id, c);
101
+ if (!persistedReread)
102
+ return json(404, { error: "memory not found" });
103
+ if (!isDeepStrictEqual(persistedReread, persistedBasis)) {
104
+ return json(409, { error: "memory_changed" });
105
+ }
106
+ const merged = {
107
+ ...reread,
108
+ archived,
109
+ updatedAt: new Date().toISOString(),
110
+ };
111
+ if (archived) {
112
+ // archivedBy is set by the caller (Memory.put() stamps archivedAt when
113
+ // archived===true). The content is unchanged, so the existing embedding
114
+ // stays valid — do NOT clear it (clearing would force a needless re-embed
115
+ // and, if the embedding engine is unavailable, silently drop the vector).
116
+ merged.archivedBy = auth.agentId;
117
+ }
118
+ else {
119
+ delete merged.archivedAt;
120
+ delete merged.archivedBy;
121
+ }
122
+ // flair#1940 A3 (item 9): omit every pointer field from the write-back so
123
+ // the stored pointer row, its full URL and its scope stand.
124
+ delete merged.hostSource;
125
+ delete merged.hostSourceScope;
126
+ delete merged.hostSourceVisibility;
127
+ // Write back — Memory.put()'s ownership gate applies (stampAttribution), so
128
+ // a non-admin caller cannot flip another agent's memory (403).
129
+ const result = await Memory.put(merged, c);
130
+ const writeRefusal = asResponse(result);
131
+ if (writeRefusal)
132
+ return writeRefusal;
133
+ return result;
134
+ });
102
135
  }
103
136
  }
@@ -2,7 +2,7 @@ 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
8
  import { withDetachedTxn, withDetachedTxnAsync } from "./table-helpers.js";
@@ -16,7 +16,10 @@ 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";
@@ -267,16 +270,14 @@ const MAX_CANDIDATE_POOL = 100;
267
270
  // record's own agentId differs from the bootstrapping agent), so
268
271
  // `m._source !== agentId` is the "is this a teammate's finding" check; own
269
272
  // memories never carry `_source` at all.
270
- function formatMemory(m, agentId) {
271
- // flair#1940 A1' item 5: bootstrap does NOT render pointers in this slice.
272
- // The pointer lives in MemoryHostSource and is joined only into Memory.get/
273
- // search/SemanticSearch results; the bootstrap citation (A6) arrives in slice
274
- // 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.
275
275
  const tag = m.durability === "permanent" ? "🔒" : m.durability === "persistent" ? "📌" : "📝";
276
276
  const date = m.createdAt ? ` (${m.createdAt.slice(0, 10)})` : "";
277
277
  const chain = m.supersedes ? " [supersedes earlier decision]" : "";
278
278
  const attribution = m._source && m._source !== agentId ? `[via ${m._source}] ` : "";
279
- 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}` : ""}`;
280
281
  // Wrap flagged memories in safety delimiters — composes with attribution
281
282
  // above (attribution is baked into `base` before wrapping, so a flagged
282
283
  // teammate memory renders with BOTH the "[via <agent>]" tag and the
@@ -459,6 +460,17 @@ export class BootstrapMemories extends Resource {
459
460
  let eventWatermark = null;
460
461
  let eventsHasMore = false;
461
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.
462
474
  const leanMemory = (m, section) => ({
463
475
  id: m.id,
464
476
  content: m.content,
@@ -499,6 +511,34 @@ export class BootstrapMemories extends Resource {
499
511
  // selector tests against maxTokens is now the figure that becomes
500
512
  // `tokenEstimate` on each path.
501
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
+ };
502
542
  // --- 1. Soul records (budgeted — prioritized by key importance) ---
503
543
  // Soul is who you are, but we still need to respect token budgets.
504
544
  // Workspace files (SOUL.md, AGENTS.md) can be massive — they're already
@@ -602,17 +642,29 @@ export class BootstrapMemories extends Resource {
602
642
  const org = { assignments: [], rows: [], instanceId: null };
603
643
  if (orgRows.length > 0
604
644
  && receivesOrgSkills(await withDetachedTxnAsync(ctx, () => databases.flair.Agent.get(agentId)))) {
605
- const refRows = [];
645
+ const refRows = new Map();
646
+ org.refSubjects = new Map();
606
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);
607
653
  const refQuery = withDetachedTxn(ctx, () => databases.flair.Memory.search({
608
- conditions: [{ attribute: "id", comparator: "equals", value: ref }],
654
+ conditions: [{
655
+ operator: "or",
656
+ conditions: [
657
+ { attribute: "id", comparator: "equals", value: ref },
658
+ { attribute: "skillSubjectId", comparator: "equals", value: subject },
659
+ ],
660
+ }],
609
661
  select: SKILL_ROW_SELECT,
610
662
  }));
611
663
  for await (const record of refQuery)
612
- refRows.push(record);
664
+ refRows.set(record.id, record);
613
665
  }
614
666
  org.assignments = orgRows;
615
- org.rows = resolvableSkillRows(refRows, scope.isAllowed);
667
+ org.rows = resolvableSkillRows([...refRows.values()], scope.isAllowed);
616
668
  org.instanceId = await localInstanceId();
617
669
  }
618
670
  if (skillAssignments.length > 0 || org.assignments.length > 0) {
@@ -676,8 +728,8 @@ export class BootstrapMemories extends Resource {
676
728
  if (isTeammate(record, agentId))
677
729
  teammateIds.push(record.id);
678
730
  }
679
- const line = formatTeamLine(teammateIds);
680
- if (line)
731
+ const line = directoryHint();
732
+ if (teammateIds.length > 0)
681
733
  sections.team.push(line);
682
734
  }
683
735
  catch {
@@ -743,9 +795,13 @@ export class BootstrapMemories extends Resource {
743
795
  // #1201 — `updatedAt` is projected on BOTH paths (not just the trust path):
744
796
  // the structured `memories`/`predicted` containers carry it so a consumer
745
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.
746
802
  const OWN_SELECT = includeTrust
747
- ? ["id", "agentId", "content", "durability", "createdAt", "updatedAt", "supersedes", "subject", "validTo", "expiresAt", "_safetyFlags", "provenance", "usageCount", "validFrom"]
748
- : ["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"];
749
805
  // flair#744 slice 1 — the Memory records that became visible lines in the
750
806
  // memory-bearing sections (permanent/recent/predicted/relevant/teammate),
751
807
  // collected as they're added so the opt-in `trust` array below can carry a
@@ -772,6 +828,11 @@ export class BootstrapMemories extends Resource {
772
828
  : 0;
773
829
  tokenBudget -= taskReserve;
774
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;
775
836
  // --- 2. Permanent memories ---
776
837
  // Own-scoped pushdown: `agentId==self` + `durability==permanent`, both
777
838
  // @indexed (a seek, not a scan) — strictly narrower than the prior
@@ -818,8 +879,9 @@ export class BootstrapMemories extends Resource {
818
879
  if (m.supersedes)
819
880
  permanentSupersededIds.add(m.supersedes);
820
881
  const permanent = permanentRows.filter((m) => !permanentSupersededIds.has(m.id));
882
+ const permanentPtr = await pointerRenders(permanent);
821
883
  const admitPermanent = (m) => {
822
- const line = formatMemory(m, agentId);
884
+ const line = formatMemory(permanentPtr.get(m.id) ?? m, agentId);
823
885
  const struct = leanMemory(m, "permanent");
824
886
  // #1199 (0.44.11) — charge what SHIPS (structured on the /mcp path, prose
825
887
  // on the REST path); see contentCost. #1207 stays honored: on the prose
@@ -902,8 +964,9 @@ export class BootstrapMemories extends Resource {
902
964
  // Budget: up to 40% of remaining for recent
903
965
  const recentBudget = Math.floor(tokenBudget * 0.4);
904
966
  let recentSpent = 0;
967
+ const recentPtr = await pointerRenders(recent);
905
968
  for (const m of recent) {
906
- const line = formatMemory(m, agentId);
969
+ const line = formatMemory(recentPtr.get(m.id) ?? m, agentId);
907
970
  const struct = leanMemory(m, "recent");
908
971
  const cost = contentCost(struct, line); // #1199 (0.44.11) — charge what ships; see contentCost
909
972
  // flair#1199 trust-admission — charge the trust block's real serialized
@@ -950,8 +1013,9 @@ export class BootstrapMemories extends Resource {
950
1013
  .sort((a, b) => (b.createdAt || "").localeCompare(a.createdAt || ""));
951
1014
  const predictedBudget = Math.floor(tokenBudget * 0.3);
952
1015
  let predictedSpent = 0;
1016
+ const predictedPtr = await pointerRenders(subjectMemories);
953
1017
  for (const m of subjectMemories) {
954
- const line = formatMemory(m, agentId);
1018
+ const line = formatMemory(predictedPtr.get(m.id) ?? m, agentId);
955
1019
  const struct = leanMemory(m, "predicted");
956
1020
  const cost = contentCost(struct, line); // #1199 (0.44.11) — charge what ships; see contentCost
957
1021
  // flair#1199 trust-admission — charge the trust block's real serialized
@@ -1018,7 +1082,6 @@ export class BootstrapMemories extends Resource {
1018
1082
  if (currentTask && tokenBudget <= 0)
1019
1083
  taskRetrievalHint = "Task retrieval skipped: no content budget remains.";
1020
1084
  if (currentTask && tokenBudget > 0) {
1021
- // Resolve the mode ONCE here so the embedding guard and the core agree.
1022
1085
  // The bm25-only arm ranks on the lexical leg alone and needs NO query
1023
1086
  // embedding — gating it on one being available would skip the lexical
1024
1087
  // search entirely and lose task-relevant memories for no reason.
@@ -1032,9 +1095,26 @@ export class BootstrapMemories extends Resource {
1032
1095
  }
1033
1096
  catch { }
1034
1097
  }
1035
- 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)
1036
1116
  taskRetrievalHint = "Task retrieval skipped: query embedding unavailable.";
1037
- if (mode === "bm25-only" || queryEmbedding) {
1117
+ if (mode === "bm25-only" || queryEmbedding || spaceGuardVerdict) {
1038
1118
  // flair#1207 — exclude own memories ALREADY placed via the authoritative
1039
1119
  // set (permanent + recent + predicted actually admitted). The old set was
1040
1120
  // built positionally (recent.filter by index) AND omitted `predicted`, so
@@ -1057,23 +1137,7 @@ export class BootstrapMemories extends Resource {
1057
1137
  queryEmbedding,
1058
1138
  conditions: [scope.condition, { attribute: "archived", comparator: "not_equal", value: true }],
1059
1139
  limit: candidatePoolK,
1060
- // flair#1246 — ONE RANKER, ONE SCALE: this pass now invokes the
1061
- // core in the SAME mode memory_search does (hybrid + q via the
1062
- // shared retrievalMode() selector, so the FLAIR_RETRIEVAL_MODE /
1063
- // FLAIR_HYBRID_RETRIEVAL kill-switch moves BOTH surfaces together —
1064
- // a split mode IS the #1246 bug). HNSW-only here was an accident of early code, and it
1065
- // made bootstrap's teammate picks diverge from search on the same
1066
- // store+query: a record whose task-relevance is LEXICAL (exact task
1067
- // terms in semantically-atypical prose) ranks BELOW bland-generic
1068
- // noise on pure cosine (measured at N=21: on-task 0.5656 vs noise
1069
- // 0.6086 — HNSW rank 6 while search fused it to rank 1), and at
1070
- // field scale (corpus >> candidatePoolK) that inversion becomes
1071
- // exclusion from the K-bounded pool entirely. The BM25 leg is the
1072
- // rescue: it admits the record at lexical rank 1 and union-RRF
1073
- // fusion carries it to the top, same as search. Perf (Kern-ratified
1074
- // trade): the BM25 corpus scan this adds to the bootstrap path is
1075
- // the same per-call scan every memory_search request already runs.
1076
- mode,
1140
+ mode: spaceGuardVerdict && mode === "vector-only" ? "bm25-only" : mode,
1077
1141
  // The lexical leg — same query text the embedding was computed
1078
1142
  // from, so both legs rank the same question (parity with search,
1079
1143
  // where `q` drives BM25 and the keyword bump).
@@ -1139,6 +1203,7 @@ export class BootstrapMemories extends Resource {
1139
1203
  const scored = candidates
1140
1204
  .filter((m) => !includedIds.has(m.id))
1141
1205
  .map((m) => ({ memory: m, score: m._score }));
1206
+ const retrievedPtr = await pointerRenders(scored.map((s) => s.memory));
1142
1207
  // flair#681: the collision block's semantic surface — one candidate
1143
1208
  // per teammate (`scored` is sorted best-first by the fused retrieval
1144
1209
  // rank, so the first occurrence of a given `_source` IS that
@@ -1164,7 +1229,7 @@ export class BootstrapMemories extends Resource {
1164
1229
  // budget regardless of which section they land in, so neither
1165
1230
  // section double-spends.
1166
1231
  for (const { memory: m } of scored) {
1167
- const line = formatMemory(m, agentId);
1232
+ const line = formatMemory(retrievedPtr.get(m.id) ?? m, agentId);
1168
1233
  // flair#1199 (0.44.11) — build the STRUCTURED container object BEFORE
1169
1234
  // the budget check so the finding is charged the cost of what actually
1170
1235
  // ships (structured on the /mcp path), not its cheaper prose line. A
@@ -1739,6 +1804,11 @@ export class BootstrapMemories extends Resource {
1739
1804
  // never absent, so "empty" is distinguishable from "unsupported").
1740
1805
  agentId,
1741
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(),
1742
1812
  scope: scopeInfo,
1743
1813
  soul: soulMap,
1744
1814
  // flair#2141 S1b — always present (`[]` when none), whatever includeSoul
@@ -1775,6 +1845,7 @@ export class BootstrapMemories extends Resource {
1775
1845
  sections: {
1776
1846
  soul: sections.soul.length,
1777
1847
  skills: sections.skills.length,
1848
+ // Fixed directory hint when a roster exists.
1778
1849
  team: sections.team.length,
1779
1850
  permanent: sections.permanent.length,
1780
1851
  recent: sections.recent.length,
@@ -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) {