@blackbelt-technology/pi-dashboard-session-distiller 0.5.4
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/NOTICE +10 -0
- package/README.md +63 -0
- package/bin/distill.mjs +12 -0
- package/package.json +35 -0
- package/src/AGENTS.md +16 -0
- package/src/__tests__/cluster.test.ts +70 -0
- package/src/__tests__/distill.test.ts +57 -0
- package/src/__tests__/fixtures/session-multi.jsonl +30 -0
- package/src/__tests__/jsonl-reader.test.ts +49 -0
- package/src/__tests__/main.test.ts +94 -0
- package/src/__tests__/route.test.ts +63 -0
- package/src/__tests__/segment.test.ts +73 -0
- package/src/__tests__/signals.test.ts +130 -0
- package/src/__tests__/trajectory.test.ts +53 -0
- package/src/__tests__/watermark.test.ts +66 -0
- package/src/cluster.ts +102 -0
- package/src/distill.ts +93 -0
- package/src/jsonl-reader.ts +43 -0
- package/src/main.ts +170 -0
- package/src/route.ts +118 -0
- package/src/segment.ts +77 -0
- package/src/signals.ts +193 -0
- package/src/trajectory.ts +122 -0
- package/src/types.ts +151 -0
- package/src/watermark.ts +98 -0
package/NOTICE
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
@blackbelt-technology/pi-dashboard-session-distiller
|
|
2
|
+
Copyright (c) BlackBelt Technology
|
|
3
|
+
|
|
4
|
+
This product is licensed under the MIT License (see package "license" field).
|
|
5
|
+
|
|
6
|
+
The session-knowledge distillation discipline (anchor every lesson to an
|
|
7
|
+
objective signal, promote only cross-session recurrences, route to
|
|
8
|
+
skill_manage / memory / docs) was designed and implemented originally in the
|
|
9
|
+
pi-agent-dashboard monorepo. All source in this package is original work; no
|
|
10
|
+
third-party source is bundled.
|
package/README.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# @blackbelt-technology/pi-dashboard-session-distiller
|
|
2
|
+
|
|
3
|
+
Offline miner that distills reusable, verified knowledge from pi session JSONL
|
|
4
|
+
logs. It is the deterministic engine behind the `distill-session-knowledge` pi
|
|
5
|
+
skill; use the skill package
|
|
6
|
+
[`@blackbelt-technology/pi-dashboard-distill-session-knowledge`](https://www.npmjs.com/package/@blackbelt-technology/pi-dashboard-distill-session-knowledge)
|
|
7
|
+
to load the discipline into a pi session, or use this engine directly as a CLI /
|
|
8
|
+
library.
|
|
9
|
+
|
|
10
|
+
## What it does
|
|
11
|
+
|
|
12
|
+
Walks the pi sessions for a project (newer than a persisted watermark),
|
|
13
|
+
segments each trajectory, and extracts five signal classes anchored on objective
|
|
14
|
+
outcomes:
|
|
15
|
+
|
|
16
|
+
- **fault** — a tool error that a later same-tool retry resolves (`isError` flip).
|
|
17
|
+
- **user_correction** — a human correction after an assistant action.
|
|
18
|
+
- **ask_user_decision** — a recorded human decision.
|
|
19
|
+
- **procedure** — an episode of >5 tool calls that ends verified-good.
|
|
20
|
+
- **documentation** — a recurring how-to summary.
|
|
21
|
+
|
|
22
|
+
Only patterns that recur across `>= N` sessions (default 3) are promoted. Each
|
|
23
|
+
promoted cluster is distilled into an artifact with provenance and a
|
|
24
|
+
confidence score that decays with age and model change, then routed to a sink
|
|
25
|
+
(`skill_manage`, `memory`, or `docs`).
|
|
26
|
+
|
|
27
|
+
## Privacy
|
|
28
|
+
|
|
29
|
+
The miner is **dry-run by default** — nothing is written until you pass
|
|
30
|
+
`--apply`. State (the watermark and below-threshold candidate store) is written
|
|
31
|
+
to `~/.pi/agent/distill-session-knowledge/` on your machine; it is never
|
|
32
|
+
bundled or transmitted. Distilled artifacts land only in your own local sinks
|
|
33
|
+
after review. The emitted plan carries slugged signatures and provenance
|
|
34
|
+
(session ids, model), not raw session payloads.
|
|
35
|
+
|
|
36
|
+
## CLI
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
# dry-run over the current project (no writes)
|
|
40
|
+
npx distill-session-knowledge --cwd "$(git rev-parse --show-toplevel)"
|
|
41
|
+
|
|
42
|
+
# change the recurrence threshold and emit the routing plan as JSON
|
|
43
|
+
npx distill-session-knowledge --cwd "$(pwd)" --n 3 --json
|
|
44
|
+
|
|
45
|
+
# persist the watermark + candidate store and print the final plan
|
|
46
|
+
npx distill-session-knowledge --cwd "$(pwd)" --apply --json
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Flags: `--cwd <dir>`, `--n <k>` (recurrence threshold), `--sessions-dir <dir>`,
|
|
50
|
+
`--apply`, `--json`.
|
|
51
|
+
|
|
52
|
+
## Library
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { run } from "@blackbelt-technology/pi-dashboard-session-distiller/main.js";
|
|
56
|
+
|
|
57
|
+
const result = run({ cwd: process.cwd(), n: 3 }); // dry-run
|
|
58
|
+
console.log(result.plan);
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## License
|
|
62
|
+
|
|
63
|
+
MIT
|
package/bin/distill.mjs
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Thin launcher: run the TypeScript orchestrator via tsx.
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
|
|
7
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
8
|
+
const entry = join(here, "..", "src", "main.ts");
|
|
9
|
+
const res = spawnSync("npx", ["tsx", entry, ...process.argv.slice(2)], {
|
|
10
|
+
stdio: "inherit",
|
|
11
|
+
});
|
|
12
|
+
process.exit(res.status ?? 1);
|
package/package.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@blackbelt-technology/pi-dashboard-session-distiller",
|
|
3
|
+
"version": "0.5.4",
|
|
4
|
+
"description": "Offline miner: distill reusable artifacts from pi session JSONL logs",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
|
|
10
|
+
"directory": "packages/session-distiller"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"pi-package",
|
|
17
|
+
"pi-session",
|
|
18
|
+
"session-mining",
|
|
19
|
+
"knowledge-distillation",
|
|
20
|
+
"pi-dashboard"
|
|
21
|
+
],
|
|
22
|
+
"exports": {
|
|
23
|
+
"./*.js": "./src/*.ts",
|
|
24
|
+
"./*": "./src/*"
|
|
25
|
+
},
|
|
26
|
+
"bin": {
|
|
27
|
+
"distill-session-knowledge": "bin/distill.mjs"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"src/",
|
|
31
|
+
"bin/",
|
|
32
|
+
"README.md",
|
|
33
|
+
"NOTICE"
|
|
34
|
+
]
|
|
35
|
+
}
|
package/src/AGENTS.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
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>/`. |
|
|
@@ -0,0 +1,70 @@
|
|
|
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
|
+
});
|
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
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"}]}}
|
|
@@ -0,0 +1,49 @@
|
|
|
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
|
+
});
|
|
@@ -0,0 +1,94 @@
|
|
|
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
|
+
});
|
|
@@ -0,0 +1,63 @@
|
|
|
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
|
+
});
|
|
@@ -0,0 +1,73 @@
|
|
|
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
|
+
});
|