@tpsdev-ai/flair 0.57.0 → 0.59.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 (143) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +4 -1
  3. package/config.yaml +3 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +1726 -376
  6. package/dist/commands/agent.js +160 -2
  7. package/dist/commands/doctor.js +177 -27
  8. package/dist/commands/federation.js +2 -1
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +150 -44
  11. package/dist/commands/mcp.js +53 -22
  12. package/dist/commands/memory.js +24 -2
  13. package/dist/commands/quality.js +26 -18
  14. package/dist/commands/service.js +137 -22
  15. package/dist/commands/status.js +114 -3
  16. package/dist/commands/upgrade.js +204 -84
  17. package/dist/doctor-client.js +50 -4
  18. package/dist/federation/scheduler.js +253 -4
  19. package/dist/install/clients.js +89 -23
  20. package/dist/install/global-bin-path.js +26 -6
  21. package/dist/lib/atomic-write.js +256 -0
  22. package/dist/lib/daemon-liveness.js +103 -0
  23. package/dist/lib/doctor-run.js +72 -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/flair-agent-role.js +116 -0
  27. package/dist/lib/init-admin-pass.js +4 -2
  28. package/dist/lib/init-listener-environ.js +38 -0
  29. package/dist/lib/init-occupied-listener.js +165 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +179 -8
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/mcp-enable.js +667 -72
  34. package/dist/lib/memory-attributes.js +77 -0
  35. package/dist/lib/node-alias-path.js +95 -0
  36. package/dist/lib/npm-registry.js +119 -6
  37. package/dist/lib/owned-pins.js +20 -6
  38. package/dist/lib/process-start-time.js +32 -0
  39. package/dist/lib/service-repoint-apply.js +267 -0
  40. package/dist/lib/service-repoint.js +575 -0
  41. package/dist/lib/toml-string-array.js +104 -0
  42. package/dist/lib/tree-divergence.js +716 -0
  43. package/dist/lib/upgrade-plain-tree.js +18 -8
  44. package/dist/lib/upgrade-prior-liveness.js +69 -0
  45. package/dist/lib/upgrade-rollback.js +116 -0
  46. package/dist/rem/runner.js +11 -0
  47. package/dist/resources/Agent.js +54 -21
  48. package/dist/resources/AgentSeed.js +44 -1
  49. package/dist/resources/Federation.js +84 -54
  50. package/dist/resources/Memory.js +567 -72
  51. package/dist/resources/MemoryArchive.js +9 -0
  52. package/dist/resources/MemoryBootstrap.js +125 -29
  53. package/dist/resources/MemoryFeed.js +204 -3
  54. package/dist/resources/MemoryHostSource.js +90 -0
  55. package/dist/resources/MemoryMaintenance.js +121 -32
  56. package/dist/resources/MemoryReflect.js +4 -1
  57. package/dist/resources/MemoryReindex.js +7 -4
  58. package/dist/resources/MemoryUsage.js +53 -3
  59. package/dist/resources/OrgSkillAssignment.js +209 -0
  60. package/dist/resources/Presence.js +18 -10
  61. package/dist/resources/RecordUsage.js +30 -40
  62. package/dist/resources/Relationship.js +167 -78
  63. package/dist/resources/SemanticSearch.js +19 -6
  64. package/dist/resources/Soul.js +31 -19
  65. package/dist/resources/XAA.js +47 -14
  66. package/dist/resources/agent-auth.js +16 -10
  67. package/dist/resources/agent-status-guard.js +63 -0
  68. package/dist/resources/auth-middleware.js +137 -49
  69. package/dist/resources/auto-promote-lib.js +4 -4
  70. package/dist/resources/bm25-index-service.js +246 -32
  71. package/dist/resources/bm25-status.js +132 -0
  72. package/dist/resources/ed25519-auth.js +11 -54
  73. package/dist/resources/embed-gpu.js +262 -47
  74. package/dist/resources/embeddings-boot.js +52 -17
  75. package/dist/resources/federation-classify.js +34 -0
  76. package/dist/resources/federation-crypto.js +65 -19
  77. package/dist/resources/flair-agent-role-boot.js +26 -0
  78. package/dist/resources/health.js +67 -16
  79. package/dist/resources/host-pointer/registry.js +35 -0
  80. package/dist/resources/host-pointer-adapter.js +15 -0
  81. package/dist/resources/host-source-visibility.js +167 -0
  82. package/dist/resources/host-source.js +151 -0
  83. package/dist/resources/instance-identity.js +3 -2
  84. package/dist/resources/key-lock.js +31 -0
  85. package/dist/resources/mcp-handler.js +147 -51
  86. package/dist/resources/mcp-oauth.js +3 -6
  87. package/dist/resources/mcp-tools.js +47 -25
  88. package/dist/resources/memory-consolidate-lib.js +3 -1
  89. package/dist/resources/memory-declared-attributes.js +103 -0
  90. package/dist/resources/memory-feed-lib.js +5 -1
  91. package/dist/resources/memory-host-source.js +163 -0
  92. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  93. package/dist/resources/migrations/visibility-backfill.js +4 -1
  94. package/dist/resources/multi-worker-guard.js +121 -0
  95. package/dist/resources/oauth-discovery.js +1 -0
  96. package/dist/resources/oauth-wellknown.js +8 -4
  97. package/dist/resources/originator-instance.js +235 -0
  98. package/dist/resources/promotion-stamp.js +2 -0
  99. package/dist/resources/provenance.js +111 -11
  100. package/dist/resources/record-owner-guard.js +19 -0
  101. package/dist/resources/record-type-kit.js +9 -12
  102. package/dist/resources/record-types.js +22 -6
  103. package/dist/resources/relay-ops.js +28 -3
  104. package/dist/resources/replay-store.js +336 -0
  105. package/dist/resources/request-transaction.js +78 -0
  106. package/dist/resources/search-readiness.js +19 -21
  107. package/dist/resources/semantic-retrieval-core.js +5 -1
  108. package/dist/resources/skill-manifest.js +181 -0
  109. package/dist/resources/skill-provenance.js +15 -10
  110. package/dist/resources/table-patch-policy.js +109 -0
  111. package/dist/resources/table-patches.js +17 -0
  112. package/dist/resources/table-post-policy.js +138 -0
  113. package/dist/resources/table-posts.js +22 -0
  114. package/dist/resources/table-subscription-policy.js +135 -0
  115. package/dist/resources/table-subscriptions.js +19 -0
  116. package/dist/resources/tool-descriptors/index.js +15 -15
  117. package/dist/resources/trust-block.js +10 -3
  118. package/dist/resources/usage-recording.js +169 -41
  119. package/dist/src/lib/flair-agent-role.js +116 -0
  120. package/dist/src/lib/memory-attributes.js +77 -0
  121. package/docs/access-control.md +667 -0
  122. package/docs/api-reference.md +85 -17
  123. package/docs/auth.md +4 -0
  124. package/docs/claude-code.md +132 -0
  125. package/docs/deepseek-harness.md +1 -1
  126. package/docs/deployment.md +1 -1
  127. package/docs/federation.md +1 -1
  128. package/docs/integrations.md +6 -6
  129. package/docs/mcp-clients.md +16 -24
  130. package/docs/notes/mcp-oauth-model2.md +15 -1
  131. package/docs/quickstart.md +5 -0
  132. package/docs/releasing.md +152 -20
  133. package/docs/supply-chain-policy.md +10 -5
  134. package/docs/troubleshooting.md +11 -0
  135. package/docs/upgrade.md +187 -61
  136. package/package.json +10 -5
  137. package/schemas/agent.graphql +9 -6
  138. package/schemas/federation.graphql +2 -11
  139. package/schemas/memory.graphql +137 -17
  140. package/schemas/oauth.graphql +8 -4
  141. package/schemas/replay.graphql +18 -0
  142. package/templates/launchd/start-flair-with-admin-pass.sh +95 -0
  143. package/dist/resources/federation-nonce-store.js +0 -195
@@ -0,0 +1,26 @@
1
+ /**
2
+ * flair-agent-role-boot.ts — at server start, attempts to bring an existing
3
+ * `flair_agent` role to this release's grants (flair#2141 S1).
4
+ *
5
+ * `flair init` writes the role. Each worker runs `alignFlairAgentRole` once,
6
+ * through Harper's in-process operations API; it never creates the role. A
7
+ * failure is logged with the `[flair-agent-role]` marker and the server keeps
8
+ * serving.
9
+ *
10
+ * Plain module (no Resource export), loaded at boot like
11
+ * resources/migration-boot.ts.
12
+ */
13
+ import { server } from "harper";
14
+ import { alignFlairAgentRole } from "../src/lib/flair-agent-role.js";
15
+ export function scheduleFlairAgentRoleAlign(op) {
16
+ const run = op ?? ((body) => server.operation(body, { user: null }, false));
17
+ setImmediate(() => {
18
+ alignFlairAgentRole(run).then((outcome) => {
19
+ if (outcome === "updated")
20
+ console.log("[flair-agent-role] the flair_agent role was updated to this release's grants");
21
+ }, (err) => {
22
+ console.error("[flair-agent-role] the flair_agent role could not be checked or updated, so it may lack the grants for tables added since it was set; restart the server to retry", { err: err instanceof Error ? err.message : String(err) });
23
+ });
24
+ });
25
+ }
26
+ scheduleFlairAgentRoleAlign();
@@ -4,17 +4,19 @@ import { homedir, platform } from "node:os";
4
4
  import { join, dirname } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { allowVerified, resolveAgentAuth } from "./agent-auth.js";
7
+ import { multiWorkerCondition, multiWorkerHealthField } from "./multi-worker-guard.js";
7
8
  import { resolveBuildInfo } from "./build-info.js";
8
9
  import { getMigrationStatusSnapshot } from "./migrations/status.js";
9
10
  import { resolveMigrationDataDirForRead } from "./migrations/data-dir.js";
10
11
  import { REM_DEDUP_STATS_PATH } from "./dedup-cluster.js";
11
12
  import { hybridEnabled, retrievalMode } from "./bm25.js";
12
- import { bm25IndexEnabled, bm25IndexStatus } from "./bm25-index-service.js";
13
+ import { bm25IndexEnabled, bm25IndexInRetrievalPath, bm25IndexStatus } from "./bm25-index-service.js";
14
+ import { bm25DisabledWarning } from "./bm25-status.js";
13
15
  import { normalizeStamp } from "./embedding-space-guard.js";
14
16
  import { getModelId } from "./embeddings-provider.js";
15
17
  import { describeStampOutstanding, EMBEDDING_STAMP_ID } from "./migrations/stamp-outstanding.js";
16
18
  import { buildPublicHealthBody, resolveSearchReadiness } from "./search-readiness.js";
17
- import { withEmbedGpuHealth } from "./embed-gpu.js";
19
+ import { embedGpuStatusNotice, withEmbedGpuHealth } from "./embed-gpu.js";
18
20
  import { classifyPeerLiveness, federationPeersAllDisconnectedWarning, PEER_LIVENESS_MEASURED_BY, summarizePeerLiveness, } from "./federation-peer-liveness.js";
19
21
  import { decideInstanceAnswer, INSTANCE_ROW_PRUNE_REMEDY } from "../src/lib/instance-identity-row.js";
20
22
  import { readAllInstanceRows } from "./Federation.js";
@@ -80,11 +82,11 @@ function resolveVersion() {
80
82
  *
81
83
  * flair#1326: `ok: true` used to mean only "this resource answered." That
82
84
  * is a green light that lies when search routes are not mounted yet, or
83
- * when the hybrid BM25 index is still cold (first search after restart
84
- * scans the corpus; the lag grows with store size). `searchReady` is
85
+ * when the BM25 index is still empty or building (a text search waits for
86
+ * the background build; the wait grows with store size). `searchReady` is
85
87
  * always present. When search cannot be served at all, this endpoint
86
- * returns HTTP 503 and `ok: false`. When the process is live but recall
87
- * is still cold, it stays 200 and names the lag on `searchReadyReason`.
88
+ * returns HTTP 503 and `ok: false`. When the process is live but the index
89
+ * is not ready, it stays 200 and names the lag on `searchReadyReason`.
88
90
  *
89
91
  * Rich stats (memory counts, agent names, etc.) are behind /HealthDetail
90
92
  * which requires authentication. This prevents information leakage on
@@ -118,25 +120,42 @@ export class Health extends Resource {
118
120
  version: build?.version ?? resolveVersion(),
119
121
  buildCommit: build?.commit ?? null,
120
122
  }));
121
- if (readiness.status !== 200) {
123
+ const multiWorker = multiWorkerHealthField(multiWorkerCondition());
124
+ let status = readiness.status;
125
+ if (multiWorker) {
126
+ body.ok = false;
127
+ body.multiWorker = multiWorker;
128
+ status = 503;
129
+ }
130
+ if (status !== 200) {
122
131
  return new Response(JSON.stringify(body), {
123
- status: readiness.status,
132
+ status,
124
133
  headers: { "content-type": "application/json" },
125
134
  });
126
135
  }
127
136
  return body;
128
137
  }
129
138
  }
130
- /** Same sources /Health and /HealthDetail consult so they cannot disagree. */
131
- export function currentSearchReadiness() {
139
+ /**
140
+ * Same sources /Health and /HealthDetail consult so they cannot disagree.
141
+ *
142
+ * `detail` includes the progress summary (doc counts) on the lag reason.
143
+ * Public /Health leaves it off — corpus size stays on the authenticated
144
+ * /HealthDetail `bm25` object, which is what `flair status` prints.
145
+ */
146
+ export function currentSearchReadiness(detail = false) {
132
147
  // Fail-open when the registry is missing (Sherlock on #1406 / flair#1411):
133
148
  // do not 503 forever. resolveSearchReadiness warns once and names the
134
149
  // degradation; we do not treat "registry should always be here" as a given.
135
150
  const resources = server.resources ?? null;
151
+ const full = bm25IndexStatus();
136
152
  return resolveSearchReadiness({
137
153
  resources,
138
154
  memoryTable: db.flair?.Memory,
139
- bm25: bm25IndexStatus(),
155
+ // Public /Health omits summary so doc counts stay off the unauthenticated
156
+ // body. `reason` still carries a skipped warm or a stale marker;
157
+ // bm25SearchLagReason reads it when summary is absent.
158
+ bm25: detail ? full : { state: full.state, reason: full.reason },
140
159
  hybridEnabled: hybridEnabled(),
141
160
  retrievalMode: retrievalMode(),
142
161
  bm25IndexEnabled: bm25IndexEnabled(),
@@ -178,11 +197,14 @@ export class HealthDetail extends Resource {
178
197
  // flair#1326: same search-ready signal as public /Health. HealthDetail
179
198
  // stays HTTP 200 (it is a stats dump, not a traffic gate); the field
180
199
  // and a warning name the lag so `flair status` / operators can see it.
181
- const readiness = currentSearchReadiness();
200
+ const readiness = currentSearchReadiness(true);
201
+ const bm25 = bm25IndexStatus();
202
+ stats.bm25 = bm25;
182
203
  const embeddingBody = withEmbedGpuHealth({ ok: true });
183
204
  stats.embedding = embeddingBody.embedding;
184
- if (embeddingBody.embedding.fallback) {
185
- warnings.push({ level: "warn", message: embeddingBody.embedding.fallback });
205
+ const embedNotice = embedGpuStatusNotice(embeddingBody.embedding);
206
+ if (embedNotice) {
207
+ warnings.push(embedNotice);
186
208
  }
187
209
  stats.searchReady = readiness.searchReady;
188
210
  // The active retrieval strategy (retrievalMode() in ./bm25.ts) — reported
@@ -196,6 +218,17 @@ export class HealthDetail extends Resource {
196
218
  stats.searchReadyReason = readiness.searchReadyReason;
197
219
  warnings.push({ level: "warn", message: readiness.searchReadyReason });
198
220
  }
221
+ else {
222
+ // A failed index answers via the per-query scan. searchReady stays
223
+ // true (recall works); the line says why the fast path is off. The
224
+ // kill switch and vector-only retrieval are settings, not warnings.
225
+ const bm25Warning = bm25DisabledWarning(bm25, {
226
+ indexEnabled: bm25IndexEnabled(),
227
+ inRetrievalPath: bm25IndexInRetrievalPath(),
228
+ });
229
+ if (bm25Warning)
230
+ warnings.push({ level: "warn", message: bm25Warning });
231
+ }
199
232
  const ctx = this.getContext?.();
200
233
  // #614 fix: resolve identity via the shared three-way verdict
201
234
  // (internal/agent/anonymous — agent-auth.ts) instead of reading
@@ -260,8 +293,6 @@ export class HealthDetail extends Resource {
260
293
  if (sorted[0])
261
294
  stats.lastWrite = sorted[0].createdAt;
262
295
  }
263
- if (expired > 0)
264
- warnings.push({ level: "warn", message: `${expired} memories have expired validTo but aren't archived` });
265
296
  // Hash-fallback coverage — tiered by percentage. Thresholds are
266
297
  // first-pass defaults; Kern's review on ops-n4n may tune them.
267
298
  if (memoriesList.length > 0) {
@@ -531,6 +562,7 @@ export class HealthDetail extends Resource {
531
562
  stats.oauth = null;
532
563
  }
533
564
  // ── REM ──
565
+ let nightlyRunFailed = false;
534
566
  try {
535
567
  const logsDir = join(homedir(), ".flair", "logs");
536
568
  const remLog = join(logsDir, "rem.jsonl");
@@ -610,6 +642,7 @@ export class HealthDetail extends Resource {
610
642
  }
611
643
  const nightlyRecords = await tailJsonl(nightlyLog);
612
644
  const lastNightlyRec = nightlyRecords[nightlyRecords.length - 1];
645
+ nightlyRunFailed = lastNightlyRec?.status === "failed";
613
646
  const lastNightlyAt = lastNightlyRec ? (lastNightlyRec.at ?? lastNightlyRec.ts ?? lastNightlyRec.timestamp ?? null) : null;
614
647
  let pendingCandidates = null;
615
648
  try {
@@ -652,6 +685,24 @@ export class HealthDetail extends Resource {
652
685
  catch {
653
686
  stats.rem = null;
654
687
  }
688
+ // Build this after REM discovery, including its unavailable-state fallback.
689
+ // Health does not read the scheduler's next-run time. The existing audit
690
+ // row does carry status; do not expose raw errors through HealthDetail.
691
+ if (stats.memories?.expired > 0) {
692
+ const nightlyHint = stats.rem?.nightlyEnabled === true
693
+ ? nightlyRunFailed
694
+ ? "nightly is enabled, but its last logged run failed — inspect ~/.flair/logs/rem-nightly.jsonl on the server"
695
+ : "nightly is enabled"
696
+ : stats.rem?.nightlyEnabled === false
697
+ ? "automate: flair rem nightly enable (includes validTo archival)"
698
+ : "nightly state is unknown — check: flair rem nightly status";
699
+ warnings.push({
700
+ level: "warn",
701
+ message: `${stats.memories.expired} memories have expired validTo but aren't archived\n` +
702
+ " clear now: flair rem light (archives expired validTo; preview: --dry-run)\n" +
703
+ ` ${nightlyHint}`,
704
+ });
705
+ }
655
706
  // ── Dedup clusters (flair-quality Slice 1c) ──
656
707
  // Cheap read: a single small stat file, not a recomputation. The
657
708
  // 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
+ }
@@ -3,8 +3,9 @@ import { readAllInstanceRows } from "./instance-identity-rows.js";
3
3
  /**
4
4
  * ─── Local instance identity (federation-edge-hardening slice 1) ────────────
5
5
  *
6
- * The write-time `originatorInstanceId` stamp (Memory.ts/Soul.ts/Agent.ts/
7
- * Relationship.ts post()/put()) needs to know THIS instance's own federation
6
+ * The write-time `originatorInstanceId` stamp (resources/originator-instance.ts,
7
+ * called by Memory.ts/Soul.ts/Agent.ts/Relationship.ts post()/put()/patch())
8
+ * needs to know THIS instance's own federation
8
9
  * identity — the same `id` FederationInstance.get() (resources/Federation.ts)
9
10
  * finds-or-creates on first boot and persists in the `Instance` table
10
11
  * (schemas/federation.graphql). Exactly one row is expected in a given
@@ -0,0 +1,31 @@
1
+ /**
2
+ * key-lock.ts — run a function while holding one key of a Harper table's
3
+ * primary-store lock (`tryLock` / `unlock`: per key, shared by the threads of
4
+ * one Harper process; resources/replay-store.ts uses the same primitive).
5
+ * No Harper imports.
6
+ */
7
+ /**
8
+ * Try the lock up to `attempts` times, `waitMs` apart. Holding it, drop the
9
+ * thread's cached read snapshot (when the store has one) and run `fn`; the
10
+ * lock is released when `fn` settles. "busy": the lock stayed held; "unavailable":
11
+ * the store has no lock. `fn` does not run in either case.
12
+ */
13
+ export async function withKeyLock(store, key, fn, attempts, waitMs) {
14
+ const lock = store;
15
+ if (typeof lock?.tryLock !== "function" || typeof lock?.unlock !== "function")
16
+ return { kind: "unavailable" };
17
+ for (let attempt = 0; attempt < attempts; attempt++) {
18
+ if (lock.tryLock(key)) {
19
+ try {
20
+ lock.resetReadTxn?.();
21
+ return { kind: "done", value: await fn() };
22
+ }
23
+ finally {
24
+ lock.unlock(key);
25
+ }
26
+ }
27
+ if (attempt + 1 < attempts)
28
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
29
+ }
30
+ return { kind: "busy" };
31
+ }