@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,6 +1,5 @@
1
1
  /**
2
- * mcp-tools.ts — the 12 curated flair tools for the Model-2 custom /mcp handler.
3
- *
2
+ * mcp-tools.ts — the 17 curated flair tools for the Model-2 custom /mcp handler.
4
3
  * Curated BY CONSTRUCTION: this module implements a fixed set of tools, each a
5
4
  * thin wrapper over the existing flair Resource handler. No business logic is
6
5
  * re-implemented — the wrapped handlers (Memory / SemanticSearch /
@@ -10,7 +9,7 @@
10
9
  * per-source scoping — see resources/AttentionQuery.ts's module doc), so the
11
10
  * MCP surface inherits the SAME security model as the signed-REST path. There
12
11
  * is no raw CRUD surface — the only way to reach the datastore through /mcp is
13
- * via one of these 14 semantic tools.
12
+ * via one of these 17 semantic tools.
14
13
  *
15
14
  * memory_search · memory_store · memory_update · memory_get · memory_delete ·
16
15
  * memory_basement · memory_restore · skill_store · skill_search · skill_get ·
@@ -885,7 +884,7 @@ export const TOOLS = bindNativeTools({
885
884
  memory_search: {
886
885
  impl: memorySearch,
887
886
  contract: {
888
- summary: "{ results: MemoryRecord[] } — semantic hits scoped to the caller's own + granted memories; each hit carries content, never the raw embedding.",
887
+ summary: "{ results: MemoryRecord[] } — semantic hits scoped to the caller's own and other agents' non-private memories; each hit carries content, never the raw embedding.",
889
888
  requiredFields: ["results"],
890
889
  fieldTypes: { results: "array" },
891
890
  invariants: {
@@ -1166,7 +1165,7 @@ export const TOOLS = bindNativeTools({
1166
1165
  },
1167
1166
  },
1168
1167
  });
1169
- /** The tool definitions for a tools/list response (exactly the 12 curated tools). */
1168
+ /** The tool definitions for a tools/list response (exactly the 17 curated tools). */
1170
1169
  export function listToolDefs() {
1171
1170
  return Object.values(TOOLS).map((t) => t.def);
1172
1171
  }
@@ -400,9 +400,25 @@ function sourceMemoryElement(m) {
400
400
  // until its escaped form fits the room the marker leaves.
401
401
  const limit = Math.max(0, SOURCE_EXCERPT_BUDGET - SOURCE_EXCERPT_MARKER.length);
402
402
  let kept = content.slice(0, limit);
403
+ // The initial budget cut can land between the two code units of an astral
404
+ // character, leaving kept ending in a lone high surrogate (flair#1772). Drop
405
+ // any trailing lone high surrogate so this cut lands on a code-point boundary.
406
+ while (kept.length >= 1 &&
407
+ kept.charCodeAt(kept.length - 1) >= 0xd800 &&
408
+ kept.charCodeAt(kept.length - 1) <= 0xdbff) {
409
+ kept = kept.slice(0, kept.length - 1);
410
+ }
403
411
  let keptEscaped = escapeElementText(kept);
404
412
  while (keptEscaped.length > limit && kept.length > 0) {
405
- kept = kept.slice(0, -1);
413
+ // Drop one whole code point: a complete surrogate pair (two code units) when
414
+ // the tail is a pair, otherwise a single BMP code unit (flair#1772).
415
+ const n = kept.length;
416
+ const tailIsPair = n >= 2 &&
417
+ kept.charCodeAt(n - 1) >= 0xdc00 &&
418
+ kept.charCodeAt(n - 1) <= 0xdfff &&
419
+ kept.charCodeAt(n - 2) >= 0xd800 &&
420
+ kept.charCodeAt(n - 2) <= 0xdbff;
421
+ kept = kept.slice(0, n - (tailIsPair ? 2 : 1));
406
422
  keptEscaped = escapeElementText(kept);
407
423
  }
408
424
  return `<memory id="${id}" date="${date}" excerpt="true">${keptEscaped}${SOURCE_EXCERPT_MARKER}</memory>`;
@@ -66,8 +66,8 @@ export function isPrivateVisibility(visibility) {
66
66
  * would fall back to the durability-keyed default, which for a permanent or
67
67
  * persistent write is `shared` — the same wrong outcome, arrived at quietly.
68
68
  *
69
- * `undefined`/`null` are accepted: omitting the field is how a caller asks for
70
- * the durability-keyed default, and that is a documented, intentional path.
69
+ * `undefined`/`null` are accepted: on a new record, omitting the field asks for
70
+ * the durability-keyed default; on an update, it keeps the stored visibility.
71
71
  */
72
72
  export function assertValidVisibility(visibility) {
73
73
  if (visibility === undefined || visibility === null)
@@ -76,8 +76,9 @@ export function assertValidVisibility(visibility) {
76
76
  return null;
77
77
  }
78
78
  return (`visibility must be ${WRITABLE_VISIBILITIES.map((v) => `"${v}"`).join(" or ")} ` +
79
- `(got: ${JSON.stringify(visibility)}). Omit it to use the durability-keyed default: ` +
80
- `permanent/persistent -> shared, standard/ephemeral -> private.`);
79
+ `(got: ${JSON.stringify(visibility)}). Omit it to use the durability-keyed default on a new ` +
80
+ `memory (permanent/persistent -> shared, standard/ephemeral -> private); on an update, ` +
81
+ `omitting it keeps a stored private or shared visibility.`);
81
82
  }
82
83
  /** Deliberately a LOCAL literal, not an import from memory-durability.ts: this
83
84
  * module's zero-imports property is load-bearing (see the header — src/cli.ts
@@ -101,7 +102,8 @@ export const EPHEMERAL_DURABILITY = "ephemeral";
101
102
  * NOT "refuse ephemeral+shared": on the read side any value other than the
102
103
  * literal "private" resolves to non-private (the migration invariant above),
103
104
  * so an unknown value on an ephemeral row would leak exactly like "shared".
104
- * assertValidVisibility refuses unknowns first at both call sites, but this
105
+ * assertValidVisibility refuses unknowns first at every call site (post, put,
106
+ * patch), but this
105
107
  * guard must stay fail-closed on its own — unknown means refused, not allowed.
106
108
  *
107
109
  * Absent (`undefined`/`null`) is accepted: it resolves through the
@@ -123,7 +125,8 @@ export function assertVisibilityAllowedForDurability(durability, visibility) {
123
125
  }
124
126
  return (`ephemeral memories are private-only (continuity journal tier, flair#1257): ` +
125
127
  `durability "${EPHEMERAL_DURABILITY}" cannot be written with visibility ${JSON.stringify(visibility)}. ` +
126
- `Omit visibility (the durability-keyed default is "${PRIVATE_VISIBILITY}") or set it to ` +
127
- `"${PRIVATE_VISIBILITY}"; for a memory other agents should read, use durability ` +
128
+ `Set visibility to "${PRIVATE_VISIBILITY}" (for a new memory, omitting it also gives ` +
129
+ `"${PRIVATE_VISIBILITY}"; an update keeps the record's stored visibility); for a memory ` +
130
+ `other agents should read, use durability ` +
128
131
  `"standard", "persistent", or "permanent".`);
129
132
  }
@@ -54,13 +54,15 @@
54
54
  * - Anything at all if the operator sets `FLAIR_RATE_LIMIT=off`.
55
55
  *
56
56
  * ── The counter is consumed BEFORE any credential is looked at ──────────────
57
- * `checkHttpRateLimit` runs at the top of auth-middleware, before the request
58
- * body is parsed and before any grant, code, secret or token is evaluated. That
57
+ * `checkHttpRateLimit` runs near the top of auth-middleware (right after its
58
+ * HTTP method check; a request with a refused method never reaches it), before
59
+ * the request body is parsed and before any grant, code, secret or token is
60
+ * evaluated. That
59
61
  * is deliberate and it is a security property, not an implementation detail: if
60
62
  * the limiter only counted FAILURES, then "did this attempt consume budget"
61
63
  * would answer "was that credential valid" — an enumeration oracle strictly
62
- * better than the 400 the endpoint already returns. Counting unconditionally
63
- * means a 429 carries no information about the credential that accompanied it,
64
+ * better than the 400 the endpoint already returns. Counting every request
65
+ * that passes the method check, whatever its credential, means a 429 carries no information about the credential that accompanied it,
64
66
  * and a valid credential and a garbage one are byte-identical once limited.
65
67
  *
66
68
  * For the same reason nothing here emits `RateLimit-Limit`/`RateLimit-Remaining`
@@ -217,8 +217,20 @@ export function makeByIdReadGate(readScope) {
217
217
  if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin)) {
218
218
  return superGet(target);
219
219
  }
220
- // Non-admin agent: scoped per the table's own read-scope model.
221
- const record = await superGet(target);
220
+ // Non-admin agent: scoped per the table's own read-scope model. The scope
221
+ // is evaluated on the FULL stored row: a target that asks for a selection
222
+ // or a single property is re-read without that shaping for the check, and
223
+ // the shaped result is returned only once the row passes.
224
+ const shaped = typeof target === "object" && target !== null && (target.select != null || target.property != null);
225
+ let unshaped = target;
226
+ if (shaped) {
227
+ const Ctor = target.constructor;
228
+ if (typeof Ctor !== "function")
229
+ return NOT_FOUND(); // fail closed: cannot re-read unshaped
230
+ unshaped = new Ctor();
231
+ unshaped.id = targetId;
232
+ }
233
+ const record = await superGet(unshaped);
222
234
  if (!record) {
223
235
  // Row did not load: either it genuinely does not exist, OR — the #1181
224
236
  // failure — a by-id read reached here on an unloaded instance and
@@ -237,7 +249,7 @@ export function makeByIdReadGate(readScope) {
237
249
  });
238
250
  return NOT_FOUND();
239
251
  }
240
- return record;
252
+ return shaped ? superGet(target) : record;
241
253
  };
242
254
  }
243
255
  // ─── (c) Scoped search — makeScopedSearch ────────────────────────────────
@@ -265,28 +277,40 @@ export function makeScopedSearch(readScope) {
265
277
  return async function scopedSearch(agentId, query, superSearch) {
266
278
  const scope = await readScope(agentId);
267
279
  const agentCondition = scope.condition;
268
- // Object with a conditions array — nest caller's conditions inside the
269
- // scope condition as the outermost AND block so a caller-supplied
270
- // `operator: "or"` cannot boolean-inject past the owner scope.
280
+ // The caller's conditions as an array. Harper accepts `conditions` as an
281
+ // array, any other iterable of conditions (it applies Array.from), or a
282
+ // single condition object; all are kept.
283
+ const isConditionIterable = (v) => !!v && typeof v === "object" && typeof v[Symbol.iterator] === "function" && !(v instanceof URLSearchParams);
284
+ const callerConditions = (list) => Array.isArray(list)
285
+ ? list
286
+ : isConditionIterable(list)
287
+ ? Array.from(list)
288
+ : list && typeof list === "object"
289
+ ? [list]
290
+ : [];
291
+ // The scope is always the OUTERMOST `and`, so a caller-supplied
292
+ // `operator: "or"` can only combine the caller's own conditions and never
293
+ // widens past the scope. A lone caller condition sits directly under that
294
+ // `and` (Harper's planner rejects a one-condition group); several keep the
295
+ // caller's operator inside their own group.
296
+ const compose = (conds, operator) => conds.length === 0
297
+ ? [agentCondition]
298
+ : conds.length === 1
299
+ ? [agentCondition, conds[0]]
300
+ : [agentCondition, { conditions: conds, operator: operator || "and" }];
301
+ // A bare iterable of conditions (not a RequestTarget, which is itself a
302
+ // URLSearchParams and carries its conditions on `.conditions`).
303
+ if (isConditionIterable(query) && !("conditions" in query)) {
304
+ return superSearch({ conditions: compose(Array.from(query), "and"), operator: "and" });
305
+ }
271
306
  if (query && typeof query === "object" && !Array.isArray(query)) {
272
- if (Array.isArray(query.conditions) && query.conditions.length > 0) {
273
- return superSearch({
274
- ...query,
275
- conditions: [agentCondition, { conditions: query.conditions, operator: query.operator || "and" }],
276
- operator: "and",
277
- });
278
- }
279
- // No (or empty) conditions array — just scope, preserving other query
280
- // properties but NOT a caller-supplied operator (force "and").
281
- const { conditions: _c, operator: _o, ...rest } = query;
282
- return superSearch({ ...rest, conditions: [agentCondition], operator: "and" });
307
+ // Preserve other query properties (select, limit, sort, ...) but never a
308
+ // caller-supplied top-level operator.
309
+ const { conditions, operator, ...rest } = query;
310
+ return superSearch({ ...rest, conditions: compose(callerConditions(conditions), operator), operator: "and" });
283
311
  }
284
- // Plain array or no query — wrap in an object with operator "and" so
285
- // the scope condition is always the outermost AND.
286
- const conditions = Array.isArray(query) && query.length > 0
287
- ? [agentCondition, { conditions: query, operator: "and" }]
288
- : [agentCondition];
289
- return superSearch({ conditions, operator: "and" });
312
+ // Plain array or no query.
313
+ return superSearch({ conditions: compose(callerConditions(query), "and"), operator: "and" });
290
314
  };
291
315
  }
292
316
  export function stampAttribution(auth, content, field, mode, forbiddenMessage) {
@@ -89,7 +89,13 @@ export function resolveSearchReadiness(opts) {
89
89
  // status stays `empty` for the life of the process — that is serving, not
90
90
  // cold. Treating it as lag would make searchReady false forever and refuse
91
91
  // a node that is already answering recall.
92
- const indexInPath = opts.hybridEnabled !== false && opts.bm25IndexEnabled !== false;
92
+ // The persistent BM25 index is in the retrieval path for "hybrid" and
93
+ // "bm25-only"; a "vector-only" process has no lexical leg to keep warm.
94
+ // `retrievalMode` is the current selector; `hybridEnabled` is the legacy
95
+ // boolean callers passed before it — an unset retrievalMode falls back to it
96
+ // exactly (false ⇒ vector-only, so the shipped behavior is unchanged).
97
+ const effectiveMode = opts.retrievalMode ?? (opts.hybridEnabled === false ? "vector-only" : "hybrid");
98
+ const indexInPath = effectiveMode !== "vector-only" && opts.bm25IndexEnabled !== false;
93
99
  if (indexInPath && opts.bm25) {
94
100
  if (opts.bm25.state === "building") {
95
101
  return namesLag("bm25 index building — first search is still scanning the corpus");
@@ -97,13 +97,13 @@ export const DEFAULT_SELECT = ["id", "agentId", "content", "contentHash", "visib
97
97
  "parentId", "derivedFrom", "sessionId", "lastReflected", "supersedes", "subject", "summary",
98
98
  "validFrom", "validTo", "_safetyFlags"];
99
99
  export async function retrieveCandidates(params) {
100
- const { queryEmbedding: qEmb, q, conditions, limit, select = DEFAULT_SELECT, includeSuperseded = false, scoring = "raw", temporalBoost = 1.0, sinceDate = null, asOf, minScore = 0, agentId, isAllowed, hybrid, ctx, withSemSimilarity = false, onLegs, } = params;
100
+ const { queryEmbedding: qEmb, q, conditions, limit, select = DEFAULT_SELECT, includeSuperseded = false, scoring = "raw", temporalBoost = 1.0, sinceDate = null, asOf, minScore = 0, agentId, isAllowed, mode, ctx, withSemSimilarity = false, onLegs, } = params;
101
101
  const passesAllowed = (record) => !isAllowed || isAllowed(record);
102
102
  const hnswSelect = [...select, "$distance"];
103
103
  const results = [];
104
104
  const hnswLegIds = [];
105
105
  const bm25LegIds = [];
106
- if (hybrid) {
106
+ if (mode === "hybrid") {
107
107
  // ─── BM25 + union-RRF hybrid path ────────────────────────────────────
108
108
  // 1. Semantic candidates via HNSW (unchanged fetch). 2. BM25 lexical pass
109
109
  // over the SCOPED corpus. 3. SECURITY: the BM25 candidate set is filtered
@@ -356,8 +356,103 @@ export async function retrieveCandidates(params) {
356
356
  }
357
357
  }
358
358
  }
359
+ else if (mode === "bm25-only") {
360
+ // ─── BM25-only path (benchmark arm) ────────────────────────────────────
361
+ // The lexical leg ALONE: no HNSW leg, no query embedding, no RRF fusion.
362
+ // `semIds` stays empty by construction and any qEmb the caller passed is
363
+ // IGNORED — ranking comes from the BM25 list and nothing else, so the arm
364
+ // measures exactly what its name says. The result shape is identical to
365
+ // the other modes (same keys, same `_rank` ordering key, stripped before
366
+ // return). `_score` carries no semantic evidence on this path (there is no
367
+ // cosine to report): it is the legacy keyword bump alone, the same value
368
+ // the no-embedding fallback reports.
369
+ const allowedById = new Map();
370
+ let bm25Ids = [];
371
+ let servedFromIndex = false;
372
+ if (q) {
373
+ const fromIndex = await indexedBm25Ids({
374
+ q: String(q),
375
+ conditions: conditions,
376
+ timeFilters: { sinceDate, asOf },
377
+ isAllowed,
378
+ limit: SEM_LIMIT,
379
+ ctx,
380
+ });
381
+ if (fromIndex) {
382
+ bm25Ids = fromIndex;
383
+ servedFromIndex = true;
384
+ }
385
+ }
386
+ if (!servedFromIndex && q) {
387
+ // Legacy path: scoped corpus scan + per-query buildBM25() (see the
388
+ // hybrid branch above for the flair#1357 rationale).
389
+ const corpusQuery = conditions.length > 0 ? { conditions, select } : { select };
390
+ const corpusResults = withDetachedTxn(ctx, () => databases.flair.Memory.search(corpusQuery));
391
+ const bm25Docs = [];
392
+ for await (const record of corpusResults) {
393
+ if (!isAllowedBm25Candidate(record, conditions, { sinceDate, asOf }))
394
+ continue;
395
+ if (!passesAllowed(record))
396
+ continue;
397
+ allowedById.set(record.id, record);
398
+ bm25Docs.push({ id: record.id, content: record.content });
399
+ }
400
+ const bm25 = buildBM25(bm25Docs);
401
+ const ranked = bm25.rank(String(q));
402
+ bm25Ids = ranked.filter(r => r.score > 0).slice(0, SEM_LIMIT).map(r => r.id);
403
+ }
404
+ if (servedFromIndex) {
405
+ const resolved = [];
406
+ for (const id of bm25Ids) {
407
+ if (allowedById.has(id)) {
408
+ resolved.push(id);
409
+ continue;
410
+ }
411
+ const full = await withDetachedTxn(ctx, () => databases.flair.Memory.get(id));
412
+ if (!full)
413
+ continue;
414
+ if (!isAllowedBm25Candidate(full, conditions, { sinceDate, asOf }))
415
+ continue;
416
+ if (!passesAllowed(full))
417
+ continue;
418
+ const projected = {};
419
+ for (const key of select)
420
+ if (key in full)
421
+ projected[key] = full[key];
422
+ allowedById.set(id, projected);
423
+ resolved.push(id);
424
+ }
425
+ bm25Ids = resolved;
426
+ }
427
+ bm25LegIds.push(...bm25Ids);
428
+ // Emit in BM25 order alone — rank 0 gets the highest `_rank`, so the final
429
+ // descending sort keeps the lexical order. No fusion, no cosine.
430
+ for (let i = 0; i < bm25Ids.length; i++) {
431
+ const id = bm25Ids[i];
432
+ const record = allowedById.get(id);
433
+ if (!record)
434
+ continue;
435
+ let keywordHit = false;
436
+ if (q && String(record.content || "").toLowerCase().includes(String(q).toLowerCase())) {
437
+ keywordHit = true;
438
+ }
439
+ const rawScore = keywordHit ? 0.05 : 0;
440
+ let finalScore = scoring === "raw" ? rawScore : compositeScore(rawScore, record);
441
+ if (temporalBoost > 1.0)
442
+ finalScore *= temporalBoost;
443
+ const isFlagged = record._safetyFlags && Array.isArray(record._safetyFlags) && record._safetyFlags.length > 0;
444
+ const source = record.agentId !== agentId ? record.agentId : undefined;
445
+ pushRanked(results, {
446
+ ...record,
447
+ content: isFlagged ? wrapUntrusted(record.content, source) : record.content,
448
+ _score: Math.round(finalScore * 1000) / 1000,
449
+ _rawScore: scoring !== "raw" ? Math.round(rawScore * 1000) / 1000 : undefined,
450
+ _source: source,
451
+ }, bm25Ids.length - i);
452
+ }
453
+ }
359
454
  else if (qEmb) {
360
- // ─── HNSW vector search path (legacy, hybrid flag OFF — the
455
+ // ─── HNSW vector search path (legacy, mode "vector-only" — the
361
456
  // FLAIR_HYBRID_RETRIEVAL kill-switch path for BOTH production callers
362
457
  // since flair#1246) ─────────────────────────────────────────────────────
363
458
  const query = {
@@ -60,3 +60,36 @@ export function withDetachedTxn(ctx, fn) {
60
60
  ctx.transaction = saved;
61
61
  }
62
62
  }
63
+ /**
64
+ * AWAITED variant (flair#1897): holds the detached window through the promise.
65
+ *
66
+ * The sync `withDetachedTxn` restores `ctx.transaction` in `finally` as soon as
67
+ * `fn` RETURNS — for an async `fn` that is when the PROMISE IS CREATED, not when
68
+ * it settles. Harper's static `put` can resolve the resource asynchronously
69
+ * before `_writeUpdate` picks its transaction via `txnForContext(getContext())`;
70
+ * if that pick runs after the restore, the write rejoins the request's deferred
71
+ * transaction and commits after the caller has moved on. This variant keeps the
72
+ * transaction detached until `fn`'s promise settles: save, clear, `await fn()`,
73
+ * THEN restore. Use it for a WRITE you need committed before the next reader.
74
+ *
75
+ * Relied-on Harper behaviour (5.2.8, exact branches): `txnForContext`
76
+ * (Table.ts:5767) selects the LMDB OR RocksDB `ImmediateTransaction`
77
+ * (LMDBTransaction.ts:349 / DatabaseTransaction.ts:1465) when `context.transaction`
78
+ * is not a joinable scope; an immediate transaction writes on its own, while a
79
+ * joined one commits when its transaction function completes. The 50-round
80
+ * integration test
81
+ * (`test/integration/federation-instance-create-race-1897.test.ts`, run in the
82
+ * REQUIRED `Integration Tests` job) is the tripwire for an upgrade changing this.
83
+ */
84
+ export async function withDetachedTxnAsync(ctx, fn) {
85
+ if (!ctx)
86
+ return fn();
87
+ const saved = ctx.transaction;
88
+ ctx.transaction = undefined;
89
+ try {
90
+ return await fn();
91
+ }
92
+ finally {
93
+ ctx.transaction = saved;
94
+ }
95
+ }
@@ -51,7 +51,7 @@ export function descriptorNames(descriptors) {
51
51
  export const TOOL_DESCRIPTORS = [
52
52
  {
53
53
  "name": "memory_search",
54
- "description": "Search memories by meaning. Understands temporal queries like 'what happened today'. Scoped to your agent's own + granted memories.",
54
+ "description": "Search memories by meaning. Understands temporal queries like 'what happened today'. Scoped to your agent's own and other agents' non-private memories.",
55
55
  "inputSchema": {
56
56
  "type": "object",
57
57
  "properties": {
@@ -80,7 +80,7 @@ export const TOOL_DESCRIPTORS = [
80
80
  "query"
81
81
  ]
82
82
  },
83
- "outputShape": "{ results: MemoryRecord[] } — semantic hits scoped to the caller's own + granted memories; each hit carries content, never the raw embedding.",
83
+ "outputShape": "{ results: MemoryRecord[] } — semantic hits scoped to the caller's own and other agents' non-private memories; each hit carries content, never the raw embedding.",
84
84
  "annotations": {
85
85
  "readOnlyHint": true
86
86
  },
@@ -10,11 +10,19 @@
10
10
  */
11
11
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
12
  import { join } from "node:path";
13
- import { homedir } from "node:os";
13
+ import { resolveHome } from "./lib/home.js";
14
14
  import { randomBytes, createCipheriv, createDecipheriv, hkdfSync, } from "node:crypto";
15
15
  // ─── Helpers ────────────────────────────────────────────────────────────────
16
+ /**
17
+ * The keystore's home comes from the ONE shared resolver (src/lib/home.ts,
18
+ * flair#1853 round 3): resolved at CALL time, with the platform rule (Windows
19
+ * uses USERPROFILE, everywhere else HOME). The runtime caches `os.homedir()` at
20
+ * process start, so a HOME set after start — the test harness in
21
+ * test/helpers/sandbox-home.ts — would otherwise be invisible and the keystore
22
+ * would reach the REAL ~/.flair/keys.
23
+ */
16
24
  function keysDir() {
17
- return join(homedir(), ".flair", "keys");
25
+ return join(resolveHome(), ".flair", "keys");
18
26
  }
19
27
  function keyPath(instanceId) {
20
28
  // Sanitize instanceId to prevent directory traversal
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The user's home directory, resolved at CALL time (flair#1853).
3
+ *
4
+ * `os.homedir()` is cached at process start, so a HOME set later in the same
5
+ * process is invisible to it. Every Flair surface that resolves `~` — the
6
+ * keystore and the client config writers — must land on the SAME home, and it
7
+ * must be the one the calling shell actually uses.
8
+ *
9
+ * Which environment variable names that home differs by platform:
10
+ *
11
+ * - **Windows** — `USERPROFILE` is authoritative. Node's `os.homedir()` reads
12
+ * it, but a POSIX-style shell (Git Bash, MSYS, Cygwin) may set `HOME` to a
13
+ * different path. Preferring `HOME` there would move `~/.flair/keys` away
14
+ * from where the keys actually live, so an existing key would read as
15
+ * missing (and a new one would be written somewhere nothing looks).
16
+ * - **Everywhere else** — `HOME` is authoritative (and is how the test harness
17
+ * redirects a process), with `os.homedir()` as the fallback.
18
+ */
19
+ import { homedir } from "node:os";
20
+ /** The home directory for this invocation, resolved at call time. */
21
+ export function resolveHome() {
22
+ return process.platform === "win32"
23
+ ? process.env.USERPROFILE || homedir()
24
+ : process.env.HOME || homedir();
25
+ }
26
+ /**
27
+ * Run `fn` with BOTH `HOME` and `USERPROFILE` pointed at `homeDir`, then restore
28
+ * both to exactly what they were — including the previously-UNSET case, and even
29
+ * when `fn` throws. Returns `fn`'s value.
30
+ *
31
+ * `resolveHome()` reads `USERPROFILE` on win32 and `HOME` elsewhere, so setting
32
+ * only `HOME` silently ignored the override on Windows: doctor, the pin refresh
33
+ * and uninstall's `unwire()` then acted on the real profile instead of the
34
+ * directory the caller named. Both are set here, so the override holds on every
35
+ * platform.
36
+ *
37
+ * `fn` MUST be synchronous. The parameter type REJECTS a Promise-returning
38
+ * callback at compile time (a Promise is not assignable to the `never` branch),
39
+ * because a sync save/restore around async work would restore the environment
40
+ * before the work runs.
41
+ */
42
+ export function withHome(homeDir, fn) {
43
+ const prevHome = process.env.HOME;
44
+ const prevProfile = process.env.USERPROFILE;
45
+ process.env.HOME = homeDir;
46
+ process.env.USERPROFILE = homeDir;
47
+ try {
48
+ return fn();
49
+ }
50
+ finally {
51
+ if (prevHome === undefined)
52
+ delete process.env.HOME;
53
+ else
54
+ process.env.HOME = prevHome;
55
+ if (prevProfile === undefined)
56
+ delete process.env.USERPROFILE;
57
+ else
58
+ process.env.USERPROFILE = prevProfile;
59
+ }
60
+ }