intent-prompt-graph 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +157 -2
- package/integrations/claude/commands/ipg-log.md +10 -0
- package/integrations/claude/commands/ipg-rejected.md +10 -0
- package/integrations/claude/commands/ipg.md +10 -0
- package/integrations/omp/intent-graph.ts +65 -0
- package/integrations/omp/types.d.ts +30 -0
- package/package.json +47 -4
- package/src/cli.ts +212 -0
- package/src/config.ts +114 -0
- package/src/export.ts +71 -0
- package/src/harness/claude.ts +349 -0
- package/src/harness/harness.ts +32 -0
- package/src/harness/omp.ts +225 -0
- package/src/heuristic.ts +440 -0
- package/src/labeler.ts +496 -0
- package/src/model.ts +67 -0
- package/src/server.ts +173 -0
- package/src/session.ts +203 -0
- package/src/store.ts +122 -0
- package/src/tail.ts +89 -0
- package/web/app.ts +349 -0
- package/web/index.html +70 -0
- package/web/layout.ts +350 -0
- package/web/style.css +647 -0
- package/web/view.ts +669 -0
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { Config } from "../config";
|
|
5
|
+
import type { Action, Trigger, Turn } from "../model";
|
|
6
|
+
import type { Harness, Reader, SessionRef } from "./harness";
|
|
7
|
+
|
|
8
|
+
const HARNESS_TEXT_MAX = 400;
|
|
9
|
+
const TEXT_MAX = 20_000;
|
|
10
|
+
const SUMMARY_MAX = 120;
|
|
11
|
+
const KEY_RE = /^[0-9a-zA-Z-]+$/;
|
|
12
|
+
|
|
13
|
+
export function agentDir(): string {
|
|
14
|
+
return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".omp", "agent");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function sessionsDir(): string {
|
|
18
|
+
return join(agentDir(), "sessions");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function globFiles(dir: string, pattern: string): string[] {
|
|
22
|
+
if (!existsSync(dir)) return [];
|
|
23
|
+
return [...new Bun.Glob(pattern).scanSync({ cwd: dir, absolute: true })];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface Head {
|
|
27
|
+
id?: string;
|
|
28
|
+
cwd?: string;
|
|
29
|
+
title?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Reads the title slot (line 1) and the session header (line 2) from the first 4 KiB. */
|
|
33
|
+
function headOf(file: string): Head {
|
|
34
|
+
const fd = openSync(file, "r");
|
|
35
|
+
try {
|
|
36
|
+
const buf = Buffer.alloc(4096);
|
|
37
|
+
const n = readSync(fd, buf, 0, buf.length, 0);
|
|
38
|
+
const head: Head = {};
|
|
39
|
+
for (const line of buf.toString("utf8", 0, n).split("\n")) {
|
|
40
|
+
let obj: Record<string, unknown>;
|
|
41
|
+
try {
|
|
42
|
+
obj = JSON.parse(line) as Record<string, unknown>;
|
|
43
|
+
} catch {
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (obj.type === "title" && typeof obj.title === "string") head.title = obj.title;
|
|
47
|
+
if (obj.type === "session") {
|
|
48
|
+
head.id = obj.id as string;
|
|
49
|
+
head.cwd = obj.cwd as string;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return head;
|
|
53
|
+
} finally {
|
|
54
|
+
closeSync(fd);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function refOf(file: string): SessionRef {
|
|
59
|
+
const head = headOf(file);
|
|
60
|
+
if (!head.id || !head.cwd) throw new Error(`no OMP session header in ${file}`);
|
|
61
|
+
return { harness: "omp", key: head.id, file, cwd: head.cwd, title: head.title };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function locate(opts: { sessionFile?: string; tty?: string; cwd: string }): Promise<SessionRef> {
|
|
65
|
+
if (opts.sessionFile) return refOf(opts.sessionFile);
|
|
66
|
+
const looked: string[] = [];
|
|
67
|
+
if (opts.tty) {
|
|
68
|
+
// Breadcrumb name: /dev/pts/9 → pts-9
|
|
69
|
+
const crumb = join(agentDir(), "terminal-sessions", opts.tty.replace(/^\/dev\//, "").replace(/\//g, "-"));
|
|
70
|
+
looked.push(crumb);
|
|
71
|
+
if (existsSync(crumb)) {
|
|
72
|
+
const target = readFileSync(crumb, "utf8").split("\n")[1]?.trim();
|
|
73
|
+
if (target && existsSync(target)) return refOf(target);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
looked.push(`newest sessions with cwd ${opts.cwd} under ${sessionsDir()}`);
|
|
77
|
+
let best: { file: string; mtime: number } | undefined;
|
|
78
|
+
for (const file of globFiles(sessionsDir(), "*/*.jsonl")) {
|
|
79
|
+
if (headOf(file).cwd !== opts.cwd) continue;
|
|
80
|
+
const mtime = statSync(file).mtimeMs;
|
|
81
|
+
if (!best || mtime > best.mtime) best = { file, mtime };
|
|
82
|
+
}
|
|
83
|
+
if (best) return refOf(best.file);
|
|
84
|
+
throw new Error(`no OMP session found; looked at: ${looked.join("; ")}`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function resolve(key: string): Promise<SessionRef> {
|
|
88
|
+
if (!KEY_RE.test(key)) throw new Error(`invalid OMP session key: ${key}`);
|
|
89
|
+
const [file] = globFiles(sessionsDir(), `*/*_${key}.jsonl`);
|
|
90
|
+
if (!file) throw new Error(`no OMP session with key ${key} under ${sessionsDir()}`);
|
|
91
|
+
return refOf(file);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function isObj(v: unknown): v is Record<string, unknown> {
|
|
95
|
+
return typeof v === "object" && v !== null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Owner user content: a string, or text blocks joined with newlines (images shown as [image]). */
|
|
99
|
+
function ownerText(content: unknown): string {
|
|
100
|
+
if (typeof content === "string") return content;
|
|
101
|
+
if (!Array.isArray(content)) return "";
|
|
102
|
+
return content
|
|
103
|
+
.map((b: unknown) => {
|
|
104
|
+
if (!isObj(b)) return "";
|
|
105
|
+
if (b.type === "text" && typeof b.text === "string") return b.text;
|
|
106
|
+
if (b.type === "image") return "[image]";
|
|
107
|
+
return "";
|
|
108
|
+
})
|
|
109
|
+
.filter(Boolean)
|
|
110
|
+
.join("\n");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Summary preference: arguments.i, then arguments.description, then the first string argument. */
|
|
114
|
+
function actionOf(name: string, args: unknown): Action {
|
|
115
|
+
const a = isObj(args) ? args : {};
|
|
116
|
+
let summary = Object.values(a).find((v): v is string => typeof v === "string") ?? "";
|
|
117
|
+
if (typeof a.description === "string") summary = a.description;
|
|
118
|
+
if (typeof a.i === "string") summary = a.i;
|
|
119
|
+
return { tool: name, summary: summary.slice(0, SUMMARY_MAX) };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function snap(t: Turn): Turn {
|
|
123
|
+
return { ...t, actions: [...t.actions] };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function ompReader(opts: { config: Config }): Reader {
|
|
127
|
+
let open: Turn | null = null;
|
|
128
|
+
let pending: Trigger | undefined;
|
|
129
|
+
let last: Turn | null = null;
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
push(record: unknown): Turn[] {
|
|
133
|
+
const changed: Turn[] = [];
|
|
134
|
+
if (!isObj(record)) return changed;
|
|
135
|
+
if (record.type === "title" || record.type === "session") return changed;
|
|
136
|
+
if (typeof record.id !== "string") return changed;
|
|
137
|
+
const id = record.id;
|
|
138
|
+
const at = Date.parse(String(record.timestamp)) || 0;
|
|
139
|
+
|
|
140
|
+
const closeOpen = () => {
|
|
141
|
+
if (!open) return;
|
|
142
|
+
open.open = false;
|
|
143
|
+
changed.push(snap(open));
|
|
144
|
+
open = null;
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
if (record.type === "message" && isObj(record.message)) {
|
|
148
|
+
const m = record.message;
|
|
149
|
+
if (m.role === "user") {
|
|
150
|
+
const text = ownerText(m.content);
|
|
151
|
+
const hit = opts.config.harnessText.some((re) => re.test(text));
|
|
152
|
+
if (hit) {
|
|
153
|
+
// Mid-turn injections are ignored; idle ones become the next agent turn's trigger.
|
|
154
|
+
if (!open) pending = { from: "owner", text: text.slice(0, HARNESS_TEXT_MAX) };
|
|
155
|
+
return changed;
|
|
156
|
+
}
|
|
157
|
+
closeOpen();
|
|
158
|
+
pending = undefined;
|
|
159
|
+
const t: Turn = { id, author: "owner", at, text, actions: [], open: false };
|
|
160
|
+
last = t;
|
|
161
|
+
changed.push(snap(t));
|
|
162
|
+
} else if (m.role === "assistant") {
|
|
163
|
+
if (!open) {
|
|
164
|
+
const t: Turn = { id, author: "agent", at, text: "", actions: [], open: true };
|
|
165
|
+
if (last?.author === "owner") t.openedBy = last.id;
|
|
166
|
+
if (pending) t.trigger = pending;
|
|
167
|
+
pending = undefined;
|
|
168
|
+
open = t;
|
|
169
|
+
last = t;
|
|
170
|
+
}
|
|
171
|
+
const cur = open;
|
|
172
|
+
const content = Array.isArray(m.content) ? m.content : [];
|
|
173
|
+
for (const b of content) {
|
|
174
|
+
if (!isObj(b)) continue;
|
|
175
|
+
if (b.type === "text" && typeof b.text === "string" && b.text) {
|
|
176
|
+
cur.text = (cur.text ? `${cur.text}\n${b.text}` : b.text).slice(-TEXT_MAX);
|
|
177
|
+
} else if (b.type === "toolCall" && typeof b.name === "string") {
|
|
178
|
+
cur.actions.push(actionOf(b.name, b.arguments));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (m.stopReason === "stop" || m.stopReason === "aborted" || m.stopReason === "error") {
|
|
182
|
+
cur.open = false;
|
|
183
|
+
open = null;
|
|
184
|
+
}
|
|
185
|
+
changed.push(snap(cur));
|
|
186
|
+
}
|
|
187
|
+
return changed;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (record.type === "custom_message") {
|
|
191
|
+
if (record.display !== true) return changed;
|
|
192
|
+
if (record.attribution === "user") {
|
|
193
|
+
closeOpen();
|
|
194
|
+
pending = undefined;
|
|
195
|
+
const t: Turn = {
|
|
196
|
+
id,
|
|
197
|
+
author: "owner",
|
|
198
|
+
at,
|
|
199
|
+
text: ownerText(record.content),
|
|
200
|
+
actions: [],
|
|
201
|
+
open: false,
|
|
202
|
+
guest: true,
|
|
203
|
+
};
|
|
204
|
+
last = t;
|
|
205
|
+
changed.push(snap(t));
|
|
206
|
+
} else if (record.attribution === "agent" && !open) {
|
|
207
|
+
pending = { from: "agent", type: String(record.customType) };
|
|
208
|
+
}
|
|
209
|
+
return changed;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (record.type === "custom" && record.customType === "session_exit") closeOpen();
|
|
213
|
+
return changed;
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export const omp: Harness = {
|
|
219
|
+
id: "omp",
|
|
220
|
+
locate,
|
|
221
|
+
resolve,
|
|
222
|
+
reader(_ref: SessionRef, opts: { config: Config }): Reader {
|
|
223
|
+
return ompReader(opts);
|
|
224
|
+
},
|
|
225
|
+
};
|
package/src/heuristic.ts
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
import type { EdgeKind, GraphEdge, GraphNode, NodeKind, SessionGraph, Turn } from "./model";
|
|
2
|
+
|
|
3
|
+
const NOISE_OWNER_RE = /^(main-guard:|Previous session file:|machine:\s*(RED|GREEN))/i;
|
|
4
|
+
const NOISE_AGENT_RE = /^(Still stuck|Still no change|Nothing has changed|Nothing new has changed|No change since my last reply|Same state:|Same as before|Nothing runnable|No plan can run now)/i;
|
|
5
|
+
const CHECK_LOOP_RE = /^(chk\s*(agn|now|nw|again)?|ch\s*agai|check(\s+again|\s+now)?|yes|ok|okay|go|continue|status\??|done\??|next\??|try again|again)\.?$/i;
|
|
6
|
+
const REJECT_RE = /\b(cancel|don't|dont|do not|never|waste|wasting|wrong|against|reject|kill|stop|instead|not yet|no,\s|fuck|ffs)\b/i;
|
|
7
|
+
const SIDE_Q_RE = /^(what is|wgat is|whats|what's|why are|why did|how does|can you explain|who is|where is)\b/i;
|
|
8
|
+
const APPROVED_RE = /\b(ready to sign off|signed off|approved|looks good|lgtm|done,\s*committed|passes locally|merged|correct\.|clean and ready)\b/i;
|
|
9
|
+
const OPTION_LINE_RE = /^\s*(?:\*\*?)?(?:Option\s*)?(\d+)[.)]\s*(?:\*\*?)?([^\n]{6,90})/gm;
|
|
10
|
+
|
|
11
|
+
/** Most nodes a heuristic graph may hold; beyond it, older steps collapse into one summary node. */
|
|
12
|
+
export const MAX_HEURISTIC_NODES = 40;
|
|
13
|
+
const EARLIER_NODE_ID = "earlier";
|
|
14
|
+
|
|
15
|
+
interface Exchange {
|
|
16
|
+
owner?: Turn;
|
|
17
|
+
agents: Turn[];
|
|
18
|
+
allTurns: Turn[];
|
|
19
|
+
at: number;
|
|
20
|
+
isNoise: boolean;
|
|
21
|
+
isCheckLoop: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Cleans markdown and whitespace into a concise single-line snippet.
|
|
26
|
+
*
|
|
27
|
+
* Args:
|
|
28
|
+
* text (string): Raw turn text.
|
|
29
|
+
* max (number): Maximum character length.
|
|
30
|
+
*
|
|
31
|
+
* Returns:
|
|
32
|
+
* string: Normalized, truncated single-line string.
|
|
33
|
+
*/
|
|
34
|
+
function snippet(text: string, max: number): string {
|
|
35
|
+
const clean = text
|
|
36
|
+
.replace(/```[\s\S]*?```/g, " [code] ")
|
|
37
|
+
.replace(/[#*_`>|]/g, "")
|
|
38
|
+
.replace(/\s+/g, " ")
|
|
39
|
+
.trim();
|
|
40
|
+
if (clean.length <= max) return clean;
|
|
41
|
+
return `${clean.slice(0, max - 1).trimEnd()}…`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Extracts a short title from the first meaningful sentence of a turn.
|
|
46
|
+
*
|
|
47
|
+
* Args:
|
|
48
|
+
* text (string): Source turn text.
|
|
49
|
+
* fallback (string): Fallback title when text is empty.
|
|
50
|
+
*
|
|
51
|
+
* Returns:
|
|
52
|
+
* string: Concise node title (up to 72 chars).
|
|
53
|
+
*/
|
|
54
|
+
function titleFrom(text: string, fallback: string): string {
|
|
55
|
+
const s = snippet(text, 140);
|
|
56
|
+
if (!s) return fallback;
|
|
57
|
+
const firstSentence = s.split(/(?<=[.!?])\s+/)[0] ?? s;
|
|
58
|
+
return firstSentence.length <= 72 ? firstSentence : `${firstSentence.slice(0, 71).trimEnd()}…`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Groups raw turns into causal exchanges (an owner turn + the agent turns answering it, or standalone agent turns).
|
|
63
|
+
*
|
|
64
|
+
* Args:
|
|
65
|
+
* turns (Turn[]): Ordered session turns.
|
|
66
|
+
*
|
|
67
|
+
* Returns:
|
|
68
|
+
* Exchange[]: Grouped exchanges ready for loop collapsing and graph construction.
|
|
69
|
+
*/
|
|
70
|
+
function groupExchanges(turns: Turn[]): Exchange[] {
|
|
71
|
+
const exchanges: Exchange[] = [];
|
|
72
|
+
const byOwner = new Map<string, Exchange>();
|
|
73
|
+
|
|
74
|
+
for (const t of turns) {
|
|
75
|
+
if (t.author === "owner") {
|
|
76
|
+
const trimmed = t.text.trim();
|
|
77
|
+
const ex: Exchange = {
|
|
78
|
+
owner: t,
|
|
79
|
+
agents: [],
|
|
80
|
+
allTurns: [t],
|
|
81
|
+
at: t.at,
|
|
82
|
+
isNoise: NOISE_OWNER_RE.test(trimmed),
|
|
83
|
+
isCheckLoop: trimmed.length <= 42 && CHECK_LOOP_RE.test(trimmed),
|
|
84
|
+
};
|
|
85
|
+
exchanges.push(ex);
|
|
86
|
+
byOwner.set(t.id, ex);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const parent = t.openedBy ? byOwner.get(t.openedBy) : undefined;
|
|
91
|
+
if (parent) {
|
|
92
|
+
parent.agents.push(t);
|
|
93
|
+
parent.allTurns.push(t);
|
|
94
|
+
parent.at = Math.max(parent.at, t.at);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const trimmed = t.text.trim();
|
|
99
|
+
const isNoise = trimmed.length === 0 || NOISE_AGENT_RE.test(trimmed);
|
|
100
|
+
exchanges.push({
|
|
101
|
+
agents: [t],
|
|
102
|
+
allTurns: [t],
|
|
103
|
+
at: t.at,
|
|
104
|
+
isNoise,
|
|
105
|
+
isCheckLoop: false,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
return exchanges;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Extracts numbered option headings from an agent message when the agent lays out multiple alternatives.
|
|
113
|
+
*
|
|
114
|
+
* Args:
|
|
115
|
+
* text (string): Agent response text.
|
|
116
|
+
*
|
|
117
|
+
* Returns:
|
|
118
|
+
* string[]: Extracted option titles (capped at 3).
|
|
119
|
+
*/
|
|
120
|
+
function extractOptions(text: string): string[] {
|
|
121
|
+
const found: string[] = [];
|
|
122
|
+
OPTION_LINE_RE.lastIndex = 0;
|
|
123
|
+
let m: RegExpExecArray | null = OPTION_LINE_RE.exec(text);
|
|
124
|
+
while (m !== null && found.length < 4) {
|
|
125
|
+
const label = snippet(m[2] ?? "", 64);
|
|
126
|
+
if (label.length >= 6) found.push(label);
|
|
127
|
+
m = OPTION_LINE_RE.exec(text);
|
|
128
|
+
}
|
|
129
|
+
return found.length >= 2 ? found.slice(0, 3) : [];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Caps a heuristic graph at MAX_HEURISTIC_NODES: keeps the goal, one summary node standing in for
|
|
134
|
+
* the older steps, and the most recent nodes. Edges into a kept node from the goal or from a
|
|
135
|
+
* collapsed node are re-attached to the summary node, so the result reads goal -> summary -> recent
|
|
136
|
+
* steps and every kept node stays reachable from the goal. Graphs at or under the cap are returned as is.
|
|
137
|
+
*
|
|
138
|
+
* Args:
|
|
139
|
+
* nodes (GraphNode[]): Nodes in creation order, goal first.
|
|
140
|
+
* edges (GraphEdge[]): Edges pointing from earlier to later nodes, ids "e1"...
|
|
141
|
+
*
|
|
142
|
+
* Returns:
|
|
143
|
+
* { nodes: GraphNode[]; edges: GraphEdge[] }: Graph with at most MAX_HEURISTIC_NODES nodes.
|
|
144
|
+
*/
|
|
145
|
+
function capGraph(nodes: GraphNode[], edges: GraphEdge[]): { nodes: GraphNode[]; edges: GraphEdge[] } {
|
|
146
|
+
const goal = nodes[0];
|
|
147
|
+
if (!goal || nodes.length <= MAX_HEURISTIC_NODES) return { nodes, edges };
|
|
148
|
+
|
|
149
|
+
const firstKept = nodes.length - (MAX_HEURISTIC_NODES - 2);
|
|
150
|
+
const collapsed = nodes.slice(1, firstKept);
|
|
151
|
+
const recent = nodes.slice(firstKept);
|
|
152
|
+
const collapsedIds = new Set<string>();
|
|
153
|
+
const turnIds = new Set<string>();
|
|
154
|
+
let at = 0;
|
|
155
|
+
for (const n of collapsed) {
|
|
156
|
+
collapsedIds.add(n.id);
|
|
157
|
+
for (const tid of n.turnIds) turnIds.add(tid);
|
|
158
|
+
at = Math.max(at, n.at);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const count = collapsed.length;
|
|
162
|
+
const summary: GraphNode = {
|
|
163
|
+
id: EARLIER_NODE_ID,
|
|
164
|
+
kind: "loop",
|
|
165
|
+
badge: `EARLIER · ${count} STEPS`,
|
|
166
|
+
title: `${count} earlier steps collapsed`,
|
|
167
|
+
desc: `${count} older steps are hidden in no-AI mode.`,
|
|
168
|
+
rationaleLabel: "Why collapsed",
|
|
169
|
+
rationale: `No-AI mode shows the session goal and only the latest ${recent.length} steps. Configure a labeler to get the full decision graph.`,
|
|
170
|
+
turnIds: [...turnIds],
|
|
171
|
+
at,
|
|
172
|
+
rounds: count,
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const kept: GraphEdge[] = [{ id: "e0", from: goal.id, to: summary.id, kind: "loop", label: `${count} earlier` }];
|
|
176
|
+
const reattached = new Set<string>();
|
|
177
|
+
for (const e of edges) {
|
|
178
|
+
if (collapsedIds.has(e.to)) continue;
|
|
179
|
+
if (e.from !== goal.id && !collapsedIds.has(e.from)) {
|
|
180
|
+
kept.push(e);
|
|
181
|
+
} else if (!reattached.has(e.to)) {
|
|
182
|
+
reattached.add(e.to);
|
|
183
|
+
kept.push({ ...e, from: summary.id });
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return { nodes: [goal, summary, ...recent], edges: kept };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Builds a deterministic Decision & Path Graph DAG directly from raw turns without needing an LLM.
|
|
192
|
+
* Collapses repetitive check/polling loops, branches rejections and side questions off the main spine,
|
|
193
|
+
* and caps the result at MAX_HEURISTIC_NODES so long sessions show the goal plus their latest steps.
|
|
194
|
+
*
|
|
195
|
+
* Args:
|
|
196
|
+
* turns (Turn[]): Ordered turns from the session transcript.
|
|
197
|
+
* sessionTitle (string | undefined): Optional session title from the harness header.
|
|
198
|
+
*
|
|
199
|
+
* Returns:
|
|
200
|
+
* SessionGraph: A connected Decision & Path Graph in "heuristic" mode.
|
|
201
|
+
*/
|
|
202
|
+
export function buildHeuristicGraph(turns: Turn[], sessionTitle?: string): SessionGraph {
|
|
203
|
+
if (turns.length === 0) {
|
|
204
|
+
return {
|
|
205
|
+
title: sessionTitle || "Waiting for turns",
|
|
206
|
+
nodes: [],
|
|
207
|
+
edges: [],
|
|
208
|
+
mode: "heuristic",
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const exchanges = groupExchanges(turns);
|
|
213
|
+
const nodes: GraphNode[] = [];
|
|
214
|
+
const edges: GraphEdge[] = [];
|
|
215
|
+
let seq = 0;
|
|
216
|
+
const nextId = (prefix = "h") => `${prefix}${++seq}`;
|
|
217
|
+
|
|
218
|
+
const firstReal = exchanges.find((e) => !e.isNoise) ?? exchanges[0];
|
|
219
|
+
const rootTitle =
|
|
220
|
+
sessionTitle?.trim() ||
|
|
221
|
+
(firstReal?.owner ? titleFrom(firstReal.owner.text, "Session start") : titleFrom(firstReal?.agents[0]?.text ?? "", "Session start"));
|
|
222
|
+
|
|
223
|
+
let spineId: string | undefined;
|
|
224
|
+
let edgeSeq = 0;
|
|
225
|
+
const addEdge = (from: string, to: string, kind: EdgeKind, label?: string) => {
|
|
226
|
+
edges.push({ id: `e${++edgeSeq}`, from, to, kind, label });
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
let i = 0;
|
|
230
|
+
while (i < exchanges.length) {
|
|
231
|
+
const ex = exchanges[i];
|
|
232
|
+
if (!ex) break;
|
|
233
|
+
|
|
234
|
+
// 1. Collapse consecutive noise / polling exchanges into one compact loop node (skip if before root).
|
|
235
|
+
if (ex.isNoise) {
|
|
236
|
+
let j = i;
|
|
237
|
+
const turnIds: string[] = [];
|
|
238
|
+
let at = ex.at;
|
|
239
|
+
while (j < exchanges.length && exchanges[j]?.isNoise) {
|
|
240
|
+
const cur = exchanges[j];
|
|
241
|
+
if (cur) {
|
|
242
|
+
turnIds.push(...cur.allTurns.map((t) => t.id));
|
|
243
|
+
at = Math.max(at, cur.at);
|
|
244
|
+
}
|
|
245
|
+
j++;
|
|
246
|
+
}
|
|
247
|
+
const rounds = j - i;
|
|
248
|
+
// Only create a node for multi-turn noise/polling runs once the root exists, so turn 1 handoffs don't become the root.
|
|
249
|
+
if (spineId && (rounds >= 2 || turnIds.length >= 2)) {
|
|
250
|
+
const id = nextId("n");
|
|
251
|
+
nodes.push({
|
|
252
|
+
id,
|
|
253
|
+
kind: "loop",
|
|
254
|
+
badge: `POLL / GUARD · ${rounds}×`,
|
|
255
|
+
title: `Collapsed ${rounds} status/guard turns`,
|
|
256
|
+
desc: snippet(ex.agents.at(-1)?.text || ex.owner?.text || "Repeated status or guard check", 130),
|
|
257
|
+
rationaleLabel: "Why collapsed",
|
|
258
|
+
rationale: `${rounds} repetitive guard or blocker-polling exchanges compressed into one node to keep the decision graph readable.`,
|
|
259
|
+
turnIds,
|
|
260
|
+
at,
|
|
261
|
+
rounds,
|
|
262
|
+
});
|
|
263
|
+
addEdge(spineId, id, "loop", `${rounds}× poll`);
|
|
264
|
+
spineId = id;
|
|
265
|
+
}
|
|
266
|
+
i = j;
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// 2. Collapse consecutive short check/approval loops (`chk agn`, `chk now`, `yes`, `go`).
|
|
271
|
+
if (ex.isCheckLoop && spineId) {
|
|
272
|
+
let j = i;
|
|
273
|
+
const turnIds: string[] = [];
|
|
274
|
+
let at = ex.at;
|
|
275
|
+
let lastAgentText = "";
|
|
276
|
+
while (j < exchanges.length && exchanges[j]?.isCheckLoop) {
|
|
277
|
+
const cur = exchanges[j];
|
|
278
|
+
if (cur) {
|
|
279
|
+
turnIds.push(...cur.allTurns.map((t) => t.id));
|
|
280
|
+
at = Math.max(at, cur.at);
|
|
281
|
+
const aText = cur.agents.at(-1)?.text ?? "";
|
|
282
|
+
if (aText) lastAgentText = aText;
|
|
283
|
+
}
|
|
284
|
+
j++;
|
|
285
|
+
}
|
|
286
|
+
const rounds = j - i;
|
|
287
|
+
const approved = APPROVED_RE.test(lastAgentText);
|
|
288
|
+
const id = nextId("l");
|
|
289
|
+
nodes.push({
|
|
290
|
+
id,
|
|
291
|
+
kind: approved ? "chosen" : "loop",
|
|
292
|
+
badge: approved ? `VERIFIED · ${rounds} ROUNDS` : `ITERATION · ${rounds} ROUNDS`,
|
|
293
|
+
title: approved ? `Check loop verified (${rounds} rounds)` : `Review / check loop (${rounds} rounds)`,
|
|
294
|
+
desc: snippet(lastAgentText || ex.owner?.text || "Iterative checks", 140),
|
|
295
|
+
rationaleLabel: "Collapsed iteration",
|
|
296
|
+
rationale: `${rounds} short back-and-forth check rounds collapsed into a single milestone node.`,
|
|
297
|
+
turnIds,
|
|
298
|
+
at,
|
|
299
|
+
rounds,
|
|
300
|
+
});
|
|
301
|
+
addEdge(spineId, id, approved ? "chosen" : "loop", `${rounds} rounds`);
|
|
302
|
+
spineId = id;
|
|
303
|
+
i = j;
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const ownerText = ex.owner?.text ?? "";
|
|
308
|
+
const agentText = ex.agents.map((a) => a.text).filter(Boolean).join("\n");
|
|
309
|
+
const turnIds = ex.allTurns.map((t) => t.id);
|
|
310
|
+
const isLast = i === exchanges.length - 1;
|
|
311
|
+
|
|
312
|
+
// 3. First real exchange becomes the root Goal node.
|
|
313
|
+
if (!spineId) {
|
|
314
|
+
const id = nextId("g");
|
|
315
|
+
nodes.push({
|
|
316
|
+
id,
|
|
317
|
+
kind: "goal",
|
|
318
|
+
badge: "SESSION GOAL",
|
|
319
|
+
title: titleFrom(ownerText || agentText, rootTitle),
|
|
320
|
+
desc: snippet(agentText || ownerText, 150),
|
|
321
|
+
rationaleLabel: "Starting context",
|
|
322
|
+
rationale: snippet(ownerText || agentText, 280),
|
|
323
|
+
turnIds,
|
|
324
|
+
at: ex.at,
|
|
325
|
+
});
|
|
326
|
+
spineId = id;
|
|
327
|
+
|
|
328
|
+
// If the agent laid out numbered options on the opening exchange, attach a compact option branch.
|
|
329
|
+
const opts = extractOptions(agentText);
|
|
330
|
+
if (opts.length >= 2) {
|
|
331
|
+
const optId = nextId("o");
|
|
332
|
+
nodes.push({
|
|
333
|
+
id: optId,
|
|
334
|
+
kind: "option",
|
|
335
|
+
badge: `${opts.length} OPTIONS PROPOSED`,
|
|
336
|
+
title: opts[0] ?? "Proposed alternatives",
|
|
337
|
+
desc: opts.slice(1).join(" · "),
|
|
338
|
+
rationaleLabel: "Alternatives laid out",
|
|
339
|
+
rationale: opts.map((o, idx) => `${idx + 1}. ${o}`).join("\n"),
|
|
340
|
+
turnIds: ex.agents.map((a) => a.id),
|
|
341
|
+
at: ex.at,
|
|
342
|
+
});
|
|
343
|
+
addEdge(id, optId, "option", "Options");
|
|
344
|
+
}
|
|
345
|
+
i++;
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// 4. Side clarification question (branches off spine without advancing the spine).
|
|
350
|
+
if (ownerText && ownerText.length < 160 && SIDE_Q_RE.test(ownerText.trim()) && !REJECT_RE.test(ownerText)) {
|
|
351
|
+
const id = nextId("s");
|
|
352
|
+
nodes.push({
|
|
353
|
+
id,
|
|
354
|
+
kind: "side",
|
|
355
|
+
badge: "SIDE QUESTION",
|
|
356
|
+
title: titleFrom(ownerText, "Clarification"),
|
|
357
|
+
desc: snippet(agentText || ownerText, 140),
|
|
358
|
+
rationaleLabel: "Clarification",
|
|
359
|
+
rationale: snippet(agentText || ownerText, 260),
|
|
360
|
+
turnIds,
|
|
361
|
+
at: ex.at,
|
|
362
|
+
});
|
|
363
|
+
addEdge(spineId, id, "side", "Clarification");
|
|
364
|
+
i++;
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// 5. Rejection / Pushback fork: owner pushes back or cancels a proposed path.
|
|
369
|
+
if (ownerText && REJECT_RE.test(ownerText)) {
|
|
370
|
+
const rejId = nextId("r");
|
|
371
|
+
nodes.push({
|
|
372
|
+
id: rejId,
|
|
373
|
+
kind: "rejected",
|
|
374
|
+
badge: "PUSHBACK / REJECTED",
|
|
375
|
+
title: titleFrom(ownerText, "Owner rejected path"),
|
|
376
|
+
desc: snippet(ownerText, 140),
|
|
377
|
+
rationaleLabel: "Why rejected / changed",
|
|
378
|
+
rationale: snippet(ownerText, 280),
|
|
379
|
+
turnIds: ex.owner ? [ex.owner.id] : turnIds,
|
|
380
|
+
at: ex.owner?.at ?? ex.at,
|
|
381
|
+
});
|
|
382
|
+
addEdge(spineId, rejId, "rejected", "Rejected");
|
|
383
|
+
|
|
384
|
+
if (agentText) {
|
|
385
|
+
const pivotId = nextId("c");
|
|
386
|
+
const pivotKind: NodeKind = isLast || APPROVED_RE.test(agentText) ? "chosen" : "decision";
|
|
387
|
+
nodes.push({
|
|
388
|
+
id: pivotId,
|
|
389
|
+
kind: pivotKind,
|
|
390
|
+
badge: pivotKind === "chosen" ? "CHOSEN PIVOT" : "PIVOT / ADJUSTMENT",
|
|
391
|
+
title: titleFrom(agentText, "Adjusted approach"),
|
|
392
|
+
desc: snippet(agentText, 150),
|
|
393
|
+
rationaleLabel: "New direction",
|
|
394
|
+
rationale: snippet(agentText, 280),
|
|
395
|
+
turnIds,
|
|
396
|
+
at: ex.at,
|
|
397
|
+
});
|
|
398
|
+
addEdge(spineId, pivotId, pivotKind, "Pivot");
|
|
399
|
+
addEdge(rejId, pivotId, "decision", "Replaced by");
|
|
400
|
+
spineId = pivotId;
|
|
401
|
+
}
|
|
402
|
+
i++;
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// 6. Standard progression node (Decision or Chosen outcome).
|
|
407
|
+
const approved = APPROVED_RE.test(agentText) || isLast;
|
|
408
|
+
const kind: NodeKind = approved ? "chosen" : "decision";
|
|
409
|
+
const id = nextId(approved ? "c" : "d");
|
|
410
|
+
nodes.push({
|
|
411
|
+
id,
|
|
412
|
+
kind,
|
|
413
|
+
badge: approved ? (isLast ? "LATEST OUTCOME" : "VERIFIED") : ex.owner ? "DECISION / STEP" : "AGENT UPDATE",
|
|
414
|
+
title: titleFrom(ownerText || agentText, "Step"),
|
|
415
|
+
desc: snippet(agentText || ownerText, 150),
|
|
416
|
+
rationaleLabel: approved ? "Outcome" : "Context",
|
|
417
|
+
rationale: snippet(agentText || ownerText, 280),
|
|
418
|
+
turnIds,
|
|
419
|
+
at: ex.at,
|
|
420
|
+
});
|
|
421
|
+
addEdge(spineId, id, kind, ex.owner ? undefined : "Auto");
|
|
422
|
+
spineId = id;
|
|
423
|
+
i++;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// Promote the final spine decision to "chosen" so trailing side questions don't obscure the session's final outcome.
|
|
427
|
+
if (spineId && !nodes.some((n) => n.kind === "chosen")) {
|
|
428
|
+
const tail = nodes.find((n) => n.id === spineId);
|
|
429
|
+
if (tail && tail.kind === "decision") {
|
|
430
|
+
tail.kind = "chosen";
|
|
431
|
+
tail.badge = "LATEST OUTCOME";
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
return {
|
|
436
|
+
title: rootTitle,
|
|
437
|
+
...capGraph(nodes, edges),
|
|
438
|
+
mode: "heuristic",
|
|
439
|
+
};
|
|
440
|
+
}
|