intent-prompt-graph 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -15,8 +15,30 @@ Three parts in one npm package:
15
15
  ## Install
16
16
 
17
17
  ```sh
18
- bun add -g intent-prompt-graph # puts `ipg` on PATH
19
- omp plugin install intent-prompt-graph # adds /ipg to OMP
18
+ bun add -g intent-prompt-graph # puts `ipg` on PATH
19
+ omp plugin install intent-prompt-graph # OMP: adds /ipg
20
+ ipg setup claude # Claude Code: adds /ipg
21
+ ```
22
+
23
+ Needs [Bun](https://bun.sh) 1.0 or later. The package has no runtime
24
+ dependencies. The labeler is optional and needs either the `claude` command or
25
+ an OpenAI-compatible endpoint.
26
+
27
+ Pick the model that draws the real graph (this writes the `labeler` section of
28
+ the [config](#config); run it again any time to change it):
29
+
30
+ ```sh
31
+ ipg setup labeler --provider claude-cli --model haiku
32
+ ipg setup labeler --provider openai --base-url https://api.example.com/v1 --model example-model --api-key-env IPG_LABELER_KEY
33
+ ipg setup labeler --off
34
+ ```
35
+
36
+ Uninstall:
37
+
38
+ ```sh
39
+ ipg uninstall # removes the Claude Code commands; --purge also deletes the config and stored graphs
40
+ omp plugin uninstall intent-prompt-graph
41
+ bun remove -g intent-prompt-graph
20
42
  ```
21
43
 
22
44
  From a checkout instead:
@@ -60,13 +82,10 @@ slash-command and `!` shell wrappers, system reminders, task notifications,
60
82
  compaction summaries and subagent conversations do not.
61
83
 
62
84
  The slash commands are the files `integrations/claude/commands/*.md` of this
63
- package. Copy or link them into your Claude Code commands directory (or into
64
- `.claude/commands/` of one project). From a checkout:
65
-
66
- ```sh
67
- mkdir -p ~/.claude/commands
68
- ln -s "$PWD"/integrations/claude/commands/*.md ~/.claude/commands/
69
- ```
85
+ package. `ipg setup claude` links them into your Claude Code commands
86
+ directory (`~/.claude/commands/`, or `$CLAUDE_CONFIG_DIR/commands/`). A file of
87
+ the same name that is not its own link is left alone. To use them in one
88
+ project only, link the files into that project's `.claude/commands/` yourself.
70
89
 
71
90
  - `/ipg` runs `ipg open --harness claude` and replies with the URL.
72
91
  - `/ipg-log` writes the decision log to `/tmp/ipg-log-<session id>.md` and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "intent-prompt-graph",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "A live browser graph of a coding-agent conversation, grouped by intent. Standalone `ipg` CLI plus plugins for OMP and Claude Code that add /ipg.",
5
5
  "keywords": [
6
6
  "ai-agents",
package/src/cli.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  #!/usr/bin/env bun
2
2
  import { writeFileSync } from "node:fs";
3
- import { configFile, type Config, loadConfig } from "./config";
3
+ import { configFile, type Config, type LabelerConfig, loadConfig } from "./config";
4
4
  import { renderDecisionLog } from "./export";
5
5
  import { type Harness, harnessById, type SessionRef } from "./harness/harness";
6
6
  import { buildHeuristicGraph } from "./heuristic";
7
7
  import type { Turn } from "./model";
8
8
  import { APP, startDaemon } from "./server";
9
+ import { setupClaude, uninstall, writeLabeler } from "./setup";
9
10
  import { openStore } from "./store";
10
11
  import { tailJsonl } from "./tail";
11
12
 
@@ -14,6 +15,10 @@ const USAGE = [
14
15
  " ipg serve [--port N]",
15
16
  " ipg open [--harness omp|claude] [--session-file <file.jsonl>] [--no-browser] [--port N]",
16
17
  " ipg log [--harness omp|claude] [--session-file <file.jsonl>] [--rejected] [--out <file.md>]",
18
+ " ipg setup claude",
19
+ " ipg setup labeler --provider claude-cli|openai --model <name> [--base-url <url>] [--api-key-env <VAR>] [--command <path>]",
20
+ " ipg setup labeler --off",
21
+ " ipg uninstall [--purge]",
17
22
  ].join("\n");
18
23
 
19
24
  // The reader closed the pipe (e.g. `| head`): exit quietly, as other Unix tools do.
@@ -187,6 +192,52 @@ function openBrowser(url: string): void {
187
192
  }
188
193
  }
189
194
 
195
+ /** One-time setup: slash commands for Claude Code, or the labeler model in config.json. */
196
+ function setup(args: string[]): number {
197
+ const [what, ...rest] = args;
198
+ if (what === "claude") {
199
+ console.log(setupClaude().join("\n"));
200
+ console.log("Restart Claude Code to load the commands.");
201
+ return 0;
202
+ }
203
+ if (what === "labeler") {
204
+ let labeler: LabelerConfig | undefined;
205
+ if (!rest.includes("--off")) {
206
+ const provider = flag(rest, "--provider");
207
+ if (provider !== "claude-cli" && provider !== "openai") {
208
+ throw new Error("--provider must be claude-cli or openai (or pass --off)");
209
+ }
210
+ labeler = { provider };
211
+ const model = flag(rest, "--model");
212
+ const baseUrl = flag(rest, "--base-url");
213
+ const apiKeyEnv = flag(rest, "--api-key-env");
214
+ const command = flag(rest, "--command");
215
+ if (model) labeler.model = model;
216
+ if (baseUrl) labeler.baseUrl = baseUrl;
217
+ if (apiKeyEnv) labeler.apiKeyEnv = apiKeyEnv;
218
+ if (command) labeler.command = command;
219
+ }
220
+ const file = writeLabeler(labeler);
221
+ console.log(labeler ? `labeler set to ${labeler.provider} / ${labeler.model} in ${file}` : `labeler turned off in ${file}`);
222
+ console.log("A running page server keeps its old setting until it restarts (it exits after its idle time).");
223
+ return 0;
224
+ }
225
+ console.error(USAGE);
226
+ return 2;
227
+ }
228
+
229
+ /** Removes the Claude Code commands (and with --purge the config and stored graphs), then says what is left. */
230
+ function uninstallAll(args: string[]): number {
231
+ const purge = args.includes("--purge");
232
+ const done = uninstall(purge);
233
+ console.log(done.length > 0 ? done.join("\n") : "nothing to remove");
234
+ if (!purge) console.log("Config and stored graphs were kept; pass --purge to delete them too.");
235
+ console.log("Last steps, to remove the program itself:");
236
+ console.log(" omp plugin uninstall intent-prompt-graph # only if you installed the OMP plugin");
237
+ console.log(" bun remove -g intent-prompt-graph");
238
+ return 0;
239
+ }
240
+
190
241
  async function main(argv: string[]): Promise<number> {
191
242
  const [cmd, ...rest] = argv;
192
243
  try {
@@ -199,6 +250,10 @@ async function main(argv: string[]): Promise<number> {
199
250
  return await open(rest);
200
251
  case "log":
201
252
  return await log(rest);
253
+ case "setup":
254
+ return setup(rest);
255
+ case "uninstall":
256
+ return uninstallAll(rest);
202
257
  default:
203
258
  console.error(USAGE);
204
259
  return 2;
@@ -22,8 +22,9 @@ const WRAPPER_RE = /^\s*<[a-z][\w-]*[\s>]/;
22
22
  /** Marker Claude Code writes when the owner pressed Esc. */
23
23
  const INTERRUPT_RE = /^\[Request interrupted by user[^\]]*\]/;
24
24
 
25
- function claudeDir(): string {
26
- return process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
25
+ /** Claude Code's config directory: `CLAUDE_CONFIG_DIR`, else `~/.claude`. */
26
+ export function claudeDir(env: NodeJS.ProcessEnv = process.env): string {
27
+ return env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
27
28
  }
28
29
 
29
30
  function projectsDir(): string {
package/src/labeler.ts CHANGED
@@ -34,6 +34,8 @@ export interface GraphExtractInput {
34
34
  nodes: { id: string; kind: NodeKind; title: string; rounds?: number }[];
35
35
  edges: { from: string; to: string; kind: EdgeKind }[];
36
36
  };
37
+ /** Present on a tidy-up request: no new turns, the reply only merges nodes to reach about this many. */
38
+ consolidate?: { targetNodes: number };
37
39
  turns: RedactedTurn[];
38
40
  }
39
41
 
@@ -46,16 +48,21 @@ Your goal is to help the human owner understand the entire session in 5 seconds:
46
48
  4. What decisions, pivots, constraints, or course corrections happened ("decision")
47
49
  5. What final paths, architectures, or fixes were chosen/verified ("chosen")
48
50
  6. Repetitive check/review/polling loops collapsed into a single node ("loop", with "rounds")
49
- 7. Tangential clarifying questions branched off the main spine ("side")
51
+ 7. A tangent that left the main line of work for several turns ("side")
50
52
 
51
53
  Rules:
52
54
  - Synthesize crisp, specific titles (<= 8 words). NEVER copy filler openers like "You're right", "Okay", "Not quite", or raw file paths as titles.
53
55
  - When the owner rejects or pushes back on an agent proposal, mark the AGENT's rejected proposal as "rejected" (with the owner's objection as "rationale") and branch the owner's new direction as "decision" or "chosen".
56
+ - "rejected" needs the owner saying no. An alternative that was merely not picked is "option". "decision" needs someone deciding something: never use it for a question, a fact, a status report or a caveat.
57
+ - Fewer nodes is better. A node is one step that changed where the session went: a direction the owner set, a proposal that was rejected, a result that shipped or was verified. These do NOT get a node of their own; fold them into the "desc" of the node they belong to: a question the agent simply answered, a caveat, a warning, a next-step note, a side effect, each item of a list of options or steps.
54
58
  - Merge repetitive back-and-forth checks (like "chk agn" / "chk now" or repeated CI/blocker status polls) into ONE "loop" node with all their turn refs in "turnIds" and an integer "rounds".
55
59
  - Keep the graph concise and high-signal (typically 5-18 nodes). Do not create separate nodes for routine acknowledgements.
56
60
  - Connect nodes with directed edges (from -> to) using kinds: "chosen", "rejected", "option", "decision", "loop", "side", with a short edge "label" (<= 4 words). Every non-goal node should be reachable from the goal.
57
61
  - Without "existingGraph", return the complete first graph for the given turns.
58
- - If "existingGraph" is provided, it outlines the graph built so far (node id, kind, title, rounds; edge from, to, kind). Reply with a PATCH for the new turns, NOT the whole graph: "nodes" holds ONLY nodes that are new or changed, and "edges" holds ONLY new edges. NEVER repeat an unchanged node. Nodes you leave out are kept exactly as they are; you cannot delete a node.
62
+ - If "existingGraph" is provided, it outlines the graph built so far (node id, kind, title, rounds; edge from, to, kind). Reply with a PATCH for the new turns, NOT the whole graph: "nodes" holds ONLY nodes that are new or changed, and "edges" holds ONLY new edges. NEVER repeat an unchanged node. Nodes you leave out are kept exactly as they are.
63
+ - In a patch, first try to extend an existing node: return its "id" with the new turn refs in "turnIds" (and a better "title" or "desc" if the step moved on). Add a new node only when the new turns start a genuinely new step. One owner message plus its reply adds at most ONE new node, plus one "rejected" node if the owner refused something. Most patches add zero or one node.
64
+ - To fold an existing node into another, return {"id":"<node to remove>","mergeInto":"<node that absorbs it>"}. Its turn refs and edges move to the absorbing node.
65
+ - If "consolidate" is provided there are no new turns: the graph has grown too long. Shrink it to about "consolidate.targetNodes" nodes using "mergeInto". Fold questions, caveats, notes, unpicked options and small sub-steps into the decision or result they belong to. Keep the goal, real owner rejections, and the main outcomes. You may also return an absorbing node with a new "title" and "desc" that cover what it absorbed. Return no new nodes.
59
66
  - To change an existing node, return its "id" plus ONLY the fields that change (e.g. "kind" with a matching "badge" and "rationaleLabel", or "rounds"). "turnIds" on a changed node lists only the newly added turn refs; they are added to the ones it already has.
60
67
  - New nodes need ids not used in "existingGraph". New edges may connect new and existing node ids. To change the kind or label of an existing edge, return it again with the same "from" and "to".
61
68
  - An empty "nodes" array is valid when the new turns add nothing to an existing graph.
@@ -259,7 +266,8 @@ function updatedNode(old: GraphNode, rec: Record<string, unknown>, turnTimestamp
259
266
  * Validates the LLM's Decision & Path Graph JSON reply and merges it into the existing graph.
260
267
  * Without an existing graph the reply is the complete first graph. With one, the reply is a patch:
261
268
  * its nodes are added or partially update a node with the same id, its edges are added or replace
262
- * the kind/label of the existing edge with the same from+to. The reply can never delete anything.
269
+ * the kind/label of the existing edge with the same from+to. A node entry with "mergeInto" folds an
270
+ * existing node into another: its turn refs and edges move there, so no turn loses its node.
263
271
  * Node errors throw so callers never commit corrupt graphs; an unusable edge is dropped on its own.
264
272
  *
265
273
  * Args:
@@ -286,6 +294,7 @@ export function parseGraphOutput(raw: string, turnTimestamps: ReadonlyMap<string
286
294
  const byId = new Map<string, GraphNode>();
287
295
  for (const n of existing?.nodes ?? []) byId.set(n.id, n);
288
296
  const seenIds = new Set<string>();
297
+ const mergeInto = new Map<string, string>();
289
298
 
290
299
  for (const item of root.nodes) {
291
300
  if (typeof item !== "object" || item === null) throw bad("node is not an object");
@@ -294,6 +303,11 @@ export function parseGraphOutput(raw: string, turnTimestamps: ReadonlyMap<string
294
303
  if (seenIds.has(id)) throw bad(`duplicate node id ${id}`);
295
304
  seenIds.add(id);
296
305
  const old = byId.get(id);
306
+ const into = optionalString(rec, "mergeInto", 48);
307
+ if (into !== undefined) {
308
+ if (old && into !== id) mergeInto.set(id, into);
309
+ continue;
310
+ }
297
311
  byId.set(id, old ? updatedNode(old, rec, turnTimestamps) : newNode(id, rec, turnTimestamps));
298
312
  }
299
313
 
@@ -338,7 +352,46 @@ export function parseGraphOutput(raw: string, turnTimestamps: ReadonlyMap<string
338
352
  }
339
353
  }
340
354
 
341
- return { title, nodes: [...byId.values()], edges, mode: "llm" };
355
+ if (mergeInto.size === 0) return { title, nodes: [...byId.values()], edges, mode: "llm" };
356
+
357
+ // Follow merge chains (a into b, b into c) to the node that survives. A merge whose chain ends
358
+ // on an unknown node, loops, or would remove the goal is ignored.
359
+ const survivor = (id: string): string => {
360
+ let cur = id;
361
+ for (let hops = 0; hops <= mergeInto.size; hops++) {
362
+ const next = mergeInto.get(cur);
363
+ if (next === undefined) return byId.has(cur) ? cur : id;
364
+ cur = next;
365
+ }
366
+ return id;
367
+ };
368
+ for (const id of [...mergeInto.keys()]) {
369
+ if (byId.get(id)?.kind === "goal" || survivor(id) === id) mergeInto.delete(id);
370
+ }
371
+ for (const id of mergeInto.keys()) {
372
+ const gone = byId.get(id);
373
+ const keepId = survivor(id);
374
+ const keep = byId.get(keepId);
375
+ if (!gone || !keep) continue;
376
+ // Oldest first, so the inspector shows the absorbed turns in the order they happened.
377
+ const turnIds = [...new Set([...keep.turnIds, ...gone.turnIds])].sort(
378
+ (a, b) => (turnTimestamps.get(a) ?? Infinity) - (turnTimestamps.get(b) ?? Infinity),
379
+ );
380
+ byId.set(keepId, { ...keep, turnIds, at: Math.max(keep.at, gone.at) });
381
+ }
382
+ for (const id of mergeInto.keys()) byId.delete(id);
383
+
384
+ const merged: GraphEdge[] = [];
385
+ const seenPairs = new Set<string>();
386
+ for (const e of edges) {
387
+ const from = survivor(e.from);
388
+ const to = survivor(e.to);
389
+ const key = pairKey(from, to);
390
+ if (from === to || seenPairs.has(key)) continue;
391
+ seenPairs.add(key);
392
+ merged.push({ ...e, from, to });
393
+ }
394
+ return { title, nodes: [...byId.values()], edges: merged, mode: "llm" };
342
395
  }
343
396
 
344
397
  /**
package/src/session.ts CHANGED
@@ -9,6 +9,21 @@ import { tailJsonl, type TailEvent } from "./tail";
9
9
  export const BATCH_TURNS = 16;
10
10
  export const BATCH_CHARS = 12_000;
11
11
  export const RETRY_MS = 60_000;
12
+ /** A graph is tidied up when it has this many nodes more than its target size. */
13
+ export const CONSOLIDATE_SLACK = 6;
14
+
15
+ /**
16
+ * Node budget for a session: about one node per three turns, never under 12 or over 40.
17
+ *
18
+ * Args:
19
+ * turnCount (number): Number of turns the graph covers.
20
+ *
21
+ * Returns:
22
+ * number: Target node count.
23
+ */
24
+ export function targetNodes(turnCount: number): number {
25
+ return Math.min(40, Math.max(12, Math.round(turnCount / 3)));
26
+ }
12
27
 
13
28
  export type SnapshotEvent = Extract<ServerEvent, { type: "snapshot" }>;
14
29
 
@@ -43,6 +58,8 @@ export async function openSession(opts: { harness: Harness; ref: SessionRef; con
43
58
  let ready = false;
44
59
  let labelerError: string | undefined;
45
60
  let retry: Timer | undefined;
61
+ /** Node count at the last tidy-up attempt; 0 before the first one. */
62
+ let consolidatedAt = 0;
46
63
  let heuristicGraph: SessionGraph = buildHeuristicGraph([], ref.title);
47
64
 
48
65
  const emit = (ev: ServerEvent) => {
@@ -133,11 +150,36 @@ export async function openSession(opts: { harness: Harness; ref: SessionRef; con
133
150
  return extractFrom(nextBatch());
134
151
  }
135
152
 
153
+ /**
154
+ * Asks the labeler to fold nodes together when the graph has outgrown its budget. Runs again only
155
+ * after the graph has grown by another CONSOLIDATE_SLACK nodes, so a reply that merges too little
156
+ * is not retried on every turn. A failed tidy-up keeps the graph as it is.
157
+ */
158
+ async function consolidate(): Promise<void> {
159
+ const before = store.graph;
160
+ if (!before || stopped) return;
161
+ const target = targetNodes(store.processedTurnIds.size);
162
+ if (before.nodes.length < Math.max(target, consolidatedAt) + CONSOLIDATE_SLACK) return;
163
+ consolidatedAt = before.nodes.length;
164
+ let graph: SessionGraph;
165
+ try {
166
+ const input: GraphExtractInput = { ...buildInput([]), consolidate: { targetNodes: target } };
167
+ graph = await extractGraph(labelerCfg, input, timestampsMap(), before);
168
+ } catch {
169
+ return;
170
+ }
171
+ if (stopped || graph.nodes.length >= before.nodes.length) return;
172
+ consolidatedAt = graph.nodes.length;
173
+ store.saveGraph(graph, []);
174
+ emit({ type: "graph", graph });
175
+ }
176
+
136
177
  async function drain(): Promise<void> {
137
178
  if (!llmEnabled || busy || stopped) return;
138
179
  busy = true;
139
180
  try {
140
181
  await extractFrom(nextBatch());
182
+ await consolidate();
141
183
  } catch (err) {
142
184
  if (stopped) return;
143
185
  setLabelerError(err instanceof Error ? err.message : String(err));
package/src/setup.ts ADDED
@@ -0,0 +1,133 @@
1
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { configFile, isLabelerConfigured, type LabelerConfig } from "./config";
5
+ import { claudeDir } from "./harness/claude";
6
+
7
+ /** The Claude Code slash-command files shipped in this package. */
8
+ const CLAUDE_COMMANDS = join(import.meta.dir, "../integrations/claude/commands");
9
+
10
+ /** True when `path` is a symlink that points into this package's command files. */
11
+ function isOurLink(path: string, target: string): boolean {
12
+ try {
13
+ return lstatSync(path).isSymbolicLink() && readlinkSync(path) === target;
14
+ } catch {
15
+ return false;
16
+ }
17
+ }
18
+
19
+ /**
20
+ * Links this package's slash commands into Claude Code's commands directory.
21
+ * A file of the same name that is not our link is left alone and reported.
22
+ *
23
+ * Args:
24
+ * env (NodeJS.ProcessEnv): Environment map; `CLAUDE_CONFIG_DIR` replaces `~/.claude`.
25
+ *
26
+ * Returns:
27
+ * string[]: One line per command file, saying what was done.
28
+ */
29
+ export function setupClaude(env: NodeJS.ProcessEnv = process.env): string[] {
30
+ const dir = join(claudeDir(env), "commands");
31
+ mkdirSync(dir, { recursive: true });
32
+ return readdirSync(CLAUDE_COMMANDS)
33
+ .filter((f) => f.endsWith(".md"))
34
+ .sort()
35
+ .map((f) => {
36
+ const target = join(CLAUDE_COMMANDS, f);
37
+ const link = join(dir, f);
38
+ const name = `/${f.slice(0, -3)}`;
39
+ if (isOurLink(link, target)) return `${name}: already set up`;
40
+ let stale = false;
41
+ try {
42
+ stale = lstatSync(link).isSymbolicLink() && !existsSync(link);
43
+ } catch {
44
+ // Nothing at that path yet.
45
+ }
46
+ if (stale) unlinkSync(link);
47
+ else if (existsSync(link)) return `${name}: skipped, ${link} exists and is not ours`;
48
+ symlinkSync(target, link);
49
+ return `${name}: added (${link})`;
50
+ });
51
+ }
52
+
53
+ /**
54
+ * Removes the slash-command links that setupClaude created. Files that are not our links stay.
55
+ *
56
+ * Args:
57
+ * env (NodeJS.ProcessEnv): Environment map; `CLAUDE_CONFIG_DIR` replaces `~/.claude`.
58
+ *
59
+ * Returns:
60
+ * string[]: One line per removed link.
61
+ */
62
+ export function removeClaude(env: NodeJS.ProcessEnv = process.env): string[] {
63
+ const dir = join(claudeDir(env), "commands");
64
+ const out: string[] = [];
65
+ for (const f of readdirSync(CLAUDE_COMMANDS)) {
66
+ const link = join(dir, f);
67
+ if (!isOurLink(link, join(CLAUDE_COMMANDS, f))) continue;
68
+ unlinkSync(link);
69
+ out.push(`removed ${link}`);
70
+ }
71
+ return out;
72
+ }
73
+
74
+ /**
75
+ * Writes the `labeler` section of config.json and keeps every other setting. `undefined` removes
76
+ * the section, which turns the labeler off.
77
+ *
78
+ * Args:
79
+ * labeler (LabelerConfig | undefined): New labeler settings, or undefined to remove them.
80
+ * env (NodeJS.ProcessEnv): Environment map for resolving the config file.
81
+ *
82
+ * Returns:
83
+ * string: Path of the config file that was written.
84
+ */
85
+ export function writeLabeler(labeler: LabelerConfig | undefined, env: NodeJS.ProcessEnv = process.env): string {
86
+ if (labeler && !isLabelerConfigured(labeler)) {
87
+ throw new Error(
88
+ labeler.model ? "provider openai needs --base-url <url>" : "a labeler needs --model <name>",
89
+ );
90
+ }
91
+ const file = configFile(env);
92
+ let json: Record<string, unknown> = {};
93
+ if (existsSync(file)) {
94
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
95
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
96
+ throw new Error(`${file} must hold a JSON object`);
97
+ }
98
+ json = { ...parsed };
99
+ }
100
+ if (labeler) json.labeler = labeler;
101
+ else delete json.labeler;
102
+ mkdirSync(dirname(file), { recursive: true });
103
+ writeFileSync(file, `${JSON.stringify(json, null, 2)}\n`);
104
+ return file;
105
+ }
106
+
107
+ /** Directory holding the stored graphs of every session. */
108
+ export function stateDir(env: NodeJS.ProcessEnv = process.env): string {
109
+ return join(env.XDG_STATE_HOME || join(homedir(), ".local", "state"), "intent-prompt-graph");
110
+ }
111
+
112
+ /**
113
+ * Removes what this tool put on the machine outside its own package: the Claude Code command
114
+ * links, and with `purge` also the config file and every stored graph.
115
+ *
116
+ * Args:
117
+ * purge (boolean): Also delete the config directory and the stored graphs.
118
+ * env (NodeJS.ProcessEnv): Environment map for resolving the directories.
119
+ *
120
+ * Returns:
121
+ * string[]: One line per thing removed.
122
+ */
123
+ export function uninstall(purge: boolean, env: NodeJS.ProcessEnv = process.env): string[] {
124
+ const out = removeClaude(env);
125
+ if (purge) {
126
+ for (const dir of [dirname(configFile(env)), stateDir(env)]) {
127
+ if (!existsSync(dir)) continue;
128
+ rmSync(dir, { recursive: true });
129
+ out.push(`removed ${dir}`);
130
+ }
131
+ }
132
+ return out;
133
+ }
package/web/view.ts CHANGED
@@ -247,6 +247,13 @@ export function summarizeGraph(graph: SessionGraph): GraphSummary {
247
247
  };
248
248
  }
249
249
 
250
+ /** Counts owner rejections and merely unpicked options apart, e.g. "4 rejected, 18 not chosen". */
251
+ function notTakenLabel(nodes: readonly GraphNode[]): string {
252
+ const rejected = nodes.filter((n) => n.kind === "rejected").length;
253
+ const options = nodes.length - rejected;
254
+ return [rejected > 0 ? `${rejected} rejected` : "", options > 0 ? `${options} not chosen` : ""].filter(Boolean).join(", ");
255
+ }
256
+
250
257
  function turnsLabel(n: GraphNode): string {
251
258
  const count = n.turnIds.length;
252
259
  const time = clock(n.at);
@@ -290,7 +297,7 @@ export function paintSidebar(s: State, els: Els): void {
290
297
  const pills = [
291
298
  `${turnCount} turns → ${nodeCount} nodes`,
292
299
  sum.decisionsCount > 0 ? `${sum.decisionsCount} decisions` : "",
293
- sum.rejected.length > 0 ? `${sum.rejected.length} ruled out` : "",
300
+ notTakenLabel(sum.rejected),
294
301
  sum.loopsCount > 0 ? `${sum.loopsCount} loops collapsed` : "",
295
302
  ]
296
303
  .filter(Boolean)
@@ -453,8 +460,8 @@ export function paintTimeline(s: State, els: Els): void {
453
460
  summaryLine("Goal", sum.goal?.title ?? "No goal identified yet", sum.goal) +
454
461
  summaryLine("Now", sum.now?.title ?? "Waiting for turns in this session…", sum.now) +
455
462
  summaryLine(
456
- "Rejected",
457
- ruledOut === 0 ? "Nothing ruled out yet" : `${ruledOut} ${ruledOut === 1 ? "path" : "paths"} ruled out · show the first`,
463
+ "Not taken",
464
+ ruledOut === 0 ? "Nothing rejected yet" : `${notTakenLabel(sum.rejected)} · show the first`,
458
465
  sum.rejected[0],
459
466
  ),
460
467
  );