opencode-self-improvement 0.9.2 → 0.11.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 +21 -13
- package/package.json +1 -1
- package/src/capture.ts +30 -2
- package/src/config.ts +4 -0
- package/src/gates.ts +12 -0
- package/src/hits.ts +213 -0
- package/src/index.ts +40 -7
- package/src/inject.ts +97 -13
- package/src/memory.ts +55 -1
- package/src/portable.ts +10 -0
- package/src/schema.ts +14 -0
- package/src/status.ts +35 -0
- package/src/tui.tsx +9 -1
package/README.md
CHANGED
|
@@ -161,11 +161,14 @@ A deterministic, auditable eval of the **shipped** matcher against classic
|
|
|
161
161
|
BM25, on query classes assigned by *measured* vocabulary overlap with the
|
|
162
162
|
right memory (store of 200; k=3 = the production injection limit):
|
|
163
163
|
|
|
164
|
-
| Query, vs. the stored memory | share | R@1 | R@3 |
|
|
165
|
-
| --- | ---: | ---: | ---: |
|
|
166
|
-
| lexical — reuses your project's words | 46% | 98% | 98% |
|
|
167
|
-
| near — reworded, one overlap | 17% | 28% | 28% |
|
|
168
|
-
| strict — zero shared words | 37% | 0% | 0% |
|
|
164
|
+
| Query, vs. the stored memory | share | R@1 | R@3 | with `kw` R@1 | with `kw` R@3 |
|
|
165
|
+
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
166
|
+
| lexical — reuses your project's words | 46% | 98% | 98% | 98% | 98% |
|
|
167
|
+
| near — reworded, one overlap | 17% | 28% | 28% | 67% | 72% |
|
|
168
|
+
| strict — zero shared words | 37% | 0% | 0% | 26% | 26% |
|
|
169
|
+
|
|
170
|
+
"with `kw`" is the same matcher over the same store, with each row's write-time
|
|
171
|
+
keywords indexed — the only changed variable is the index.
|
|
169
172
|
|
|
170
173
|
What the benchmark bought us:
|
|
171
174
|
|
|
@@ -183,14 +186,19 @@ What the benchmark bought us:
|
|
|
183
186
|
exactly: near-class R@3 83% → 28% (the remainder is keyword-length queries,
|
|
184
187
|
which still inject on one concept) for the 34% → 6% wrong-memory number
|
|
185
188
|
above. A quiet turn beats a confident wrong one.
|
|
186
|
-
- **Strict paraphrase
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
189
|
+
- **Strict paraphrase was the real lexical wall, and write-time keywords
|
|
190
|
+
cracked part of it.** Nothing that reads-only ever crossed it: the matcher
|
|
191
|
+
went *silent* when the vocabulary shared nothing (35 of 39 strict queries
|
|
192
|
+
injected nothing at all), leaving `memory_recall` as the pull path. So the
|
|
193
|
+
fix moved to write time — `memory_remember` and auto-capture ask each row for
|
|
194
|
+
3-5 `kw` aliases (other names, other verb forms, the literal command), which
|
|
195
|
+
are indexed and never rendered. Result: strict R@1 0% → 26% and near R@1 28% →
|
|
196
|
+
67%, top-1 wrong-memory noise unchanged at 6%, abstentions 47 → 30. A
|
|
197
|
+
permutation control (every row given someone else's aliases) scores 29%/35%,
|
|
198
|
+
so the gain is meaning, not extra tokens. The wall is not gone — 26% is a
|
|
199
|
+
third of it, and embeddings remain the only general crossing (the bench
|
|
200
|
+
exposes a scorer seam if you want to measure them; requiring an inference
|
|
201
|
+
engine just to remember things is a non-starter for a zero-dependency plugin).
|
|
194
202
|
- Caveats, honestly: the dataset is synthetic (52 memories / 105 queries, a
|
|
195
203
|
fictional project), its class mix is deliberately adversarial (far richer in
|
|
196
204
|
zero-overlap paraphrases than real prompts), and scoring is single-gold.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.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": {
|
package/src/capture.ts
CHANGED
|
@@ -26,6 +26,28 @@ export interface CaptureCandidate {
|
|
|
26
26
|
scope: string;
|
|
27
27
|
content: string;
|
|
28
28
|
status?: "open" | "settled";
|
|
29
|
+
/** Retrieval keywords (#40): indexed by the store, never rendered. */
|
|
30
|
+
kw?: string[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Keywords are the vocabulary bridge for the strict-paraphrase wall, mined from
|
|
34
|
+
// the transcript the model just saw. Cap and shape mirror the store's own
|
|
35
|
+
// limits; the store normalises again at write, so this only has to stay
|
|
36
|
+
// junk-proof (capture.ts never imports the store — it stays dependency-free).
|
|
37
|
+
const CAPTURE_KEYWORD_CAP = 8;
|
|
38
|
+
const CAPTURE_KEYWORD_CHARS = 48;
|
|
39
|
+
|
|
40
|
+
function cleanKeywords(value: unknown): string[] | undefined {
|
|
41
|
+
if (!Array.isArray(value)) return undefined;
|
|
42
|
+
const out: string[] = [];
|
|
43
|
+
for (const item of value) {
|
|
44
|
+
if (typeof item !== "string") continue;
|
|
45
|
+
const k = item.trim().toLowerCase();
|
|
46
|
+
if (!k || k.length > CAPTURE_KEYWORD_CHARS || flattenMemoryText(k) !== k) continue;
|
|
47
|
+
if (!out.includes(k)) out.push(k);
|
|
48
|
+
if (out.length === CAPTURE_KEYWORD_CAP) break;
|
|
49
|
+
}
|
|
50
|
+
return out.length ? out : undefined;
|
|
29
51
|
}
|
|
30
52
|
|
|
31
53
|
// Prompt for the cheap capture model. The output contract is a bare JSON
|
|
@@ -35,13 +57,14 @@ export function buildCapturePrompt(transcript: string, max = 3): string {
|
|
|
35
57
|
"You mine one coding-agent session transcript for durable memories worth keeping across future sessions.",
|
|
36
58
|
"",
|
|
37
59
|
`Output ONLY a JSON array of at most ${max} objects (a fenced json block is fine), each:`,
|
|
38
|
-
'{"type": "...", "scope": "...", "content": "...", "status": "..."}',
|
|
60
|
+
'{"type": "...", "scope": "...", "content": "...", "status": "...", "kw": ["...", "..."]}',
|
|
39
61
|
"",
|
|
40
62
|
"Rules:",
|
|
41
63
|
`- type: one of ${TYPES.join(", ")}.`,
|
|
42
64
|
"- scope: short area name (e.g. auth, api, build).",
|
|
43
65
|
'- status: "open" for a live planning thread; otherwise "settled".',
|
|
44
66
|
"- content: one self-contained fact, 20-600 characters, useful in a NEW session.",
|
|
67
|
+
'- kw: 3-5 search keywords for how a DIFFERENT session would ask for this — synonyms and alternate names, other verb forms, the literal command or file name. They are indexed for retrieval and never shown to a model. Omit (or []) when the content already uses those words.',
|
|
45
68
|
"- Keep: decisions made, working commands, user preferences, blockers hit, durable context, conventions.",
|
|
46
69
|
"- Skip: anything derivable from the code or git history, small talk, and details that only mattered inside this conversation.",
|
|
47
70
|
"- If nothing is worth remembering, output [ ].",
|
|
@@ -112,7 +135,12 @@ export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
|
|
|
112
135
|
if (!VALID_TYPES.has(type)) continue;
|
|
113
136
|
if (content.length < 20 || content.length > 600) continue;
|
|
114
137
|
const status = o.status === "open" || o.status === "settled" ? o.status : undefined;
|
|
115
|
-
|
|
138
|
+
// A bad kw list costs the row its keywords, never the row itself.
|
|
139
|
+
const kw = cleanKeywords(o.kw);
|
|
140
|
+
out.push({
|
|
141
|
+
...(status ? { type, scope, content, status } : { type, scope, content }),
|
|
142
|
+
...(kw ? { kw } : {}),
|
|
143
|
+
});
|
|
116
144
|
}
|
|
117
145
|
return out;
|
|
118
146
|
} catch {
|
package/src/config.ts
CHANGED
|
@@ -33,6 +33,10 @@ export function canonicalFile(): string {
|
|
|
33
33
|
return join(memoryRoot(), "canonical.logfmt");
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
+
// The use ledger (src/hits.ts). Lives in the store root beside the day files
|
|
37
|
+
// but is NOT a memory file: memory.ts's RESERVED set keeps it out of loadAll().
|
|
38
|
+
export const HITS_FILENAME = "hits.logfmt";
|
|
39
|
+
|
|
36
40
|
export function deletionsFile(): string {
|
|
37
41
|
return join(memoryRoot(), "deletions.logfmt");
|
|
38
42
|
}
|
package/src/gates.ts
CHANGED
|
@@ -33,6 +33,10 @@ export interface WriteCandidate {
|
|
|
33
33
|
content: string;
|
|
34
34
|
issue?: string;
|
|
35
35
|
tags?: string[];
|
|
36
|
+
// Retrieval keywords (#40) — indexed for recall, never rendered. Normalised
|
|
37
|
+
// (trim/lowercase/cap) at promotion, so a caller may hand junk without
|
|
38
|
+
// changing the verdict the prose deserves.
|
|
39
|
+
kw?: string[];
|
|
36
40
|
status?: "open" | "settled";
|
|
37
41
|
// "global" = cross-project (memory_remember global:true; imports carry a
|
|
38
42
|
// row's origin stamp). Any other value (including undefined) is resolved by
|
|
@@ -242,6 +246,13 @@ export async function runWriteGate(
|
|
|
242
246
|
) {
|
|
243
247
|
badMetadata.push("tags");
|
|
244
248
|
}
|
|
249
|
+
if (
|
|
250
|
+
candidate.kw !== undefined &&
|
|
251
|
+
(!Array.isArray(candidate.kw) ||
|
|
252
|
+
candidate.kw.some((k) => typeof k !== "string" || flattenMemoryText(k) !== k))
|
|
253
|
+
) {
|
|
254
|
+
badMetadata.push("kw");
|
|
255
|
+
}
|
|
245
256
|
if (badMetadata.length) {
|
|
246
257
|
await recordWriteBlocked(4, "invalid_metadata", [`fields=${badMetadata.join(",")}`], chain);
|
|
247
258
|
return {
|
|
@@ -255,6 +266,7 @@ export async function runWriteGate(
|
|
|
255
266
|
const credentialMetadata = [
|
|
256
267
|
containsSecret(candidate.scope) ? "scope" : undefined,
|
|
257
268
|
candidate.tags?.some(containsSecret) ? "tags" : undefined,
|
|
269
|
+
candidate.kw?.some(containsSecret) ? "kw" : undefined,
|
|
258
270
|
containsSecret(candidate.issue) ? "issue" : undefined,
|
|
259
271
|
].filter((field): field is string => field !== undefined);
|
|
260
272
|
if (credentialMetadata.length) {
|
package/src/hits.ts
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// The use ledger (#42). Decay, consolidation and the status surfaces all act
|
|
2
|
+
// on memories today with no idea whether anybody ever reads them — the store
|
|
3
|
+
// knows what was written and nothing about what was used. This module closes
|
|
4
|
+
// that loop with one append-only logfmt file.
|
|
5
|
+
//
|
|
6
|
+
// What a "use" is, deliberately narrow:
|
|
7
|
+
// inject — the rows that actually survived into an epoch block (offered to
|
|
8
|
+
// the model on every request of that epoch);
|
|
9
|
+
// pull — rows appended to a grep/glob/read result by the contextual pull;
|
|
10
|
+
// recall — rows returned by a memory_recall call.
|
|
11
|
+
//
|
|
12
|
+
// What it is NOT: evidence is a different file and a different contract. This
|
|
13
|
+
// ledger is DATA, never injected (I3 holds), never a memory row (hits.logfmt
|
|
14
|
+
// is in memory.ts's RESERVED set so loadAll() cannot ingest it), and it logs no
|
|
15
|
+
// prompt text — only the tokens a row and the query shared, each of which
|
|
16
|
+
// already exists inside that row.
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
import { memoryRoot, HITS_FILENAME } from "./config.ts";
|
|
19
|
+
import { appendLog, bracketList, formatLine, parseLine, readLines, writeAtomic } from "./logfmt.ts";
|
|
20
|
+
import type { UseSignals } from "./inject.ts";
|
|
21
|
+
import { withStoreLock, LOCK_WRITE } from "./lock.ts";
|
|
22
|
+
import type { Memory } from "./memory.ts";
|
|
23
|
+
|
|
24
|
+
export type HitSource = "inject" | "pull" | "recall";
|
|
25
|
+
|
|
26
|
+
export { HITS_FILENAME };
|
|
27
|
+
|
|
28
|
+
// The ledger is a bounded ring, not a growing file: one line per (source,
|
|
29
|
+
// session, row-set) per THROTTLE_MS, and at MAX_HITS_BYTES the older half is
|
|
30
|
+
// dropped whole-line. Use data older than the window is not interesting — a
|
|
31
|
+
// memory unused since before the window is the finding, not the record. The
|
|
32
|
+
// size is sized for the hour throttle (worst case ~200 B/line × 24 h × dozens
|
|
33
|
+
// of row-sets covering the 30-day dead-weight window for ordinary traffic);
|
|
34
|
+
// when it is shorter than the window, the surfaces say so with the ledger's
|
|
35
|
+
// own first line rather than inflating "never" (status.ledgerSince).
|
|
36
|
+
const MAX_HITS_BYTES = 2_000_000;
|
|
37
|
+
export const THROTTLE_MS = 3_600_000;
|
|
38
|
+
const MAX_LOGGED_TERMS = 8;
|
|
39
|
+
|
|
40
|
+
export function hitsFile(): string {
|
|
41
|
+
return join(memoryRoot(), HITS_FILENAME);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface HitEntry {
|
|
45
|
+
ts: string;
|
|
46
|
+
src: HitSource;
|
|
47
|
+
sid: string;
|
|
48
|
+
mems: string[];
|
|
49
|
+
terms: string[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// --- writing --------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
// key -> ms of the last line actually written. The epoch block rides EVERY
|
|
55
|
+
// request of an epoch, so without this one "offer" would be counted dozens of
|
|
56
|
+
// times and the dead-weight number would be fiction.
|
|
57
|
+
const lastWrite = new Map<string, number>();
|
|
58
|
+
|
|
59
|
+
/** Clear the throttle window (tests; also what a process restart does). */
|
|
60
|
+
export function resetHitThrottle(): void {
|
|
61
|
+
lastWrite.clear();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function rotateIfNeeded(): Promise<void> {
|
|
65
|
+
const file = Bun.file(hitsFile());
|
|
66
|
+
const size = await file.size;
|
|
67
|
+
if (size <= MAX_HITS_BYTES) return;
|
|
68
|
+
const lines = (await file.text()).split("\n").filter((l) => l.trim());
|
|
69
|
+
await writeAtomic(hitsFile(), lines.slice(Math.floor(lines.length / 2)).join("\n") + "\n");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Record one use of a set of rows. Throttled per (source, session, row-set),
|
|
74
|
+
* fail-soft: the ledger is telemetry, so a write failure must never break the
|
|
75
|
+
* read path that noticed it.
|
|
76
|
+
*
|
|
77
|
+
* `terms` are the tokens the query and these rows shared (never the query
|
|
78
|
+
* itself), capped and pre-sanitised by sharedTerms() in src/inject.ts. They
|
|
79
|
+
* exist so #45 can ask "if we merge these rows, do the same reads still
|
|
80
|
+
* land?" — a question no use log without them can answer.
|
|
81
|
+
*/
|
|
82
|
+
export async function recordHits(
|
|
83
|
+
source: HitSource,
|
|
84
|
+
sid: string,
|
|
85
|
+
rows: Memory[],
|
|
86
|
+
terms: string[] = [],
|
|
87
|
+
now = Date.now(),
|
|
88
|
+
): Promise<boolean> {
|
|
89
|
+
if (!rows.length) return false;
|
|
90
|
+
const ids = rows.map((m) => m.ts);
|
|
91
|
+
const key = `${source}|${sid}|${ids.join(",")}`;
|
|
92
|
+
const prev = lastWrite.get(key);
|
|
93
|
+
if (prev !== undefined && now - prev < THROTTLE_MS) return false;
|
|
94
|
+
lastWrite.set(key, now);
|
|
95
|
+
// Bound the throttle map: sessions churn, and a long-lived server must not
|
|
96
|
+
// grow one entry per row-set forever. Oldest-inserted entries go first.
|
|
97
|
+
if (lastWrite.size > 2000) {
|
|
98
|
+
for (const k of [...lastWrite.keys()].slice(0, 1000)) lastWrite.delete(k);
|
|
99
|
+
}
|
|
100
|
+
const line = formatLine({
|
|
101
|
+
ev: "memory_used",
|
|
102
|
+
ts: new Date(now).toISOString(),
|
|
103
|
+
src: source,
|
|
104
|
+
sid,
|
|
105
|
+
mem: bracketList(ids),
|
|
106
|
+
...(terms.length ? { terms: bracketList(terms.slice(0, MAX_LOGGED_TERMS)) } : {}),
|
|
107
|
+
});
|
|
108
|
+
try {
|
|
109
|
+
await withStoreLock(
|
|
110
|
+
hitsFile(),
|
|
111
|
+
async () => {
|
|
112
|
+
await rotateIfNeeded();
|
|
113
|
+
await appendLog(hitsFile(), line);
|
|
114
|
+
},
|
|
115
|
+
LOCK_WRITE,
|
|
116
|
+
);
|
|
117
|
+
return true;
|
|
118
|
+
} catch {
|
|
119
|
+
return false; // telemetry never breaks retrieval
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// --- reading --------------------------------------------------------------------
|
|
124
|
+
|
|
125
|
+
export interface UseSignal {
|
|
126
|
+
count: number;
|
|
127
|
+
last: string; // newest hit ts
|
|
128
|
+
terms: string[];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export interface UseLedger {
|
|
132
|
+
/** row ts -> what the ledger knows about it. */
|
|
133
|
+
byRow: Map<string, UseSignal>;
|
|
134
|
+
/** oldest line in the ledger — "never retrieved" is only true since this. */
|
|
135
|
+
since: string | null;
|
|
136
|
+
lines: number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Read the whole ledger. Cheap by construction: it is a bounded ring. */
|
|
140
|
+
export async function readLedger(): Promise<UseLedger> {
|
|
141
|
+
const byRow = new Map<string, UseSignal>();
|
|
142
|
+
let since: string | null = null;
|
|
143
|
+
let lines = 0;
|
|
144
|
+
for (const line of await readLines(hitsFile())) {
|
|
145
|
+
const f = parseLine(line);
|
|
146
|
+
if (!f || f.ev !== "memory_used") continue;
|
|
147
|
+
lines++;
|
|
148
|
+
const ts = typeof f.ts === "string" ? f.ts : "";
|
|
149
|
+
if (ts && (!since || ts < since)) since = ts;
|
|
150
|
+
const mem = typeof f.mem === "string" ? parseList(f.mem) : [];
|
|
151
|
+
const terms = typeof f.terms === "string" ? parseList(f.terms) : [];
|
|
152
|
+
for (const row of mem) {
|
|
153
|
+
const cur = byRow.get(row);
|
|
154
|
+
if (!cur) byRow.set(row, { count: 1, last: ts, terms: [...terms] });
|
|
155
|
+
else {
|
|
156
|
+
cur.count++;
|
|
157
|
+
if (ts > cur.last) cur.last = ts;
|
|
158
|
+
for (const t of terms) if (!cur.terms.includes(t)) cur.terms.push(t);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return { byRow, since, lines };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function parseList(value: string): string[] {
|
|
166
|
+
return value
|
|
167
|
+
.replace(/^\[|\]$/g, "")
|
|
168
|
+
.split(",")
|
|
169
|
+
.map((s) => s.trim())
|
|
170
|
+
.filter(Boolean);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Rows the ledger has NEVER seen used, plus the honest since-qualifier. */
|
|
174
|
+
export function neverRetrieved(rows: Memory[], ledger: UseLedger, days = 30): Memory[] {
|
|
175
|
+
const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
|
|
176
|
+
return rows.filter((m) => {
|
|
177
|
+
const u = ledger.byRow.get(m.ts);
|
|
178
|
+
return !u || u.last < cutoff;
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Active rows used at least once inside the window. */
|
|
183
|
+
export function usedRecently(rows: Memory[], ledger: UseLedger, days = 30): number {
|
|
184
|
+
const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
|
|
185
|
+
return rows.filter((m) => {
|
|
186
|
+
const u = ledger.byRow.get(m.ts);
|
|
187
|
+
return !!u && u.last >= cutoff;
|
|
188
|
+
}).length;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// --- cached view for the read path -------------------------------------------------
|
|
192
|
+
// A contextual pull runs on every grep/glob/read, so the ledger is read at most
|
|
193
|
+
// once per LEDGER_TTL_MS. Ranking may therefore lag a write by one TTL — the
|
|
194
|
+
// epoch only re-scores when the store changes anyway, so this never costs a
|
|
195
|
+
// prompt-cache bust, and reinforcement is a tie-break, not a guarantee.
|
|
196
|
+
|
|
197
|
+
const LEDGER_TTL_MS = 60_000;
|
|
198
|
+
let ledgerCache: { at: number; ledger: UseLedger } | null = null;
|
|
199
|
+
|
|
200
|
+
export async function useSignals(ttlMs = LEDGER_TTL_MS, now = Date.now()): Promise<UseSignals> {
|
|
201
|
+
if (!ledgerCache || now - ledgerCache.at > ttlMs) {
|
|
202
|
+
ledgerCache = { at: now, ledger: await readLedger() };
|
|
203
|
+
}
|
|
204
|
+
return ledgerCache.ledger.byRow;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Drop the cached ledger (tests). There is no write hook: between resets the
|
|
208
|
+
* cache simply expires after `ttlMs`, so ranking can lag a new hit by up to
|
|
209
|
+
* one TTL — fine for a tie-break, and it keeps a pull from re-reading the
|
|
210
|
+
* ring on every grep/glob/read. */
|
|
211
|
+
export function resetLedgerCache(): void {
|
|
212
|
+
ledgerCache = null;
|
|
213
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -37,11 +37,14 @@ import {
|
|
|
37
37
|
contextualPull,
|
|
38
38
|
formatMemory,
|
|
39
39
|
injectedRows,
|
|
40
|
+
pullQuery,
|
|
40
41
|
selectRelevant,
|
|
42
|
+
sharedTerms,
|
|
41
43
|
storeVersion,
|
|
42
44
|
systemDigest,
|
|
43
45
|
} from "./inject.ts";
|
|
44
46
|
import { attributeSession, deriveMemoryRefs, type MemoryRefs } from "./attribution.ts";
|
|
47
|
+
import { readLedger, neverRetrieved, recordHits, useSignals, type HitSource } from "./hits.ts";
|
|
45
48
|
import { formatInit, runInit } from "./init.ts";
|
|
46
49
|
import { ensureInitCommand, ensureMemoryReportCommand } from "./command.ts";
|
|
47
50
|
import {
|
|
@@ -52,6 +55,7 @@ import {
|
|
|
52
55
|
type Measured,
|
|
53
56
|
type SessionStats,
|
|
54
57
|
type StatusPayload,
|
|
58
|
+
type StoreCounts,
|
|
55
59
|
} from "./status.ts";
|
|
56
60
|
import {
|
|
57
61
|
afterTool,
|
|
@@ -92,7 +96,10 @@ import {
|
|
|
92
96
|
} from "./schema.ts";
|
|
93
97
|
|
|
94
98
|
function scoreMemory(m: Memory, q: string): number {
|
|
95
|
-
|
|
99
|
+
// Same indexed fields as the injection scorer (#40): a row recalled by one of
|
|
100
|
+
// its keywords is the same row recalled by the prose that keyword stands for.
|
|
101
|
+
const kw = m.kw?.length ? ` ${m.kw.join(" ")}` : "";
|
|
102
|
+
const hay = `${m.type} ${m.scope} ${m.content}${kw}`.toLowerCase();
|
|
96
103
|
let score = 0;
|
|
97
104
|
for (const w of q.toLowerCase().split(/\s+/).filter(Boolean)) {
|
|
98
105
|
if (hay.includes(w)) score++;
|
|
@@ -297,7 +304,7 @@ const impl = {
|
|
|
297
304
|
editor.add(validated(RememberArgs, {
|
|
298
305
|
name: "memory_remember",
|
|
299
306
|
description:
|
|
300
|
-
"Store a memory after the 4-gate write pipeline validates it (canonical graph, stale refs, dupes). Blocked writes record evidence instead of persisting.",
|
|
307
|
+
"Store a memory after the 4-gate write pipeline validates it (canonical graph, stale refs, dupes). Blocked writes record evidence instead of persisting. Add `kw` — 3-5 aliases, synonyms, verb forms or the literal command a FUTURE session would search with — to make a row findable when the wording differs; keywords are indexed, never injected.",
|
|
301
308
|
options: direct,
|
|
302
309
|
async execute(args): Promise<{ content: string }> {
|
|
303
310
|
const candidate: WriteCandidate = {
|
|
@@ -306,6 +313,7 @@ const impl = {
|
|
|
306
313
|
content: args.content,
|
|
307
314
|
issue: args.issue,
|
|
308
315
|
tags: args.tags,
|
|
316
|
+
kw: args.kw,
|
|
309
317
|
status: args.status,
|
|
310
318
|
repo: args.global ? "global" : undefined,
|
|
311
319
|
};
|
|
@@ -364,6 +372,7 @@ const impl = {
|
|
|
364
372
|
turn: firstFrontierTap(cur.sid)?.turn,
|
|
365
373
|
});
|
|
366
374
|
}
|
|
375
|
+
if (args.query) await noteHits("recall", getCurrent().sid, limited, args.query);
|
|
367
376
|
return { content: `Found ${results.length} (${total} total)\n\n${limited.map(formatMemory).join("\n")}` };
|
|
368
377
|
},
|
|
369
378
|
}));
|
|
@@ -398,7 +407,7 @@ const impl = {
|
|
|
398
407
|
}
|
|
399
408
|
const target = resolved.target;
|
|
400
409
|
const outcome = await runWriteGate(
|
|
401
|
-
{ type: args.type, scope: args.scope, content: args.content, status: args.status },
|
|
410
|
+
{ type: args.type, scope: args.scope, content: args.content, kw: args.kw, status: args.status },
|
|
402
411
|
gateContext(),
|
|
403
412
|
);
|
|
404
413
|
if (outcome.action === "promoted" && outcome.ts && target) {
|
|
@@ -644,13 +653,18 @@ const impl = {
|
|
|
644
653
|
const status = sid === "?" ? null : await buildPayload(sid);
|
|
645
654
|
const all = await loadAll();
|
|
646
655
|
const act = all.filter(isActive);
|
|
647
|
-
const store = {
|
|
656
|
+
const store: StoreCounts = {
|
|
648
657
|
active: act.length,
|
|
649
658
|
superseded: all.length - act.length,
|
|
650
659
|
open: act.filter((m) => m.status === "open").length,
|
|
651
660
|
scopes: new Set(act.map((m) => m.scope)).size,
|
|
652
661
|
malformed: malformedCount(),
|
|
653
662
|
};
|
|
663
|
+
// Use ledger (#42): how much of the store has never been surfaced.
|
|
664
|
+
// Reported, never acted on — retirement is a decision, not a metric.
|
|
665
|
+
const ledger = await readLedger();
|
|
666
|
+
store.neverRetrieved = neverRetrieved(act, ledger).length;
|
|
667
|
+
store.ledgerSince = ledger.since;
|
|
654
668
|
return {
|
|
655
669
|
content: renderMemoryReport({ status, store, blocked: await blockedRecent(6) }),
|
|
656
670
|
};
|
|
@@ -705,6 +719,7 @@ const impl = {
|
|
|
705
719
|
if (!ep) return null;
|
|
706
720
|
const all = await loadAll();
|
|
707
721
|
const act = all.filter(isActive);
|
|
722
|
+
const led = await readLedger();
|
|
708
723
|
return {
|
|
709
724
|
at: ep.at,
|
|
710
725
|
sessionID: sid,
|
|
@@ -719,6 +734,8 @@ const impl = {
|
|
|
719
734
|
open: act.filter((m) => m.status === "open").length,
|
|
720
735
|
scopes: new Set(act.map((m) => m.scope)).size,
|
|
721
736
|
malformed: malformedCount(),
|
|
737
|
+
neverRetrieved: neverRetrieved(act, led).length,
|
|
738
|
+
ledgerSince: led.since,
|
|
722
739
|
},
|
|
723
740
|
stats: statsFor(sid),
|
|
724
741
|
measured: measuredTurns.get(sid) ?? null,
|
|
@@ -734,18 +751,33 @@ const impl = {
|
|
|
734
751
|
// loop cannot ride one more request waiting for another user prompt.
|
|
735
752
|
const injectableRows = async (): Promise<Memory[]> =>
|
|
736
753
|
(await loadAll()).filter((m) => isActive(m) && isVisibleHere(m));
|
|
754
|
+
// Use ledger (#42). `query` is what retrieval was asked with; what gets
|
|
755
|
+
// stored is the vocabulary the answer SHARES with the query, taken from the
|
|
756
|
+
// memory side, so the ledger can never become a copy of user prompts.
|
|
757
|
+
// Fail-soft inside recordHits: telemetry must not break a read path.
|
|
758
|
+
const noteHits = async (src: HitSource, sid: string, rows: Memory[], query: string): Promise<void> => {
|
|
759
|
+
if (!rows.length || !query.trim()) return;
|
|
760
|
+
const terms: string[] = [];
|
|
761
|
+
for (const m of rows) for (const t of sharedTerms(query, m)) if (!terms.includes(t)) terms.push(t);
|
|
762
|
+
await recordHits(src, sid, rows, terms);
|
|
763
|
+
};
|
|
737
764
|
const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
|
|
738
765
|
if (!latestPrompt.has(sid)) return;
|
|
739
766
|
const mems = rows ?? await injectableRows();
|
|
740
767
|
const version = await storeVersion(mems);
|
|
741
768
|
const cached = epoch.get(sid);
|
|
742
769
|
if (cached?.version === version) return;
|
|
743
|
-
const
|
|
770
|
+
const prompt = latestPrompt.get(sid) ?? "";
|
|
771
|
+
const sel = await selectRelevant(prompt, 5, mems, await useSignals()); // widen candidate pool
|
|
744
772
|
const block = sel.block ? capToBudget(sel.block, budget) : "";
|
|
745
773
|
// Refs the ACTUALLY-injected rows assert (paths + commands), the join key
|
|
746
774
|
// for attribution. Derived from the budget-surviving rows, not the wider
|
|
747
775
|
// candidate pool — crediting paths the model never saw would overclaim.
|
|
748
|
-
const
|
|
776
|
+
const rode = injectedRows(block, sel.selected);
|
|
777
|
+
const refs = deriveMemoryRefs(rode);
|
|
778
|
+
// Use ledger (#42): the rows that actually rode the block, credited with
|
|
779
|
+
// the terms the prompt and those rows shared (never the prompt itself).
|
|
780
|
+
await noteHits("inject", sid, rode, prompt);
|
|
749
781
|
const at = new Date().toISOString();
|
|
750
782
|
const reason: "first" | "store_changed" = cached ? "store_changed" : "first";
|
|
751
783
|
epoch.set(sid, { version, block, at, reason, refs });
|
|
@@ -796,7 +828,8 @@ const impl = {
|
|
|
796
828
|
setCurrent(input);
|
|
797
829
|
const out = { output: resultText(event?.result), metadata: resultMeta(event?.result) };
|
|
798
830
|
await afterTool(input, out);
|
|
799
|
-
await contextualPull(input, out as { output?: unknown }, budget);
|
|
831
|
+
const pulled = await contextualPull(input, out as { output?: unknown }, budget, await useSignals());
|
|
832
|
+
if (pulled.length) await noteHits("pull", String(event?.sessionID ?? ""), pulled, pullQuery(input.args));
|
|
800
833
|
// Write a contextual-pull append back when the tool result is text we own.
|
|
801
834
|
if (event?.result && typeof event.result === "object" && typeof event.result.content === "string") {
|
|
802
835
|
const text = resultText(event.result);
|
package/src/inject.ts
CHANGED
|
@@ -99,9 +99,19 @@ const QUERY_STOPWORDS = new Set(
|
|
|
99
99
|
// quiet unless the vocabulary genuinely agrees twice.
|
|
100
100
|
const LONG_QUERY_TOKENS = 3;
|
|
101
101
|
|
|
102
|
-
// Production relevance ranking
|
|
102
|
+
// Production relevance ranking. Candidates must clear the concept-overlap
|
|
103
103
|
// gate, then rank by Robertson-IF of the shared tokens (rare concepts beat
|
|
104
104
|
// piles of common ones — the same idf form the bench's BM25 row uses).
|
|
105
|
+
// Ties break deliberately, in this order: open threads first (a pinned frontier
|
|
106
|
+
// row beats an equal-scoring settled one — that is what the frontier is for),
|
|
107
|
+
// then rows the use ledger has actually retrieved, most-recently-used first
|
|
108
|
+
// (#42 reinforcement), then the newer row (#40 item 2: between two equally
|
|
109
|
+
// relevant facts, the one stating what is true NOW is the better guess;
|
|
110
|
+
// epoch-freeze-safe because ts never changes for a given row).
|
|
111
|
+
// The haystack is `scope + type + content + kw`, where `kw` are the
|
|
112
|
+
// author-supplied aliases indexed at write time (#40 item 3, the vocabulary
|
|
113
|
+
// bridge for the bench's strict-paraphrase wall). Keywords are indexed, never
|
|
114
|
+
// rendered, so they cannot change what a block costs.
|
|
105
115
|
// Exported for bench/recall-quality.ts — the benchmark measures the shipped
|
|
106
116
|
// matcher.
|
|
107
117
|
//
|
|
@@ -110,12 +120,17 @@ const LONG_QUERY_TOKENS = 3;
|
|
|
110
120
|
// loadAll() result must not be the one place a retired memory leaks back into
|
|
111
121
|
// an injected block (#43 item 1: forbidden hits). The drop also keeps a
|
|
112
122
|
// retired row from diluting the document frequencies the ranking depends on.
|
|
113
|
-
export function scoreMemories(
|
|
123
|
+
export function scoreMemories(
|
|
124
|
+
term: string,
|
|
125
|
+
mems: Memory[],
|
|
126
|
+
limit: number,
|
|
127
|
+
use?: UseSignals,
|
|
128
|
+
): Memory[] {
|
|
114
129
|
const live = mems.filter((m) => !m.superseded_by);
|
|
115
130
|
const query = new Set(words(term).filter((t) => !QUERY_STOPWORDS.has(t)));
|
|
116
131
|
if (!query.size) return [];
|
|
117
132
|
const needShared = query.size >= LONG_QUERY_TOKENS ? 2 : 1;
|
|
118
|
-
const hays = live.map((m) => new Set(words(
|
|
133
|
+
const hays = live.map((m) => new Set(words(haystack(m))));
|
|
119
134
|
const df = new Map<string, number>();
|
|
120
135
|
for (const h of hays) for (const t of h) df.set(t, (df.get(t) ?? 0) + 1);
|
|
121
136
|
const n = live.length || 1;
|
|
@@ -132,11 +147,74 @@ export function scoreMemories(term: string, mems: Memory[], limit: number): Memo
|
|
|
132
147
|
return { m, shared, score };
|
|
133
148
|
})
|
|
134
149
|
.filter((s) => s.shared >= needShared)
|
|
135
|
-
.sort(
|
|
150
|
+
.sort(
|
|
151
|
+
(a, b) =>
|
|
152
|
+
b.score - a.score ||
|
|
153
|
+
openRank(b.m) - openRank(a.m) ||
|
|
154
|
+
useBoost(b.m, use) - useBoost(a.m, use) ||
|
|
155
|
+
cmpTs(use?.get(b.m.ts)?.last ?? "", use?.get(a.m.ts)?.last ?? "") ||
|
|
156
|
+
cmpTs(b.m.ts, a.m.ts),
|
|
157
|
+
)
|
|
136
158
|
.slice(0, limit)
|
|
137
159
|
.map((s) => s.m);
|
|
138
160
|
}
|
|
139
161
|
|
|
162
|
+
// What a row is matched against. Kept in one place so the bench's arms and
|
|
163
|
+
// production can never disagree about the indexed fields.
|
|
164
|
+
export function haystack(m: Memory): string {
|
|
165
|
+
return `${m.scope} ${m.type} ${m.content}${m.kw?.length ? ` ${m.kw.join(" ")}` : ""}`;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* The content concepts a query and a row actually share (stopwords dropped,
|
|
170
|
+
* capped, `ts` never included). This is what the use ledger records (#42):
|
|
171
|
+
* every term in it already exists inside the row, so a hit line reveals
|
|
172
|
+
* nothing about the prompt beyond the memory it points at — and it is enough
|
|
173
|
+
* for #45 to replay a merge and prove the same reads would still land.
|
|
174
|
+
*/
|
|
175
|
+
/** The text a contextual pull actually searched with, for hit bookkeeping. */
|
|
176
|
+
export function pullQuery(args: unknown): string {
|
|
177
|
+
return argText(args);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function sharedTerms(query: string, m: Memory, cap = 8): string[] {
|
|
181
|
+
const q = new Set(words(query).filter((t) => !QUERY_STOPWORDS.has(t)));
|
|
182
|
+
if (!q.size) return [];
|
|
183
|
+
const hay = new Set(words(haystack(m)));
|
|
184
|
+
const out: string[] = [];
|
|
185
|
+
for (const t of q) {
|
|
186
|
+
if (hay.has(t) && !out.includes(t)) out.push(t);
|
|
187
|
+
if (out.length === cap) break;
|
|
188
|
+
}
|
|
189
|
+
return out;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Reinforcement (#42): a row the ledger has seen used breaks a tie over a row
|
|
193
|
+
// nobody ever read, and the more recently used one breaks it first. A TIE-BREAK
|
|
194
|
+
// only — the two-concept gate and IDF score still decide relevance, because
|
|
195
|
+
// popularity is not truth: reinforcement without evidence just amplifies
|
|
196
|
+
// whatever was retrieved first.
|
|
197
|
+
export interface UseSignals {
|
|
198
|
+
get(ts: string): { count: number; last: string } | undefined;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function useBoost(a: Memory | undefined, use?: UseSignals): number {
|
|
202
|
+
if (!use || !a) return 0;
|
|
203
|
+
return use.get(a.ts) ? 1 : 0;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Numeric compare, with the string compare kept as fallback for non-dates
|
|
207
|
+
// (the ledger hands "" when a row was never used). ISO strings agree with
|
|
208
|
+
// Date.parse only while the FORMAT agrees: a legacy second-precision stamp
|
|
209
|
+
// ("…:01Z") and a millisecond stamp ("…:01.000Z") for the same instant order
|
|
210
|
+
// wrong as strings, which would silently mis-rank the recency tie-break.
|
|
211
|
+
function cmpTs(a: string, b: string): number {
|
|
212
|
+
const na = Date.parse(a);
|
|
213
|
+
const nb = Date.parse(b);
|
|
214
|
+
if (!Number.isNaN(na) && !Number.isNaN(nb)) return na < nb ? -1 : na > nb ? 1 : 0;
|
|
215
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
216
|
+
}
|
|
217
|
+
|
|
140
218
|
function openRank(m: Memory): number {
|
|
141
219
|
return m.status === "open" ? 1 : 0;
|
|
142
220
|
}
|
|
@@ -209,7 +287,7 @@ export async function systemDigest(
|
|
|
209
287
|
|
|
210
288
|
const open = mems
|
|
211
289
|
.filter((m) => m.status === "open")
|
|
212
|
-
.sort((a, b) => (
|
|
290
|
+
.sort((a, b) => cmpTs(b.ts, a.ts))
|
|
213
291
|
.slice(0, OPEN_THREAD_LIMIT);
|
|
214
292
|
if (!open.length) return;
|
|
215
293
|
|
|
@@ -254,12 +332,13 @@ export async function selectRelevant(
|
|
|
254
332
|
message: string,
|
|
255
333
|
limit = 3,
|
|
256
334
|
rows?: Memory[],
|
|
335
|
+
use?: UseSignals,
|
|
257
336
|
): Promise<{ block: string; selected: Memory[] }> {
|
|
258
337
|
const text = message.trim();
|
|
259
338
|
if (!text) return { block: "", selected: [] };
|
|
260
339
|
// Repo-scoped: model-facing reads see this repo + global rows.
|
|
261
340
|
const mems = rows ?? visibleHere((await loadAll()).filter(isActive));
|
|
262
|
-
const top = scoreMemories(text, mems, limit);
|
|
341
|
+
const top = scoreMemories(text, mems, limit, use);
|
|
263
342
|
if (!top.length) return { block: "", selected: [] };
|
|
264
343
|
return {
|
|
265
344
|
block: `## Relevant durable memory${FRAME}\n${top.map(formatMemory).join("\n")}`,
|
|
@@ -293,7 +372,7 @@ export async function storeVersion(rows?: Memory[]): Promise<string> {
|
|
|
293
372
|
let max = "";
|
|
294
373
|
const hash = createHash("sha256");
|
|
295
374
|
for (const m of mems) {
|
|
296
|
-
if (m.ts >
|
|
375
|
+
if (cmpTs(m.ts, max) > 0) max = m.ts;
|
|
297
376
|
hash.update(JSON.stringify([m.ts, formatMemory(m)]));
|
|
298
377
|
hash.update("\n");
|
|
299
378
|
}
|
|
@@ -335,7 +414,7 @@ export async function compactionAnchor(limit = 12): Promise<string> {
|
|
|
335
414
|
// Repo-scoped: model-facing reads see this repo + global rows.
|
|
336
415
|
const mems = visibleHere((await loadAll()).filter(isActive));
|
|
337
416
|
if (!mems.length) return "";
|
|
338
|
-
const byNewest = (a: Memory, b: Memory) => (
|
|
417
|
+
const byNewest = (a: Memory, b: Memory) => cmpTs(b.ts, a.ts);
|
|
339
418
|
const open = mems
|
|
340
419
|
.filter((m) => m.status === "open")
|
|
341
420
|
.sort(byNewest)
|
|
@@ -357,18 +436,23 @@ export async function contextualPull(
|
|
|
357
436
|
input: PullInput,
|
|
358
437
|
output: PullOutput,
|
|
359
438
|
budget = injectBudget(),
|
|
360
|
-
|
|
439
|
+
use?: UseSignals,
|
|
440
|
+
): Promise<Memory[]> {
|
|
361
441
|
const tool = typeof input.tool === "string" ? input.tool : "";
|
|
362
|
-
if (!["grep", "glob", "read"].includes(tool)) return;
|
|
442
|
+
if (!["grep", "glob", "read"].includes(tool)) return [];
|
|
363
443
|
const term = argText(input.args);
|
|
364
|
-
if (!term) return;
|
|
444
|
+
if (!term) return [];
|
|
365
445
|
// Repo-scoped: model-facing reads see this repo + global rows.
|
|
366
446
|
const mems = visibleHere((await loadAll()).filter(isActive));
|
|
367
|
-
const top = scoreMemories(term, mems, 3);
|
|
368
|
-
if (!top.length) return;
|
|
447
|
+
const top = scoreMemories(term, mems, 3, use);
|
|
448
|
+
if (!top.length) return [];
|
|
369
449
|
// Held to the injection budget too: three long rows were ~12 KB per call.
|
|
370
450
|
const block = capToBudget(`## Related durable memory (pull)${FRAME}\n${top.map(formatMemory).join("\n")}`, budget);
|
|
371
451
|
if (block && typeof output.output === "string") {
|
|
372
452
|
output.output += `\n${block}`;
|
|
453
|
+
// What the ledger counts is what actually rode the result — the budget can
|
|
454
|
+
// drop rows, and crediting a memory the model never saw would inflate it.
|
|
455
|
+
return injectedRows(block, top);
|
|
373
456
|
}
|
|
457
|
+
return [];
|
|
374
458
|
}
|
package/src/memory.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import { existsSync } from "node:fs";
|
|
6
6
|
import { open } from "node:fs/promises";
|
|
7
7
|
import { join, basename } from "node:path";
|
|
8
|
-
import { dateStr, memoryRoot, deletionsFile, snapshotDir } from "./config.ts";
|
|
8
|
+
import { dateStr, memoryRoot, deletionsFile, snapshotDir, HITS_FILENAME } from "./config.ts";
|
|
9
9
|
import { repoScopeFor } from "./repokey.ts";
|
|
10
10
|
import { getCurrent } from "./state.ts";
|
|
11
11
|
import { appendLog, ensureDir, formatLine, parseLine, readLines, writeAtomic, type Fields } from "./logfmt.ts";
|
|
@@ -24,6 +24,37 @@ export type MemoryStatus = "open" | "settled";
|
|
|
24
24
|
// absolutely in appendMemory (throws, covering gate-bypassing callers).
|
|
25
25
|
export const MAX_CONTENT_CHARS = 4000;
|
|
26
26
|
|
|
27
|
+
/** How many retrieval keywords a row may carry, and how long each one may be. */
|
|
28
|
+
export const MAX_KEYWORDS = 8;
|
|
29
|
+
export const MAX_KEYWORD_CHARS = 48;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Normalise author-supplied retrieval keywords: trim, lowercase, split on the
|
|
33
|
+
* storage delimiter, de-duplicate, drop empties and over-long entries, cap the
|
|
34
|
+
* count. TOTAL on purpose — junk yields a shorter list rather than a throw,
|
|
35
|
+
* because keywords only ever widen recall and must never be able to fail a
|
|
36
|
+
* write the prose alone deserved.
|
|
37
|
+
*/
|
|
38
|
+
export function normalizeKeywords(kw: unknown): string[] | undefined {
|
|
39
|
+
if (!Array.isArray(kw)) return undefined;
|
|
40
|
+
const out: string[] = [];
|
|
41
|
+
for (const item of kw) {
|
|
42
|
+
if (typeof item !== "string") continue;
|
|
43
|
+
// Commas are the storage delimiter (kw serialises as one comma-joined
|
|
44
|
+
// scalar), so an item carrying one would read back fragmented. Treat them
|
|
45
|
+
// as separators: "build, test" becomes two aliases, never a " test".
|
|
46
|
+
for (const part of item.split(",")) {
|
|
47
|
+
const k = part.trim().toLowerCase();
|
|
48
|
+
if (!k || k.length > MAX_KEYWORD_CHARS) continue;
|
|
49
|
+
if (!out.includes(k)) out.push(k);
|
|
50
|
+
if (out.length === MAX_KEYWORDS) break;
|
|
51
|
+
}
|
|
52
|
+
if (out.length === MAX_KEYWORDS) break;
|
|
53
|
+
}
|
|
54
|
+
return out.length ? out : undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
27
58
|
export interface Memory {
|
|
28
59
|
ts: string;
|
|
29
60
|
type: string;
|
|
@@ -31,6 +62,13 @@ export interface Memory {
|
|
|
31
62
|
content: string;
|
|
32
63
|
issue?: string;
|
|
33
64
|
tags?: string[];
|
|
65
|
+
// Retrieval keywords (#40): author-supplied aliases, verb forms and synonyms
|
|
66
|
+
// for this row, written at capture time. They widen the scoring haystack
|
|
67
|
+
// ONLY — a row is never rendered through them, so injection bytes and the
|
|
68
|
+
// content cap stay exactly what the prose says. This is the zero-embedding
|
|
69
|
+
// answer to the bench's strict-paraphrase wall (0% R@1: the user's words are
|
|
70
|
+
// not the memory's words).
|
|
71
|
+
kw?: string[];
|
|
34
72
|
superseded_by?: string;
|
|
35
73
|
reason?: string;
|
|
36
74
|
status?: MemoryStatus;
|
|
@@ -49,6 +87,9 @@ const RESERVED = new Set([
|
|
|
49
87
|
"deleted.logfmt",
|
|
50
88
|
"canonical.logfmt",
|
|
51
89
|
"blocklist.logfmt",
|
|
90
|
+
// The use ledger (src/hits.ts): telemetry, not memory. A hit line must never
|
|
91
|
+
// be able to become a row — or to be superseded, exported, or injected.
|
|
92
|
+
HITS_FILENAME,
|
|
52
93
|
]);
|
|
53
94
|
|
|
54
95
|
// Row identity is `ts`: supersede chains, the blocklist, undo matching, and
|
|
@@ -88,6 +129,9 @@ function toMemory(fields: Record<string, unknown>, file: string, index: number):
|
|
|
88
129
|
content: typeof fields.content === "string" ? fields.content : "",
|
|
89
130
|
issue: typeof fields.issue === "string" ? fields.issue : undefined,
|
|
90
131
|
tags: typeof fields.tags === "string" ? fields.tags.split(",") : undefined,
|
|
132
|
+
kw: typeof fields.kw === "string" && fields.kw
|
|
133
|
+
? fields.kw.split(",").map((k) => k.trim()).filter((k) => k.length > 0)
|
|
134
|
+
: undefined,
|
|
91
135
|
superseded_by: typeof fields.superseded_by === "string" ? fields.superseded_by : undefined,
|
|
92
136
|
reason: typeof fields.reason === "string" ? fields.reason : undefined,
|
|
93
137
|
status:
|
|
@@ -139,6 +183,8 @@ export interface AppendMemoryInput {
|
|
|
139
183
|
content: string;
|
|
140
184
|
issue?: string;
|
|
141
185
|
tags?: string[];
|
|
186
|
+
/** Retrieval keywords (#40); normalised and capped by appendMemory. */
|
|
187
|
+
kw?: string[];
|
|
142
188
|
status?: MemoryStatus;
|
|
143
189
|
// "global" for explicit cross-project writes; imports may carry a validated
|
|
144
190
|
// same-repo origin stamp (see portable.ts). Any missing value is resolved by
|
|
@@ -182,9 +228,15 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
|
|
|
182
228
|
if (input.tags?.some((tag) => flattenMemoryText(tag) !== tag)) {
|
|
183
229
|
throw new Error("memory tags must not contain control characters");
|
|
184
230
|
}
|
|
231
|
+
// Keywords are indexed, never rendered, but they still live on the row's
|
|
232
|
+
// single line, so the same control-character floor applies.
|
|
233
|
+
if (input.kw?.some((k) => typeof k !== "string" || flattenMemoryText(k) !== k)) {
|
|
234
|
+
throw new Error("memory keywords must not contain control characters");
|
|
235
|
+
}
|
|
185
236
|
const credentialMetadata = [
|
|
186
237
|
containsSecret(input.scope) ? "scope" : undefined,
|
|
187
238
|
input.tags?.some(containsSecret) ? "tags" : undefined,
|
|
239
|
+
input.kw?.some(containsSecret) ? "kw" : undefined,
|
|
188
240
|
containsSecret(input.issue) ? "issue" : undefined,
|
|
189
241
|
].filter((field): field is string => field !== undefined);
|
|
190
242
|
if (credentialMetadata.length) {
|
|
@@ -221,6 +273,7 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
|
|
|
221
273
|
while (taken.has(ts) && guard++ < 1000) {
|
|
222
274
|
ts = new Date(new Date(ts).getTime() + 1).toISOString();
|
|
223
275
|
}
|
|
276
|
+
const kw = normalizeKeywords(input.kw);
|
|
224
277
|
await appendLog(
|
|
225
278
|
file,
|
|
226
279
|
formatLine({
|
|
@@ -230,6 +283,7 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
|
|
|
230
283
|
content,
|
|
231
284
|
issue: input.issue,
|
|
232
285
|
tags: input.tags?.length ? input.tags.join(",") : undefined,
|
|
286
|
+
kw: kw?.join(","),
|
|
233
287
|
status: input.status,
|
|
234
288
|
repo,
|
|
235
289
|
repoPath,
|
package/src/portable.ts
CHANGED
|
@@ -64,6 +64,7 @@ export async function exportMemories(opts: ExportOptions = {}): Promise<ExportRe
|
|
|
64
64
|
content: m.content,
|
|
65
65
|
status: m.status,
|
|
66
66
|
tags: m.tags,
|
|
67
|
+
kw: m.kw,
|
|
67
68
|
issue: m.issue,
|
|
68
69
|
// Origin stamps ride along so a same-repo machine hop can retain them.
|
|
69
70
|
// Import validates them against its current repo before promotion.
|
|
@@ -124,9 +125,18 @@ function parseRow(line: string): WriteCandidate | null {
|
|
|
124
125
|
r.tags.some((t) => typeof t === "string" && flattenMemoryText(t) !== t)
|
|
125
126
|
) return null;
|
|
126
127
|
if (typeof r.issue === "string" && flattenMemoryText(r.issue) !== r.issue) return null;
|
|
128
|
+
// Keywords widen recall only, so a malformed entry costs them, never the row
|
|
129
|
+
// (contrast scope/content, where a bad value makes the line malformed).
|
|
130
|
+
const kw = Array.isArray(r.kw)
|
|
131
|
+
? r.kw.filter(
|
|
132
|
+
(k): k is string =>
|
|
133
|
+
typeof k === "string" && !!k.trim() && flattenMemoryText(k.trim()) === k.trim(),
|
|
134
|
+
)
|
|
135
|
+
: undefined;
|
|
127
136
|
const c: WriteCandidate = { type: r.type, scope: r.scope, content: r.content };
|
|
128
137
|
if (r.status === "open" || r.status === "settled") c.status = r.status;
|
|
129
138
|
if (Array.isArray(r.tags) && r.tags.every((t) => typeof t === "string")) c.tags = r.tags;
|
|
139
|
+
if (kw?.length) c.kw = kw;
|
|
130
140
|
if (typeof r.issue === "string" && r.issue) c.issue = r.issue;
|
|
131
141
|
// Origin stamps survive an export/import hop (repokey.ts): a row written
|
|
132
142
|
// for repo X stays visible only where repo X is opened, even on a new
|
package/src/schema.ts
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
import { z, type ZodTypeAny } from "zod";
|
|
18
18
|
import { STATUSES, TYPES } from "./types.ts";
|
|
19
19
|
import { flattenMemoryText } from "./sanitize.ts";
|
|
20
|
+
import { MAX_KEYWORDS } from "./memory.ts";
|
|
20
21
|
|
|
21
22
|
type JSONSchema = Record<string, unknown>;
|
|
22
23
|
|
|
@@ -32,6 +33,17 @@ const memoryField = z.string().refine((value) => flattenMemoryText(value) === va
|
|
|
32
33
|
message: "must not contain control characters",
|
|
33
34
|
});
|
|
34
35
|
|
|
36
|
+
// Retrieval keywords (#40). The shape cap mirrors MAX_KEYWORDS in memory.ts,
|
|
37
|
+
// which is the authority at write time (it also lowercases, de-dupes and drops
|
|
38
|
+
// over-long entries rather than rejecting the write).
|
|
39
|
+
const keywordList = z
|
|
40
|
+
.array(memoryField)
|
|
41
|
+
.max(MAX_KEYWORDS)
|
|
42
|
+
.describe(
|
|
43
|
+
"3-5 keywords for how a FUTURE session would search for this row: aliases and alternate names, verb forms, synonyms of the words you used, the literal command or file name. Indexed for matching only — never shown in an injected block. Skip it when the prose already says it.",
|
|
44
|
+
)
|
|
45
|
+
.optional();
|
|
46
|
+
|
|
35
47
|
// ---- tool argument schemas (JSON Schema generated from these) ------------
|
|
36
48
|
|
|
37
49
|
export const RememberArgs = z.object({
|
|
@@ -40,6 +52,7 @@ export const RememberArgs = z.object({
|
|
|
40
52
|
content: z.string().describe("The memory content"),
|
|
41
53
|
issue: memoryField.describe("Related issue").optional(),
|
|
42
54
|
tags: z.array(memoryField).optional(),
|
|
55
|
+
kw: keywordList,
|
|
43
56
|
status: z
|
|
44
57
|
.enum(STATUSES)
|
|
45
58
|
.describe(
|
|
@@ -73,6 +86,7 @@ export const UpdateArgs = z.object({
|
|
|
73
86
|
scope: memoryField,
|
|
74
87
|
type: z.enum(TYPES),
|
|
75
88
|
content: z.string(),
|
|
89
|
+
kw: keywordList,
|
|
76
90
|
query: z
|
|
77
91
|
.string()
|
|
78
92
|
.describe(
|
package/src/status.ts
CHANGED
|
@@ -25,6 +25,27 @@ export interface StoreCounts {
|
|
|
25
25
|
scopes: number;
|
|
26
26
|
/** Rows skipped as malformed by the most recent store read. */
|
|
27
27
|
malformed: number;
|
|
28
|
+
/**
|
|
29
|
+
* Active rows the use ledger has never credited (or not inside the window).
|
|
30
|
+
* Undefined until #42's ledger is read — an absent number, never a zero.
|
|
31
|
+
*/
|
|
32
|
+
neverRetrieved?: number;
|
|
33
|
+
/**
|
|
34
|
+
* Oldest line in the use ledger, or null when it holds none. The 30-day
|
|
35
|
+
* dead-weight number is only honest inside the ledger's coverage; a young
|
|
36
|
+
* ledger says so instead of inflating "never" (see `ledgerIsYoung`).
|
|
37
|
+
*/
|
|
38
|
+
ledgerSince?: string | null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* True when the ledger cannot honestly cover the 30-day window: its first
|
|
43
|
+
* line is younger than the window, or there is no ledger at all. Every "never
|
|
44
|
+
* retrieved" surface must carry this qualifier when it returns true.
|
|
45
|
+
*/
|
|
46
|
+
export function ledgerIsYoung(ledgerSince: string | null | undefined, now = Date.now()): boolean {
|
|
47
|
+
if (!ledgerSince) return true;
|
|
48
|
+
return ledgerSince > new Date(now - 30 * 86_400_000).toISOString();
|
|
28
49
|
}
|
|
29
50
|
|
|
30
51
|
/**
|
|
@@ -391,6 +412,20 @@ export function renderMemoryReport(input: {
|
|
|
391
412
|
` ${store.active} active · ${store.superseded} superseded · ${store.open} open · ${store.scopes} scopes` +
|
|
392
413
|
(store.malformed ? ` · ${store.malformed} malformed (skipped; fix the ts= field or undo)` : ""),
|
|
393
414
|
);
|
|
415
|
+
if (store.neverRetrieved !== undefined) {
|
|
416
|
+
const used = store.active - store.neverRetrieved;
|
|
417
|
+
const share = store.active ? Math.round((store.neverRetrieved / store.active) * 100) : 0;
|
|
418
|
+
// A ledger younger than the window cannot honestly call anything "never"
|
|
419
|
+
// — it has not been watching long enough. Say what it covers instead of
|
|
420
|
+
// letting day-one readers see 100% dead weight.
|
|
421
|
+
const young = ledgerIsYoung(store.ledgerSince);
|
|
422
|
+
const basis = young
|
|
423
|
+
? `, ledger only covers since ${store.ledgerSince ? store.ledgerSince.slice(0, 10) : "no lines yet"}`
|
|
424
|
+
: "";
|
|
425
|
+
out.push(
|
|
426
|
+
` retrieved ${used} rows in the last 30d; never retrieved ${store.neverRetrieved} (${share}%)${basis} — reported, not acted on`,
|
|
427
|
+
);
|
|
428
|
+
}
|
|
394
429
|
out.push("", "Terminal (CLI/TUI) users: /memory opens this as a live panel; the footer shows a one-line badge.");
|
|
395
430
|
return out.join("\n");
|
|
396
431
|
}
|
package/src/tui.tsx
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
cacheRate,
|
|
21
21
|
cacheLines,
|
|
22
22
|
contextLines,
|
|
23
|
+
ledgerIsYoung,
|
|
23
24
|
readStatus,
|
|
24
25
|
statusDir,
|
|
25
26
|
windowLines,
|
|
@@ -299,7 +300,14 @@ function MemoryPanel(props: {
|
|
|
299
300
|
<text fg={context.theme.text.base}>
|
|
300
301
|
{" " + (s()?.store.active ?? 0) + " active · " + (s()?.store.superseded ?? 0) + " superseded · " +
|
|
301
302
|
(s()?.store.open ?? 0) + " open · " + (s()?.store.scopes ?? 0) + " scopes" +
|
|
302
|
-
((s()?.store.malformed ?? 0) > 0 ? " · " + s()!.store.malformed + " malformed (skipped)" : "")
|
|
303
|
+
((s()?.store.malformed ?? 0) > 0 ? " · " + s()!.store.malformed + " malformed (skipped)" : "") +
|
|
304
|
+
((s()?.store.neverRetrieved ?? 0) > 0
|
|
305
|
+
? " · " +
|
|
306
|
+
s()!.store.neverRetrieved +
|
|
307
|
+
(ledgerIsYoung(s()!.store.ledgerSince)
|
|
308
|
+
? " never retrieved (ledger since " + (s()!.store.ledgerSince?.slice(0, 10) ?? "no lines") + ")"
|
|
309
|
+
: " never retrieved (30d)")
|
|
310
|
+
: "")}
|
|
303
311
|
</text>
|
|
304
312
|
</Show>
|
|
305
313
|
|