opencode-self-improvement 0.10.0 → 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/package.json +1 -1
- package/src/config.ts +4 -0
- package/src/hits.ts +213 -0
- package/src/index.ts +33 -4
- package/src/inject.ts +68 -11
- package/src/memory.ts +4 -1
- package/src/status.ts +35 -0
- package/src/tui.tsx +9 -1
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/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/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,
|
|
@@ -368,6 +372,7 @@ const impl = {
|
|
|
368
372
|
turn: firstFrontierTap(cur.sid)?.turn,
|
|
369
373
|
});
|
|
370
374
|
}
|
|
375
|
+
if (args.query) await noteHits("recall", getCurrent().sid, limited, args.query);
|
|
371
376
|
return { content: `Found ${results.length} (${total} total)\n\n${limited.map(formatMemory).join("\n")}` };
|
|
372
377
|
},
|
|
373
378
|
}));
|
|
@@ -648,13 +653,18 @@ const impl = {
|
|
|
648
653
|
const status = sid === "?" ? null : await buildPayload(sid);
|
|
649
654
|
const all = await loadAll();
|
|
650
655
|
const act = all.filter(isActive);
|
|
651
|
-
const store = {
|
|
656
|
+
const store: StoreCounts = {
|
|
652
657
|
active: act.length,
|
|
653
658
|
superseded: all.length - act.length,
|
|
654
659
|
open: act.filter((m) => m.status === "open").length,
|
|
655
660
|
scopes: new Set(act.map((m) => m.scope)).size,
|
|
656
661
|
malformed: malformedCount(),
|
|
657
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;
|
|
658
668
|
return {
|
|
659
669
|
content: renderMemoryReport({ status, store, blocked: await blockedRecent(6) }),
|
|
660
670
|
};
|
|
@@ -709,6 +719,7 @@ const impl = {
|
|
|
709
719
|
if (!ep) return null;
|
|
710
720
|
const all = await loadAll();
|
|
711
721
|
const act = all.filter(isActive);
|
|
722
|
+
const led = await readLedger();
|
|
712
723
|
return {
|
|
713
724
|
at: ep.at,
|
|
714
725
|
sessionID: sid,
|
|
@@ -723,6 +734,8 @@ const impl = {
|
|
|
723
734
|
open: act.filter((m) => m.status === "open").length,
|
|
724
735
|
scopes: new Set(act.map((m) => m.scope)).size,
|
|
725
736
|
malformed: malformedCount(),
|
|
737
|
+
neverRetrieved: neverRetrieved(act, led).length,
|
|
738
|
+
ledgerSince: led.since,
|
|
726
739
|
},
|
|
727
740
|
stats: statsFor(sid),
|
|
728
741
|
measured: measuredTurns.get(sid) ?? null,
|
|
@@ -738,18 +751,33 @@ const impl = {
|
|
|
738
751
|
// loop cannot ride one more request waiting for another user prompt.
|
|
739
752
|
const injectableRows = async (): Promise<Memory[]> =>
|
|
740
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
|
+
};
|
|
741
764
|
const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
|
|
742
765
|
if (!latestPrompt.has(sid)) return;
|
|
743
766
|
const mems = rows ?? await injectableRows();
|
|
744
767
|
const version = await storeVersion(mems);
|
|
745
768
|
const cached = epoch.get(sid);
|
|
746
769
|
if (cached?.version === version) return;
|
|
747
|
-
const
|
|
770
|
+
const prompt = latestPrompt.get(sid) ?? "";
|
|
771
|
+
const sel = await selectRelevant(prompt, 5, mems, await useSignals()); // widen candidate pool
|
|
748
772
|
const block = sel.block ? capToBudget(sel.block, budget) : "";
|
|
749
773
|
// Refs the ACTUALLY-injected rows assert (paths + commands), the join key
|
|
750
774
|
// for attribution. Derived from the budget-surviving rows, not the wider
|
|
751
775
|
// candidate pool — crediting paths the model never saw would overclaim.
|
|
752
|
-
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);
|
|
753
781
|
const at = new Date().toISOString();
|
|
754
782
|
const reason: "first" | "store_changed" = cached ? "store_changed" : "first";
|
|
755
783
|
epoch.set(sid, { version, block, at, reason, refs });
|
|
@@ -800,7 +828,8 @@ const impl = {
|
|
|
800
828
|
setCurrent(input);
|
|
801
829
|
const out = { output: resultText(event?.result), metadata: resultMeta(event?.result) };
|
|
802
830
|
await afterTool(input, out);
|
|
803
|
-
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));
|
|
804
833
|
// Write a contextual-pull append back when the tool result is text we own.
|
|
805
834
|
if (event?.result && typeof event.result === "object" && typeof event.result.content === "string") {
|
|
806
835
|
const text = resultText(event.result);
|
package/src/inject.ts
CHANGED
|
@@ -104,9 +104,10 @@ const LONG_QUERY_TOKENS = 3;
|
|
|
104
104
|
// piles of common ones — the same idf form the bench's BM25 row uses).
|
|
105
105
|
// Ties break deliberately, in this order: open threads first (a pinned frontier
|
|
106
106
|
// row beats an equal-scoring settled one — that is what the frontier is for),
|
|
107
|
-
// then the
|
|
108
|
-
//
|
|
109
|
-
//
|
|
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).
|
|
110
111
|
// The haystack is `scope + type + content + kw`, where `kw` are the
|
|
111
112
|
// author-supplied aliases indexed at write time (#40 item 3, the vocabulary
|
|
112
113
|
// bridge for the bench's strict-paraphrase wall). Keywords are indexed, never
|
|
@@ -119,7 +120,12 @@ const LONG_QUERY_TOKENS = 3;
|
|
|
119
120
|
// loadAll() result must not be the one place a retired memory leaks back into
|
|
120
121
|
// an injected block (#43 item 1: forbidden hits). The drop also keeps a
|
|
121
122
|
// retired row from diluting the document frequencies the ranking depends on.
|
|
122
|
-
export function scoreMemories(
|
|
123
|
+
export function scoreMemories(
|
|
124
|
+
term: string,
|
|
125
|
+
mems: Memory[],
|
|
126
|
+
limit: number,
|
|
127
|
+
use?: UseSignals,
|
|
128
|
+
): Memory[] {
|
|
123
129
|
const live = mems.filter((m) => !m.superseded_by);
|
|
124
130
|
const query = new Set(words(term).filter((t) => !QUERY_STOPWORDS.has(t)));
|
|
125
131
|
if (!query.size) return [];
|
|
@@ -141,7 +147,14 @@ export function scoreMemories(term: string, mems: Memory[], limit: number): Memo
|
|
|
141
147
|
return { m, shared, score };
|
|
142
148
|
})
|
|
143
149
|
.filter((s) => s.shared >= needShared)
|
|
144
|
-
.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
|
+
)
|
|
145
158
|
.slice(0, limit)
|
|
146
159
|
.map((s) => s.m);
|
|
147
160
|
}
|
|
@@ -152,6 +165,44 @@ export function haystack(m: Memory): string {
|
|
|
152
165
|
return `${m.scope} ${m.type} ${m.content}${m.kw?.length ? ` ${m.kw.join(" ")}` : ""}`;
|
|
153
166
|
}
|
|
154
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
|
+
|
|
155
206
|
// Numeric compare, with the string compare kept as fallback for non-dates
|
|
156
207
|
// (the ledger hands "" when a row was never used). ISO strings agree with
|
|
157
208
|
// Date.parse only while the FORMAT agrees: a legacy second-precision stamp
|
|
@@ -281,12 +332,13 @@ export async function selectRelevant(
|
|
|
281
332
|
message: string,
|
|
282
333
|
limit = 3,
|
|
283
334
|
rows?: Memory[],
|
|
335
|
+
use?: UseSignals,
|
|
284
336
|
): Promise<{ block: string; selected: Memory[] }> {
|
|
285
337
|
const text = message.trim();
|
|
286
338
|
if (!text) return { block: "", selected: [] };
|
|
287
339
|
// Repo-scoped: model-facing reads see this repo + global rows.
|
|
288
340
|
const mems = rows ?? visibleHere((await loadAll()).filter(isActive));
|
|
289
|
-
const top = scoreMemories(text, mems, limit);
|
|
341
|
+
const top = scoreMemories(text, mems, limit, use);
|
|
290
342
|
if (!top.length) return { block: "", selected: [] };
|
|
291
343
|
return {
|
|
292
344
|
block: `## Relevant durable memory${FRAME}\n${top.map(formatMemory).join("\n")}`,
|
|
@@ -384,18 +436,23 @@ export async function contextualPull(
|
|
|
384
436
|
input: PullInput,
|
|
385
437
|
output: PullOutput,
|
|
386
438
|
budget = injectBudget(),
|
|
387
|
-
|
|
439
|
+
use?: UseSignals,
|
|
440
|
+
): Promise<Memory[]> {
|
|
388
441
|
const tool = typeof input.tool === "string" ? input.tool : "";
|
|
389
|
-
if (!["grep", "glob", "read"].includes(tool)) return;
|
|
442
|
+
if (!["grep", "glob", "read"].includes(tool)) return [];
|
|
390
443
|
const term = argText(input.args);
|
|
391
|
-
if (!term) return;
|
|
444
|
+
if (!term) return [];
|
|
392
445
|
// Repo-scoped: model-facing reads see this repo + global rows.
|
|
393
446
|
const mems = visibleHere((await loadAll()).filter(isActive));
|
|
394
|
-
const top = scoreMemories(term, mems, 3);
|
|
395
|
-
if (!top.length) return;
|
|
447
|
+
const top = scoreMemories(term, mems, 3, use);
|
|
448
|
+
if (!top.length) return [];
|
|
396
449
|
// Held to the injection budget too: three long rows were ~12 KB per call.
|
|
397
450
|
const block = capToBudget(`## Related durable memory (pull)${FRAME}\n${top.map(formatMemory).join("\n")}`, budget);
|
|
398
451
|
if (block && typeof output.output === "string") {
|
|
399
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);
|
|
400
456
|
}
|
|
457
|
+
return [];
|
|
401
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";
|
|
@@ -87,6 +87,9 @@ const RESERVED = new Set([
|
|
|
87
87
|
"deleted.logfmt",
|
|
88
88
|
"canonical.logfmt",
|
|
89
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,
|
|
90
93
|
]);
|
|
91
94
|
|
|
92
95
|
// Row identity is `ts`: supersede chains, the blocklist, undo matching, and
|
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
|
|