open-memex 0.10.0-alpha.3 → 0.10.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.
@@ -1,376 +1,399 @@
1
- // D78 curate fixture - measurement first.
2
- //
3
- // Usage: node --experimental-strip-types scripts/curate-eval.ts
4
- //
5
- // Baseline (2026-11-13, 0.10.0-alpha.2, no curation): lint 9 findings
6
- // (orphan 7, dangling 1, stale 1); deterministic candidates: exact-dup 1,
7
- // empty 1, title 2; near-dup report (not auto) 1.
8
- //
9
- // Seeds two scratch projects with the same corpus, measures the deterministic
10
- // curation candidates in the first, then runs `submit` in the second and reads
11
- // the curation summary it prints. The baseline half contains no product logic;
12
- // it uses the same contentHash/similarity the write path already uses, so the
13
- // numbers are comparable before and after D78's auto-apply tier lands.
14
- //
15
- // Isolated: temp HOME + OPEN_MEMEX_HOME + temp git repo. Touches nothing real.
16
-
17
- import { execFileSync } from "node:child_process";
18
- import fs from "node:fs";
19
- import os from "node:os";
20
- import path from "node:path";
21
- import { fileURLToPath } from "node:url";
22
- import { contentHash, similarity, NEAR_DUP_THRESHOLD } from "../src/store/lifecycle.ts";
23
-
24
- const REPO = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
25
- const CLI = path.join(REPO, "dist", "cli.js");
26
- const T = fs.mkdtempSync(path.join(os.tmpdir(), "om-curate-"));
27
- const HOME = path.join(T, "home");
28
- const DATA = path.join(T, "data");
29
- fs.mkdirSync(HOME, { recursive: true });
30
- const ENV: NodeJS.ProcessEnv = {
31
- ...process.env,
32
- HOME,
33
- USERPROFILE: HOME,
34
- OPEN_MEMEX_HOME: DATA,
35
- };
36
-
37
- function run(args: string[], cwd: string): { out: string; err: string; code: number } {
38
- try {
39
- return {
40
- out: execFileSync("node", [CLI, ...args], {
41
- cwd,
42
- env: ENV,
43
- encoding: "utf8",
44
- stdio: ["ignore", "pipe", "pipe"],
45
- }),
46
- err: "",
47
- code: 0,
48
- };
49
- } catch (e: any) {
50
- return { out: e.stdout ?? "", err: e.stderr ?? "", code: e.status ?? 1 };
51
- }
52
- }
53
-
54
- function git(args: string[], cwd: string): void {
55
- execFileSync("git", args, { cwd, env: ENV, stdio: "ignore" });
56
- }
57
-
58
- function mkproj(name: string): string {
59
- const p = path.join(T, name);
60
- fs.mkdirSync(p, { recursive: true });
61
- git(["init", "-q"], p);
62
- git(["config", "user.email", "test@example.com"], p);
63
- git(["config", "user.name", "Test"], p);
64
- fs.writeFileSync(path.join(p, "README.md"), "# curate eval\n");
65
- git(["add", "."], p);
66
- git(["commit", "-qm", "init"], p);
67
- return p;
68
- }
69
-
70
- // Crockford-safe, 26-char fixture ids so graph extraction sees real ULIDs.
71
- function id(tag: string): string {
72
- const safe = tag.toUpperCase().replace(/[^0-9A-HJKMNP-TV-Z]/g, "0");
73
- return `01D78${safe.padEnd(21, "0")}`.slice(0, 26);
74
- }
75
-
76
- interface FixtureOptions {
77
- status?: string;
78
- tags?: string[];
79
- createdAt?: string;
80
- supersedes?: string | null;
81
- supersededBy?: string | null;
82
- }
83
-
84
- function fixture(
85
- dir: string,
86
- memId: string,
87
- body: string,
88
- scopeKey: string,
89
- opts: FixtureOptions = {},
90
- ): void {
91
- const now = opts.createdAt ?? "2026-01-01T00:00:00.000Z";
92
- fs.mkdirSync(dir, { recursive: true });
93
- fs.writeFileSync(
94
- path.join(dir, `${memId}.md`),
95
- `---
96
- id: ${memId}
97
- schema_version: 2
98
- scope_key: ${scopeKey}
99
- scope: project
100
- visibility: internal
101
- project_name: d78
102
- type: fact
103
- role: knowledge
104
- importance: normal
105
- status: ${opts.status ?? "active"}
106
- tags: [${(opts.tags ?? []).join(", ")}]
107
- source: cli
108
- created_at: "${now}"
109
- updated_at: "${now}"
110
- supersedes: ${opts.supersedes ?? "null"}
111
- superseded_by: ${opts.supersededBy ?? "null"}
112
- review_state: draft
113
- proposed_by: null
114
- approved_by: null
115
- derived_from: null
116
- review_note: null
117
- review_history: []
118
- ---
119
-
120
- ${body}
121
- `,
122
- "utf8",
123
- );
124
- }
125
-
126
- function normalizeTitleLine(line: string): string {
127
- return line.trim().replace(/\s+/g, " ");
128
- }
129
-
130
- function firstNonEmptyLine(body: string): string {
131
- return body.split("\n").find((l) => l.trim().length > 0) ?? "";
132
- }
133
-
134
- interface Seed {
135
- project: string;
136
- scopeKey: string;
137
- outboxDir: string;
138
- repoDir: string;
139
- batchIds: string[];
140
- }
141
-
142
- function seed(name: string): Seed {
143
- const project = mkproj(name);
144
- const where = run(["where"], project);
145
- const scopeKey = (/project:\s*(\S+)/.exec(where.out) ?? [])[1] ?? "";
146
- if (!scopeKey) throw new Error(`could not resolve scope key: ${where.out}${where.err}`);
147
- const outboxDir = path.join(DATA, "memories", scopeKey);
148
- const repoDir = path.join(project, ".ai", "open-memex");
149
-
150
- const orphan = id("ORPHAN");
151
- const dangling = id("DANGLING");
152
- const staleOld = id("STALEOLD");
153
- const staleNew = id("STALENEW");
154
- const staleMate = id("STALEMATE");
155
- fixture(repoDir, orphan, "zzq d78 orphan editor parser note with unique tag", scopeKey, {
156
- tags: ["orphanonly"],
157
- });
158
- fixture(
159
- repoDir,
160
- dangling,
161
- `zzq d78 dangling link see [[${id("MISSING")}]]`,
162
- scopeKey,
163
- { tags: ["dangletag"] },
164
- );
165
- fixture(repoDir, staleOld, "zzq d78 stale deploy checklist build sign upload", scopeKey, {
166
- status: "superseded",
167
- tags: ["staletag"],
168
- });
169
- fixture(repoDir, staleNew, "zzq d78 stale deploy checklist build sign upload now", scopeKey, {
170
- tags: ["staletag"],
171
- });
172
- fixture(repoDir, staleMate, "zzq d78 stale partner release notes", scopeKey, {
173
- tags: ["staletag"],
174
- });
175
-
176
- const dupA = id("DUPA");
177
- const dupB = id("DUPB");
178
- const empty = id("EMPTY");
179
- const title = id("TITLE");
180
- const nearA = id("NEARA");
181
- const nearB = id("NEARB");
182
- fixture(outboxDir, dupA, "zzq d78 exact duplicate remember the deploy window", scopeKey, {
183
- createdAt: "2026-01-01T00:00:01.000Z",
184
- });
185
- fixture(outboxDir, dupB, " zzq d78 exact duplicate remember the deploy window ", scopeKey, {
186
- createdAt: "2026-01-01T00:00:02.000Z",
187
- });
188
- fixture(outboxDir, empty, " \n\t\n", scopeKey);
189
- fixture(outboxDir, title, " zzq d78 title needs collapsing \n\nsecond line", scopeKey);
190
- fixture(
191
- outboxDir,
192
- nearA,
193
- "zzq d78 near duplicate deployment window opens thursday morning",
194
- scopeKey,
195
- );
196
- fixture(
197
- outboxDir,
198
- nearB,
199
- "zzq d78 near duplicate deployment window opens friday morning",
200
- scopeKey,
201
- );
202
-
203
- const re = run(["reindex"], project);
204
- if (re.code !== 0) throw new Error(`reindex failed: ${re.out}${re.err}`);
205
- return {
206
- project,
207
- scopeKey,
208
- outboxDir,
209
- repoDir,
210
- batchIds: [dupA, dupB, empty, title, nearA, nearB],
211
- };
212
- }
213
-
214
- interface Measure {
215
- lintTotal: number;
216
- orphan: number;
217
- dangling: number;
218
- stale: number;
219
- exactDuplicates: number;
220
- emptyBodies: number;
221
- titlesToNormalize: number;
222
- nearPairs: number;
223
- }
224
-
225
- interface LintCounts {
226
- total: number;
227
- orphan: number;
228
- dangling: number;
229
- stale: number;
230
- }
231
-
232
- function lint(s: Seed): LintCounts {
233
- const r = run(["graph", "lint", "--json"], s.project);
234
- try {
235
- const parsed = JSON.parse(r.out) as {
236
- findings: unknown[];
237
- counts: { orphan: number; "dangling-edge": number; stale: number };
238
- };
239
- return {
240
- total: parsed.findings.length,
241
- orphan: parsed.counts.orphan,
242
- dangling: parsed.counts["dangling-edge"],
243
- stale: parsed.counts.stale,
244
- };
245
- } catch {
246
- throw new Error(`graph lint --json did not parse: ${r.out}${r.err}`);
247
- }
248
- }
249
-
250
- function measure(s: Seed): Measure {
251
- const counts = lint(s);
252
-
253
- const batch = s.batchIds.map((memId) => {
254
- const raw = fs.readFileSync(path.join(s.outboxDir, `${memId}.md`), "utf8");
255
- const body = raw.slice(raw.indexOf("\n---\n") + 5);
256
- return { id: memId, body };
257
- });
258
-
259
- const groups = new Map<string, string[]>();
260
- for (const b of batch) {
261
- const key = contentHash(b.body);
262
- const list = groups.get(key) ?? [];
263
- list.push(b.id);
264
- groups.set(key, list);
265
- }
266
- let exactDuplicates = 0;
267
- for (const list of groups.values()) exactDuplicates += Math.max(0, list.length - 1);
268
-
269
- let emptyBodies = 0;
270
- let titlesToNormalize = 0;
271
- for (const b of batch) {
272
- if (b.body.trim().length === 0) {
273
- emptyBodies++;
274
- continue;
275
- }
276
- const line = firstNonEmptyLine(b.body);
277
- if (line !== normalizeTitleLine(line)) titlesToNormalize++;
278
- }
279
-
280
- let nearPairs = 0;
281
- for (let i = 0; i < batch.length; i++) {
282
- for (let j = i + 1; j < batch.length; j++) {
283
- const a = batch[i]!;
284
- const b = batch[j]!;
285
- if (contentHash(a.body) === contentHash(b.body)) continue;
286
- if (similarity(a.body, b.body) >= NEAR_DUP_THRESHOLD) nearPairs++;
287
- }
288
- }
289
-
290
- return {
291
- lintTotal: counts.total,
292
- orphan: counts.orphan,
293
- dangling: counts.dangling,
294
- stale: counts.stale,
295
- exactDuplicates,
296
- emptyBodies,
297
- titlesToNormalize,
298
- nearPairs,
299
- };
300
- }
301
-
302
- interface Curated {
303
- autoApplied: number;
304
- merged: number;
305
- archived: number;
306
- normalized: number;
307
- receipts: string[];
308
- output: string;
309
- }
310
-
311
- function curated(s: Seed): Curated {
312
- const r = run(["submit", ...s.batchIds], s.project);
313
- const output = `${r.out}${r.err}`;
314
- const applied = Number((/curation auto-applied:\s*(\d+)/.exec(output) ?? [])[1] ?? 0);
315
- return {
316
- autoApplied: applied,
317
- merged: (output.match(/\bmerged\b/g) ?? []).length,
318
- archived: (output.match(/\barchived\b/g) ?? []).length,
319
- normalized: (output.match(/\bnormalized\b/g) ?? []).length,
320
- receipts: output
321
- .split("\n")
322
- .map((l) => l.trim())
323
- .filter((l) => /^(merged|archived|normalized) /.test(l)),
324
- output,
325
- };
326
- }
327
-
328
- function noCurate(s: Seed): { disabled: boolean; autoApplied: number; output: string } {
329
- const r = run(["submit", "--no-curate", ...s.batchIds], s.project);
330
- const output = `${r.out}${r.err}`;
331
- return {
332
- disabled: /curation auto-apply skipped \(--no-curate\)/.test(output),
333
- autoApplied: Number((/curation auto-applied:\s*(\d+)/.exec(output) ?? [])[1] ?? 0),
334
- output,
335
- };
336
- }
337
-
338
- function line(label: string, m: Measure): string {
339
- return (
340
- `${label}: lint ${m.lintTotal} (orphan ${m.orphan}, dangling ${m.dangling}, stale ${m.stale}) | ` +
341
- `deterministic candidates: exact-dup ${m.exactDuplicates}, empty ${m.emptyBodies}, ` +
342
- `title ${m.titlesToNormalize} | near-dup report ${m.nearPairs}`
343
- );
344
- }
345
-
346
- console.log("D78 curate eval (scratch stores, no real data)");
347
- const baseSeed = seed("baseline");
348
- const base = measure(baseSeed);
349
- console.log(line("baseline", base));
350
-
351
- const curSeed = seed("curated");
352
- const before = measure(curSeed);
353
- const after = curated(curSeed);
354
- console.log(line("curated pre-submit", before));
355
- const afterLint = lint(curSeed);
356
- console.log(
357
- `curated lint after submit: ${afterLint.total} (orphan ${afterLint.orphan}, dangling ${afterLint.dangling}, stale ${afterLint.stale})`,
358
- );
359
- console.log(
360
- `curated auto-applied: ${after.autoApplied} (merged ${after.merged}, archived ${after.archived}, normalized ${after.normalized})`,
361
- );
362
- for (const r of after.receipts) console.log(` ${r}`);
363
- if (after.autoApplied === 0) {
364
- console.log(" (no curation summary yet - this is the pre-D78 baseline run)");
365
- }
366
-
367
- const noSeed = seed("no-curate");
368
- const no = noCurate(noSeed);
369
- console.log(
370
- `--no-curate: ${no.disabled ? "curation skipped as requested" : "MISSING SKIP LINE"}; auto-applied ${no.autoApplied}`,
371
- );
372
-
373
- const undoIds = [id("DUPB"), id("TITLE"), id("EMPTY")];
374
- const undoResults = undoIds.map((memId) => run(["curate", "undo", memId], curSeed.project));
375
- console.log(`undo checks: ${undoResults.filter((r) => r.code === 0).length}/${undoResults.length} succeeded`);
376
- console.log(`scratch: ${T}`);
1
+ // D78 curate fixture - measurement first.
2
+ //
3
+ // Usage: node --experimental-strip-types scripts/curate-eval.ts
4
+ //
5
+ // Baseline (2026-11-13, 0.10.0-alpha.2, no curation): lint 9 findings
6
+ // (orphan 7, dangling 1, stale 1); deterministic candidates: exact-dup 1,
7
+ // empty 1, title 2; near-dup report (not auto) 1.
8
+ //
9
+ // Seeds two scratch projects with the same corpus, measures the deterministic
10
+ // curation candidates in the first, then runs `submit` in the second and reads
11
+ // the curation summary it prints. The baseline half contains no product logic;
12
+ // it uses the same contentHash/similarity the write path already uses, so the
13
+ // numbers are comparable before and after D78's auto-apply tier lands.
14
+ //
15
+ // Isolated: temp HOME + OPEN_MEMEX_HOME + temp git repo. Touches nothing real.
16
+
17
+ import { execFileSync } from "node:child_process";
18
+ import fs from "node:fs";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+ import { contentHash, similarity, NEAR_DUP_THRESHOLD } from "../src/store/lifecycle.ts";
23
+
24
+ const REPO = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
25
+ const CLI = path.join(REPO, "dist", "cli.js");
26
+ const T = fs.mkdtempSync(path.join(os.tmpdir(), "om-curate-"));
27
+ const HOME = path.join(T, "home");
28
+ const DATA = path.join(T, "data");
29
+ fs.mkdirSync(HOME, { recursive: true });
30
+ const ENV: NodeJS.ProcessEnv = {
31
+ ...process.env,
32
+ HOME,
33
+ USERPROFILE: HOME,
34
+ OPEN_MEMEX_HOME: DATA,
35
+ };
36
+
37
+ function run(args: string[], cwd: string): { out: string; err: string; code: number } {
38
+ try {
39
+ return {
40
+ out: execFileSync("node", [CLI, ...args], {
41
+ cwd,
42
+ env: ENV,
43
+ encoding: "utf8",
44
+ stdio: ["ignore", "pipe", "pipe"],
45
+ }),
46
+ err: "",
47
+ code: 0,
48
+ };
49
+ } catch (e: any) {
50
+ return { out: e.stdout ?? "", err: e.stderr ?? "", code: e.status ?? 1 };
51
+ }
52
+ }
53
+
54
+ function git(args: string[], cwd: string): void {
55
+ execFileSync("git", args, { cwd, env: ENV, stdio: "ignore" });
56
+ }
57
+
58
+ function mkproj(name: string): string {
59
+ const p = path.join(T, name);
60
+ fs.mkdirSync(p, { recursive: true });
61
+ git(["init", "-q"], p);
62
+ git(["config", "user.email", "test@example.com"], p);
63
+ git(["config", "user.name", "Test"], p);
64
+ fs.writeFileSync(path.join(p, "README.md"), "# curate eval\n");
65
+ git(["add", "."], p);
66
+ git(["commit", "-qm", "init"], p);
67
+ return p;
68
+ }
69
+
70
+ // Crockford-safe, 26-char fixture ids so graph extraction sees real ULIDs.
71
+ function id(tag: string): string {
72
+ const safe = tag.toUpperCase().replace(/[^0-9A-HJKMNP-TV-Z]/g, "0");
73
+ return `01D78${safe.padEnd(21, "0")}`.slice(0, 26);
74
+ }
75
+
76
+ interface FixtureOptions {
77
+ status?: string;
78
+ tags?: string[];
79
+ createdAt?: string;
80
+ supersedes?: string | null;
81
+ supersededBy?: string | null;
82
+ }
83
+
84
+ function fixture(
85
+ dir: string,
86
+ memId: string,
87
+ body: string,
88
+ scopeKey: string,
89
+ opts: FixtureOptions = {},
90
+ ): void {
91
+ const now = opts.createdAt ?? "2026-01-01T00:00:00.000Z";
92
+ fs.mkdirSync(dir, { recursive: true });
93
+ fs.writeFileSync(
94
+ path.join(dir, `${memId}.md`),
95
+ `---
96
+ id: ${memId}
97
+ schema_version: 2
98
+ scope_key: ${scopeKey}
99
+ scope: project
100
+ visibility: internal
101
+ project_name: d78
102
+ type: fact
103
+ role: knowledge
104
+ importance: normal
105
+ status: ${opts.status ?? "active"}
106
+ tags: [${(opts.tags ?? []).join(", ")}]
107
+ source: cli
108
+ created_at: "${now}"
109
+ updated_at: "${now}"
110
+ supersedes: ${opts.supersedes ?? "null"}
111
+ superseded_by: ${opts.supersededBy ?? "null"}
112
+ review_state: draft
113
+ proposed_by: null
114
+ approved_by: null
115
+ derived_from: null
116
+ review_note: null
117
+ review_history: []
118
+ ---
119
+
120
+ ${body}
121
+ `,
122
+ "utf8",
123
+ );
124
+ }
125
+
126
+ function normalizeTitleLine(line: string): string {
127
+ return line.trim().replace(/\s+/g, " ");
128
+ }
129
+
130
+ function firstNonEmptyLine(body: string): string {
131
+ return body.split("\n").find((l) => l.trim().length > 0) ?? "";
132
+ }
133
+
134
+ interface Seed {
135
+ project: string;
136
+ scopeKey: string;
137
+ outboxDir: string;
138
+ repoDir: string;
139
+ batchIds: string[];
140
+ }
141
+
142
+ function seed(name: string): Seed {
143
+ const project = mkproj(name);
144
+ const where = run(["where"], project);
145
+ const scopeKey = (/project:\s*(\S+)/.exec(where.out) ?? [])[1] ?? "";
146
+ if (!scopeKey) throw new Error(`could not resolve scope key: ${where.out}${where.err}`);
147
+ const outboxDir = path.join(DATA, "memories", scopeKey);
148
+ const repoDir = path.join(project, ".ai", "open-memex");
149
+
150
+ const orphan = id("ORPHAN");
151
+ const dangling = id("DANGLING");
152
+ const staleOld = id("STALEOLD");
153
+ const staleNew = id("STALENEW");
154
+ const staleMate = id("STALEMATE");
155
+ fixture(repoDir, orphan, "zzq d78 orphan editor parser note with unique tag", scopeKey, {
156
+ tags: ["orphanonly"],
157
+ });
158
+ fixture(
159
+ repoDir,
160
+ dangling,
161
+ `zzq d78 dangling link see [[${id("MISSING")}]]`,
162
+ scopeKey,
163
+ { tags: ["dangletag"] },
164
+ );
165
+ fixture(repoDir, staleOld, "zzq d78 stale deploy checklist build sign upload", scopeKey, {
166
+ status: "superseded",
167
+ tags: ["staletag"],
168
+ });
169
+ fixture(repoDir, staleNew, "zzq d78 stale deploy checklist build sign upload now", scopeKey, {
170
+ tags: ["staletag"],
171
+ });
172
+ fixture(repoDir, staleMate, "zzq d78 stale partner release notes", scopeKey, {
173
+ tags: ["staletag"],
174
+ });
175
+
176
+ const dupA = id("DUPA");
177
+ const dupB = id("DUPB");
178
+ const empty = id("EMPTY");
179
+ const title = id("TITLE");
180
+ const nearA = id("NEARA");
181
+ const nearB = id("NEARB");
182
+ fixture(outboxDir, dupA, "zzq d78 exact duplicate remember the deploy window", scopeKey, {
183
+ createdAt: "2026-01-01T00:00:01.000Z",
184
+ });
185
+ fixture(outboxDir, dupB, " zzq d78 exact duplicate remember the deploy window ", scopeKey, {
186
+ createdAt: "2026-01-01T00:00:02.000Z",
187
+ });
188
+ fixture(outboxDir, empty, " \n\t\n", scopeKey);
189
+ fixture(outboxDir, title, " zzq d78 title needs collapsing \n\nsecond line", scopeKey);
190
+ fixture(
191
+ outboxDir,
192
+ nearA,
193
+ "zzq d78 near duplicate deployment window opens thursday morning",
194
+ scopeKey,
195
+ );
196
+ fixture(
197
+ outboxDir,
198
+ nearB,
199
+ "zzq d78 near duplicate deployment window opens friday morning",
200
+ scopeKey,
201
+ );
202
+
203
+ const re = run(["reindex"], project);
204
+ if (re.code !== 0) throw new Error(`reindex failed: ${re.out}${re.err}`);
205
+ return {
206
+ project,
207
+ scopeKey,
208
+ outboxDir,
209
+ repoDir,
210
+ batchIds: [dupA, dupB, empty, title, nearA, nearB],
211
+ };
212
+ }
213
+
214
+ interface Measure {
215
+ lintTotal: number;
216
+ orphan: number;
217
+ dangling: number;
218
+ stale: number;
219
+ exactDuplicates: number;
220
+ emptyBodies: number;
221
+ titlesToNormalize: number;
222
+ nearPairs: number;
223
+ }
224
+
225
+ interface LintCounts {
226
+ total: number;
227
+ orphan: number;
228
+ dangling: number;
229
+ stale: number;
230
+ }
231
+
232
+ function lint(s: Seed): LintCounts {
233
+ const r = run(["graph", "lint", "--json"], s.project);
234
+ try {
235
+ const parsed = JSON.parse(r.out) as {
236
+ findings: unknown[];
237
+ counts: { orphan: number; "dangling-edge": number; stale: number };
238
+ };
239
+ return {
240
+ total: parsed.findings.length,
241
+ orphan: parsed.counts.orphan,
242
+ dangling: parsed.counts["dangling-edge"],
243
+ stale: parsed.counts.stale,
244
+ };
245
+ } catch {
246
+ throw new Error(`graph lint --json did not parse: ${r.out}${r.err}`);
247
+ }
248
+ }
249
+
250
+ function measure(s: Seed): Measure {
251
+ const counts = lint(s);
252
+
253
+ const batch = s.batchIds.map((memId) => {
254
+ const raw = fs.readFileSync(path.join(s.outboxDir, `${memId}.md`), "utf8");
255
+ const body = raw.slice(raw.indexOf("\n---\n") + 5);
256
+ return { id: memId, body };
257
+ });
258
+
259
+ const groups = new Map<string, string[]>();
260
+ for (const b of batch) {
261
+ const key = contentHash(b.body);
262
+ const list = groups.get(key) ?? [];
263
+ list.push(b.id);
264
+ groups.set(key, list);
265
+ }
266
+ let exactDuplicates = 0;
267
+ for (const list of groups.values()) exactDuplicates += Math.max(0, list.length - 1);
268
+
269
+ let emptyBodies = 0;
270
+ let titlesToNormalize = 0;
271
+ for (const b of batch) {
272
+ if (b.body.trim().length === 0) {
273
+ emptyBodies++;
274
+ continue;
275
+ }
276
+ const line = firstNonEmptyLine(b.body);
277
+ if (line !== normalizeTitleLine(line)) titlesToNormalize++;
278
+ }
279
+
280
+ let nearPairs = 0;
281
+ for (let i = 0; i < batch.length; i++) {
282
+ for (let j = i + 1; j < batch.length; j++) {
283
+ const a = batch[i]!;
284
+ const b = batch[j]!;
285
+ if (contentHash(a.body) === contentHash(b.body)) continue;
286
+ if (similarity(a.body, b.body) >= NEAR_DUP_THRESHOLD) nearPairs++;
287
+ }
288
+ }
289
+
290
+ return {
291
+ lintTotal: counts.total,
292
+ orphan: counts.orphan,
293
+ dangling: counts.dangling,
294
+ stale: counts.stale,
295
+ exactDuplicates,
296
+ emptyBodies,
297
+ titlesToNormalize,
298
+ nearPairs,
299
+ };
300
+ }
301
+
302
+ interface Curated {
303
+ autoApplied: number;
304
+ merged: number;
305
+ archived: number;
306
+ normalized: number;
307
+ submittedCount: number;
308
+ prTitleCount: number | null;
309
+ prBody: string;
310
+ receipts: string[];
311
+ output: string;
312
+ }
313
+
314
+ function curated(s: Seed): Curated {
315
+ const r = run(["submit", ...s.batchIds], s.project);
316
+ const output = `${r.out}${r.err}`;
317
+ const applied = Number((/curation auto-applied:\s*(\d+)/.exec(output) ?? [])[1] ?? 0);
318
+ const titleCount = /--title "mem: review (\d+) /.exec(output);
319
+ return {
320
+ autoApplied: applied,
321
+ merged: (output.match(/\bmerged\b/g) ?? []).length,
322
+ archived: (output.match(/\barchived\b/g) ?? []).length,
323
+ normalized: (output.match(/\bnormalized\b/g) ?? []).length,
324
+ submittedCount: (output.match(/^submitted /gm) ?? []).length,
325
+ prTitleCount: titleCount ? Number(titleCount[1]) : null,
326
+ prBody: (/--body "([^"]*)"/.exec(output) ?? [])[1] ?? "",
327
+ receipts: output
328
+ .split("\n")
329
+ .map((l) => l.trim())
330
+ .filter((l) => /^(merged|archived|normalized) /.test(l)),
331
+ output,
332
+ };
333
+ }
334
+
335
+ function noCurate(s: Seed): { disabled: boolean; autoApplied: number; output: string } {
336
+ const r = run(["submit", "--no-curate", ...s.batchIds], s.project);
337
+ const output = `${r.out}${r.err}`;
338
+ return {
339
+ disabled: /curation auto-apply skipped \(--no-curate\)/.test(output),
340
+ autoApplied: Number((/curation auto-applied:\s*(\d+)/.exec(output) ?? [])[1] ?? 0),
341
+ output,
342
+ };
343
+ }
344
+
345
+ function line(label: string, m: Measure): string {
346
+ return (
347
+ `${label}: lint ${m.lintTotal} (orphan ${m.orphan}, dangling ${m.dangling}, stale ${m.stale}) | ` +
348
+ `deterministic candidates: exact-dup ${m.exactDuplicates}, empty ${m.emptyBodies}, ` +
349
+ `title ${m.titlesToNormalize} | near-dup report ${m.nearPairs}`
350
+ );
351
+ }
352
+
353
+ console.log("D78 curate eval (scratch stores, no real data)");
354
+ const baseSeed = seed("baseline");
355
+ const base = measure(baseSeed);
356
+ console.log(line("baseline", base));
357
+
358
+ const curSeed = seed("curated");
359
+ const before = measure(curSeed);
360
+ const after = curated(curSeed);
361
+ console.log(line("curated pre-submit", before));
362
+ const afterLint = lint(curSeed);
363
+ console.log(
364
+ `curated lint after submit: ${afterLint.total} (orphan ${afterLint.orphan}, dangling ${afterLint.dangling}, stale ${afterLint.stale})`,
365
+ );
366
+ console.log(
367
+ `curated auto-applied: ${after.autoApplied} (merged ${after.merged}, archived ${after.archived}, normalized ${after.normalized})`,
368
+ );
369
+ for (const r of after.receipts) console.log(` ${r}`);
370
+ if (after.autoApplied === 0) {
371
+ console.log(" (no curation summary yet - this is the pre-D78 baseline run)");
372
+ }
373
+ const bodyIds = (/IDs: ([^.]+)\./.exec(after.prBody) ?? [])[1]?.trim().split(/\s+/).filter(Boolean)
374
+ .length ?? 0;
375
+ const prOk =
376
+ after.submittedCount > 0 &&
377
+ after.prTitleCount === after.submittedCount &&
378
+ bodyIds === after.submittedCount &&
379
+ /Lint before curation: 9 finding\(s\) \(orphans 7, dangling 1, stale 1; report only\)\. Auto-applied 3: merged 1, archived 1, normalized 1\.$/.test(
380
+ after.prBody,
381
+ );
382
+ console.log(
383
+ `pr command: title ${after.prTitleCount ?? "missing"} (submitted ${after.submittedCount}), body ids ${bodyIds}, summary ${prOk ? "ok" : "MISSING"}`,
384
+ );
385
+ if (!prOk) throw new Error(`PR command does not match the submitted set:\n${after.output}`);
386
+
387
+ const noSeed = seed("no-curate");
388
+ const no = noCurate(noSeed);
389
+ console.log(
390
+ `--no-curate: ${no.disabled ? "curation skipped as requested" : "MISSING SKIP LINE"}; auto-applied ${no.autoApplied}`,
391
+ );
392
+
393
+ const undoIds = [id("DUPB"), id("TITLE"), id("EMPTY")];
394
+ const undoResults = undoIds.map((memId) => run(["curate", "undo", memId], curSeed.project));
395
+ console.log(`undo checks: ${undoResults.filter((r) => r.code === 0).length}/${undoResults.length} succeeded`);
396
+ undoResults.forEach((r, i) => {
397
+ if (r.code !== 0) console.log(` undo ${undoIds[i]} failed: ${(r.err || r.out).trim()}`);
398
+ });
399
+ console.log(`scratch: ${T}`);