Opt-in Claude Code mod for MCP Task Orchestrator: live work graph, gate band, and in-process orchestration hooks (early-access function-hooks API)

An opt-in Claude Code mod for MCP Task Orchestrator: a live work-graph pane, an in-flight band and status line, and in-process orchestration hooks. It ships as a separate plugin in the same marketplace as the task-orchestrator plugin and does not replace it.
A mod is a plugin of in-process TypeScript function hooks (hooks/hooks.json points at ./register.ts). It is additive: the server stays the gate authority, and the task-orchestrator plugin's command hooks remain the baseline for clients that do not load the mod.
The function-hooks API this mod uses is early access. A Claude Code update can break the mod or switch it off. It was built and tested against Claude Code 2.1.286, and the per-build types file shipped with your Claude Code is the authority on the API.
If the mod misbehaves, disable it. The task-orchestrator command hooks resume by themselves, because the dedupe flags (see Dedupe with the command hooks) are only set when the mod handled the event.
Verification status:
/to-graph pane and the band.mcp-task-orchestrator. The name is fixed in the mod and matches the registration shown in the root README. The mod speaks the 4.0 tools (items_read, notes_read, deps_read, runs_read, advance, items_write, notes_write, deps_write, runs_write, config) and reads every result from its envelope (structuredContent); a 3.x server is not supported..taskorchestrator/config.yaml with project.rootId, read relative to the session working directory.curl on PATH. See Live updates.Marketplace install, after the existing marketplace add from the root README:
/plugin install task-orchestrator-mod@task-orchestrator-marketplace
To disable it:
/plugin disable task-orchestrator-mod@task-orchestrator-marketplace
From a checkout on disk:
claude --plugin-dir <repo>/claude-plugins/task-orchestrator-mod
On the desktop app, where no flag can be passed, set CLAUDE_CODE_PLUGIN_DIRS in the process environment or in the env block of ~/.claude/settings.json. Do not put it in project settings. Both forms are watched and hot-reload on save.
Headless claude -p and claude plugin test need CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1.
Do not load the marketplace copy and a disk copy at the same time.
The marketplace install path has not yet been confirmed end to end. If your build needs an extra enable step, it is not described here.
The graph pane draws boxes and edges differently per surface. The terminal falls back to a raster; every other surface uses an SVG edge layer.
| Surface | Rendering | Status |
|---|---|---|
| Terminal | Boxes with a box-drawing edge raster | Kit-tested, not live-verified |
| Desktop Code tab | Boxes with an SVG edge layer; cell size comes from userConfig | Live-verified |
| VS Code and mobile | Take the SVG path | Unverified |
On all surfaces:
clip, pbcopy, wl-copy or xclip). On mobile that is the host machine's clipboard, which is unverified./to-graphroot or an item id./to-graph, or the band opening the pane, starts in auto: while the pane is open, a TO call or a spawned agent that names an item outside the graph moves the pane to that item's owning scope. An id argument, root, This feature, Whole project, a breadcrumb, Open graph or a click on a box pins the scope, and a pinned scope never moves; the Follow button (shown only while pinned) or a bare /to-graph returns to auto. Besides this session's own activity, an item transition made by another session in this project (an item.advanced event outside this session's echo window) moves an auto pane after a 3 second pause, when this session has been quiet for 30 seconds.This feature and Whole project. The whole-project view is an overview of the root's children with role roll-ups, from a single call limited to 100 children; past that it shows "More children than shown."properties.planLabel (1 to 12 characters).Show done steps / Hide done steps toggle.Loading ... shows while the scope switches.stalled marks an item whose last move was 30 minutes ago or more. gate: marks this session's gate-blocked advance and is kept for 10 minutes.seat · model. A star marks a recent change. A ? marks an item with an open decision (from decision.* events on the live stream; an answered or withdrawn decision clears it).runs: <n> open, <m> paused while the project has open or paused runs (from run.* events on the live stream).get view.Reconnect shows only when live updates are degraded.item-id · done/total done · ready: ... · waiting: .... Otherwise it shows the in-flight item and its gate./to-band hides or shows it.TO, the item id prefix and a finished/remaining count.curl stream, or a 15 second poll) runs for the whole session.Opt-in through graphToasts. A toast appears when an item completes, becomes ready, is sent back from review to work, or one of this session's advances is gate-blocked. At most three toasts are shown per snapshot.
A change made by another session, seen over the live stream outside a short window after your own writes, is marked in the graph. Poll mode never marks changes.
The mod offers the session retrospective itself, by spawning the retrospective agent, when the session is not headless, a config is readable (at AGENT_CONFIG_DIR or the working directory) and extensions.claude-code.retrospective.mode is not off. It follows run marks, like the command hooks: a retrospective is owed per closed run on the project root that is not marked retro. On a successful runs_write close (and again at Stop) it lists the root's closed, unmarked runs of the last 24 hours, reads each run's terminal count, and in dispatch mode at or above dispatchThreshold tries to win the run's retro mark (first write wins, so two sessions never both dispatch) before spawning one agent for /session-retrospective --run <runId>; otherwise it nudges. In a subagent, or without a project rootId, the close is recorded and the Stop nudges once. Test-kit verified, not live-verified.
The mark goes over the REST API (the server serves runs_write mark over REST only): it needs the server's REST API enabled (API_ENABLED=true), curl on PATH, and the same API URL and token resolution as live updates. The token is passed to curl on stdin, never on the command line. Without the REST API, or when the mark fails, every dispatch-eligible run is nudged instead of dispatched.
An in-process version of the phase guard that blocks a sub-agent from stopping with its phase notes unfilled. It records the items an advance call entered (a transition, or a gate_blocked element), reads each item's gate with items_read context, and never records a call made under a run seatToken or blocks a workflow subagent. Test-kit verified, not live-verified.
Test-kit verified, not live-verified. The mod repairs common call shapes before the server sees them, and logs one transcript line call-shape: <tool> <rule> for each rule it applied. An input already in the 4.0 shape is passed through unchanged.
ancestorId=<project rootId> into items_read list, next, blocked and item-less context calls. It applies only when all of these hold: ancestorId is absent, there is no parentId, a list has depth other than 0, there is no tags, type or traits filter, and a root id resolves.ancestorId: "" is the opt-out: the mod removes it and injects nothing.op and no ops is wrapped into ops[0] (atomic and seatToken stay at the top).transitions[] on advance or notes[] on notes_write becomes ops[], each element given op: "transition" or op: "upsert" when it has none.actor and an actor on any ops element are removed (4.0 takes the caller from the transport and refuses a body actor).items_write create and update, properties.traits moves to the op's traits (dropped when the op already has traits).The mod never guesses a missing type: the server's schema_violation lists the available types.
The mod and the plugin's command hooks would otherwise act twice on the same event. The mod forwards a flag on the classic event, and the matching command hook exits early when it sees it.
| Area | Flag the mod sets | Command hooks that step aside |
|---|---|---|
| Retrospective | to_mod_retro: true, on classic.PostToolUse (runs_write) and classic.Stop | retro-trigger and retro-backstop |
| Phase guard | to_mod_active: true, after a clean run, on classic.PostToolUse (advance) and classic.SubagentStop | phase-guard-record and phase-guard |
If the phase guard hits an internal error it sends no flag, and the command hook acts instead.
Skill enforcement is deliberately not ported: a flag on PreToolUse would land inside the tool input, so the command hook stays authoritative. There is no actor-attribution hook: 4.0 takes the caller from the transport.
Call-shape rewrites need no dedupe: the mod's tool-call hook runs before the classic PreToolUse, so the command hooks see the repaired input.
Version: pair the mod with the task-orchestrator plugin 4.0.0. The early exits exist only in a task-orchestrator plugin newer than 3.9.0; with an older plugin, the retrospective is offered twice (a spawned agent plus the command-hook directive), and both phase guards block.
Live updates need the server's REST API (API_ENABLED=true) and curl on PATH.
The API URL is resolved in this order:
TASK_ORCHESTRATOR_API_URL environment variable..taskorchestrator/client.json in the working directory (a bare loopback origin only).client.json under TASK_ORCHESTRATOR_HOME, HOME or USERPROFILE.A bearer token from TASK_ORCHESTRATOR_API_TOKEN is passed to curl on stdin, never on the command line. The mod streams GET /api/v1/events for the project root, subscribed to the 4.0 item, note, dependency, scope, run, seat and decision events. An event that arrives while one of this session's writes is in flight, or within 5 seconds after the last one, is this session's own echo; every other event came from another session. The event's actor is not used: in 4.0 it is the transport principal, which every session on one credential shares.
A reconnect resumes the stream: the mod sends the last event id it saw as Last-Event-ID (kept as text, since event ids are above 10^12). When the server cannot replay from it, the first frame is sync.lost; the graph re-reads at once and the stream resumes from the id the sync.lost frame carries. A restarted live source (Reconnect, or the pane and band all closed) starts without a resume id.
With no URL, or after three failed connects, a 15 second poll takes over. Reconnect in the pane restarts the stream.
Set these from the plugin's config menu rows, or in settings under pluginConfigs["task-orchestrator-mod"].options.
| Option | Default | Meaning |
|---|---|---|
cellWidthPx | 8.4 | Width of one character cell in the desktop pane; clamped to 4-32 |
cellHeightPx | 18 | Height of one character cell in the desktop pane; clamped to 8-64 |
graphToasts | false | Show graph toasts |
client.json are resolved from the session working directory only. There is no walk-up, no main-checkout lookup from a linked worktree, and no user-level config, unlike the task-orchestrator hooks. A session in a linked worktree falls back to polling unless the API URL is set through the environment or a user-level client.json.mcp-task-orchestrator./to-graph and /to-band are registered lazily, on the first band draw or snapshot./to-graph <prefix> of the root id walks the subtree instead of showing the overview; Copy UUID on Linux may report unavailable; a critical path can drop the SVG layer; and a teardown error can replace a tool result.ancestorId: "" to opt out):items_read context (the health view): process-global scopes such as Retrospective Trends, Observations or Proposals lose their active, blocked and stalled items.items_read blocked: blocked process-global items vanish from the broad view.items_read list with claimStatus: "claimed": claims outside the root are hidden.items_read next: work outside the root is not offered.The skills are not changed by the mod.
runs_read decisions is director-only)./to-graph <prefix> needs at least 8 hex characters on a 4.0 server.Authoring and testing rules for this plugin are in CLAUDE.md.
hooks/register.ts 21 lines1// Entry module for the task-orchestrator-mod plugin. Thin by design: each feature lives under
2// src/<feature>/ and owns its own hooks; this file only wires them. Add a feature by importing its
3// register function here — do not put hook logic in this file.
4import type { Register } from 'claude-code'
5
6import { registerBand } from '../src/band/index.ts'
7import { registerCallShape } from '../src/call-shape/index.ts'
8import { registerGraphData } from '../src/graph-data/index.ts'
9import { registerGraphPane } from '../src/graph-pane/index.ts'
10import { registerPhaseGuard } from '../src/phase-guard/index.ts'
11import { registerRetro } from '../src/retro/index.ts'
12
13export const register: Register = (on, options) => {
14 registerGraphData(on, options)
15 registerGraphPane(on, options)
16 registerBand(on)
17 registerRetro(on)
18 registerPhaseGuard(on)
19 registerCallShape(on)
20}
21src/band/index.ts 119 lines1// Status line + AbovePrompt band: in-flight item and gate progress (T4).
2// Owned by work item ec1e2f91-1d16-43dc-a9c9-f86aea28a050. Read-only: it draws from T2's snapshot
3// atom and makes no TO call and no write beyond its own state.
4//
5// The validator follows `$` only into functions of the same file, so the atoms below are this
6// file's own same-literal declarations of graph-data's keys (an atom is a typed reference to a
7// host-held value); only the pure steps and types come from graph-data.
8import { atom, read, update } from 'claude-code'
9import type { EngineInterface, On } from 'claude-code'
10
11import type { GraphSnapshot } from '../../types'
12import { addSubscriber, requestLiveSync } from '../graph-data/index.ts'
13import { bandLine, bandModel } from './model.ts'
14
15/** Below this many columns the band hides; the status line still carries the item. */
16export const MIN_BAND_COLUMNS = 40
17
18/** The /to-graph pane's id (graph-pane PANE_ID); the band's text opens it. */
19const PANE_ID = 'to-graph'
20
21const graphSnapshot = atom({ plugin: 'task-orchestrator-mod', key: 'graphSnapshot' } as const, null as GraphSnapshot | null)
22const graphSubscribers = atom({ plugin: 'task-orchestrator-mod', key: 'graphSubscribers' } as const, 0)
23const graphPaneOpen = atom({ plugin: 'task-orchestrator-mod', key: 'graphPaneOpen' } as const, false)
24const graphScopeMode = atom({ plugin: 'task-orchestrator-mod', key: 'graphScopeMode' } as const, 'auto' as 'auto' | 'pinned')
25const bandHidden = atom({ plugin: 'task-orchestrator-mod', key: 'bandHidden' } as const, false)
26const bandSubscribed = atom({ plugin: 'task-orchestrator-mod', key: 'bandSubscribed' } as const, false)
27
28const toggle = (hidden: boolean): boolean => !hidden
29const hide = (): boolean => true
30const yes = (): boolean => true
31const auto = (): 'auto' | 'pinned' => 'auto'
32
33/** Set once per module load, so a hot reload (which drops the registered command) registers it again. */
34let commandRegistered = false
35
36/**
37 * Brings the status line to the current snapshot, subscribes the band once per session (bandSubscribed
38 * lives in $.state, so a hot reload does not count twice) and registers /to-band, the way back after
39 * Hide. Idempotent; safe to call from any hook.
40 */
41async function sync($: EngineInterface): Promise<void> {
42 $.ui.status(bandModel(await read($, graphSnapshot), true).status)
43 if (!(await read($, bandSubscribed))) {
44 await update($, bandSubscribed, yes)
45 await update($, graphSubscribers, addSubscriber)
46 requestLiveSync(await read($, graphSubscribers))
47 }
48 if (!commandRegistered) {
49 commandRegistered = true
50 await $.command.register({ name: 'to-band', description: 'Show or hide the Task Orchestrator in-flight band' })
51 }
52}
53
54/**
55 * The band's text pressed: open the work graph pane on the current scope, and count it once as a
56 * subscriber, the same steps /to-graph runs (graph-pane index.ts). Run directly, not through a hook on
57 * our own state write (a plugin's own `$.state.set` does not reliably reach its own hooks).
58 */
59async function openPane($: EngineInterface): Promise<void> {
60 await $.ui.open({ id: PANE_ID, title: 'TO graph' })
61 if (!(await read($, graphPaneOpen))) {
62 // The band opens the pane on the current scope without choosing one: follow this session's activity.
63 await update($, graphScopeMode, auto)
64 await update($, graphPaneOpen, yes)
65 await update($, graphSubscribers, addSubscriber)
66 requestLiveSync(await read($, graphSubscribers))
67 }
68}
69
70export function registerBand(on: On): void {
71 // Graph-data writes the snapshot atom; this observes the write after it lands. There is no
72 // session.start hook here (graph-data owns the one unmatched session.start and the validator refuses
73 // a second). A write raised from a timer callback may not reach this hook in every engine, so the
74 // prompt and turn hooks below run the same sync from events that always dispatch the whole chain;
75 // the status line is then at worst one prompt or turn behind.
76 on('state.set', { plugin: 'task-orchestrator-mod', key: 'graphSnapshot' }, async ($, e, next) => {
77 const wrote = await next(e)
78 const result = wrote as { isSet?: boolean; value?: { isSet?: boolean } }
79 if (result.isSet === true || result.value?.isSet === true) await sync($)
80
81 return wrote
82 })
83
84 on('prompt.submit', async ($, e, next) => {
85 await sync($)
86
87 return next(e)
88 })
89
90 on('turn.complete', async ($, e, next) => {
91 await sync($)
92
93 return next(e)
94 })
95
96 on('command.run', { command: 'to-band' }, async $ => {
97 const hidden = await update($, bandHidden, toggle)
98
99 return { text: hidden ? 'In-flight band hidden. Run /to-band to show it again.' : 'In-flight band shown.' }
100 })
101
102 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
103 if (e.props.hasSurvey || e.props.bodyColumns < MIN_BAND_COLUMNS) return next(e)
104 if (await read($, bandHidden)) return next(e)
105 // The smart line while the graph is scoped to an item, else today's in-flight line (model.ts).
106 const text = bandLine(await read($, graphSnapshot), e.props.bodyColumns)
107 if (text === undefined) return next(e)
108
109 const { Box, Button } = $.ui.resolve(e)
110
111 return h(
112 Box,
113 null,
114 h(Button, { key: 'band-open', label: text, plain: true, onPress: () => openPane($) }),
115 h(Button, { key: 'hide', label: 'Hide', onPress: () => update($, bandHidden, hide) }),
116 )
117 })
118}
119src/call-shape/index.ts 35 lines1// Call-shape repair rewrites for TO tool calls (T7, ported to the 4.0 tools).
2// Owned by work item cedcfc11-6205-432d-8968-371bdf1cb917.
3//
4// `tool.call` sits above `classic.PreToolUse`, so the TO command hooks see the repaired input. Only the
5// call's shape is repaired; server validation and write semantics are untouched.
6import type { On } from 'claude-code'
7
8import { PLUGIN, toToolName } from '../shared/constants.ts'
9import { CONFIG_PATH, parseProjectRootId } from '../shared/config.ts'
10import { isOwnCall, rewriteCall } from './rewrite.ts'
11
12/** Every 4.0 TO tool: R1/R2 apply to items_read, W1-W4 to the write tools, W3 to all. */
13const REPAIRED_TOOLS = /^mcp__.*task-orchestrator.*__(?:advance|config|deps_read|deps_write|docs_read|docs_write|items_read|items_write|notes_read|notes_write|report|runs_read|runs_write)$/
14
15export function registerCallShape(on: On): void {
16 on('tool.call', { tool: REPAIRED_TOOLS }, async ($, e, next) => {
17 const tool = toToolName(e.tool)
18 if (tool === null || isOwnCall(next.origin?.plugin, PLUGIN)) return next(e)
19
20 let rootId: string | null = null
21 try {
22 rootId = parseProjectRootId(await $.fs.read(CONFIG_PATH))
23 } catch {
24 rootId = null
25 }
26
27 const { input, changes } = rewriteCall(tool, e as unknown as Record<string, unknown>, rootId)
28 if (changes.length === 0) return next(e)
29
30 for (const change of changes) $.ui.log(`call-shape: ${change}`)
31
32 return next(input as unknown as typeof e)
33 })
34}
35src/graph-data/index.ts 254 lines1// Graph snapshot data layer + live invalidation (T2).
2// Owned by work item 32492bfa-93d5-4e72-93cc-e56ecf8b68c8. Read-only: the data layer renders
3// nothing and never calls a TO write tool. T3 (pane) and T4 (band) import from this file.
4//
5// This is the only file here that touches `$`: the plugin validator follows `$` only into functions
6// declared in the same file, so `graphIo` turns `$` into plain functions (GraphIo) and every other
7// module takes that. Consumers control the layer through the atoms (see the atoms below), not by calling
8// helpers with their own `$`.
9import { atom, read, update } from 'claude-code'
10import type { EngineInterface, On, PluginOptions } from 'claude-code'
11
12import { PLUGIN, TO_SERVER, toToolName } from '../shared/constants.ts'
13import { envelopeOf, parseToResult } from '../shared/to-client.ts'
14import type { GraphDecision, GraphRun, GraphSnapshot, GraphStatus } from '../../types'
15import { touchedIds } from '../graph-pane/activity.ts'
16import { snapshotEvents, toastLines } from './events.ts'
17import type { GraphIo } from './io.ts'
18import { invalidateLabels } from './labels.ts'
19import { restartLive, syncLive } from './live.ts'
20import { refresh, refreshNow, sameSnapshot, sameStatus } from './refresh.ts'
21import { clearRemote, resultItemIds, withLocalWrite } from './remote.ts'
22
23export type { GateInfo, GraphDecision, GraphEdge, GraphNode, GraphRun, GraphSnapshot, GraphStatus } from '../../types'
24// ── Atoms: the control and data surface for T3 (pane) and T4 (band) ──
25// Consumers cannot call helpers that take `$` (the validator follows `$` only into functions of the
26// same file), so they use the library's `update($, atom, step)` / `read($, atom)` on these:
27// - show a scope: update($, graphScope, scopeTo(id)) // null = the project root
28// - start/stop live: update($, graphSubscribers, addSubscriber) // on pane/band open
29// update($, graphSubscribers, removeSubscriber) // on close
30// - ask for a refresh: update($, graphRefreshRequest, bump)
31// The write alone does not reach this plugin's own state.set hooks reliably, so each write is followed by
32// the matching `$`-free request function below (requestRefresh, requestLiveSync, requestReconnect).
33// The state.set hooks further down remain a backstop. Plugin and key are literals so
34// `claude plugin validate` can list them.
35
36/** The item id in view; null means the project root. Writing it re-snapshots at once. */
37export const graphScope = atom({ plugin: 'task-orchestrator-mod', key: 'graphScope' } as const, null as string | null)
38
39/** The latest snapshot, or null before the first one lands. Written by graph-data only. */
40export const graphSnapshot = atom({ plugin: 'task-orchestrator-mod', key: 'graphSnapshot' } as const, null as GraphSnapshot | null)
41
42/** Whether a refresh is running, the last error, and which live source keeps the snapshot current. */
43export const graphStatus = atom(
44 { plugin: 'task-orchestrator-mod', key: 'graphStatus' } as const,
45 { refreshing: false, liveSource: 'none' } as GraphStatus,
46)
47
48/** Consumers showing the graph. The SSE stream or the poll runs only while this is above 0. */
49export const graphSubscribers = atom({ plugin: 'task-orchestrator-mod', key: 'graphSubscribers' } as const, 0)
50
51/** Bump it to request a debounced re-snapshot. */
52export const graphRefreshRequest = atom({ plugin: 'task-orchestrator-mod', key: 'graphRefreshRequest' } as const, 0)
53
54/** Bump it to restart the live source (SSE/poll) and re-snapshot. */
55export const graphReconnectRequest = atom({ plugin: 'task-orchestrator-mod', key: 'graphReconnectRequest' } as const, 0)
56
57/** Items whose last change came from another session (SSE, not our echo): short id -> when (ms). Written through graphIo.updateRemote only. */
58export const graphRemote = atom({ plugin: 'task-orchestrator-mod', key: 'graphRemote' } as const, {} as Record<string, number>)
59
60/** Open decisions seen over SSE: short item id -> decision. Written through graphIo.updateDecisions only. */
61export const graphDecisions = atom({ plugin: 'task-orchestrator-mod', key: 'graphDecisions' } as const, {} as Record<string, GraphDecision>)
62
63/** The project's open and paused runs seen over SSE: run id -> status. Written through graphIo.updateRuns only. */
64export const graphRuns = atom({ plugin: 'task-orchestrator-mod', key: 'graphRuns' } as const, {} as Record<string, GraphRun>)
65
66/** Steps for `update($, atom, step)`. */
67export const addSubscriber = (n: number): number => n + 1
68export const removeSubscriber = (n: number): number => Math.max(0, n - 1)
69export const bump = (n: number): number => n + 1
70export const scopeTo =
71 (id: string | null) =>
72 (): string | null =>
73 id
74
75export type { GraphIo } from './io.ts'
76export { snapshot } from './snapshot.ts'
77export { invalidateLabels } from './labels.ts'
78export { remoteAdvanceListener, setRemoteAdvanceListener } from './live.ts'
79
80/** TO tools whose calls can change the graph; a call of one re-snapshots. */
81export const WRITE_TOOLS: ReadonlySet<string> = new Set(['advance', 'items_write', 'notes_write', 'deps_write', 'runs_write', 'config'])
82
83/** The engine's spelling of those tools (`mcp__<server>__<tool>`), for the hook matcher. */
84export const WRITE_TOOL_NAME = /^mcp__.*task-orchestrator.*__(advance|items_write|notes_write|deps_write|runs_write|config)$/
85
86/**
87 * Whether a finished tool call should refresh the graph: a TO write tool, not raised by this plugin's own
88 * `$` call (its reads re-enter `tool.call`), and not denied. `isError` is not consulted: a 4.0 batch that
89 * partly failed is `isError: true` although some of its elements wrote.
90 */
91export function shouldRefresh(tool: string, originPlugin: string, result: { deny?: unknown }): boolean {
92 const name = toToolName(tool)
93
94 return name !== null && WRITE_TOOLS.has(name) && originPlugin !== PLUGIN && result.deny === undefined
95}
96
97/**
98 * The IO bound when the session started. A plugin's own `$.state.set` does not reliably reach its own
99 * `state.set` hooks (verified live 2026-10-05: scope changes never refreshed), so consumers in this
100 * plugin call these `$`-free functions right after writing a control atom.
101 */
102let sessionIo: GraphIo | null = null
103
104/** The `graphToasts` option (default off): set by registerGraphData, read when a snapshot lands. */
105let toastsOn = false
106
107/** Re-snapshot for the current scope now (a scope change) or after the debounce window. */
108export function requestRefresh(now = true): void {
109 if (sessionIo !== null) void (now ? refreshNow(sessionIo) : refresh(sessionIo))
110}
111
112/** Restart the live source and re-snapshot (the Reconnect button). */
113export function requestReconnect(subscribers: number): void {
114 if (sessionIo === null) return
115 invalidateLabels()
116 restartLive(sessionIo, subscribers)
117 void refreshNow(sessionIo)
118}
119
120/** Start or stop the live source for a new subscriber count (pane or band opened or closed). */
121export function requestLiveSync(subscribers: number): void {
122 if (sessionIo !== null) syncLive(sessionIo, subscribers)
123}
124
125function graphIo($: EngineInterface): GraphIo {
126 return {
127 callTool: async (tool, args) => parseToResult<unknown>(tool, await $.mcp.call(TO_SERVER, tool, args)),
128 readFile: path => $.fs.read(path),
129 now: () => $.clock.now(),
130 after: (ms, fn) => $.clock.after(ms, fn),
131 every: (ms, fn) => $.clock.every(ms, fn),
132 sleep: (ms, signal) => $.clock.sleep(ms, { signal }),
133 spawn: request => $.process.spawn(request),
134 readScope: () => read($, graphScope),
135 // Skip writes that change nothing: every write redraws the pane and band (and flashes the Svg frame).
136 // A real change may raise toasts (graphToasts on): only against the previous snapshot of the same
137 // scope, so the first snapshot after a load or a scope switch is quiet (events.ts).
138 setSnapshot: async value => {
139 const prev = await read($, graphSnapshot)
140 if (sameSnapshot(prev, value)) return
141 await update($, graphSnapshot, () => value)
142 if (toastsOn) for (const line of toastLines(snapshotEvents(prev, value))) $.ui.toast(line)
143 },
144 updateRemote: async step => {
145 const current = await read($, graphRemote)
146 if (step(current) === current) return
147 await update($, graphRemote, step)
148 },
149 updateDecisions: async step => {
150 const current = await read($, graphDecisions)
151 if (step(current) === current) return
152 await update($, graphDecisions, step)
153 },
154 updateRuns: async step => {
155 const current = await read($, graphRuns)
156 if (step(current) === current) return
157 await update($, graphRuns, step)
158 },
159 updateStatus: async change => {
160 // Pre-check only: the write applies `change` to the value current at write time, so a
161 // concurrent setLiveSource is never overwritten by a stale precomputed status.
162 const current = await read($, graphStatus)
163 if (sameStatus(current, change(current))) return
164 await update($, graphStatus, change)
165 },
166 envApiUrl: () => $.env.get('TASK_ORCHESTRATOR_API_URL'),
167 envApiToken: () => $.env.get('TASK_ORCHESTRATOR_API_TOKEN'),
168 homeDir: async () => (await $.env.get('TASK_ORCHESTRATOR_HOME')) || (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')),
169 }
170}
171
172/**
173 * A local write clears the remote marks of every item it named or that its result names (cascades included),
174 * only when its result has an envelope that is ok or carries `data.results` (a partial batch). No envelope, or
175 * a whole-call refusal, clears nothing. Advisory.
176 */
177async function clearLocalMarks($: EngineInterface, e: unknown, ran: unknown): Promise<void> {
178 const env = envelopeOf(ran)
179 if (env === null) return
180 const results = (env.data as { results?: unknown } | undefined)?.results
181 if (env.ok !== true && !Array.isArray(results)) return
182 const ids = [...touchedIds(e).map(t => t.id), ...resultItemIds(ran)]
183 if (ids.length === 0) return
184 try {
185 await graphIo($).updateRemote?.(map => clearRemote(map, ids))
186 } catch {
187 // marks are advisory
188 }
189}
190
191export function registerGraphData(on: On, options: PluginOptions = {}): void {
192 toastsOn = options.graphToasts === true
193 // Matched (the validator refuses a second unmatched `tool.call`): same names as WRITE_TOOLS.
194 // Matcher spelled as a literal: the engine resolves matchers from source, and an imported or exported constant stays unresolved (never matches).
195 on('tool.call', { tool: /^mcp__.*task-orchestrator.*__(advance|items_write|notes_write|deps_write|runs_write|config)$/ }, async ($, e, next) => {
196 if (next.origin.plugin === PLUGIN) return next(e)
197 // The local-write window: SSE events for this write (its echo) are not marked as remote (remote.ts).
198 const ran = await withLocalWrite(() => next(e), () => $.clock.now())
199 // Debounced and never awaited: the model's call is not slowed by the snapshot.
200 if (shouldRefresh(e.tool, next.origin.plugin, ran)) {
201 if (toToolName(e.tool) === 'items_write') invalidateLabels()
202 void refresh(graphIo($))
203 void clearLocalMarks($, e, ran)
204 }
205
206 return ran
207 })
208
209 on('session.start', async ($, e, next) => {
210 const started = await next(e)
211 sessionIo = graphIo($)
212 // A hot reload resets module state (the live source) but $.state survives, so resume live from the
213 // surviving subscriber count. A fresh session has 0, which makes this a no-op.
214 syncLive(sessionIo, await read($, graphSubscribers))
215 void refresh(sessionIo)
216
217 return started
218 })
219
220 // Consumer controls: they write these atoms, and the layer reacts once the write has landed.
221 // state.set matchers use the literal plugin name for the same reason (an imported PLUGIN never matched).
222 on('state.set', { plugin: 'task-orchestrator-mod', key: 'graphScope' }, async ($, e, next) => {
223 const wrote = await next(e)
224 if (wrote.isSet) void refreshNow(graphIo($))
225
226 return wrote
227 })
228
229 on('state.set', { plugin: 'task-orchestrator-mod', key: 'graphRefreshRequest' }, async ($, e, next) => {
230 const wrote = await next(e)
231 if (wrote.isSet) void refresh(graphIo($))
232
233 return wrote
234 })
235
236 on('state.set', { plugin: 'task-orchestrator-mod', key: 'graphReconnectRequest' }, async ($, e, next) => {
237 const wrote = await next(e)
238 if (wrote.isSet) {
239 invalidateLabels()
240 restartLive(graphIo($), await read($, graphSubscribers))
241 void refreshNow(graphIo($))
242 }
243
244 return wrote
245 })
246
247 on('state.set', { plugin: 'task-orchestrator-mod', key: 'graphSubscribers' }, async ($, e, next) => {
248 const wrote = await next(e)
249 if (wrote.isSet) syncLive(graphIo($), typeof e.value === 'number' ? e.value : 0)
250
251 return wrote
252 })
253}
254src/graph-pane/index.ts 735 lines1// /to-graph pane: a top-down dependency graph of keyed, state-filled boxes (T3 a47dcd6f, rewritten).
2// Read-only: the pane makes only items_read and notes_read calls and no TO write tool, ever.
3//
4// This is the only file here that touches `$` (the plugin validator follows `$` only into functions
5// of the same file). Control is atom-driven, so the atoms below are this file's own same-literal
6// declarations of graph-data's keys; only the pure steps come from the other modules.
7import { atom, read, update } from 'claude-code'
8import type { EngineInterface, On, PluginOptions } from 'claude-code'
9
10import type { GraphActivity, GraphAgentInfo, GraphDecision, GraphDetail, GraphRun, GraphSnapshot, GraphStatus } from '../../types'
11import { CONFIG_PATH, parseProjectRootId } from '../shared/config.ts'
12import { PLUGIN, TO_SERVER } from '../shared/constants.ts'
13import { parseToResult } from '../shared/to-client.ts'
14import { addSubscriber, bump, removeSubscriber, requestLiveSync, requestReconnect, requestRefresh, scopeTo, setRemoteAdvanceListener, shouldRefresh } from '../graph-data/index.ts'
15import { GATE_BLOCK_MS, WORKING_TTL_MS, RECENT_MS, gateBlocks, pruneActivity, recordActivity, recordGateBlocks, rememberAgent, resolveId, seatOf, touchedIds } from './activity.ts'
16import type { GateBlockRow } from './activity.ts'
17import { edgePlan, extrasChars, marksFit } from './budget.ts'
18import { cellSize } from './cell.ts'
19import { layoutTD } from './layout.ts'
20import { cut, titleLines } from './wrap.ts'
21import type { TopDown } from './layout.ts'
22import { cardsOf, criticalPath, stepsOf } from './model.ts'
23import type { Card, CriticalPath, Model } from './model.ts'
24import { recordFocusOrder, redirectFocus } from './focus.ts'
25import { gateToastLines } from '../graph-data/events.ts'
26import { decisionGlyph, runSummary } from '../graph-data/runs.ts'
27import { activeScope, detailLines, firstSpawnUuid, isDegraded, isSwitching, loadingTitle, owningScope, parseScopeArg, scopeHeader, summaryLine } from './pane-model.ts'
28import type { ToolCall } from './pane-model.ts'
29import { CRIT_COLOR, raster, runs } from './raster.ts'
30import { routes } from './route.ts'
31import { KIND, READY, id8, legendItems } from './shared.ts'
32import type { GraphView } from './shared.ts'
33import { edgeSvg, px } from './svg.ts'
34
35export const PANE_ID = 'to-graph'
36
37/** Every TO tool this pane calls; none is a write tool. */
38export const READ_TOOLS: readonly string[] = ['items_read', 'notes_read']
39
40const graphSnapshot = atom({ plugin: 'task-orchestrator-mod', key: 'graphSnapshot' } as const, null as GraphSnapshot | null)
41const graphStatus = atom({ plugin: 'task-orchestrator-mod', key: 'graphStatus' } as const, { refreshing: false, liveSource: 'none' } as GraphStatus)
42const graphScope = atom({ plugin: 'task-orchestrator-mod', key: 'graphScope' } as const, null as string | null)
43const graphScopeMode = atom({ plugin: 'task-orchestrator-mod', key: 'graphScopeMode' } as const, 'auto' as 'auto' | 'pinned')
44const graphSubscribers = atom({ plugin: 'task-orchestrator-mod', key: 'graphSubscribers' } as const, 0)
45const graphReconnectRequest = atom({ plugin: 'task-orchestrator-mod', key: 'graphReconnectRequest' } as const, 0)
46const graphPaneOpen = atom({ plugin: 'task-orchestrator-mod', key: 'graphPaneOpen' } as const, false)
47const graphDetail = atom({ plugin: 'task-orchestrator-mod', key: 'graphDetail' } as const, null as GraphDetail | null)
48const graphActivity = atom({ plugin: 'task-orchestrator-mod', key: 'graphActivity' } as const, { working: {}, changed: {} } as GraphActivity)
49const graphAgents = atom({ plugin: 'task-orchestrator-mod', key: 'graphAgents' } as const, {} as Record<string, GraphAgentInfo>)
50const graphShowDone = atom({ plugin: 'task-orchestrator-mod', key: 'graphShowDone' } as const, false)
51const graphRemote = atom({ plugin: 'task-orchestrator-mod', key: 'graphRemote' } as const, {} as Record<string, number>)
52const graphDecisions = atom({ plugin: 'task-orchestrator-mod', key: 'graphDecisions' } as const, {} as Record<string, GraphDecision>)
53const graphRuns = atom({ plugin: 'task-orchestrator-mod', key: 'graphRuns' } as const, {} as Record<string, GraphRun>)
54
55/** The engine's spelling of every TO tool (`mcp__<server>__<tool>`); reads count as "working on it". */
56const TO_TOOL = /^mcp__.*task-orchestrator.*__[a-z_]+$/
57
58const yes = (): boolean => true
59const no = (): boolean => false
60const pinned = (): 'auto' | 'pinned' => 'pinned'
61const auto = (): 'auto' | 'pinned' => 'auto'
62
63/** Items already resolved to an owning scope (null: none). Capped; a repeat touch of an id reads nothing. */
64const SCOPE_MEMO_MAX = 200
65const scopeMemo = new Map<string, string | null>()
66
67/** Set once per module load, so a hot reload (which drops the registered command) registers it again. */
68let commandRegistered = false
69
70/**
71 * Copies `text` with the host's clipboard tool (`clip` on Windows, `pbcopy` on macOS, `wl-copy` or
72 * `xclip` on Linux). Used when `$.ui.copy` cannot reach the surface, as on the desktop app today.
73 */
74async function hostCopy($: EngineInterface, text: string): Promise<boolean> {
75 const windows = (await $.env.get('OS')) === 'Windows_NT'
76 const tools: string[][] = windows ? [['clip']] : [['pbcopy'], ['wl-copy'], ['xclip', '-selection', 'clipboard']]
77 for (const argv of tools) {
78 try {
79 const ran = await $.process.run(argv, { stdin: text, timeoutMs: 3000 })
80 if (ran.exitCode === 0) return true
81 } catch {
82 // that tool is not installed here; try the next
83 }
84 }
85
86 return false
87}
88
89/**
90 * The scope `/to-graph` opens with no argument: the owning scope of the latest transition under the
91 * project root (pane-model `activeScope`), else the most recently modified feature-implementation in
92 * work, else null. A failed or empty scope read falls back to the legacy query; no root id makes no call.
93 */
94async function activeFeature($: EngineInterface): Promise<string | null> {
95 try {
96 const rootId = parseProjectRootId(await $.fs.read(CONFIG_PATH))
97 if (rootId === null) return null
98 const call = async (tool: string, args: Record<string, unknown>): Promise<unknown> => parseToResult<unknown>(tool, await $.mcp.call(TO_SERVER, tool, args))
99 try {
100 const scope = await activeScope(call, rootId, await $.clock.now())
101 if (scope !== null) return scope
102 } catch {
103 // fall through to the legacy rule
104 }
105 const found = (await call('items_read', {
106 select: 'list',
107 ancestorId: rootId,
108 type: 'feature-implementation',
109 role: 'work',
110 sort: 'modifiedAt',
111 order: 'desc',
112 limit: 1,
113 })) as { items?: { id?: unknown }[] }
114 const id = found.items?.[0]?.id
115
116 return typeof id === 'string' ? id : null
117 } catch {
118 return null
119 }
120}
121
122const message = (err: unknown): string => (err instanceof Error ? err.message : String(err))
123
124/** Reads the three read-only calls for one node into the detail atom. Each failure is tolerated. In-pane, read-only. */
125async function openDetail($: EngineInterface, itemId: string): Promise<void> {
126 // Clicking a node is a choice of focus: stop following this session's activity.
127 await update($, graphScopeMode, pinned)
128 const call = async (tool: string, args: Record<string, unknown>): Promise<unknown> => parseToResult<unknown>(tool, await $.mcp.call(TO_SERVER, tool, args))
129 const [ctx, item, notes] = await Promise.allSettled([
130 call('items_read', { select: 'context', itemId }),
131 call('items_read', { select: 'get', itemId, fields: ['createdAt', 'modifiedAt', 'roleChangedAt'] }),
132 call('notes_read', { select: 'list', itemId, limit: 200 }),
133 ])
134 const now = await $.clock.now()
135 const lines =
136 ctx.status === 'rejected'
137 ? [`Could not read ${id8(itemId)}: ${message(ctx.reason)}`]
138 : detailLines({
139 itemId,
140 ctx: ctx.value,
141 now,
142 ...(item.status === 'fulfilled' ? { item: item.value } : { itemFailed: true }),
143 ...(notes.status === 'fulfilled' ? { notes: notes.value } : { notesFailed: true }),
144 })
145 // Graph ids are short ids; the full UUID (for Copy UUID) comes from the get view.
146 const full = item.status === 'fulfilled' && typeof (item.value as { id?: unknown })?.id === 'string' ? ((item.value as { id: string }).id) : undefined
147 await update($, graphDetail, () => ({ itemId, lines, ...(full !== undefined ? { uuid: full } : {}) }))
148}
149
150/**
151 * Auto mode only, pane open: re-scopes the pane to the owning scope of the first candidate id the
152 * snapshot cannot place (one attempt per call). Never throws; the caller's result is untouched.
153 */
154async function followActivity($: EngineInterface, pick: (rootId: string) => string[]): Promise<void> {
155 try {
156 if ((await read($, graphScopeMode)) !== 'auto' || !(await read($, graphPaneOpen))) return
157 const snap = await read($, graphSnapshot)
158 if (snap === null) return
159 const rootId = parseProjectRootId(await $.fs.read(CONFIG_PATH))
160 if (rootId === null) return
161 const known = snap.nodes.map(n => n.id)
162 const target = pick(rootId).find(c => resolveId(c, known) === null)
163 if (target === undefined) return
164 const key = `${rootId}:${target}`
165 let scope: string | null
166 if (scopeMemo.has(key)) scope = scopeMemo.get(key) ?? null
167 else {
168 const call: ToolCall = async (tool, args) => parseToResult<unknown>(tool, await $.mcp.call(TO_SERVER, tool, args))
169 try {
170 scope = await owningScope(call, target, rootId)
171 } catch {
172 scope = null
173 }
174 if (scopeMemo.size >= SCOPE_MEMO_MAX) scopeMemo.delete(scopeMemo.keys().next().value as string)
175 scopeMemo.set(key, scope)
176 }
177 if (scope === null || scope === (await read($, graphScope))) return
178 await update($, graphDetail, () => null)
179 await update($, graphScope, scopeTo(scope))
180 requestRefresh()
181 } catch {
182 // following is best effort: the model's call is never affected
183 }
184}
185
186/** Seat and expiry bookkeeping of one TO tool call: who is working on which snapshot item, what changed. */
187async function noteActivity(
188 $: EngineInterface,
189 e: { tool: string; agentId?: string },
190 changed: boolean,
191): Promise<void> {
192 const snap = await read($, graphSnapshot)
193 if (snap === null) return
194 const known = snap.nodes.map(n => n.id)
195 const agents = await read($, graphAgents)
196 const hits: { id: string; seat: string; model?: string }[] = []
197 for (const t of touchedIds(e)) {
198 const id = resolveId(t.id, known)
199 if (id === null) continue
200 const model = e.agentId !== undefined ? agents[e.agentId]?.model : undefined
201 hits.push({ id, seat: seatOf(e.agentId, agents), ...(model !== undefined ? { model } : {}) })
202 }
203 if (hits.length === 0) return
204 const now = await $.clock.now()
205 const fold = (cur: GraphActivity): GraphActivity => hits.reduce((acc, h) => recordActivity(acc, { ...h, agentId: e.agentId ?? 'main', changed }, now), cur)
206 const before = await read($, graphActivity)
207 if (fold(before) === before) return
208 await update($, graphActivity, fold)
209 // Entries expire even when nothing else redraws the pane (and a hot reload drops these timers: every
210 // record call prunes first, so stale entries clear on the next write too).
211 const prune = async (): Promise<void> => {
212 const t = await $.clock.now()
213 const cur = await read($, graphActivity)
214 if (pruneActivity(cur, t) !== cur) await update($, graphActivity, c => pruneActivity(c, t))
215 }
216 if (changed) $.clock.after(RECENT_MS + 500, () => void prune())
217 $.clock.after(WORKING_TTL_MS + 500, () => void prune())
218}
219
220/** Marks this session's gate-blocked advance elements on their snapshot items; they expire after GATE_BLOCK_MS. */
221async function noteGateBlocks($: EngineInterface, rows: readonly GateBlockRow[]): Promise<void> {
222 const snap = await read($, graphSnapshot)
223 if (snap === null) return
224 const known = snap.nodes.map(n => n.id)
225 const hits: { id: string; missing: string[]; target?: string }[] = []
226 for (const r of rows) {
227 const id = resolveId(r.itemId, known)
228 if (id !== null) hits.push({ id, missing: r.missing, ...(r.targetRole !== undefined ? { target: r.targetRole } : {}) })
229 }
230 if (hits.length === 0) return
231 const now = await $.clock.now()
232 const before = await read($, graphActivity)
233 if (recordGateBlocks(before, hits, now) === before) return
234 await update($, graphActivity, cur => recordGateBlocks(cur, hits, now))
235 $.clock.after(GATE_BLOCK_MS + 500, async () => {
236 const t = await $.clock.now()
237 const cur = await read($, graphActivity)
238 if (pruneActivity(cur, t) !== cur) await update($, graphActivity, c => pruneActivity(c, t))
239 })
240}
241
242/** With the `graphToasts` option on: one toast per gate-blocked row of this session (capped; events.ts). */
243async function toastGateBlocks($: EngineInterface, rows: readonly GateBlockRow[]): Promise<void> {
244 for (const line of gateToastLines(rows, await read($, graphSnapshot))) $.ui.toast(line)
245}
246
247/** What the tool.call hook needs of the outside world: record one call's activity and its gate blocks. */
248export interface ActivityIo {
249 note: (e: { tool: string; agentId?: string }, changed: boolean) => Promise<void>
250 gate: (rows: readonly GateBlockRow[]) => Promise<void>
251}
252
253/** The toast goes first: a block on an item outside the snapshot is still worth one, and marking it may throw. */
254const activityIo = ($: EngineInterface, toasts: boolean): ActivityIo => ({
255 note: async (e, changed) => {
256 await noteActivity($, e, changed)
257 await followActivity($, () => touchedIds(e).map(t => t.id))
258 },
259 gate: async rows => {
260 if (toasts) await toastGateBlocks($, rows)
261 await noteGateBlocks($, rows)
262 },
263})
264
265/**
266 * The tool.call hook body: skips the pane's own calls, always returns the call's result untouched.
267 * The gate blocks are recorded after the call's activity, so the call's own write does not clear them.
268 */
269export async function trackToolCall<E extends { tool: string; agentId?: string }, R extends { deny?: unknown; isError?: unknown; result?: unknown }>(
270 io: ActivityIo,
271 e: E,
272 next: ((e: E) => Promise<R>) & { origin: { plugin: string } },
273): Promise<R> {
274 if (next.origin.plugin === PLUGIN) return next(e)
275 const ran = await next(e)
276 try {
277 await io.note(e, shouldRefresh(e.tool, next.origin.plugin, ran))
278 const blocks = ran.deny === undefined ? gateBlocks(e.tool, ran) : []
279 if (blocks.length > 0) await io.gate(blocks)
280 } catch {
281 // bookkeeping only: the model's call is never affected
282 }
283
284 return ran
285}
286
287/** Registers /to-graph once per module load. Idempotent. */
288async function ensureCommand($: EngineInterface): Promise<void> {
289 if (commandRegistered) return
290 commandRegistered = true
291 try {
292 await $.command.register({ name: 'to-graph', description: 'Open the Task Orchestrator work graph (active feature, an item id, or root)' })
293 } catch {
294 commandRegistered = false
295 }
296}
297
298type Ui = ReturnType<EngineInterface['ui']['resolve']>
299
300interface BoxSpec {
301 key: string
302 id: string
303 rect: { left: number; top: number; width: number; height: number }
304 fill: string
305 line1: string
306 line3: string
307 /** The state line is a warning: drawn undimmed. */
308 warn: boolean
309 recent: boolean
310 /** Last changed by another session: `⇄ ` after the `✱ ` on line 1. */
311 remote: boolean
312 /** The open-decision glyph (`?`) after those, or '' when the item has no open decision. */
313 decision: string
314}
315
316/**
317 * Below this many boxes every line of a box is clickable; from it on only the state line. 90 whole-click
318 * cards (COST.wholeCardChars) leave room for step chips in the tree budget; canvasOf also falls back to
319 * one Button per box whenever whole-click boxes alone would not fit.
320 */
321export const WHOLE_CLICK_MAX = 90
322
323/** One state-filled box: a pure function of its spec (an id-derived key, nothing view-wide). */
324function boxOf(ui: Ui, s: BoxSpec, open: (id: string) => void, wholeClick = true): unknown {
325 const { Box, Text, Button } = ui
326 const n = s.rect.width - 2
327 // A recently changed item is marked in its title (a Button label takes no colour); a change made by
328 // another session adds `⇄ ` after it.
329 const [first, second] = titleLines(`${s.recent ? '✱ ' : ''}${s.remote ? '⇄ ' : ''}${s.decision !== '' ? `${s.decision} ` : ''}${s.line1}`, n)
330 const press = () => open(s.id)
331 const dim = s.warn ? {} : { dimColor: true }
332
333 const frame = { key: s.key, position: 'absolute', top: s.rect.top, left: s.rect.left, width: s.rect.width, height: s.rect.height, backgroundColor: s.fill, flexDirection: 'column', paddingX: 1 }
334 if (!wholeClick) {
335 return h(
336 Box,
337 frame,
338 h(Text, { color: '#ffffff', bold: true, wrap: 'truncate-end' }, first),
339 h(Text, { color: '#ffffff', wrap: 'truncate-end' }, second),
340 h(Button, { key: `open:${s.id}`, label: cut(s.line3, n) || ' ', plain: true, ...dim, onPress: press }),
341 )
342 }
343
344 // Box takes no onPress and a Button label is a single string, so every line of the box is a plain
345 // Button opening the same detail: a click anywhere on the box opens it.
346 return h(
347 Box,
348 frame,
349 h(Button, { key: `open:${s.id}:1`, label: first || ' ', plain: true, onPress: press }),
350 h(Button, { key: `open:${s.id}:2`, label: second || ' ', plain: true, onPress: press }),
351 h(Button, { key: `open:${s.id}`, label: cut(s.line3, n) || ' ', plain: true, ...dim, onPress: press }),
352 )
353}
354
355interface CanvasInput {
356 model: Model
357 lay: TopDown
358 desktop: boolean
359 cell: { w: number; h: number }
360 steps: number
361 open: (id: string) => void
362 count: number
363 /** The project-root overview: the root plus one row of children, no steps. */
364 overview: boolean
365 /** What the detail panel and breadcrumb add (charged to the edge drawing only). */
366 extraChars: number
367 /** The critical path (empty on the overview). */
368 crit: CriticalPath
369 /** Open decisions by short item id (graphDecisions), for the per-box glyph. */
370 decisions: Record<string, GraphDecision>
371}
372
373/** The graph canvas (or a one-line notice when the tree would not fit). */
374function canvasOf(ui: Ui, i: CanvasInput): unknown[] {
375 const { Box, Text, Svg } = ui
376 const { model, lay } = i
377 const rs = routes(lay, model.cards, i.desktop ? 'px' : 'cell', i.crit.edges)
378 const critIds = new Set(i.crit.ids.filter(id => lay.cards.has(id)))
379 const marks = critIds.size
380 let edges: unknown = null
381 let plan: ReturnType<typeof edgePlan>
382 const cardCount = lay.cards.size + (model.root !== undefined ? 1 : 0)
383 // Whole-click costs more per card: fall back to one Button per card rather than refuse the boxes.
384 const wholeClick = model.cards.length < WHOLE_CLICK_MAX && edgePlan({ desktop: i.desktop, wholeClick: true, cards: cardCount, chips: lay.chips.length, cells: 0, runs: 0, svgChars: 0, svgWidth: 0, svgHeight: 0 }) !== 'too-large'
385 if (i.desktop) {
386 const svg = edgeSvg(rs, i.cell, lay.width, lay.height)
387 plan = edgePlan({ desktop: true, wholeClick, extraChars: i.extraChars, marks, cards: lay.cards.size + (model.root !== undefined ? 1 : 0), chips: lay.chips.length, cells: 0, runs: 0, svgChars: svg.length, svgWidth: px(lay.width, i.cell.w), svgHeight: px(lay.height, i.cell.h) })
388 if (plan === 'full' && Svg !== undefined) {
389 edges = h(Box, { key: 'edges', position: 'absolute', top: 0, left: 0 }, h(Svg, { source: svg, alt: 'dependency edges', width: px(lay.width, i.cell.w), height: px(lay.height, i.cell.h) }))
390 }
391 } else {
392 const cells = raster(rs)
393 const merged = runs(cells)
394 plan = edgePlan({ desktop: false, wholeClick, extraChars: i.extraChars, marks, cards: lay.cards.size + (model.root !== undefined ? 1 : 0), chips: lay.chips.length, cells: cells.size, runs: merged.length, svgChars: 0, svgWidth: 0, svgHeight: 0 })
395 if (plan === 'full') {
396 edges = h(
397 Box,
398 { key: 'edges', position: 'absolute', top: 0, left: 0, width: lay.width, height: lay.height },
399 ...[...cells].map(([k, c]) => {
400 const [x, y] = k.split('_').map(Number) as [number, number]
401
402 return h(Box, { key: `e:${k}`, position: 'absolute', top: y, left: x, width: 1, height: 1 }, h(Text, { color: c.color, dimColor: c.dim }, c.glyph))
403 }),
404 )
405 } else if (plan === 'runs') {
406 edges = h(
407 Box,
408 { key: 'edges', position: 'absolute', top: 0, left: 0, width: lay.width, height: lay.height },
409 ...merged.map(r => h(Box, { key: `e:${r.x}_${r.y}`, position: 'absolute', top: r.y, left: r.x, width: r.n, height: 1 }, h(Text, { color: r.color, dimColor: r.dim }, r.glyph.repeat(r.n)))),
410 )
411 }
412 }
413 if (plan === 'too-large') {
414 recordFocusOrder(null)
415
416 return [h(Text, { key: 'too-large' }, `Too large to draw (${i.count} items). Open a smaller scope.`)]
417 }
418 // Stripes go with the edges; with boxes only, when they still fit (they never refuse the scope).
419 const stripes = marks > 0 && marksFit({ desktop: i.desktop, wholeClick, extraChars: i.extraChars, marks, cards: cardCount, chips: lay.chips.length, cells: 0, runs: 0, svgChars: 0, svgWidth: 0, svgHeight: 0 }, plan)
420 /** Box ids in drawn order, for the one-stop-per-box focus. */
421 const order: string[] = []
422
423 const byId = new Map(model.cards.map(c => [c.id, c]))
424 const boxes: unknown[] = []
425 const root = model.root
426 if (root !== undefined) {
427 const words = root.kind === 'terminal' ? 'done' : root.kind
428 boxes.push(
429 boxOf(ui, { key: `card:${root.id}`, id: root.id, rect: lay.root, fill: KIND[root.kind], line1: `${root.glyph} [${root.label}] ${root.title}`, line3: i.overview ? `${words} · ${model.cards.length} children` : `${words} · ${model.cards.length} items · ${i.steps} steps`, warn: false, recent: false, remote: false, decision: decisionGlyph(root.id, i.decisions) }, i.open, wholeClick),
430 )
431 order.push(root.id)
432 }
433 for (const row of lay.rows) {
434 if (row.chip) {
435 const chip = lay.chips.find(c => c.step === row.step)
436 if (chip === undefined) continue
437 boxes.push(
438 h(
439 Box,
440 { key: `step:${chip.step}`, position: 'absolute', top: chip.rect.top, left: chip.rect.left, width: chip.rect.width, height: 1, backgroundColor: KIND.terminal },
441 h(Text, { color: '#ffffff', wrap: 'truncate-end' }, `✓ step ${chip.step} · ${chip.done} done${chip.cancelled > 0 ? `, ${chip.cancelled} cancelled` : ''}`),
442 ),
443 )
444 continue
445 }
446 for (const id of row.ids) {
447 const card = byId.get(id) as Card
448 const rect = lay.cards.get(id)
449 if (rect === undefined) continue
450 boxes.push(boxOf(ui, { key: `card:${id}`, id, rect, fill: card.ready ? READY : KIND[card.kind], line1: `${card.glyph} [${card.label}] ${card.title}`, line3: card.stateText, warn: card.warn, recent: card.recent, remote: card.remote, decision: decisionGlyph(id, i.decisions) }, i.open, wholeClick))
451 order.push(id)
452 // A sibling stripe on the card's left column: the card's own subtree is untouched (G5 keys hold).
453 if (stripes && critIds.has(id)) {
454 boxes.push(h(Box, { key: `crit:${id}`, position: 'absolute', top: rect.top, left: rect.left, width: 1, height: rect.height, backgroundColor: CRIT_COLOR }))
455 }
456 }
457 }
458 recordFocusOrder(order)
459
460 const omitted = plan === 'omit' ? [h(Text, { key: 'edges-omitted', dimColor: true }, 'Too many edges to draw here; boxes only.')] : []
461
462 return [...omitted, h(Box, { key: 'canvas', position: 'relative', width: lay.width, height: lay.height }, ...(edges !== null ? [edges] : []), ...boxes)]
463}
464
465export function registerGraphPane(on: On, options: PluginOptions = {}): void {
466 const cell = cellSize(options as { cellWidthPx?: unknown; cellHeightPx?: unknown })
467 const toasts = options.graphToasts === true
468
469 // Every unmatched hook of the session events is already taken (graph-data owns session.start, band
470 // owns prompt.submit/turn.complete, and the validator refuses a second one), so the command is
471 // registered from two matched hooks: the first snapshot landing (graph-data refreshes at session
472 // start) and the first AbovePrompt draw, whichever comes first. Idempotent.
473 on('state.set', { plugin: 'task-orchestrator-mod', key: 'graphSnapshot' }, async ($, e, next) => {
474 const wrote = await next(e)
475 await ensureCommand($)
476
477 return wrote
478 })
479
480 // The terminal redraws the prompt area at once and often, so this is the reliable early trigger.
481 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
482 await ensureCommand($)
483
484 return next(e)
485 })
486
487 on('command.run', { command: 'to-graph' }, async ($, e) => {
488 const arg = parseScopeArg(e.args)
489 if (arg.kind === 'invalid') return { text: `Unknown argument "${arg.text}". Use /to-graph, /to-graph root, or /to-graph <item id>.` }
490 const scope = arg.kind === 'id' ? arg.id : arg.kind === 'root' ? null : await activeFeature($)
491
492 await update($, graphDetail, () => null)
493 await update($, graphScopeMode, arg.kind === 'active' ? auto : pinned)
494 await update($, graphScope, scopeTo(scope))
495 requestRefresh()
496 await $.ui.open({ id: PANE_ID, title: 'TO graph' })
497 // Counted once per open pane: a repeat /to-graph neither double-counts nor leaks a subscriber.
498 // Another session's transition in this project (graph-data/live.ts, debounced and quiet-gated): a $-free listener over this pane's own follow.
499 setRemoteAdvanceListener(itemId => void followActivity($, () => [itemId]))
500 if (!(await read($, graphPaneOpen))) {
501 await update($, graphPaneOpen, yes)
502 await update($, graphSubscribers, addSubscriber)
503 requestLiveSync(await read($, graphSubscribers))
504 }
505
506 return { text: scope === null ? 'Opened the work graph for the project root.' : `Opened the work graph for ${scope.slice(0, 8)}.` }
507 })
508
509 on('ui.close', { id: PANE_ID }, async ($, e, next) => {
510 const closed = await next(e)
511 setRemoteAdvanceListener(null)
512 if (await read($, graphPaneOpen)) {
513 await update($, graphPaneOpen, no)
514 await update($, graphSubscribers, removeSubscriber)
515 requestLiveSync(await read($, graphSubscribers))
516 }
517
518 return closed
519 })
520
521 // Remembers each spawned subagent's seat and model, so its TO calls can be attributed. Unmatched, and
522 // the only agent.spawn hook of the mod; the result is returned untouched.
523 on('agent.spawn', async ($, e, next) => {
524 const spawned = await next(e)
525 if (spawned.agentId !== undefined) {
526 const agentId = spawned.agentId
527 const info: GraphAgentInfo = { seat: e.subagentType.replace(/^[^:]+:/, ''), ...(spawned.model !== undefined ? { model: spawned.model } : {}) }
528 try {
529 await update($, graphAgents, cur => rememberAgent(cur, agentId, info))
530 } catch {
531 // bookkeeping only: the spawn is never affected
532 }
533 }
534 await followActivity($, rootId => {
535 const id = firstSpawnUuid(e.description, e.prompt, rootId)
536
537 return id === null ? [] : [id]
538 })
539
540 return spawned
541 })
542
543 // Who is working on which item, and what changed a moment ago. Matched (the mod's other tool.call hooks
544 // are matched too); the pane's own reads are skipped; the result is always returned as it came.
545 on('tool.call', { tool: TO_TOOL }, ($, e, next) => trackToolCall(activityIo($, toasts), e, next))
546
547 // One focus stop per box: a whole-click box's title lines hand the ring to its state line (focus.ts).
548 // Matcher spelled as a literal (an imported constant stays unresolved and never matches).
549 on('ui.focus', { requestId: 'to-graph' }, async ($, e, next) => redirectFocus(e, next))
550
551 on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e) => {
552 // Cross-session follow: (re)set the one-slot listener on every draw so a pane opened from the band or redrawn after a hot reload still follows (a draw after close is harmless: followActivity checks graphPaneOpen).
553 setRemoteAdvanceListener(itemId => void followActivity($, () => [itemId]))
554 const ui = $.ui.resolve(e)
555 const { Box, Text, Button, Svg } = ui
556 const snap = await read($, graphSnapshot)
557 const status = await read($, graphStatus)
558 const scope = await read($, graphScope)
559 const mode = await read($, graphScopeMode)
560 const detail = await read($, graphDetail)
561 const activity = await read($, graphActivity)
562 const showDone = await read($, graphShowDone)
563 const remote = (await read($, graphRemote)) ?? {}
564 const decisions = (await read($, graphDecisions)) ?? {}
565 const runSummaryText = runSummary((await read($, graphRuns)) ?? {})
566 const open = (id: string): Promise<void> => openDetail($, id)
567
568 const view: GraphView | null = snap
569 const switching = isSwitching(scope, snap)
570 const model = view === null ? null : cardsOf(view, activity.working, activity.changed, activity.blocked ?? {}, remote)
571 const steps = model === null ? null : stepsOf(model.cards)
572 const crit: CriticalPath = model === null || steps === null || view?.overview === true ? { ids: [], edges: new Set() } : criticalPath(model.cards, steps)
573 const lay = model === null || steps === null ? null : layoutTD(model.cards, steps, { bodyColumns: (e.props as { bodyColumns?: number }).bodyColumns, showDone: showDone || view?.overview === true, hasRoot: model.root !== undefined, wrap: view?.overview === true })
574
575 // Refresh is automatic (SSE or poll); Reconnect restarts the live source and shows only while degraded.
576 const controls = h(
577 Box,
578 { key: 'controls', flexDirection: 'row', columnGap: 1, marginBottom: 1 },
579 // Two-state scope toggle; the active scope draws as the primary button.
580 h(Button, {
581 key: 'scope-feature',
582 label: 'This feature',
583 ...(scope !== null ? { variant: 'primary' } : {}),
584 onPress: async () => {
585 const feature = await activeFeature($)
586 if (feature === null) $.ui.toast('No active feature in this project.')
587 else {
588 await update($, graphScopeMode, pinned)
589 await update($, graphScope, scopeTo(feature))
590 requestRefresh()
591 }
592 },
593 }),
594 h(Button, { key: 'scope-project', label: 'Whole project', ...(scope === null ? { variant: 'primary' } : {}), onPress: async () => {
595 await update($, graphScopeMode, pinned)
596 await update($, graphScope, scopeTo(null))
597 requestRefresh()
598 } }),
599 // Shown only while pinned: back to following this session's own TO activity (the bare /to-graph result).
600 ...(mode === 'pinned'
601 ? [h(Button, { key: 'scope-follow', label: 'Follow', onPress: async () => {
602 await update($, graphScopeMode, auto)
603 await update($, graphScope, scopeTo(await activeFeature($)))
604 requestRefresh()
605 } })]
606 : []),
607 ...(lay !== null && view?.overview !== true && lay.doneSteps.length > 0
608 ? [h(Button, { key: 'done-steps', label: showDone ? 'Hide done steps' : 'Show done steps', onPress: () => update($, graphShowDone, v => !v) })]
609 : []),
610 ...(isDegraded(status) ? [h(Button, { key: 'reconnect', label: 'Reconnect', onPress: async () => {
611 await update($, graphReconnectRequest, bump)
612 requestReconnect(await read($, graphSubscribers))
613 } })] : []),
614 )
615
616 if (view === null || model === null || steps === null || lay === null) {
617 return h(Box, { flexDirection: 'column' }, controls, h(Text, { key: 'loading' }, status.lastError ?? 'Loading the work graph…'))
618 }
619
620 // A scope switch is still loading: say so, and draw nothing of the old scope (the header would claim it).
621 if (switching) return h(Box, { flexDirection: 'column' }, controls, h(Text, { key: 'switching' }, `Loading ${loadingTitle(scope, snap)}…`))
622
623 // With a breadcrumb the scope is named there; the header keeps the counts and the live source.
624 const trail = view.trail ?? []
625 const header = [...(trail.length > 0 ? [] : [scopeHeader(view)]), summaryLine(view), ...(runSummaryText !== '' ? [runSummaryText] : []), `live: ${status.liveSource}${status.refreshing ? ' · refreshing' : ''}`].join(' · ')
626 const crumbs = trail.flatMap((c, i) => {
627 const last = i === trail.length - 1
628 const sep = i > 0 ? [h(Text, { key: `crumb-sep:${c.id}`, dimColor: true }, ' › ')] : []
629 if (last) return [...sep, h(Text, { key: `crumb:${c.id}`, bold: true }, cut(c.title, 40))]
630 const target = c.id === view.rootId ? null : c.id
631
632 return [
633 ...sep,
634 h(Button, {
635 key: `crumb:${c.id}`,
636 label: cut(c.title, 28),
637 plain: true,
638 onPress: async () => {
639 await update($, graphDetail, () => null)
640 await update($, graphScopeMode, pinned)
641 await update($, graphScope, scopeTo(target))
642 requestRefresh()
643 },
644 }),
645 ]
646 })
647 const body: unknown[] = []
648 if (view.truncated) body.push(h(Text, { key: 'truncated', dimColor: true }, view.overview === true ? 'More children than shown.' : 'Large subtree: showing only the shallowest 150 items.'))
649 if (view.error !== undefined) body.push(h(Text, { key: 'error', color: 'red' }, view.error))
650
651 if (view.nodes.length === 0) {
652 body.push(h(Text, { key: 'empty' }, 'No items in this scope.'))
653 } else {
654 body.push(
655 h(
656 Box,
657 { key: 'legend', flexDirection: 'row', flexWrap: 'wrap', rowGap: 1, marginBottom: 1 },
658 ...legendItems().map(item => h(Box, { key: `legend-${item.key}`, backgroundColor: item.color, paddingX: 1, marginRight: 1 }, h(Text, { color: '#ffffff' }, item.text))),
659 h(Box, { key: 'legend-ready', backgroundColor: READY, paddingX: 1, marginRight: 1 }, h(Text, { color: '#ffffff' }, '○ ready')),
660 h(Text, { key: 'legend-edges', dimColor: true }, '┄ contains ╌ open blocker ─ satisfied'),
661 ...(crit.ids.length > 0 ? [h(Text, { key: 'legend-crit', color: CRIT_COLOR }, ' ━ critical path')] : []),
662 ...(view.nodes.some(n => n.planLabel !== undefined) ? [h(Text, { key: 'legend-label', dimColor: true }, ' Tn = plan label')] : []),
663 ),
664 )
665 if (lay.tooWide !== null) {
666 body.push(h(Text, { key: 'too-wide', dimColor: true }, `Graph is ${lay.tooWide} columns wide; the pane shows ${lay.cols}. Widen the pane or open a smaller scope.`))
667 }
668 body.push(...canvasOf(ui, { model, lay, desktop: e.surface !== 'terminal' && Svg !== undefined, cell, steps: steps.max, open, count: view.nodes.length, overview: view.overview === true, extraChars: extrasChars(detail?.lines ?? null, trail.map(c => c.title)), crit, decisions }))
669 }
670
671 if (detail !== null) {
672 // The detail is its own bordered panel: title line bold, then facts, then a row of actions.
673 const uuid = detail.uuid ?? detail.itemId
674 const facts = [
675 ...detail.lines.map((line, i) => h(Text, { key: `detail-${i}`, ...(i === 0 ? { bold: true } : {}) }, line)),
676 h(Text, { key: 'detail-uuid', dimColor: true }, `uuid: ${uuid}`),
677 ]
678 const working = (activity.working[detail.itemId] ?? []).map(w =>
679 h(Text, { key: `working-${w.agentId}` }, `working: ${w.seat}${w.model !== undefined ? ` · ${w.model}` : ''} · ${w.agentId === 'main' ? 'main loop' : id8(w.agentId)}`),
680 )
681 const actions = [
682 h(Button, {
683 key: 'detail-copy',
684 label: 'Copy UUID',
685 onPress: async press => {
686 let copied = false
687 try {
688 const res = (await $.ui.copy({ text: uuid, surface: press.surface })) as { isCopied?: boolean; value?: { isCopied?: boolean } }
689 copied = res.isCopied === true || res.value?.isCopied === true
690 } catch {
691 copied = false
692 }
693 // $.ui.copy has no path on a remote surface (the desktop app) yet: fall back to the OS clipboard tool.
694 if (!copied) copied = await hostCopy($, uuid)
695 $.ui.toast(copied ? `Copied ${uuid}` : `Copy unavailable here. UUID: ${uuid}`)
696 },
697 }),
698 ...(detail.itemId !== view.scopeId
699 ? [
700 h(Button, {
701 key: 'detail-open-graph',
702 label: 'Open graph',
703 onPress: async () => {
704 await update($, graphDetail, () => null)
705 await update($, graphScopeMode, pinned)
706 await update($, graphScope, scopeTo(detail.itemId))
707 requestRefresh()
708 },
709 }),
710 ]
711 : []),
712 h(Button, { key: 'detail-close', label: 'Close detail', onPress: () => update($, graphDetail, () => null) }),
713 ]
714 body.push(
715 h(
716 Box,
717 { key: 'detail', flexDirection: 'column', borderStyle: 'round', borderColor: '#4b5563', paddingX: 1, marginTop: 1 },
718 ...facts,
719 ...working,
720 h(Box, { key: 'detail-actions', flexDirection: 'row', columnGap: 1, marginTop: 1 }, ...actions),
721 ),
722 )
723 }
724
725 return h(
726 Box,
727 { flexDirection: 'column', paddingX: 1 },
728 ...(crumbs.length > 0 ? [h(Box, { key: 'trail', flexDirection: 'row', flexWrap: 'wrap' }, ...crumbs)] : []),
729 h(Box, { key: 'header', marginBottom: 1 }, h(Text, { bold: crumbs.length === 0, dimColor: crumbs.length > 0 }, header)),
730 controls,
731 ...body,
732 )
733 })
734}
735src/phase-guard/index.ts 69 lines1// Phase guard in-process (T6, ported to the 4.0 tools).
2// Owned by work item 26246238-681f-497d-ae4c-6dbafd2c1e12.
3//
4// In-process ports of two TO command hooks, semantics unchanged except that reads go through the
5// engine's own MCP connection (D2) and state lives in session-scoped `$.state` (D7), so no tmpdir
6// marker file is written while the mod runs:
7// - phase-guard-record.mjs -> classic.PostToolUse (advance), registered
8// - phase-guard.mjs -> classic.SubagentStop, returns { block }, registered
9// The 3.x skill-enforcement and actor-attribution PreToolUse ports are gone: 4.0 refuses a body actor,
10// and a PreToolUse wrapper could not carry the dedupe flag anyway (it would land inside tool_input).
11//
12// Dedupe (D3): after a clean run the hook forwards `next({ ...e, [MOD_ACTIVE_FLAG]: true })` so the
13// command hook, which checks `to_mod_active` on stdin, exits early. On an internal error it forwards
14// without the flag and the command hook acts as the fallback. T1 P3 proved the flag reaches stdin on
15// classic.PostToolUse; SubagentStop is unproven (if it does not reach stdin, the command phase-guard
16// finds no marker - recording was suppressed - and no-ops, so nothing is lost or doubled).
17//
18// This is the only file here that touches `$` (the validator follows `$` only into functions declared
19// in the same file); `guardIo` turns `$` into the plain functions the rest takes.
20import type { EngineInterface, On } from 'claude-code'
21
22import type { PhaseGuardEntry } from '../../types'
23import { MOD_ACTIVE_FLAG, PLUGIN, TO_SERVER, toToolName } from '../shared/constants.ts'
24import { parseToResult } from '../shared/to-client.ts'
25import { checkStop, normalizeEntry, recordAdvance } from './core.ts'
26import type { GuardIo } from './core.ts'
27
28export { checkStop, recordAdvance } from './core.ts'
29
30function guardIo($: EngineInterface): GuardIo {
31 return {
32 getEntry: async agentId => normalizeEntry((await $.state.get({ plugin: 'task-orchestrator-mod', key: 'phaseGuardAgents', id: agentId } as const)).value),
33 setEntry: async (agentId, entry: PhaseGuardEntry) => {
34 await $.state.set({ plugin: 'task-orchestrator-mod', key: 'phaseGuardAgents', id: agentId } as const, entry)
35 },
36 callTo: async (tool, args) => parseToResult<unknown>(tool, await $.mcp.call(TO_SERVER, tool, args)),
37 isHeadless: async () => (await $.env.get('TASK_ORCHESTRATOR_MODE')) === 'headless-iteration',
38 }
39}
40
41export function registerPhaseGuard(on: On): void {
42 // phase-guard-record.mjs: remember which items a subagent entered a phase for.
43 on('classic.PostToolUse', async ($, e, next) => {
44 // Not an advance call, or one this plugin's own `$` call raised: pass through untouched (D4).
45 if (toToolName(e.tool_name) !== 'advance' || next.origin?.plugin === PLUGIN) return next(e)
46 try {
47 await recordAdvance(guardIo($), e as never)
48 } catch {
49 return next(e)
50 }
51
52 return next({ ...e, [MOD_ACTIVE_FLAG]: true } as never)
53 })
54
55 // phase-guard.mjs: block a subagent that stops with its phase's required notes missing.
56 on('classic.SubagentStop', async ($, e, next) => {
57 if (next.origin?.plugin === PLUGIN) return next(e)
58 let reason: string | null
59 try {
60 reason = await checkStop(guardIo($), e as never)
61 } catch {
62 return next(e)
63 }
64 if (reason !== null) return { block: reason }
65
66 return next({ ...e, [MOD_ACTIVE_FLAG]: true } as never)
67 })
68}
69src/retro/index.ts 310 lines1// Retrospective dispatch in-process (T5, ported to 4.0 run marks).
2// Owned by work item 0f4fe024-9c3f-454c-83f7-ec13de173355.
3//
4// In-process port of retro-trigger.mjs (PostToolUse on runs_write) and retro-backstop.mjs (Stop). State
5// lives in session-scoped `$.state` (it survives /compact and hot reload), the cross-session dedupe is the
6// server's `retro` run mark (first write wins), and the retrospective is spawned with `$.agent.spawn` at
7// the run boundary instead of being handed to the model as a directive.
8//
9// tool.call (runs_write) a successful close: in a subagent or without a project rootId, record it;
10// else evaluate the root's closed, unmarked runs (runs_read list + frontier,
11// REST runs_write mark) and add the one-line "queued" notice or a nudge to the
12// result's context
13// classic.PostToolUse forward `to_mod_retro` so retro-trigger.mjs steps aside
14// classic.Stop spawn the queued retrospective once nothing runs in the background; else
15// evaluate again (rootId) or nudge once from recorded closes (no rootId)
16// Reads go through the engine's own MCP connection (the mod's own calls are skipped by every mod hook, own
17// origin); the mark is REST only on the server, so it is a curl POST to /api/v1/ops/runs_write, and a failed
18// mark (no API URL, curl error, bad body, error envelope) nudges, never dispatches unmarked.
19//
20// Ownership: the mod owns retro handling only when the session is not a headless iteration AND the
21// cwd config is readable (the mod cannot see AGENT_CONFIG_DIR fallbacks such as the main-checkout or user
22// configs, and must not override a config it cannot see). Otherwise every hook passes through untouched
23// and the command hooks act as before. The flag is feature-scoped (`to_mod_retro`), so it cannot silence
24// another feature's command hook.
25//
26// This is the only file here that touches `$` (the validator follows `$` only into functions
27// declared in the same file); logic.ts is pure.
28import type { EngineInterface, On } from 'claude-code'
29
30import type { RetroState } from '../../types'
31import { CONFIG_PATH } from '../shared/config.ts'
32import { PLUGIN, TO_SERVER, toToolName } from '../shared/constants.ts'
33import { parseToResult } from '../shared/to-client.ts'
34import { resolveApiUrl } from '../graph-data/live.ts'
35import { readSection, scalar } from '../lib/yaml-lite.mjs'
36import {
37 QUEUED_NOTICE,
38 buildDispatch,
39 buildNudge,
40 buildSpawnPrompt,
41 evaluateRuns,
42 holdsForTasks,
43 markRequest,
44 normalizeState,
45 parseRetrospectiveConfig,
46 recordCloses,
47 successfulCloses,
48} from './logic.ts'
49import type { RetroCall, RetroConfig } from './logic.ts'
50
51/** Added to a classic.PostToolUse / classic.Stop event so the retro command hooks exit early. */
52export const RETRO_OWNED_FLAG = 'to_mod_retro'
53
54const MAX_RETRO_AGENTS = 20
55
56/** The one tool the retro hooks care about: runs_write (a run close). */
57const RETRO_TOOLS = /^mcp__.*task-orchestrator.*__runs_write$/
58
59type Ownership = { owned: boolean; cfg: RetroConfig; ancestorId: string | null }
60type Held = { state: RetroState; version: number }
61
62async function ownership($: EngineInterface): Promise<Ownership> {
63 const none: Ownership = { owned: false, cfg: parseRetrospectiveConfig(null), ancestorId: null }
64 if ((await $.env.get('TASK_ORCHESTRATOR_MODE')) === 'headless-iteration') return none
65 // Same first step as the command hooks' config-locator: $AGENT_CONFIG_DIR's config wins when readable.
66 // The rest of the locator (walk-up, main checkout of a worktree, user-level config) is not mirrored:
67 // the mod reads only the cwd-relative config, so ownership is claimed only for what it can see.
68 let text: string | null = null
69 const dir = await $.env.get('AGENT_CONFIG_DIR')
70 if (typeof dir === 'string' && dir.length > 0) {
71 try {
72 text = await $.fs.read(`${dir.replace(/[\\/]+$/, '')}/${CONFIG_PATH}`)
73 } catch {
74 text = null
75 }
76 }
77 if (text === null) {
78 try {
79 text = await $.fs.read(CONFIG_PATH)
80 } catch {
81 return none
82 }
83 }
84 const cfg = parseRetrospectiveConfig(text)
85 const section = readSection(text, 'project', { blockOnly: true })
86 const id = section ? scalar(section.lines, 'rootId') : null
87
88 return { owned: cfg.mode !== 'off', cfg, ancestorId: typeof id === 'string' && id.length > 0 ? id : null }
89}
90
91async function load($: EngineInterface): Promise<Held> {
92 const got = await $.state.get({ plugin: 'task-orchestrator-mod', key: 'retro' } as const)
93
94 return { state: normalizeState(got.value), version: got.version }
95}
96
97async function save($: EngineInterface, state: RetroState, ifVersion?: number): Promise<boolean> {
98 const res = await $.state.set({ plugin: 'task-orchestrator-mod', key: 'retro' } as const, state, ifVersion === undefined ? undefined : { ifVersion })
99
100 return res.isSet
101}
102
103/**
104 * A TO call returning the envelope `data` (rejects on an error envelope). Reads go over the engine's MCP
105 * connection; the one write, `runs_write` `mark`, is REST only on the server, so it is POSTed with curl
106 * (markRequest: the token rides curl's stdin, never argv, and never enters an error string).
107 */
108function toCall($: EngineInterface): RetroCall {
109 return async (tool, args) => {
110 if (tool !== 'runs_write') return parseToResult<unknown>(tool, await $.mcp.call(TO_SERVER, tool, args))
111 const base = await resolveApiUrl({
112 envApiUrl: () => $.env.get('TASK_ORCHESTRATOR_API_URL'),
113 readFile: p => $.fs.read(p),
114 homeDir: async () => (await $.env.get('TASK_ORCHESTRATOR_HOME')) || (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')),
115 })
116 if (base === null) throw new Error('runs_write: no REST API')
117 const ops = (args as { ops?: { runId?: unknown }[] }).ops
118 const runId = Array.isArray(ops) && typeof ops[0]?.runId === 'string' ? ops[0].runId : ''
119 const token = await $.env.get('TASK_ORCHESTRATOR_API_TOKEN')
120 const { argv, input } = markRequest(base, runId, token)
121 const ran = await $.process.run(argv, { stdin: input, timeoutMs: 3000 })
122 if (ran.exitCode !== 0) throw new Error(`runs_write: curl exit ${ran.exitCode}`)
123 let body: unknown
124 try {
125 body = JSON.parse(ran.stdout)
126 } catch {
127 throw new Error('runs_write: unparsable response')
128 }
129
130 return parseToResult<unknown>('runs_write', body)
131 }
132}
133
134/** True for a retrospective agent the mod spawned and for any agent it descends from one. */
135async function isRetroAgent($: EngineInterface, agentId: string | undefined, state: RetroState): Promise<boolean> {
136 const mine = state.retroAgents ?? []
137 if (agentId === undefined || mine.length === 0) return false
138 if (mine.includes(agentId)) return true
139 const list = await $.agent.list()
140 let cur = agentId
141 for (let i = 0; i < 10; i++) {
142 const parent = list.find(a => a.id === cur)?.parentId
143 if (parent === undefined) return false
144 if (mine.includes(parent)) return true
145 cur = parent
146 }
147
148 return false
149}
150
151function withContext<T extends object>(r: T, line: string): T {
152 const ctx = (r as { context?: readonly string[] }).context ?? []
153
154 return { ...r, context: [...ctx, line] }
155}
156
157function withBlock<T extends object>(r: T, text: string): T {
158 const prior = (r as { block?: string }).block
159
160 return { ...r, block: prior ? `${prior}\n\n${text}` : text }
161}
162
163/**
164 * Spawns one retrospective agent for `runs` and records it. False when the spawn was denied or threw (the
165 * caller then falls back to a Stop block carrying buildDispatch).
166 */
167async function spawnRetro($: EngineInterface, runs: readonly string[], ancestorId: string | null): Promise<boolean> {
168 let agentId: string | undefined
169 try {
170 const spawned = await $.agent.spawn({
171 subagentType: 'general-purpose',
172 model: 'sonnet',
173 description: 'Session retrospective',
174 prompt: buildSpawnPrompt(runs, ancestorId),
175 })
176 // Core sets agentId on a started agent; a denial carries `deny` and starts none.
177 if (spawned.deny !== undefined) return false
178 agentId = spawned.agentId
179 } catch {
180 return false
181 }
182 const now = await $.clock.now()
183 const cur = (await load($)).state
184 await save($, {
185 ...cur,
186 dispatched: { ...(agentId !== undefined && { agentId }), runs: [...runs], at: now },
187 ...(agentId !== undefined && { retroAgents: [...(cur.retroAgents ?? []), agentId].slice(-MAX_RETRO_AGENTS) }),
188 })
189
190 return true
191}
192
193/** Whether background work is running: the Stop event's own list, else the agent list. */
194async function isBusy($: EngineInterface, tasks: readonly { status: string }[] | undefined): Promise<boolean> {
195 return tasks !== undefined ? holdsForTasks(tasks) : holdsForTasks(await $.agent.list())
196}
197
198export function registerRetro(on: On): void {
199 on('tool.call', { tool: RETRO_TOOLS }, async ($, e, next) => {
200 if (next.origin?.plugin === PLUGIN) return next(e)
201 if (toToolName(e.tool) !== 'runs_write') return next(e)
202
203 let own: Ownership
204 let retro: boolean
205 try {
206 own = await ownership($)
207 if (!own.owned) return next(e)
208 retro = await isRetroAgent($, e.agentId, (await load($)).state)
209 } catch {
210 return next(e)
211 }
212 if (retro) return next(e)
213
214 const r = await next(e)
215 // `isError` is not consulted: a batch with a failed element is isError although its closes succeeded.
216 if (r.deny !== undefined) return r
217 try {
218 const closes = successfulCloses(e, r)
219 if (closes === null) return r
220 const cur = (await load($)).state
221 // A subagent never acts, and without a project rootId there is nothing to evaluate: record the close
222 // for the main session's Stop.
223 if (e.agentId !== undefined || own.ancestorId === null) {
224 await save($, recordCloses(cur, closes))
225
226 return r
227 }
228 const result = await evaluateRuns(toCall($), own.ancestorId, own.cfg, cur, await $.clock.now())
229 const updated: RetroState = result.won.length > 0 ? { ...result.state, pendingDispatch: [...new Set([...(result.state.pendingDispatch ?? []), ...result.won])] } : result.state
230 if (updated !== cur) await save($, updated)
231 if (result.won.length > 0) return withContext(r, QUEUED_NOTICE)
232 if (result.nudge.length > 0) return withContext(r, buildNudge(result.nudge))
233 } catch {
234 return r
235 }
236
237 return r
238 })
239
240 on('classic.PostToolUse', { tool_name: RETRO_TOOLS }, async ($, e, next) => {
241 if (toToolName(e.tool_name) !== 'runs_write' || next.origin?.plugin === PLUGIN) return next(e)
242 try {
243 if (!(await ownership($)).owned) return next(e)
244 } catch {
245 return next(e)
246 }
247
248 return next({ ...e, [RETRO_OWNED_FLAG]: true } as never)
249 })
250
251 on('classic.Stop', async ($, e, next) => {
252 if (next.origin?.plugin === PLUGIN) return next(e)
253 let own: Ownership
254 try {
255 own = await ownership($)
256 if (!own.owned) return next(e)
257 } catch {
258 return next(e)
259 }
260 // Other plugins' Stop hooks run first, whatever this one decides.
261 const r = await next({ ...e, [RETRO_OWNED_FLAG]: true } as never)
262 if (e.stop_hook_active) return r
263
264 try {
265 const { state, version } = await load($)
266
267 const queued = state.pendingDispatch ?? []
268 if (queued.length > 0) {
269 // Hold while work runs in the background; the Stop that ends the wake-up turn re-checks.
270 if (await isBusy($, e.background_tasks)) return r
271 // Claim it: only the Stop whose write lands at `version` spawns.
272 if (!(await save($, { ...state, pendingDispatch: null }, version))) return r
273 if (!(await spawnRetro($, queued, own.ancestorId))) return withBlock(r, buildDispatch(queued, own.ancestorId))
274
275 return r
276 }
277
278 if (own.ancestorId !== null) {
279 const result = await evaluateRuns(toCall($), own.ancestorId, own.cfg, state, await $.clock.now())
280 if (result.won.length > 0) {
281 if (await isBusy($, e.background_tasks)) {
282 await save($, { ...result.state, pendingDispatch: [...result.won] })
283
284 return r
285 }
286 if (result.state !== state) await save($, result.state)
287 if (!(await spawnRetro($, result.won, own.ancestorId))) return withBlock(r, buildDispatch(result.won, own.ancestorId))
288
289 return r
290 }
291 if (result.nudge.length > 0) {
292 await save($, result.state)
293
294 return withBlock(r, buildNudge(result.nudge))
295 }
296
297 return r
298 }
299
300 // No project rootId: nudge once per session from the closes this session recorded.
301 if (!state.sawClose || state.backstopNudged) return r
302 await save($, { ...state, backstopNudged: true })
303
304 return withBlock(r, buildNudge(state.closes ?? []))
305 } catch {
306 return r
307 }
308 })
309}
310src/band/model.ts 113 lines1// Pure selection and text for the band and the status line (T4 ec1e2f91). No `$`, no atoms: the
2// hooks in index.ts feed it a snapshot and draw what it returns.
3import type { GateInfo, GraphNode, GraphSnapshot } from '../../types'
4import { cardsOf, num } from '../graph-pane/model.ts'
5
6export interface BandModel {
7 /** The band's line; absent when hidden or nothing is in flight. */
8 band?: string
9 /** The compact status-line text; absent when nothing is in flight (clears the line). */
10 status?: string
11}
12
13/** Columns the Hide button and its spacing take beside the band text. */
14const BUTTON_COLUMNS = 10
15const MIN_TITLE = 8
16
17const ACTIVE = new Set(['work', 'review'])
18
19/** The in-flight leaves, in the order the band picks from: work before review, deeper first, snapshot order. */
20export function inFlight(snapshot: GraphSnapshot | null): GraphNode[] {
21 if (!snapshot) return []
22 const active = snapshot.nodes.filter(node => ACTIVE.has(node.role))
23 const byId = new Map(snapshot.nodes.map(node => [node.id, node]))
24 // A node is a container when an active descendant exists: mark every ancestor of every active node.
25 const containers = new Set<string>()
26 for (const node of active) {
27 let parent = node.parentId === null ? undefined : byId.get(node.parentId)
28 for (let guard = 0; parent && guard < 1000; guard += 1) {
29 containers.add(parent.id)
30 parent = parent.parentId === null ? undefined : byId.get(parent.parentId)
31 }
32 }
33 const rank = (node: GraphNode): number => (node.role === 'work' ? 0 : 1)
34
35 return active
36 .map((node, index) => ({ node, index }))
37 .filter(({ node }) => !containers.has(node.id))
38 .sort((a, b) => rank(a.node) - rank(b.node) || b.node.depth - a.node.depth || a.index - b.index)
39 .map(({ node }) => node)
40}
41
42/** `2/3 work notes`, `work` (nothing required), or the role (no gate entry); ` ✓` when it can advance. */
43export function gateText(node: GraphNode, gate: GateInfo | undefined): string {
44 if (!gate) return node.role
45 const base = gate.required > 0 ? `${gate.filled}/${gate.required} ${gate.phase} notes` : gate.phase
46
47 return gate.canAdvance ? `${base} ✓` : base
48}
49
50/** `title` cut to `room` characters with a trailing ellipsis. */
51export function truncate(title: string, room: number): string {
52 if (title.length <= room) return title
53 if (room <= 1) return '…'
54
55 return `${title.slice(0, room - 1)}…`
56}
57
58/** Most labels shown per segment of the smart line; the rest read ` +k`. */
59export const SEGMENT_MAX = 3
60
61const byPlanNumber = (a: string, b: string): number => num(a) - num(b) || (a < b ? -1 : a > b ? 1 : 0)
62
63function segment(name: string, labels: string[]): string | undefined {
64 if (labels.length === 0) return undefined
65 const sorted = [...labels].sort(byPlanNumber)
66 const more = sorted.length > SEGMENT_MAX ? ` +${sorted.length - SEGMENT_MAX}` : ''
67
68 return `${name}: ${sorted.slice(0, SEGMENT_MAX).join(', ')}${more}`
69}
70
71/**
72 * The band line while the graph is scoped to an item (D1 a): `◉ <id8> · <d>/<n> done · ready: … · waiting: …`.
73 * n counts the scope's cards (not the scope itself), d the terminal ones (cancelled counts as done);
74 * ready are queue cards with every blocker satisfied, waiting the open cards with an open blocker.
75 * Undefined on the root overview, with no snapshot, or with no cards (the in-flight line then shows).
76 */
77export function smartLine(snapshot: GraphSnapshot | null, bodyColumns = 80): string | undefined {
78 if (!snapshot || snapshot.overview === true || snapshot.scopeId === null) return undefined
79 const { cards } = cardsOf(snapshot)
80 if (cards.length === 0) return undefined
81 const done = cards.filter(c => c.role === 'terminal').length
82 const parts = [
83 `◉ ${snapshot.scopeId.slice(0, 8)}`,
84 `${done}/${cards.length} done`,
85 segment('ready', cards.filter(c => c.ready).map(c => c.label)),
86 segment('waiting', cards.filter(c => c.role !== 'terminal' && c.openBlockers.length > 0).map(c => c.label)),
87 ].filter((p): p is string => p !== undefined)
88
89 return truncate(parts.join(' · '), Math.max(MIN_TITLE, bodyColumns - BUTTON_COLUMNS))
90}
91
92/** What the band draws: the smart line when scoped to an item, else the in-flight line (undefined: nothing). */
93export function bandLine(snapshot: GraphSnapshot | null, bodyColumns = 80): string | undefined {
94 return smartLine(snapshot, bodyColumns) ?? bandModel(snapshot, false, bodyColumns).band
95}
96
97export function bandModel(snapshot: GraphSnapshot | null, hidden: boolean, bodyColumns = 80): BandModel {
98 const list = inFlight(snapshot)
99 const first = list[0]
100 if (!snapshot || !first) return {}
101
102 const id8 = first.id.slice(0, 8)
103 const more = list.length > 1 ? ` (+${list.length - 1})` : ''
104 const gate = gateText(first, snapshot.gates[first.id])
105 const status = `TO ◉ ${id8} ${gate.replace(' notes', '')}${more}`
106 if (hidden) return { status }
107
108 const fixed = `◉ ${id8} — ${gate}${more}`.length
109 const room = Math.max(MIN_TITLE, bodyColumns - BUTTON_COLUMNS - fixed)
110
111 return { band: `◉ ${id8} ${truncate(first.title, room)} — ${gate}${more}`, status }
112}
113src/shared/constants.ts 32 lines1// Names shared by every feature of the mod. Facts behind them were verified live in spike
2// 11960f01 (see its implementation-notes).
3
4/** This plugin's name: `next.origin.plugin` equals it when a dispatch was raised by our own `$` call. */
5export const PLUGIN = 'task-orchestrator-mod'
6
7/** The TO MCP server's name as `/mcp` lists it; what `$.mcp.call` takes. */
8export const TO_SERVER = 'mcp-task-orchestrator'
9
10/** Matches the tool names of the TO MCP server as the engine spells them (`mcp__<server>__<tool>`). */
11export const TO_TOOL = /^mcp__.*task-orchestrator.*__/
12
13/**
14 * The 4.0 TO tool names, sorted. Kept equal to the task-orchestrator plugin's generated catalog
15 * (hooks/lib/tool-catalog.json) by its mod-contract test; the mod cannot import that file.
16 */
17export const TO_TOOLS: readonly string[] = Object.freeze(['advance', 'config', 'deps_read', 'deps_write', 'docs_read', 'docs_write', 'items_read', 'items_write', 'notes_read', 'notes_write', 'report', 'runs_read', 'runs_write'])
18
19/** The 4.0 TO tools whose call shape is `ops[]` (the catalog's `kind: ops`), sorted. */
20export const TO_WRITE_TOOLS: readonly string[] = Object.freeze(['advance', 'config', 'deps_write', 'docs_write', 'items_write', 'notes_write', 'runs_write'])
21
22/**
23 * Field a `classic.<Event>` hook adds to the event before `next`, so a TO command hook reading it
24 * on stdin can tell the mod already handled that event and exit early (selective dedupe).
25 */
26export const MOD_ACTIVE_FLAG = 'to_mod_active'
27
28/** The bare TO tool name (`advance`) of an engine tool name, or null when it is not a TO tool. */
29export function toToolName(tool: string): string | null {
30 return TO_TOOL.test(tool) ? tool.replace(TO_TOOL, '') : null
31}
32src/shared/config.ts 18 lines1// Project config parsing. Pure: the caller reads the file itself with `$.fs.read(CONFIG_PATH)` in
2// the module that owns `$` — the plugin validator follows `$` only within one file, so a helper
3// that takes `$` across an import is refused. src/lib/yaml-lite.mjs is a copy of
4// claude-plugins/task-orchestrator/hooks/yaml-lite.mjs — keep the two in sync.
5import { readSection, scalar } from '../lib/yaml-lite.mjs'
6
7/** The project config, relative to the session's working directory. */
8export const CONFIG_PATH = '.taskorchestrator/config.yaml'
9
10/** `project.rootId` from config text, or null when there is none. */
11export function parseProjectRootId(configText: string | null): string | null {
12 if (!configText) return null
13 const section = readSection(configText, 'project', { blockOnly: true })
14 const rootId = section ? scalar(section.lines, 'rootId') : null
15
16 return typeof rootId === 'string' && rootId.length > 0 ? rootId : null
17}
18src/call-shape/rewrite.ts 130 lines1// Pure call-shape repair for TO tool calls (T7, 4.0 set). No `$`, so it is unit-testable: the caller
2// reads the project rootId and hands it in. The engine's reserved keys of a `tool.call` event (`tool`,
3// `tool_use_id`, `agentId`, `consent`) always stay at the top level and are never moved or removed.
4//
5// Rules, each applied at most once per call and labelled `<tool> <rule>`:
6// R1 items_read select list, next, blocked, or context without itemId: inject ancestorId=<rootId>
7// when ancestorId is absent (undefined), parentId absent or null, there is no tags/type/traits filter, a list
8// has depth !== 0, and a root id resolved.
9// R2 items_read ancestorId: "" (the opt-out) is removed and nothing is injected.
10// W1 a call with a top-level `op` string and no `ops` becomes {ops: [{...}], atomic?, seatToken?}.
11// W2 advance transitions[] / notes_write notes[] (only when ops is absent) become ops[], each
12// element given op 'transition' / 'upsert' when it has none.
13// W3 a top-level actor and an actor on every ops element are deleted (4.0 refuses a body actor).
14// W4 items_write create/update ops: properties.traits moves to the op's traits (dropped when the op
15// already has traits); an emptied properties is deleted.
16// No missing-`type` repair: a guessed type silently mis-schemas the item, and the server's
17// schema_violation already lists the available types.
18
19export type Rewrite = { input: Record<string, unknown>; changes: string[] }
20
21type Input = Record<string, unknown>
22
23const absent = (v: unknown): boolean => v === undefined || v === null
24
25/** Keys of a `tool.call` event the engine owns: a rewrite never moves them into an op. */
26const RESERVED: readonly string[] = ['tool', 'tool_use_id', 'agentId', 'consent']
27const isObj = (v: unknown): v is Input => typeof v === 'object' && v !== null && !Array.isArray(v)
28
29/** A tags, type or traits filter of any value: the caller wants a kind of item that may live outside the project root. */
30function hasKindFilter(input: Input): boolean {
31 return !absent(input.tags) || !absent(input.type) || !absent(input.traits)
32}
33
34/** Whether R1 (inject `ancestorId`) is in play for this items_read input, before the skip conditions. */
35function isScopable(input: Input): boolean {
36 switch (input.select) {
37 case 'list':
38 return input.depth !== 0
39 case 'next':
40 case 'blocked':
41 return true
42 case 'context':
43 return absent(input.itemId)
44 default:
45 return false
46 }
47}
48
49/** True when the tool's own caller is this plugin (its `$.mcp.call` reads), which are never repaired. */
50export function isOwnCall(originPlugin: string | undefined, plugin: string): boolean {
51 return originPlugin === plugin
52}
53
54/** W4 on one op: the op itself when nothing moves. */
55function moveTraits(op: Input): Input {
56 if ((op.op !== 'create' && op.op !== 'update') || !isObj(op.properties) || !('traits' in op.properties)) return op
57 const { traits, ...rest } = op.properties
58 const out: Input = { ...op }
59 if (out.traits === undefined) out.traits = traits
60 if (Object.keys(rest).length > 0) out.properties = rest
61 else delete out.properties
62
63 return out
64}
65
66/**
67 * Repairs one TO tool call. `tool` is the bare TO tool name, `input` the call (reserved keys allowed). Returns
68 * the (possibly new) input and one change label per applied rule; `input` is the SAME object when
69 * nothing changed.
70 */
71export function rewriteCall(tool: string, input: Input, rootId: string | null): Rewrite {
72 const changes: string[] = []
73 let out = input
74
75 if (tool === 'items_read') {
76 if (out.ancestorId === '') {
77 const { ancestorId: _blank, ...rest } = out
78 out = rest
79 changes.push(`${tool} R2`)
80 } else if (rootId !== null && isScopable(out) && out.ancestorId === undefined && absent(out.parentId) && !hasKindFilter(out)) {
81 out = { ...out, ancestorId: rootId }
82 changes.push(`${tool} R1`)
83 }
84 }
85
86 if (typeof out.op === 'string' && out.ops === undefined) {
87 const top: Input = {}
88 const element: Input = {}
89 for (const [k, v] of Object.entries(out)) (k === 'atomic' || k === 'seatToken' || RESERVED.includes(k) ? top : element)[k] = v
90 out = { ops: [element], ...top }
91 changes.push(`${tool} W1`)
92 }
93
94 const legacyKey = tool === 'advance' ? 'transitions' : tool === 'notes_write' ? 'notes' : null
95 if (legacyKey !== null && out.ops === undefined && Array.isArray(out[legacyKey])) {
96 const op = tool === 'advance' ? 'transition' : 'upsert'
97 const { [legacyKey]: list, ...rest } = out
98 out = { ...rest, ops: (list as unknown[]).map(el => (isObj(el) && el.op === undefined ? { op, ...el } : el)) }
99 changes.push(`${tool} W2`)
100 }
101
102 const opsHaveActor = Array.isArray(out.ops) && out.ops.some(el => isObj(el) && 'actor' in el)
103 if ('actor' in out || opsHaveActor) {
104 const { actor: _actor, ...rest } = out
105 out = rest
106 if (Array.isArray(out.ops)) {
107 out = {
108 ...out,
109 ops: out.ops.map(el => {
110 if (!isObj(el) || !('actor' in el)) return el
111 const { actor: _elActor, ...elRest } = el
112
113 return elRest
114 }),
115 }
116 }
117 changes.push(`${tool} W3`)
118 }
119
120 if (tool === 'items_write' && Array.isArray(out.ops)) {
121 const moved = out.ops.map(el => (isObj(el) ? moveTraits(el) : el))
122 if (moved.some((el, i) => el !== (out.ops as unknown[])[i])) {
123 out = { ...out, ops: moved }
124 changes.push(`${tool} W4`)
125 }
126 }
127
128 return { input: out, changes }
129}
130src/shared/to-client.ts 91 lines1// Parsing of TO MCP tool results (4.0 envelope). Pure: the caller makes the `$.mcp.call(TO_SERVER, ...)`
2// itself in the module that owns `$` (the plugin validator refuses `$` passed across an import).
3//
4// A 4.0 result carries its envelope `{ok, data | error{code, kind, message, detail}, meta}` only in
5// `structuredContent`; the text content is just `ok` or `<code>: <message>`, and `isError` is `!ok`, so a
6// partly failed batch is `isError: true` with `data.results`. Read the envelope, never the text.
7//
8// A `$.mcp.call` raises `tool.call` and `classic.PostToolUse` like a model's call does, so the TO command
9// hooks run on it too. The mod's MCP calls are read-only; retro's one write, `runs_write` `mark`, goes over
10// REST. Every hook that reacts to TO tool calls skips dispatches whose `next.origin.plugin` is PLUGIN.
11
12export interface ToError {
13 code?: string
14 kind?: string
15 message?: string
16 detail?: unknown
17 [key: string]: unknown
18}
19
20/** A 4.0 response envelope. `data` is absent when the operation returns nothing. */
21export interface ToEnvelope {
22 ok: boolean
23 data?: unknown
24 error?: ToError
25 meta?: unknown
26}
27
28type Obj = Record<string, unknown>
29const isObj = (v: unknown): v is Obj => typeof v === 'object' && v !== null && !Array.isArray(v)
30
31/** The payload as an envelope: null for a 3.x payload (a top-level `success` key) or one without a boolean `ok`. */
32function asEnvelope(payload: unknown): ToEnvelope | null {
33 if (!isObj(payload)) return null
34 if (Object.prototype.hasOwnProperty.call(payload, 'success')) return null
35
36 return typeof payload.ok === 'boolean' ? (payload as unknown as ToEnvelope) : null
37}
38
39/** The JSON value of the first text block of a content array, or undefined. */
40function blockJson(content: unknown): unknown {
41 if (!Array.isArray(content)) return undefined
42 for (const block of content) {
43 if (isObj(block) && typeof block.text === 'string') {
44 try {
45 return JSON.parse(block.text)
46 } catch {
47 return undefined
48 }
49 }
50 }
51
52 return undefined
53}
54
55/**
56 * The envelope of a TO tool result, wherever it sits: `structuredContent` (a `$.mcp.call` result or a
57 * PostToolUse `tool_response`), then `result.structuredContent` (a `tool.call` result), then the JSON text
58 * of the first content block, then the value itself when it is a bare envelope. Null when there is none,
59 * and for a 3.x payload (top-level `success`).
60 */
61export function envelopeOf(value: unknown): ToEnvelope | null {
62 if (!isObj(value)) return null
63 if (isObj(value.structuredContent)) return asEnvelope(value.structuredContent)
64 if (isObj(value.result) && isObj(value.result.structuredContent)) return asEnvelope(value.result.structuredContent)
65 const fromText = blockJson(value.content)
66 if (fromText !== undefined) return asEnvelope(fromText)
67 if (Object.prototype.hasOwnProperty.call(value, 'success')) return null
68
69 return typeof value.ok === 'boolean' ? (value as unknown as ToEnvelope) : null
70}
71
72/**
73 * The `data` of a TO tool result (`{}` when ok without data). Throws `Error("<tool>: <code>: <message>")`
74 * on an error envelope and `Error("<tool>: no envelope")` when the result carries none.
75 */
76export function parseToResult<T>(tool: string, result: unknown): T {
77 const env = envelopeOf(result)
78 if (env === null) throw new Error(`${tool}: no envelope`)
79 if (!env.ok) {
80 const err: Obj = isObj(env.error) ? env.error : {}
81 throw new Error(`${tool}: ${String(err.code ?? 'error')}: ${String(err.message ?? '')}`)
82 }
83
84 return (env.data === undefined ? {} : env.data) as T
85}
86
87/** The 8-hex short id of an id (its first 8 characters, lower-cased): the key every graph structure uses. */
88export function shortId(id: string): string {
89 return id.slice(0, 8).toLowerCase()
90}
91