@tpsdev-ai/flair 0.56.0 → 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 (63) hide show
  1. package/README.md +16 -17
  2. package/dist/build-info.json +3 -3
  3. package/dist/cli.js +115 -14
  4. package/dist/commands/agent.js +22 -15
  5. package/dist/commands/bridge.js +40 -3
  6. package/dist/commands/doctor.js +52 -0
  7. package/dist/commands/federation.js +263 -37
  8. package/dist/commands/init.js +29 -4
  9. package/dist/lib/auth-resolve.js +46 -0
  10. package/dist/lib/instance-identity-row.js +580 -0
  11. package/dist/lib/redact-token-id.js +197 -0
  12. package/dist/resources/AgentSeed.js +4 -1
  13. package/dist/resources/Asset.js +3 -11
  14. package/dist/resources/Credential.js +4 -10
  15. package/dist/resources/Federation.js +232 -78
  16. package/dist/resources/Integration.js +8 -32
  17. package/dist/resources/Memory.js +58 -16
  18. package/dist/resources/MemoryBootstrap.js +19 -12
  19. package/dist/resources/MemoryCandidate.js +3 -11
  20. package/dist/resources/MemoryDedupStats.js +1 -1
  21. package/dist/resources/MemoryFeed.js +10 -2
  22. package/dist/resources/MemoryGrant.js +19 -40
  23. package/dist/resources/MemoryUsage.js +7 -20
  24. package/dist/resources/Relationship.js +3 -11
  25. package/dist/resources/SemanticSearch.js +25 -13
  26. package/dist/resources/auth-middleware.js +32 -5
  27. package/dist/resources/bm25.js +13 -14
  28. package/dist/resources/federation-cleanup.js +289 -51
  29. package/dist/resources/health.js +48 -8
  30. package/dist/resources/in-process-api.js +2 -1
  31. package/dist/resources/instance-create-lock.js +363 -0
  32. package/dist/resources/instance-identity-rows.js +43 -0
  33. package/dist/resources/instance-identity.js +94 -10
  34. package/dist/resources/mcp-handler.js +9 -1
  35. package/dist/resources/mcp-tool-arguments.js +83 -0
  36. package/dist/resources/mcp-tools.js +4 -5
  37. package/dist/resources/memory-visibility.js +10 -7
  38. package/dist/resources/rate-limit.js +6 -4
  39. package/dist/resources/record-type-kit.js +47 -23
  40. package/dist/resources/search-readiness.js +7 -1
  41. package/dist/resources/semantic-retrieval-core.js +98 -3
  42. package/dist/resources/table-helpers.js +33 -0
  43. package/dist/resources/tool-descriptors/index.js +2 -2
  44. package/dist/src/lib/instance-identity-row.js +580 -0
  45. package/dist/src/lib/redact-token-id.js +197 -0
  46. package/docs/api-reference.md +1 -1
  47. package/docs/auth.md +5 -5
  48. package/docs/claude-code.md +5 -6
  49. package/docs/deploying-on-fabric.md +6 -3
  50. package/docs/embedding-in-a-harper-app.md +3 -3
  51. package/docs/federation.md +16 -9
  52. package/docs/hosted-on-fabric.md +4 -3
  53. package/docs/integrations.md +24 -15
  54. package/docs/mcp-clients.md +16 -12
  55. package/docs/n8n.md +8 -8
  56. package/docs/notes/mcp-oauth-model2.md +12 -17
  57. package/docs/openclaw.md +29 -28
  58. package/docs/spoke-bringup.md +14 -11
  59. package/docs/standalone-local.md +2 -2
  60. package/docs/supply-chain-policy.md +21 -8
  61. package/docs/system-requirements.md +1 -1
  62. package/docs/upgrade.md +2 -2
  63. package/package.json +1 -1
@@ -15,7 +15,7 @@ import { buildCollisionEntries, buildEntityMatchCondition, freshPresenceByAgent,
15
15
  // retrievalCount hit-tracking side effects (see resources/
16
16
  // semantic-retrieval-core.ts's module doc for the full boundary).
17
17
  import { retrieveCandidates, DEFAULT_SELECT } from "./semantic-retrieval-core.js";
18
- import { hybridEnabled } from "./bm25.js";
18
+ import { retrievalMode } from "./bm25.js";
19
19
  import { buildTrustBlock } from "./trust-block.js";
20
20
  import { bestSemanticSimilarity, evaluateAbstention } from "./abstention.js";
21
21
  import { estimateTokens } from "./token-estimate.js";
@@ -939,16 +939,23 @@ export class BootstrapMemories extends Resource {
939
939
  if (currentTask && tokenBudget <= 0)
940
940
  taskRetrievalHint = "Task retrieval skipped: no content budget remains.";
941
941
  if (currentTask && tokenBudget > 0) {
942
+ // Resolve the mode ONCE here so the embedding guard and the core agree.
943
+ // The bm25-only arm ranks on the lexical leg alone and needs NO query
944
+ // embedding — gating it on one being available would skip the lexical
945
+ // search entirely and lose task-relevant memories for no reason.
946
+ const mode = retrievalMode();
942
947
  let queryEmbedding = null;
943
- try {
944
- // flair#504 Phase 2: 'query' — currentTask is the bootstrap's
945
- // task-relevance search query, not stored content.
946
- queryEmbedding = await getEmbedding(currentTask, "query");
948
+ if (mode !== "bm25-only") {
949
+ try {
950
+ // flair#504 Phase 2: 'query' — currentTask is the bootstrap's
951
+ // task-relevance search query, not stored content.
952
+ queryEmbedding = await getEmbedding(currentTask, "query");
953
+ }
954
+ catch { }
947
955
  }
948
- catch { }
949
- if (!queryEmbedding)
956
+ if (mode !== "bm25-only" && !queryEmbedding)
950
957
  taskRetrievalHint = "Task retrieval skipped: query embedding unavailable.";
951
- if (queryEmbedding) {
958
+ if (mode === "bm25-only" || queryEmbedding) {
952
959
  // flair#1207 — exclude own memories ALREADY placed via the authoritative
953
960
  // set (permanent + recent + predicted actually admitted). The old set was
954
961
  // built positionally (recent.filter by index) AND omitted `predicted`, so
@@ -973,9 +980,9 @@ export class BootstrapMemories extends Resource {
973
980
  limit: candidatePoolK,
974
981
  // flair#1246 — ONE RANKER, ONE SCALE: this pass now invokes the
975
982
  // core in the SAME mode memory_search does (hybrid + q via the
976
- // shared hybridEnabled() selector, so the FLAIR_HYBRID_RETRIEVAL
977
- // kill-switch moves BOTH surfaces together — a split mode IS the
978
- // #1246 bug). HNSW-only here was an accident of early code, and it
983
+ // shared retrievalMode() selector, so the FLAIR_RETRIEVAL_MODE /
984
+ // FLAIR_HYBRID_RETRIEVAL kill-switch moves BOTH surfaces together —
985
+ // a split mode IS the #1246 bug). HNSW-only here was an accident of early code, and it
979
986
  // made bootstrap's teammate picks diverge from search on the same
980
987
  // store+query: a record whose task-relevance is LEXICAL (exact task
981
988
  // terms in semantically-atypical prose) ranks BELOW bland-generic
@@ -987,7 +994,7 @@ export class BootstrapMemories extends Resource {
987
994
  // fusion carries it to the top, same as search. Perf (Kern-ratified
988
995
  // trade): the BM25 corpus scan this adds to the bootstrap path is
989
996
  // the same per-call scan every memory_search request already runs.
990
- hybrid: hybridEnabled(),
997
+ mode,
991
998
  // The lexical leg — same query text the embedding was computed
992
999
  // from, so both legs rank the same question (parity with search,
993
1000
  // where `q` drives BM25 and the keyword bump).
@@ -1,7 +1,7 @@
1
1
  import { databases } from "harper";
2
2
  import { resolveAgentAuth } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
- import { makeAuthGate, makeReadScope, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
4
+ import { makeAuthGate, makeReadScope, makeScopedSearch, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
5
5
  import { RECORD_TYPES } from "./record-types.js";
6
6
  // Parameterized from RECORD_TYPES.MemoryCandidate (record-types slice 2,
7
7
  // flair#520) rather than a hand-typed "owner-only" literal — the registry is
@@ -11,6 +11,7 @@ import { RECORD_TYPES } from "./record-types.js";
11
11
  // `.ownerField` against RECORD_TYPES.MemoryCandidate — not for any other
12
12
  // runtime consumer.
13
13
  export const memoryCandidateReadScope = makeReadScope(RECORD_TYPES.MemoryCandidate.readScope, RECORD_TYPES.MemoryCandidate.ownerField);
14
+ const memoryCandidateScopedSearch = makeScopedSearch(memoryCandidateReadScope);
14
15
  const memoryCandidateByIdReadGate = makeByIdReadGate(memoryCandidateReadScope);
15
16
  // See makeAuthGate's doc (record-type-kit.ts): must be wired as a genuine
16
17
  // prototype method below, never a class-field assignment.
@@ -97,16 +98,7 @@ export class MemoryCandidate extends databases.flair.MemoryCandidate {
97
98
  if (gate.kind === "unfiltered")
98
99
  return super.search(query);
99
100
  // Non-admin agent: scope to own candidates only.
100
- const scope = await memoryCandidateReadScope(gate.agentId);
101
- const agentCondition = scope.condition;
102
- if (!query?.conditions) {
103
- return super.search({ conditions: [agentCondition], ...(query || {}) });
104
- }
105
- return super.search({
106
- ...query,
107
- conditions: [agentCondition, { conditions: query.conditions, operator: query.operator || "and" }],
108
- operator: "and",
109
- });
101
+ return memoryCandidateScopedSearch(gate.agentId, query, (q) => super.search(q));
110
102
  }
111
103
  /**
112
104
  * No shipped CLI path calls POST today (the FLAIR-NIGHTLY-REM staging
@@ -131,7 +131,7 @@ async function computeAndPersist(ctx, opts) {
131
131
  queryEmbedding: memory.embedding,
132
132
  conditions: NOT_ARCHIVED,
133
133
  limit: annK + 1,
134
- hybrid: false,
134
+ mode: "vector-only",
135
135
  scoring: "raw",
136
136
  withSemSimilarity: true,
137
137
  select: ["id"],
@@ -1,9 +1,10 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { Resource, databases } from "harper";
2
3
  import { allowVerified, resolveAgentAuth } from "./agent-auth.js";
3
4
  import { computeContentHash, findExistingMemoryByContentHash } from "./memory-feed-lib.js";
4
5
  import { FORBIDDEN, UNAUTH, stampAttribution } from "./record-type-kit.js";
5
6
  import { guardAuthorityFields, stripAuthorityFields } from "./authority-field-guard.js";
6
- import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VISIBILITY } from "./memory-visibility.js";
7
+ import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
7
8
  import { assertValidDurability } from "./memory-durability.js";
8
9
  import { enforceSkillDurability, refuseSkillWriteSource, skillScanGate } from "./skill-write.js";
9
10
  import { noteMemoryUpsert } from "./bm25-index-service.js";
@@ -49,6 +50,13 @@ export class FeedMemories extends Resource {
49
50
  if (existingRecord && existingRecord.agentId !== content.agentId) {
50
51
  return FORBIDDEN("forbidden: cannot write a feed memory owned by another agent");
51
52
  }
53
+ // Preserve stored visibility on updates before applying write policy
54
+ // (the same rule as Memory.put; only the two writable values).
55
+ if (existingRecord &&
56
+ (content.visibility === undefined || content.visibility === null) &&
57
+ (existingRecord.visibility === PRIVATE_VISIBILITY || existingRecord.visibility === SHARED_VISIBILITY)) {
58
+ content.visibility = existingRecord.visibility;
59
+ }
52
60
  }
53
61
  const agentId = content.agentId;
54
62
  const body = String(content?.content ?? "");
@@ -135,7 +143,7 @@ export class FeedMemories extends Resource {
135
143
  return existing;
136
144
  const record = {
137
145
  ...content,
138
- id: content.id ?? `${agentId}-${Date.now()}`,
146
+ id: content.id ?? `${agentId}-${Date.now()}-${randomUUID()}`,
139
147
  agentId,
140
148
  content: body,
141
149
  contentHash,
@@ -1,6 +1,22 @@
1
1
  import { databases } from "harper";
2
2
  import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
+ import { makeByIdReadGate, makeScopedSearch } from "./record-type-kit.js";
5
+ // A grant is readable by either party: owner OR grantee. One scope object feeds
6
+ // both the shared by-id gate and the scoped search, so the collection scope is
7
+ // always the outermost AND and the by-id check reads the stored record.
8
+ const grantReadScope = Object.assign(async (agentId) => ({
9
+ condition: {
10
+ operator: "or",
11
+ conditions: [
12
+ { attribute: "ownerId", comparator: "equals", value: agentId },
13
+ { attribute: "granteeId", comparator: "equals", value: agentId },
14
+ ],
15
+ },
16
+ isAllowed: (record) => !!record && (record.ownerId === agentId || record.granteeId === agentId),
17
+ }), { mode: "owner-only", ownerField: "ownerId" });
18
+ const grantByIdReadGate = makeByIdReadGate(grantReadScope);
19
+ const grantScopedSearch = makeScopedSearch(grantReadScope);
4
20
  const FORBIDDEN = (msg) => new Response(JSON.stringify({ error: msg }), { status: 403, headers: { "Content-Type": "application/json" } });
5
21
  const UNAUTH = () => new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
6
22
  const NOT_FOUND = () => new Response(JSON.stringify({ error: "not found" }), { status: 404, headers: { "Content-Type": "application/json" } });
@@ -38,31 +54,7 @@ export class MemoryGrant extends databases.flair.MemoryGrant {
38
54
  * to enumerate other agents' grant ids.
39
55
  */
40
56
  async get(target) {
41
- // Collection / query reads arrive as a RequestTarget with
42
- // `isCollection === true`, and are governed by search() (same owner/
43
- // grantee scoping). Only a genuine by-id get is ownership-checked below
44
- // — see Memory.ts's get() for the full rationale (same bug class).
45
- if (!target || (typeof target === "object" && target.isCollection)) {
46
- return this.search(target);
47
- }
48
- const auth = await this._auth();
49
- // Anonymous by-id read is already blocked at the allowRead() gate (403);
50
- // this is defense-in-depth if get() is ever reached directly.
51
- if (auth.kind === "anonymous") {
52
- return NOT_FOUND();
53
- }
54
- // Trusted internal call or admin agent — unfiltered, unchanged behavior.
55
- if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin)) {
56
- return super.get(target);
57
- }
58
- // Non-admin agent: visible if it's the owner OR the grantee (parity with
59
- // search()'s owner-OR-grantee scope).
60
- const record = await super.get(target);
61
- if (!record)
62
- return NOT_FOUND();
63
- if (record.ownerId !== auth.agentId && record.granteeId !== auth.agentId)
64
- return NOT_FOUND();
65
- return record;
57
+ return grantByIdReadGate.call(this, target, (t) => super.get(t));
66
58
  }
67
59
  async search(query) {
68
60
  const auth = await this._auth();
@@ -71,21 +63,8 @@ export class MemoryGrant extends databases.flair.MemoryGrant {
71
63
  if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin)) {
72
64
  return super.search(query);
73
65
  }
74
- // owner OR grantee
75
- const scope = {
76
- operator: "or",
77
- conditions: [
78
- { attribute: "ownerId", comparator: "equals", value: auth.agentId },
79
- { attribute: "granteeId", comparator: "equals", value: auth.agentId },
80
- ],
81
- };
82
- if (query && typeof query === "object" && !Array.isArray(query)) {
83
- const existing = query.conditions ?? [];
84
- query.conditions = Array.isArray(existing) ? [scope, ...existing] : [scope, existing];
85
- return super.search(query);
86
- }
87
- const conditions = Array.isArray(query) && query.length > 0 ? [scope, ...query] : [scope];
88
- return super.search(conditions);
66
+ // owner OR grantee, as the outermost AND (makeScopedSearch).
67
+ return grantScopedSearch(auth.agentId, query, (q) => super.search(q));
89
68
  }
90
69
  async post(content, context) {
91
70
  const denied = await this._enforceOwnerWrite(content);
@@ -43,6 +43,11 @@
43
43
  */
44
44
  import { databases } from "harper";
45
45
  import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
46
+ import { makeByIdReadGate, makeReadScope, makeScopedSearch } from "./record-type-kit.js";
47
+ // Owner-only read scope through the shared by-id gate and scoped search.
48
+ const usageReadScope = makeReadScope("owner-only", "agentId");
49
+ const usageByIdReadGate = makeByIdReadGate(usageReadScope);
50
+ const usageScopedSearch = makeScopedSearch(usageReadScope);
46
51
  const FORBIDDEN = (msg) => new Response(JSON.stringify({ error: msg }), { status: 403, headers: { "Content-Type": "application/json" } });
47
52
  const UNAUTH = () => new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
48
53
  const NOT_FOUND = () => new Response(JSON.stringify({ error: "not found" }), { status: 404, headers: { "Content-Type": "application/json" } });
@@ -52,18 +57,7 @@ export class MemoryUsage extends databases.flair.MemoryUsage {
52
57
  * etc.). Per-record scoping happens in get()/search() below. */
53
58
  allowRead() { return allowVerified(this.getContext?.()); }
54
59
  async get(target) {
55
- if (!target || (typeof target === "object" && target.isCollection)) {
56
- return this.search(target);
57
- }
58
- const auth = await resolveAgentAuth(this.getContext?.());
59
- if (auth.kind === "anonymous")
60
- return NOT_FOUND();
61
- if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin))
62
- return super.get(target);
63
- const record = await super.get(target);
64
- if (!record || record.agentId !== auth.agentId)
65
- return NOT_FOUND();
66
- return record;
60
+ return usageByIdReadGate.call(this, target, (t) => super.get(t));
67
61
  }
68
62
  async search(query) {
69
63
  const auth = await resolveAgentAuth(this.getContext?.());
@@ -71,14 +65,7 @@ export class MemoryUsage extends databases.flair.MemoryUsage {
71
65
  return UNAUTH();
72
66
  if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin))
73
67
  return super.search(query);
74
- const scope = { attribute: "agentId", comparator: "equals", value: auth.agentId };
75
- if (query && typeof query === "object" && !Array.isArray(query)) {
76
- const existing = query.conditions ?? [];
77
- query.conditions = Array.isArray(existing) ? [scope, ...existing] : [scope, existing];
78
- return super.search(query);
79
- }
80
- const conditions = Array.isArray(query) && query.length > 0 ? [scope, ...query] : [scope];
81
- return super.search(conditions);
68
+ return usageScopedSearch(auth.agentId, query, (q) => super.search(q));
82
69
  }
83
70
  // Append-only ledger: rows are created via RecordUsage's RAW table call
84
71
  // (bypasses this class entirely — see module doc), never via this
@@ -3,7 +3,7 @@ import { resolveAgentAuth } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
4
  import { checkRateLimit, rateLimitResponse } from "./rate-limiter.js";
5
5
  import { localInstanceId } from "./instance-identity.js";
6
- import { buildProvenance, makeAuthGate, makeReadScope, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
6
+ import { buildProvenance, makeAuthGate, makeReadScope, makeScopedSearch, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
7
7
  import { RECORD_TYPES } from "./record-types.js";
8
8
  // Parameterized from RECORD_TYPES.Relationship (record-types slice 2,
9
9
  // flair#520) rather than a hand-typed "owner-only" literal — the registry is
@@ -13,6 +13,7 @@ import { RECORD_TYPES } from "./record-types.js";
13
13
  // `.ownerField` against RECORD_TYPES.Relationship — not for any other
14
14
  // runtime consumer.
15
15
  export const relationshipReadScope = makeReadScope(RECORD_TYPES.Relationship.readScope, RECORD_TYPES.Relationship.ownerField);
16
+ const relationshipScopedSearch = makeScopedSearch(relationshipReadScope);
16
17
  const relationshipByIdReadGate = makeByIdReadGate(relationshipReadScope);
17
18
  // See makeAuthGate's doc (record-type-kit.ts): must be wired as a genuine
18
19
  // prototype method below, never a class-field assignment — Harper's
@@ -75,16 +76,7 @@ export class Relationship extends databases.flair.Relationship {
75
76
  if (gate.kind === "unfiltered")
76
77
  return super.search(query);
77
78
  // Non-admin agent: scope to own relationships.
78
- const scope = await relationshipReadScope(gate.agentId);
79
- const agentCondition = scope.condition;
80
- if (!query?.conditions) {
81
- return super.search({ conditions: [agentCondition], ...(query || {}) });
82
- }
83
- return super.search({
84
- ...query,
85
- conditions: [agentCondition, { conditions: query.conditions, operator: query.operator || "and" }],
86
- operator: "and",
87
- });
79
+ return relationshipScopedSearch(gate.agentId, query, (q) => super.search(q));
88
80
  }
89
81
  /**
90
82
  * ─── Auth reconcile (relationship-write-path, folded K&S refinement) ──────
@@ -11,7 +11,7 @@ import { resolveReadScope } from "./memory-read-scope.js";
11
11
  // of 2026-07-08 (see ./bm25.ts's hybridEnabled() doc); set
12
12
  // FLAIR_HYBRID_RETRIEVAL=false to revert to the legacy HNSW + +0.05
13
13
  // keyword-bump path, byte-identical to the original pre-hybrid behavior.
14
- import { hybridEnabled } from "./bm25.js";
14
+ import { retrievalMode } from "./bm25.js";
15
15
  // The actual HNSW/BM25 retrieval + post-retrieval filtering (temporal/
16
16
  // supersede/isAllowed) now lives in the pure, side-effect-free
17
17
  // retrieveCandidates() core (flair-bootstrap-scale-fix, Kern-approved
@@ -28,9 +28,9 @@ export class SemanticSearch extends Resource {
28
28
  // Self-authorize via the Ed25519 agent verify instead of relying on the auth
29
29
  // gate's admin super_user elevation (removed in the auth reshape). Any
30
30
  // cryptographically-verified agent may search; per-agent RESULT scoping is
31
- // enforced in post() below (an agent only sees its own memories, any
32
- // visibility, plus granted owners' SHARED memories — never their private
33
- // ones). Without this, Harper's default denies the POST for the
31
+ // enforced in post() below (an agent sees its own records at any visibility
32
+ // plus every other agent's non-private records; grants are not consulted on
33
+ // reads — resolveReadScope()). Without this, Harper's default denies the POST for the
34
34
  // least-privilege flair_agent role (AccessViolation 403).
35
35
  async allowCreate() {
36
36
  return allowVerified(this.getContext?.());
@@ -100,24 +100,33 @@ export class SemanticSearch extends Resource {
100
100
  error: "forbidden: agentId must match authenticated agent",
101
101
  }), { status: 403, headers: { "Content-Type": "application/json" } });
102
102
  }
103
- // Scope: non-admin agent → own (+ granted). Admin agent or trusted internal
104
- // call (no request) → honor the body-supplied agentId.
103
+ // Scope: non-admin agent → its own records at any visibility plus every
104
+ // other agent's non-private records (grants are not consulted on reads —
105
+ // resolveReadScope()). Admin agent or trusted internal call (no request) →
106
+ // honor the body-supplied agentId.
105
107
  const agentId = (authenticatedAgent && !callerIsAdmin)
106
108
  ? authenticatedAgent
107
109
  : bodyAgentId;
108
- // Read-scope: own (any visibility) + granted owners' SHARED memories only
109
- // (Layer 1). Centralized in resolveReadScope() — this used to be
110
+ // Read-scope: own records at any visibility + every other agent's
111
+ // non-private records (grants are not consulted on reads). Centralized in
112
+ // resolveReadScope() — this used to be
110
113
  // an inline grant-resolution loop here PLUS a `visibility === "office"`
111
114
  // global OR-clause below that leaked ANY authenticated agent's read of
112
115
  // ANY other agent's office-visible memories. Both are gone;
113
116
  // this is the ONE scoping resolution for this endpoint now.
114
117
  const scope = agentId ? await resolveReadScope(agentId) : null;
118
+ // Select the retrieval mode ONCE per request (bench-facing selector; see
119
+ // the flag doc in ./bm25.ts). Default (FLAIR_RETRIEVAL_MODE unset) follows
120
+ // the legacy FLAIR_HYBRID_RETRIEVAL boolean exactly.
121
+ const mode = retrievalMode();
115
122
  // Generate query embedding
116
123
  let qEmb = queryEmbedding;
117
- if (!qEmb && q) {
124
+ if (!qEmb && q && mode !== "bm25-only") {
118
125
  // Always attempt embedding generation — getEmbedding() handles init internally.
119
126
  // Don't gate on getMode() which may return "none" before init completes in worker threads.
120
127
  // flair#504 Phase 2: 'query' — this is a search query, not stored content.
128
+ // bm25-only: skipped — that arm ranks on the lexical leg alone and must
129
+ // perform NO embedding call (the core ignores any qEmb it is handed).
121
130
  try {
122
131
  qEmb = await getEmbedding(String(q).slice(0, 8000), "query");
123
132
  }
@@ -171,8 +180,9 @@ export class SemanticSearch extends Resource {
171
180
  }
172
181
  // ─── Build conditions for Harper query ──────────────────────────────────
173
182
  const conditions = [];
174
- // Agent scoping: own (any visibility) OR granted-owner's SHARED memories
175
- // (private-exclusion) — the centralized read-scope condition. No agentId
183
+ // Agent scoping: own records at any visibility OR every other agent's
184
+ // non-private records (grants are not consulted on reads — resolveReadScope())
185
+ // — the centralized read-scope condition. No agentId
176
186
  // → no scoping condition pushed (trusted internal call / admin without a
177
187
  // target agentId — matches the pre-existing unscoped fallback).
178
188
  if (scope) {
@@ -228,7 +238,9 @@ export class SemanticSearch extends Resource {
228
238
  scoring,
229
239
  };
230
240
  }
231
- const hybrid = hybridEnabled();
241
+ // (`mode` was resolved at the top of post(); the bm25-only arm has no
242
+ // embedding, so the HNSW-leg portion of the overfetch policy does not apply
243
+ // to it — the core ignores `queryEmbedding` on that branch.)
232
244
  // The overfetch policy (how many raw candidates to pull from the
233
245
  // HNSW/BM25 legs relative to what the caller ultimately wants) is THIS
234
246
  // wrapper's decision — retrieveCandidates() never multiplies its `limit`
@@ -254,7 +266,7 @@ export class SemanticSearch extends Resource {
254
266
  minScore,
255
267
  agentId,
256
268
  isAllowed: scope?.isAllowed,
257
- hybrid,
269
+ mode,
258
270
  ctx,
259
271
  onLegs: includeLegs ? (l) => { legs = l; } : undefined,
260
272
  // flair#744 slice 1: the trust block needs `provenance`, which the
@@ -65,15 +65,41 @@ async function backfillEmbedding(memoryId) {
65
65
  }
66
66
  }
67
67
  // ─── HTTP middleware ──────────────────────────────────────────────────────────
68
+ // Flair's clients use exactly these HTTP methods. Harper routes other methods
69
+ // to resource handlers as well; refusing them here, before any other branch of
70
+ // the default REST middleware, keeps the tables it serves to the methods their
71
+ // handlers are written and tested for. (Separately mounted routes such as /mcp
72
+ // and OAuth discovery have their own dispatch chains and method handling.)
73
+ const ALLOWED_HTTP_METHODS = new Set([
74
+ "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE",
75
+ ]);
68
76
  server.http(async (request, nextLayer) => {
77
+ // ── HTTP method allowlist, FIRST ───────────────────────────────────────────
78
+ // Before the public-path passthrough and before any auth branch, so no path
79
+ // and no caller (anonymous, agent or admin) can reach a handler through any
80
+ // other method.
81
+ // Exact match: HTTP methods are case-sensitive, and these are the spellings
82
+ // Flair's clients send.
83
+ const httpMethod = String(request.method ?? "");
84
+ if (!ALLOWED_HTTP_METHODS.has(httpMethod)) {
85
+ return new Response(JSON.stringify({
86
+ error: "method_not_allowed",
87
+ detail: `Flair accepts ${[...ALLOWED_HTTP_METHODS].join(", ")}.`,
88
+ }), {
89
+ status: 405,
90
+ headers: { "content-type": "application/json", allow: [...ALLOWED_HTTP_METHODS].join(", ") },
91
+ });
92
+ }
69
93
  const url = new URL(request.url, "http://" + (request.headers.get("host") || "localhost"));
70
- // ── Rate limiting, FIRST ───────────────────────────────────────────────────
94
+ // ── Rate limiting, right after the method check ────────────────────────────
71
95
  // Before the public-path passthrough below (the OAuth endpoints all sit on it,
72
96
  // so a hook placed after it would never run for them), and before anything
73
- // reads a credential.
97
+ // reads a credential. A request refused by the method check above never
98
+ // reaches the limiter, and consumes no budget.
74
99
  //
75
100
  // Ordering is a security property, not tidiness. The counter is consumed for
76
- // every request to a throttled endpoint whether or not the credential that
101
+ // every request to a throttled endpoint that passes the method check, whether
102
+ // or not the credential that
77
103
  // came with it was any good — if only failures were counted, "did this consume
78
104
  // budget" would answer "was that credential valid", which is a cleaner
79
105
  // enumeration oracle than the 400 the endpoint already returns. Because the
@@ -607,8 +633,9 @@ server.http(async (request, nextLayer) => {
607
633
  if (memId) {
608
634
  const record = await databases.flair.Memory.get(memId);
609
635
  if (record && record.agentId && record.agentId !== agentId) {
610
- // Centralized read-scope (Layer 1): a grant only covers
611
- // the owner's SHARED memories, never their private ones. This
636
+ // Centralized read-scope (Layer 1): the owner's records at any
637
+ // visibility plus every other agent's non-private records; grants
638
+ // are not consulted on reads (resolveReadScope()). This
612
639
  // used to be a `visibility === "office"` bypass (any authenticated
613
640
  // agent, no grant needed) — that's gone; the private-exclusion is
614
641
  // now enforced the same way every other read path enforces it.
@@ -8,21 +8,20 @@
8
8
  // 5552320), which validated: BM25 alone recovers 5/6 severe misses into top-3;
9
9
  // candidate-UNION RRF (NOT naive whole-corpus RRF) recovers 4/6 into top-10 with
10
10
  // no regression on the within-cluster gate (p@3 holds 0.88).
11
- // ─── Feature flag: BM25 + union-RRF hybrid retrieval ────────────────────────
12
- // ACTIVATED 2026-07-08 (ops-i39b activation follow-up to #519): default is now
13
- // ON. Recall-eval validated at build time (CHANGELOG 0.20.x): NEW-8
14
- // within-cluster gate p@3 holds 0.88 (no regression), OLD-6 severe
15
- // near-verbatim misses recover 0/6 → 4/6 into top-10. A fresh isolated-Harper
16
- // measurement at activation time (no prod contact) confirmed zero regression
17
- // on both severe- and within-cluster-style synthetic queries and a small
18
- // (~+4ms/query) latency delta. Set FLAIR_HYBRID_RETRIEVAL=false (also "0" /
19
- // "off") to REVERT to the pre-hybrid legacy path — byte-identical to the
20
- // original default-OFF behavior, no code rollback needed. Read per-call so it
21
- // can be flipped without a rebuild and set per-case in tests. Lives here
22
- // (Harper-free) so it's unit-testable.
11
+ const RETRIEVAL_MODES = ["hybrid", "vector-only", "bm25-only"];
12
+ export function retrievalMode() {
13
+ const raw = process.env.FLAIR_RETRIEVAL_MODE;
14
+ if (raw !== undefined) {
15
+ const v = raw.toLowerCase();
16
+ if (RETRIEVAL_MODES.includes(v))
17
+ return v;
18
+ throw new Error(`unknown FLAIR_RETRIEVAL_MODE value "${raw}" (accepted: ${RETRIEVAL_MODES.join(", ")})`);
19
+ }
20
+ const legacy = (process.env.FLAIR_HYBRID_RETRIEVAL ?? "true").toLowerCase();
21
+ return (legacy === "true" || legacy === "1" || legacy === "on") ? "hybrid" : "vector-only";
22
+ }
23
23
  export function hybridEnabled() {
24
- const v = (process.env.FLAIR_HYBRID_RETRIEVAL ?? "true").toLowerCase();
25
- return v === "true" || v === "1" || v === "on";
24
+ return retrievalMode() === "hybrid";
26
25
  }
27
26
  // BM25 parameters (Kern-approved): k1≈1.2, b≈0.75; standard IDF + BM25.
28
27
  export const BM25_K1 = 1.2;