@tpsdev-ai/flair 0.56.0 → 0.58.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 (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
@@ -8,14 +8,17 @@ import { resolveBuildInfo } from "./build-info.js";
8
8
  import { getMigrationStatusSnapshot } from "./migrations/status.js";
9
9
  import { resolveMigrationDataDirForRead } from "./migrations/data-dir.js";
10
10
  import { REM_DEDUP_STATS_PATH } from "./dedup-cluster.js";
11
- import { hybridEnabled } from "./bm25.js";
12
- import { bm25IndexEnabled, bm25IndexStatus } from "./bm25-index-service.js";
11
+ import { hybridEnabled, retrievalMode } from "./bm25.js";
12
+ import { bm25IndexEnabled, bm25IndexInRetrievalPath, bm25IndexStatus } from "./bm25-index-service.js";
13
+ import { bm25DisabledWarning } from "./bm25-status.js";
13
14
  import { normalizeStamp } from "./embedding-space-guard.js";
14
15
  import { getModelId } from "./embeddings-provider.js";
15
16
  import { describeStampOutstanding, EMBEDDING_STAMP_ID } from "./migrations/stamp-outstanding.js";
16
17
  import { buildPublicHealthBody, resolveSearchReadiness } from "./search-readiness.js";
17
- import { withEmbedGpuHealth } from "./embed-gpu.js";
18
+ import { embedGpuStatusNotice, withEmbedGpuHealth } from "./embed-gpu.js";
18
19
  import { classifyPeerLiveness, federationPeersAllDisconnectedWarning, PEER_LIVENESS_MEASURED_BY, summarizePeerLiveness, } from "./federation-peer-liveness.js";
20
+ import { decideInstanceAnswer, INSTANCE_ROW_PRUNE_REMEDY } from "../src/lib/instance-identity-row.js";
21
+ import { readAllInstanceRows } from "./Federation.js";
19
22
  const db = databases;
20
23
  const redactHome = (p) => {
21
24
  const home = homedir();
@@ -78,11 +81,11 @@ function resolveVersion() {
78
81
  *
79
82
  * flair#1326: `ok: true` used to mean only "this resource answered." That
80
83
  * is a green light that lies when search routes are not mounted yet, or
81
- * when the hybrid BM25 index is still cold (first search after restart
82
- * scans the corpus; the lag grows with store size). `searchReady` is
84
+ * when the BM25 index is still empty or building (a text search waits for
85
+ * the background build; the wait grows with store size). `searchReady` is
83
86
  * always present. When search cannot be served at all, this endpoint
84
- * returns HTTP 503 and `ok: false`. When the process is live but recall
85
- * is still cold, it stays 200 and names the lag on `searchReadyReason`.
87
+ * returns HTTP 503 and `ok: false`. When the process is live but the index
88
+ * is not ready, it stays 200 and names the lag on `searchReadyReason`.
86
89
  *
87
90
  * Rich stats (memory counts, agent names, etc.) are behind /HealthDetail
88
91
  * which requires authentication. This prevents information leakage on
@@ -125,17 +128,28 @@ export class Health extends Resource {
125
128
  return body;
126
129
  }
127
130
  }
128
- /** Same sources /Health and /HealthDetail consult so they cannot disagree. */
129
- export function currentSearchReadiness() {
131
+ /**
132
+ * Same sources /Health and /HealthDetail consult so they cannot disagree.
133
+ *
134
+ * `detail` includes the progress summary (doc counts) on the lag reason.
135
+ * Public /Health leaves it off — corpus size stays on the authenticated
136
+ * /HealthDetail `bm25` object, which is what `flair status` prints.
137
+ */
138
+ export function currentSearchReadiness(detail = false) {
130
139
  // Fail-open when the registry is missing (Sherlock on #1406 / flair#1411):
131
140
  // do not 503 forever. resolveSearchReadiness warns once and names the
132
141
  // degradation; we do not treat "registry should always be here" as a given.
133
142
  const resources = server.resources ?? null;
143
+ const full = bm25IndexStatus();
134
144
  return resolveSearchReadiness({
135
145
  resources,
136
146
  memoryTable: db.flair?.Memory,
137
- bm25: bm25IndexStatus(),
147
+ // Public /Health omits summary so doc counts stay off the unauthenticated
148
+ // body. `reason` still carries a skipped warm or a stale marker;
149
+ // bm25SearchLagReason reads it when summary is absent.
150
+ bm25: detail ? full : { state: full.state, reason: full.reason },
138
151
  hybridEnabled: hybridEnabled(),
152
+ retrievalMode: retrievalMode(),
139
153
  bm25IndexEnabled: bm25IndexEnabled(),
140
154
  warn: (message) => { logger.warn?.(message); },
141
155
  });
@@ -175,13 +189,20 @@ export class HealthDetail extends Resource {
175
189
  // flair#1326: same search-ready signal as public /Health. HealthDetail
176
190
  // stays HTTP 200 (it is a stats dump, not a traffic gate); the field
177
191
  // and a warning name the lag so `flair status` / operators can see it.
178
- const readiness = currentSearchReadiness();
192
+ const readiness = currentSearchReadiness(true);
193
+ const bm25 = bm25IndexStatus();
194
+ stats.bm25 = bm25;
179
195
  const embeddingBody = withEmbedGpuHealth({ ok: true });
180
196
  stats.embedding = embeddingBody.embedding;
181
- if (embeddingBody.embedding.fallback) {
182
- warnings.push({ level: "warn", message: embeddingBody.embedding.fallback });
197
+ const embedNotice = embedGpuStatusNotice(embeddingBody.embedding);
198
+ if (embedNotice) {
199
+ warnings.push(embedNotice);
183
200
  }
184
201
  stats.searchReady = readiness.searchReady;
202
+ // The active retrieval strategy (retrievalMode() in ./bm25.ts) — reported
203
+ // so an operator can see WHICH ranker a process is serving from. Default
204
+ // (FLAIR_RETRIEVAL_MODE unset) is "hybrid", the shipped behavior.
205
+ stats.retrievalMode = retrievalMode();
185
206
  // Public/detail shape is unchanged: searchReadyReason stays a lag signal
186
207
  // (present iff !searchReady). Ready-path verification constants stay on
187
208
  // the decision object (flair#1411).
@@ -189,6 +210,17 @@ export class HealthDetail extends Resource {
189
210
  stats.searchReadyReason = readiness.searchReadyReason;
190
211
  warnings.push({ level: "warn", message: readiness.searchReadyReason });
191
212
  }
213
+ else {
214
+ // A failed index answers via the per-query scan. searchReady stays
215
+ // true (recall works); the line says why the fast path is off. The
216
+ // kill switch and vector-only retrieval are settings, not warnings.
217
+ const bm25Warning = bm25DisabledWarning(bm25, {
218
+ indexEnabled: bm25IndexEnabled(),
219
+ inRetrievalPath: bm25IndexInRetrievalPath(),
220
+ });
221
+ if (bm25Warning)
222
+ warnings.push({ level: "warn", message: bm25Warning });
223
+ }
192
224
  const ctx = this.getContext?.();
193
225
  // #614 fix: resolve identity via the shared three-way verdict
194
226
  // (internal/agent/anonymous — agent-auth.ts) instead of reading
@@ -253,8 +285,6 @@ export class HealthDetail extends Resource {
253
285
  if (sorted[0])
254
286
  stats.lastWrite = sorted[0].createdAt;
255
287
  }
256
- if (expired > 0)
257
- warnings.push({ level: "warn", message: `${expired} memories have expired validTo but aren't archived` });
258
288
  // Hash-fallback coverage — tiered by percentage. Thresholds are
259
289
  // first-pass defaults; Kern's review on ops-n4n may tune them.
260
290
  if (memoriesList.length > 0) {
@@ -371,12 +401,46 @@ export class HealthDetail extends Resource {
371
401
  }
372
402
  // ── Federation ──
373
403
  try {
374
- const instances = [];
404
+ // flair#1896: read the Instance rows the SAME way GET /FederationInstance
405
+ // does — through readAllInstanceRows (the strict reader, which throws on a
406
+ // row it cannot name) and decide with decideInstanceAnswer. A read that
407
+ // FAILS is not "no instance": it must report unreadable, never a silent
408
+ // null (swallowing a failed read as absent was the defect this fix ends).
409
+ // Several rows are a refusal naming the prune, never a coin-toss pick of
410
+ // whichever row the search happened to yield first.
411
+ let instanceReport = null;
375
412
  try {
376
- for await (const i of db.flair.Instance.search({}))
377
- instances.push(i);
413
+ const instanceRows = await readAllInstanceRows();
414
+ const instanceDecision = decideInstanceAnswer(instanceRows);
415
+ if (instanceDecision.kind === "answer") {
416
+ instanceReport = {
417
+ id: instanceDecision.row.id,
418
+ role: instanceDecision.row.role ?? null,
419
+ status: instanceDecision.row.status ?? null,
420
+ };
421
+ }
422
+ else if (instanceDecision.kind === "refuse-multiple") {
423
+ const multi = {
424
+ multiple: true,
425
+ count: instanceDecision.rows.length,
426
+ remedy: INSTANCE_ROW_PRUNE_REMEDY,
427
+ };
428
+ if (isAdmin) {
429
+ multi.rows = instanceDecision.rows.map((r) => ({
430
+ id: r.id,
431
+ role: r.role ?? null,
432
+ createdAt: r.createdAt ?? null,
433
+ }));
434
+ }
435
+ instanceReport = multi;
436
+ }
437
+ // "none" leaves instanceReport === null — exactly as before.
438
+ }
439
+ catch {
440
+ // A failed read, or a row the reader could not name, is UNREADABLE —
441
+ // never a silent null. (readAllInstanceRows throws in both cases.)
442
+ instanceReport = { unreadable: true };
378
443
  }
379
- catch { /* absent */ }
380
444
  const peers = [];
381
445
  try {
382
446
  for await (const p of db.flair.Peer.search({}))
@@ -389,11 +453,10 @@ export class HealthDetail extends Resource {
389
453
  tokens.push(t);
390
454
  }
391
455
  catch { /* absent */ }
392
- if (instances.length === 0 && peers.length === 0) {
456
+ if (instanceReport === null && peers.length === 0) {
393
457
  stats.federation = null;
394
458
  }
395
459
  else {
396
- const inst = instances[0];
397
460
  // flair#1499: derive connected/down from lastSyncAt, not stored
398
461
  // status. Pairing writes `paired`; a recent lastSyncAt is connected.
399
462
  // Revoked rows are counted separately and never drive the >24h warning.
@@ -410,7 +473,7 @@ export class HealthDetail extends Resource {
410
473
  };
411
474
  const pendingTokens = tokens.filter((t) => !t.consumedBy && t.expiresAt && new Date(t.expiresAt).getTime() > nowMs).length;
412
475
  stats.federation = {
413
- instance: inst ? { id: inst.id, role: inst.role, status: inst.status } : null,
476
+ instance: instanceReport,
414
477
  peers: peersBlock,
415
478
  pendingTokens,
416
479
  peerList: isAdmin
@@ -491,6 +554,7 @@ export class HealthDetail extends Resource {
491
554
  stats.oauth = null;
492
555
  }
493
556
  // ── REM ──
557
+ let nightlyRunFailed = false;
494
558
  try {
495
559
  const logsDir = join(homedir(), ".flair", "logs");
496
560
  const remLog = join(logsDir, "rem.jsonl");
@@ -570,6 +634,7 @@ export class HealthDetail extends Resource {
570
634
  }
571
635
  const nightlyRecords = await tailJsonl(nightlyLog);
572
636
  const lastNightlyRec = nightlyRecords[nightlyRecords.length - 1];
637
+ nightlyRunFailed = lastNightlyRec?.status === "failed";
573
638
  const lastNightlyAt = lastNightlyRec ? (lastNightlyRec.at ?? lastNightlyRec.ts ?? lastNightlyRec.timestamp ?? null) : null;
574
639
  let pendingCandidates = null;
575
640
  try {
@@ -612,6 +677,24 @@ export class HealthDetail extends Resource {
612
677
  catch {
613
678
  stats.rem = null;
614
679
  }
680
+ // Build this after REM discovery, including its unavailable-state fallback.
681
+ // Health does not read the scheduler's next-run time. The existing audit
682
+ // row does carry status; do not expose raw errors through HealthDetail.
683
+ if (stats.memories?.expired > 0) {
684
+ const nightlyHint = stats.rem?.nightlyEnabled === true
685
+ ? nightlyRunFailed
686
+ ? "nightly is enabled, but its last logged run failed — inspect ~/.flair/logs/rem-nightly.jsonl on the server"
687
+ : "nightly is enabled"
688
+ : stats.rem?.nightlyEnabled === false
689
+ ? "automate: flair rem nightly enable (includes validTo archival)"
690
+ : "nightly state is unknown — check: flair rem nightly status";
691
+ warnings.push({
692
+ level: "warn",
693
+ message: `${stats.memories.expired} memories have expired validTo but aren't archived\n` +
694
+ " clear now: flair rem light (archives expired validTo; preview: --dry-run)\n" +
695
+ ` ${nightlyHint}`,
696
+ });
697
+ }
615
698
  // ── Dedup clusters (flair-quality Slice 1c) ──
616
699
  // Cheap read: a single small stat file, not a recomputation. The
617
700
  // computation itself is a nightly server-side sweep (POST
@@ -0,0 +1,35 @@
1
+ /**
2
+ * host-pointer/registry.ts — the host-pointer write adapter (flair#1940 slice 1).
3
+ * The build check recursively scans JavaScript (`.js`) files under `dist`, excluding
4
+ * `node_modules`, for the former seam symbol and failure switch. This module is NOT under `dist/resources/*.js` (the
5
+ * jsResource glob loads only top-level files there), so it is not a resource
6
+ * surface. It exports NO failure switch and NO test seam: the production
7
+ * adapter is the real MemoryHostSource table, and tests that need a failing
8
+ * pointer write drive the failure from TEST code (the shared Harper mock's
9
+ * next-write failure flag in test/helpers/memory-search-harness.ts).
10
+ */
11
+ import { databases } from "harper";
12
+ import { MEMORY_HOST_SOURCE_TABLE } from "../memory-host-source.js";
13
+ function pointerTable() {
14
+ return databases.flair?.[MEMORY_HOST_SOURCE_TABLE];
15
+ }
16
+ /** The production adapter: the real MemoryHostSource table. Throws when the
17
+ * table is unavailable — fail closed, never a silent skip (A1-iv item 4). */
18
+ export const productionHostPointerAdapter = {
19
+ async putPointerRow(row, ctx) {
20
+ const table = pointerTable();
21
+ if (!table?.put)
22
+ throw new Error("MemoryHostSource table unavailable");
23
+ await table.put(row, ctx);
24
+ },
25
+ async deletePointerRow(memoryId, ctx) {
26
+ const table = pointerTable();
27
+ if (!table?.delete)
28
+ throw new Error("MemoryHostSource table unavailable");
29
+ await table.delete(memoryId, ctx);
30
+ },
31
+ };
32
+ /** The adapter the write path uses. The production one, always. */
33
+ export function currentHostPointerAdapter() {
34
+ return productionHostPointerAdapter;
35
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * host-pointer-adapter.ts — the resource-surface shim the Memory write path
3
+ * calls to write/delete a MemoryHostSource row (flair#1940 slice 1). The build check
4
+ * recursively scans JavaScript (`.js`) files under `dist`, excluding `node_modules`,
5
+ * for the former seam symbol and failure switch. This shim holds NO failure switch: the adapter it
6
+ * delegates to lives in ./host-pointer/registry.js, which has no test seam.
7
+ * Production behaviour is the real table.
8
+ */
9
+ import { currentHostPointerAdapter } from "./host-pointer/registry.js";
10
+ export function putPointerRow(row, ctx) {
11
+ return currentHostPointerAdapter().putPointerRow(row, ctx);
12
+ }
13
+ export function deletePointerRowViaTable(memoryId, ctx) {
14
+ return currentHostPointerAdapter().deletePointerRow(memoryId, ctx);
15
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * host-source-visibility.ts — A3: the hostSource read projection (flair#1940
3
+ * slice 1 / A1'). PURE beyond the A2 validator and the visibility predicate,
4
+ * so it is unit-testable and usable from the read paths.
5
+ *
6
+ * A1' moved the pointer OFF the Memory row and into its OWN table
7
+ * (`MemoryHostSource`, keyed by memoryId). Supported writes store host pointers
8
+ * only in `MemoryHostSource`. A pointer reaches a non-admin reader only through
9
+ * the gated join. For non-admin `Memory.get`, `Memory.search`, and
10
+ * `SemanticSearch` results, the gated projection removes inline pointer fields
11
+ * and renders a pointer only from a bound `MemoryHostSource` row.
12
+ * So the projection no longer reads a field off the record: the caller reads the
13
+ * pointer ROW and passes it in. The three outcomes of the join (A1' item 4) are:
14
+ * - no pointer row → the record is returned with any inline
15
+ * `hostSource` removed (hostSource absent/null —
16
+ * byte-identical to a pointerless record, which
17
+ * is what every legacy row is);
18
+ * - a pointer the reader may NOT see → `hostSource: "withheld"` (present but
19
+ * unrendered, so the "externally sourced" signal
20
+ * survives);
21
+ * - a pointer the reader may see → the canonical pointer (URL query/fragment
22
+ * stripped).
23
+ *
24
+ * The rule (A3): a pointer is content, never wider than its record.
25
+ * - Default (scopeAtWrite absent/null): the pointer is visible ONLY to the
26
+ * pointer row's AUTHOR (`authorId`).
27
+ * - Opted in: the pointer row stored the record's visibility AS IT WAS AT
28
+ * WRITE (`scopeAtWrite`); the pointer's EFFECTIVE visibility is the
29
+ * NARROWER of that stored value and the record's CURRENT visibility, so a
30
+ * later widening of the record never widens the pointer.
31
+ *
32
+ * A1'' item 4: the reader is compared with the POINTER ROW's `authorId`
33
+ * (server-stamped from the authenticated principal at Memory write time),
34
+ * never with Memory provenance.
35
+ *
36
+ * The decision is made HERE, on the server, in the read projection — no client
37
+ * or MCP layer can un-redact. `Memory.get()`, `Memory.search()` and
38
+ * `SemanticSearch` render pointers through the pointer helper. Other Memory
39
+ * projections, bootstrap included, do not render pointers in this slice (see the
40
+ * handler-level tests in test/unit/memory-host-source.test.ts).
41
+ */
42
+ import { parseHostSource } from "./host-source.js";
43
+ import { isPrivateVisibility } from "./memory-visibility.js";
44
+ /** The literal a reader gets in place of a pointer they may not see (A3). */
45
+ export const HOST_SOURCE_WITHHELD = "withheld";
46
+ /** The NARROWER of two visibilities (A3): "private" wins over anything else. */
47
+ export function narrowerVisibility(a, b) {
48
+ return isPrivateVisibility(a) || isPrivateVisibility(b) ? "private" : "shared";
49
+ }
50
+ /** Strip query and fragment so a rendered URL shows only scheme, host, path
51
+ * (A3). A value that is not a parseable absolute URL is returned unchanged. */
52
+ export function renderHostSourceUrl(url) {
53
+ try {
54
+ const u = new URL(url);
55
+ return `${u.protocol}//${u.host}${u.pathname}`;
56
+ }
57
+ catch {
58
+ return url;
59
+ }
60
+ }
61
+ /** The canonical hostSource VALUE to RENDER: the full pointer, with any URL
62
+ * reduced to scheme/host/path (query + fragment stripped, A3). A1'' item 6:
63
+ * reads return the validated OBJECT (not the stored canonical string), so a
64
+ * read-then-full-update round trip hands the validator a value it accepts. */
65
+ function renderableCanonical(stored) {
66
+ const parsed = parseHostSource(stored);
67
+ if (!parsed)
68
+ return HOST_SOURCE_WITHHELD; // a stored value that will not re-validate never renders raw
69
+ return parsed.url !== undefined ? { ...parsed, url: renderHostSourceUrl(parsed.url) } : parsed;
70
+ }
71
+ /**
72
+ * Whether a reader may see a pointer row, given the record it belongs to. The
73
+ * single decision point the three outcomes fall out of:
74
+ * "none" — no pointer row (the record is returned unchanged);
75
+ * "pointer" — render the canonical pointer;
76
+ * "withheld" — render HOST_SOURCE_WITHHELD.
77
+ *
78
+ * A1-iv item 1 (the binding): the pointer is returned (or withheld) ONLY when
79
+ * ALL of these hold — otherwise it is as if no pointer existed, so a stale
80
+ * pointer can never be returned, whichever write path forgot to clean it up:
81
+ * - pointer.authorId === record.agentId (the pointer's authenticated author
82
+ * is the row's CURRENT owner);
83
+ * - pointer.memoryInstanceToken === record.instanceToken (the SAME row
84
+ * incarnation — a deleted-and-recreated id gets a NEW token);
85
+ * - the record is not archived.
86
+ * (pointer.memoryId === record.id is implicit: the caller reads the pointer by
87
+ * the record's id.)
88
+ */
89
+ export function pointerOutcomeFor(record, readerAgentId, pointer) {
90
+ if (!pointer || typeof pointer.hostSource !== "string" || pointer.hostSource.length === 0)
91
+ return "none";
92
+ // A1'' item 4: the author is the POINTER row's `authorId`, stamped from the
93
+ // authenticated principal at Memory write time (resources/Memory.ts).
94
+ const author = typeof pointer.authorId === "string" && pointer.authorId.length > 0 ? pointer.authorId : null;
95
+ if (author === null)
96
+ return "none";
97
+ // A1-iv item 1: the binding. authorId must equal the row's CURRENT agentId,
98
+ // the incarnation token must match, and the row must not be archived.
99
+ if (typeof record?.agentId !== "string" || author !== record.agentId)
100
+ return "none";
101
+ const rowToken = typeof record?.instanceToken === "string" && record.instanceToken.length > 0 ? record.instanceToken : null;
102
+ const ptrToken = typeof pointer.memoryInstanceToken === "string" && pointer.memoryInstanceToken.length > 0 ? pointer.memoryInstanceToken : null;
103
+ if (rowToken === null || ptrToken === null || rowToken !== ptrToken)
104
+ return "none";
105
+ if (record?.archived === true)
106
+ return "none";
107
+ const isAuthor = readerAgentId != null && author === readerAgentId;
108
+ if (isAuthor)
109
+ return "pointer";
110
+ const scopeAtWrite = pointer.scopeAtWrite;
111
+ if (scopeAtWrite === undefined || scopeAtWrite === null)
112
+ return "withheld"; // author-only
113
+ const effective = narrowerVisibility(scopeAtWrite, record?.visibility);
114
+ return isPrivateVisibility(effective) ? "withheld" : "pointer";
115
+ }
116
+ /** The pointer-input keys the named non-admin read paths remove from their
117
+ * output (A1' item 1). A supported write strips them before persist; a RAW
118
+ * writer can leave one on the row, so the named non-admin reads (Memory.get,
119
+ * Memory.search, SemanticSearch) strip them. Other Memory projections do not
120
+ * render pointers in this slice and do not run this strip. */
121
+ const INLINE_POINTER_FIELDS = ["hostSource", "hostSourceScope", "hostSourceVisibility"];
122
+ /** Return `record` with every inline pointer-input field removed. Returns the
123
+ * SAME reference when there is nothing to remove, so a clean record is
124
+ * byte-identical to today. The one helper the named non-admin reads
125
+ * (Memory.get, Memory.search, SemanticSearch) use to drop inline pointer
126
+ * fields independently of the gated join. */
127
+ export function stripInlinePointerFields(record) {
128
+ if (!record || typeof record !== "object")
129
+ return record;
130
+ const r = record;
131
+ if (!INLINE_POINTER_FIELDS.some((k) => k in r))
132
+ return record;
133
+ const out = { ...r };
134
+ for (const k of INLINE_POINTER_FIELDS)
135
+ delete out[k];
136
+ return out;
137
+ }
138
+ /**
139
+ * Project a record's pointer for a given reader, given that record's pointer
140
+ * row (or null). Every call to `projectHostSource` removes inline pointer fields.
141
+ * Other response paths must remove them independently or exclude them from their
142
+ * selected fields:
143
+ * - no pointer row (or one that is unbound/token-mismatched) → the record is
144
+ * returned with any inline `hostSource` removed;
145
+ * - otherwise `hostSource` is set to the canonical pointer or
146
+ * HOST_SOURCE_WITHHELD.
147
+ */
148
+ export function projectHostSource(record, readerAgentId, pointer) {
149
+ if (!record || typeof record !== "object")
150
+ return record;
151
+ const decision = pointerOutcomeFor(record, readerAgentId, pointer);
152
+ if (decision === "none")
153
+ return stripInlinePointerFields(record);
154
+ // Always write the rendering onto a FRESH object: `stripInlinePointerFields`
155
+ // returns the SAME reference when there is nothing to strip, so assigning
156
+ // `hostSource` onto it would mutate the caller's (possibly stored) row. A
157
+ // materialized read is a copy in production, but the gated join must not
158
+ // depend on that — the pointer decision reads the STORED row unchanged.
159
+ const out = { ...stripInlinePointerFields(record) };
160
+ if (decision === "withheld") {
161
+ out.hostSource = HOST_SOURCE_WITHHELD;
162
+ }
163
+ else {
164
+ out.hostSource = renderableCanonical(pointer.hostSource);
165
+ }
166
+ return out;
167
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * host-source.ts — This validates pointers stored in `MemoryHostSource`; it
3
+ * accepts a pointer object or a JSON string representing one.
4
+ * (flair#1940 slice 1 / A2). PURE: zero imports (not even "harper"), so it can
5
+ * be unit-tested directly and imported from any write path.
6
+ *
7
+ * A hostSource is a host-object pointer, versioned JSON:
8
+ * { "v": 1, "host": <closed set>, "kind": <closed set>, "id": <grammar>, "url"?: <https> }
9
+ *
10
+ * The server validates at write time and NEVER truncates or coerces: any
11
+ * violation is a REFUSAL with a named error. The value stored is the CANONICAL
12
+ * form — NFC-normalised values, keys in the fixed order v, host, kind, id, url.
13
+ */
14
+ /** The initial closed vocabulary (A2). A PR that adds a pair extends this constant. */
15
+ export const HOST_SOURCE_HOSTS = Object.freeze(["openclaw", "cursor", "codex"]);
16
+ export const HOST_SOURCE_KINDS = Object.freeze(["run", "launch", "turn"]);
17
+ /** The host/kind PAIRS the server accepts (A2's initial set). */
18
+ export const HOST_SOURCE_PAIRS = Object.freeze([
19
+ { host: "openclaw", kind: "run" },
20
+ { host: "cursor", kind: "launch" },
21
+ { host: "codex", kind: "turn" },
22
+ ]);
23
+ /** The id grammar (A2). */
24
+ export const HOST_SOURCE_ID_RE = /^[A-Za-z0-9._:/@#-]{1,256}$/;
25
+ /** The url cap (A2), in characters. */
26
+ export const HOST_SOURCE_URL_MAX = 2048;
27
+ /** Control characters (C0, DEL, the C1 range U+0080-U+009F including U+0085)
28
+ * and the FULL bidi set (LRE/RLE/PDF/LRO/RLO U+202A-U+202E, the isolates
29
+ * U+2066-U+2069, and the marks LRM U+200E / RLM U+200F) are refused anywhere
30
+ * (A2). */
31
+ const FORBIDDEN = /[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;
32
+ /** NFC-normalise a string value (returns it unchanged if already NFC). */
33
+ function nfc(s) {
34
+ return s.normalize("NFC");
35
+ }
36
+ /**
37
+ * Validate and canonicalise a hostSource. Refuses (never truncates/coerces) on
38
+ * any violation, naming the field and the reason.
39
+ */
40
+ export function validateHostSource(input) {
41
+ // This validates pointers stored in `MemoryHostSource`; it accepts a pointer
42
+ // object or a JSON string representing one, so a value read back (or echoed by
43
+ // a client) round-trips through the write validator unchanged.
44
+ let raw = input;
45
+ if (typeof input === "string") {
46
+ try {
47
+ raw = JSON.parse(input);
48
+ }
49
+ catch {
50
+ return { ok: false, error: "hostSource must be an object or its canonical JSON string" };
51
+ }
52
+ }
53
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
54
+ return { ok: false, error: "hostSource must be an object" };
55
+ }
56
+ const obj = raw;
57
+ // Unknown top-level keys and any v other than 1 are refused (A2).
58
+ const allowed = new Set(["v", "host", "kind", "id", "url"]);
59
+ for (const key of Object.keys(obj)) {
60
+ if (!allowed.has(key))
61
+ return { ok: false, error: `hostSource: unknown key ${JSON.stringify(key)}` };
62
+ }
63
+ if (obj.v !== 1)
64
+ return { ok: false, error: `hostSource: unsupported v ${JSON.stringify(obj.v)} (only 1)` };
65
+ const field = (name, value) => {
66
+ if (typeof value !== "string")
67
+ return { ok: false, error: `hostSource.${name} must be a string` };
68
+ if (FORBIDDEN.test(value)) {
69
+ return { ok: false, error: `hostSource.${name} contains a control character or bidi override` };
70
+ }
71
+ return { ok: true, s: nfc(value) };
72
+ };
73
+ const host = field("host", obj.host);
74
+ if (!host.ok)
75
+ return host;
76
+ const kind = field("kind", obj.kind);
77
+ if (!kind.ok)
78
+ return kind;
79
+ const id = field("id", obj.id);
80
+ if (!id.ok)
81
+ return id;
82
+ // host/kind in the closed PAIR set.
83
+ if (!HOST_SOURCE_HOSTS.includes(host.s)) {
84
+ return { ok: false, error: `hostSource.host ${JSON.stringify(host.s)} is not in the closed set` };
85
+ }
86
+ if (!HOST_SOURCE_KINDS.includes(kind.s)) {
87
+ return { ok: false, error: `hostSource.kind ${JSON.stringify(kind.s)} is not in the closed set` };
88
+ }
89
+ if (!HOST_SOURCE_PAIRS.some((p) => p.host === host.s && p.kind === kind.s)) {
90
+ return { ok: false, error: `hostSource host/kind ${JSON.stringify(`${host.s}/${kind.s}`)} is not an allowed pair` };
91
+ }
92
+ if (!HOST_SOURCE_ID_RE.test(id.s)) {
93
+ return { ok: false, error: `hostSource.id ${JSON.stringify(id.s)} does not match the id grammar` };
94
+ }
95
+ // url is optional; https only, no userinfo, capped (A2).
96
+ let url;
97
+ if (obj.url !== undefined) {
98
+ const u = field("url", obj.url);
99
+ if (!u.ok)
100
+ return u;
101
+ if (u.s.length > HOST_SOURCE_URL_MAX) {
102
+ return { ok: false, error: `hostSource.url exceeds ${HOST_SOURCE_URL_MAX} characters` };
103
+ }
104
+ let parsed;
105
+ try {
106
+ parsed = new URL(u.s);
107
+ }
108
+ catch {
109
+ return { ok: false, error: `hostSource.url ${JSON.stringify(u.s)} is not a valid URL` };
110
+ }
111
+ if (parsed.protocol !== "https:")
112
+ return { ok: false, error: "hostSource.url must be https" };
113
+ // Userinfo is refused — INCLUDING EMPTY userinfo ("https://@host/"), which
114
+ // parses with parsed.username === "" and parsed.password === "" (A2 fix).
115
+ // Detect the "@" in the authority directly so an empty userinfo cannot slip
116
+ // through the username/password check.
117
+ const authority = u.s.replace(/^https:\/\//i, "").split(/[/?#]/)[0];
118
+ if (authority.includes("@") || parsed.username !== "" || parsed.password !== "") {
119
+ return { ok: false, error: "hostSource.url must not carry userinfo" };
120
+ }
121
+ url = u.s;
122
+ }
123
+ const value = {
124
+ v: 1,
125
+ host: host.s,
126
+ kind: kind.s,
127
+ id: id.s,
128
+ ...(url !== undefined ? { url } : {}),
129
+ };
130
+ // Canonical serialization: fixed key order v, host, kind, id, url (A2).
131
+ const canonical = JSON.stringify(value);
132
+ return { ok: true, canonical, value };
133
+ }
134
+ /**
135
+ * Parse a STORED hostSource string back to its value, or null when absent. The
136
+ * reader never renders the raw string; a stored value that does not re-validate
137
+ * reads as null (never a raw passthrough).
138
+ */
139
+ export function parseHostSource(stored) {
140
+ if (typeof stored !== "string" || stored.length === 0)
141
+ return null;
142
+ let parsed;
143
+ try {
144
+ parsed = JSON.parse(stored);
145
+ }
146
+ catch {
147
+ return null;
148
+ }
149
+ const r = validateHostSource(parsed);
150
+ return r.ok ? r.value : null;
151
+ }
@@ -154,7 +154,8 @@ class AgentMemory {
154
154
  * Search memories scoped to this agent.
155
155
  *
156
156
  * Delegates to Memory.search() which applies the agent's read scope
157
- * (own memories + granted owners' shared memories).
157
+ * (own records at any visibility + every other agent's non-private records;
158
+ * grants are not consulted on reads — see resolveReadScope()).
158
159
  */
159
160
  async search(opts) {
160
161
  const Cls = resolveResource(this.#server, "Memory");