@blackbelt-technology/pi-dashboard-session-distiller 0.7.0 → 0.8.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-session-distiller",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Offline miner: distill reusable artifacts from pi session JSONL logs",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -30,6 +30,11 @@
30
30
  "src/",
31
31
  "bin/",
32
32
  "README.md",
33
- "NOTICE"
33
+ "NOTICE",
34
+ "!**/AGENTS.md",
35
+ "!**/*.AGENTS.md",
36
+ "!**/__tests__",
37
+ "!**/*.test.ts",
38
+ "!**/*.test.tsx"
34
39
  ]
35
40
  }
package/src/AGENTS.md DELETED
@@ -1,16 +0,0 @@
1
- # DOX — packages/session-distiller/src
2
-
3
- Files in this directory. One row per source file.
4
-
5
- | File | Purpose |
6
- |------|---------|
7
- | `cluster.ts` | Cross-session cluster + recurrence gate. `mergeIntoStore`, `promote`, `loadStore`/`saveStore`. Promote when distinct sessionIds >= N (default 3). `candidates.json` store. |
8
- | `distill.ts` | Distill artifact + confidence decay. `distill`, `computeConfidence`, `CONFIDENCE_FLOOR`. Provenance `{sessionIds, model, date, confidence}`. Decay by age/model-change; workarounds decay fastest. |
9
- | `jsonl-reader.ts` | Standalone JSONL reader. `parseSessionText`, `readSession`, `sessionHeader`. Skips+counts malformed lines. |
10
- | `main.ts` | Orchestrator. `run()`, `main()` CLI. Pipeline harvest→segment→extract→cluster→promote→distill→route. Dry-run default; `--apply` persists watermark+store. |
11
- | `route.ts` | Dedup + route + dry-run plan. `buildRoutePlan`, `sinkFor`, `summarizePlan`. procedure→skill_manage; fault/correction→memory(failure); decision→memory(project); doc→docs. Rule correction flags +AGENTS.md patch. |
12
- | `segment.ts` | Segment trajectory into task episodes. `segment`, `isCorrection`. Boundaries: fresh user task, name change, time gap. Correction lexicon excluded from boundaries. |
13
- | `signals.ts` | Five signal detectors + verification gate. `detectFaults`/`detectDecisions`/`detectCorrections`/`detectProcedures`/`detectDocumentation`, `extractSignals`. Drops unverified non-doc candidates. |
14
- | `trajectory.ts` | Normalize events to trajectory. `buildTrajectory`, `pairToolCalls`. Pairs `toolCall.id` to `toolResult.toolCallId`. |
15
- | `types.ts` | Shared types. `RawEvent`, `Trajectory`, `Turn`, `ToolPair`, `Episode`, `Candidate` union (fault/decision/correction/procedure/documentation). |
16
- | `watermark.ts` | Watermark + session listing. `readWatermark`/`writeWatermark`, `listNewerSessions`, `timestampFromName`, `sessionDirName`, `cwdHash`. State under `~/.pi/agent/distill-session-knowledge/<cwd-hash>/`. |
@@ -1,70 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import { mkdtempSync, writeFileSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { mergeIntoStore, promote, loadStore, type CandidateStore } from "../cluster.js";
6
- import type { FaultCandidate } from "../types.js";
7
-
8
- function fault(sessionId: string, sig = "fault:bash:enoent"): FaultCandidate {
9
- return {
10
- signal: "fault",
11
- sessionId,
12
- signature: sig,
13
- verified: true,
14
- wrongCall: { id: "a", name: "bash", arguments: {} },
15
- error: "ENOENT",
16
- fixCall: { id: "b", name: "bash", arguments: {} },
17
- };
18
- }
19
-
20
- describe("clustering + recurrence gate (tasks 4.1, 4.2)", () => {
21
- it("clusters the same fault signature across sessions", () => {
22
- let store: CandidateStore = {};
23
- store = mergeIntoStore(store, [fault("s1")]);
24
- store = mergeIntoStore(store, [fault("s2")]);
25
- expect(store["fault:bash:enoent"].sessionIds).toEqual(["s1", "s2"]);
26
- });
27
-
28
- it("tracks per-cluster recency (lastSeen) from session timestamps", () => {
29
- const ts = new Map([
30
- ["s1", "2026-06-20T10:00:00.000Z"],
31
- ["s2", "2026-06-22T10:00:00.000Z"],
32
- ]);
33
- let store: CandidateStore = {};
34
- store = mergeIntoStore(store, [fault("s1")], ts);
35
- store = mergeIntoStore(store, [fault("s2")], ts);
36
- // newest sighting wins, regardless of merge order
37
- expect(store["fault:bash:enoent"].lastSeen).toBe("2026-06-22T10:00:00.000Z");
38
- });
39
-
40
- it("does not double-count the same session", () => {
41
- let store: CandidateStore = {};
42
- store = mergeIntoStore(store, [fault("s1"), fault("s1")]);
43
- expect(store["fault:bash:enoent"].sessionIds).toEqual(["s1"]);
44
- });
45
-
46
- it("promotes a cluster seen in >= N sessions and holds the rest", () => {
47
- let store: CandidateStore = {};
48
- store = mergeIntoStore(store, [fault("s1"), fault("s2", "fault:read:notfound")]);
49
- store = mergeIntoStore(store, [fault("s2"), fault("s3")]);
50
- const { promoted, remaining } = promote(store, 3);
51
- expect(promoted.map((p) => p.signature)).toEqual(["fault:bash:enoent"]);
52
- expect(Object.keys(remaining)).toEqual(["fault:read:notfound"]);
53
- });
54
-
55
- it("throws on a corrupt candidates store instead of silently resetting", () => {
56
- const dir = mkdtempSync(join(tmpdir(), "distill-store-"));
57
- const p = join(dir, "candidates.json");
58
- writeFileSync(p, "{ not valid json");
59
- expect(() => loadStore(p)).toThrow(/corrupt/i);
60
- });
61
-
62
- it("auto-promotes once a later run pushes the count to N", () => {
63
- let store: CandidateStore = {};
64
- store = mergeIntoStore(store, [fault("s1")]);
65
- store = mergeIntoStore(store, [fault("s2")]);
66
- expect(promote(store, 3).promoted.length).toBe(0); // held at 2
67
- store = mergeIntoStore(store, [fault("s3")]);
68
- expect(promote(store, 3).promoted.length).toBe(1); // promoted at 3
69
- });
70
- });
@@ -1,57 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import { distill, computeConfidence, CONFIDENCE_FLOOR } from "../distill.js";
3
- import type { HeldCluster } from "../cluster.js";
4
-
5
- const cluster: HeldCluster = {
6
- signature: "fault:bash:enoent",
7
- signal: "fault",
8
- sessionIds: ["s1", "s2", "s3"],
9
- lastSeen: "",
10
- sample: {
11
- signal: "fault",
12
- sessionId: "s1",
13
- model: "claude-opus-4-8",
14
- signature: "fault:bash:enoent",
15
- verified: true,
16
- wrongCall: { id: "a", name: "bash", arguments: {} },
17
- error: "ENOENT",
18
- fixCall: { id: "b", name: "bash", arguments: {} },
19
- },
20
- };
21
-
22
- describe("distillation provenance (task 4.3)", () => {
23
- it("stamps provenance with sessionIds, model, date, confidence", () => {
24
- const a = distill(cluster, { n: 3 });
25
- expect(a.provenance.sessionIds).toEqual(["s1", "s2", "s3"]);
26
- expect(a.provenance.model).toBe("claude-opus-4-8");
27
- expect(a.provenance.date).toMatch(/^\d{4}-\d{2}-\d{2}T/);
28
- expect(a.provenance.confidence).toBeGreaterThan(CONFIDENCE_FLOOR);
29
- expect(a.stale).toBe(false);
30
- });
31
- });
32
-
33
- describe("confidence decay (task 4.3)", () => {
34
- it("rises with recurrence", () => {
35
- const low = computeConfidence({ recurrence: 3, n: 3, ageDays: 0, modelChanged: false, isModelWorkaround: false });
36
- const high = computeConfidence({ recurrence: 6, n: 3, ageDays: 0, modelChanged: false, isModelWorkaround: false });
37
- expect(high).toBeGreaterThan(low);
38
- });
39
-
40
- it("decays an aged artifact below the floor without fresh recurrence", () => {
41
- const aged = distill(cluster, {
42
- n: 3,
43
- now: new Date("2026-12-01T00:00:00Z"),
44
- lastSeen: new Date("2026-06-01T00:00:00Z"), // ~6 months stale
45
- });
46
- expect(aged.provenance.confidence).toBeLessThan(CONFIDENCE_FLOOR);
47
- expect(aged.stale).toBe(true);
48
- });
49
-
50
- it("model-limitation workarounds decay fastest and carry an expiry note", () => {
51
- const wk: HeldCluster = { ...cluster, signature: "fault:model-token-limit:overflow" };
52
- const a = distill(wk, { n: 3, now: new Date("2026-06-21T00:00:00Z"), lastSeen: new Date("2026-06-01T00:00:00Z") });
53
- const normal = distill(cluster, { n: 3, now: new Date("2026-06-21T00:00:00Z"), lastSeen: new Date("2026-06-01T00:00:00Z") });
54
- expect(a.provenance.confidence).toBeLessThan(normal.provenance.confidence);
55
- expect(a.expiryNote).toMatch(/model/i);
56
- });
57
- });
@@ -1,30 +0,0 @@
1
- {"type":"session","version":3,"id":"sess1","timestamp":"2026-06-20T10:00:00.000Z","cwd":"/repo"}
2
- {"type":"model_change","id":"m1","parentId":null,"timestamp":"2026-06-20T10:00:01.000Z","provider":"anthropic","modelId":"claude-opus-4-8"}
3
- {"type":"session_info","id":"si1","timestamp":"2026-06-20T10:00:02.000Z","name":"harvest-work"}
4
- {"type":"message","id":"u1","timestamp":"2026-06-20T10:00:03.000Z","message":{"role":"user","content":[{"type":"text","text":"Add the standalone jsonl reader to the package."}]}}
5
- {"type":"message","id":"a1","timestamp":"2026-06-20T10:00:04.000Z","message":{"role":"assistant","content":[{"type":"text","text":"I will add it."},{"type":"toolCall","id":"c1","name":"write","arguments":{"path":"reader.ts"}}]}}
6
- {"type":"message","id":"r1","timestamp":"2026-06-20T10:00:05.000Z","message":{"role":"toolResult","toolCallId":"c1","toolName":"write","isError":false,"content":[{"type":"text","text":"ok"}]}}
7
- {"type":"message","id":"a2","timestamp":"2026-06-20T10:00:06.000Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"c2","name":"bash","arguments":{"command":"npm test"}}]}}
8
- {"type":"message","id":"r2","timestamp":"2026-06-20T10:00:07.000Z","message":{"role":"toolResult","toolCallId":"c2","toolName":"bash","isError":true,"content":[{"type":"text","text":"error: cannot find module"}]}}
9
- {"type":"message","id":"a3","timestamp":"2026-06-20T10:00:08.000Z","message":{"role":"assistant","content":[{"type":"thinking","text":"missing dep"},{"type":"toolCall","id":"c3","name":"bash","arguments":{"command":"npm test"}}]}}
10
- {"type":"message","id":"r3","timestamp":"2026-06-20T10:00:09.000Z","message":{"role":"toolResult","toolCallId":"c3","toolName":"bash","isError":false,"content":[{"type":"text","text":"tests pass"}]}}
11
- {"type":"message","id":"u2","timestamp":"2026-06-20T10:00:10.000Z","message":{"role":"user","content":[{"type":"text","text":"no, actually use the forks pool instead"}]}}
12
- {"type":"message","id":"a4","timestamp":"2026-06-20T10:00:11.000Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"c4","name":"edit","arguments":{"path":"vitest.config.ts"}}]}}
13
- {"type":"message","id":"r4","timestamp":"2026-06-20T10:00:12.000Z","message":{"role":"toolResult","toolCallId":"c4","toolName":"edit","isError":false,"content":[{"type":"text","text":"ok"}]}}
14
- {"type":"message","id":"u3","timestamp":"2026-06-20T10:00:13.000Z","message":{"role":"user","content":[{"type":"text","text":"Now build the trajectory segmenter."}]}}
15
- {"type":"message","id":"a5","timestamp":"2026-06-20T10:00:14.000Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"c5","name":"ask_user","arguments":{"title":"Which boundary rule?"}}]}}
16
- {"type":"message","id":"r5","timestamp":"2026-06-20T10:00:15.000Z","message":{"role":"toolResult","toolCallId":"c5","toolName":"ask_user","isError":false,"content":[{"type":"text","text":"Use top-level user messages as boundaries"}]}}
17
- { this is : not json ]
18
- {"type":"message","id":"u4","timestamp":"2026-06-20T10:00:16.000Z","message":{"role":"user","content":[{"type":"text","text":"Finally, add unit tests for everything."}]}}
19
- {"type":"message","id":"a6","timestamp":"2026-06-20T10:00:17.000Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"c6","name":"read","arguments":{"path":"a"}}]}}
20
- {"type":"message","id":"r6","timestamp":"2026-06-20T10:00:18.000Z","message":{"role":"toolResult","toolCallId":"c6","toolName":"read","isError":false,"content":[{"type":"text","text":"x"}]}}
21
- {"type":"message","id":"a7","timestamp":"2026-06-20T10:00:19.000Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"c7","name":"write","arguments":{"path":"b"}}]}}
22
- {"type":"message","id":"r7","timestamp":"2026-06-20T10:00:20.000Z","message":{"role":"toolResult","toolCallId":"c7","toolName":"write","isError":false,"content":[{"type":"text","text":"ok"}]}}
23
- {"type":"message","id":"a8","timestamp":"2026-06-20T10:00:21.000Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"c8","name":"write","arguments":{"path":"c"}}]}}
24
- {"type":"message","id":"r8","timestamp":"2026-06-20T10:00:22.000Z","message":{"role":"toolResult","toolCallId":"c8","toolName":"write","isError":false,"content":[{"type":"text","text":"ok"}]}}
25
- {"type":"message","id":"a9","timestamp":"2026-06-20T10:00:23.000Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"c9","name":"bash","arguments":{"command":"ls"}}]}}
26
- {"type":"message","id":"r9","timestamp":"2026-06-20T10:00:24.000Z","message":{"role":"toolResult","toolCallId":"c9","toolName":"bash","isError":false,"content":[{"type":"text","text":"ok"}]}}
27
- {"type":"message","id":"a10","timestamp":"2026-06-20T10:00:25.000Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"c10","name":"bash","arguments":{"command":"npm test"}}]}}
28
- {"type":"message","id":"r10","timestamp":"2026-06-20T10:00:26.000Z","message":{"role":"toolResult","toolCallId":"c10","toolName":"bash","isError":false,"content":[{"type":"text","text":"tests pass"}]}}
29
- {"type":"message","id":"a11","timestamp":"2026-06-20T10:00:27.000Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"c11","name":"bash","arguments":{"command":"git add -A"}}]}}
30
- {"type":"message","id":"r11","timestamp":"2026-06-20T10:00:28.000Z","message":{"role":"toolResult","toolCallId":"c11","toolName":"bash","isError":false,"content":[{"type":"text","text":"ok"}]}}
@@ -1,49 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import { fileURLToPath } from "node:url";
3
- import { dirname, join } from "node:path";
4
- import { readSession, parseSessionText, sessionHeader } from "../jsonl-reader.js";
5
-
6
- const FIXTURE = join(
7
- dirname(fileURLToPath(import.meta.url)),
8
- "fixtures",
9
- "session-multi.jsonl",
10
- );
11
-
12
- describe("jsonl-reader (task 2.1)", () => {
13
- it("parses the fixture into ordered events and skips+counts malformed lines", () => {
14
- const { events, malformed } = readSession(FIXTURE);
15
- // 30 lines total, 1 malformed => 29 well-formed events.
16
- expect(events.length).toBe(29);
17
- expect(malformed).toBe(1);
18
- });
19
-
20
- it("returns events in file order", () => {
21
- const { events } = readSession(FIXTURE);
22
- expect(events[0].type).toBe("session");
23
- expect(events[1].type).toBe("model_change");
24
- expect(events[2].type).toBe("session_info");
25
- });
26
-
27
- it("identifies the session header", () => {
28
- const { events } = readSession(FIXTURE);
29
- expect(sessionHeader(events)?.id).toBe("sess1");
30
- });
31
-
32
- it("tolerates a malformed line inline without aborting", () => {
33
- const { events, malformed } = parseSessionText(
34
- '{"type":"a"}\nGARBAGE NOT JSON\n{"type":"b"}\n',
35
- );
36
- expect(events.map((e) => e.type)).toEqual(["a", "b"]);
37
- expect(malformed).toBe(1);
38
- });
39
-
40
- it("counts parseable-but-shapeless JSON as malformed", () => {
41
- const { events, malformed } = parseSessionText('{"type":"ok"}\n42\n{"foo":1}\n');
42
- expect(events.map((e) => e.type)).toEqual(["ok"]);
43
- expect(malformed).toBe(2); // 42 and {foo:1} lack a string `type`
44
- });
45
-
46
- it("returns empty result for a missing file", () => {
47
- expect(readSession("/nonexistent/x.jsonl")).toEqual({ events: [], malformed: 0 });
48
- });
49
- });
@@ -1,94 +0,0 @@
1
- import { describe, it, expect, beforeEach } from "vitest";
2
- import { mkdtempSync, copyFileSync, writeFileSync, readFileSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join, dirname } from "node:path";
5
- import { fileURLToPath } from "node:url";
6
- import { run, parseArgs } from "../main.js";
7
- import { candidatesPath } from "../cluster.js";
8
- import { readWatermark } from "../watermark.js";
9
-
10
- const FIXTURE = join(
11
- dirname(fileURLToPath(import.meta.url)),
12
- "fixtures",
13
- "session-multi.jsonl",
14
- );
15
- const CWD = "/repo";
16
-
17
- let root: string;
18
- let sessions: string;
19
-
20
- /** Copy the fixture into a sessions dir under a session filename for sessionId `sid`. */
21
- function placeSession(ts: string, sid: string) {
22
- const name = `${ts}_${sid}.jsonl`;
23
- const dest = join(sessions, name);
24
- // rewrite the embedded sessionId so each copy clusters as a distinct session
25
- const text = readFileSync(FIXTURE, "utf-8").replace(/"id":"sess1"/, `"id":"${sid}"`);
26
- writeFileSync(dest, text);
27
- }
28
-
29
- beforeEach(() => {
30
- root = mkdtempSync(join(tmpdir(), "distill-main-root-"));
31
- sessions = mkdtempSync(join(tmpdir(), "distill-main-sess-"));
32
- });
33
-
34
- describe("CLI flag validation", () => {
35
- it("rejects a non-positive-integer --n", () => {
36
- expect(() => parseArgs(["--n", "x"])).toThrow(/positive integer/i);
37
- expect(() => parseArgs(["--n", "0"])).toThrow(/positive integer/i);
38
- });
39
- it("rejects a missing flag value", () => {
40
- expect(() => parseArgs(["--cwd"])).toThrow(/missing value/i);
41
- });
42
- it("rejects an unknown argument", () => {
43
- expect(() => parseArgs(["--bogus"])).toThrow(/unknown argument/i);
44
- });
45
- it("parses a valid invocation", () => {
46
- const o = parseArgs(["--cwd", "/repo", "--n", "3", "--apply", "--json"]);
47
- expect(o).toMatchObject({ cwd: "/repo", n: 3, apply: true, json: true });
48
- });
49
- });
50
-
51
- describe("orchestrator run (tasks 4.5, integration)", () => {
52
- it("dry-run by default mutates no state", () => {
53
- placeSession("2026-06-20T10-00-00-000Z", "s1");
54
- const r = run({ cwd: CWD, n: 1, root, sessionsDir: sessions });
55
- expect(r.plan.dryRun).toBe(true);
56
- expect(r.processedSessions).toBe(1);
57
- expect(r.malformedLines).toBe(1); // fixture has one malformed line
58
- // watermark untouched in dry-run
59
- expect(readWatermark(CWD, root).lastTimestamp).toBe("");
60
- });
61
-
62
- it("promotes single-session signals when N=1 and routes them", () => {
63
- placeSession("2026-06-20T10-00-00-000Z", "s1");
64
- const r = run({ cwd: CWD, n: 1, root, sessionsDir: sessions });
65
- const signals = r.plan.entries.map((e) => e.signal).sort();
66
- expect(signals).toContain("fault");
67
- expect(signals).toContain("ask_user_decision");
68
- expect(signals).toContain("user_correction");
69
- expect(signals).toContain("procedure");
70
- });
71
-
72
- it("holds below-threshold clusters and auto-promotes across runs (N=3)", () => {
73
- placeSession("2026-06-20T10-00-00-000Z", "s1");
74
- const r1 = run({ cwd: CWD, n: 3, root, sessionsDir: sessions, apply: true });
75
- expect(r1.promoted.length).toBe(0); // held at 1 session
76
-
77
- placeSession("2026-06-21T10-00-00-000Z", "s2");
78
- const r2 = run({ cwd: CWD, n: 3, root, sessionsDir: sessions, apply: true });
79
- expect(r2.promoted.length).toBe(0); // held at 2
80
-
81
- placeSession("2026-06-22T10-00-00-000Z", "s3");
82
- const r3 = run({ cwd: CWD, n: 3, root, sessionsDir: sessions, apply: true });
83
- expect(r3.promoted.length).toBeGreaterThan(0); // promoted at 3
84
- });
85
-
86
- it("advances the watermark on --apply and re-run is a no-op", () => {
87
- placeSession("2026-06-20T10-00-00-000Z", "s1");
88
- const r1 = run({ cwd: CWD, n: 1, root, sessionsDir: sessions, apply: true });
89
- expect(readWatermark(CWD, root).lastTimestamp).toBe("2026-06-20T10:00:00.000Z");
90
- const r2 = run({ cwd: CWD, n: 1, root, sessionsDir: sessions, apply: true });
91
- expect(r2.processedSessions).toBe(0); // nothing newer than watermark
92
- void r1;
93
- });
94
- });
@@ -1,63 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import { buildRoutePlan, sinkFor, type ExistsFn } from "../route.js";
3
- import { distill } from "../distill.js";
4
- import type { HeldCluster } from "../cluster.js";
5
- import type { SignalClass } from "../types.js";
6
-
7
- function cluster(signal: SignalClass, signature: string, extra: Record<string, unknown> = {}): HeldCluster {
8
- return {
9
- signature,
10
- signal,
11
- sessionIds: ["s1", "s2", "s3"],
12
- lastSeen: "",
13
- sample: { signal, sessionId: "s1", signature, verified: true, ...extra } as never,
14
- };
15
- }
16
-
17
- describe("sink routing (task 4.4)", () => {
18
- it("maps each signal class to the correct sink", () => {
19
- expect(sinkFor("procedure")).toEqual({ sink: "skill_manage" });
20
- expect(sinkFor("fault")).toMatchObject({ sink: "memory", memoryTarget: "failure" });
21
- expect(sinkFor("ask_user_decision")).toMatchObject({ sink: "memory", memoryTarget: "project", memoryCategory: "convention" });
22
- expect(sinkFor("documentation")).toEqual({ sink: "docs" });
23
- });
24
-
25
- it("flags AGENTS.md patch for a rule-establishing correction", () => {
26
- const c = cluster("user_correction", "correction:always-grep-docs-first", { rule: true, correction: "always grep docs first" });
27
- const a = distill(c, { n: 3 });
28
- const plan = buildRoutePlan([a], {
29
- clustersBySignature: new Map([[a.signature, c]]),
30
- });
31
- expect(plan.entries[0].patchesAgentsMd).toBe(true);
32
- expect(plan.entries[0].memoryCategory).toBe("correction");
33
- });
34
-
35
- it("does not flag AGENTS.md for a non-rule correction", () => {
36
- const c = cluster("user_correction", "correction:use-forks", { rule: false, correction: "use forks" });
37
- const a = distill(c, { n: 3 });
38
- const plan = buildRoutePlan([a], { clustersBySignature: new Map([[a.signature, c]]) });
39
- expect(plan.entries[0].patchesAgentsMd).toBe(false);
40
- });
41
- });
42
-
43
- describe("dedup + dry-run (tasks 4.4, 4.5)", () => {
44
- it("defaults to dry-run and writes nothing", () => {
45
- const a = distill(cluster("fault", "fault:bash:enoent"), { n: 3 });
46
- const plan = buildRoutePlan([a]);
47
- expect(plan.dryRun).toBe(true);
48
- });
49
-
50
- it("re-apply over an existing corpus merges instead of creating duplicates", () => {
51
- const a = distill(cluster("fault", "fault:bash:enoent"), { n: 3 });
52
- const alwaysExists: ExistsFn = () => true;
53
- const plan = buildRoutePlan([a], { dryRun: false, exists: alwaysExists });
54
- expect(plan.entries.every((e) => e.action === "merge")).toBe(true);
55
- expect(plan.entries.filter((e) => e.action === "create").length).toBe(0);
56
- });
57
-
58
- it("creates when the sink has no matching entry", () => {
59
- const a = distill(cluster("procedure", "procedure:read>write>bash"), { n: 3 });
60
- const plan = buildRoutePlan([a], { dryRun: false, exists: () => false });
61
- expect(plan.entries[0].action).toBe("create");
62
- });
63
- });
@@ -1,73 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import { fileURLToPath } from "node:url";
3
- import { dirname, join } from "node:path";
4
- import { readSession } from "../jsonl-reader.js";
5
- import { buildTrajectory } from "../trajectory.js";
6
- import { segment, isCorrection } from "../segment.js";
7
-
8
- const FIXTURE = join(
9
- dirname(fileURLToPath(import.meta.url)),
10
- "fixtures",
11
- "session-multi.jsonl",
12
- );
13
-
14
- describe("segmentation (task 2.4)", () => {
15
- it("yields one episode per distinct user-initiated task", () => {
16
- const traj = buildTrajectory(readSession(FIXTURE).events);
17
- const eps = segment(traj);
18
- expect(eps.length).toBe(3);
19
- expect(eps[0].userPrompt).toMatch(/jsonl reader/i);
20
- expect(eps[1].userPrompt).toMatch(/segmenter/i);
21
- expect(eps[2].userPrompt).toMatch(/unit tests/i);
22
- });
23
-
24
- it("does not split on correction-style user messages", () => {
25
- const traj = buildTrajectory(readSession(FIXTURE).events);
26
- const eps = segment(traj);
27
- // "no, actually use the forks pool instead" stays inside episode 1.
28
- const ep1Texts = eps[0].turns.map((t) => t.text).filter(Boolean).join(" ");
29
- expect(ep1Texts).toMatch(/forks pool/i);
30
- });
31
-
32
- it("splits on a large time gap", () => {
33
- const traj = buildTrajectory(readSession(FIXTURE).events);
34
- // A 1ms threshold forces a boundary at every timestamped transition.
35
- const eps = segment(traj, 1);
36
- expect(eps.length).toBeGreaterThan(3);
37
- });
38
-
39
- it("splits on a session_info.name change", () => {
40
- const mkUser = (text: string, name: string, ts: string) => ({
41
- role: "user" as const,
42
- text,
43
- timestamp: ts,
44
- name,
45
- toolCalls: [],
46
- toolResults: [],
47
- });
48
- const traj = {
49
- sessionId: "s",
50
- cwd: "",
51
- startedAt: "",
52
- turns: [
53
- mkUser("work on alpha", "alpha", "2026-06-20T10:00:00.000Z"),
54
- mkUser("keep going", "alpha", "2026-06-20T10:00:01.000Z"),
55
- mkUser("now beta task", "beta", "2026-06-20T10:00:02.000Z"),
56
- ],
57
- pairs: [],
58
- };
59
- // suppress the user-task boundary by making messages corrections-only? no:
60
- // here every user msg is a fresh task too, but the name change still must split.
61
- const eps = segment(traj, 60_000);
62
- expect(eps.length).toBeGreaterThanOrEqual(2);
63
- // the beta turn must not share an episode with alpha turns
64
- const betaEp = eps.find((e) => e.turns.some((t) => t.name === "beta"))!;
65
- expect(betaEp.turns.every((t) => t.name === "beta")).toBe(true);
66
- });
67
-
68
- it("recognizes correction lexicon", () => {
69
- expect(isCorrection("no, do it differently")).toBe(true);
70
- expect(isCorrection("actually use forks")).toBe(true);
71
- expect(isCorrection("Add the reader")).toBe(false);
72
- });
73
- });
@@ -1,130 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import { fileURLToPath } from "node:url";
3
- import { dirname, join } from "node:path";
4
- import { readSession } from "../jsonl-reader.js";
5
- import { buildTrajectory } from "../trajectory.js";
6
- import { segment } from "../segment.js";
7
- import {
8
- detectFaults,
9
- detectDecisions,
10
- detectCorrections,
11
- detectProcedures,
12
- verificationGate,
13
- extractSignals,
14
- episodeVerifiedGood,
15
- } from "../signals.js";
16
- import type { Candidate, Trajectory, Turn } from "../types.js";
17
-
18
- const FIXTURE = join(
19
- dirname(fileURLToPath(import.meta.url)),
20
- "fixtures",
21
- "session-multi.jsonl",
22
- );
23
-
24
- function load() {
25
- const traj = buildTrajectory(readSession(FIXTURE).events);
26
- return { traj, eps: segment(traj) };
27
- }
28
-
29
- describe("fault detector (task 3.1)", () => {
30
- it("detects an isError flip on the same tool", () => {
31
- const { traj } = load();
32
- const faults = detectFaults(traj);
33
- expect(faults.length).toBe(1);
34
- expect(faults[0].wrongCall.id).toBe("c2");
35
- expect(faults[0].fixCall.id).toBe("c3");
36
- expect(faults[0].error).toMatch(/cannot find module/i);
37
- });
38
-
39
- it("ignores a non-recovering error", () => {
40
- const t: Trajectory = {
41
- sessionId: "s",
42
- cwd: "",
43
- startedAt: "",
44
- turns: [],
45
- pairs: [
46
- { call: { id: "a", name: "bash", arguments: {} }, result: { toolCallId: "a", text: "boom", isError: true } },
47
- ],
48
- };
49
- expect(detectFaults(t).length).toBe(0);
50
- });
51
- });
52
-
53
- describe("ask_user decision detector (task 3.2)", () => {
54
- it("captures question + answer", () => {
55
- const { traj } = load();
56
- const decisions = detectDecisions(traj);
57
- expect(decisions.length).toBe(1);
58
- expect(decisions[0].question).toMatch(/boundary rule/i);
59
- expect(decisions[0].answer).toMatch(/top-level user messages/i);
60
- });
61
- });
62
-
63
- describe("user correction detector (task 3.3)", () => {
64
- it("emits a correction after an assistant action", () => {
65
- const { traj } = load();
66
- const corrections = detectCorrections(traj);
67
- expect(corrections.length).toBe(1);
68
- expect(corrections[0].correction).toMatch(/forks pool/i);
69
- });
70
- });
71
-
72
- describe("procedure detector (task 3.4)", () => {
73
- it("accepts a long verified episode and rejects short ones", () => {
74
- const { traj, eps } = load();
75
- const procs = detectProcedures(traj, eps);
76
- expect(procs.length).toBe(1);
77
- expect(procs[0].toolSequence.length).toBeGreaterThan(5);
78
- });
79
- });
80
-
81
- describe("episodeVerifiedGood judges the terminal state", () => {
82
- const result = (text: string, isError: boolean): Turn => ({
83
- role: "toolResult",
84
- toolCalls: [],
85
- toolResults: [{ toolCallId: "x", text, isError }],
86
- });
87
- it("is false when an early pass is followed by a terminal error", () => {
88
- expect(episodeVerifiedGood([result("tests pass", false), result("boom", true)])).toBe(false);
89
- });
90
- it("is true when the terminal result is non-error", () => {
91
- expect(episodeVerifiedGood([result("boom", true), result("ok", false)])).toBe(true);
92
- });
93
- });
94
-
95
- describe("verification anchor gate (task 3.5)", () => {
96
- it("drops unverified non-documentation candidates", () => {
97
- const unverified: Candidate = {
98
- signal: "fault",
99
- sessionId: "s",
100
- signature: "fault:x:y",
101
- verified: false,
102
- wrongCall: { id: "a", name: "bash", arguments: {} },
103
- error: "e",
104
- fixCall: { id: "b", name: "bash", arguments: {} },
105
- };
106
- expect(verificationGate([unverified]).length).toBe(0);
107
- });
108
-
109
- it("keeps documentation candidates (anchored later by recurrence)", () => {
110
- const doc: Candidate = {
111
- signal: "documentation",
112
- sessionId: "s",
113
- signature: "doc:x",
114
- verified: false,
115
- summary: "## Heading\n- a\n- b",
116
- };
117
- expect(verificationGate([doc]).length).toBe(1);
118
- });
119
- });
120
-
121
- describe("extractSignals integration", () => {
122
- it("returns fault + decision + correction + procedure for the fixture", () => {
123
- const { traj, eps } = load();
124
- const classes = extractSignals(traj, eps).map((c) => c.signal).sort();
125
- expect(classes).toContain("fault");
126
- expect(classes).toContain("ask_user_decision");
127
- expect(classes).toContain("user_correction");
128
- expect(classes).toContain("procedure");
129
- });
130
- });
@@ -1,53 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import { fileURLToPath } from "node:url";
3
- import { dirname, join } from "node:path";
4
- import { readSession } from "../jsonl-reader.js";
5
- import { buildTrajectory, pairToolCalls } from "../trajectory.js";
6
-
7
- const FIXTURE = join(
8
- dirname(fileURLToPath(import.meta.url)),
9
- "fixtures",
10
- "session-multi.jsonl",
11
- );
12
-
13
- function traj() {
14
- return buildTrajectory(readSession(FIXTURE).events);
15
- }
16
-
17
- describe("trajectory normalization (task 2.2)", () => {
18
- it("captures session metadata from header / model_change / session_info", () => {
19
- const t = traj();
20
- expect(t.sessionId).toBe("sess1");
21
- expect(t.cwd).toBe("/repo");
22
- expect(t.model).toBe("claude-opus-4-8");
23
- expect(t.name).toBe("harvest-work");
24
- });
25
-
26
- it("pairs every toolCall to its toolResult", () => {
27
- const t = traj();
28
- const totalCalls = t.turns.reduce((n, tu) => n + tu.toolCalls.length, 0);
29
- expect(t.pairs.length).toBe(totalCalls);
30
- const unpaired = t.pairs.filter((p) => !p.result);
31
- expect(unpaired.length).toBe(0);
32
- // spot-check a known flip pair
33
- const c2 = t.pairs.find((p) => p.call.id === "c2");
34
- expect(c2?.result?.isError).toBe(true);
35
- const c3 = t.pairs.find((p) => p.call.id === "c3");
36
- expect(c3?.result?.isError).toBe(false);
37
- });
38
-
39
- it("extracts text and thinking blocks onto assistant turns", () => {
40
- const t = traj();
41
- const withText = t.turns.find((tu) => tu.text?.startsWith("I will add it"));
42
- expect(withText).toBeTruthy();
43
- const withThinking = t.turns.find((tu) => tu.thinking === "missing dep");
44
- expect(withThinking).toBeTruthy();
45
- });
46
-
47
- it("flags unpaired calls when a result is missing", () => {
48
- const pairs = pairToolCalls([
49
- { role: "assistant", toolCalls: [{ id: "x", name: "bash", arguments: {} }], toolResults: [] },
50
- ]);
51
- expect(pairs[0].result).toBeUndefined();
52
- });
53
- });
@@ -1,66 +0,0 @@
1
- import { describe, it, expect, beforeEach } from "vitest";
2
- import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import {
6
- readWatermark,
7
- writeWatermark,
8
- listNewerSessions,
9
- timestampFromName,
10
- sessionDirName,
11
- cwdHash,
12
- } from "../watermark.js";
13
-
14
- let root: string;
15
- let sessions: string;
16
-
17
- beforeEach(() => {
18
- root = mkdtempSync(join(tmpdir(), "distill-wm-"));
19
- sessions = mkdtempSync(join(tmpdir(), "distill-sess-"));
20
- });
21
-
22
- describe("watermark store (task 2.3)", () => {
23
- it("returns an empty watermark before any run", () => {
24
- expect(readWatermark("/repo", root).lastTimestamp).toBe("");
25
- });
26
-
27
- it("round-trips a written watermark", () => {
28
- writeWatermark("/repo", "2026-06-20T10:00:00.000Z", root);
29
- expect(readWatermark("/repo", root).lastTimestamp).toBe("2026-06-20T10:00:00.000Z");
30
- });
31
-
32
- it("isolates watermarks per cwd hash", () => {
33
- expect(cwdHash("/a")).not.toBe(cwdHash("/b"));
34
- });
35
-
36
- it("encodes a cwd to its session dir name", () => {
37
- expect(sessionDirName("/Users/x/proj")).toBe("--Users-x-proj--");
38
- });
39
-
40
- it("parses the timestamp from a session filename", () => {
41
- expect(timestampFromName("2026-06-23T22-25-00-849Z_uuid.jsonl")).toBe(
42
- "2026-06-23T22:25:00.849Z",
43
- );
44
- });
45
-
46
- it("lists only sessions newer than the watermark", () => {
47
- const mk = (name: string) => writeFileSync(join(sessions, name), "{}\n");
48
- mk("2026-06-20T10-00-00-000Z_a.jsonl");
49
- mk("2026-06-21T10-00-00-000Z_b.jsonl");
50
- mk("2026-06-22T10-00-00-000Z_c.jsonl");
51
- const newer = listNewerSessions("/repo", "2026-06-20T10:00:00.000Z", sessions);
52
- expect(newer.map((r) => r.path.endsWith("_b.jsonl") || r.path.endsWith("_c.jsonl"))).toEqual([
53
- true,
54
- true,
55
- ]);
56
- });
57
-
58
- it("re-run over unchanged corpus is a no-op", () => {
59
- writeFileSync(join(sessions, "2026-06-21T10-00-00-000Z_b.jsonl"), "{}\n");
60
- const first = listNewerSessions("/repo", "", sessions);
61
- expect(first.length).toBe(1);
62
- const watermark = first[first.length - 1].timestamp;
63
- const second = listNewerSessions("/repo", watermark, sessions);
64
- expect(second.length).toBe(0);
65
- });
66
- });