@tpsdev-ai/flair 0.55.2 → 0.57.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 (106) hide show
  1. package/README.md +18 -19
  2. package/dist/bridges/builtins/markdown.js +2 -2
  3. package/dist/bridges/discover.js +2 -2
  4. package/dist/bridges/runtime/allow-list.js +2 -2
  5. package/dist/build-info.json +3 -3
  6. package/dist/cli.js +125 -26
  7. package/dist/commands/agent.js +22 -15
  8. package/dist/commands/attention.js +2 -2
  9. package/dist/commands/backup.js +2 -2
  10. package/dist/commands/bridge.js +40 -3
  11. package/dist/commands/doctor.js +91 -28
  12. package/dist/commands/export.js +2 -2
  13. package/dist/commands/federation.js +441 -68
  14. package/dist/commands/hook.js +4 -4
  15. package/dist/commands/init.js +59 -12
  16. package/dist/commands/mcp.js +2 -2
  17. package/dist/commands/migrate-harness-memory.js +8 -8
  18. package/dist/commands/rem.js +2 -2
  19. package/dist/commands/service.js +25 -1
  20. package/dist/commands/session.js +2 -2
  21. package/dist/commands/uninstall.js +2 -2
  22. package/dist/commands/upgrade.js +3 -3
  23. package/dist/doctor-client.js +5 -23
  24. package/dist/engine-version.js +2 -2
  25. package/dist/federation/scheduler.js +5 -5
  26. package/dist/install/clients.js +5 -10
  27. package/dist/keystore.js +10 -2
  28. package/dist/lib/auth-resolve.js +51 -5
  29. package/dist/lib/doctor-config-path.js +2 -2
  30. package/dist/lib/flair-paths.js +29 -0
  31. package/dist/lib/home.js +60 -0
  32. package/dist/lib/instance-identity-row.js +580 -0
  33. package/dist/lib/launchd-repair.js +6 -0
  34. package/dist/lib/mcp-enable.js +4 -4
  35. package/dist/lib/owned-pins.js +1 -13
  36. package/dist/lib/redact-token-id.js +197 -0
  37. package/dist/lib/socket-path-limit.js +120 -0
  38. package/dist/lib/uninstall-purge.js +2 -18
  39. package/dist/lib/upgrade-plain-tree.js +2 -2
  40. package/dist/mcp-client-assertion.js +3 -3
  41. package/dist/rem/runner.js +3 -3
  42. package/dist/rem/scheduler.js +5 -5
  43. package/dist/rem/snapshot.js +2 -2
  44. package/dist/resources/AgentSeed.js +4 -1
  45. package/dist/resources/Asset.js +3 -11
  46. package/dist/resources/Credential.js +4 -10
  47. package/dist/resources/Federation.js +232 -78
  48. package/dist/resources/Integration.js +8 -32
  49. package/dist/resources/Memory.js +58 -16
  50. package/dist/resources/MemoryBootstrap.js +19 -12
  51. package/dist/resources/MemoryCandidate.js +3 -11
  52. package/dist/resources/MemoryDedupStats.js +1 -1
  53. package/dist/resources/MemoryFeed.js +10 -2
  54. package/dist/resources/MemoryGrant.js +19 -40
  55. package/dist/resources/MemoryUsage.js +7 -20
  56. package/dist/resources/OAuth.js +62 -11
  57. package/dist/resources/Presence.js +135 -47
  58. package/dist/resources/Relationship.js +3 -11
  59. package/dist/resources/SemanticSearch.js +25 -13
  60. package/dist/resources/admin-layout.js +7 -2
  61. package/dist/resources/auth-middleware.js +32 -5
  62. package/dist/resources/bm25.js +13 -14
  63. package/dist/resources/federation-cleanup.js +289 -51
  64. package/dist/resources/health.js +48 -8
  65. package/dist/resources/in-process-api.js +2 -1
  66. package/dist/resources/instance-create-lock.js +363 -0
  67. package/dist/resources/instance-identity-rows.js +43 -0
  68. package/dist/resources/instance-identity.js +94 -10
  69. package/dist/resources/mcp-handler.js +9 -1
  70. package/dist/resources/mcp-tool-arguments.js +83 -0
  71. package/dist/resources/mcp-tools.js +4 -5
  72. package/dist/resources/memory-reflect-lib.js +17 -1
  73. package/dist/resources/memory-visibility.js +10 -7
  74. package/dist/resources/rate-limit.js +6 -4
  75. package/dist/resources/record-type-kit.js +47 -23
  76. package/dist/resources/search-readiness.js +7 -1
  77. package/dist/resources/semantic-retrieval-core.js +98 -3
  78. package/dist/resources/table-helpers.js +33 -0
  79. package/dist/resources/tool-descriptors/index.js +2 -2
  80. package/dist/src/keystore.js +10 -2
  81. package/dist/src/lib/home.js +60 -0
  82. package/dist/src/lib/instance-identity-row.js +580 -0
  83. package/dist/src/lib/redact-token-id.js +197 -0
  84. package/dist/src/rem/scheduler.js +5 -5
  85. package/dist/version-check.js +2 -2
  86. package/dist/version-handshake.js +2 -2
  87. package/docs/api-reference.md +32 -7
  88. package/docs/auth.md +19 -7
  89. package/docs/claude-code.md +5 -6
  90. package/docs/deploying-on-fabric.md +8 -4
  91. package/docs/deployment.md +26 -37
  92. package/docs/embedding-in-a-harper-app.md +4 -2
  93. package/docs/entity-vocabulary.md +5 -5
  94. package/docs/federation.md +48 -21
  95. package/docs/hosted-on-fabric.md +7 -4
  96. package/docs/integrations.md +24 -15
  97. package/docs/mcp-clients.md +44 -23
  98. package/docs/n8n.md +8 -8
  99. package/docs/notes/mcp-oauth-model2.md +12 -17
  100. package/docs/openclaw.md +29 -28
  101. package/docs/spoke-bringup.md +44 -22
  102. package/docs/standalone-local.md +12 -16
  103. package/docs/supply-chain-policy.md +21 -8
  104. package/docs/system-requirements.md +1 -1
  105. package/docs/upgrade.md +2 -2
  106. package/package.json +1 -1
@@ -1,21 +1,31 @@
1
+ import { decideSweepMode, INSTANCE_ROW_PRUNE_REMEDY, readableInstanceRows, writeConfirmed, } from "../src/lib/instance-identity-row.js";
2
+ import { createTokenRedactor, redactTokenMessage, TOKEN_ID_PREFIX_LENGTH, } from "../src/lib/redact-token-id.js";
1
3
  const CLEANUP_INTERVAL_MS = 300_000; // 5 minutes
4
+ /** Prefix of the throwaway Basic users minted by `flair federation token`. */
5
+ export const BOOTSTRAP_USER_PREFIX = "pair-bootstrap-";
2
6
  let cleanupTimer = null;
3
7
  /**
4
8
  * Initialise the federation cleanup sweep.
5
9
  *
6
- * Only active on hub instances — reads the Instance table to determine
7
- * role. On spokes this is a no-op.
10
+ * The sweep is INSTALLED on every instance and re-reads the identity row's role
11
+ * on EVERY tick (flair#1883). It used to read the role once, at module init,
12
+ * before the server had started: on a fresh hub no `Instance` row existed yet,
13
+ * so the check saw "not a hub", disabled the sweep permanently, and later ticks
14
+ * never re-read. Nothing about that is a property of a hub — it is a property of
15
+ * when a row happened to appear.
8
16
  *
9
- * On hubs: ensures a 5-minute setInterval that sweeps PairingToken records
10
- * for consumed or expired tokens, drops the corresponding bootstrap users,
11
- * and performs housekeeping on expired/unconsumed token records.
17
+ * A role of `hub` is what runs the sweep; two or more `Instance` rows is a
18
+ * logged error with its remedy, never "first row wins"; an `Instance` read that
19
+ * failed is its own state, not a spoke.
12
20
  *
13
21
  * In test environments, callers pass mock serverOp/db via `opts` so this
14
22
  * module never imports harper at the top level (which would
15
- * crash when STORAGE_PATH isn't set).
23
+ * crash when STORAGE_PATH isn't set). `instanceRole` overrides the per-tick
24
+ * read (tests); `intervalMs` shortens the cadence (tests).
16
25
  */
17
26
  export async function initFederationCleanup(opts) {
18
27
  const immediate = opts?.immediateTick ?? true;
28
+ const intervalMs = opts?.intervalMs ?? CLEANUP_INTERVAL_MS;
19
29
  // Resolve server / databases: use caller-supplied mocks when available,
20
30
  // otherwise lazy-import harper at call time.
21
31
  let svr;
@@ -35,42 +45,159 @@ export async function initFederationCleanup(opts) {
35
45
  return;
36
46
  }
37
47
  }
38
- const role = opts?.instanceRole !== undefined
39
- ? opts.instanceRole
40
- : await getInstanceRole(db);
41
- if (role !== "hub") {
42
- console.log("[federation-cleanup] not a hub instance — cleanup disabled");
43
- return;
44
- }
45
- console.log("[federation-cleanup] starting cleanup sweep (5-min cadence)");
48
+ console.log(`[federation-cleanup] sweep installed (${Math.round(intervalMs / 1000)}s cadence); the identity role is re-read on every tick`);
46
49
  if (cleanupTimer)
47
50
  clearInterval(cleanupTimer);
48
- cleanupTimer = setInterval(() => {
49
- runCleanupTick({ serverOp: svr, db }).catch((err) => {
50
- console.error("[federation-cleanup] tick error:", err?.message ?? err);
51
- });
52
- }, CLEANUP_INTERVAL_MS);
51
+ const state = { last: null };
52
+ const tick = () => runSweepTick({
53
+ serverOp: svr,
54
+ db,
55
+ instanceRole: opts?.instanceRole,
56
+ state,
57
+ }).catch((err) => {
58
+ // The ids this tick read are mirrored on `state`; route the failure through
59
+ // the same redactor, so an error that echoes one is cut to its prefix too
60
+ // (flair#1902).
61
+ logTickError(err, state);
62
+ });
63
+ cleanupTimer = setInterval(tick, intervalMs);
53
64
  if (immediate) {
54
- // Run an immediate first tick after role detection
55
- runCleanupTick({ serverOp: svr, db }).catch((err) => {
56
- console.error("[federation-cleanup] initial tick error:", err?.message ?? err);
57
- });
65
+ // Run an immediate first tick after installing the sweep
66
+ await tick();
58
67
  }
59
68
  }
69
+ /** Stop the sweep. Tests install a short cadence and must be able to end it. */
70
+ export function stopFederationCleanup() {
71
+ if (cleanupTimer)
72
+ clearInterval(cleanupTimer);
73
+ cleanupTimer = null;
74
+ }
60
75
  /**
61
- * Look up the instance role from the Instance table.
62
- * Returns null if the table doesn't exist or no record is present.
76
+ * One sweep tick: decide from the CURRENT identity rows, then sweep if hub.
77
+ *
78
+ * Exported so the decision can be driven directly (and so a test can watch a
79
+ * hub row appear after startup start the sweep without a restart).
63
80
  */
64
- async function getInstanceRole(db) {
81
+ export async function runSweepTick(opts) {
82
+ let db = opts.db;
83
+ if (opts.instanceRole === undefined && db === undefined) {
84
+ const harper = await import("harper");
85
+ db = harper.databases;
86
+ }
87
+ const rows = opts.instanceRole !== undefined
88
+ ? [{ id: "(explicit role)", role: opts.instanceRole }]
89
+ : await readInstanceRowsOrNull(db);
90
+ const mode = decideSweepMode(rows);
91
+ noteSweepMode(mode, opts.state, opts.log);
92
+ if (mode !== "hub")
93
+ return mode;
94
+ let svr;
95
+ if (opts.serverOp) {
96
+ svr = opts.serverOp;
97
+ }
98
+ else {
99
+ const harper = await import("harper");
100
+ svr = harper.server.operation;
101
+ }
102
+ const users = await listUsernamesOrNull(svr, opts.log);
103
+ await runCleanupTick({ serverOp: svr, db, now: opts.now, users, state: opts.state });
104
+ return mode;
105
+ }
106
+ /**
107
+ * Log a tick-level failure through the token-id redactor, carrying the ids the
108
+ * tick read (mirrored on `state`), so an error that echoes one is cut to its
109
+ * prefix (flair#1902). Exported so the path can be driven directly: nothing
110
+ * inside a tick throws after the scan today, so the wiring has no reachable site
111
+ * of its own to exercise — but this line is a catch-all and must not print an
112
+ * id whole if one ever does.
113
+ */
114
+ export function logTickError(err, state, log = console) {
115
+ const redactor = createTokenRedactor(state?.seenTokenIds ?? []);
116
+ log.error(redactor.redactMessage("[federation-cleanup] tick error:"), redactor.redactMessage(String(err?.message ?? err)));
117
+ }
118
+ /** Log the sweep's state; only on change, so a steady state is not a log flood. */
119
+ export function noteSweepMode(mode, state, log = console) {
120
+ if (state) {
121
+ if (state.last === mode)
122
+ return;
123
+ state.last = mode;
124
+ }
125
+ switch (mode) {
126
+ case "hub":
127
+ log.log("[federation-cleanup] this instance is the hub — cleanup sweep active");
128
+ return;
129
+ case "not-hub":
130
+ log.log("[federation-cleanup] not a hub instance — nothing to sweep");
131
+ return;
132
+ case "multiple":
133
+ log.error("[federation-cleanup] ERROR: this instance has more than one Instance row, so it has no canonical identity " +
134
+ "and the sweep cannot know whether it is a hub. No cleanup will run.");
135
+ log.error(`[federation-cleanup] Fix: keep one row and delete the rest — ${INSTANCE_ROW_PRUNE_REMEDY} ` +
136
+ `(see \`flair doctor\`, which lists the rows)`);
137
+ return;
138
+ case "unreadable":
139
+ log.log("[federation-cleanup] could not read the Instance table this tick — sweep paused, not disabled");
140
+ return;
141
+ }
142
+ }
143
+ /**
144
+ * All Instance rows, or null when the read failed. Null is its own answer: a
145
+ * failed read is not a spoke, and must not be reported as one. An entry with no
146
+ * usable id makes the whole read unreadable (the same strict reader init and the
147
+ * server use): a row the sweep cannot name may be a second identity, so the
148
+ * sweep pauses rather than treating the rest as the whole table.
149
+ */
150
+ async function readInstanceRowsOrNull(db) {
65
151
  try {
152
+ const entries = [];
66
153
  for await (const inst of db.flair.Instance.search()) {
67
- return inst.role ?? null;
154
+ entries.push(inst);
68
155
  }
156
+ return readableInstanceRows(entries);
69
157
  }
70
158
  catch {
71
159
  /* table may not exist yet */
160
+ return null;
161
+ }
162
+ }
163
+ /**
164
+ * The usernames of the `pair-bootstrap-*` users on this instance, or null when
165
+ * the list could not be read. Only the usernames — never a credential.
166
+ */
167
+ export async function listUsernamesOrNull(svr, log = console, secrets = []) {
168
+ try {
169
+ const result = await svr({ operation: "list_users" }, { user: null }, false);
170
+ const users = Array.isArray(result) ? result : Array.isArray(result?.users) ? result.users : null;
171
+ if (users === null)
172
+ return null;
173
+ return users
174
+ .map((u) => (typeof u === "string" ? u : u?.username ?? u?.user?.username))
175
+ .filter((name) => typeof name === "string" && name.startsWith(BOOTSTRAP_USER_PREFIX));
176
+ }
177
+ catch (err) {
178
+ // A table-level line: routed through the same redactor, with the ids read so
179
+ // far (none by default — list_users runs before the token scan; a caller may
180
+ // pass any it already holds) (flair#1902).
181
+ log.error(redactTokenMessage("[federation-cleanup] failed to list users:", secrets), redactTokenMessage(String(err?.message ?? err), secrets));
182
+ return null;
72
183
  }
73
- return null;
184
+ }
185
+ /**
186
+ * Log one line about one pairing token, or about the bootstrap user named for
187
+ * it, through the ONE shared token-id redactor
188
+ * (src/lib/redact-token-id.ts, flair#1902): every `secret` is cut to its
189
+ * 8-character prefix in the message and in every string of the fields at any
190
+ * depth — string values, array elements, and object KEYS. Non-string values
191
+ * pass through untouched.
192
+ *
193
+ * `secrets` is the current token id PLUS every token id the sweep has read this
194
+ * pass, so a caller-supplied value that embeds a DIFFERENT token id (e.g. a
195
+ * `consumedBy` naming another token) is cut too. Hygiene, not a boundary: this
196
+ * log is the operator's, and the sweep touches only expired or consumed tokens,
197
+ * which cannot pair.
198
+ */
199
+ function tokenLog(level, message, fields, redact) {
200
+ console[level](redact.redactMessage(message), redact.redactValue(fields));
74
201
  }
75
202
  /**
76
203
  * Core cleanup logic — exposed for unit testing.
@@ -82,6 +209,11 @@ async function getInstanceRole(db) {
82
209
  * swallowed).
83
210
  * - Deletes the PairingToken record if expired AND not consumed
84
211
  * (housekeeping). Consumed records are kept for audit.
212
+ * - THEN walks the `pair-bootstrap-*` users the caller listed (`users`) and
213
+ * drops every one whose token is missing, consumed or expired (flair#1883).
214
+ * Iterating tokens alone cannot see those users: a bootstrap user whose token
215
+ * record is gone is invisible to every token-shaped query, which is exactly
216
+ * the debris this sweep exists to collect.
85
217
  *
86
218
  * Logging emits token-id prefix only (NEVER the full username, NEVER a
87
219
  * password).
@@ -101,61 +233,167 @@ export async function runCleanupTick(opts = {}) {
101
233
  const now = opts.now ?? new Date();
102
234
  // ── Query candidates ──────────────────────────────────────────────────
103
235
  const candidates = [];
236
+ // Every token id READ this pass. The redactor's secrets are the current token
237
+ // id plus these, so a value that embeds a DIFFERENT token id (a consumedBy
238
+ // naming another token, a Harper error echoing one) is cut too (flair#1902).
239
+ if (opts.state && !opts.state.seenTokenIds)
240
+ opts.state.seenTokenIds = [];
241
+ const seenTokenIds = opts.state?.seenTokenIds ?? [];
242
+ seenTokenIds.length = 0; // this tick's ids only
243
+ // Token-id prefixes that are still LIVE (unconsumed and unexpired). A live
244
+ // token still needs its bootstrap user, so the user-driven pass (below) must
245
+ // not collect that user. Built in the same scan: one pass over the table.
246
+ const liveTokenPrefixes = new Set();
104
247
  try {
105
248
  for await (const token of db.flair.PairingToken.search()) {
249
+ if (token && token.id !== undefined && token.id !== null) {
250
+ seenTokenIds.push(String(token.id));
251
+ }
106
252
  const consumed = !!token.consumedBy;
107
253
  const expired = token.expiresAt && new Date(token.expiresAt) < now;
108
254
  if (consumed || expired) {
109
255
  candidates.push(token);
110
256
  }
257
+ else {
258
+ liveTokenPrefixes.add(String(token.id).slice(0, 8));
259
+ }
111
260
  }
112
261
  }
113
262
  catch (err) {
114
- console.error("[federation-cleanup] failed to query PairingToken records:", err?.message ?? err);
263
+ // A table-level line: routed through the same redactor, with the ids read so
264
+ // far (which may be none). A mid-scan failure can still echo an id already
265
+ // read, so this is not a no-op path (flair#1902).
266
+ tokenLog("error", "[federation-cleanup] failed to query PairingToken records", { err: String(err?.message ?? err) }, createTokenRedactor(seenTokenIds));
115
267
  return;
116
268
  }
117
269
  // ── Process each candidate ────────────────────────────────────────────
270
+ // ONE redactor for the whole pass, compiled from every id the scan read: the
271
+ // current candidate's id is in that set, and so is any foreign id a value may
272
+ // embed, so per-candidate lines need no per-line matcher (flair#1902).
273
+ const redactor = createTokenRedactor(seenTokenIds);
274
+ const droppedUsers = new Set();
118
275
  for (const token of candidates) {
119
276
  const tokenId = token.id;
120
277
  const consumed = !!token.consumedBy;
121
278
  const expired = token.expiresAt && new Date(token.expiresAt) < now;
122
- const bootstrapUsername = `pair-bootstrap-${tokenId.slice(0, 8)}`;
279
+ const bootstrapUsername = `${BOOTSTRAP_USER_PREFIX}${tokenId.slice(0, 8)}`;
123
280
  // Drop the bootstrap user
124
- try {
125
- await svr({ operation: "drop_user", username: bootstrapUsername }, { user: null }, false);
126
- console.log("[federation-cleanup] dropped user", { tid: tokenId.slice(0, 8) });
127
- }
128
- catch (err) {
129
- const msg = err?.message ?? "";
130
- const isNotFound = err?.statusCode === 404 ||
131
- msg.toLowerCase().includes("not exist") ||
132
- msg.toLowerCase().includes("not found");
133
- if (isNotFound) {
134
- // Idempotent — user already gone, no action needed
135
- }
136
- else {
137
- console.error("[federation-cleanup] drop_user error", { tid: tokenId.slice(0, 8), err: String(err?.message ?? err) });
138
- }
139
- }
281
+ await dropBootstrapUser(svr, bootstrapUsername, tokenId.slice(0, 8), droppedUsers, redactor);
140
282
  // ── Housekeeping ────────────────────────────────────────────────────
141
283
  if (expired && !consumed) {
142
284
  // Delete the expired, unconsumed token record itself
143
285
  try {
144
- await svr({
286
+ const result = await svr({
145
287
  operation: "delete",
146
288
  database: "flair",
147
289
  table: "PairingToken",
148
- hash_value: tokenId,
290
+ // `hash_values` is the field Harper's delete schema REQUIRES. The
291
+ // singular `hash_value` this used to send is refused with a 400 on
292
+ // Harper 5.2.8, so an expired token record was never actually
293
+ // deleted: every tick retried the same delete and logged the same
294
+ // error. Found by the live-Harper test
295
+ // (test/integration/init-remote-instance-identity.test.ts).
296
+ hash_values: [tokenId],
149
297
  }, { user: null }, false);
150
- console.log("[federation-cleanup] deleted expired token", { tid: tokenId.slice(0, 8) });
298
+ // Verified against the RESULT, the way `deleteInstanceRow` and
299
+ // `updateInstanceRole` verify their writes (flair#1898): Harper answers a
300
+ // delete with 200 even when it removes nothing, reporting what it removed
301
+ // in `deleted_hashes` and naming a record it did NOT remove in
302
+ // `skipped_hashes`. Status alone would let a skipped record be logged as
303
+ // deleted — a cleanup that did not happen. A skipped record is left in the
304
+ // table, so the next tick sees it as a candidate again and retries it.
305
+ if (writeConfirmed(result, "deleted_hashes", tokenId)) {
306
+ tokenLog("log", "[federation-cleanup] deleted expired token", { tid: tokenId.slice(0, 8) }, redactor);
307
+ }
308
+ else {
309
+ tokenLog("error", "[federation-cleanup] expired token delete NOT confirmed — Harper's result does not confirm the record was removed; if it is still in the table, the next tick retries it",
310
+ // The token id IS the pairing credential, and skipped_hashes holds
311
+ // token ids: log the prefix, as every other line in this sweep does,
312
+ // and whether Harper named this token as skipped, never the values.
313
+ {
314
+ tid: tokenId.slice(0, 8),
315
+ namedSkipped: Array.isArray(result?.skipped_hashes)
316
+ ? result.skipped_hashes.map(String).includes(tokenId)
317
+ : "no skipped_hashes in the result",
318
+ }, redactor);
319
+ }
151
320
  }
152
321
  catch (err) {
153
- console.error("[federation-cleanup] delete token error", { tid: tokenId.slice(0, 8), err: String(err?.message ?? err) });
322
+ tokenLog("error", "[federation-cleanup] delete token error",
323
+ // A Harper error can echo the request, and the token id is the
324
+ // pairing credential: cut every occurrence of it to its prefix.
325
+ { tid: tokenId.slice(0, 8), err: String(err?.message ?? err) }, redactor);
154
326
  }
155
327
  }
156
328
  // Consumed tokens: keep record for audit trail
157
329
  if (consumed) {
158
- console.log("[federation-cleanup] keeping audit record", { tid: tokenId.slice(0, 8), consumedBy: token.consumedBy });
330
+ tokenLog("log", "[federation-cleanup] keeping audit record", { tid: tokenId.slice(0, 8), consumedBy: token.consumedBy }, redactor);
331
+ }
332
+ }
333
+ // ── User-driven pass (flair#1883) ──────────────────────────────────────
334
+ // Every `pair-bootstrap-*` user whose token is missing, consumed or expired
335
+ // goes, whether or not this tick saw a token row for it. A user whose token
336
+ // is gone has no token to iterate.
337
+ if (opts.users) {
338
+ // Collect the users to drop first (bootstrap-prefixed and not live), then
339
+ // compile ONE redactor over the ids read plus their suffixes, and drop them.
340
+ // A username suffix IS the token's first 8 characters for a real bootstrap
341
+ // user, but a hand-made one can carry a whole token id and Harper's error can
342
+ // echo the name, so a long suffix is a secret too (flair#1902).
343
+ const toDrop = [];
344
+ for (const username of opts.users) {
345
+ // Only bootstrap users. The reader already filters by prefix; this is the
346
+ // write-side guard: a caller that hands this function an `admin` must not
347
+ // be able to get it dropped.
348
+ if (!username.startsWith(BOOTSTRAP_USER_PREFIX))
349
+ continue;
350
+ const tid = username.slice(BOOTSTRAP_USER_PREFIX.length);
351
+ if (liveTokenPrefixes.has(tid))
352
+ continue;
353
+ toDrop.push({ username, tid });
354
+ }
355
+ const userRedactor = createTokenRedactor([
356
+ ...seenTokenIds,
357
+ // A real bootstrap user's suffix IS the token's 8-character prefix — the
358
+ // very value this log prints anyway — so it is not a secret. Adding it
359
+ // would let the length guard replace the prefix itself with [redacted],
360
+ // and the operator could no longer tell which user was dropped. Only a
361
+ // suffix LONGER than the prefix (a hand-made user carrying a whole token
362
+ // id, which Harper's error can echo) is a secret (flair#1902).
363
+ ...toDrop.map(({ tid }) => tid).filter((tid) => tid.length > TOKEN_ID_PREFIX_LENGTH),
364
+ ]);
365
+ for (const { username, tid } of toDrop) {
366
+ await dropBootstrapUser(svr, username, tid, droppedUsers, userRedactor);
367
+ }
368
+ }
369
+ }
370
+ /**
371
+ * Drop one bootstrap user, idempotently. A 404 (or an equivalent "no such
372
+ * user" refusal) is the desired end state, not an error; anything else is
373
+ * logged with the token-id prefix and never aborts the sweep.
374
+ */
375
+ async function dropBootstrapUser(svr, username, tid, droppedUsers, redact) {
376
+ if (droppedUsers.has(username))
377
+ return;
378
+ droppedUsers.add(username);
379
+ try {
380
+ await svr({ operation: "drop_user", username }, { user: null }, false);
381
+ tokenLog("log", "[federation-cleanup] dropped user", { tid: tid.slice(0, 8) }, redact);
382
+ }
383
+ catch (err) {
384
+ const msg = err?.message ?? "";
385
+ const isNotFound = err?.statusCode === 404 ||
386
+ msg.toLowerCase().includes("not exist") ||
387
+ msg.toLowerCase().includes("not found");
388
+ if (isNotFound) {
389
+ // Idempotent — user already gone, no action needed
390
+ }
391
+ else {
392
+ tokenLog("error", "[federation-cleanup] drop_user error",
393
+ // A bootstrap username is pair-bootstrap- plus the token's first 8
394
+ // characters, but a hand-made one can carry more, and Harper's error can
395
+ // echo it: bound the suffix and cut it out of the message.
396
+ { tid: tid.slice(0, 8), err: String(err?.message ?? err) }, redact);
159
397
  }
160
398
  }
161
399
  }
@@ -8,7 +8,7 @@ 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";
11
+ import { hybridEnabled, retrievalMode } from "./bm25.js";
12
12
  import { bm25IndexEnabled, bm25IndexStatus } from "./bm25-index-service.js";
13
13
  import { normalizeStamp } from "./embedding-space-guard.js";
14
14
  import { getModelId } from "./embeddings-provider.js";
@@ -16,6 +16,8 @@ import { describeStampOutstanding, EMBEDDING_STAMP_ID } from "./migrations/stamp
16
16
  import { buildPublicHealthBody, resolveSearchReadiness } from "./search-readiness.js";
17
17
  import { withEmbedGpuHealth } from "./embed-gpu.js";
18
18
  import { classifyPeerLiveness, federationPeersAllDisconnectedWarning, PEER_LIVENESS_MEASURED_BY, summarizePeerLiveness, } from "./federation-peer-liveness.js";
19
+ import { decideInstanceAnswer, INSTANCE_ROW_PRUNE_REMEDY } from "../src/lib/instance-identity-row.js";
20
+ import { readAllInstanceRows } from "./Federation.js";
19
21
  const db = databases;
20
22
  const redactHome = (p) => {
21
23
  const home = homedir();
@@ -136,6 +138,7 @@ export function currentSearchReadiness() {
136
138
  memoryTable: db.flair?.Memory,
137
139
  bm25: bm25IndexStatus(),
138
140
  hybridEnabled: hybridEnabled(),
141
+ retrievalMode: retrievalMode(),
139
142
  bm25IndexEnabled: bm25IndexEnabled(),
140
143
  warn: (message) => { logger.warn?.(message); },
141
144
  });
@@ -182,6 +185,10 @@ export class HealthDetail extends Resource {
182
185
  warnings.push({ level: "warn", message: embeddingBody.embedding.fallback });
183
186
  }
184
187
  stats.searchReady = readiness.searchReady;
188
+ // The active retrieval strategy (retrievalMode() in ./bm25.ts) — reported
189
+ // so an operator can see WHICH ranker a process is serving from. Default
190
+ // (FLAIR_RETRIEVAL_MODE unset) is "hybrid", the shipped behavior.
191
+ stats.retrievalMode = retrievalMode();
185
192
  // Public/detail shape is unchanged: searchReadyReason stays a lag signal
186
193
  // (present iff !searchReady). Ready-path verification constants stay on
187
194
  // the decision object (flair#1411).
@@ -371,12 +378,46 @@ export class HealthDetail extends Resource {
371
378
  }
372
379
  // ── Federation ──
373
380
  try {
374
- const instances = [];
381
+ // flair#1896: read the Instance rows the SAME way GET /FederationInstance
382
+ // does — through readAllInstanceRows (the strict reader, which throws on a
383
+ // row it cannot name) and decide with decideInstanceAnswer. A read that
384
+ // FAILS is not "no instance": it must report unreadable, never a silent
385
+ // null (swallowing a failed read as absent was the defect this fix ends).
386
+ // Several rows are a refusal naming the prune, never a coin-toss pick of
387
+ // whichever row the search happened to yield first.
388
+ let instanceReport = null;
375
389
  try {
376
- for await (const i of db.flair.Instance.search({}))
377
- instances.push(i);
390
+ const instanceRows = await readAllInstanceRows();
391
+ const instanceDecision = decideInstanceAnswer(instanceRows);
392
+ if (instanceDecision.kind === "answer") {
393
+ instanceReport = {
394
+ id: instanceDecision.row.id,
395
+ role: instanceDecision.row.role ?? null,
396
+ status: instanceDecision.row.status ?? null,
397
+ };
398
+ }
399
+ else if (instanceDecision.kind === "refuse-multiple") {
400
+ const multi = {
401
+ multiple: true,
402
+ count: instanceDecision.rows.length,
403
+ remedy: INSTANCE_ROW_PRUNE_REMEDY,
404
+ };
405
+ if (isAdmin) {
406
+ multi.rows = instanceDecision.rows.map((r) => ({
407
+ id: r.id,
408
+ role: r.role ?? null,
409
+ createdAt: r.createdAt ?? null,
410
+ }));
411
+ }
412
+ instanceReport = multi;
413
+ }
414
+ // "none" leaves instanceReport === null — exactly as before.
415
+ }
416
+ catch {
417
+ // A failed read, or a row the reader could not name, is UNREADABLE —
418
+ // never a silent null. (readAllInstanceRows throws in both cases.)
419
+ instanceReport = { unreadable: true };
378
420
  }
379
- catch { /* absent */ }
380
421
  const peers = [];
381
422
  try {
382
423
  for await (const p of db.flair.Peer.search({}))
@@ -389,11 +430,10 @@ export class HealthDetail extends Resource {
389
430
  tokens.push(t);
390
431
  }
391
432
  catch { /* absent */ }
392
- if (instances.length === 0 && peers.length === 0) {
433
+ if (instanceReport === null && peers.length === 0) {
393
434
  stats.federation = null;
394
435
  }
395
436
  else {
396
- const inst = instances[0];
397
437
  // flair#1499: derive connected/down from lastSyncAt, not stored
398
438
  // status. Pairing writes `paired`; a recent lastSyncAt is connected.
399
439
  // Revoked rows are counted separately and never drive the >24h warning.
@@ -410,7 +450,7 @@ export class HealthDetail extends Resource {
410
450
  };
411
451
  const pendingTokens = tokens.filter((t) => !t.consumedBy && t.expiresAt && new Date(t.expiresAt).getTime() > nowMs).length;
412
452
  stats.federation = {
413
- instance: inst ? { id: inst.id, role: inst.role, status: inst.status } : null,
453
+ instance: instanceReport,
414
454
  peers: peersBlock,
415
455
  pendingTokens,
416
456
  peerList: isAdmin
@@ -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");