@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.
@@ -0,0 +1,130 @@
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
+ });
@@ -0,0 +1,53 @@
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
+ });
@@ -0,0 +1,66 @@
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
+ });
package/src/cluster.ts ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Cross-session clustering + recurrence gate (tasks 4.1, 4.2).
3
+ * Clusters candidates by signature (tool sequence + error class + file/topic,
4
+ * already encoded in Candidate.signature) and accumulates distinct sessionIds in
5
+ * a persisted candidates store so a cluster is promoted only when seen in >= N
6
+ * sessions. Below-threshold clusters are held, auto-promoted once a later run
7
+ * raises the count to N.
8
+ */
9
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+ import { defaultRoot, cwdHash } from "./watermark.js";
12
+ import type { Candidate, SignalClass } from "./types.js";
13
+
14
+ export const DEFAULT_RECURRENCE = 3;
15
+
16
+ export interface HeldCluster {
17
+ signature: string;
18
+ signal: SignalClass;
19
+ sessionIds: string[]; // distinct, accumulated across runs
20
+ sample: Candidate; // a representative candidate for distillation
21
+ /** newest session timestamp (ISO) in which this cluster was seen; drives recency */
22
+ lastSeen: string;
23
+ }
24
+
25
+ function maxIso(a: string, b: string | undefined): string {
26
+ if (!b) return a;
27
+ if (!a) return b;
28
+ return Date.parse(b) > Date.parse(a) ? b : a;
29
+ }
30
+
31
+ export type CandidateStore = Record<string, HeldCluster>;
32
+
33
+ export function candidatesPath(cwd: string, root = defaultRoot()): string {
34
+ return join(root, cwdHash(cwd), "candidates.json");
35
+ }
36
+
37
+ export function loadStore(path: string): CandidateStore {
38
+ if (!existsSync(path)) return {};
39
+ try {
40
+ return JSON.parse(readFileSync(path, "utf-8")) as CandidateStore;
41
+ } catch (e) {
42
+ // Never silently reset: a later saveStore(remaining) would persist the empty
43
+ // store and wipe accumulated clusters. Abort so the user can recover.
44
+ throw new Error(
45
+ `Corrupt candidates store at ${path}: ${(e as Error).message}. ` +
46
+ `Refusing to overwrite (would lose accumulated cross-session clusters).`,
47
+ );
48
+ }
49
+ }
50
+
51
+ export function saveStore(path: string, store: CandidateStore): void {
52
+ mkdirSync(dirname(path), { recursive: true });
53
+ writeFileSync(path, JSON.stringify(store, null, 2));
54
+ }
55
+
56
+ /**
57
+ * Merge a run's candidates into the store, unioning distinct sessionIds and
58
+ * tracking per-cluster recency. `timestamps` maps sessionId -> session ISO time
59
+ * so each cluster carries its OWN newest sighting (not a run-global max).
60
+ */
61
+ export function mergeIntoStore(
62
+ store: CandidateStore,
63
+ candidates: Candidate[],
64
+ timestamps?: Map<string, string>,
65
+ ): CandidateStore {
66
+ const next: CandidateStore = { ...store };
67
+ for (const c of candidates) {
68
+ const ts = timestamps?.get(c.sessionId);
69
+ const held = next[c.signature];
70
+ if (held) {
71
+ const sessionIds = held.sessionIds.includes(c.sessionId)
72
+ ? held.sessionIds
73
+ : [...held.sessionIds, c.sessionId];
74
+ next[c.signature] = { ...held, sessionIds, lastSeen: maxIso(held.lastSeen, ts) };
75
+ } else {
76
+ next[c.signature] = {
77
+ signature: c.signature,
78
+ signal: c.signal,
79
+ sessionIds: [c.sessionId],
80
+ sample: c,
81
+ lastSeen: ts ?? "",
82
+ };
83
+ }
84
+ }
85
+ return next;
86
+ }
87
+
88
+ export interface PromotionResult {
89
+ promoted: HeldCluster[];
90
+ remaining: CandidateStore; // below-threshold clusters held for later
91
+ }
92
+
93
+ /** Promote clusters seen in >= N distinct sessions; hold the rest. */
94
+ export function promote(store: CandidateStore, n = DEFAULT_RECURRENCE): PromotionResult {
95
+ const promoted: HeldCluster[] = [];
96
+ const remaining: CandidateStore = {};
97
+ for (const [sig, held] of Object.entries(store)) {
98
+ if (held.sessionIds.length >= n) promoted.push(held);
99
+ else remaining[sig] = held;
100
+ }
101
+ return { promoted, remaining };
102
+ }
package/src/distill.ts ADDED
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Distillation with provenance + confidence decay (task 4.3).
3
+ * The deterministic core lives here (provenance assembly, confidence model). The
4
+ * actual natural-language artifact body is produced by a haiku-class subagent on
5
+ * the --apply path (see route.ts / main.ts); tests cover the math, not the LLM.
6
+ */
7
+ import type { HeldCluster } from "./cluster.js";
8
+ import type { SignalClass } from "./types.js";
9
+
10
+ export interface Provenance {
11
+ sessionIds: string[];
12
+ model?: string;
13
+ date: string; // ISO of distillation
14
+ confidence: number; // 0..1
15
+ }
16
+
17
+ export interface Artifact {
18
+ signature: string;
19
+ signal: SignalClass;
20
+ provenance: Provenance;
21
+ /** placeholder body; --apply replaces with subagent output */
22
+ body: string;
23
+ stale: boolean;
24
+ expiryNote?: string;
25
+ }
26
+
27
+ export const CONFIDENCE_FLOOR = 0.25;
28
+ const DECAY_PER_DAY = 0.01;
29
+ const MODEL_CHANGE_PENALTY = 0.2;
30
+
31
+ export interface ConfidenceInput {
32
+ recurrence: number; // distinct sessions seen
33
+ n: number; // promotion threshold
34
+ ageDays: number; // days since last sighting
35
+ modelChanged: boolean;
36
+ isModelWorkaround: boolean; // workarounds decay fastest
37
+ }
38
+
39
+ /**
40
+ * Confidence rises with recurrence, decays with age / model change, and decays
41
+ * fastest for model-limitation workarounds. Fresh recurrence (ageDays ~ 0)
42
+ * refreshes it; no hard TTL cliff.
43
+ */
44
+ export function computeConfidence(i: ConfidenceInput): number {
45
+ const base = clamp(0.3 + 0.2 * (i.recurrence - i.n + 1), 0, 1);
46
+ const decayRate = DECAY_PER_DAY * (i.isModelWorkaround ? 3 : 1);
47
+ const aged = base - i.ageDays * decayRate - (i.modelChanged ? MODEL_CHANGE_PENALTY : 0);
48
+ return clamp(aged, 0, 1);
49
+ }
50
+
51
+ export function isModelWorkaround(signature: string): boolean {
52
+ return /model|token|context.?window|hallucin|workaround/i.test(signature);
53
+ }
54
+
55
+ export function distill(
56
+ cluster: HeldCluster,
57
+ opts: { n: number; now?: Date; lastSeen?: Date; modelChanged?: boolean } = { n: 3 },
58
+ ): Artifact {
59
+ const now = opts.now ?? new Date();
60
+ const lastSeen = opts.lastSeen ?? now;
61
+ const ageDays = Math.max(0, (now.getTime() - lastSeen.getTime()) / 86_400_000);
62
+ const workaround = isModelWorkaround(cluster.signature);
63
+ const confidence = computeConfidence({
64
+ recurrence: cluster.sessionIds.length,
65
+ n: opts.n,
66
+ ageDays,
67
+ modelChanged: opts.modelChanged ?? false,
68
+ isModelWorkaround: workaround,
69
+ });
70
+ return {
71
+ signature: cluster.signature,
72
+ signal: cluster.signal,
73
+ provenance: {
74
+ sessionIds: [...cluster.sessionIds],
75
+ model: cluster.sample.model,
76
+ date: now.toISOString(),
77
+ confidence,
78
+ },
79
+ body: placeholderBody(cluster),
80
+ stale: confidence < CONFIDENCE_FLOOR,
81
+ expiryNote: workaround
82
+ ? "Model-limitation workaround — expires as models improve."
83
+ : undefined,
84
+ };
85
+ }
86
+
87
+ function placeholderBody(cluster: HeldCluster): string {
88
+ return `[${cluster.signal}] ${cluster.signature} (seen in ${cluster.sessionIds.length} sessions)`;
89
+ }
90
+
91
+ function clamp(x: number, lo: number, hi: number): number {
92
+ return Math.max(lo, Math.min(hi, x));
93
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Standalone JSONL session reader (task 2.1).
3
+ * Parses one session file into ordered raw events. Malformed lines are skipped
4
+ * and counted, never aborting the run.
5
+ */
6
+ import { readFileSync, existsSync } from "node:fs";
7
+ import type { RawEvent, ReadResult } from "./types.js";
8
+
9
+ /** A parsed line is a usable event only if it is an object with a string `type`. */
10
+ function isRawEvent(o: unknown): o is RawEvent {
11
+ return !!o && typeof o === "object" && typeof (o as { type?: unknown }).type === "string";
12
+ }
13
+
14
+ /** Parse JSONL text into ordered events + a malformed-line count. */
15
+ export function parseSessionText(content: string): ReadResult {
16
+ const events: RawEvent[] = [];
17
+ let malformed = 0;
18
+ for (const line of content.split("\n")) {
19
+ const trimmed = line.trim();
20
+ if (!trimmed) continue;
21
+ try {
22
+ const obj: unknown = JSON.parse(trimmed);
23
+ if (isRawEvent(obj)) events.push(obj);
24
+ else malformed++; // parseable JSON but not a valid event shape
25
+ } catch {
26
+ malformed++;
27
+ }
28
+ }
29
+ return { events, malformed };
30
+ }
31
+
32
+ /** Read + parse a session file from disk. Missing file => empty result. */
33
+ export function readSession(filePath: string): ReadResult {
34
+ if (!existsSync(filePath)) return { events: [], malformed: 0 };
35
+ return parseSessionText(readFileSync(filePath, "utf-8"));
36
+ }
37
+
38
+ /** The session header event (type=session), if present and well-formed. */
39
+ export function sessionHeader(events: RawEvent[]): RawEvent | undefined {
40
+ const h = events[0];
41
+ if (h && h.type === "session" && typeof h.id === "string") return h;
42
+ return undefined;
43
+ }
package/src/main.ts ADDED
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Orchestrator (stages 1-7). Deterministic planner: harvest -> segment ->
3
+ * extract -> cluster -> promote -> distill -> route. Defaults to dry-run; with
4
+ * --apply it persists the watermark + candidates store and prints the final
5
+ * routing plan as JSON. The actual sink writes (skill_manage / memory / docs +
6
+ * ctx_index, AGENTS.md patch via docs subagent) are performed by the pi agent
7
+ * following the SKILL.md using this plan — that is the haiku-class subagent path.
8
+ */
9
+ import { readSession } from "./jsonl-reader.js";
10
+ import { buildTrajectory } from "./trajectory.js";
11
+ import { segment } from "./segment.js";
12
+ import { extractSignals } from "./signals.js";
13
+ import {
14
+ loadStore,
15
+ saveStore,
16
+ mergeIntoStore,
17
+ promote,
18
+ candidatesPath,
19
+ DEFAULT_RECURRENCE,
20
+ type HeldCluster,
21
+ } from "./cluster.js";
22
+ import { distill } from "./distill.js";
23
+ import { buildRoutePlan, summarizePlan, type RoutePlan } from "./route.js";
24
+ import {
25
+ readWatermark,
26
+ writeWatermark,
27
+ listNewerSessions,
28
+ sessionsRoot,
29
+ } from "./watermark.js";
30
+ import { defaultRoot } from "./watermark.js";
31
+ import type { Candidate } from "./types.js";
32
+
33
+ export interface RunOptions {
34
+ cwd: string;
35
+ n?: number;
36
+ apply?: boolean;
37
+ root?: string; // distiller state root (watermark + candidates)
38
+ sessionsDir?: string; // session JSONL dir
39
+ now?: Date;
40
+ }
41
+
42
+ export interface RunResult {
43
+ processedSessions: number;
44
+ malformedLines: number;
45
+ candidates: number;
46
+ promoted: HeldCluster[];
47
+ plan: RoutePlan;
48
+ newWatermark: string;
49
+ }
50
+
51
+ export function run(opts: RunOptions): RunResult {
52
+ const n = opts.n ?? DEFAULT_RECURRENCE;
53
+ const root = opts.root ?? defaultRoot();
54
+ const dir = opts.sessionsDir ?? sessionsRoot(opts.cwd);
55
+ const now = opts.now ?? new Date();
56
+
57
+ const wm = readWatermark(opts.cwd, root);
58
+ const refs = listNewerSessions(opts.cwd, wm.lastTimestamp, dir);
59
+
60
+ const candidates: Candidate[] = [];
61
+ const timestamps = new Map<string, string>(); // sessionId -> session ISO time
62
+ let malformed = 0;
63
+ let maxTs = wm.lastTimestamp;
64
+
65
+ for (const ref of refs) {
66
+ const { events, malformed: m } = readSession(ref.path);
67
+ malformed += m;
68
+ const traj = buildTrajectory(events);
69
+ const episodes = segment(traj);
70
+ timestamps.set(traj.sessionId, ref.timestamp);
71
+ candidates.push(...extractSignals(traj, episodes));
72
+ if (Date.parse(ref.timestamp) > Date.parse(maxTs || "1970-01-01")) {
73
+ maxTs = ref.timestamp;
74
+ }
75
+ }
76
+
77
+ const storePath = candidatesPath(opts.cwd, root);
78
+ const merged = mergeIntoStore(loadStore(storePath), candidates, timestamps);
79
+ const { promoted, remaining } = promote(merged, n);
80
+
81
+ const clustersBySignature = new Map(promoted.map((c) => [c.signature, c]));
82
+ // Per-cluster recency: each artifact decays from ITS OWN newest sighting,
83
+ // not a run-global max (avoids a recent unrelated session refreshing a stale cluster).
84
+ const artifacts = promoted.map((c) =>
85
+ distill(c, { n, now, lastSeen: c.lastSeen ? new Date(c.lastSeen) : now }),
86
+ );
87
+ const plan = buildRoutePlan(artifacts, {
88
+ dryRun: !opts.apply,
89
+ clustersBySignature,
90
+ });
91
+
92
+ if (opts.apply) {
93
+ // Persist below-threshold clusters for later auto-promotion; advance watermark.
94
+ saveStore(storePath, remaining);
95
+ if (maxTs) writeWatermark(opts.cwd, maxTs, root);
96
+ }
97
+
98
+ return {
99
+ processedSessions: refs.length,
100
+ malformedLines: malformed,
101
+ candidates: candidates.length,
102
+ promoted,
103
+ plan,
104
+ newWatermark: maxTs,
105
+ };
106
+ }
107
+
108
+ // --- CLI ---
109
+
110
+ function requireValue(flag: string, value: string | undefined): string {
111
+ if (value === undefined) throw new Error(`Missing value for ${flag}`);
112
+ return value;
113
+ }
114
+
115
+ export function parseArgs(argv: string[]): RunOptions & { json?: boolean } {
116
+ const out: RunOptions & { json?: boolean } = { cwd: process.cwd() };
117
+ for (let i = 0; i < argv.length; i++) {
118
+ const a = argv[i];
119
+ if (a === "--apply") out.apply = true;
120
+ else if (a === "--json") out.json = true;
121
+ else if (a === "--cwd") out.cwd = requireValue(a, argv[++i]);
122
+ else if (a === "--sessions-dir") out.sessionsDir = requireValue(a, argv[++i]);
123
+ else if (a === "--n") {
124
+ const n = Number(requireValue(a, argv[++i]));
125
+ if (!Number.isInteger(n) || n < 1) throw new Error(`--n must be a positive integer, got "${n}"`);
126
+ out.n = n;
127
+ } else throw new Error(`Unknown argument: ${a}`);
128
+ }
129
+ return out;
130
+ }
131
+
132
+ export function main(argv = process.argv.slice(2)): void {
133
+ let opts: RunOptions & { json?: boolean };
134
+ try {
135
+ opts = parseArgs(argv);
136
+ } catch (e) {
137
+ process.stderr.write(`Error: ${(e as Error).message}\n`);
138
+ process.exitCode = 1;
139
+ return;
140
+ }
141
+ let result: ReturnType<typeof run>;
142
+ try {
143
+ result = run(opts);
144
+ } catch (e) {
145
+ process.stderr.write(`Error: ${(e as Error).message}\n`);
146
+ process.exitCode = 1;
147
+ return;
148
+ }
149
+ if (opts.json) {
150
+ process.stdout.write(JSON.stringify(result.plan, null, 2) + "\n");
151
+ return;
152
+ }
153
+ process.stdout.write(
154
+ [
155
+ `Processed ${result.processedSessions} session(s), ${result.malformedLines} malformed line(s).`,
156
+ `Candidates this run: ${result.candidates}. Promoted clusters: ${result.promoted.length}.`,
157
+ summarizePlan(result.plan),
158
+ opts.apply ? `Watermark advanced to ${result.newWatermark}.` : "Dry-run: no sinks mutated. Re-run with --apply to persist.",
159
+ ].join("\n") + "\n",
160
+ );
161
+ }
162
+
163
+ const isMain = (() => {
164
+ try {
165
+ return import.meta.url === `file://${process.argv[1]}`;
166
+ } catch {
167
+ return false;
168
+ }
169
+ })();
170
+ if (isMain) main();