Live terminal visualization of Omnigraph operations


omnigraph-viz is a Claude Code mod that shows, live in your terminal, what an agent does to an Omnigraph graph. Every omnigraph command Claude runs lands in a pane beside the conversation: a browser that follows the agent through the graph, and a feed of every operation.
Epic › Offline editing & sync › contains › ….● label, links as thin dotted lines.◆ query ready · 5).NEW.enter shows the command and its output.◉ og · main · 14 ops · +3n./og replay <ledger> plays a recorded session offline, with no Omnigraph needed: a demo that can't fail on stage.The mod only watches. It never changes the agent's command or what the agent reads back, and a bug in the viz never turns into a tool error.
omnigraph CLI on your PATH, or its path in the omnigraphBin option. The mod follows both 0.14's --target and the older --store/--server flags.In Claude Code:
/plugin marketplace add pronskiy/omnigraph-claude-mod
/plugin install omnigraph-viz@omnigraph-claude-mod
Or run it from a clone:
git clone https://github.com/pronskiy/omnigraph-claude-mod
cd omnigraph-claude-mod
claude --plugin-dir ./omnigraph-viz
Open the pane with /og, then work with Omnigraph as usual: ask Claude to query or change a graph. The mod records operations from the first omnigraph command whether or not the pane is open.
/og | toggle the pane (it opens with the keyboard) |
/og replay <ledger.jsonl> [speed] | replay a recorded session; 0.5 is half speed, 2 double |
/og stop | end a replay, back to the live session |
/og clear | reset the Feed (the graph stays) |
g / f | Graph / Feed tab |
| click the graph | hand it the keys (once; until then the arrows move between the pane's buttons) |
| ↑ / ↓ | select in the rightmost column |
| → or ⏎ or ⌥↓ | open the selection as a new column |
| ← or ⌫ or ⌥↑ | back one column |
l | follow the agent again |
enter (Feed) | show an operation's command and output; select it to see it in the browser |
esc | keys back to the prompt |
For Finder's ⌘↓ / ⌘↑ in iTerm2, map them to send ⌥↓ / ⌥↑ (Profile → Keys → Key Mappings → Send Escape Sequence [1;3B / [1;3A).
From a clone, start Claude Code with the plugin and replay the recorded demo, an agent triaging a bug bash on the dev-graph cookbook:
/og replay demos/dev-graph-triage.jsonl
To run it live with a real agent, see the runbook in docs/demo.md: scripts/setup-demo-graph.sh builds the store, and demos/dev-graph-triage.prompt.txt is the prompt.
| Option | Default | What it does |
|---|---|---|
omnigraphBin | omnigraph | Name or absolute path of the CLI. When the bare name isn't on Claude Code's PATH, the mod also asks your login shell and tries the usual install folders. |
maxGhostNodes | 2000 | Largest graph loaded whole; a bigger one keeps its best-connected nodes |
ledgerDir | .omnigraph-viz | Where session ledgers go, relative to the session directory |
enrich | true | Run omnigraph … --json in the background for graph detail (export once, commit changes after writes) |
debug | false | Log viz errors as dim lines in the transcript |
With --plugin-dir, pass options as settings:
claude --plugin-dir ./omnigraph-viz \
--settings '{"pluginConfigs":{"omnigraph-viz":{"options":{"omnigraphBin":"/Users/you/.local/bin/omnigraph"}}}}'
tool.call hook spots omnigraph invocations in Bash commands (through cd … &&, env prefixes and pipes). It lets each one run untouched and parses its human or --json output.omnigraph calls on the same store: export once to load the graph, and commit list / commit changes after each write. These give the exact nodes and edges that changed. Reads light the nodes their result rows name..omnigraph-viz/. The mod adds a .gitignore there, because ledgers hold command output.npm install
claude --plugin-dir ./omnigraph-viz # once: Claude Code lays the mod API types that tsc needs next to the plugin
npm run check # tsc, claude plugin validate, claude plugin test
Hot reload: with claude --plugin-dir ./omnigraph-viz, saving a file reloads the mod.
.claude-plugin/marketplace.json the marketplace (one plugin)
omnigraph-viz/
hooks/register.tsx wiring: hooks, commands, the pane, state
hooks/explore.tsx the browser's Client: draws rows, posts keys
src/capture/ command tokenizer, classifier, output parser
src/enrich/ background omnigraph calls, read highlighting
src/model/ ledger, reducer, view state
src/graph/ graph model, effects, palette
src/browse/ browser model and star layout (pure)
src/render/ canvas, browser drawing, pane, feed
src/replay/ /og replay player
tests/ claude plugin test suites
demos/ a recorded demo ledger and its prompt
scripts/ dev-only Node and shell scripts
The tests stand in for the engine: they answer every $ call themselves and mount the pane with $.ui.mount. They need no file system, network or omnigraph.
hooks/register.tsx 604 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import { beginOps, endLines } from '../src/capture/capture'
5import { parseOutput } from '../src/capture/parse-output'
6import { findInvocations } from '../src/capture/tokenize'
7import {
8 addressesGraph, commitChangesArgv, commitListArgv, exportArgv, parseChanges, parseCommits, pickCommit, schemaArgv, schemaSourceOf,
9 targetKey,
10} from '../src/enrich/cli'
11import { buildMatchIndex, matchCells } from '../src/enrich/highlight'
12import { binCandidates, isPlainName, pathFromShell } from '../src/enrich/locate'
13import { JobQueue } from '../src/enrich/queue'
14import { foldExport, parseEdgeEnds } from '../src/graph/ghost'
15import { LedgerWriter, decodeLedger, ledgerPathFor } from '../src/model/ledger'
16import type { LedgerIO } from '../src/model/ledger'
17import { emptyViz, reduce } from '../src/model/reduce'
18import { INITIAL_UI, INITIAL_VIEW, toView } from '../src/model/state'
19import { BrailleCanvas } from '../src/render/braille'
20import { statusText } from '../src/render/format'
21import { browserRowsFor } from '../src/render/graph-view'
22import type { GraphViewData } from '../src/render/graph-view'
23import { drawPane } from '../src/render/pane'
24import { actionFor } from '../src/render/explore'
25import { opName, Scene } from '../src/render/scene'
26import { OG_HINT, parseOgArgs } from '../src/replay/command'
27import { Player, readReplay } from '../src/replay/player'
28import { basename, resolvePath } from '../src/util/path'
29import type { GraphState, LedgerLine, OpEvent, OpIntent, UiState, VizState } from '../types'
30
31const MOD_VERSION = '0.1.0'
32const PANE = 'omnigraph'
33const FRAME_MS = 33
34
35interface Config {
36 bin: string
37 ledgerDir: string
38 maxGhostNodes: number
39 isEnriching: boolean
40 isDebug: boolean
41}
42
43/** What the pane can show: a reduced state and the scene drawn from the same lines. */
44interface Show {
45 viz: VizState
46 scene: Scene
47}
48
49interface Session extends Show {
50 cwd: string
51 /** Created by the first op, so a session without omnigraph leaves no files. */
52 ledger: LedgerWriter | undefined
53 /** After `session.end`: background jobs may still finish, but the status line stays clear. */
54 isEnded?: boolean
55}
56
57/** A recorded ledger playing in the pane instead of the live session (which carries on, unseen). */
58interface Replay extends Show {
59 name: string
60 player: Player
61 hasGraph: boolean
62 timer: { cancel: () => void } | undefined
63}
64
65// $.state: small, survives hot reload, redraws its readers. Declared here so the validator can see them.
66const uiAtom = atom({ plugin: 'omnigraph-viz', key: 'ui' } as const, INITIAL_UI)
67const viewAtom = atom({ plugin: 'omnigraph-viz', key: 'view' } as const, INITIAL_VIEW)
68const ledgerPathAtom = atom({ plugin: 'omnigraph-viz', key: 'ledgerPath' } as const, null)
69
70// Module memory: rebuilt from the ledger on every (re)load.
71let config: Config = { bin: 'omnigraph', ledgerDir: '.omnigraph-viz', maxGhostNodes: 2000, isEnriching: true, isDebug: false }
72let session: Session | undefined
73let replay: Replay | undefined
74let queue: JobQueue | undefined
75/** Bootstrap progress for the graph `graphKey` names; `ready` once a graph line exists. */
76let graphState: GraphState = 'none'
77let graphMessage: string | null = null
78let graphKey: string | null = null
79/** The browser's canvas while the Graph tab is on screen; the animation loop redraws it. */
80let canvas: BrailleCanvas | null = null
81let frameTimer: { cancel: () => void } | undefined
82let isFrameBusy = false
83/** Where `omnigraph` really is, once a bare name failed to start on Claude Code's PATH. */
84let resolvedBin: string | undefined
85/** HOME, read once: `null` until then. */
86let homeCache: string | undefined | null = null
87
88function io($: EngineInterface): LedgerIO {
89 return {
90 write: (path, text) => $.fs.write(path, text),
91 onError: err => debug($, err),
92 }
93}
94
95function debug($: EngineInterface, err: unknown): void {
96 if (config.isDebug) $.ui.log(`omnigraph-viz: ${err instanceof Error ? err.message : String(err)}`)
97}
98
99/** The pane shows the replay while one is on, else the live session. */
100function shown(): Show | undefined {
101 return replay ?? session
102}
103
104/** The one path every line takes, live or replayed: the reducer, then the scene. */
105function feed(show: Show, line: LedgerLine): void {
106 const before = show.viz.ghost
107 show.viz = reduce(show.viz, line)
108 show.scene.onLine(line, before, show.viz.ghost)
109}
110
111/** Every live change goes through here: ledger, then reducer and scene, then animation. */
112function apply($: EngineInterface, s: Session, line: LedgerLine): void {
113 s.ledger?.append(line, io($))
114 if (line.t === 'graph') graphKey = targetKey(line.target, line.cwd)
115 feed(s, line)
116 if (shown() === s && (line.t === 'graph' || line.t === 'diff' || line.t === 'touch')) startAnimation($)
117}
118
119/** The view and status line of whatever the pane shows. */
120async function publish($: EngineInterface): Promise<void> {
121 const r = replay
122 const view = r
123 ? toView(r.viz, r.viz.ghost ? 'ready' : r.hasGraph ? 'loading' : 'none', null, {
124 speed: r.player.speed,
125 progress: r.player.progress,
126 isDone: r.player.isDone,
127 })
128 : session
129 ? toView(session.viz, graphState, graphMessage)
130 : INITIAL_VIEW
131 await update($, viewAtom, () => view)
132 $.ui.status(view.counters.ops > 0 && !session?.isEnded ? statusText(view) : undefined)
133}
134
135/** On the first op: the ledger file, a `.gitignore` beside it, and the session line. */
136async function ensureLedger($: EngineInterface, s: Session, now: number): Promise<void> {
137 if (s.ledger) return
138 const path = ledgerPathFor(s.cwd, config.ledgerDir, now)
139 const ignore = `${path.slice(0, path.lastIndexOf('/'))}/.gitignore`
140 if (!(await $.fs.exists(ignore))) await $.fs.write(ignore, '*\n')
141 await update($, ledgerPathAtom, () => path)
142 s.ledger = new LedgerWriter(path)
143 apply($, s, { v: 1, t: 'session', at: now, cwd: s.cwd, mod: MOD_VERSION })
144}
145
146/**
147 * Rehydrates from the ledger `$.state` remembers (a hot reload), else starts
148 * a new one. The scene is laid out once from the final graph: replaying every
149 * diff's layout would make a reload as slow as the session was long.
150 */
151async function openSession($: EngineInterface, cwd: string): Promise<Session> {
152 const s: Session = { cwd, ledger: undefined, viz: emptyViz(), scene: new Scene() }
153 const previous = await read($, ledgerPathAtom)
154 if (previous === null) return s
155 try {
156 const { lines } = decodeLedger(await $.fs.read(previous))
157 let graphLine: Extract<LedgerLine, { t: 'graph' }> | undefined
158 for (const line of lines) {
159 s.viz = reduce(s.viz, line)
160 if (line.t === 'graph') graphLine = line
161 }
162 if (graphLine && s.viz.ghost) {
163 graphKey = targetKey(graphLine.target, graphLine.cwd)
164 graphState = 'ready'
165 s.scene.onLine({ ...graphLine, at: await $.clock.now(), graph: s.viz.ghost }, null, s.viz.ghost)
166 }
167 s.ledger = new LedgerWriter(previous, lines)
168 return s
169 } catch {
170 // file gone: start over
171 return { cwd, ledger: undefined, viz: emptyViz(), scene: new Scene() }
172 }
173}
174
175/**
176 * Finds `omnigraph` the way the person's terminal does: their login shell
177 * (whose profile usually adds ~/.local/bin and the like), then the usual
178 * install folders. Claude Code's own PATH may lack what its Bash tool has.
179 */
180async function locateOmnigraph($: EngineInterface): Promise<string | undefined> {
181 if (!isPlainName(config.bin)) return undefined
182 const shell = (await $.env.get('SHELL')) ?? '/bin/sh'
183 const viaShell = await $.process
184 .run([shell, '-lic', `command -v ${config.bin}`], { timeoutMs: 5000 })
185 .then(r => pathFromShell(r.stdout, config.bin))
186 .catch(() => undefined)
187 if (viaShell !== undefined) return viaShell
188 for (const path of binCandidates(await $.env.get('HOME'), config.bin)) {
189 if (await $.fs.exists(path)) return path
190 }
191 return undefined
192}
193
194/** Runs `omnigraph <args>`; if the binary does not start, locates it once and retries. */
195async function runOmnigraph($: EngineInterface, args: readonly string[], cwd: string) {
196 const run = (bin: string) => $.process.run([bin, ...args], { cwd, timeoutMs: 20_000 })
197 if (resolvedBin !== undefined) return run(resolvedBin)
198 try {
199 return await run(config.bin)
200 } catch (err) {
201 const found = await locateOmnigraph($)
202 if (found === undefined) {
203 throw new Error(
204 `can't find \`${config.bin}\` on Claude Code's PATH: set the omnigraphBin option to its full path (\`which ${config.bin}\`)`,
205 )
206 }
207 resolvedBin = found
208 return run(found)
209 }
210}
211
212function enqueue($: EngineInterface, at: number, run: () => Promise<void>): void {
213 queue ??= new JobQueue(() => $.clock.now(), err => debug($, err))
214 queue.push({ at, run })
215}
216
217/** Schema (for edge endpoint types) and export of the graph the op ran against → a `graph` line. */
218async function bootstrap($: EngineInterface, s: Session, intent: OpIntent): Promise<void> {
219 const run = (argv: string[]) => runOmnigraph($, argv.slice(1), intent.cwd)
220 try {
221 const schema = await run(schemaArgv(config.bin, intent.target)).catch(() => undefined)
222 const edgeEnds = parseEdgeEnds(schemaSourceOf(schema?.stdout ?? '') ?? '')
223 const out = await run(exportArgv(config.bin, intent.target))
224 if (out.exitCode !== 0) {
225 const failure = parseOutput(out.stdout, out.stderr, true)
226 throw new Error(failure.kind === 'error' ? failure.message : `exit ${out.exitCode}`)
227 }
228 // Over `$.process.run`'s 4 MiB cap the export is cut: start touched-only instead.
229 const graph = out.isStdoutTruncated
230 ? { nodes: [], edges: [], truncated: true, edgeEnds }
231 : foldExport(out.stdout, edgeEnds, config.maxGhostNodes)
232 apply($, s, { v: 1, t: 'graph', at: await $.clock.now(), target: intent.target, cwd: intent.cwd, graph })
233 graphState = 'ready'
234 graphMessage = null
235 } catch (err) {
236 graphState = 'failed'
237 graphMessage = (err instanceof Error ? err.message : String(err)).slice(0, 160)
238 }
239 await publish($)
240}
241
242/** The commit a write op made → its changes → a `diff` line. */
243async function enrichWrite($: EngineInterface, s: Session, op: OpEvent, branch: string, endedAt: number): Promise<void> {
244 if (!s.viz.ghost) return
245 const run = (argv: string[]) => runOmnigraph($, argv.slice(1), op.intent.cwd)
246 const list = await run(commitListArgv(config.bin, op.intent.target, branch))
247 const consumed = new Set((s.ledger?.lines ?? []).flatMap(l => (l.t === 'diff' ? [l.commitId] : [])))
248 const commitId = pickCommit(parseCommits(list.stdout), op.startedAt, endedAt, consumed)
249 if (commitId === undefined) return
250 const changes = await run(commitChangesArgv(config.bin, op.intent.target, commitId))
251 const parsed = parseChanges(changes.stdout)
252 if (parsed.changes.length === 0) return
253 apply($, s, { v: 1, t: 'diff', at: await $.clock.now(), opId: op.id, commitId, ...parsed })
254}
255
256/** After an op ends: bootstrap the graph once, light a read's nodes, fetch a write's diff. */
257function enrich($: EngineInterface, s: Session, op: OpEvent, end: LedgerLine): void {
258 if (!config.isEnriching || end.t !== 'op.end') return
259 const key = targetKey(op.intent.target, op.intent.cwd)
260 const o = end.outcome
261 const isWrite = end.status === 'ok' && (o.kind === 'change' || o.kind === 'load')
262 // Bootstrap once; after a failure, retry for another graph or once a write on this one succeeded.
263 const needsBootstrap = graphState === 'none' || (graphState === 'failed' && (key !== graphKey || isWrite))
264 if (addressesGraph(op.intent.verb) && needsBootstrap) {
265 graphState = 'loading'
266 graphKey = key
267 enqueue($, end.at, () => bootstrap($, s, op.intent))
268 }
269 // Only the session's graph is drawn: another graph's ops stay in the Feed alone.
270 if (end.status !== 'ok' || key !== graphKey) return
271 if (o.kind === 'read' && o.cells.length > 0) {
272 enqueue($, end.at, async () => {
273 if (!s.viz.ghost) return
274 const { nodeIds, isExact } = matchCells(o.cells, buildMatchIndex(s.viz.ghost))
275 if (nodeIds.length > 0) apply($, s, { v: 1, t: 'touch', at: await $.clock.now(), opId: op.id, nodeIds, isExact })
276 })
277 }
278 const branch = o.kind === 'change' || o.kind === 'load' ? o.branch : o.kind === 'branch' && o.action === 'merged' ? o.into : undefined
279 if (branch) enqueue($, end.at, () => enrichWrite($, s, op, branch, end.at))
280}
281
282async function startCapture($: EngineInterface, command: string, toolUseId: string, agentId: string | undefined): Promise<OpEvent[]> {
283 const s = session
284 // Tokenize before any $ call: most Bash commands are not omnigraph.
285 if (!s || findInvocations(command, '/', config.bin).length === 0) return []
286 const now = await $.clock.now()
287 await ensureLedger($, s, now)
288 if (homeCache === null) homeCache = await $.env.get('HOME')
289 const home = homeCache
290 const ops = beginOps({
291 command,
292 toolUseId,
293 cwd: await $.session.cwd(),
294 bin: config.bin,
295 now,
296 ...(agentId !== undefined ? { agentId } : {}),
297 ...(home !== undefined ? { home } : {}),
298 })
299 for (const op of ops) apply($, s, { v: 1, t: 'op.start', at: op.startedAt, op })
300 if (ops.length > 0) await publish($)
301 return ops
302}
303
304async function finishCapture($: EngineInterface, ops: readonly OpEvent[], r: Parameters<typeof endLines>[1]): Promise<void> {
305 const s = session
306 if (!s || ops.length === 0) return
307 const ends = endLines(ops, r, await $.clock.now())
308 for (const line of ends) apply($, s, line)
309 ops.forEach((op, i) => enrich($, s, op, ends[i]!))
310 await publish($)
311}
312
313function stopAnimation(): void {
314 frameTimer?.cancel()
315 frameTimer = undefined
316}
317
318/** Runs frames while the Graph tab is on screen and something moves; idles otherwise. */
319function startAnimation($: EngineInterface): void {
320 if (frameTimer || !canvas) return
321 frameTimer = $.clock.every(FRAME_MS, () => void frame($))
322}
323
324async function frame($: EngineInterface): Promise<void> {
325 if (isFrameBusy) return
326 const c = canvas
327 if (!c) {
328 stopAnimation()
329 return
330 }
331 isFrameBusy = true
332 try {
333 const now = await $.clock.now()
334 // Replay lines due by now play first, so a frame never steps the layout past one.
335 const isNewLines = playDue(now)
336 const show = shown()
337 if (!show) {
338 stopAnimation()
339 return
340 }
341 show.scene.tick(now)
342 // The browser is a Client: its pane redraws it, and the pane's draw renders the frame.
343 $.ui.invalidate('ui.render')
344 if (isNewLines) await publish($)
345 if (!show.scene.isAnimating(now)) stopAnimation()
346 } catch (err) {
347 debug($, err)
348 stopAnimation()
349 } finally {
350 isFrameBusy = false
351 }
352}
353
354/** The selection link: the op's nodes light up again on the graph and keep their labels. */
355async function selectOp($: EngineInterface, id: string): Promise<void> {
356 const ui = await update($, uiAtom, u => ({ ...u, selectedOpId: u.selectedOpId === id ? null : id }))
357 const show = shown()
358 const ghost = show?.viz.ghost
359 if (!show || ui.selectedOpId === null || !ghost) {
360 if (show && ghost) {
361 show.scene.unfocus(ghost, await $.clock.now())
362 startAnimation($)
363 } else if (show) show.scene.pinned = []
364 return
365 }
366 const op = show.viz.ops.find(o => o.id === ui.selectedOpId)
367 show.scene.focus(show.viz.touches[ui.selectedOpId] ?? [], ghost, await $.clock.now(), op ? opName(op.intent) : undefined)
368 startAnimation($)
369}
370
371/** The Graph tab's browser: a canvas sized to the pane, drawn now. */
372async function graphView($: EngineInterface, show: Show | undefined, columns: number, bodyRows: number, ghost: GraphViewData['ghost']): Promise<GraphViewData> {
373 // A truncated graph says so in a row of its own under the browser.
374 const rows = browserRowsFor(bodyRows) - (ghost.truncated ? 1 : 0)
375 let runs: GraphViewData['runs'] = null
376 if (show?.viz.ghost) {
377 if (!canvas || canvas.cols !== columns || canvas.rows !== rows) canvas = new BrailleCanvas(columns, rows)
378 const now = await $.clock.now()
379 canvas.clear()
380 show.scene.drawFrame(canvas, show.viz.ghost, now)
381 runs = canvas.runs()
382 // Only while something moves: each frame redraws the pane, and this draw must not restart a loop that just stopped.
383 if (show.scene.isAnimating(now)) startAnimation($)
384 } else {
385 canvas = null
386 }
387 return { ghost, columns, rows, runs, isBrowsing: show ? !show.scene.isFollowing : false, recent: show?.viz.ops.slice(-3) ?? [] }
388}
389
390/** Plays every replay line now due; true when any did. */
391function playDue(now: number): boolean {
392 const r = replay
393 if (!r) return false
394 const lines = r.player.due(now)
395 for (const line of lines) feed(r, line)
396 return lines.length > 0
397}
398
399/** The replay's clock: plays what is due, publishes, and sleeps until the next line. A failure ends the replay. */
400async function pumpReplay($: EngineInterface, r: Replay): Promise<void> {
401 r.timer = undefined
402 if (replay !== r) return
403 try {
404 const now = await $.clock.now()
405 if (playDue(now)) {
406 startAnimation($)
407 await publish($)
408 }
409 const next = r.player.nextAt
410 if (replay === r && next !== undefined) r.timer = $.clock.after(Math.max(0, next - now), () => void pumpReplay($, r))
411 } catch (err) {
412 debug($, err)
413 if (replay === r) {
414 stopReplay()
415 await publish($).catch(() => undefined)
416 }
417 }
418}
419
420function stopReplay(): void {
421 replay?.timer?.cancel()
422 replay = undefined
423}
424
425/** `/og replay <path> [speed]`: reads and checks the ledger, then plays it in the pane's Graph tab. */
426async function startReplay($: EngineInterface, path: string, speed: number): Promise<string> {
427 if (homeCache === null) homeCache = await $.env.get('HOME')
428 const file = resolvePath(session?.cwd ?? (await $.session.cwd()), path, homeCache)
429 let text: string
430 try {
431 text = await $.fs.read(file)
432 } catch (err) {
433 return `Can't read ${path}: ${err instanceof Error ? err.message : String(err)}`
434 }
435 const loaded = readReplay(text)
436 if ('error' in loaded) return `Can't replay ${path}: ${loaded.error}`
437 // Everything that can fail before the switch happens first, so a running replay is never left half-stopped.
438 const r: Replay = {
439 name: basename(file),
440 player: new Player(loaded.lines, speed, Math.round(await $.clock.now())),
441 hasGraph: loaded.lines.some(line => line.t === 'graph'),
442 viz: emptyViz(),
443 scene: new Scene(),
444 timer: undefined,
445 }
446 stopReplay()
447 if (session) session.scene.pinned = []
448 replay = r
449 try {
450 await update($, uiAtom, (u): UiState => ({ ...u, tab: 'graph', selectedOpId: null }))
451 await $.ui.open({ id: PANE, title: 'omnigraph', focus: true })
452 await pumpReplay($, r)
453 await publish($)
454 } catch (err) {
455 debug($, err)
456 if (replay === r) stopReplay()
457 await publish($).catch(() => undefined)
458 return `Couldn't replay ${path}: ${err instanceof Error ? err.message : String(err)}`
459 }
460 return `Replaying ${r.name} at ${speed}×, about ${Math.round(r.player.durationMs / 1000)} s. /og stop ends it.`
461}
462
463export const register: Register = (on, options) => {
464 config = {
465 bin: typeof options.omnigraphBin === 'string' ? options.omnigraphBin : 'omnigraph',
466 ledgerDir: typeof options.ledgerDir === 'string' ? options.ledgerDir : '.omnigraph-viz',
467 maxGhostNodes: typeof options.maxGhostNodes === 'number' ? options.maxGhostNodes : 2000,
468 isEnriching: options.enrich !== false,
469 isDebug: options.debug === true,
470 }
471
472 on('session.start', async ($, e, next) => {
473 try {
474 await $.command.register({
475 name: 'og',
476 description: 'Omnigraph viz: toggle the pane, replay a recorded session, or reset the view',
477 argumentHint: OG_HINT,
478 })
479 stopReplay()
480 graphState = 'none'
481 graphMessage = null
482 graphKey = null
483 session = await openSession($, e.cwd)
484 await publish($)
485 } catch (err) {
486 debug($, err)
487 }
488 return next(e)
489 })
490
491 on('session.end', async ($, e, next) => {
492 // `/clear` raises session.end but no session.start follows: the session goes on.
493 if (e.reason !== 'clear') {
494 if (session) session.isEnded = true
495 stopReplay()
496 }
497 stopAnimation()
498 $.ui.status(undefined)
499 return next(e)
500 })
501
502 on('command.run', { command: 'og' }, async ($, e) => {
503 const cmd = parseOgArgs(e.args)
504 if (cmd.kind === 'usage') return { text: cmd.message }
505 if (cmd.kind === 'replay') return { text: await startReplay($, cmd.path, cmd.speed) }
506 if (cmd.kind === 'stop') {
507 if (!replay) return { text: 'No replay is running.' }
508 stopReplay()
509 if (session) session.scene.pinned = []
510 await update($, uiAtom, u => ({ ...u, selectedOpId: null }))
511 await publish($)
512 return { text: 'Replay stopped; back to the live session.' }
513 }
514 if (cmd.kind === 'clear') {
515 stopReplay()
516 if (session) {
517 // The Feed starts over; the graph stays, so the Graph tab keeps working.
518 session.viz = { ...emptyViz(), ghost: session.viz.ghost }
519 }
520 await publish($)
521 return { text: 'Omnigraph viz cleared.' }
522 }
523 const isShown = (await $.ui.panes()).some(p => p.id === PANE && p.isShown)
524 if (isShown) {
525 await $.ui.close({ id: PANE })
526 return { text: 'Omnigraph viz closed.' }
527 }
528 // Focused, so g / f / Tab / Enter work at once; Esc hands the keys back to the prompt.
529 await $.ui.open({ id: PANE, title: 'omnigraph', focus: true })
530 return { text: 'Omnigraph viz opened.' }
531 })
532
533 // Observer only: the command and the result pass through untouched. Every
534 // Bash call comes through (a custom omnigraphBin need not say "omnigraph");
535 // startCapture tokenizes before touching $.
536 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
537 let ops: OpEvent[] = []
538 try {
539 ops = await startCapture($, e.command, e.tool_use_id, e.agentId)
540 } catch (err) {
541 debug($, err)
542 }
543 const r = await next(e)
544 try {
545 await finishCapture($, ops, r)
546 } catch (err) {
547 debug($, err)
548 }
549 return r
550 }).catch(($, e, next) => next(e))
551
552 // The browser Client's keys: select, open, go back, follow live, switch tabs. The answer is its next rows.
553 on('ui.message', { requestId: 'omnigraph' }, async ($, e) => {
554 const show = shown()
555 const ghost = show?.viz.ghost
556 const data = e.data as { key?: unknown; meta?: unknown; shift?: unknown; ctrl?: unknown } | null
557 if (!show || !ghost || !canvas || e.element !== 'explore' || typeof data?.key !== 'string') return {}
558 const action = actionFor({ key: data.key, meta: data.meta === true, shift: data.shift === true, ctrl: data.ctrl === true })
559 if (action.kind === 'tab') {
560 await update($, uiAtom, (u): UiState => ({ ...u, tab: action.tab }))
561 return {}
562 }
563 const wasFollowing = show.scene.isFollowing
564 const now = await $.clock.now()
565 show.scene.key(action, ghost, now)
566 // The tab row's hint changes when browsing starts or stops: redraw the pane for it.
567 if (show.scene.isFollowing !== wasFollowing) $.ui.invalidate('ui.render')
568 if (show.scene.isAnimating(now)) startAnimation($)
569 canvas.clear()
570 show.scene.drawFrame(canvas, ghost, now)
571 return { props: { rows: canvas.runs() } }
572 })
573
574 on('ui.render', { component: 'Pane', requestId: 'omnigraph' }, async ($, e, next) => {
575 if (e.surface !== 'terminal') return next(e)
576 const [view, ui] = await Promise.all([read($, viewAtom), read($, uiAtom)])
577 const show = shown()
578 const selectedOutput = show?.viz.ops.find(op => op.id === ui.selectedOpId)?.output
579 const columns = e.props.bodyColumns
580 const rows = e.props.scroll.bodyRows
581 let graph: GraphViewData | undefined
582 if (ui.tab !== 'feed') {
583 graph = await graphView($, show, columns, rows, view.ghost)
584 } else {
585 canvas = null
586 }
587 return drawPane(
588 $.ui.resolve(e),
589 {
590 view,
591 ui,
592 columns,
593 rows,
594 ...(selectedOutput !== undefined ? { selectedOutput } : {}),
595 ...(graph !== undefined ? { graph } : {}),
596 },
597 {
598 setTab: tab => void update($, uiAtom, u => ({ ...u, tab })),
599 select: id => void selectOp($, id),
600 },
601 )
602 })
603}
604src/capture/capture.ts 130 lines1import type { LedgerLine, OpEvent, OpOutcome, Verb } from '../../types'
2import { classify } from './classify'
3import { parseOutput, segmentOutput, stripAnsi } from './parse-output'
4import { findInvocations } from './tokenize'
5
6/** The parts of a `tool.call` result the capture reads. */
7export interface ToolResultLike {
8 deny?: string
9 isError?: boolean
10 result?: unknown
11 text?: string
12}
13
14export function bashOutput(r: ToolResultLike): { stdout: string; stderr: string; isError: boolean } {
15 if (r.deny !== undefined) return { stdout: '', stderr: r.deny, isError: true }
16 const result = r.result
17 if (typeof result === 'object' && result !== null && 'stdout' in result) {
18 const { stdout, stderr } = result as { stdout?: unknown; stderr?: unknown }
19 return {
20 stdout: typeof stdout === 'string' ? stdout : '',
21 stderr: typeof stderr === 'string' ? stderr : '',
22 isError: r.isError === true,
23 }
24 }
25 return { stdout: r.text ?? '', stderr: '', isError: r.isError === true }
26}
27
28export const OUTPUT_LINES = 40
29export const OUTPUT_CHARS = 4000
30
31/** The first 40 lines / 4000 chars: enough for the Feed's detail, small enough for the ledger. */
32export function clipOutput(text: string): string {
33 const lines = text.split('\n')
34 const head = lines.slice(0, OUTPUT_LINES).join('\n')
35 const clipped = head.length > OUTPUT_CHARS ? head.slice(0, OUTPUT_CHARS) : head
36 return clipped.length < text.length ? `${clipped.trimEnd()}\n…` : clipped
37}
38
39export interface BeginArgs {
40 command: string
41 toolUseId: string
42 cwd: string
43 bin: string
44 now: number
45 agentId?: string
46 /** HOME, to expand `~` the way the shell did. */
47 home?: string
48}
49
50export function beginOps(args: BeginArgs): OpEvent[] {
51 return findInvocations(args.command, args.cwd, args.bin, args.home).map(inv => {
52 const op: OpEvent = {
53 id: `${args.toolUseId}#${inv.index}`,
54 startedAt: args.now,
55 intent: classify(inv),
56 status: 'running',
57 }
58 if (args.agentId !== undefined) op.agentId = args.agentId
59 return op
60 })
61}
62
63/** Which verbs can have produced each outcome kind. */
64const PRODUCED_BY: Readonly<Record<OpOutcome['kind'], readonly Verb[] | 'any'>> = {
65 read: ['query', 'alias'],
66 change: ['mutate'],
67 branch: ['branch', 'mutate'],
68 load: ['load'],
69 error: 'any',
70 other: 'any',
71}
72
73const isResult = (o: OpOutcome | undefined) => o !== undefined && o.kind !== 'error' && o.kind !== 'other'
74
75interface Slot {
76 outcome: OpOutcome
77 output: string
78}
79
80/**
81 * One outcome per op. A single call parses the whole output. Several calls
82 * get one segment each when the counts line up; otherwise each segment goes
83 * to the next op whose verb can have produced it, so one result never counts
84 * twice. A failed exit with no error found blames the last op with no result.
85 */
86function slotsFor(ops: readonly OpEvent[], stdout: string, stderr: string, isError: boolean): Slot[] {
87 if (ops.length === 1) {
88 return [{ outcome: parseOutput(stdout, stderr, isError), output: isError && stderr !== '' ? stderr : stdout }]
89 }
90 const segments = segmentOutput(stdout)
91 const slots: (Slot | undefined)[] = ops.map(() => undefined)
92 if (segments.length === ops.length) {
93 segments.forEach((segment, i) => {
94 slots[i] = { outcome: parseOutput(segment, '', false), output: segment }
95 })
96 } else {
97 let from = 0
98 for (const segment of segments) {
99 const outcome = parseOutput(segment, '', false)
100 const verbs = PRODUCED_BY[outcome.kind]
101 const at = ops.findIndex((op, i) => i >= from && (verbs === 'any' || verbs.includes(op.intent.verb)))
102 if (at < 0) continue
103 slots[at] = { outcome, output: segment }
104 from = at + 1
105 }
106 }
107 if (isError && !slots.some(slot => slot?.outcome.kind === 'error')) {
108 let at = -1
109 slots.forEach((slot, i) => {
110 if (!isResult(slot?.outcome)) at = i
111 })
112 if (at >= 0) slots[at] = { outcome: parseOutput(stdout, stderr, true), output: stderr !== '' ? stderr : stdout }
113 }
114 return slots.map(slot => slot ?? { outcome: { kind: 'other', firstLine: '' }, output: '' })
115}
116
117export function endLines(ops: readonly OpEvent[], r: ToolResultLike, now: number): LedgerLine[] {
118 const { stdout, stderr, isError } = bashOutput(r)
119 return slotsFor(ops, stdout, stderr, isError).map(({ outcome, output }, i) => ({
120 v: 1,
121 t: 'op.end',
122 at: now,
123 id: ops[i]!.id,
124 status: outcome.kind === 'error' ? 'error' : 'ok',
125 durationMs: Math.max(0, now - ops[i]!.startedAt),
126 outcome,
127 output: clipOutput(stripAnsi(output)),
128 }))
129}
130src/capture/parse-output.ts 320 lines1import type { MergeKind, OpOutcome } from '../../types'
2
3// Human formats from crates/omnigraph-cli/src/output.rs and read_format.rs.
4const READ_HEADER = /^(\d+) rows(?: from (branch|snapshot) (\S+))? via (\S+)$/m
5const CHANGE = /^changed (\S+) via (\S+): (\d+) nodes, (\d+) edges$/m
6const BRANCH_CREATED = /^created branch (\S+) from (\S+)(?: at \S+)?$/m
7const BRANCH_DELETED = /^deleted branch (\S+)$/m
8const BRANCH_MERGED = /^merged (\S+) into (\S+)(?: as commit \S+)?: (already_up_to_date|fast_forward|merged)$/m
9const LOADED =
10 /^loaded (\S+) on branch (\S+) with (\w+): (\d+) entities across (\d+) node types and (\d+) edge types$/m
11const LOAD_BRANCH = /^branch (\S+) created from (\S+)$/m
12/** `snapshot`'s human output starts with this line. */
13const SNAPSHOT_HEAD = /^graph_branch: \S+$/
14
15/**
16 * The target echo on stderr: a write's before 0.14, every command's since
17 * (scope.rs `report`). Claude's Bash merges it into stdout.
18 */
19const TARGET_ECHO = /^(?:omnigraph \S+ → .+ \((?:direct|served)[^)]*\)|target .+ \((?:explicit|default|inline)\): .+)$/
20/** A 0.14 write's scope, printed right after its target echo. */
21const WRITE_SCOPE = /^target write scope: .+$/
22/**
23 * clap's `error: …`, a coded diagnostic's `error[CODE]: …` and color-eyre's
24 * `Error:` (message on the next line, as ` 0: …`). All print at column 0;
25 * an indented `error:` is data (a schema property, a cell).
26 */
27const ERROR_START = /^error(?:\[[^\]]*\])?:/i
28/** The last line of a failure the 0.14 CLI classified (app.rs); its message comes first. */
29const DISPOSITION = /^disposition: \{.*\}$/
30/** What may sit between that message and its disposition. */
31const FAILURE_DETAIL = /^(?:HTTP \d{3}|Retry-After: .*)$/
32/**
33 * Terminal escapes a shell can wrap output in: CSI (colors, `ESC[?25h`), OSC
34 * (titles, links), charset picks such as `ESC(B` (what `tput sgr0` prints;
35 * seen before every result when Claude Code's sandbox is off) and the other
36 * two-byte escapes.
37 */
38const ANSI = /\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[ -/]+[0-~]|[0-~])/g
39
40/** The first line of any result the CLI prints; used to split multi-invocation output. */
41const RESULT_LINE = new RegExp(
42 [READ_HEADER, CHANGE, BRANCH_CREATED, BRANCH_DELETED, BRANCH_MERGED, LOADED, SNAPSHOT_HEAD]
43 .map(re => re.source)
44 .join('|'),
45)
46
47export const MAX_ROWS = 200
48
49type Json = Record<string, unknown>
50
51const isRecord = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v)
52const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined)
53const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : undefined)
54
55function lastLine(text: string): string | undefined {
56 const lines = text.split('\n').map(l => l.trim()).filter(Boolean)
57 return lines[lines.length - 1]
58}
59
60function firstLine(text: string): string {
61 return (text.split('\n').find(l => l.trim() !== '') ?? '').trim().slice(0, 200)
62}
63
64/** As read_format.rs `stringify_value` prints a cell. */
65export function cellText(v: unknown): string {
66 if (v === null || v === undefined) return 'null'
67 if (typeof v === 'string') return v
68 if (typeof v === 'number' || typeof v === 'boolean') return String(v)
69 return JSON.stringify(v)
70}
71
72/** Control characters left after the escapes (tmux's sgr0 ends with SI); tabs and line breaks stay. */
73const CONTROL = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g
74
75export function stripAnsi(text: string): string {
76 return text.replace(ANSI, '').replace(CONTROL, '')
77}
78
79/** No colors, no CRLF, no target echo or write scope lines. */
80function clean(text: string): string {
81 return stripAnsi(text)
82 .replace(/\r\n/g, '\n')
83 .split('\n')
84 .filter(line => !TARGET_ECHO.test(line) && !WRITE_SCOPE.test(line))
85 .join('\n')
86}
87
88/** The message of the first error block in `text`, if there is one. */
89function errorIn(text: string): string | undefined {
90 const lines = text.split('\n')
91 const at = lines.findIndex(line => ERROR_START.test(line))
92 if (at < 0) return classifiedFailureIn(lines)
93 const inline = lines[at]!.replace(ERROR_START, '').trim()
94 if (inline !== '') return inline.slice(0, 200)
95 const next = lines.slice(at + 1).find(line => line.trim() !== '')
96 return next?.trim().replace(/^\d+:\s*/, '').slice(0, 200)
97}
98
99/** A 0.14 failure: the message line above its HTTP status, Retry-After and disposition. */
100function classifiedFailureIn(lines: readonly string[]): string | undefined {
101 let at = lines.findIndex(line => DISPOSITION.test(line))
102 if (at < 0) return undefined
103 while (at > 0 && (FAILURE_DETAIL.test(lines[at - 1]!) || lines[at - 1]!.trim() === '')) at--
104 return at > 0 ? lines[at - 1]!.trim().slice(0, 200) : undefined
105}
106
107/** A failure envelope from `--json`: `{"error": …, "disposition": …}`. */
108function jsonErrorIn(text: string): string | undefined {
109 const head = parseJsonish(text.trim())?.[0]
110 return isRecord(head) && typeof head.error === 'string' ? head.error.slice(0, 200) : undefined
111}
112
113function errorMessage(stdout: string, stderr: string): string {
114 return (
115 errorIn(stderr) ?? errorIn(stdout) ?? jsonErrorIn(stdout) ?? lastLine(stderr) ?? lastLine(stdout) ?? 'command failed'
116 ).slice(0, 200)
117}
118
119function parseTable(text: string, m: RegExpMatchArray): OpOutcome {
120 const where =
121 m[2] === 'branch' ? { branch: m[3]! } : m[2] === 'snapshot' ? { snapshot: m[3]! } : {}
122 const base = { kind: 'read' as const, queryName: m[4]!, rowCount: Number(m[1]), ...where }
123 const lines = text.slice((m.index ?? 0) + m[0].length).split('\n').slice(1)
124 const head = lines[0]
125 if (head === undefined || head.trim() === '' || head.trim() === '(no rows)') {
126 return { ...base, columns: [], cells: [] }
127 }
128 const columns = head.split(' | ').map(c => c.trim())
129 const firstRow = /^[-+]+$/.test(lines[1]?.trim() ?? '') ? 2 : 1
130 const cells: string[][] = []
131 for (const line of lines.slice(firstRow)) {
132 if (line.trim() === '') break
133 const parts = line.split(' | ')
134 if (parts.length !== columns.length) break
135 const row = parts.map(c => c.trimEnd())
136 const prev = cells[cells.length - 1]
137 // Wrap layout: a continuation line repeats the row with blanks where nothing wrapped.
138 if (prev && row[0] === '' && row.some(c => c !== '')) {
139 row.forEach((c, i) => {
140 prev[i] = `${prev[i] ?? ''}${c}`
141 })
142 continue
143 }
144 if (cells.length >= MAX_ROWS) break
145 cells.push(row)
146 }
147 return { ...base, columns, cells }
148}
149
150function parseJsonish(text: string): unknown[] | undefined {
151 try {
152 return [JSON.parse(text)]
153 } catch {
154 // maybe JSONL: metadata first, then one row per line
155 }
156 const out: unknown[] = []
157 for (const line of text.split('\n')) {
158 if (line.trim() === '') continue
159 try {
160 out.push(JSON.parse(line))
161 } catch {
162 return undefined
163 }
164 }
165 return out.length > 0 ? out : undefined
166}
167
168function parseJson(text: string): OpOutcome | undefined {
169 const values = parseJsonish(text)
170 const head = values?.[0]
171 if (!values || !isRecord(head)) return undefined
172
173 if (typeof head.error === 'string' && isRecord(head.disposition)) return { kind: 'error', message: head.error.slice(0, 200) }
174 if ('row_count' in head || 'rows' in head) {
175 const rows = Array.isArray(head.rows) ? head.rows : values.slice(1)
176 const first = rows[0]
177 const columns = Array.isArray(head.columns)
178 ? head.columns.filter((c): c is string => typeof c === 'string')
179 : isRecord(first)
180 ? Object.keys(first)
181 : []
182 const target = isRecord(head.target) ? head.target : {}
183 const branch = str(target.branch)
184 const snapshot = str(target.snapshot)
185 return {
186 kind: 'read',
187 queryName: str(head.query_name) ?? '',
188 rowCount: num(head.row_count) ?? rows.length,
189 ...(branch !== undefined ? { branch } : {}),
190 ...(snapshot !== undefined ? { snapshot } : {}),
191 columns,
192 cells: rows.slice(0, MAX_ROWS).map(r => columns.map(c => cellText(isRecord(r) ? r[c] : undefined))),
193 }
194 }
195
196 const outcome = head.outcome
197 if (isRecord(outcome) && typeof outcome.kind === 'string') {
198 if (outcome.kind === 'created') {
199 return { kind: 'branch', action: 'created', name: str(outcome.name) ?? '', from: str(outcome.from) ?? '' }
200 }
201 if (outcome.kind === 'deleted') return { kind: 'branch', action: 'deleted', name: str(outcome.name) ?? '' }
202 if (outcome.kind === 'merged') {
203 return {
204 kind: 'branch', action: 'merged', name: str(outcome.source) ?? '',
205 into: str(outcome.target) ?? '', merge: (str(outcome.merge) ?? 'merged') as MergeKind,
206 }
207 }
208 }
209 if ('affected_nodes' in head) {
210 return {
211 kind: 'change', branch: str(head.branch) ?? '', queryName: str(head.query_name) ?? '',
212 nodes: num(head.affected_nodes) ?? 0, edges: num(head.affected_edges) ?? 0,
213 }
214 }
215 if (typeof head.source === 'string' && typeof head.target === 'string' && typeof outcome === 'string') {
216 return { kind: 'branch', action: 'merged', name: head.source, into: head.target, merge: outcome as MergeKind }
217 }
218 if ('total_entities' in head) {
219 const base = str(head.base_branch)
220 return {
221 kind: 'load', branch: str(head.branch) ?? '', mode: str(head.mode) ?? '',
222 total: num(head.total_entities) ?? 0,
223 nodeTypes: Array.isArray(head.nodes) ? head.nodes.length : 0,
224 edgeTypes: Array.isArray(head.edges) ? head.edges.length : 0,
225 ...(head.branch_created === true && base !== undefined ? { branchCreatedFrom: base } : {}),
226 }
227 }
228 // `branch create|delete --json`: the graph's uri and the branch, with `from` for a create.
229 if (typeof head.uri === 'string' && typeof head.name === 'string') {
230 if (typeof head.from === 'string') return { kind: 'branch', action: 'created', name: head.name, from: head.from }
231 if (Object.keys(head).every(k => k === 'uri' || k === 'name' || k === 'actor_id')) {
232 return { kind: 'branch', action: 'deleted', name: head.name }
233 }
234 }
235 return { kind: 'other', firstLine: firstLine(text) }
236}
237
238/** A read envelope cut off mid-way (long output gets truncated): keep the header facts. */
239function parseCutJson(text: string): OpOutcome | undefined {
240 const queryName = text.match(/"query_name"\s*:\s*"([^"]*)"/)?.[1]
241 const rowCount = text.match(/"row_count"\s*:\s*(\d+)/)?.[1]
242 if (queryName === undefined || rowCount === undefined) return undefined
243 const branch = text.match(/"branch"\s*:\s*"([^"]*)"/)?.[1]
244 return {
245 kind: 'read', queryName, rowCount: Number(rowCount),
246 ...(branch !== undefined ? { branch } : {}),
247 columns: [], cells: [],
248 }
249}
250
251export function parseOutput(stdout: string, stderr: string, isError: boolean): OpOutcome {
252 const text = clean(stdout)
253 const errors = clean(stderr)
254 if (isError) return { kind: 'error', message: errorMessage(text, errors) }
255 const trimmed = text.trim()
256 if (trimmed.startsWith('{')) {
257 const fromJson = parseJson(trimmed) ?? parseCutJson(trimmed)
258 if (fromJson) return fromJson
259 }
260 let m = text.match(READ_HEADER)
261 if (m) return parseTable(text, m)
262 if ((m = text.match(CHANGE))) {
263 return { kind: 'change', branch: m[1]!, queryName: m[2]!, nodes: Number(m[3]), edges: Number(m[4]) }
264 }
265 if ((m = text.match(BRANCH_CREATED))) return { kind: 'branch', action: 'created', name: m[1]!, from: m[2]! }
266 if ((m = text.match(BRANCH_DELETED))) return { kind: 'branch', action: 'deleted', name: m[1]! }
267 if ((m = text.match(BRANCH_MERGED))) {
268 return { kind: 'branch', action: 'merged', name: m[1]!, into: m[2]!, merge: m[3] as MergeKind }
269 }
270 if ((m = text.match(LOADED))) {
271 const created = text.match(LOAD_BRANCH)
272 return {
273 kind: 'load', branch: m[2]!, mode: m[3]!, total: Number(m[4]),
274 nodeTypes: Number(m[5]), edgeTypes: Number(m[6]),
275 ...(created ? { branchCreatedFrom: created[2]! } : {}),
276 }
277 }
278 // No result line, but an error block: a failure the shell's exit status hid (`a ; b`).
279 const failure = errorIn(text) ?? errorIn(errors)
280 if (failure !== undefined) return { kind: 'error', message: failure }
281 return { kind: 'other', firstLine: firstLine(trimmed) }
282}
283
284type Boundary = 'echo' | 'result' | 'error'
285
286function boundaryOf(line: string): Boundary | undefined {
287 if (TARGET_ECHO.test(line)) return 'echo'
288 if (RESULT_LINE.test(line)) return 'result'
289 if (ERROR_START.test(line)) return 'error'
290 return undefined
291}
292
293/**
294 * Cuts one command's stdout into the outputs of the omnigraph calls in it.
295 * A call's output starts at a write's target echo, a result line or an error
296 * block; a result or error right after an echo belongs to that echo. Lines
297 * before the first boundary join the first segment; no boundary, one segment.
298 */
299export function segmentOutput(stdout: string): string[] {
300 const lines = stripAnsi(stdout).replace(/\r\n/g, '\n').split('\n')
301 const starts: number[] = []
302 let isEchoOpen = false
303 lines.forEach((line, i) => {
304 const boundary = boundaryOf(line)
305 if (boundary === undefined) return
306 if (boundary !== 'echo' && isEchoOpen) {
307 isEchoOpen = false
308 return
309 }
310 starts.push(i)
311 isEchoOpen = boundary === 'echo'
312 })
313 if (starts.length === 0) return [stdout]
314 starts[0] = 0
315 return starts.map((start, k) => {
316 const end = starts[k + 1] ?? lines.length
317 return lines.slice(start, end).join('\n') + (end < lines.length ? '\n' : '')
318 })
319}
320src/capture/tokenize.ts 199 lines1import type { Invocation } from '../../types'
2import { basename, expandHome, resolvePath } from '../util/path'
3
4type Token = { kind: 'word'; value: string } | { kind: 'op'; value: string }
5
6const WRAPPERS = new Set(['env', 'time', 'command', 'exec', 'nohup'])
7/** Words that open a compound command's body: `do omnigraph …`, `then omnigraph …`. */
8const KEYWORDS = new Set(['do', 'then', 'else', 'elif', 'if', 'while', 'until', '!', '{'])
9/** `timeout` options that take a value. */
10const TIMEOUT_VALUE_FLAGS = new Set(['-s', '-k', '--signal', '--kill-after'])
11const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/
12
13/**
14 * A small POSIX-ish lexer: quotes, escapes, comments, `&&` `||` `;` `|` `&`,
15 * newlines and parentheses as separators, and redirections (`>`, `>>`, `<`,
16 * `2>`, `2>&1`, `&>`), whose targets are dropped.
17 */
18export function lex(src: string): Token[] {
19 const tokens: Token[] = []
20 let word = ''
21 let isInWord = false
22 const flush = () => {
23 if (isInWord) tokens.push({ kind: 'word', value: word })
24 word = ''
25 isInWord = false
26 }
27 let i = 0
28 while (i < src.length) {
29 const c = src[i]!
30 if (c === "'") {
31 const end = src.indexOf("'", i + 1)
32 const stop = end < 0 ? src.length : end
33 word += src.slice(i + 1, stop)
34 isInWord = true
35 i = stop + 1
36 continue
37 }
38 if (c === '"') {
39 isInWord = true
40 i++
41 while (i < src.length && src[i] !== '"') {
42 const next = src[i + 1]
43 if (src[i] === '\\' && next !== undefined && '"\\$`'.includes(next)) {
44 word += next
45 i += 2
46 continue
47 }
48 word += src[i]
49 i++
50 }
51 i++
52 continue
53 }
54 if (c === '\\') {
55 const next = src[i + 1]
56 if (next !== undefined && next !== '\n') {
57 word += next
58 isInWord = true
59 }
60 i += 2
61 continue
62 }
63 if (c === ' ' || c === '\t') {
64 flush()
65 i++
66 continue
67 }
68 if (c === '#' && !isInWord) {
69 while (i < src.length && src[i] !== '\n') i++
70 continue
71 }
72 if (c === '\n' || c === ';' || c === '(' || c === ')') {
73 flush()
74 tokens.push({ kind: 'op', value: ';' })
75 i++
76 continue
77 }
78 if (c === '&' || c === '|') {
79 flush()
80 const two = src.slice(i, i + 2)
81 if (two === '&&' || two === '||') {
82 tokens.push({ kind: 'op', value: two })
83 i += 2
84 continue
85 }
86 if (two === '&>') {
87 tokens.push({ kind: 'op', value: '>' })
88 i += 2
89 continue
90 }
91 tokens.push({ kind: 'op', value: c })
92 i++
93 continue
94 }
95 if (c === '>' || c === '<') {
96 if (isInWord && /^\d+$/.test(word)) {
97 word = ''
98 isInWord = false
99 } else {
100 flush()
101 }
102 let j = i + 1
103 if (src[j] === c) j++
104 if (src[j] === '&') {
105 j++
106 while (j < src.length && /[\d-]/.test(src[j]!)) j++
107 i = j
108 continue
109 }
110 tokens.push({ kind: 'op', value: '>' })
111 i = j
112 continue
113 }
114 word += c
115 isInWord = true
116 i++
117 }
118 flush()
119 return tokens
120}
121
122/**
123 * Strips compound-command keywords (`do`, `then`, `{`, …), `VAR=x`, and the
124 * `env`, `time`, `command`, `exec`, `nohup`, `timeout <duration>` wrappers;
125 * undefined for `command -v x`.
126 */
127function stripPrefixes(words: string[]): string[] | undefined {
128 let k = 0
129 for (;;) {
130 const word = words[k]
131 if (word === undefined) break
132 if (KEYWORDS.has(word) || ASSIGNMENT.test(word)) {
133 k++
134 continue
135 }
136 if (word === 'timeout') {
137 k++
138 while (words[k]?.startsWith('-')) k += TIMEOUT_VALUE_FLAGS.has(words[k]!) ? 2 : 1
139 k++ // the duration
140 continue
141 }
142 if (WRAPPERS.has(word)) {
143 k++
144 if (word === 'command' && (words[k] === '-v' || words[k] === '-V')) return undefined
145 while (k < words.length && (ASSIGNMENT.test(words[k]!) || words[k]!.startsWith('-'))) k++
146 continue
147 }
148 break
149 }
150 return words.slice(k)
151}
152
153/**
154 * Every `omnigraph` invocation in a Bash command line, with the directory it
155 * runs in (`cd` segments move it). `bin` is the configured binary; matching is
156 * by basename, so `/usr/local/bin/omnigraph` matches `omnigraph`. With `home`,
157 * `~` in `cd` targets and leading `~/` in arguments expand as the shell would.
158 */
159export function findInvocations(command: string, cwd: string, bin: string, home?: string): Invocation[] {
160 const want = basename(bin)
161 const found: Invocation[] = []
162 let dir = cwd
163 let words: string[] = []
164 let isSkippingTarget = false
165
166 const endSegment = () => {
167 const segment = stripPrefixes(words)
168 words = []
169 if (!segment || segment.length === 0) return
170 if (segment[0] === 'cd') {
171 const to = segment[1]
172 if (to !== undefined && to !== '-') dir = resolvePath(dir, to, home)
173 return
174 }
175 if (basename(segment[0]!) === want) {
176 // The shell expands a leading `~`: record what omnigraph actually received.
177 found.push({ argv: segment.map(word => expandHome(word, home)), cwd: dir, index: found.length })
178 }
179 }
180
181 for (const token of lex(command)) {
182 if (token.kind === 'word') {
183 if (isSkippingTarget) {
184 isSkippingTarget = false
185 continue
186 }
187 words.push(token.value)
188 continue
189 }
190 if (token.value === '>') {
191 isSkippingTarget = true
192 continue
193 }
194 endSegment()
195 }
196 endSegment()
197 return found
198}
199src/enrich/cli.ts 142 lines1import type { EntityChange, Target, Verb } from '../../types'
2import { resolvePath } from '../util/path'
3
4/** Global flags that choose the graph, passed through as the agent gave them. */
5export function targetFlags(t: Target): string[] {
6 const flags: string[] = []
7 for (const name of ['server', 'graph', 'store', 'profile', 'cluster', 'target', 'operator-config'] as const) {
8 const value = t[name]
9 if (value !== undefined) flags.push(`--${name}`, value)
10 }
11 return flags
12}
13
14const uri = (t: Target): string[] => (t.uri !== undefined ? [t.uri] : [])
15
16export const schemaArgv = (bin: string, t: Target): string[] => [bin, 'schema', 'show', ...uri(t), '--json', ...targetFlags(t)]
17
18export const exportArgv = (bin: string, t: Target): string[] => [bin, 'export', ...uri(t), ...targetFlags(t)]
19
20export const commitListArgv = (bin: string, t: Target, branch: string): string[] => [
21 bin, 'commit', 'list', ...uri(t), '--branch', branch, '--json', ...targetFlags(t),
22]
23
24export const commitChangesArgv = (bin: string, t: Target, commitId: string): string[] => [
25 bin, 'commit', 'changes', commitId, ...(t.uri !== undefined ? ['--uri', t.uri] : []), '--json', ...targetFlags(t),
26]
27
28const isUrl = (p: string) => /^[a-z][a-z0-9+.-]*:\/\//i.test(p)
29const absolute = (cwd: string, p: string | undefined) => (p === undefined ? '' : isUrl(p) ? p : resolvePath(cwd, p))
30/** A registered target's name (0.14 grammar); anything else given to `--target` is a local path. */
31const isTargetName = (t: string) => /^[A-Za-z][A-Za-z0-9_.-]*$/.test(t)
32
33/**
34 * Which graph an op ran against. Paths resolve against the op's directory,
35 * so `cd dev && … --store graphs/x` and `… --store dev/graphs/x` are one
36 * graph; with no path at all the directory itself (its config) decides.
37 */
38export function targetKey(t: Target, cwd: string): string {
39 const hasPath = t.store !== undefined || t.uri !== undefined || t.cluster !== undefined || t.target !== undefined
40 const target = t.target === undefined || isTargetName(t.target) ? (t.target ?? '') : absolute(cwd, t.target)
41 return JSON.stringify([
42 hasPath ? '' : cwd,
43 t.server ?? '', t.graph ?? '', t.profile ?? '',
44 absolute(cwd, t.store), absolute(cwd, t.cluster), absolute(cwd, t.uri),
45 target, absolute(cwd, t['operator-config']),
46 ])
47}
48
49/** Whether a command reads or writes a graph, so the graph it names can be loaded (not `version`, `lint`, `login`…). */
50export const addressesGraph = (verb: Verb): boolean => verb !== 'other' && verb !== 'lint'
51
52type Json = Record<string, unknown>
53const isRecord = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v)
54
55export function schemaSourceOf(stdout: string): string | undefined {
56 try {
57 const parsed: unknown = JSON.parse(stdout)
58 return isRecord(parsed) && typeof parsed.schema_source === 'string' ? parsed.schema_source : undefined
59 } catch {
60 return undefined
61 }
62}
63
64export interface CommitRef {
65 id: string
66 /** µs since the epoch. */
67 createdAt: number
68}
69
70/** `commit list --json`: newest first. */
71export function parseCommits(stdout: string): CommitRef[] {
72 try {
73 const parsed: unknown = JSON.parse(stdout)
74 const list = isRecord(parsed) && Array.isArray(parsed.commits) ? parsed.commits : Array.isArray(parsed) ? parsed : []
75 return list.flatMap(c =>
76 isRecord(c) && typeof c.graph_commit_id === 'string' && typeof c.created_at === 'number'
77 ? [{ id: c.graph_commit_id, createdAt: c.created_at }]
78 : [],
79 )
80 } catch {
81 return []
82 }
83}
84
85/** Clock slack between the agent's shell and the store, in ms. */
86export const COMMIT_SLACK_MS = 5000
87
88/**
89 * The op's commit: the oldest one made while it ran (with slack) that no
90 * earlier diff took. Chained writes in one Bash call share a window, so each
91 * takes the next commit in order instead of all taking the newest.
92 */
93export function pickCommit(
94 commits: readonly CommitRef[],
95 opStartedAtMs: number,
96 opEndedAtMs: number,
97 consumed: ReadonlySet<string> = new Set(),
98): string | undefined {
99 const inWindow = commits.filter(c => {
100 const ms = c.createdAt / 1000
101 return ms >= opStartedAtMs - COMMIT_SLACK_MS && ms <= opEndedAtMs + COMMIT_SLACK_MS && !consumed.has(c.id)
102 })
103 return inWindow[inWindow.length - 1]?.id // newest first: the oldest is last
104}
105
106export const MAX_CHANGES = 500
107
108const labelIn = (image: unknown): string | undefined => {
109 if (!isRecord(image) || !isRecord(image.properties)) return undefined
110 for (const field of ['name', 'title', 'slug']) {
111 const value = image.properties[field]
112 if (typeof value === 'string' && value !== '') return value
113 }
114 return undefined
115}
116
117/** `commit changes --json` → entity changes (at most 500) and how many more there were. */
118export function parseChanges(stdout: string): { changes: EntityChange[]; more: number } {
119 let parsed: unknown
120 try {
121 parsed = JSON.parse(stdout)
122 } catch {
123 return { changes: [], more: 0 }
124 }
125 const raw = isRecord(parsed) && Array.isArray(parsed.changes) ? parsed.changes : []
126 const changes: EntityChange[] = []
127 for (const c of raw) {
128 if (!isRecord(c) || !isRecord(c.type) || typeof c.type.name !== 'string' || typeof c.id !== 'string') continue
129 if (c.kind !== 'node' && c.kind !== 'edge') continue
130 if (c.op !== 'insert' && c.op !== 'update' && c.op !== 'delete') continue
131 const image = c.after ?? c.before
132 const change: EntityChange = { kind: c.kind, type: c.type.name, id: c.id, op: c.op }
133 const ends = isRecord(image) && isRecord(image.endpoints) ? image.endpoints : undefined
134 if (typeof ends?.from === 'string') change.from = ends.from
135 if (typeof ends?.to === 'string') change.to = ends.to
136 const label = labelIn(image)
137 if (label !== undefined) change.label = label
138 changes.push(change)
139 }
140 return { changes: changes.slice(0, MAX_CHANGES), more: Math.max(0, changes.length - MAX_CHANGES) }
141}
142src/enrich/highlight.ts 79 lines1import type { GhostGraph } from '../../types'
2
3export interface MatchIndex {
4 byKey: Map<string, string[]>
5 byLabel: Map<string, string[]>
6}
7
8export const MAX_MATCHES = 50
9
10function add(map: Map<string, string[]>, text: string, id: string): void {
11 const ids = map.get(text)
12 if (!ids) map.set(text, [id])
13 else if (!ids.includes(id)) ids.push(id)
14}
15
16export function buildMatchIndex(graph: GhostGraph): MatchIndex {
17 const byKey = new Map<string, string[]>()
18 const byLabel = new Map<string, string[]>()
19 for (const node of graph.nodes) {
20 add(byKey, node.key, node.id)
21 add(byLabel, node.label, node.id)
22 }
23 return { byKey, byLabel }
24}
25
26/** A `return { $p }` cell is the node as JSON: `{"@id": "…", …}`. */
27function exactKey(cell: string): string | undefined {
28 if (!cell.startsWith('{')) return undefined
29 try {
30 const parsed: unknown = JSON.parse(cell)
31 if (typeof parsed !== 'object' || parsed === null) return undefined
32 const id = (parsed as Record<string, unknown>)['@id']
33 return typeof id === 'string' ? id : undefined
34 } catch {
35 return undefined
36 }
37}
38
39function prefixMatch(map: Map<string, string[]>, prefix: string): string[] | undefined {
40 let found: string[] | undefined
41 for (const [text, ids] of map) {
42 if (!text.startsWith(prefix)) continue
43 if (found) return undefined
44 found = ids
45 }
46 return found
47}
48
49/**
50 * Nodes a read's result cells name: exact via `@id`, else a cell equal to a
51 * node key or label, else a truncated cell (`…`) matching one key or label.
52 * Numbers, booleans, `null` and short cells are ignored; at most 50 nodes.
53 */
54export function matchCells(cells: readonly string[][], index: MatchIndex): { nodeIds: string[]; isExact: boolean } {
55 const found = new Set<string>()
56 let isExact = true
57 for (const row of cells) {
58 for (const cell of row) {
59 if (found.size >= MAX_MATCHES) break
60 const text = cell.trim()
61 if (text.length < 3 || text === 'null' || text === 'true' || text === 'false' || /^-?\d+(\.\d+)?$/.test(text)) continue
62 const key = exactKey(text)
63 let ids: string[] | undefined
64 if (key !== undefined) {
65 ids = index.byKey.get(key)
66 } else {
67 ids = index.byKey.get(text) ?? index.byLabel.get(text)
68 if (!ids && text.endsWith('…') && text.length > 3) {
69 const prefix = text.slice(0, -1)
70 ids = prefixMatch(index.byKey, prefix) ?? prefixMatch(index.byLabel, prefix)
71 }
72 if (ids) isExact = false
73 }
74 for (const id of ids ?? []) if (found.size < MAX_MATCHES) found.add(id)
75 }
76 }
77 return { nodeIds: [...found], isExact: found.size > 0 && isExact }
78}
79src/enrich/locate.ts 18 lines1/** A bare command name, safe to hand to a shell as `command -v <name>`. */
2export function isPlainName(bin: string): boolean {
3 return /^[A-Za-z0-9._-]+$/.test(bin)
4}
5
6/** Where installers usually put a CLI, for when neither PATH nor the shell knows it. */
7export function binCandidates(home: string | undefined, bin: string): string[] {
8 const homeDirs = home !== undefined ? [`${home}/.local/bin`, `${home}/.cargo/bin`] : []
9 return [...homeDirs, '/opt/homebrew/bin', '/usr/local/bin'].map(dir => `${dir}/${bin}`)
10}
11
12/** The absolute path `command -v <bin>` printed, past any shell start-up noise. */
13export function pathFromShell(stdout: string, bin: string): string | undefined {
14 const lines = stdout.split('\n').map(l => l.trim()).filter(Boolean)
15 const last = lines[lines.length - 1]
16 return last !== undefined && last.startsWith('/') && last.endsWith(`/${bin}`) ? last : undefined
17}
18src/enrich/queue.ts 46 lines1export interface Job {
2 run: () => Promise<void>
3 /** When it was queued, in the same clock as `now`. */
4 at: number
5}
6
7/**
8 * Background work, one job at a time, in order. A job that waited longer
9 * than `maxAgeMs` is dropped: by then the moment it would have shown is gone.
10 */
11export class JobQueue {
12 private jobs: Job[] = []
13 private isRunning = false
14
15 constructor(
16 private readonly now: () => Promise<number>,
17 private readonly onError: (err: unknown) => void,
18 private readonly maxAgeMs = 60_000,
19 ) {}
20
21 get size(): number {
22 return this.jobs.length + (this.isRunning ? 1 : 0)
23 }
24
25 push(job: Job): void {
26 this.jobs.push(job)
27 if (!this.isRunning) void this.drain()
28 }
29
30 private async drain(): Promise<void> {
31 this.isRunning = true
32 try {
33 for (let job = this.jobs.shift(); job; job = this.jobs.shift()) {
34 if ((await this.now()) - job.at > this.maxAgeMs) continue
35 try {
36 await job.run()
37 } catch (err) {
38 this.onError(err)
39 }
40 }
41 } finally {
42 this.isRunning = false
43 }
44 }
45}
46src/graph/ghost.ts 126 lines1import type { EntityChange, GhostEdge, GhostGraph, GhostNode } from '../../types'
2
3export const nodeId = (type: string, key: string): string => `${type}:${key}`
4
5/** `edge Name: From -> To` declarations of a `.pg` schema. */
6export function parseEdgeEnds(schemaSource: string): Record<string, [string, string]> {
7 const ends: Record<string, [string, string]> = {}
8 for (const m of schemaSource.matchAll(/^\s*edge\s+(\w+)\s*:\s*(\w+)\s*->\s*(\w+)/gm)) {
9 ends[m[1]!] = [m[2]!, m[3]!]
10 }
11 return ends
12}
13
14export function labelOf(data: Record<string, unknown>, key: string): string {
15 for (const field of ['name', 'title', 'slug']) {
16 const value = data[field]
17 if (typeof value === 'string' && value !== '') return value
18 }
19 return key
20}
21
22/** The node id a raw key names; with several types sharing it, `type` picks one. */
23export function resolveKey(graph: GhostGraph, key: string, type?: string): string | undefined {
24 if (type !== undefined) {
25 const id = nodeId(type, key)
26 return graph.nodes.some(n => n.id === id) ? id : undefined
27 }
28 const found = graph.nodes.filter(n => n.key === key)
29 return found.length === 1 ? found[0]!.id : undefined
30}
31
32function resolveEnd(byKey: Map<string, GhostNode[]>, key: string, type: string | undefined): string | undefined {
33 const candidates = byKey.get(key) ?? []
34 if (type !== undefined) return candidates.find(n => n.type === type)?.id ?? (candidates.length === 1 ? candidates[0]!.id : undefined)
35 return candidates.length === 1 ? candidates[0]!.id : undefined
36}
37
38function keyIndex(nodes: readonly GhostNode[]): Map<string, GhostNode[]> {
39 const byKey = new Map<string, GhostNode[]>()
40 for (const node of nodes) byKey.set(node.key, [...(byKey.get(node.key) ?? []), node])
41 return byKey
42}
43
44/**
45 * Folds `omnigraph export` JSONL (`{"type","id","data"}` nodes and
46 * `{"edge","id","from","to","data"}` edges) into a ghost graph. Above
47 * `maxNodes`, the best-connected nodes are kept (ties in export order).
48 */
49export function foldExport(jsonl: string, edgeEnds: Record<string, [string, string]>, maxNodes: number): GhostGraph {
50 const nodes: GhostNode[] = []
51 const rawEdges: { id: string; type: string; from: string; to: string }[] = []
52 for (const line of jsonl.split('\n')) {
53 if (line.trim() === '') continue
54 let row: unknown
55 try {
56 row = JSON.parse(line)
57 } catch {
58 continue
59 }
60 if (typeof row !== 'object' || row === null) continue
61 const r = row as Record<string, unknown>
62 const data = typeof r.data === 'object' && r.data !== null ? (r.data as Record<string, unknown>) : {}
63 if (typeof r.edge === 'string' && typeof r.from === 'string' && typeof r.to === 'string') {
64 rawEdges.push({ id: typeof r.id === 'string' ? r.id : `${r.edge}|${r.from}|${r.to}`, type: r.edge, from: r.from, to: r.to })
65 } else if (typeof r.type === 'string' && typeof r.id === 'string') {
66 nodes.push({ id: nodeId(r.type, r.id), type: r.type, key: r.id, label: labelOf(data, r.id) })
67 }
68 }
69 const byKey = keyIndex(nodes)
70 let edges: GhostEdge[] = []
71 for (const e of rawEdges) {
72 const ends = edgeEnds[e.type]
73 const from = resolveEnd(byKey, e.from, ends?.[0])
74 const to = resolveEnd(byKey, e.to, ends?.[1])
75 if (from !== undefined && to !== undefined) edges.push({ id: e.id, type: e.type, from, to })
76 }
77 if (nodes.length <= maxNodes) return { nodes, edges, truncated: false, edgeEnds }
78
79 const degree = new Map<string, number>()
80 for (const e of edges) {
81 degree.set(e.from, (degree.get(e.from) ?? 0) + 1)
82 degree.set(e.to, (degree.get(e.to) ?? 0) + 1)
83 }
84 const ranked = nodes
85 .map((node, order) => ({ node, order, degree: degree.get(node.id) ?? 0 }))
86 .sort((a, b) => b.degree - a.degree || a.order - b.order)
87 .slice(0, maxNodes)
88 .sort((a, b) => a.order - b.order)
89 const kept = new Set(ranked.map(r => r.node.id))
90 edges = edges.filter(e => kept.has(e.from) && kept.has(e.to))
91 return { nodes: ranked.map(r => r.node), edges, truncated: true, edgeEnds }
92}
93
94/** A commit's changes applied to the graph (a new graph; the input is untouched). */
95export function applyChanges(graph: GhostGraph, changes: readonly EntityChange[]): GhostGraph {
96 let nodes = graph.nodes.slice()
97 let edges = graph.edges.slice()
98 for (const c of changes) {
99 if (c.kind === 'node') {
100 const id = nodeId(c.type, c.id)
101 const at = nodes.findIndex(n => n.id === id)
102 if (c.op === 'delete') {
103 if (at >= 0) nodes.splice(at, 1)
104 edges = edges.filter(e => e.from !== id && e.to !== id)
105 } else if (at >= 0) {
106 if (c.label !== undefined) nodes[at] = { ...nodes[at]!, label: c.label }
107 } else {
108 nodes.push({ id, type: c.type, key: c.id, label: c.label ?? c.id })
109 }
110 continue
111 }
112 if (c.op === 'delete') {
113 edges = edges.filter(e => e.id !== c.id)
114 continue
115 }
116 if (c.from === undefined || c.to === undefined || edges.some(e => e.id === c.id)) continue
117 const byKey = keyIndex(nodes)
118 const ends = graph.edgeEnds[c.type]
119 const from = resolveEnd(byKey, c.from, ends?.[0])
120 const to = resolveEnd(byKey, c.to, ends?.[1])
121 if (from !== undefined && to !== undefined) edges.push({ id: c.id, type: c.type, from, to })
122 }
123 nodes = nodes.slice()
124 return { ...graph, nodes, edges }
125}
126src/model/ledger.ts 96 lines1import { resolvePath } from '../util/path'
2import type { LedgerLine } from '../../types'
3
4/** The `$` calls the writer needs, bound to whichever hook is appending. */
5export interface LedgerIO {
6 write: (path: string, text: string) => Promise<void>
7 onError?: (err: unknown) => void
8}
9
10export function encodeLedger(lines: readonly LedgerLine[]): string {
11 return lines.map(line => `${JSON.stringify(line)}\n`).join('')
12}
13
14function isLedgerLine(v: unknown): v is LedgerLine {
15 if (typeof v !== 'object' || v === null) return false
16 const { v: version, t } = v as { v?: unknown; t?: unknown }
17 return version === 1 && typeof t === 'string'
18}
19
20/** Parses a ledger; a cut-off last line (a crash mid-write) is dropped silently. */
21export function decodeLedger(text: string): { lines: LedgerLine[]; errors: string[] } {
22 const raw = text.split('\n')
23 let last = raw.length - 1
24 while (last >= 0 && raw[last]!.trim() === '') last--
25 const lines: LedgerLine[] = []
26 const errors: string[] = []
27 raw.forEach((row, i) => {
28 if (row.trim() === '') return
29 let value: unknown
30 try {
31 value = JSON.parse(row)
32 } catch {
33 if (i !== last) errors.push(`line ${i + 1}: not JSON`)
34 return
35 }
36 if (isLedgerLine(value)) lines.push(value)
37 else errors.push(`line ${i + 1}: not a v1 ledger line`)
38 })
39 return { lines, errors }
40}
41
42export function ledgerFileName(nowMs: number): string {
43 const d = new Date(nowMs)
44 const pad = (n: number, width = 2) => String(n).padStart(width, '0')
45 return (
46 `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}-` +
47 `${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}-` +
48 `${pad(d.getUTCMilliseconds(), 3)}.jsonl`
49 )
50}
51
52/** Absolute: `$.fs` resolves relative paths against the process, not the session. */
53export function ledgerPathFor(cwd: string, ledgerDir: string, nowMs: number): string {
54 return resolvePath(cwd, `${ledgerDir.replace(/\/+$/, '')}/${ledgerFileName(nowMs)}`)
55}
56
57/**
58 * Keeps every line in memory and writes through: each append rewrites the
59 * file, and appends made while a write is in flight ride on the next one. No
60 * timer, so a hot reload (which cancels pending waits) loses nothing.
61 */
62export class LedgerWriter {
63 readonly lines: LedgerLine[] = []
64 private isDirty = false
65 private isWriting = false
66
67 constructor(
68 readonly path: string,
69 initial: readonly LedgerLine[] = [],
70 ) {
71 this.lines.push(...initial)
72 }
73
74 append(line: LedgerLine, io: LedgerIO): void {
75 this.lines.push(line)
76 this.isDirty = true
77 if (!this.isWriting) void this.drain(io)
78 }
79
80 private async drain(io: LedgerIO): Promise<void> {
81 this.isWriting = true
82 try {
83 while (this.isDirty) {
84 this.isDirty = false
85 try {
86 await io.write(this.path, encodeLedger(this.lines))
87 } catch (err) {
88 io.onError?.(err)
89 }
90 }
91 } finally {
92 this.isWriting = false
93 }
94 }
95}
96src/model/reduce.ts 104 lines1import { applyChanges, resolveKey } from '../graph/ghost'
2import { basename } from '../util/path'
3import type { Counters, EntityChange, GhostGraph, LedgerLine, OpOutcome, Target, VizState } from '../../types'
4
5export function emptyViz(): VizState {
6 return {
7 ops: [],
8 counters: { ops: 0, errors: 0, nodes: 0, edges: 0 },
9 graph: null,
10 branch: null,
11 ghost: null,
12 touches: {},
13 }
14}
15
16/** A short name for where an op ran: the graph id, else the store/uri/cluster folder, else the server. */
17export function targetLabel(t: Target): string | null {
18 if (t.graph) return t.graph
19 const where = t.store ?? t.uri ?? t.cluster ?? t.target
20 if (where) return basename(where.replace(/\/+$/, ''))
21 return t.server ?? null
22}
23
24function outcomeBranch(o: OpOutcome): string | null {
25 switch (o.kind) {
26 case 'read':
27 return o.branch ?? null
28 case 'change':
29 case 'load':
30 return o.branch || null
31 case 'branch':
32 return o.action === 'merged' ? (o.into ?? null) : null
33 default:
34 return null
35 }
36}
37
38function addCounts(c: Counters, o: OpOutcome): Counters {
39 if (o.kind === 'error') return { ...c, errors: c.errors + 1 }
40 if (o.kind === 'change') return { ...c, nodes: c.nodes + o.nodes, edges: c.edges + o.edges }
41 if (o.kind === 'load') return { ...c, nodes: c.nodes + o.total }
42 return c
43}
44
45/** Node ids a diff touched: changed nodes and both ends of changed edges. */
46function diffTouches(graph: GhostGraph, changes: readonly EntityChange[]): string[] {
47 const ids = new Set<string>()
48 for (const c of changes) {
49 if (c.kind === 'node') {
50 ids.add(`${c.type}:${c.id}`)
51 continue
52 }
53 const ends = graph.edgeEnds[c.type]
54 for (const [key, type] of [[c.from, ends?.[0]], [c.to, ends?.[1]]] as const) {
55 const id = key === undefined ? undefined : resolveKey(graph, key, type)
56 if (id !== undefined) ids.add(id)
57 }
58 }
59 return [...ids]
60}
61
62export function reduce(s: VizState, line: LedgerLine): VizState {
63 if (line.t === 'graph') return { ...s, ghost: line.graph }
64 if (line.t === 'touch') return { ...s, touches: { ...s.touches, [line.opId]: line.nodeIds } }
65 if (line.t === 'diff') {
66 if (!s.ghost) return s
67 const ghost = applyChanges(s.ghost, line.changes)
68 return { ...s, ghost, touches: { ...s.touches, [line.opId]: diffTouches(ghost, line.changes) } }
69 }
70 if (line.t === 'op.start') {
71 return {
72 ...s,
73 ops: [...s.ops, line.op],
74 counters: { ...s.counters, ops: s.counters.ops + 1 },
75 graph: targetLabel(line.op.intent.target) ?? s.graph,
76 branch: line.op.intent.branch ?? s.branch,
77 }
78 }
79 if (line.t === 'op.end') {
80 const i = s.ops.findIndex(o => o.id === line.id)
81 const prev = s.ops[i]
82 if (!prev) return s
83 const ops = s.ops.slice()
84 ops[i] = {
85 ...prev,
86 status: line.status,
87 durationMs: line.durationMs,
88 outcome: line.outcome,
89 output: line.output,
90 }
91 return {
92 ...s,
93 ops,
94 counters: addCounts(s.counters, line.outcome),
95 branch: outcomeBranch(line.outcome) ?? s.branch,
96 }
97 }
98 return s
99}
100
101export function reduceAll(lines: readonly LedgerLine[], from: VizState = emptyViz()): VizState {
102 return lines.reduce(reduce, from)
103}
104src/model/state.ts 44 lines1import type { GraphState, OpEvent, ReplayView, UiState, ViewState, VizState } from '../../types'
2
3export const RECENT_OPS = 200
4
5export const INITIAL_UI: UiState = { tab: 'graph', selectedOpId: null }
6
7export const INITIAL_VIEW: ViewState = {
8 recentOps: [],
9 counters: { ops: 0, errors: 0, nodes: 0, edges: 0 },
10 graph: null,
11 branch: null,
12 ghost: { state: 'none', nodes: 0, edges: 0, truncated: false, message: null },
13 replay: null,
14}
15
16/** What the Feed lists: no raw output, no read cells (those stay in module memory). */
17function slim(op: OpEvent): OpEvent {
18 const { output: _output, ...rest } = op
19 if (rest.outcome?.kind === 'read') return { ...rest, outcome: { ...rest.outcome, cells: [] } }
20 return rest
21}
22
23export function toView(
24 viz: VizState,
25 state: GraphState = 'none',
26 message: string | null = null,
27 replay: ReplayView | null = null,
28): ViewState {
29 return {
30 ghost: {
31 state: viz.ghost ? 'ready' : state,
32 nodes: viz.ghost?.nodes.length ?? 0,
33 edges: viz.ghost?.edges.length ?? 0,
34 truncated: viz.ghost?.truncated ?? false,
35 message,
36 },
37 recentOps: viz.ops.slice(-RECENT_OPS).map(slim),
38 counters: viz.counters,
39 graph: viz.graph,
40 branch: viz.branch,
41 replay,
42 }
43}
44