opencode-self-improvement 0.25.0 → 0.26.1
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 +3 -0
- package/package.json +1 -1
- package/src/recall/dedupe.ts +182 -0
- package/src/recall/score.ts +110 -12
- package/src/tools/recall.ts +16 -3
package/README.md
CHANGED
|
@@ -87,6 +87,7 @@ Zero configuration is the default. To tune, use the object form of the plugin en
|
|
|
87
87
|
| `OPENCODE_MEMORY_ALLOW_OUTSIDE_PATHS` | Operator-only. When truthy, `memory_export`/`memory_import` accept paths anywhere on disk instead of confining themselves to the store. Off by default. See [Export and move between machines](#export-and-move-between-machines). |
|
|
88
88
|
| `OPENCODE_MEMORY_INJECT_BUDGET` | Fallback for `injectBudget`. |
|
|
89
89
|
| `OPENCODE_MEMORY_FRONTIER_BUDGET` | Fallback for `frontierBudget`. |
|
|
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). |
|
|
90
91
|
| `OPENCODE_COMMANDS_DIR` | Where the plugin mirrors its slash commands (default `~/.config/opencode/commands`). |
|
|
91
92
|
| `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). |
|
|
92
93
|
| `OPENCODE_VIEWER_PORT` | Admin editor port (default `8787`). |
|
|
@@ -179,6 +180,7 @@ Two results. Only two are quoted, each with its `n` and the seat it ran on, beca
|
|
|
179
180
|
- **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.
|
|
180
181
|
- **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.
|
|
181
182
|
- **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.
|
|
183
|
+
- **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.
|
|
182
184
|
- **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`).
|
|
183
185
|
- **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)).
|
|
184
186
|
- **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries.
|
|
@@ -219,6 +221,7 @@ No vector database, no embedding model, no API key. **Bench** — what the keywo
|
|
|
219
221
|
- **In-project prompts are overwhelmingly lexical** (`bun test`, "the rate limiter", "staging deploys"): 98–100% R@3, flat from store size 50 to 500.
|
|
220
222
|
- **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.
|
|
221
223
|
- **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.
|
|
224
|
+
- **`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)).
|
|
222
225
|
- **Caveats.** The dataset is synthetic (52 memories / 105 queries, a fictional project), its class mix is deliberately adversarial, and scoring is single-gold.
|
|
223
226
|
|
|
224
227
|
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.
|
|
3
|
+
"version": "0.26.1",
|
|
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,182 @@
|
|
|
1
|
+
// Near-duplicate suppression inside a returned window (#409, RESULTS §17).
|
|
2
|
+
//
|
|
3
|
+
// The live store carries repeated rows — superseded snapshots, cursor rows that
|
|
4
|
+
// differ only by a timestamp, the same decision restated after a compaction —
|
|
5
|
+
// and the matcher scores them all the same. With a fixed window they crowd out
|
|
6
|
+
// distinct facts, which is what breaks composition: two memories a later task
|
|
7
|
+
// needs together rarely fit side by side because the first one's copies take
|
|
8
|
+
// the slots.
|
|
9
|
+
//
|
|
10
|
+
// The fix is one deterministic pass AFTER ranking: skip any candidate whose
|
|
11
|
+
// content-token Jaccard against an already-kept row of the same scope reaches
|
|
12
|
+
// the threshold, keeping the NEWEST copy of a clash (§17's adoption rule: the
|
|
13
|
+
// live duplicates are stale cursors and superseded snapshots, so the row that
|
|
14
|
+
// survives is the one written last, not the one that ranked highest). No model,
|
|
15
|
+
// no new index, and nothing changes unless the flag is set:
|
|
16
|
+
//
|
|
17
|
+
// OPENCODE_MEMORY_DEDUP=0.8 (unset or 0 = shipped behavior, byte-identical)
|
|
18
|
+
//
|
|
19
|
+
// Threshold guidance from the live replay (§17): 0.5-0.7 suppresses rows that
|
|
20
|
+
// are merely related (92% of them at 0.5) and forces the window deep into the
|
|
21
|
+
// ranking; 0.8 suppresses only near-identical copies. Values below 0.5 are a
|
|
22
|
+
// misconfiguration, not an aggressive setting: at Jaccard 1e-9 a single shared
|
|
23
|
+
// fragment suppressed rows, so anything under 0.5 turns the pass off.
|
|
24
|
+
//
|
|
25
|
+
// WHAT COUNTS AS A NEAR-COPY — the first version's three mistakes, each pinned
|
|
26
|
+
// by a test:
|
|
27
|
+
//
|
|
28
|
+
// 1. It scored `type` and `scope` as tokens. Same-scope rows then shared two
|
|
29
|
+
// free tokens, so short rows looked like copies of each other. Comparison is
|
|
30
|
+
// content-only.
|
|
31
|
+
// 2. It compared whole token sets, so a prohibition read as a copy of the
|
|
32
|
+
// permission it denies: "force push main" inside "never force push main"
|
|
33
|
+
// reaches Jaccard 0.833, and at threshold 0.8 the WRONG copy survived. If
|
|
34
|
+
// exactly one row of a pair carries a negation word, it is not a copy.
|
|
35
|
+
// 3. It had no floor. Non-Latin prose tokenises to nothing under `words()`
|
|
36
|
+
// (which splits on [^a-z0-9_]+), so two unrelated Chinese rows in one scope
|
|
37
|
+
// both reduced to the empty content set — Jaccard over empty sets is
|
|
38
|
+
// defined here as 0, but the pre-floor version scored them on type and
|
|
39
|
+
// scope alone at 1.0 and deleted the second row. A row with fewer than
|
|
40
|
+
// MIN_CONTENT content tokens is never suppressed: there is nothing to
|
|
41
|
+
// compare.
|
|
42
|
+
// 4. It treated differing numeric facts as duplicates. `words()` drops tokens
|
|
43
|
+
// of length <= 2, so "Rate limiter reads Redis DB 3." and "...DB 4." have
|
|
44
|
+
// identical token sets (Jaccard 1) and the older row was suppressed even at
|
|
45
|
+
// threshold 1 (review #415, reproduced through the handler). Numbers are
|
|
46
|
+
// compared as a sorted multiset of literals and a pair that disagrees on
|
|
47
|
+
// them is never a copy.
|
|
48
|
+
import type { Memory } from "../store/model/memory.ts";
|
|
49
|
+
import { haystack, words } from "./score.ts";
|
|
50
|
+
|
|
51
|
+
export const DEDUPE_ENV = "OPENCODE_MEMORY_DEDUP";
|
|
52
|
+
|
|
53
|
+
/** Below this, the value is a misconfiguration and the pass stays off. */
|
|
54
|
+
export const MIN_THRESHOLD = 0.5;
|
|
55
|
+
|
|
56
|
+
/** A row with fewer content tokens than this is never compared (§17 floor). */
|
|
57
|
+
export const MIN_CONTENT = 4;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Tokens that reverse a row's meaning. If exactly one row of a candidate pair
|
|
61
|
+
* carries any of them, the rows disagree, and disagreement is not duplication.
|
|
62
|
+
* Only words that survive `words()` (lower-case, length > 2) are listed;
|
|
63
|
+
* contractions split ("don't" yields "don"), which is why "don" appears.
|
|
64
|
+
*/
|
|
65
|
+
export const POLARITY_WORDS = new Set([
|
|
66
|
+
"never",
|
|
67
|
+
"not",
|
|
68
|
+
"cannot",
|
|
69
|
+
"cant",
|
|
70
|
+
"dont",
|
|
71
|
+
"don",
|
|
72
|
+
"avoid",
|
|
73
|
+
"forbidden",
|
|
74
|
+
"prohibited",
|
|
75
|
+
"banned",
|
|
76
|
+
]);
|
|
77
|
+
|
|
78
|
+
/** Threshold from the environment. Unset, empty, unparsable, < MIN_THRESHOLD or > 1 means off. */
|
|
79
|
+
export function dedupeThreshold(
|
|
80
|
+
env: Record<string, string | undefined> = process.env,
|
|
81
|
+
): number {
|
|
82
|
+
const raw = env[DEDUPE_ENV];
|
|
83
|
+
if (!raw) return 0;
|
|
84
|
+
const n = Number(raw);
|
|
85
|
+
return Number.isFinite(n) && n >= MIN_THRESHOLD && n <= 1 ? n : 0;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function jaccard(a: Set<string>, b: Set<string>): number {
|
|
89
|
+
let inter = 0;
|
|
90
|
+
const small = a.size <= b.size ? a : b;
|
|
91
|
+
const large = small === a ? b : a;
|
|
92
|
+
for (const t of small) if (large.has(t)) inter++;
|
|
93
|
+
const union = a.size + b.size - inter;
|
|
94
|
+
return union ? inter / union : 0;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The short tokens `words()` drops (chunks of length <= 2). They are where
|
|
99
|
+
* single-digit facts hide: "Rate limiter reads Redis DB 3." and "...DB 4."
|
|
100
|
+
* have identical token sets and reach Jaccard 1 (review #415). Timestamped
|
|
101
|
+
* cursor rows — the rows this pass exists to suppress — keep their digit
|
|
102
|
+
* groups inside longer tokens ("15z"), so comparing the dropped chunks only
|
|
103
|
+
* guards real fact changes without touching the cursor case. A pair whose
|
|
104
|
+
* dropped chunks differ is never a copy.
|
|
105
|
+
*/
|
|
106
|
+
export function droppedChunks(content: string): string[] {
|
|
107
|
+
return content
|
|
108
|
+
.toLowerCase()
|
|
109
|
+
.split(/[^a-z0-9_]+/)
|
|
110
|
+
.filter((t) => t.length > 0 && t.length <= 2)
|
|
111
|
+
.sort();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** True when two rows carry the same short chunks (same multiset). */
|
|
115
|
+
function sameDroppedChunks(a: Memory, b: Memory): boolean {
|
|
116
|
+
const na = droppedChunks(a.content);
|
|
117
|
+
const nb = droppedChunks(b.content);
|
|
118
|
+
if (na.length !== nb.length) return false;
|
|
119
|
+
for (let i = 0; i < na.length; i++) if (na[i] !== nb[i]) return false;
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* A row's own tokens: everything except the `type` and `scope` values, which
|
|
125
|
+
* the same-scope requirement already guarantees are shared and which made short
|
|
126
|
+
* unrelated rows look like copies.
|
|
127
|
+
*/
|
|
128
|
+
export function contentTokens(m: Memory): Set<string> {
|
|
129
|
+
const out = new Set(words(haystack(m)));
|
|
130
|
+
out.delete(m.type.toLowerCase());
|
|
131
|
+
out.delete(m.scope.toLowerCase());
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function hasPolarity(tokens: Set<string>): boolean {
|
|
136
|
+
for (const w of tokens) if (POLARITY_WORDS.has(w)) return true;
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Keep at most `limit` rows from `ranked`, in ranking order, skipping a row
|
|
142
|
+
* when it is a near-copy (same scope, content-token Jaccard >= `threshold`) of
|
|
143
|
+
* a row already kept. When a clash happens the NEWER row takes the slot —
|
|
144
|
+
* §17: the duplicates are stale snapshots, so recency decides, not rank. Rows
|
|
145
|
+
* under `MIN_CONTENT` content tokens, pairs that disagree on a negation word,
|
|
146
|
+
* and pairs whose numeric literals differ are never suppressed. `threshold <= 0`
|
|
147
|
+
* returns the plain top-`limit` slice, so the flag-off path costs nothing and
|
|
148
|
+
* cannot reorder.
|
|
149
|
+
*/
|
|
150
|
+
export function dedupeWindow(
|
|
151
|
+
ranked: Memory[],
|
|
152
|
+
limit: number,
|
|
153
|
+
threshold: number,
|
|
154
|
+
): Memory[] {
|
|
155
|
+
if (threshold <= 0 || ranked.length <= 1) return ranked.slice(0, limit);
|
|
156
|
+
const tokenSets = ranked.map(contentTokens);
|
|
157
|
+
const polarity = tokenSets.map(hasPolarity);
|
|
158
|
+
const kept: number[] = [];
|
|
159
|
+
for (let i = 0; i < ranked.length && kept.length < limit; i++) {
|
|
160
|
+
if (tokenSets[i]!.size < MIN_CONTENT) {
|
|
161
|
+
kept.push(i);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
let clash = -1; // position within `kept`, not the row index
|
|
165
|
+
for (const pos of kept.keys()) {
|
|
166
|
+
const k = kept[pos]!;
|
|
167
|
+
if (
|
|
168
|
+
ranked[k]!.scope === ranked[i]!.scope &&
|
|
169
|
+
tokenSets[k]!.size >= MIN_CONTENT &&
|
|
170
|
+
polarity[k] === polarity[i] &&
|
|
171
|
+
sameDroppedChunks(ranked[k]!, ranked[i]!) &&
|
|
172
|
+
jaccard(tokenSets[i]!, tokenSets[k]!) >= threshold
|
|
173
|
+
) {
|
|
174
|
+
clash = pos;
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (clash === -1) kept.push(i);
|
|
179
|
+
else if (ranked[i]!.ts > ranked[kept[clash]!]!.ts) kept[clash] = i;
|
|
180
|
+
}
|
|
181
|
+
return kept.map((i) => ranked[i]!);
|
|
182
|
+
}
|
package/src/recall/score.ts
CHANGED
|
@@ -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
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
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,7 +87,8 @@ export const QUERY_STOPWORDS = new Set(
|
|
|
24
87
|
),
|
|
25
88
|
);
|
|
26
89
|
|
|
27
|
-
// A free-text prompt long enough to carry >= this many
|
|
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
|
|
@@ -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
|
|
65
|
-
if (!
|
|
66
|
-
const needShared =
|
|
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
|
|
76
|
-
|
|
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
|
-
|
|
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)
|
package/src/tools/recall.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
|
|
|
10
10
|
import type { Memory } from "../store/model/memory.ts";
|
|
11
11
|
import { RecallArgs, validated } from "./schema.ts";
|
|
12
12
|
import { firstFrontierTap, markFrontierTap } from "../capture/triggers.ts";
|
|
13
|
+
import { dedupeThreshold, dedupeWindow } from "../recall/dedupe.ts";
|
|
13
14
|
|
|
14
15
|
function scoreMemory(m: Memory, q: string): number {
|
|
15
16
|
// Same indexed fields as the injection scorer (#40): a row recalled by one of
|
|
@@ -31,7 +32,7 @@ export const register: ToolRegister = (editor, deps) => {
|
|
|
31
32
|
validated(RecallArgs, {
|
|
32
33
|
name: "memory_recall",
|
|
33
34
|
description:
|
|
34
|
-
"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.",
|
|
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. Returns at most 5 rows by default, best match first — pass `limit` when you genuinely need a wider sweep.",
|
|
35
36
|
options: direct,
|
|
36
37
|
async execute(args, context): Promise<{ content: string }> {
|
|
37
38
|
const { sid, call } = toolIds(context);
|
|
@@ -51,9 +52,21 @@ export const register: ToolRegister = (editor, deps) => {
|
|
|
51
52
|
.sort((a, b) => b.score - a.score)
|
|
52
53
|
.map((x) => x.m);
|
|
53
54
|
}
|
|
54
|
-
|
|
55
|
+
// #409: the default window was 20. A live audit joined 1,090 recall
|
|
56
|
+
// events to their session transcripts: rank-1 rows go on to be
|
|
57
|
+
// referenced at 3.4x the rate of a random store row, ranks 11-20 at
|
|
58
|
+
// 1.16x — noise. Returning 17.7 rows per call meant most of the window
|
|
59
|
+
// was paid for in context and never read. 5 is the last rank where a
|
|
60
|
+
// useful row survives the cut; a caller that wants more still asks.
|
|
61
|
+
// Non-positive or fractional limits are coerced, never trusted: a
|
|
62
|
+
// negative slice(0, n) / slice(-n) silently returns MORE rows, not fewer.
|
|
63
|
+
const limit = args.limit && args.limit > 0 ? Math.floor(args.limit) : 5;
|
|
64
|
+
// #409 dedup lane (RESULTS §17): flag off, this is the same slice as
|
|
65
|
+
// before. Flag on, near-duplicate copies are skipped so the window
|
|
66
|
+
// fills with distinct rows instead of repeats of the top hit.
|
|
67
|
+
const dedupeAt = dedupeThreshold();
|
|
55
68
|
const limited = args.query
|
|
56
|
-
? results
|
|
69
|
+
? dedupeWindow(results, limit, dedupeAt)
|
|
57
70
|
: results.slice(-limit);
|
|
58
71
|
if (!limited.length) return { content: "No matching memories" };
|
|
59
72
|
const openIn = limited.filter((m) => m.status === "open").length;
|