@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
@@ -1,3 +1,4 @@
1
+ import { systemdAgentId } from "../src/lib/systemd-agent-id.js";
1
2
  import { Resource, databases, server, logger } from "harper";
2
3
  import { promises as fsp, existsSync, readFileSync } from "node:fs";
3
4
  import { homedir, platform } from "node:os";
@@ -12,18 +13,20 @@ import { REM_DEDUP_STATS_PATH } from "./dedup-cluster.js";
12
13
  import { hybridEnabled, retrievalMode } from "./bm25.js";
13
14
  import { bm25IndexEnabled, bm25IndexInRetrievalPath, bm25IndexStatus } from "./bm25-index-service.js";
14
15
  import { bm25DisabledWarning } from "./bm25-status.js";
15
- import { normalizeStamp } from "./embedding-space-guard.js";
16
+ import { normalizeStamp, spaceGuardState } from "./embedding-space-guard.js";
16
17
  import { getModelId } from "./embeddings-provider.js";
17
18
  import { describeStampOutstanding, EMBEDDING_STAMP_ID } from "./migrations/stamp-outstanding.js";
18
19
  import { buildPublicHealthBody, resolveSearchReadiness } from "./search-readiness.js";
19
20
  import { embedGpuStatusNotice, withEmbedGpuHealth } from "./embed-gpu.js";
20
21
  import { classifyPeerLiveness, federationPeersAllDisconnectedWarning, PEER_LIVENESS_MEASURED_BY, summarizePeerLiveness, } from "./federation-peer-liveness.js";
21
22
  import { decideInstanceAnswer, INSTANCE_ROW_PRUNE_REMEDY } from "../src/lib/instance-identity-row.js";
23
+ import { summarizeExpiredByAgent, expiredByAgentWarningLines } from "../src/lib/expired-by-agent.js";
22
24
  import { readAllInstanceRows } from "./Federation.js";
25
+ import { mcpOAuthProviderReadiness } from "./mcp-oauth-env-guard.js";
23
26
  const db = databases;
24
27
  const redactHome = (p) => {
25
28
  const home = homedir();
26
- return p.startsWith(home) ? "~" + p.slice(home.length) : p;
29
+ return p === home ? "~" : p.startsWith(home + "/") ? "~" + p.slice(home.length) : "[redacted]";
27
30
  };
28
31
  const exists = async (path) => {
29
32
  try {
@@ -101,10 +104,6 @@ export class Health extends Resource {
101
104
  // `version` (flair#695, the CLI↔server handshake — src/version-handshake.ts):
102
105
  // exposed on the PUBLIC endpoint deliberately, so the check works even
103
106
  // before an agent identity/key exists (fresh install, pre-`flair init`).
104
- // Sherlock verdict: fine while locally bound; if /Health is ever fronted
105
- // PUBLICLY over Fabric, the public surface must omit this field (the
106
- // richer, auth-gated /HealthDetail already carried version pre-existing —
107
- // this only adds it to the anonymous endpoint too).
108
107
  //
109
108
  // flair#1076: both values come from dist/build-info.json — the stamp the
110
109
  // build wrote next to the modules Harper actually loaded — so /Health
@@ -120,6 +119,17 @@ export class Health extends Resource {
120
119
  version: build?.version ?? resolveVersion(),
121
120
  buildCommit: build?.commit ?? null,
122
121
  }));
122
+ // flair#2530 — the query-time embedding-space guard's state, for `flair
123
+ // doctor`. Sync, no scan, no vector read. `state` is one of
124
+ // uniform | mixed | unverified | scan-failed | excluded; `reason` is the
125
+ // bounded error
126
+ // of the last failed scan (on scan-failed, or on mixed when a scan failed
127
+ // before or after the foreign stamp was seen); `excluded` is the last
128
+ // published count of arrays or typed arrays, empty included, without a trusted
129
+ // current-space stamp (null until a scan publishes one). Calls that consult a
130
+ // non-uniform verdict skip vector comparisons against the stored corpus
131
+ // (flair#2559). The field is on the 503 body too; doctor reads it there.
132
+ body.embeddingSpace = spaceGuardState();
123
133
  const multiWorker = multiWorkerHealthField(multiWorkerCondition());
124
134
  let status = readiness.status;
125
135
  if (multiWorker) {
@@ -137,7 +147,7 @@ export class Health extends Resource {
137
147
  }
138
148
  }
139
149
  /**
140
- * Same sources /Health and /HealthDetail consult so they cannot disagree.
150
+ * Sources /Health and /HealthDetail consult.
141
151
  *
142
152
  * `detail` includes the progress summary (doc counts) on the lag reason.
143
153
  * Public /Health leaves it off — corpus size stays on the authenticated
@@ -183,7 +193,7 @@ export class HealthDetail extends Resource {
183
193
  return allowVerified(this.getContext?.());
184
194
  }
185
195
  async get() {
186
- const stats = { ok: true };
196
+ const stats = { ok: true, mcpOAuthProvider: mcpOAuthProviderReadiness() };
187
197
  const nowMs = Date.now();
188
198
  const warnings = [];
189
199
  // flair#1073: set while walking memories, consumed after the migrations
@@ -248,6 +258,9 @@ export class HealthDetail extends Resource {
248
258
  const isAdmin = auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin);
249
259
  stats.caller = { agentId: callerAgent ?? null, isAdmin };
250
260
  let memoriesList = [];
261
+ // Per-agent split of the expired-but-unarchived count, filled from the same
262
+ // single Memory scan below — not a second table read (flair#2231).
263
+ const expiredAgentCounts = new Map();
251
264
  // ── Memory stats ──
252
265
  try {
253
266
  for await (const m of db.flair.Memory.search({})) {
@@ -274,8 +287,11 @@ export class HealthDetail extends Resource {
274
287
  byDurability[d]++;
275
288
  if (m.archived)
276
289
  archived++;
277
- if (!m.archived && m.validTo && new Date(m.validTo).getTime() < nowMs)
290
+ if (!m.archived && m.validTo && new Date(m.validTo).getTime() < nowMs) {
278
291
  expired++;
292
+ const owner = typeof m.agentId === "string" ? m.agentId : "";
293
+ expiredAgentCounts.set(owner, (expiredAgentCounts.get(owner) ?? 0) + 1);
294
+ }
279
295
  }
280
296
  stats.memories = {
281
297
  total: memoriesList.length,
@@ -563,6 +579,10 @@ export class HealthDetail extends Resource {
563
579
  }
564
580
  // ── REM ──
565
581
  let nightlyRunFailed = false;
582
+ let nightlyProbeOk = false;
583
+ let nightlyInstalled = false;
584
+ let nightlyDriverAgent = null;
585
+ let nightlyDriverAgentKnown = false;
566
586
  try {
567
587
  const logsDir = join(homedir(), ".flair", "logs");
568
588
  const remLog = join(logsDir, "rem.jsonl");
@@ -621,29 +641,89 @@ export class HealthDetail extends Resource {
621
641
  // exist; async + short-timeout so a slow/hung service manager can't
622
642
  // stall this request.
623
643
  let nightlyEnabled = null;
624
- let nightlyInstalled = false;
625
644
  const plat = platform();
626
645
  if (plat === "darwin" || plat === "linux") {
627
- nightlyInstalled = plat === "darwin"
628
- ? await exists(join(homedir(), "Library", "LaunchAgents", "dev.flair.rem.nightly.plist"))
629
- : await exists(join(homedir(), ".config", "systemd", "user", "flair-rem-nightly.timer"));
630
- if (nightlyInstalled) {
646
+ const schedulerPath = plat === "darwin"
647
+ ? join(homedir(), "Library", "LaunchAgents", "dev.flair.rem.nightly.plist")
648
+ : join(homedir(), ".config", "systemd", "user", "flair-rem-nightly.timer");
649
+ const unitPath = plat === "darwin" ? schedulerPath
650
+ : join(homedir(), ".config", "systemd", "user", "flair-rem-nightly.service");
651
+ const probeError = (path, error) => {
652
+ const code = error?.code ?? "error code unavailable";
653
+ warnings.push({ level: "warn", message: `REM nightly driver state unknown: ${isAdmin ? path : redactHome(path)} (${code})` });
654
+ };
655
+ const filePresent = async (path) => {
656
+ try {
657
+ await fsp.stat(path);
658
+ return true;
659
+ }
660
+ catch (error) {
661
+ if (error?.code === "ENOENT")
662
+ return false;
663
+ probeError(path, error);
664
+ return null;
665
+ }
666
+ };
667
+ const [schedulerPresent, unitPresent] = await Promise.all([
668
+ filePresent(schedulerPath),
669
+ plat === "darwin" ? Promise.resolve(true) : filePresent(unitPath),
670
+ ]);
671
+ nightlyInstalled = schedulerPresent === null || unitPresent === null
672
+ ? null : schedulerPresent && unitPresent;
673
+ if (plat === "linux" && schedulerPresent !== null && unitPresent !== null
674
+ && schedulerPresent !== unitPresent) {
675
+ const orphan = schedulerPresent ? "timer" : "service";
676
+ const orphanPath = schedulerPresent ? schedulerPath : unitPath;
677
+ warnings.push({ level: "warn", message: `REM nightly orphan ${orphan} file: ${isAdmin ? orphanPath : redactHome(orphanPath)}` });
678
+ }
679
+ if (nightlyInstalled === true) {
631
680
  try {
632
681
  const { queryActiveStateAsync } = await import("../src/rem/scheduler.js");
633
682
  nightlyEnabled = await queryActiveStateAsync(plat);
683
+ if (nightlyEnabled === null)
684
+ probeError(schedulerPath);
634
685
  }
635
- catch {
686
+ catch (error) {
636
687
  nightlyEnabled = null;
688
+ probeError(schedulerPath, error);
689
+ }
690
+ try {
691
+ const unitText = await fsp.readFile(unitPath, "utf-8");
692
+ const agent = plat === "darwin"
693
+ ? unitText.match(/<key>FLAIR_AGENT_ID<\/key>\s*<string>([^<]+)<\/string>/)?.[1].trim() ?? null
694
+ : systemdAgentId(unitText);
695
+ if (agent) {
696
+ nightlyDriverAgent = agent;
697
+ nightlyDriverAgentKnown = true;
698
+ }
699
+ }
700
+ catch (error) {
701
+ probeError(unitPath, error);
637
702
  }
638
703
  }
639
- else {
704
+ else if (nightlyInstalled === false) {
640
705
  nightlyEnabled = false;
641
706
  }
642
707
  }
708
+ nightlyProbeOk = true;
643
709
  const nightlyRecords = await tailJsonl(nightlyLog);
644
710
  const lastNightlyRec = nightlyRecords[nightlyRecords.length - 1];
645
711
  nightlyRunFailed = lastNightlyRec?.status === "failed";
646
712
  const lastNightlyAt = lastNightlyRec ? (lastNightlyRec.at ?? lastNightlyRec.ts ?? lastNightlyRec.timestamp ?? null) : null;
713
+ // Newest distillation from a completed cycle with no errors or skips, observed in the server-local log tail.
714
+ let lastDistilledAt = null;
715
+ const completeDistillation = (rec) => rec?.status === "completed"
716
+ && !rec.errors?.length && !rec.skips?.length && !rec.distill?.aborted
717
+ && typeof rec.distilledAt === "string" && Number.isFinite(Date.parse(rec.distilledAt))
718
+ && Number.isInteger(rec.distill?.gathered) && rec.distill.gathered > 0;
719
+ const lastDistillationIncomplete = !!lastNightlyRec && !completeDistillation(lastNightlyRec);
720
+ for (let i = nightlyRecords.length - 1; i >= 0; i--) {
721
+ const rec = nightlyRecords[i];
722
+ if (completeDistillation(rec)) {
723
+ lastDistilledAt = rec.distilledAt;
724
+ break;
725
+ }
726
+ }
647
727
  let pendingCandidates = null;
648
728
  try {
649
729
  let count = 0;
@@ -661,6 +741,7 @@ export class HealthDetail extends Resource {
661
741
  !lastRestorativeAt &&
662
742
  nightlyEnabled === null &&
663
743
  !lastNightlyAt &&
744
+ !lastDistilledAt &&
664
745
  pendingCandidates === null;
665
746
  if (allNull) {
666
747
  stats.rem = null;
@@ -672,6 +753,8 @@ export class HealthDetail extends Resource {
672
753
  lastRestorativeAt,
673
754
  nightlyEnabled,
674
755
  lastNightlyAt,
756
+ lastDistilledAt,
757
+ lastDistillationIncomplete,
675
758
  pendingCandidates,
676
759
  };
677
760
  if (nightlyEnabled && lastNightlyAt && nowMs - new Date(lastNightlyAt).getTime() > 48 * 3600 * 1000) {
@@ -687,7 +770,7 @@ export class HealthDetail extends Resource {
687
770
  }
688
771
  // Build this after REM discovery, including its unavailable-state fallback.
689
772
  // 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.
773
+ // row does carry status.
691
774
  if (stats.memories?.expired > 0) {
692
775
  const nightlyHint = stats.rem?.nightlyEnabled === true
693
776
  ? nightlyRunFailed
@@ -696,9 +779,17 @@ export class HealthDetail extends Resource {
696
779
  : stats.rem?.nightlyEnabled === false
697
780
  ? "automate: flair rem nightly enable (includes validTo archival)"
698
781
  : "nightly state is unknown — check: flair rem nightly status";
782
+ const driver = {
783
+ installed: nightlyProbeOk ? nightlyInstalled : null,
784
+ agent: nightlyDriverAgent,
785
+ agentKnown: nightlyDriverAgentKnown,
786
+ };
787
+ const breakdown = summarizeExpiredByAgent(expiredAgentCounts, driver);
788
+ stats.memories.expiredByAgent = breakdown;
699
789
  warnings.push({
700
790
  level: "warn",
701
791
  message: `${stats.memories.expired} memories have expired validTo but aren't archived\n` +
792
+ expiredByAgentWarningLines(breakdown) +
702
793
  " clear now: flair rem light (archives expired validTo; preview: --dry-run)\n" +
703
794
  ` ${nightlyHint}`,
704
795
  });
@@ -749,7 +840,18 @@ export class HealthDetail extends Resource {
749
840
  // didn't run, not merely that it didn't.
750
841
  try {
751
842
  const migrationsDataDir = resolveMigrationDataDirForRead();
752
- const snapshot = getMigrationStatusSnapshot(migrationsDataDir);
843
+ const rawSnapshot = getMigrationStatusSnapshot(migrationsDataDir);
844
+ const redactReason = (reason) => reason ? "details redacted; consult the operator log or an administrator" : reason;
845
+ const snapshot = isAdmin ? rawSnapshot : {
846
+ ...rawSnapshot,
847
+ lastCycleError: redactReason(rawSnapshot.lastCycleError),
848
+ migrations: rawSnapshot.migrations.map((m) => ({
849
+ ...m,
850
+ reason: m.state === "completed" && m.reason
851
+ ? "recorded complete; not re-verified this boot"
852
+ : redactReason(m.reason),
853
+ })),
854
+ };
753
855
  stats.migrations = {
754
856
  cyclePhase: snapshot.cyclePhase,
755
857
  lastCycleAt: snapshot.lastCycleAt ?? null,
@@ -0,0 +1,49 @@
1
+ /**
2
+ * host-source-citation.ts — the bootstrap prose citation for a bound host
3
+ * pointer (flair#1940 A6). PURE and Harper-free (it depends only on the A2
4
+ * validator), so it is unit-testable directly and usable from the prose path.
5
+ *
6
+ * A6 asks for ONE exported citation format. The citation names the host object
7
+ * the WRITER CLAIMED — host/kind, then the first 8 characters of the id — and
8
+ * marks the claim `(unverified)`: flair does not verify the host object and does
9
+ * not sign the pointer body, so the citation attributes a claim, it never
10
+ * asserts host authorship. The 8-character id is display-only; the STORED id is
11
+ * never truncated. The full URL never appears here (A6 reserves it for MCP/CLI
12
+ * detail output), and the rendered citation is well under the 20-token budget
13
+ * (`HOST_SOURCE_CITATION_MAX_TOKENS`) for any accepted pointer.
14
+ *
15
+ * `formatHostSourceCitation` takes the GATED join's rendered value — the
16
+ * validated pointer OBJECT (see host-source-visibility.ts's `projectHostSource`),
17
+ * the literal `"withheld"`, or nothing — NOT the raw stored string. So the
18
+ * citation inherits the server's redaction decision and can never render a
19
+ * pointer the reader could not see.
20
+ */
21
+ /** The citation format template (A6). Exported so the test asserting the
22
+ * rendered shape and the caller share one definition. */
23
+ export const HOST_SOURCE_CITATION_FORMAT = "[via {host}/{kind} {id8} (unverified)]";
24
+ /** The number of id characters shown (A6: display-only; the stored id is never
25
+ * truncated). */
26
+ export const HOST_SOURCE_ID_DISPLAY_CHARS = 8;
27
+ /** The marker rendered in place of a pointer the reader may not see (A3). */
28
+ export const HOST_SOURCE_WITHHELD_CITATION = "[via withheld]";
29
+ /** The per-cited-item token ceiling A6 sets. */
30
+ export const HOST_SOURCE_CITATION_MAX_TOKENS = 20;
31
+ /**
32
+ * Render the bootstrap citation for one joined pointer value, or null when the
33
+ * record has no renderable pointer (no pointer, an unbound/archived pointer, or
34
+ * a value that does not re-validate). A `"withheld"` pointer renders the
35
+ * withheld marker, so the "externally sourced" signal survives without
36
+ * revealing the host object (A3).
37
+ */
38
+ export function formatHostSourceCitation(rendered) {
39
+ if (rendered === "withheld" || rendered === HOST_SOURCE_WITHHELD_CITATION) {
40
+ return HOST_SOURCE_WITHHELD_CITATION;
41
+ }
42
+ if (!rendered || typeof rendered !== "object")
43
+ return null;
44
+ const { host, kind, id } = rendered;
45
+ if (typeof host !== "string" || typeof kind !== "string" || typeof id !== "string" || id.length === 0) {
46
+ return null;
47
+ }
48
+ return `[via ${host}/${kind} ${id.slice(0, HOST_SOURCE_ID_DISPLAY_CHARS)} (unverified)]`;
49
+ }
@@ -34,10 +34,10 @@
34
34
  * never with Memory provenance.
35
35
  *
36
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).
37
+ * or MCP layer can un-redact. `Memory.get()`, `Memory.search()`,
38
+ * `SemanticSearch` and bootstrap render pointers through the pointer helper;
39
+ * bootstrap renders a visible pointer as a prose citation (A6; see
40
+ * resources/MemoryBootstrap.ts).
41
41
  */
42
42
  import { parseHostSource } from "./host-source.js";
43
43
  import { isPrivateVisibility } from "./memory-visibility.js";
@@ -116,8 +116,9 @@ export function pointerOutcomeFor(record, readerAgentId, pointer) {
116
116
  /** The pointer-input keys the named non-admin read paths remove from their
117
117
  * output (A1' item 1). A supported write strips them before persist; a RAW
118
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. */
119
+ * Memory.search, SemanticSearch) strip them. Bootstrap projects through the
120
+ * pointer helper too, so its inline fields are dropped as well, except where
121
+ * its `?? m` fallback uses the row as read. */
121
122
  const INLINE_POINTER_FIELDS = ["hostSource", "hostSourceScope", "hostSourceVisibility"];
122
123
  /** Return `record` with every inline pointer-input field removed. Returns the
123
124
  * SAME reference when there is nothing to remove, so a clean record is
@@ -71,6 +71,23 @@ export const KEYSTORE_FAILURE_NOTE = "[federation] Could not store the federatio
71
71
  /** The lock-dir remedy, in the same style as KEYSTORE_FAILURE_NOTE. */
72
72
  export const LOCK_DIR_REMEDY = "Remedy: make the Flair home writable by the Harper process (a directory the process can create " +
73
73
  "$HOME/.flair/locks with mode 0700). Identity creation is REFUSED while the lock dir is unusable.";
74
+ /** The sidecar-write failure note (flair#2200) — the seed IS stored; only ownership is missing. */
75
+ export function seedOwnerFailureNote(id, err) {
76
+ return (`[federation] stored the signing seed for ${id} but could not record its ownership sidecar ` +
77
+ `(${err instanceof Error ? err.message : String(err)}). Node-shaped files without .pub stay report-only. ` +
78
+ `Remedy: inspect and clear any conflicting sidecar path; check that $HOME/.flair/keys is writable by the Harper process (mode 0700).`);
79
+ }
80
+ /** Store the seed and attempt to record its sidecar; metadata failure is logged. */
81
+ export async function storeInstanceSeed(id, seed, dataDir = harperRootPath()) {
82
+ const { keystore, recordSeedOwner } = await import("../src/keystore.js");
83
+ keystore.setPrivateKeySeed(id, seed);
84
+ try {
85
+ recordSeedOwner(id, dataDir);
86
+ }
87
+ catch (err) {
88
+ console.error(seedOwnerFailureNote(id, err));
89
+ }
90
+ }
74
91
  /**
75
92
  * Harper's data root for THIS process — the `ROOTPATH` env var Harper sets for a
76
93
  * component (read the same way `resources/models-dir.ts` reads it). The lock lives
@@ -122,6 +122,29 @@ export async function localInstanceId() {
122
122
  // "none" — a SUCCESSFUL read found no Instance row: null, uncached, as today.
123
123
  return null;
124
124
  }
125
+ /**
126
+ * This instance's canonical id from the `Instance` table AS IT IS NOW: a fresh
127
+ * read on every call, through the same strict reader and the same shared rule as
128
+ * {@link localInstanceId}, but never answered from that function's cache and
129
+ * never written into it (flair#2472).
130
+ *
131
+ * For a guard that must refuse when it could not confirm a single canonical
132
+ * Instance row. `localInstanceId()` keeps a successful id for the process
133
+ * lifetime, so after that row is removed, or a second row is added, it still
134
+ * answers the old id. This returns null when the read finds no row, several
135
+ * rows, or fails.
136
+ */
137
+ export async function currentInstanceId() {
138
+ let rows;
139
+ try {
140
+ rows = await readAllInstanceRows();
141
+ }
142
+ catch {
143
+ return null;
144
+ }
145
+ const decision = decideInstanceAnswer(rows);
146
+ return decision.kind === "answer" ? decision.row.id : null;
147
+ }
125
148
  /**
126
149
  * Test-only: force re-resolution on the next localInstanceId() call. The
127
150
  * module-level cache otherwise persists across test files that share the