opencode-self-improvement 0.12.0 → 0.13.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 +32 -0
- package/package.json +1 -1
- package/src/consolidate.ts +321 -0
- package/src/hits.ts +19 -0
- package/src/index.ts +28 -0
- package/src/inject.ts +3 -1
- package/src/repokey.ts +25 -5
- package/src/schema.ts +11 -0
package/README.md
CHANGED
|
@@ -240,6 +240,38 @@ STORE
|
|
|
240
240
|
Sessions idle for an hour produce an hour-old capture; now you can see it
|
|
241
241
|
instead of guessing.
|
|
242
242
|
|
|
243
|
+
## Consolidation that has to earn its merge
|
|
244
|
+
|
|
245
|
+
Stores accumulate near-duplicates: the same fact written three times, weeks
|
|
246
|
+
apart, in slightly different words. `memory_consolidate` finds them and proposes
|
|
247
|
+
a merge — and it is built to say **no** more often than to say yes:
|
|
248
|
+
|
|
249
|
+
- **Deterministic merge.** The canonical row is the survivor's prose *verbatim*,
|
|
250
|
+
plus the absorbed rows' aliases as keywords. No model rewrites anything: a
|
|
251
|
+
rewrite cannot be diffed, audited, or proven to preserve meaning, and this
|
|
252
|
+
plugin ships no model.
|
|
253
|
+
- **Proven reads, per cluster.** Every read the use ledger recorded for that
|
|
254
|
+
cluster is replayed against the merged store. A merge is proposed only when
|
|
255
|
+
the canonical row catches at least as many of the cluster's own reads as the
|
|
256
|
+
best single member did alone. A cluster with no recorded reads is reported as
|
|
257
|
+
*unmeasured* and never merged on resemblance.
|
|
258
|
+
- **Proposals, not writes.** The tool writes nothing. It prints the exact
|
|
259
|
+
`memory_merge_review` call that resolves each proposal; resolving is
|
|
260
|
+
supersede-not-delete, so absorbed rows stay recoverable.
|
|
261
|
+
- **The most recently used member is never a loser.**
|
|
262
|
+
|
|
263
|
+
On the shipped eval dataset the pass takes 200 rows to 52 with
|
|
264
|
+
**R@3 52 → 53 and R@1 52 → 50**, and store-wide injected characters 25 945c →
|
|
265
|
+
6 933c (two queries out of 105 get a block up to 48 characters bigger, because a
|
|
266
|
+
canonical row inherits aliases and wins a slot it used to lose). That trade is
|
|
267
|
+
asserted in CI, not assumed: `test/consolidate-bench.test.ts` bounds both the
|
|
268
|
+
regression and the budget swap.
|
|
269
|
+
|
|
270
|
+
The ticket carried a HOLD pending "a month of hits data", on the reasoning that
|
|
271
|
+
consolidation is fragile and may not earn its cost. Measurement answers that
|
|
272
|
+
better than a calendar does — so the harness measures it, per cluster, on every
|
|
273
|
+
run.
|
|
274
|
+
|
|
243
275
|
## Quick start
|
|
244
276
|
|
|
245
277
|
1. Add the plugin to your Opencode config (see install below) and restart Opencode.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.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,321 @@
|
|
|
1
|
+
// Consolidation proposals (#45): episodic rows → one canonical row, proposed and
|
|
2
|
+
// measured, never silently applied.
|
|
3
|
+
//
|
|
4
|
+
// The write-gate already collapses byte-identical restatements and flags >0.9
|
|
5
|
+
// jaccard overlaps *at write time*. What it cannot do is notice the slow drift
|
|
6
|
+
// that only a store develops later: three settled rows in one scope, written
|
|
7
|
+
// weeks apart, saying nearly the same thing in slightly different words. Every
|
|
8
|
+
// one of them rides the budget, and each is reachable by a different fragment
|
|
9
|
+
// of vocabulary.
|
|
10
|
+
//
|
|
11
|
+
// The literature is blunt that this step is where memory systems break (arXiv
|
|
12
|
+
// 2603.07670: "rarely automatic… fragile and hard to validate"), and NOOA's
|
|
13
|
+
// published numbers are the reason this file refuses to be clever: their
|
|
14
|
+
// reflection records were 22% of rows but ~1% of reads, and abstracting hurt
|
|
15
|
+
// pinpoint lookup. So the rules here are:
|
|
16
|
+
//
|
|
17
|
+
// 1. DETERMINISTIC MERGE. The canonical row is the survivor's prose, verbatim,
|
|
18
|
+
// plus the aliases and distinctive vocabulary of the rows it absorbs. No
|
|
19
|
+
// model rewrites anything — a rewrite cannot be diffed, audited, or proven
|
|
20
|
+
// to preserve meaning, and this plugin ships no model.
|
|
21
|
+
// 2. PROVEN READS, per cluster. Every read the cluster has actually served is
|
|
22
|
+
// taken from the use ledger and replayed against the merged store. A merge
|
|
23
|
+
// is proposed only when the merged row catches at least as many of those
|
|
24
|
+
// reads as the best single member did. "Looks redundant" is not a reason.
|
|
25
|
+
// 3. PROPOSALS, not writes. Nothing here mutates the store. A human resolves a
|
|
26
|
+
// proposal through memory_merge_review (supersede-not-delete, recoverable).
|
|
27
|
+
// 4. The most recently used member is never a loser (#42's rule, inherited).
|
|
28
|
+
import type { Memory } from "./memory.ts";
|
|
29
|
+
import type { UseSignal } from "./hits.ts";
|
|
30
|
+
import { cmpTs, formatMemory, scoreMemories, words } from "./inject.ts";
|
|
31
|
+
|
|
32
|
+
/** Default jaccard floor for "these two rows are the same statement". */
|
|
33
|
+
export const DEFAULT_JACCARD = 0.55;
|
|
34
|
+
/** Aliases are useful up to a point; a merged row that hoards 60 words is noise. */
|
|
35
|
+
export const MAX_MERGED_KW = 12;
|
|
36
|
+
|
|
37
|
+
export interface ReadSet {
|
|
38
|
+
/** The terms a real read used, exactly as the ledger recorded them. */
|
|
39
|
+
terms: string[];
|
|
40
|
+
/** Row ids that read credited. */
|
|
41
|
+
rows: string[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ClusterOptions {
|
|
45
|
+
jaccard?: number;
|
|
46
|
+
/** Smallest cluster worth proposing (2 = a pair). */
|
|
47
|
+
minMembers?: number;
|
|
48
|
+
/** Ceiling on cluster size: 6 rows merged is a rewrite, not a merge. */
|
|
49
|
+
maxMembers?: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function tokens(text: string): string[] {
|
|
53
|
+
return text.toLowerCase().split(/[^a-z0-9_.]+/).filter(Boolean);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function jaccard(a: Set<string>, b: Set<string>): number {
|
|
57
|
+
let inter = 0;
|
|
58
|
+
for (const t of a) if (b.has(t)) inter++;
|
|
59
|
+
const union = a.size + b.size - inter;
|
|
60
|
+
return union === 0 ? 0 : inter / union;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Candidate clusters of settled, same-scope, same-type rows that say the same
|
|
65
|
+
* thing. Grouping is transitive on the jaccard edge (union-find), so a chain of
|
|
66
|
+
* "almost the same" rows becomes one cluster instead of N/2 arbitrary pairs.
|
|
67
|
+
*
|
|
68
|
+
* Open rows are excluded on purpose: an open thread is a live plan, not episodic
|
|
69
|
+
* material to compress, and collapsing it would destroy the frontier the panel
|
|
70
|
+
* is showing the user.
|
|
71
|
+
*/
|
|
72
|
+
export function clustersFor(rows: Memory[], opts: ClusterOptions = {}): Memory[][] {
|
|
73
|
+
const min = opts.jaccard ?? DEFAULT_JACCARD;
|
|
74
|
+
const minMembers = opts.minMembers ?? 2;
|
|
75
|
+
const maxMembers = opts.maxMembers ?? 6;
|
|
76
|
+
const pool = rows
|
|
77
|
+
.filter((m) => !m.superseded_by && m.status !== "open" && m.content.trim())
|
|
78
|
+
.sort((a, b) => cmpTs(a.ts, b.ts));
|
|
79
|
+
|
|
80
|
+
const parent = pool.map((_, i) => i);
|
|
81
|
+
const find = (i: number): number => {
|
|
82
|
+
while (parent[i] !== i) {
|
|
83
|
+
parent[i] = parent[parent[i]!]!;
|
|
84
|
+
i = parent[i]!;
|
|
85
|
+
}
|
|
86
|
+
return i;
|
|
87
|
+
};
|
|
88
|
+
const union = (a: number, b: number) => {
|
|
89
|
+
const ra = find(a);
|
|
90
|
+
const rb = find(b);
|
|
91
|
+
if (ra !== rb) parent[rb] = ra;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const toks = pool.map((m) => new Set(tokens(m.content)));
|
|
95
|
+
for (let i = 0; i < pool.length; i++) {
|
|
96
|
+
for (let j = i + 1; j < pool.length; j++) {
|
|
97
|
+
const a = pool[i]!;
|
|
98
|
+
const b = pool[j]!;
|
|
99
|
+
if (a.scope !== b.scope || a.type !== b.type) continue;
|
|
100
|
+
if (jaccard(toks[i]!, toks[j]!) >= min) union(i, j);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const groups = new Map<number, Memory[]>();
|
|
105
|
+
pool.forEach((m, i) => {
|
|
106
|
+
const root = find(i);
|
|
107
|
+
const g = groups.get(root) ?? [];
|
|
108
|
+
g.push(m);
|
|
109
|
+
groups.set(root, g);
|
|
110
|
+
});
|
|
111
|
+
return [...groups.values()]
|
|
112
|
+
.filter((g) => g.length >= minMembers && g.length <= maxMembers)
|
|
113
|
+
.sort((a, b) => cmpTs(a[0]!.ts, b[0]!.ts));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The canonical row of a cluster: the most recently used member, falling back to
|
|
118
|
+
* the newest row when the ledger knows nothing. Recency in the boost is not
|
|
119
|
+
* recency in the ledger — a row that retrieval has actually been landing on is
|
|
120
|
+
* the one worth keeping, and this is #42's rule applied to merges.
|
|
121
|
+
*/
|
|
122
|
+
export function survivorFor(cluster: Memory[], use?: Map<string, UseSignal>): Memory {
|
|
123
|
+
return [...cluster].sort((a, b) => {
|
|
124
|
+
const la = use?.get(a.ts)?.last ?? "";
|
|
125
|
+
const lb = use?.get(b.ts)?.last ?? "";
|
|
126
|
+
if (la !== lb) return la < lb ? 1 : -1;
|
|
127
|
+
return cmpTs(b.ts, a.ts);
|
|
128
|
+
})[0]!;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export interface MergePlan {
|
|
132
|
+
id: string;
|
|
133
|
+
scope: string;
|
|
134
|
+
type: string;
|
|
135
|
+
survivor: Memory;
|
|
136
|
+
losers: Memory[];
|
|
137
|
+
/** What the canonical row would look like. */
|
|
138
|
+
merged: Memory;
|
|
139
|
+
/** Reads the cluster served, taken from the ledger. */
|
|
140
|
+
reads: ReadSet[];
|
|
141
|
+
readsBefore: number;
|
|
142
|
+
readsAfter: number;
|
|
143
|
+
bestMemberBefore: number;
|
|
144
|
+
bytesBefore: number;
|
|
145
|
+
bytesAfter: number;
|
|
146
|
+
accepted: boolean;
|
|
147
|
+
reasons: string[];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Distinctive vocabulary of the absorbed rows: what the survivor does not say. */
|
|
151
|
+
function inheritedKw(cluster: Memory[], survivor: Memory): string[] {
|
|
152
|
+
const have = new Set(words(`${survivor.content} ${(survivor.kw ?? []).join(" ")}`));
|
|
153
|
+
const out = [...(survivor.kw ?? [])];
|
|
154
|
+
for (const m of cluster) {
|
|
155
|
+
if (m.ts === survivor.ts) continue;
|
|
156
|
+
for (const k of m.kw ?? []) if (!out.includes(k)) out.push(k);
|
|
157
|
+
// Only distinctive words the absorbed row was FOUND by, in practice: its
|
|
158
|
+
// own vocabulary minus what the survivor already carries.
|
|
159
|
+
for (const w of words(m.content)) {
|
|
160
|
+
if (!have.has(w) && !out.includes(w)) out.push(w);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return out.slice(0, MAX_MERGED_KW);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function buildMerged(cluster: Memory[], survivor: Memory): Memory {
|
|
167
|
+
const kw = inheritedKw(cluster, survivor);
|
|
168
|
+
return {
|
|
169
|
+
...survivor,
|
|
170
|
+
kw: kw.length ? kw : undefined,
|
|
171
|
+
tags: [...new Set(["consolidated", ...(survivor.tags ?? []), ...cluster.flatMap((m) => m.tags ?? [])])].slice(
|
|
172
|
+
0,
|
|
173
|
+
12,
|
|
174
|
+
),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Replay the cluster's real reads against a store where the cluster has been
|
|
180
|
+
* replaced by the merged row. `rows` is the whole active store; the function
|
|
181
|
+
* returns how many of those reads still land on the cluster.
|
|
182
|
+
*/
|
|
183
|
+
// Cluster bookkeeping uses OBJECT identity, not `ts`. The ledger keys on ts
|
|
184
|
+
// (correctly — it is the row id in the store), but nothing here may assume two
|
|
185
|
+
// rows cannot share one timestamp: the eval store does exactly that, and a
|
|
186
|
+
// ts-keyed filter would silently absorb an entire cluster into its survivor.
|
|
187
|
+
function replayReads(rows: Memory[], cluster: Memory[], replacement: Memory | null, reads: ReadSet[]): number {
|
|
188
|
+
const inCluster = new Set(cluster);
|
|
189
|
+
const store = replacement ? [...rows.filter((m) => !inCluster.has(m)), replacement] : rows;
|
|
190
|
+
let hits = 0;
|
|
191
|
+
for (const r of reads) {
|
|
192
|
+
const query = r.terms.join(" ");
|
|
193
|
+
if (!query.trim()) continue;
|
|
194
|
+
const top = scoreMemories(query, store, 3);
|
|
195
|
+
const landed = top.some((m) => (replacement ? m === replacement : inCluster.has(m)));
|
|
196
|
+
if (landed) hits++;
|
|
197
|
+
}
|
|
198
|
+
return hits;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Reads the ledger says this cluster served (any member credited). */
|
|
202
|
+
export function readsFor(cluster: Memory[], allReads: ReadSet[]): ReadSet[] {
|
|
203
|
+
const ids = new Set(cluster.map((m) => m.ts));
|
|
204
|
+
return allReads.filter((r) => r.rows.some((id) => ids.has(id)) && r.terms.length > 0);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* One cluster → one measured proposal. `rows` is the full active store; `use`
|
|
209
|
+
* and `reads` come from the use ledger. A cluster with no recorded reads is
|
|
210
|
+
* reported as unmeasurable rather than merged on vibes.
|
|
211
|
+
*/
|
|
212
|
+
export function proposeCluster(
|
|
213
|
+
rows: Memory[],
|
|
214
|
+
cluster: Memory[],
|
|
215
|
+
use: Map<string, UseSignal>,
|
|
216
|
+
allReads: ReadSet[],
|
|
217
|
+
): MergePlan {
|
|
218
|
+
const survivor = survivorFor(cluster, use);
|
|
219
|
+
const losers = cluster.filter((m) => m !== survivor);
|
|
220
|
+
const merged = buildMerged(cluster, survivor);
|
|
221
|
+
const reads = readsFor(cluster, allReads);
|
|
222
|
+
|
|
223
|
+
// The bar the ticket sets: the merged row must catch at least as many of the
|
|
224
|
+
// cluster's own reads as the BEST single member did on its own.
|
|
225
|
+
const members = cluster.map((m) => replayReads(rows, cluster, m, reads));
|
|
226
|
+
const bestMemberBefore = members.length ? Math.max(...members) : 0;
|
|
227
|
+
const readsBefore = replayReads(rows, cluster, null, reads);
|
|
228
|
+
const readsAfter = replayReads(rows, cluster, merged, reads);
|
|
229
|
+
|
|
230
|
+
const bytesBefore = cluster.reduce((n, m) => n + formatMemory(m).length, 0);
|
|
231
|
+
const bytesAfter = formatMemory(merged).length;
|
|
232
|
+
|
|
233
|
+
const reasons: string[] = [];
|
|
234
|
+
if (!reads.length) reasons.push("unmeasured: the ledger has no read for any member of this cluster");
|
|
235
|
+
else if (readsAfter < bestMemberBefore)
|
|
236
|
+
reasons.push(
|
|
237
|
+
`reads would drop: merged row catches ${readsAfter} of ${reads.length}, the best member alone caught ${bestMemberBefore}`,
|
|
238
|
+
);
|
|
239
|
+
if (bytesAfter > bytesBefore) reasons.push("merged row is larger than the rows it absorbs");
|
|
240
|
+
|
|
241
|
+
return {
|
|
242
|
+
id: `cl-${cluster
|
|
243
|
+
.map((m) => m.ts)
|
|
244
|
+
.sort()[0]!
|
|
245
|
+
.replace(/[^0-9]/g, "")
|
|
246
|
+
.slice(-9)}`,
|
|
247
|
+
scope: survivor.scope,
|
|
248
|
+
type: survivor.type,
|
|
249
|
+
survivor,
|
|
250
|
+
losers,
|
|
251
|
+
merged,
|
|
252
|
+
reads,
|
|
253
|
+
readsBefore,
|
|
254
|
+
readsAfter,
|
|
255
|
+
bestMemberBefore,
|
|
256
|
+
bytesBefore,
|
|
257
|
+
bytesAfter,
|
|
258
|
+
accepted: reasons.length === 0,
|
|
259
|
+
reasons,
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export interface ProposalReport {
|
|
264
|
+
plans: MergePlan[];
|
|
265
|
+
rowsBefore: number;
|
|
266
|
+
rowsAfter: number;
|
|
267
|
+
injectedBefore: number;
|
|
268
|
+
injectedAfter: number;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* The pass: cluster, measure, keep only proposals that prove the reads survive.
|
|
273
|
+
* Dry by construction — the caller decides whether anything is applied.
|
|
274
|
+
*/
|
|
275
|
+
export function proposeConsolidations(
|
|
276
|
+
rows: Memory[],
|
|
277
|
+
use: Map<string, UseSignal>,
|
|
278
|
+
reads: ReadSet[],
|
|
279
|
+
opts: ClusterOptions = {},
|
|
280
|
+
): ProposalReport {
|
|
281
|
+
const plans = clustersFor(rows, opts)
|
|
282
|
+
.map((c) => proposeCluster(rows, c, use, reads))
|
|
283
|
+
.filter((p) => p.accepted);
|
|
284
|
+
const absorbed = new Set<Memory>(plans.flatMap((p) => p.losers));
|
|
285
|
+
const injected = (list: Memory[]) => list.reduce((n, m) => n + formatMemory(m).length, 0);
|
|
286
|
+
return {
|
|
287
|
+
plans,
|
|
288
|
+
rowsBefore: rows.length,
|
|
289
|
+
rowsAfter: rows.length - absorbed.size,
|
|
290
|
+
injectedBefore: injected(rows),
|
|
291
|
+
// Absorbed rows leave the budget; canonical rows keep theirs (kw never renders).
|
|
292
|
+
injectedAfter: injected(rows.filter((m) => !absorbed.has(m))),
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Human-readable proposal list. Ends with the exact command to resolve one. */
|
|
297
|
+
export function renderProposals(report: ProposalReport): string {
|
|
298
|
+
const out: string[] = ["CONSOLIDATION PROPOSALS — nothing was written", ""];
|
|
299
|
+
if (!report.plans.length) {
|
|
300
|
+
out.push(" none — no cluster proved it could hold its reads.");
|
|
301
|
+
return out.join("\n");
|
|
302
|
+
}
|
|
303
|
+
for (const p of report.plans) {
|
|
304
|
+
out.push(
|
|
305
|
+
`${p.id} ${p.type}/${p.scope} ${p.losers.length + 1} rows → 1`,
|
|
306
|
+
` keep ${p.survivor.ts}`,
|
|
307
|
+
` ${p.survivor.content.slice(0, 160)}`,
|
|
308
|
+
...p.losers.map((l) => ` absorb ${l.ts} ${l.content.slice(0, 120)}`),
|
|
309
|
+
` reads ${p.reads.length} logged · best member alone ${p.bestMemberBefore} · merged ${p.readsAfter}`,
|
|
310
|
+
` budget ${p.bytesBefore}c → ${p.bytesAfter}c for this cluster`,
|
|
311
|
+
` resolve: memory_merge_review(loser="${p.losers[0]!.ts}", survivor="${p.survivor.ts}", reason="consolidate ${p.id}")`,
|
|
312
|
+
"",
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
out.push(
|
|
316
|
+
`STORE ${report.rowsBefore} rows → ${report.rowsAfter} if every proposal is resolved · ` +
|
|
317
|
+
`injected ${report.injectedBefore}c → ${report.injectedAfter}c`,
|
|
318
|
+
);
|
|
319
|
+
out.push("Resolving is supersede-not-delete: absorbed rows stay recoverable via memory_undo.");
|
|
320
|
+
return out.join("\n");
|
|
321
|
+
}
|
package/src/hits.ts
CHANGED
|
@@ -20,6 +20,7 @@ import { appendLog, bracketList, formatLine, parseLine, readLines, writeAtomic }
|
|
|
20
20
|
import type { UseSignals } from "./inject.ts";
|
|
21
21
|
import { withStoreLock, LOCK_WRITE } from "./lock.ts";
|
|
22
22
|
import type { Memory } from "./memory.ts";
|
|
23
|
+
import type { ReadSet } from "./consolidate.ts";
|
|
23
24
|
|
|
24
25
|
export type HitSource = "inject" | "pull" | "recall";
|
|
25
26
|
|
|
@@ -170,6 +171,24 @@ function parseList(value: string): string[] {
|
|
|
170
171
|
.filter(Boolean);
|
|
171
172
|
}
|
|
172
173
|
|
|
174
|
+
/**
|
|
175
|
+
* Every read the ledger recorded, in file order: the terms used and the rows it
|
|
176
|
+
* credited. This is the corpus consolidation (#45) replays — "would this merge
|
|
177
|
+
* have lost a read that actually happened?" is only answerable against real
|
|
178
|
+
* reads, and a per-row aggregate has already thrown the grouping away.
|
|
179
|
+
*/
|
|
180
|
+
export async function readReads(): Promise<ReadSet[]> {
|
|
181
|
+
const out: ReadSet[] = [];
|
|
182
|
+
for (const line of await readLines(hitsFile())) {
|
|
183
|
+
const f = parseLine(line);
|
|
184
|
+
if (!f || f.ev !== "memory_used") continue;
|
|
185
|
+
const rows = typeof f.mem === "string" ? parseList(f.mem) : [];
|
|
186
|
+
const terms = typeof f.terms === "string" ? parseList(f.terms) : [];
|
|
187
|
+
if (rows.length) out.push({ terms, rows });
|
|
188
|
+
}
|
|
189
|
+
return out;
|
|
190
|
+
}
|
|
191
|
+
|
|
173
192
|
/** Rows the ledger has NEVER seen used, plus the honest since-qualifier. */
|
|
174
193
|
export function neverRetrieved(rows: Memory[], ledger: UseLedger, days = 30): Memory[] {
|
|
175
194
|
const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
|
package/src/index.ts
CHANGED
|
@@ -31,6 +31,8 @@ import { exportMemories, findStaleOpen, importMemories } from "./portable.ts";
|
|
|
31
31
|
import { listSnapshots, restoreSnapshot } from "./undo.ts";
|
|
32
32
|
import { SESSION_CAP, SessionLru } from "./sessions.ts";
|
|
33
33
|
import { record, recordCaptureLag } from "./evidence.ts";
|
|
34
|
+
import { proposeConsolidations, renderProposals } from "./consolidate.ts";
|
|
35
|
+
import { readReads } from "./hits.ts";
|
|
34
36
|
import {
|
|
35
37
|
capToBudget,
|
|
36
38
|
compactionAnchor,
|
|
@@ -90,6 +92,7 @@ import {
|
|
|
90
92
|
ForgetArgs,
|
|
91
93
|
ImportArgs,
|
|
92
94
|
InitArgs,
|
|
95
|
+
ConsolidateArgs,
|
|
93
96
|
MergeReviewArgs,
|
|
94
97
|
RecallArgs,
|
|
95
98
|
RememberArgs,
|
|
@@ -332,6 +335,31 @@ const impl = {
|
|
|
332
335
|
},
|
|
333
336
|
}));
|
|
334
337
|
|
|
338
|
+
editor.add(validated(ConsolidateArgs, {
|
|
339
|
+
name: "memory_consolidate",
|
|
340
|
+
description:
|
|
341
|
+
"Propose consolidations of near-duplicate settled rows — read-only, nothing is written. Clusters same-scope same-type rows by jaccard, picks the most recently used member as canonical (#42's rule: the row retrieval keeps landing on), and proposes it ONLY when replaying the cluster's own logged reads proves the merged row catches at least as many reads as the best single member did. A cluster with no recorded reads is reported as unmeasured, never merged on resemblance. Resolve a proposal with memory_merge_review; absorbed rows stay recoverable. The merge is deterministic — the canonical row is the survivor's prose plus the absorbed rows' aliases — because this plugin ships no model and a rewritten row cannot be diffed or audited.",
|
|
342
|
+
options: direct,
|
|
343
|
+
async execute(args): Promise<{ content: string }> {
|
|
344
|
+
const all = (await loadAll()).filter(isActive).filter(isVisibleHere);
|
|
345
|
+
const rows = args.scope ? all.filter((m) => m.scope === args.scope) : all;
|
|
346
|
+
const ledger = await readLedger();
|
|
347
|
+
const use = ledger.byRow;
|
|
348
|
+
const reads = await readReads();
|
|
349
|
+
const report = proposeConsolidations(rows, use, reads, {
|
|
350
|
+
...(args.jaccard !== undefined ? { jaccard: args.jaccard } : {}),
|
|
351
|
+
});
|
|
352
|
+
const shown = report.plans.slice(0, args.limit ?? 10);
|
|
353
|
+
const out = renderProposals({ ...report, plans: shown });
|
|
354
|
+
await record(
|
|
355
|
+
"consolidate_propose",
|
|
356
|
+
{ clusters: shown.length, rows: report.rowsBefore, would_drop: report.rowsBefore - report.rowsAfter },
|
|
357
|
+
false,
|
|
358
|
+
);
|
|
359
|
+
return { content: out };
|
|
360
|
+
},
|
|
361
|
+
}));
|
|
362
|
+
|
|
335
363
|
editor.add(validated(InitArgs, {
|
|
336
364
|
name: "memory_init",
|
|
337
365
|
description:
|
package/src/inject.ts
CHANGED
|
@@ -208,7 +208,9 @@ function useBoost(a: Memory | undefined, use?: UseSignals): number {
|
|
|
208
208
|
// Date.parse only while the FORMAT agrees: a legacy second-precision stamp
|
|
209
209
|
// ("…:01Z") and a millisecond stamp ("…:01.000Z") for the same instant order
|
|
210
210
|
// wrong as strings, which would silently mis-rank the recency tie-break.
|
|
211
|
-
|
|
211
|
+
// Exported for consolidate.ts — cluster ordering must not disagree with the
|
|
212
|
+
// ranking it is merging.
|
|
213
|
+
export function cmpTs(a: string, b: string): number {
|
|
212
214
|
const na = Date.parse(a);
|
|
213
215
|
const nb = Date.parse(b);
|
|
214
216
|
if (!Number.isNaN(na) && !Number.isNaN(nb)) return na < nb ? -1 : na > nb ? 1 : 0;
|
package/src/repokey.ts
CHANGED
|
@@ -7,13 +7,16 @@
|
|
|
7
7
|
// Two keys, both cheap, with opposite failure modes:
|
|
8
8
|
// key — sha1 of the normalized origin URL: survives re-clone, moves, and
|
|
9
9
|
// export/import to another machine. Absent when the repo has no
|
|
10
|
-
// origin (fresh or remote-less)
|
|
11
|
-
//
|
|
12
|
-
//
|
|
10
|
+
// origin (fresh or remote-less): sha1 of the NORMALIZED resolved
|
|
11
|
+
// path instead, so repo= is always a bare token — a raw path with
|
|
12
|
+
// a space gets logfmt-quoted, which breaks naive field extraction
|
|
13
|
+
// and can't be hash-compared (#92). path stays the human-readable
|
|
14
|
+
// secondary, so rows stamped before the hash keep matching.
|
|
13
15
|
// Rows carry no stamp when their writer had no scope (viewer process,
|
|
14
16
|
// tests) and legacy rows predate the field: both read as GLOBAL — visible
|
|
15
17
|
// everywhere — which keeps every upgrade non-breaking.
|
|
16
18
|
import { createHash } from "node:crypto";
|
|
19
|
+
import { realpathSync } from "node:fs";
|
|
17
20
|
|
|
18
21
|
export interface RepoScope {
|
|
19
22
|
key: string;
|
|
@@ -56,14 +59,31 @@ function git(args: string[], cwd: string): string | null {
|
|
|
56
59
|
}
|
|
57
60
|
}
|
|
58
61
|
|
|
62
|
+
// Normalize a directory for hashing: symlinks, junctions, and Windows 8.3
|
|
63
|
+
// aliases collapse to the real path (realpath), separators unify to "/",
|
|
64
|
+
// a trailing separator disappears, and case folds ONLY on the
|
|
65
|
+
// case-insensitive filesystems (win32/darwin) where two spellings are the
|
|
66
|
+
// same directory — Linux folds nothing, there "Foo" and "foo" are two dirs.
|
|
67
|
+
export function normalizeDirPath(p: string): string {
|
|
68
|
+
let r = p;
|
|
69
|
+
try {
|
|
70
|
+
r = realpathSync(r);
|
|
71
|
+
} catch {
|
|
72
|
+
// deleted/unreadable mid-resolve: hash the given spelling rather than throw
|
|
73
|
+
}
|
|
74
|
+
r = r.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
75
|
+
if (process.platform === "win32" || process.platform === "darwin") r = r.toLowerCase();
|
|
76
|
+
return r || "/";
|
|
77
|
+
}
|
|
78
|
+
|
|
59
79
|
// Resolve the current repo from any start dir (never throws; a non-git dir
|
|
60
|
-
// simply scopes by its own path).
|
|
80
|
+
// simply scopes by the hash of its own normalized path).
|
|
61
81
|
export function resolveRepo(startDir: string): RepoScope {
|
|
62
82
|
const path = git(["git", "rev-parse", "--show-toplevel"], startDir) ?? startDir;
|
|
63
83
|
const remote = git(["git", "remote", "get-url", "origin"], path);
|
|
64
84
|
const key = remote
|
|
65
85
|
? createHash("sha1").update(normalizeRemote(remote)).digest("hex").slice(0, 12)
|
|
66
|
-
: path;
|
|
86
|
+
: createHash("sha1").update(normalizeDirPath(path)).digest("hex").slice(0, 12);
|
|
67
87
|
return { key, path };
|
|
68
88
|
}
|
|
69
89
|
|
package/src/schema.ts
CHANGED
|
@@ -132,6 +132,17 @@ export const MergeReviewArgs = z.object({
|
|
|
132
132
|
reason: z.string().describe("Why the survivor is canonical over the loser (written to evidence)"),
|
|
133
133
|
});
|
|
134
134
|
|
|
135
|
+
export const ConsolidateArgs = z.object({
|
|
136
|
+
scope: z.string().describe("Only consider rows in this scope").optional(),
|
|
137
|
+
jaccard: z
|
|
138
|
+
.number()
|
|
139
|
+
.describe("Similarity floor for 'same statement' (default 0.55)")
|
|
140
|
+
.min(0.2)
|
|
141
|
+
.max(0.95)
|
|
142
|
+
.optional(),
|
|
143
|
+
limit: z.number().describe("Maximum proposals to report (default 10)").min(1).max(50).optional(),
|
|
144
|
+
});
|
|
145
|
+
|
|
135
146
|
export const ExportArgs = z.object({
|
|
136
147
|
scope: z.string().describe("Only export memories in this exact scope").optional(),
|
|
137
148
|
file: z.string().describe("Destination path (default: <memory-root>/exports/)").optional(),
|