@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/src/route.ts ADDED
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Dedup + route + dry-run (tasks 4.4, 4.5).
3
+ * Maps each distilled artifact to its sink, queries the sink for an existing
4
+ * entry (injectable) to decide merge-vs-create, and defaults to dry-run: a
5
+ * routing plan is emitted and nothing is written unless --apply is given.
6
+ *
7
+ * Routing (design.md "Signal -> anchor -> sink map"):
8
+ * procedure -> skill_manage
9
+ * fault -> memory(failure) [tool-quirk]
10
+ * user_correction -> memory(failure) [correction] (+AGENTS.md if rule)
11
+ * ask_user_decision -> memory(project) [convention]
12
+ * documentation -> docs/ + ctx_index
13
+ */
14
+ import type { Artifact } from "./distill.js";
15
+ import type { CorrectionCandidate, SignalClass } from "./types.js";
16
+ import type { HeldCluster } from "./cluster.js";
17
+
18
+ export type Sink = "skill_manage" | "memory" | "docs";
19
+ export type MemoryTarget = "failure" | "project" | "user";
20
+
21
+ export interface RouteEntry {
22
+ signature: string;
23
+ signal: SignalClass;
24
+ sink: Sink;
25
+ memoryTarget?: MemoryTarget;
26
+ memoryCategory?: string;
27
+ patchesAgentsMd: boolean;
28
+ action: "create" | "merge";
29
+ stale: boolean;
30
+ artifact: Artifact;
31
+ }
32
+
33
+ export interface RoutePlan {
34
+ entries: RouteEntry[];
35
+ dryRun: boolean;
36
+ }
37
+
38
+ /** Does this artifact's promoted cluster establish a reusable rule? */
39
+ function establishesRule(cluster: HeldCluster | undefined): boolean {
40
+ return (
41
+ cluster?.signal === "user_correction" &&
42
+ (cluster.sample as CorrectionCandidate).rule === true
43
+ );
44
+ }
45
+
46
+ interface SinkSpec {
47
+ sink: Sink;
48
+ memoryTarget?: MemoryTarget;
49
+ memoryCategory?: string;
50
+ }
51
+
52
+ export function sinkFor(signal: SignalClass): SinkSpec {
53
+ switch (signal) {
54
+ case "procedure":
55
+ return { sink: "skill_manage" };
56
+ case "fault":
57
+ return { sink: "memory", memoryTarget: "failure", memoryCategory: "tool-quirk" };
58
+ case "user_correction":
59
+ return { sink: "memory", memoryTarget: "failure", memoryCategory: "correction" };
60
+ case "ask_user_decision":
61
+ return { sink: "memory", memoryTarget: "project", memoryCategory: "convention" };
62
+ case "documentation":
63
+ return { sink: "docs" };
64
+ }
65
+ }
66
+
67
+ /** A predicate that reports whether the target sink already holds this artifact. */
68
+ export type ExistsFn = (artifact: Artifact, spec: SinkSpec) => boolean;
69
+
70
+ const NEVER_EXISTS: ExistsFn = () => false;
71
+
72
+ export interface PlanOptions {
73
+ dryRun?: boolean;
74
+ exists?: ExistsFn;
75
+ clustersBySignature?: Map<string, HeldCluster>;
76
+ }
77
+
78
+ /** Build the routing plan from distilled artifacts. */
79
+ export function buildRoutePlan(artifacts: Artifact[], opts: PlanOptions = {}): RoutePlan {
80
+ const exists = opts.exists ?? NEVER_EXISTS;
81
+ const clusters = opts.clustersBySignature;
82
+ const entries: RouteEntry[] = artifacts.map((artifact) => {
83
+ const spec = sinkFor(artifact.signal);
84
+ const cluster = clusters?.get(artifact.signature);
85
+ return {
86
+ signature: artifact.signature,
87
+ signal: artifact.signal,
88
+ sink: spec.sink,
89
+ memoryTarget: spec.memoryTarget,
90
+ memoryCategory: spec.memoryCategory,
91
+ patchesAgentsMd: establishesRule(cluster),
92
+ action: exists(artifact, spec) ? "merge" : "create",
93
+ stale: artifact.stale,
94
+ artifact,
95
+ };
96
+ });
97
+ return { entries, dryRun: opts.dryRun ?? true };
98
+ }
99
+
100
+ /** Human-readable summary of a plan (used by the skill's dry-run review). */
101
+ export function summarizePlan(plan: RoutePlan): string {
102
+ const lines = [
103
+ `Routing plan (${plan.dryRun ? "DRY-RUN — no writes" : "APPLY"}): ${plan.entries.length} artifact(s)`,
104
+ ];
105
+ for (const e of plan.entries) {
106
+ const tgt =
107
+ e.sink === "memory" ? `memory(${e.memoryTarget}/${e.memoryCategory})` : e.sink;
108
+ const flags = [
109
+ e.action,
110
+ e.patchesAgentsMd ? "+AGENTS.md" : "",
111
+ e.stale ? "STALE" : "",
112
+ ]
113
+ .filter(Boolean)
114
+ .join(" ");
115
+ lines.push(` - ${e.signal} -> ${tgt} [${flags}] conf=${e.artifact.provenance.confidence.toFixed(2)}`);
116
+ }
117
+ return lines.join("\n");
118
+ }
package/src/segment.ts ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Trajectory segmentation into task episodes (task 2.4).
3
+ * Boundaries: a new top-level user message (a fresh task, NOT a correction),
4
+ * a session_info.name change, or a time gap beyond a threshold.
5
+ */
6
+ import type { Episode, Trajectory, Turn } from "./types.js";
7
+
8
+ export const DEFAULT_GAP_MS = 30 * 60 * 1000; // 30 minutes
9
+
10
+ /** Correction lexicon — user messages that steer, not start, a task. */
11
+ const CORRECTION_RE =
12
+ /\b(no|nope|actually|don['’]?t|do not|instead|wrong|not quite|stop|rather)\b/i;
13
+
14
+ export function isCorrection(text: string | undefined): boolean {
15
+ return !!text && CORRECTION_RE.test(text);
16
+ }
17
+
18
+ function plainUserText(turn: Turn): string | undefined {
19
+ if (turn.role !== "user") return undefined;
20
+ return turn.text;
21
+ }
22
+
23
+ /** Is this user turn a fresh task boundary (not a correction follow-up)? */
24
+ function startsNewTask(turn: Turn, prev: Turn | undefined): boolean {
25
+ const text = plainUserText(turn);
26
+ if (text === undefined) return false;
27
+ if (isCorrection(text)) return false;
28
+ // A user message right after another user message with no assistant action
29
+ // between is still a boundary; corrections are excluded above.
30
+ void prev;
31
+ return true;
32
+ }
33
+
34
+ function gapMs(a?: string, b?: string): number {
35
+ if (!a || !b) return 0;
36
+ return Math.abs(Date.parse(b) - Date.parse(a));
37
+ }
38
+
39
+ export function segment(
40
+ traj: Trajectory,
41
+ gapThresholdMs = DEFAULT_GAP_MS,
42
+ ): Episode[] {
43
+ const episodes: Episode[] = [];
44
+ let current: Turn[] = [];
45
+ let lastTs: string | undefined;
46
+ let prev: Turn | undefined;
47
+
48
+ const flush = () => {
49
+ if (current.length === 0) return;
50
+ const first = current[0];
51
+ const userTurn = current.find((t) => t.role === "user");
52
+ episodes.push({
53
+ sessionId: traj.sessionId,
54
+ index: episodes.length,
55
+ name: traj.name,
56
+ userPrompt: userTurn?.text,
57
+ startedAt: first.timestamp,
58
+ turns: current,
59
+ });
60
+ current = [];
61
+ };
62
+
63
+ for (const turn of traj.turns) {
64
+ const timeBoundary =
65
+ lastTs !== undefined && gapMs(lastTs, turn.timestamp) > gapThresholdMs;
66
+ const taskBoundary = startsNewTask(turn, prev);
67
+ const nameBoundary = prev !== undefined && turn.name !== prev.name;
68
+
69
+ if (current.length > 0 && (timeBoundary || taskBoundary || nameBoundary)) flush();
70
+
71
+ current.push(turn);
72
+ lastTs = turn.timestamp;
73
+ prev = turn;
74
+ }
75
+ flush();
76
+ return episodes;
77
+ }
package/src/signals.ts ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Verified-signal extraction (tasks 3.1-3.5).
3
+ * Detects five signal classes and admits a candidate only when its span ends in
4
+ * a verified-good state (isError flip true->false on the same tool, a passing
5
+ * check, or a following user confirmation). Unverified spans are dropped.
6
+ *
7
+ * Anchors per class (design.md "Signal -> anchor -> sink map"):
8
+ * - fault : the isError flip
9
+ * - ask_user : answer recorded
10
+ * - correction : the human correction itself
11
+ * - procedure : verified-good terminal state of the episode
12
+ * - documentation : cross-session frequency (verified later at the recurrence
13
+ * gate, so it is exempt from the terminal gate here)
14
+ */
15
+ import type {
16
+ Candidate,
17
+ CorrectionCandidate,
18
+ DecisionCandidate,
19
+ DocumentationCandidate,
20
+ Episode,
21
+ FaultCandidate,
22
+ ProcedureCandidate,
23
+ ToolResult,
24
+ Trajectory,
25
+ Turn,
26
+ } from "./types.js";
27
+ import { isCorrection } from "./segment.js";
28
+
29
+ const PASS_RE = /\b(tests?\s+pass|all\s+pass|0\s+errors?|exit\s+0|✓|passed)\b/i;
30
+ const RULE_RE = /\b(always|never|don['’]?t|do not|must|use\s+.+\s+instead|remember|prefer)\b/i;
31
+ const PROCEDURE_MIN_CALLS = 5; // strictly more than five
32
+
33
+ function slug(s: string): string {
34
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 48);
35
+ }
36
+
37
+ function errorClass(text: string): string {
38
+ const m = text.match(/\b(ENOENT|EACCES|cannot find module|not found|undefined|type ?error|syntax ?error|permission denied|timeout)\b/i);
39
+ if (m) return slug(m[1]);
40
+ return slug(text.split(/[:\n]/)[0] ?? text).slice(0, 24);
41
+ }
42
+
43
+ function passingCheck(r: ToolResult | undefined): boolean {
44
+ return !!r && !r.isError && PASS_RE.test(r.text);
45
+ }
46
+
47
+ /**
48
+ * Verified-good is judged by the episode's TERMINAL state, not by any earlier
49
+ * passing output — an episode that later ends in an error is NOT verified-good.
50
+ */
51
+ export function episodeVerifiedGood(turns: Turn[]): boolean {
52
+ const last = turns[turns.length - 1];
53
+ if (last?.role === "user" && last.text && !isCorrection(last.text)) return true;
54
+ const lastResult = [...turns].reverse().find((t) => t.toolResults.length)?.toolResults.at(-1);
55
+ if (!lastResult) return false;
56
+ return passingCheck(lastResult) || !lastResult.isError;
57
+ }
58
+
59
+ /** Task 3.1 — fault/correction: isError=true then retry same tool isError=false. */
60
+ export function detectFaults(traj: Trajectory): FaultCandidate[] {
61
+ const out: FaultCandidate[] = [];
62
+ const pairs = traj.pairs;
63
+ for (let i = 0; i < pairs.length; i++) {
64
+ const bad = pairs[i];
65
+ if (!bad.result?.isError) continue;
66
+ for (let j = i + 1; j < pairs.length; j++) {
67
+ const fix = pairs[j];
68
+ if (fix.call.name !== bad.call.name) continue;
69
+ if (fix.result && !fix.result.isError) {
70
+ out.push({
71
+ signal: "fault",
72
+ sessionId: traj.sessionId,
73
+ model: traj.model,
74
+ signature: `fault:${bad.call.name}:${errorClass(bad.result.text)}`,
75
+ verified: true,
76
+ wrongCall: bad.call,
77
+ error: bad.result.text.slice(0, 300),
78
+ fixCall: fix.call,
79
+ });
80
+ break;
81
+ }
82
+ }
83
+ }
84
+ return out;
85
+ }
86
+
87
+ /** Task 3.2 — ask_user decision: ask_user call + its result. */
88
+ export function detectDecisions(traj: Trajectory): DecisionCandidate[] {
89
+ const out: DecisionCandidate[] = [];
90
+ for (const p of traj.pairs) {
91
+ if (p.call.name !== "ask_user" || !p.result) continue;
92
+ const args = (p.call.arguments ?? {}) as Record<string, unknown>;
93
+ const question = String(args.title ?? args.message ?? args.question ?? "decision");
94
+ out.push({
95
+ signal: "ask_user_decision",
96
+ sessionId: traj.sessionId,
97
+ model: traj.model,
98
+ signature: `decision:${slug(question)}`,
99
+ verified: true, // answer recorded
100
+ question,
101
+ answer: p.result.text.slice(0, 300),
102
+ });
103
+ }
104
+ return out;
105
+ }
106
+
107
+ /** Task 3.3 — user correction: user msg (correction lexicon) after assistant action. */
108
+ export function detectCorrections(traj: Trajectory): CorrectionCandidate[] {
109
+ const out: CorrectionCandidate[] = [];
110
+ const turns = traj.turns;
111
+ for (let i = 1; i < turns.length; i++) {
112
+ const turn = turns[i];
113
+ if (turn.role !== "user" || !isCorrection(turn.text)) continue;
114
+ // Look back past tool-result turns to the assistant action being corrected.
115
+ let prev: Turn | undefined;
116
+ for (let k = i - 1; k >= 0; k--) {
117
+ if (turns[k].role === "toolResult") continue;
118
+ prev = turns[k];
119
+ break;
120
+ }
121
+ const prevWasAction =
122
+ !!prev && prev.role === "assistant" && (prev.toolCalls.length > 0 || !!prev.text);
123
+ if (!prevWasAction) continue;
124
+ out.push({
125
+ signal: "user_correction",
126
+ sessionId: traj.sessionId,
127
+ model: traj.model,
128
+ signature: `correction:${slug(turn.text ?? "")}`,
129
+ verified: true, // human correction is ground truth
130
+ correction: (turn.text ?? "").slice(0, 300),
131
+ precededBy: prev?.text?.slice(0, 160),
132
+ rule: RULE_RE.test(turn.text ?? ""),
133
+ });
134
+ }
135
+ return out;
136
+ }
137
+
138
+ /** Task 3.4 — procedure: episode with >5 toolCalls ending verified-good. */
139
+ export function detectProcedures(traj: Trajectory, episodes: Episode[]): ProcedureCandidate[] {
140
+ const out: ProcedureCandidate[] = [];
141
+ for (const ep of episodes) {
142
+ const calls = ep.turns.flatMap((t) => t.toolCalls);
143
+ if (calls.length <= PROCEDURE_MIN_CALLS) continue;
144
+ if (!episodeVerifiedGood(ep.turns)) continue;
145
+ const toolSequence = calls.map((c) => c.name);
146
+ out.push({
147
+ signal: "procedure",
148
+ sessionId: traj.sessionId,
149
+ model: traj.model,
150
+ signature: `procedure:${toolSequence.join(">")}`,
151
+ verified: true,
152
+ toolSequence,
153
+ userPrompt: ep.userPrompt,
154
+ });
155
+ }
156
+ return out;
157
+ }
158
+
159
+ /** Documentation candidates: assistant summary turns (anchored later by recurrence). */
160
+ export function detectDocumentation(traj: Trajectory): DocumentationCandidate[] {
161
+ const out: DocumentationCandidate[] = [];
162
+ for (const t of traj.turns) {
163
+ if (t.role !== "assistant" || !t.text) continue;
164
+ const looksLikeSummary = /(^|\n)#{1,4}\s|\n[-*]\s|\n\d+\.\s/.test(t.text) && t.text.length > 200;
165
+ if (!looksLikeSummary) continue;
166
+ out.push({
167
+ signal: "documentation",
168
+ sessionId: traj.sessionId,
169
+ model: traj.model,
170
+ signature: `doc:${slug(t.text.split("\n")[0] ?? "")}`,
171
+ verified: false, // anchored on cross-session frequency at recurrence gate
172
+ summary: t.text.slice(0, 600),
173
+ });
174
+ }
175
+ return out;
176
+ }
177
+
178
+ /** Task 3.5 — verification anchor gate. Documentation deferred to recurrence. */
179
+ export function verificationGate(candidates: Candidate[]): Candidate[] {
180
+ return candidates.filter((c) => c.signal === "documentation" || c.verified);
181
+ }
182
+
183
+ /** Run every detector + apply the gate. */
184
+ export function extractSignals(traj: Trajectory, episodes: Episode[]): Candidate[] {
185
+ const all: Candidate[] = [
186
+ ...detectFaults(traj),
187
+ ...detectDecisions(traj),
188
+ ...detectCorrections(traj),
189
+ ...detectProcedures(traj, episodes),
190
+ ...detectDocumentation(traj),
191
+ ];
192
+ return verificationGate(all);
193
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Trajectory normalization (task 2.2).
3
+ * Turns raw events into a trajectory model: turns carrying role/text/thinking/
4
+ * toolCalls/toolResults, plus toolCall.id <-> toolResult.toolCallId pairing.
5
+ */
6
+ import type {
7
+ RawEvent,
8
+ RawMessage,
9
+ ToolCall,
10
+ ToolPair,
11
+ ToolResult,
12
+ Trajectory,
13
+ Turn,
14
+ } from "./types.js";
15
+ import { sessionHeader } from "./jsonl-reader.js";
16
+
17
+ function blocksOf(content: unknown): any[] {
18
+ if (Array.isArray(content)) return content;
19
+ return [];
20
+ }
21
+
22
+ function textFromContent(content: unknown): string {
23
+ if (typeof content === "string") return content;
24
+ return blocksOf(content)
25
+ .filter((b) => b && b.type === "text" && typeof b.text === "string")
26
+ .map((b) => b.text)
27
+ .join("\n");
28
+ }
29
+
30
+ function resultText(content: unknown): string {
31
+ if (typeof content === "string") return content;
32
+ return blocksOf(content)
33
+ .filter((b) => b && typeof b.text === "string")
34
+ .map((b) => b.text)
35
+ .join("\n");
36
+ }
37
+
38
+ function toTurn(ev: RawEvent): Turn | undefined {
39
+ const m = ev.message as RawMessage | undefined;
40
+ if (!m) return undefined;
41
+ const turn: Turn = {
42
+ role: m.role,
43
+ timestamp: ev.timestamp,
44
+ toolCalls: [],
45
+ toolResults: [],
46
+ };
47
+
48
+ if (m.role === "toolResult") {
49
+ turn.toolResults.push({
50
+ toolCallId: m.toolCallId ?? "",
51
+ toolName: m.toolName,
52
+ text: resultText(m.content),
53
+ isError: m.isError === true,
54
+ timestamp: ev.timestamp,
55
+ });
56
+ return turn;
57
+ }
58
+
59
+ const blocks = blocksOf(m.content);
60
+ const thinking = blocks
61
+ .filter((b) => b && b.type === "thinking" && typeof b.text === "string")
62
+ .map((b) => b.text)
63
+ .join("\n");
64
+ if (thinking) turn.thinking = thinking;
65
+
66
+ const text = textFromContent(m.content);
67
+ if (text) turn.text = text;
68
+
69
+ for (const b of blocks) {
70
+ if (b && b.type === "toolCall" && typeof b.id === "string" && typeof b.name === "string") {
71
+ turn.toolCalls.push({ id: b.id, name: b.name, arguments: b.arguments });
72
+ }
73
+ }
74
+ return turn;
75
+ }
76
+
77
+ /** Build the normalized trajectory from ordered raw events. */
78
+ export function buildTrajectory(events: RawEvent[]): Trajectory {
79
+ const header = sessionHeader(events);
80
+ const turns: Turn[] = [];
81
+ let model: string | undefined;
82
+ let name: string | undefined;
83
+
84
+ for (const ev of events) {
85
+ if (ev.type === "model_change" && ev.modelId) model = ev.modelId;
86
+ if (ev.type === "session_info" && ev.name) name = ev.name;
87
+ if (ev.type === "message") {
88
+ const turn = toTurn(ev);
89
+ if (turn) {
90
+ turn.name = name; // session_info.name in effect at this turn
91
+ turns.push(turn);
92
+ }
93
+ }
94
+ }
95
+
96
+ return {
97
+ sessionId: header?.id ?? "unknown",
98
+ cwd: header?.cwd ?? "",
99
+ startedAt: header?.timestamp ?? turns[0]?.timestamp ?? "",
100
+ model,
101
+ name,
102
+ turns,
103
+ pairs: pairToolCalls(turns),
104
+ };
105
+ }
106
+
107
+ /** Pair every toolCall with its toolResult by id (result undefined => unpaired). */
108
+ export function pairToolCalls(turns: Turn[]): ToolPair[] {
109
+ const results = new Map<string, ToolResult>();
110
+ for (const t of turns) {
111
+ for (const r of t.toolResults) {
112
+ if (r.toolCallId) results.set(r.toolCallId, r);
113
+ }
114
+ }
115
+ const pairs: ToolPair[] = [];
116
+ for (const t of turns) {
117
+ for (const c of t.toolCalls) {
118
+ pairs.push({ call: c, result: results.get(c.id) });
119
+ }
120
+ }
121
+ return pairs;
122
+ }
package/src/types.ts ADDED
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Shared types for the session-knowledge distiller.
3
+ * Schema derived from pi session JSONL (see design.md → "Context").
4
+ */
5
+
6
+ // --- Raw session events (one per JSONL line) ---
7
+
8
+ export interface RawMessage {
9
+ role: "user" | "assistant" | "toolResult";
10
+ content?: unknown; // string | ContentBlock[]
11
+ toolCallId?: string;
12
+ toolName?: string;
13
+ isError?: boolean;
14
+ }
15
+
16
+ export interface RawEvent {
17
+ type: string; // session | model_change | session_info | custom | message | ...
18
+ id?: string;
19
+ parentId?: string | null;
20
+ timestamp?: string;
21
+ // session header
22
+ cwd?: string;
23
+ version?: number;
24
+ // model_change
25
+ provider?: string;
26
+ modelId?: string;
27
+ // session_info
28
+ name?: string;
29
+ // custom
30
+ customType?: string;
31
+ data?: unknown;
32
+ // message
33
+ message?: RawMessage;
34
+ }
35
+
36
+ export interface ReadResult {
37
+ events: RawEvent[];
38
+ malformed: number;
39
+ }
40
+
41
+ // --- Normalized trajectory model ---
42
+
43
+ export interface ToolCall {
44
+ id: string;
45
+ name: string;
46
+ arguments: unknown;
47
+ }
48
+
49
+ export interface ToolResult {
50
+ toolCallId: string;
51
+ toolName?: string;
52
+ text: string;
53
+ isError: boolean;
54
+ timestamp?: string;
55
+ }
56
+
57
+ export interface Turn {
58
+ role: "user" | "assistant" | "toolResult";
59
+ timestamp?: string;
60
+ text?: string;
61
+ thinking?: string;
62
+ toolCalls: ToolCall[];
63
+ toolResults: ToolResult[];
64
+ /** session_info.name in effect at this turn (drives name-change segmentation) */
65
+ name?: string;
66
+ }
67
+
68
+ /** A call paired to its result (result undefined => unpaired). */
69
+ export interface ToolPair {
70
+ call: ToolCall;
71
+ result?: ToolResult;
72
+ }
73
+
74
+ export interface Trajectory {
75
+ sessionId: string;
76
+ cwd: string;
77
+ startedAt: string;
78
+ model?: string;
79
+ name?: string;
80
+ turns: Turn[];
81
+ pairs: ToolPair[];
82
+ }
83
+
84
+ // --- Episodes (segmented tasks within a trajectory) ---
85
+
86
+ export interface Episode {
87
+ sessionId: string;
88
+ index: number;
89
+ name?: string;
90
+ userPrompt?: string;
91
+ startedAt?: string;
92
+ turns: Turn[];
93
+ }
94
+
95
+ // --- Extracted signal candidates ---
96
+
97
+ export type SignalClass =
98
+ | "fault"
99
+ | "ask_user_decision"
100
+ | "user_correction"
101
+ | "procedure"
102
+ | "documentation";
103
+
104
+ export interface CandidateBase {
105
+ signal: SignalClass;
106
+ sessionId: string;
107
+ model?: string;
108
+ /** signature for cross-session clustering */
109
+ signature: string;
110
+ /** whether the span ended in a verified-good state */
111
+ verified: boolean;
112
+ }
113
+
114
+ export interface FaultCandidate extends CandidateBase {
115
+ signal: "fault";
116
+ wrongCall: ToolCall;
117
+ error: string;
118
+ fixCall: ToolCall;
119
+ }
120
+
121
+ export interface DecisionCandidate extends CandidateBase {
122
+ signal: "ask_user_decision";
123
+ question: string;
124
+ answer: string;
125
+ }
126
+
127
+ export interface CorrectionCandidate extends CandidateBase {
128
+ signal: "user_correction";
129
+ correction: string;
130
+ precededBy?: string;
131
+ /** correction establishes a reusable rule => also patch AGENTS.md */
132
+ rule: boolean;
133
+ }
134
+
135
+ export interface ProcedureCandidate extends CandidateBase {
136
+ signal: "procedure";
137
+ toolSequence: string[];
138
+ userPrompt?: string;
139
+ }
140
+
141
+ export interface DocumentationCandidate extends CandidateBase {
142
+ signal: "documentation";
143
+ summary: string;
144
+ }
145
+
146
+ export type Candidate =
147
+ | FaultCandidate
148
+ | DecisionCandidate
149
+ | CorrectionCandidate
150
+ | ProcedureCandidate
151
+ | DocumentationCandidate;