opencode-self-improvement 0.26.0 → 0.27.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.
package/README.md CHANGED
@@ -88,6 +88,7 @@ Zero configuration is the default. To tune, use the object form of the plugin en
88
88
  | `OPENCODE_MEMORY_INJECT_BUDGET` | Fallback for `injectBudget`. |
89
89
  | `OPENCODE_MEMORY_FRONTIER_BUDGET` | Fallback for `frontierBudget`. |
90
90
  | `OPENCODE_MEMORY_DEDUP` | Near-duplicate suppression inside a `memory_recall` window. Set to a content-token Jaccard threshold, for example `0.8`: a row that is a near-copy (same scope, Jaccard at or above the threshold) of a row already returned is skipped — the newest copy of a clash survives — so the window fills with distinct facts instead of repeats of the top hit. Rows that disagree on a negation word, or carry too little comparable content, are never suppressed. Unset or `0` returns the plain top-`limit` slice, byte-identical to previous behavior; below `0.5` the value is treated as a misconfiguration and the pass stays off; see [#409](https://github.com/abogartz/opencode-self-improvement/issues/409). |
91
+ | `OPENCODE_MEMORY_QUERY_GATE` | When `1`, `true`, `yes` or `on`, a `memory_recall` match must share **two** whole words of the query once the query has three content words — the rule the injected relevance block already applies. Every other value, including `no`, keeps the matcher's permissive one-word admission. |
91
92
  | `OPENCODE_COMMANDS_DIR` | Where the plugin mirrors its slash commands (default `~/.config/opencode/commands`). |
92
93
  | `OPENCODE_VIEWER_HOST` | Interface the editor binds to (default `127.0.0.1`). A non-loopback bind serves the store over plain HTTP with no authentication — only do it on a network you control. See [Surfaces](#surfaces). |
93
94
  | `OPENCODE_VIEWER_PORT` | Admin editor port (default `8787`). |
@@ -180,6 +181,7 @@ Two results. Only two are quoted, each with its `n` and the seat it ran on, beca
180
181
  - **Section-frozen injection.** The whole memory section — standing digest, open-thread frontier, relevance block — is computed once per epoch and delivered byte-identically until something the model actually needs changes. The epoch's authority is the **rendered bytes**, not the store fingerprint: a promoted row that changes nothing visible costs no cache bust.
181
182
  - **A session never pays for bytes it is not riding.** A memory *you* saved in this session is a fact you already produced — it is in your own transcript — so it never busts your cache. The test is not "did the store change" but "would the frozen bytes still have been produced from the same inputs, minus the rows this session authored since": a correction, blocklisting, redaction or supersession of a row you are riding, and anything another session, the viewer or an import wrote, all still land on your next request.
182
183
  - **Two-concept threshold.** A free-text prompt must share at least two distinct concepts with a memory for it to be injected; keyword-length queries (one or two words) need only one. Silence on single-word coincidences is deliberate; `memory_recall` still reaches them on the pull path.
184
+ - **Identifiers split.** `getUserAccount`, `get_user_account`, `get-user-account` and `get.user.account` are one concept to the matcher rather than four, and a memory citing `src/recall/score.ts` answers a session that typed the path ([#409](https://github.com/abogartz/opencode-self-improvement/issues/409)). Measured on the published eval: aggregate recall unchanged, wrong-memory-first at the top falls 6% → 5%. Replayed over 1,091 logged recall queries through this scorer against the live store: 92.3% of top-5 sets are identical and 97.5% keep their top row.
183
185
  - **User-stated guidance rides ahead of relevance.** A row auto-capture tagged `user-guided` — something you said outright, like "the correct sales tax rate is 8.25%" — rides the block ahead of the lexical picks: newest-first, at most three, and `injectBudget` still bounds the whole block (`test/hint-channel.test.ts`). The channel exists because ranking cannot bridge vocabulary: a prompt about "the injected bug" shares no word with a row stating a tax rate, and the shipped matcher scored it zero ([#334](https://github.com/abogartz/opencode-self-improvement/issues/334)). `memory_recall` and the contextual pull stay query-driven — the channel changes only what rides the prompt. Because always-riding priority is a poisoning amplifier, the tag is minted by auto-capture alone: `memory_remember`, `memory_update` replacements and JSONL imports strip it, along with the contradiction fields ([#342](https://github.com/abogartz/opencode-self-improvement/issues/342), `test/guidance-provenance.test.ts`).
184
186
  - **The block re-scores at every user turn.** An epoch is not frozen at the first request: a later prompt re-scores, and the epoch MOVES only when the rendered bytes move — a prompt change that selects the same rows in the same order costs no cache bust ([#340](https://github.com/abogartz/opencode-self-improvement/issues/340), `test/epoch.test.ts`). Order is part of those bytes on this build: the lexical picks render in score order, so a prompt that keeps the same rows and re-ranks them moves the bytes and pays the bust. Canonical render order, which removes that churn, is still open ([#388](https://github.com/abogartz/opencode-self-improvement/issues/388), [#396](https://github.com/abogartz/opencode-self-improvement/pull/396)).
185
187
  - **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries.
@@ -220,6 +222,7 @@ No vector database, no embedding model, no API key. **Bench** — what the keywo
220
222
  - **In-project prompts are overwhelmingly lexical** (`bun test`, "the rate limiter", "staging deploys"): 98–100% R@3, flat from store size 50 to 500.
221
223
  - **Single-overlap guessing was traded away.** Free-text prompts that share one concept abstain rather than force a guess; wrong top-memory fell to 6%. `memory_recall` still covers them.
222
224
  - **Zero-overlap paraphrase is the real limit, and write time is where it is answered.** `memory_remember` asks each row for 3–5 `kw` aliases (other names, other verb forms, the literal command); auto-capture asks for the same list, so these numbers are measured through the tool path rather than through capture. Keywords are indexed and never rendered. Strict R@1 0% → 26%, near R@1 28% → 67%. A permutation control (every row given someone else's aliases) scores 29%/35%, so the gain is meaning rather than extra tokens. The limit is narrowed, not removed.
225
+ - **`memory_recall` returns 5 rows by default, not 20.** A live audit joined 1,090 recall events to their session transcripts: a returned row at rank 1 shows up in a later tool call at 3.4x the rate of a random store row, ranks 2–3 at 2.4x, and ranks 11–20 at 1.16x — noise against a 0.129 null. The old default returned 17.7 rows per call, so most of the window was context nobody read. At limit 5, recall@1 and recall@3 are unchanged, precision rises 4.1% → 13.1%, and 74% of the returned characters disappear; every gold row the cut dropped sat at ranks 6–20. Pass `limit` for a wider sweep ([#409](https://github.com/abogartz/opencode-self-improvement/issues/409)).
223
226
  - **Caveats.** The dataset is synthetic (52 memories / 105 queries, a fictional project), its class mix is deliberately adversarial, and scoring is single-gold.
224
227
 
225
228
  Full methodology and all store sizes: `bench/recall-results.md`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.26.0",
3
+ "version": "0.27.0",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
@@ -0,0 +1,131 @@
1
+ // Two-concept admission for the recall tool's matcher (#409, case bank).
2
+ //
3
+ // The tool scores a row by counting how many of the query's words appear in it
4
+ // as substrings, and returns anything that scores above zero. One shared word is
5
+ // enough, so `watermark 283 287 head` returns every row that mentions a head,
6
+ // and `fixer ready tickets queue blocked` returns rows about the GitHub CLI and
7
+ // about npm publishing. Measured on 404 real recall queries taken from 30 days of
8
+ // session transcripts and labelled by two independent readers (poc-409/casebank),
9
+ // a large share of what the tool returned was judged irrelevant rather than
10
+ // answering.
11
+ //
12
+ // The injection path already refuses single-concept matches once a query is long
13
+ // enough to be a deliberate search (LONG_QUERY_TOKENS in score.ts). This applies
14
+ // that rule to the tool, so the two paths agree on when nothing is a good enough
15
+ // answer. It changes admission only: ranking, scoring and the window size are
16
+ // untouched, and the flag-off path is the shipped behaviour.
17
+ //
18
+ // OPENCODE_MEMORY_QUERY_GATE=1 (unset or anything else = shipped behaviour)
19
+ //
20
+ // WHY THE GATE COUNTS WORDS AND THE SCORER COUNTS SUBSTRINGS
21
+ //
22
+ // These are different questions, and using the tool's own substring test here was
23
+ // the first version's mistake. Scoring asks how strongly a row matches, and
24
+ // substring matching is deliberate there: it is how `getUserAccount` finds a row
25
+ // written `get_user_account`. Admission asks how many DISTINCT CONCEPTS the query
26
+ // and the row share, and a substring is not a concept. Counting substrings made
27
+ // the gate satisfiable by two accidents: `on` occurs inside `context` and inside
28
+ // `decision`, so every row of those types shared it; `pr` occurs inside
29
+ // `preference`; and `283` occurs inside `build2837`, so the query that motivated
30
+ // this change, `watermark 283 287 head`, still admitted the row it was supposed to
31
+ // refuse. The gate therefore compares whole words, and drops the query's stopwords
32
+ // and fragments, which is exactly the vocabulary the injection scorer counts.
33
+ //
34
+ // Whole words are also what makes the number queries work. `#277` tokenises to
35
+ // `277`, so a PR-number search still matches the row that cites it, while `283` no
36
+ // longer matches `#2830`.
37
+ //
38
+ // STATUS: measured on the case bank; see the PR for the current numbers. The
39
+ // first version's numbers were measured with substring counting and are void.
40
+ // See https://github.com/abogartz/opencode-self-improvement/issues/409.
41
+ import type { Memory } from "../store/model/memory.ts";
42
+ import { LONG_QUERY_TOKENS, QUERY_STOPWORDS } from "./score.ts";
43
+
44
+ export const GATE_ENV = "OPENCODE_MEMORY_QUERY_GATE";
45
+
46
+ /**
47
+ * On only for an explicit affirmative. Everything else — unset, empty, `0`,
48
+ * `false`, and in particular `no`, which a shell user writes meaning off — is off.
49
+ * A deny-list was the first version's mistake: `=no`, `=n`, `=00` and `=0.0` all
50
+ * enabled the gate.
51
+ */
52
+ export function gateEnabled(
53
+ env: Record<string, string | undefined> = process.env,
54
+ ): boolean {
55
+ const raw = env[GATE_ENV]?.trim().toLowerCase();
56
+ return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
57
+ }
58
+
59
+ /**
60
+ * The text a recall query is matched against: type, scope, prose and the
61
+ * author-supplied keyword aliases, lower-cased. The tool's scorer shares this one
62
+ * definition so a row can never be scored against one string and admitted against
63
+ * another. Distinct from score.ts's `haystack`, which orders the same fields for
64
+ * the injection scorer.
65
+ */
66
+ export function recallHaystack(m: Memory): string {
67
+ const kw = m.kw?.length ? ` ${m.kw.join(" ")}` : "";
68
+ return `${m.type} ${m.scope} ${m.content}${kw}`.toLowerCase();
69
+ }
70
+
71
+ // Split into whole words at whitespace and punctuation. Underscore stays inside a
72
+ // word so the identifier a user searches for — `db_id`, `OPENCODE_MEMORY_DIR` —
73
+ // survives as the single concept it is (splitting it is the regression that
74
+ // blocked PR #417); a dash separates, because prose writes `get-user-account` as
75
+ // the three words it means. `build2837` stays one word, which is why `283` can no
76
+ // longer match it.
77
+ const WORD = /[^a-z0-9_]+/;
78
+
79
+ /**
80
+ * The query's distinct concepts: lower-cased whole words, with fragments and the
81
+ * scorer's own stopword list removed. A gate that counted `on` or `i` was counting
82
+ * punctuation and grammar, not concepts.
83
+ */
84
+ export function queryConcepts(query: string): string[] {
85
+ const out: string[] = [];
86
+ for (const w of query.toLowerCase().split(WORD))
87
+ if (w.length > 2 && !QUERY_STOPWORDS.has(w) && !out.includes(w))
88
+ out.push(w);
89
+ return out;
90
+ }
91
+
92
+ /** The row's concepts, as a set for whole-word membership tests. */
93
+ export function rowConcepts(m: Memory): Set<string> {
94
+ return new Set(
95
+ recallHaystack(m)
96
+ .split(WORD)
97
+ .filter((w) => w.length > 2),
98
+ );
99
+ }
100
+
101
+ /** How many of `concepts` the row contains as whole words. */
102
+ export function sharedConcepts(
103
+ m: Memory,
104
+ concepts: readonly string[],
105
+ row?: Set<string>,
106
+ ): number {
107
+ const words = row ?? rowConcepts(m);
108
+ let shared = 0;
109
+ for (const w of concepts) if (words.has(w)) shared++;
110
+ return shared;
111
+ }
112
+
113
+ /**
114
+ * True when the row may be returned. A query of LONG_QUERY_TOKENS or more
115
+ * concepts is a deliberate search, so a row must share two of them; a shorter
116
+ * query is too vague to hold a row to two. `concepts` is passed in so the split
117
+ * happens once per call rather than once per candidate.
118
+ */
119
+ export function admitsRow(
120
+ m: Memory,
121
+ concepts: readonly string[],
122
+ row?: Set<string>,
123
+ ): boolean {
124
+ // A query that reduces to zero concepts ("how do I") abstains on every row.
125
+ // That is intended: the scorer matched it on grammar alone — `i` occurs inside
126
+ // most English prose — and grammar-only matches are the noise this gate exists
127
+ // to refuse. "No matching memories" is the honest answer to a contentless
128
+ // query, and the tool already returns it when nothing scores.
129
+ const need = concepts.length >= LONG_QUERY_TOKENS ? 2 : 1;
130
+ return sharedConcepts(m, concepts, row) >= need;
131
+ }
@@ -5,11 +5,74 @@ import { isInjectable } from "../store/model/predicates.ts";
5
5
  import { cmpTs } from "../core/cmp-ts.ts";
6
6
  import { type UseSignals, useBoost } from "./relevant.ts";
7
7
 
8
+ /**
9
+ * The matcher's tokenizer. Identifier-aware (#409, RESULTS §15): the shipped
10
+ * version kept `_` inside a token and never touched case, so `getUserAccount`,
11
+ * `get_user_account` and `get-user-account` were three unrelated tokens.
12
+ *
13
+ * Each identifier (a maximal run of letters, digits, `_`, `.`, `-`, `/`) emits
14
+ * TWO granularities: the whole identifier lower-cased, and its segments split
15
+ * at camelCase boundaries and separators. The whole form is what preserves the
16
+ * exact match the shipped tokenizer had — `db_id` and `OPENCODE_MEMORY_DIR`
17
+ * stay single tokens, and an authored keyword stored fused (`memoryrecallthreshold`)
18
+ * still matches the query that cites it. Dropping the whole form is the
19
+ * regression that made the first version of this change abstain on `db_id`
20
+ * queries and break the #40 vocabulary bridge for camelCase aliases. The
21
+ * segments are what make the styles match each other: a query typed
22
+ * `getUserAccount` shares `get`, `user`, `account` with a row written
23
+ * `get_user_account`.
24
+ *
25
+ * The scan is one linear pass with no backtracking: a 4,000-character row of
26
+ * adversarial text costs microseconds, not milliseconds.
27
+ *
28
+ * Measured on the bench fixture at the SHIPPED configuration (`kw` indexed,
29
+ * store 200 and 48): lexical R@1 stays 98% and top-1 noise stays 6% — the
30
+ * fixture's queries never spell the same identifier two ways, so this is a
31
+ * correctness fix the fixture cannot price, not a measured win. The no-keyword
32
+ * arm moves (lexical R@1 98% -> 100%), but production indexes keywords.
33
+ */
8
34
  export function words(text: string): string[] {
9
- return text
10
- .toLowerCase()
11
- .split(/[^a-z0-9_]+/)
12
- .filter((t) => t.length > 2);
35
+ const out: string[] = [];
36
+ const ids = text.match(/[A-Za-z0-9_.\-/]+/g);
37
+ if (!ids) return out;
38
+ for (const id of ids) {
39
+ // Sentence punctuation is not part of the identifier: a row ending
40
+ // `Join on db_id.` must still carry the token `db_id`. Underscore stays
41
+ // (the shipped tokenizer kept it), and interior separators stay — only
42
+ // the edges are trimmed.
43
+ const whole = id.replace(/^[./-]+|[./-]+$/g, "").toLowerCase();
44
+ if (whole.length > 2) out.push(whole);
45
+ let cur = "";
46
+ const flush = () => {
47
+ if (cur.length > 2) {
48
+ const seg = cur.toLowerCase();
49
+ if (seg !== whole) out.push(seg); // single words emit once, as before
50
+ }
51
+ cur = "";
52
+ };
53
+ for (let i = 0; i < id.length; i++) {
54
+ const ch = id[i]!;
55
+ const c = id.charCodeAt(i);
56
+ const isUpper = c >= 65 && c <= 90;
57
+ const isLower = c >= 97 && c <= 122;
58
+ const isDigit = c >= 48 && c <= 57;
59
+ if (!isUpper && !isLower && !isDigit) {
60
+ flush(); // `_`, `.`, `-`, `/` end a segment
61
+ continue;
62
+ }
63
+ if (isUpper && cur) {
64
+ const prev = cur.charCodeAt(cur.length - 1)!;
65
+ const next = i + 1 < id.length ? id.charCodeAt(i + 1)! : 0;
66
+ const boundary =
67
+ (prev >= 97 && prev <= 122) || // getUser -> get | User
68
+ (prev >= 65 && prev <= 90 && next >= 97 && next <= 122); // HTTPServer -> HTTP | Server
69
+ if (boundary) flush();
70
+ }
71
+ cur += ch;
72
+ }
73
+ flush();
74
+ }
75
+ return out;
13
76
  }
14
77
 
15
78
  // Query-side stopwords: bag-of-words scoring has no IDF, so "the/what/how"
@@ -24,14 +87,15 @@ export const QUERY_STOPWORDS = new Set(
24
87
  ),
25
88
  );
26
89
 
27
- // A free-text prompt long enough to carry >= this many content tokens must
90
+ // A free-text prompt long enough to carry >= this many distinct concepts (see
91
+ // queryConcepts: an identifier and its segments count once) must
28
92
  // share >= 2 distinct concepts with a memory to inject: with a long query
29
93
  // vocabulary, one shared token is near-certain coincidence (a live store hit
30
94
  // injected a git memory on the word "should", df=1). A keyword-length query
31
95
  // is a deliberate search — one shared concept suffices. memory_recall and the
32
96
  // contextual pull keep single-overlap matches reachable; injection just stays
33
97
  // quiet unless the vocabulary genuinely agrees twice.
34
- const LONG_QUERY_TOKENS = 3;
98
+ export const LONG_QUERY_TOKENS = 3;
35
99
 
36
100
  // Production relevance ranking. Candidates must clear the concept-overlap
37
101
  // gate, then rank by Robertson-IF of the shared tokens (rare concepts beat
@@ -54,6 +118,30 @@ const LONG_QUERY_TOKENS = 3;
54
118
  // loadAll() result must not be the one place a retired memory leaks back into
55
119
  // an injected block (#43 item 1: forbidden hits). The drop also keeps a
56
120
  // retired row from diluting the document frequencies the ranking depends on.
121
+ /**
122
+ * The query's distinct concepts. `words()` emits each identifier at two
123
+ * granularities — whole form plus camel/separator segments — and the admission
124
+ * gate must count ONE concept per identifier, not one per token: a query
125
+ * citing `memoryRecallThreshold` is a single concept even though it emits
126
+ * four tokens (review #417: the flat token count raised needShared from 1 to
127
+ * 2 and a row carrying that keyword fused in `kw` stopped matching its own
128
+ * keyword). Identifiers sharing any token — the same concept spelled two ways
129
+ * in one query — merge into one group.
130
+ */
131
+ function queryConcepts(term: string): string[][] {
132
+ const groups: string[][] = [];
133
+ for (const id of term.match(/[A-Za-z0-9_.\-/]+/g) ?? []) {
134
+ const toks = words(id).filter((t) => !QUERY_STOPWORDS.has(t));
135
+ if (!toks.length) continue;
136
+ let hit = -1;
137
+ for (let g = 0; g < groups.length && hit === -1; g++)
138
+ if (toks.some((t) => groups[g]!.includes(t))) hit = g;
139
+ if (hit === -1) groups.push([...new Set(toks)]);
140
+ else groups[hit] = [...new Set([...groups[hit]!, ...toks])];
141
+ }
142
+ return groups;
143
+ }
144
+
57
145
  export function scoreMemories(
58
146
  term: string,
59
147
  mems: Memory[],
@@ -61,9 +149,9 @@ export function scoreMemories(
61
149
  use?: UseSignals,
62
150
  ): Memory[] {
63
151
  const live = mems.filter(isInjectable);
64
- const query = new Set(words(term).filter((t) => !QUERY_STOPWORDS.has(t)));
65
- if (!query.size) return [];
66
- const needShared = query.size >= LONG_QUERY_TOKENS ? 2 : 1;
152
+ const concepts = queryConcepts(term);
153
+ if (!concepts.length) return [];
154
+ const needShared = concepts.length >= LONG_QUERY_TOKENS ? 2 : 1;
67
155
  const hays = live.map((m) => new Set(words(haystack(m))));
68
156
  const df = new Map<string, number>();
69
157
  for (const h of hays) for (const t of h) df.set(t, (df.get(t) ?? 0) + 1);
@@ -72,12 +160,22 @@ export function scoreMemories(
72
160
  .map((m, i) => {
73
161
  let shared = 0;
74
162
  let score = 0;
75
- for (const w of query)
76
- if (hays[i]!.has(w)) {
163
+ for (const c of concepts) {
164
+ // A concept contributes at most its best-matching token's idf: the
165
+ // whole form and its segments are one concept, not four independent
166
+ // agreements, so a row cannot out-rank another by spelling the same
167
+ // identifier in more granularities.
168
+ let best = 0;
169
+ for (const w of c)
170
+ if (hays[i]!.has(w)) {
171
+ const d = df.get(w) ?? 0;
172
+ best = Math.max(best, Math.log(1 + (n - d + 0.5) / (d + 0.5)));
173
+ }
174
+ if (best > 0) {
77
175
  shared++;
78
- const d = df.get(w) ?? 0;
79
- score += Math.log(1 + (n - d + 0.5) / (d + 0.5));
176
+ score += best;
80
177
  }
178
+ }
81
179
  return { m, shared, score };
82
180
  })
83
181
  .filter((s) => s.shared >= needShared)
@@ -4,6 +4,12 @@
4
4
  import type { ToolRegister } from "./deps.ts";
5
5
  import { record } from "../evidence/record.ts";
6
6
  import { formatMemory } from "../inject/format.ts";
7
+ import {
8
+ admitsRow,
9
+ gateEnabled,
10
+ queryConcepts,
11
+ recallHaystack,
12
+ } from "../recall/gate.ts";
7
13
  import { loadAll } from "../store/files/load.ts";
8
14
  import { isInjectable } from "../store/model/predicates.ts";
9
15
  import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
@@ -15,8 +21,7 @@ import { dedupeThreshold, dedupeWindow } from "../recall/dedupe.ts";
15
21
  function scoreMemory(m: Memory, q: string): number {
16
22
  // Same indexed fields as the injection scorer (#40): a row recalled by one of
17
23
  // its keywords is the same row recalled by the prose that keyword stands for.
18
- const kw = m.kw?.length ? ` ${m.kw.join(" ")}` : "";
19
- const hay = `${m.type} ${m.scope} ${m.content}${kw}`.toLowerCase();
24
+ const hay = recallHaystack(m);
20
25
  let score = 0;
21
26
  for (const w of q.toLowerCase().split(/\s+/).filter(Boolean)) {
22
27
  if (hay.includes(w)) score++;
@@ -32,7 +37,7 @@ export const register: ToolRegister = (editor, deps) => {
32
37
  validated(RecallArgs, {
33
38
  name: "memory_recall",
34
39
  description:
35
- "Look up durable project knowledge — build/test/lint commands, decisions, patterns, preferences, blockers — BEFORE searching the repo or reading files. Use for 'how do I run X', conventions, and past decisions. By scope, type, or free-text query; with no filters it returns the most recent memories.",
40
+ "Look up durable project knowledge — build/test/lint commands, decisions, patterns, preferences, blockers — BEFORE searching the repo or reading files. Use for 'how do I run X', conventions, and past decisions. By scope, type, or free-text query; with no filters it returns the most recent memories. Returns at most 5 rows by default, best match first — pass `limit` when you genuinely need a wider sweep.",
36
41
  options: direct,
37
42
  async execute(args, context): Promise<{ content: string }> {
38
43
  const { sid, call } = toolIds(context);
@@ -46,13 +51,26 @@ export const register: ToolRegister = (editor, deps) => {
46
51
  results = results.filter((m) => m.scope.includes(args.scope!));
47
52
  if (args.type) results = results.filter((m) => m.type === args.type);
48
53
  if (args.query) {
54
+ // Flag off, this is the shipped filter. Flag on, a row also has to
55
+ // share two whole words of the query — the concepts rule, not the
56
+ // scorer's substring test (src/recall/gate.ts, #409).
57
+ const gate = gateEnabled();
58
+ const concepts = gate ? queryConcepts(args.query) : [];
49
59
  results = results
50
60
  .map((m) => ({ m, score: scoreMemory(m, args.query!) }))
51
- .filter((x) => x.score > 0)
61
+ .filter((x) => x.score > 0 && (!gate || admitsRow(x.m, concepts)))
52
62
  .sort((a, b) => b.score - a.score)
53
63
  .map((x) => x.m);
54
64
  }
55
- const limit = args.limit || 20;
65
+ // #409: the default window was 20. A live audit joined 1,090 recall
66
+ // events to their session transcripts: rank-1 rows go on to be
67
+ // referenced at 3.4x the rate of a random store row, ranks 11-20 at
68
+ // 1.16x — noise. Returning 17.7 rows per call meant most of the window
69
+ // was paid for in context and never read. 5 is the last rank where a
70
+ // useful row survives the cut; a caller that wants more still asks.
71
+ // Non-positive or fractional limits are coerced, never trusted: a
72
+ // negative slice(0, n) / slice(-n) silently returns MORE rows, not fewer.
73
+ const limit = args.limit && args.limit > 0 ? Math.floor(args.limit) : 5;
56
74
  // #409 dedup lane (RESULTS §17): flag off, this is the same slice as
57
75
  // before. Flag on, near-duplicate copies are skipped so the window
58
76
  // fills with distinct rows instead of repeats of the top hit.