SLOPSHOPPER

timeline

Vertical orchestration timeline: talk on the left, work milestones with progress and live subagent cards on the right, per repo across sessions.

paneguardcommandtoastprompttool
v0.1.0MITupdated 2026-10-20tyree88/tempered_plugins/mods/timeline
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · timeline
│ ┃ Timeline ✕ › fix the failing auth test and add an audit log call │ ┃ app │ ┃ ⏺ Read(src/auth.ts) │ ┃ No activity yet. Claude's task list, ⎿ Read 6 lines │ ┃ subagents and plan steps show here. ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /timeline │ ⎿ timeline: Timeline opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Timeline
app No activity yet. Claude's task list, subagents and plan steps show here.
README

Tempered Plugins

This repository holds plugins from Tempered Works for AI coding tools. Five plugins are for Claude Code. One plugin is for Codex.

A Claude Code "mod" is a plugin of function hooks. A function hook is code that Claude Code runs when an event occurs, for example when a tool call ends. The five Claude Code plugins here are mods. They run inside Claude Code, in the terminal and in the desktop Code tab.

What is in this repository

FolderToolWhat it does
ship-state/Claude CodeShows the git, pull request, CI and deploy state of the current repo in one line above the prompt. Ends the line with a button to commit or push.
timeline/Claude CodeShows a side pane with what is running now, what is next, and what is blocked. The history of the work is below.
limit-resume/Claude CodeShows your usage limits and continues a turn after a rate limit resets.
followups/Claude CodeShows 4 options for your next prompt above the prompt box after each answer. You press 1 to 4 to put one in the box.
lessons/Claude CodeFinds wins and pitfalls in your prompts. It then asks Claude to run your own win-logger and pitfall-logger skills. The status line shows how many entries you logged.
multi-harness/CodexGives Codex 6 skills to plan large work in waves and to track it to completion.
.claude-plugin/marketplace.jsonClaude CodeLists the 5 Claude Code plugins so that Claude Code can install them from this repository.

Why these plugins exist

ship-state. During a coding session, you often need to know if your work is pushed, if CI passed, and if production has the change. Without this plugin, you ask Claude, and Claude runs git and gh commands to find out. Each check costs a model turn. ship-state shows the answer on screen at all times and makes no model calls. When the tree has uncommitted files, the line ends with a button. One key sends the commit prompt. You do not type it.

timeline. Long work with many steps and many subagents is hard to follow. Without a record, you ask "what is running now?", "what is next?" and "what is blocked?" many times. You also cannot see which model each subagent uses. timeline answers these 3 questions at a glance in a side pane. The history of the work is below the answers. timeline keeps one record per repo across sessions.

limit-resume. When a session hits a usage limit, the work stops until you type "try again". If you are away, the session stays idle after the limit resets. limit-resume continues the work at the reset time. It also shows your usage before you reach the limit.

followups. Claude Code shows one grey suggestion for your next prompt. That suggestion is often the wrong one. followups shows 4 options in 4 directions: continue the plan, verify the work, take the alternative path, and wrap up. These options cover the usual next moves. You choose one and edit it. followups sends nothing until you press Enter.

lessons. The same mistakes happen again, and good patterns get lost. A skill that logs them is useful, but it often does not run at the right moment. lessons makes the skill run. It reads your prompts for praise, frustration, and repeated requests. When it finds one, it tells Claude to run the matching skill after Claude finishes your request. The skill always asks "Log it? y/n" before it writes. You stay in control.

multi-harness. Large product work needs a plan, branch and pull request gates, tracker updates, QA evidence, and a safe closeout. multi-harness gives Codex a repeatable method for these steps. The method is the same for every product.

Requirements

  • Claude Code with support for function-hook plugins. We tested the plugins on Claude Code 2.1.288 on macOS. All Claude Code plugins pass claude plugin validate.
  • git 2.31 or newer.
  • The GitHub CLI gh, signed in. ship-state and timeline use it for pull request, CI and deploy data. Without gh, they show only local git data.
  • Production deploy data comes from GitHub deployment records. Vercel and most hosting services create these records.

How to install the Claude Code plugins

Use one of these 2 methods.

Method 1: install from the marketplace. Run these commands in a Claude Code session:

/plugin marketplace add tyree88/tempered_plugins
/plugin install ship-state@tempered-plugins
/plugin install timeline@tempered-plugins
/plugin install limit-resume@tempered-plugins
/plugin install followups@tempered-plugins
/plugin install lessons@tempered-plugins

Install only the plugins that you want.

Method 2: load the folders directly. Clone this repository. Then add the plugin folders to the env block of ~/.claude/settings.json. Separate the folders with :.

{ "env": { "CLAUDE_CODE_PLUGIN_DIRS": "/path/to/tempered_plugins/ship-state:/path/to/tempered_plugins/timeline:/path/to/tempered_plugins/followups:/path/to/tempered_plugins/lessons" } }

New sessions load the plugins. Sessions that are already open do not.

How to use ship-state

ship-state needs no action. It starts with each session.

  1. Look at the band above the prompt. It shows the current repo and branch.
  2. Read the state from left to right:
app ⎇ feat/waitlist  ·  3 dirty  ·  ↑2 ↓0  ·  PR #312  ·  CI ⏳ 4/5  ·  prod = HEAD ✓ 2h ago  ·  0: commit 3 files
PartMeaning
3 dirty3 files have changes that are not committed.
↑2 ↓02 commits are not pushed. 0 commits are not pulled.
PR #312The branch has open pull request 312.
CI ⏳ 4/54 of 5 CI checks are complete.
prod = HEAD ✓Production runs the current commit.
0: commit 3 filesA button. Press 0 in an empty prompt box, or click it. ship-state sends "Commit the working tree changes with a sensible message." to Claude. After 5 minutes, the button also shows how long the files have waited, for example · 24m ago. The key 0 works only when the prompt box is empty. If you type 0 as the first character of a message, it presses the button and sends the commit prompt. Type a space first to start a message with 0.
  1. After a push or a merge, wait for the toast. ship-state shows "CI ✓", "CI ✗" with the failed check names, or "Live on prod".
  2. When the tree is clean and commits are not pushed, the button reads push ↑2. It has no key. Click it, or press ctrl+x tab to focus the band, press Tab or an arrow key to move to push ↑2, then press Enter. It sends "Push the branch." to Claude. The button does not show while Claude works. After you press it, the button stays hidden until Claude's turn ends, or for 60 seconds at most.

ship-state follows Claude when Claude changes to another repo or worktree. It reads local git data every 20 seconds. It reads GitHub data every 5 minutes. After a push or merge, it reads GitHub data every 20 seconds for 10 minutes.

The band of ship-state stacks with the bands of other plugins, such as followups. followups uses the keys 1 to 4. ship-state uses the key 0 for commit only.

How to use timeline

  1. Type /timeline to open or close the pane.
  2. Wait for the pane to open by itself. It opens once per session, on the first of these events:
  3. Claude logs a task.
  4. Claude has 3 or more open tasks.
  5. Claude starts a subagent.
  6. Read the pane from top to bottom. The table below lists the zones.
  7. Look for ⚠ inherited model on a subagent in NOW. This mark means that no model was set for the subagent, so it uses the model of the main session.
  8. If HISTORY has more than 30 entries, use ◀ older and newer ▶ to move between pages.

The pane uses the text and colors of the app, on the desktop and in the terminal. It fits any width. At 70 columns or more, NEXT and BLOCKED sit side by side. At fewer columns, they stack.

ZoneWhat it shows
HeaderThe repo and the branch.
GOALThe title of the plan while the plan has unticked boxes. Otherwise, the latest active task that Claude logged in the last 24 hours.
PLANA progress bar, the current section of the plan file, and the steps done out of the total. It shows only when at least 1 box in the plan is ticked.
NOWThe tasks that Claude logged as in progress in the last 24 hours, with a progress bar when the task has steps. Then the tasks that Claude has in progress, and the subagents that run now. A subagent shows its title, type, model, elapsed time, tool calls and tokens. It also shows now: (the current tool) and next: (the next step) when they are known. Subagents from another session that started more than 24 hours ago do not show.
NEXTUp to 5 pending tasks that wait on nothing. Then +N more.
BLOCKEDPending tasks that wait on an unfinished task (waits on #N). Also the tasks that Claude logged as blocked in the last 24 hours.
AGENTS · last 15 minOne bar for each subagent run in the last 15 minutes, up to 8. Each bar has the short description of the subagent as its label, not the type. The bar starts when the subagent starts and stops when it ends. The colors are blue for running, green for done, red for failed and gray for status unknown. The terminal draws the bars with block characters. Below the bars are the start time, the middle time and now.
HISTORYOne line for each entry, newest first: the time, a mark, and the text. Each subagent shows below the task that it ran for, on a line that starts with ├ or └. A subagent that ran for no logged task has a line of its own. A subagent line shows the type, the model, the title and the run time. History does not show the results of subagents. Each page has 30 entries, and each entry keeps its subagent lines.

The marks in HISTORY are:

MarkMeaning
💬A request or a decision.
▶Running.
✓Done.
⚠Blocked.
✗Failed.
?Status unknown.
↳A commit, a push, a pull request or a CI result.

timeline reads 4 sources:

  • The task list of Claude (TaskCreate, TaskUpdate, TaskList and TodoWrite).
  • The subagents.
  • The plan file that Claude reads or edits. A plan file is a markdown file with checkboxes. Its name contains "plan", or it has 3 or more boxes.
  • The tool mcp__timeline__log.

How timeline works:

  • The plugin adds a tool, mcp__timeline__log. It also adds an instruction of about 100 tokens that tells Claude when to log. Claude logs once for each change of direction, and once at the start, each step, the end, or a block of each task.
  • Each subagent gets a shorter instruction to log its own progress.
  • The instruction tells Claude to write each title, how and next in Simplified Technical English: one short sentence, active voice, no filler.
  • The log tool needs no permission prompt.
  • timeline stores the history per repo in ~/.claude/timelines/<repo>-<hash>/. Each session writes only its own files. Worktrees of a repo share one timeline.
  • If 2 sessions work in the same repo, each pane shows the entries of the other session within 10 seconds.

Usage cost: each logged entry costs approximately 40 to 80 output tokens. The instruction costs approximately 140 tokens in each session.

Privacy: the timeline files contain Claude's one-line summaries, the first 2000 characters of each subagent prompt, and commit subjects. The files stay on your computer.

How to use followups

followups needs no action. It starts with each session.

  1. Wait for Claude to finish an answer. A few seconds later, 4 options appear in the band above the prompt box. Each option has its own row: 1: … to 4: ….
  2. Read the options. Each option goes in a different direction:
  3. Continue the plan.
  4. Verify or test the work.
  5. Take the alternative path, or ask an open question.
  6. Wrap up or commit.
  7. Press 1 to 4 when the prompt box is empty. You can also click an option. The text of the option goes into the prompt box.
  8. Edit the text, or press Enter to send it. followups never sends anything by itself.
  9. To ignore the options, type your own message.
  10. To turn the plugin off or on, type /followups off or /followups on. Type /followups status to see the current setting and the last error, for example a refused model call.

When the band shows, a digit that you type in an empty prompt box picks an option. To start a message with a digit, type a space first.

The band hides while the prompt box has text, while a turn runs, and while a survey uses the band. It comes back when the prompt box is empty.

followups hides the built-in grey suggestion of Claude Code, but only after its own band has drawn once. In a surface without the band, the built-in suggestion stays.

followups makes no options for subagent turns, interrupted turns, errors, and empty answers. If you send a prompt before Haiku answers, followups drops the old reply. After /clear or a resume, followups removes the old options.

Usage cost: followups makes one Haiku call for each answered turn. A call costs approximately 2,000 input tokens and 150 output tokens. followups adds nothing to the context of the main model.

Privacy: the first 1,500 characters of your last prompt and the last 4,000 characters of the answer go to Haiku. The call uses the API client of Claude Code.

How to use lessons

lessons needs 2 skills of your own. Name them win-logger and pitfall-logger. This repository does not include them. The skills decide where an entry goes, for example a Notion database. Each skill always asks "Log it? y/n" before it writes.

  1. Add the 2 skills to Claude Code. Any skills with these names work.
  2. Work as usual. lessons watches only the prompts that you send yourself: in the terminal, in Remote Control, in your own Slack ping, and in the Claude desktop app. It ignores prompts from plugins, notifications, other sessions, and subagents.
  3. Send a prompt that shows a win or a pitfall. The table below lists the signals.
  4. Claude finishes your request first. Then Claude runs the matching skill. lessons adds a short note to your prompt to cause this. You do not see the note.
  5. Read the draft that the skill shows. Answer y to log it. Answer n to skip it.
  6. Look at the status line. 🌱 2 · ⚠ 1 means 2 wins and 1 pitfall are logged in this session. lessons counts a row when you answer y to a draft. The count resets after /clear or a resume.
  7. To turn the plugin off or on, type /lessons off or /lessons on. Type /lessons status to see the setting, the counts, and where each skill was found.
KindSignals
WinPraise, for example "perfect", "nailed it", "love this", "this is great", "exactly what I wanted". Or an ask: "log this win", "log this as a win", "add this to learnings", "remember this worked".
PitfallFrustration, for example "I already told you", "no, I said", "still wrong", "still failing", "this is the third time", "why did you change…", "not what I asked". Or shouting: several words in all capitals. Or the same request sent again: it has high word overlap with one of your last 10 prompts. Or an ask: "log this", "add this to pitfalls", "remember this lesson".

lessons avoids common false signals. These prompts do not trigger it: "exactly 3 retries", "pixel perfect", "log this error to sentry", "why did you choose zod?", "the second time I click it throws". File names such as README or CHANGELOG do not trigger it. HTTP method names do not trigger it.

lessons adds at most 1 note of each kind for each 5 prompts.

lessons looks for the skills in 2 places:

  • The skills loaded in the session. The name can also be anthropic-skills:<name>.
  • On macOS, the synced-skills folder of the Claude desktop app.

If a skill is missing, lessons shows a toast at most once a day. /lessons status shows "missing" for that skill.

Usage cost: lessons makes no model calls. A note costs approximately 40 tokens. lessons adds a note only to a prompt that matches.

Privacy: your last 10 prompts stay in memory only, for the repeat check. lessons does not write them to disk.

How to use limit-resume

limit-resume needs no action. It starts with each session.

  1. Read the status line below the prompt. It shows your usage, for example 5h 62% · 7d 41%. 5h is the 5-hour window. 7d is the 7-day window.
  2. If the 5-hour usage reaches 85%, a toast tells you. Commit your work at this point.
  3. If a turn stops because of a usage limit, the status line shows when the work continues. At the reset time plus 1 minute, limit-resume sends "Continue from where you left off".
  4. If a turn stops because of a temporary API error, limit-resume tries again after 1, 2, 4, and 8 minutes, then every 15 minutes. It stops after 12 tries.
  5. To cancel a pending continue, type any message.
  6. To turn the plugin off or on, type /autoresume off or /autoresume on. Type /autoresume status to see the current setting.

Claude Code has a built-in setting, autoContinueAtUsageLimit, that also continues after a usage limit. Do not use the built-in setting and limit-resume together for usage limits. If you do, the turn gets 2 "continue" messages.

How to use multi-harness

multi-harness is a Codex plugin. Its manifest is multi-harness/.codex-plugin/plugin.json, and its plugin name is platform-orchestrator. It is not in the Claude Code marketplace file.

  1. Install the multi-harness folder with the Codex plugin installer.
  2. Ask Codex to use Platform Orchestrator on a backlog. For example: "Use Platform Orchestrator to turn this backlog into shippable waves, branch and PR gates, tracker updates, and verification evidence."
  3. Use the templates in multi-harness/assets/templates/ for wave plans, tracker updates, QA evidence, and pull request closeout.

The 6 skills are:

SkillUse
platform-wave-orchestratorDivide a backlog into agent lanes and implementation waves.
platform-agent-patternsChoose how agents work together on a wave.
platform-pr-closeoutGate and close branches and pull requests.
platform-tracker-syncUpdate GitHub and Notion trackers.
platform-qa-evidenceCollect QA evidence for each change.
platform-safety-reviewReview work that touches sensitive data, regulated text, or trust and safety limits.

To check the folder structure, run python3 multi-harness/scripts/check_plugin_structure.py.

Development

Each Claude Code plugin has checks for its logic. Node 23 or newer runs the .ts check files directly.

node limit-resume/check.ts
node ship-state/check.ts
node followups/checks/ask.check.ts
node lessons/checks/detect.check.ts
bash timeline/checks/run.sh

To run the behavior test of ship-state, run claude plugin test ship-state. It runs 16 cases on the terminal and desktop surfaces.

To run the behavior test of timeline, run claude plugin test timeline. It runs 18 cases on the terminal and desktop surfaces.

To run the behavior test of followups, run claude plugin test followups. It runs 8 cases on the terminal and desktop surfaces.

To run the behavior test of lessons, run claude plugin test lessons. It runs 9 cases.

To type-check timeline, do these 2 steps:

  1. In a Claude Code session in this repository, run /plugin-types .claude/types. This command writes the Claude Code type declarations.
  2. Run tsc -p timeline/tsconfig.check.json.

License

MIT. See LICENSE. Copyright 2026 Tempered Works LLC.

Source 9 files
hooks/register.tsx 587 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface as Engine, Register } from 'claude-code'
3
4import type { Entry, LiveAgent, Task, View } from '../types'
5import { buildNodes, buildPanel } from './layout'
6import { ciFact, clip, factsFromBash, folderName, fromLog, lastCd, mainArg, mergeEntries, parseJsonl, repoRoot, toJsonl, tzMinutes, type Found } from './model'
7import { drawPane } from './pane'
8import { parsePlan, type Plan } from './plan'
9import { applyTaskCall, createdId, fromTaskList } from './tasks'
10
11const view = atom({ plugin: 'timeline', key: 'view' } as const, null)
12const tasks = atom({ plugin: 'timeline', key: 'tasks' } as const, [] as Task[])
13
14const PANE = 'timeline'
15const TOOL = 'mcp__timeline__log'
16const PAGE_SIZE = 30
17const REFRESH_MS = 10_000
18const TASK_TOOLS = ['TaskCreate', 'TaskUpdate', 'TodoWrite', 'TaskList'] as const
19const DOC_TOOLS = ['Read', 'Write', 'Edit'] as const
20const PLAN_MAX_BYTES = 262_144 // a bigger .md is not read for plan detection
21const AUTO_OPEN_TASKS = 3 // open tasks that make the pane worth opening
22
23const MAIN_NOTE =
24  'Timeline: call `mcp__timeline__log` (1) once after a user message that sets or changes direction: kind "talk", title = one-line summary of what they asked or decided; (2) when you start a task, finish a step of it, finish it, or get blocked: kind "work", a stable kebab-case `task`, `done`/`total` steps, `status`, `how` (one line), `next` (one line). Never once per tool call; about one entry every few minutes of work. Do not mention the logging in replies. Write `title`, `how` and `next` in Simplified Technical English: one short declarative sentence each (max 12 words), active voice, present tense, exact names, no filler or hedging.'
25const AGENT_NOTE =
26  '\n\nWhile you work, call `mcp__timeline__log` with kind "work" at start, after each step, and at the end, with `done`/`total`, `how`, and `next`. Keep each call short. Write `title`, `how` and `next` in Simplified Technical English: one short declarative sentence each (max 12 words), active voice, present tense, exact names, no filler or hedging.'
27
28const INPUT_SCHEMA = {
29  type: 'object',
30  required: ['kind', 'title'],
31  properties: {
32    kind: { enum: ['talk', 'work'] },
33    title: { type: 'string' },
34    task: { type: 'string' },
35    done: { type: 'integer' },
36    total: { type: 'integer' },
37    status: { enum: ['active', 'done', 'blocked'] },
38    how: { type: 'string' },
39    next: { type: 'string' },
40  },
41}
42
43// A host command's trimmed stdout, or undefined on a non-zero exit or a spawn failure.
44async function run($: Engine, argv: string[], cwd?: string): Promise<string | undefined> {
45  try {
46    const r = await $.process.run(argv, cwd ? { cwd, timeoutMs: 10_000 } : { timeoutMs: 10_000 })
47    return r.exitCode === 0 ? r.stdout.trim() : undefined
48  } catch {
49    return undefined
50  }
51}
52
53type Repo = { root: string; name: string; isGit: boolean; worktree?: string }
54
55// The repo a path belongs to; worktrees share their main checkout's root. A non-git path is its own identity.
56// One rev-parse call. Git older than 2.31 echoes the unknown --path-format flag, so a non-absolute line means "not git".
57async function identify($: Engine, path: string): Promise<Repo> {
58  const out = await run($, ['git', '-C', path, 'rev-parse', '--path-format=absolute', '--git-common-dir', '--show-toplevel'])
59  const [common, top] = out?.split('\n') ?? []
60  if (!common?.startsWith('/') || !top?.startsWith('/')) {
61    return { root: path, name: path.split('/').filter(Boolean).at(-1) ?? path, isGit: false }
62  }
63  const root = repoRoot(common)
64  const name = root.split('/').filter(Boolean).at(-1) ?? root
65  if (top === root) return { root, name, isGit: true }
66  return { root, name, isGit: true, worktree: top.startsWith(`${root}/`) ? top.slice(root.length + 1) : top }
67}
68
69type Store = {
70  dir: string
71  lastSeq: () => number
72  append: (entry: Entry) => Promise<string | undefined>
73  readAll: () => Promise<{ entries: Entry[]; bad: number }>
74}
75
76type Listed = { name: string; kind: string; mtimeMs: number; size: number }
77
78const PART_CHARS = 1_048_576 // start a new part file past 1 MiB of text; $.fs reads and writes cap at 4 MiB
79
80const seqOf = (entries: readonly Entry[]) => entries.reduce((max, e) => Math.max(max, Number(e.id.split('-').at(-1)) || 0), 0)
81
82// One repo's timeline folder. This session rewrites only its current part file (`<session>.jsonl`, then
83// `<session>-1.jsonl`, …). Every other file, this session's earlier parts included, is read and cached by mtime and size.
84// A part that can't be read or has unreadable lines is never rewritten: writing continues in a new part.
85async function openStore($: Engine, home: string, root: string, session: string): Promise<Store> {
86  const dir = `${home}/.claude/timelines/${folderName(root)}`
87  const partName = (n: number) => (n ? `${session}-${n}.jsonl` : `${session}.jsonl`)
88  const partIndex = (name: string) => {
89    if (name === `${session}.jsonl`) return 0
90    const m = name.match(/^(.+)-(\d+)\.jsonl$/)
91    return m && m[1] === session ? Number(m[2]) : -1
92  }
93  const cache = new Map<string, { mtimeMs: number; size: number; entries: Entry[]; bad: number }>()
94  let part = 0
95  let own: Entry[] = []
96  let saved = 0 // how many entries of `own` are on disk
97
98  const list = async (): Promise<readonly Listed[] | undefined> => {
99    try {
100      return await $.fs.list(dir)
101    } catch {
102      return undefined // no folder yet
103    }
104  }
105
106  const parts = ((await list()) ?? []).filter(f => f.kind === 'file').map(f => partIndex(f.name)).filter(n => n >= 0)
107  if (parts.length) {
108    part = Math.max(...parts)
109    try {
110      const parsed = parseJsonl(await $.fs.read(`${dir}/${partName(part)}`))
111      if (parsed.bad) part += 1
112      else {
113        own = parsed.entries
114        saved = own.length
115      }
116    } catch {
117      part += 1 // over 4 MiB or unreadable: leave it alone
118    }
119  }
120
121  const readAll = async () => {
122    const listed = await list()
123    if (!listed) return { entries: [...own], bad: 0 }
124    const current = partName(part)
125    for (const name of [...cache.keys()]) if (!listed.some(f => f.name === name)) cache.delete(name)
126    for (const file of listed) {
127      if (file.kind !== 'file' || !file.name.endsWith('.jsonl') || file.name === current) continue
128      const hit = cache.get(file.name)
129      if (hit && hit.mtimeMs === file.mtimeMs && hit.size === file.size) continue
130      try {
131        cache.set(file.name, { mtimeMs: file.mtimeMs, size: file.size, ...parseJsonl(await $.fs.read(`${dir}/${file.name}`)) })
132      } catch {
133        cache.delete(file.name)
134      }
135    }
136    const others = [...cache.values()]
137    return { entries: mergeEntries([own, ...others.map(c => c.entries)]), bad: others.reduce((n, c) => n + c.bad, 0) }
138  }
139
140  const write = async (entry: Entry): Promise<string | undefined> => {
141    own = [...own, entry]
142    let text = toJsonl(own)
143    if (text.length > PART_CHARS && saved > 0) {
144      // This part is full; what is saved stays there. Entries not yet on disk move to the next part.
145      part += 1
146      own = own.slice(saved)
147      saved = 0
148      text = toJsonl(own)
149    }
150    try {
151      await $.fs.write(`${dir}/${partName(part)}`, text)
152      saved = own.length
153      return undefined
154    } catch (error) {
155      return error instanceof Error ? error.message : String(error)
156    }
157  }
158
159  // One write at a time: parallel subagents logging together must not let an older whole-file write land last.
160  let chain: Promise<unknown> = Promise.resolve()
161  const append = (entry: Entry): Promise<string | undefined> => {
162    const next = chain.then(() => write(entry))
163    chain = next
164    return next
165  }
166
167  // Highest id suffix across all of this session's parts, so a new id never repeats one.
168  const lastSeq = () =>
169    Math.max(seqOf(own), ...[...cache].filter(([name]) => partIndex(name) >= 0).map(([, c]) => seqOf(c.entries)))
170
171  await readAll()
172  return { dir, lastSeq, append, readAll }
173}
174
175// Shared by the hooks and the top-level helpers below: the loader lets $ reach only functions declared at the top of this file.
176const st = {
177  session: '',
178  home: '',
179  tz: 0,
180  repo: undefined as Repo | undefined,
181  store: undefined as Store | undefined,
182  branch: undefined as string | undefined,
183  seq: 0,
184  page: 0,
185  entries: [] as Entry[],
186  bad: 0,
187  activeTask: undefined as string | undefined,
188  hasAutoOpened: false,
189  hasWarnedWrite: false,
190  drawSeq: 0,
191  live: {} as Record<string, LiveAgent>,
192  planPath: undefined as string | undefined,
193  plan: undefined as { path: string; mtime: number; parsed: Plan | null } | undefined,
194  notPlan: new Map<string, number>(), // .md path → the mtime at which it was read and was not a plan
195  taskSeq: 0,
196}
197
198// The active plan, re-parsed only when its file changed. A missing or unreadable file clears it.
199async function loadPlan($: Engine): Promise<Plan | null> {
200  const path = st.planPath
201  if (!path) return null
202  try {
203    const { mtimeMs } = await $.fs.stat(path)
204    if (st.plan?.path !== path || st.plan.mtime !== mtimeMs) {
205      st.plan = { path, mtime: mtimeMs, parsed: parsePlan(await $.fs.read(path)) }
206    }
207    return st.plan.parsed
208  } catch {
209    st.planPath = undefined
210    st.plan = undefined
211    return null
212  }
213}
214
215const redraw = async ($: Engine) => {
216  const mine = ++st.drawSeq
217  const now = await $.clock.now()
218  const nodes = buildNodes(st.entries, st.live, st.session, now)
219  const panel = buildPanel(nodes, await read($, tasks), await loadPlan($), st.page, PAGE_SIZE, now)
220  st.page = panel.page
221  const next: View = { repo: st.repo?.name ?? 'timeline', ...(st.branch ? { branch: st.branch } : {}), bad: st.bad, tz: st.tz, panel }
222  if (mine !== st.drawSeq) return // an older redraw that finishes late must not land last
223  // update retries on a version miss; by then a newer redraw may have started, so keep whatever is newer.
224  await update($, view, prev => (mine === st.drawSeq ? next : prev))
225}
226
227const reload = async ($: Engine) => {
228  if (!st.store) return
229  const all = await st.store.readAll()
230  st.entries = all.entries
231  st.bad = all.bad
232  await redraw($)
233}
234
235const stamp = async ($: Engine, agentId?: string) => ({
236  id: `${st.session.slice(0, 8)}-${++st.seq}`,
237  at: new Date(await $.clock.now()).toISOString(),
238  session: st.session,
239  ...(st.branch ? { branch: st.branch } : {}),
240  ...(st.repo?.worktree ? { worktree: st.repo.worktree } : {}),
241  ...(agentId ? { agentId } : {}),
242})
243
244const isShown = async ($: Engine) => (await $.ui.panes()).some(p => p.id === PANE && p.isShown && p.isPlaced)
245
246// Opens the pane once per process, on the first sign of real work. Skips when the pane is already open.
247// panes() lists only open panes, so one the person closed reopens once after a reload.
248const autoOpen = async ($: Engine) => {
249  if (st.hasAutoOpened) return
250  st.hasAutoOpened = true
251  if (!(await $.ui.panes()).some(p => p.id === PANE)) void $.ui.open({ id: PANE, title: 'Timeline' }).catch(() => {})
252}
253
254const record = async ($: Engine, entry: Entry) => {
255  if (!st.store) return 'timeline has no repo yet'
256  const error = await st.store.append(entry)
257  st.entries = mergeEntries([st.entries, [entry]])
258  if (error && !st.hasWarnedWrite) {
259    st.hasWarnedWrite = true
260    $.ui.toast(`timeline: can't write ${st.store.dir}: ${error}`, { timeoutMs: 10_000 })
261  }
262  if (entry.kind === 'work' && !entry.agentId) await autoOpen($)
263  await redraw($)
264  return error
265}
266
267// Switch the timeline to the repo `path` is in. requireGit: ignore non-git folders (a `cd` into a scratch dir).
268const enterRepo = async ($: Engine, path: string, requireGit: boolean) => {
269  const found = await identify($, path)
270  if (requireGit && !found.isGit) return
271  const newBranch = found.isGit ? await run($, ['git', '-C', path, 'symbolic-ref', '--short', '-q', 'HEAD']) : undefined
272  if (st.repo?.root === found.root) {
273    st.repo = found
274    st.branch = newBranch ?? st.branch
275    return
276  }
277  if (st.store) {
278    await record($, { v: 1, ...(await stamp($)), kind: 'session', title: `session ${st.session.slice(0, 8)} left for ${found.name}`, event: 'close' })
279  }
280  st.repo = found
281  st.branch = newBranch
282  st.store = await openStore($, st.home, found.root, st.session)
283  st.seq = st.store.lastSeq()
284  st.entries = []
285  st.page = 0
286  st.activeTask = undefined
287  await record($, { v: 1, ...(await stamp($)), kind: 'session', title: `session ${st.session.slice(0, 8)} opened`, event: 'open' })
288  await reload($)
289}
290
291// /clear keeps the process but starts a new session id, with no session.start: follow it on the next prompt.
292const syncSession = async ($: Engine) => {
293  const id = await $.session.id()
294  if (!st.session || id === st.session || !st.repo) return
295  // Open first, then switch id, store and seq together: no log may be stamped with the new id into the old store.
296  const opened = await openStore($, st.home, st.repo.root, id)
297  st.session = id
298  st.store = opened
299  st.seq = opened.lastSeq()
300  st.hasAutoOpened = false
301  st.activeTask = undefined
302  await st.store.append({ v: 1, ...(await stamp($)), kind: 'session', title: `session ${st.session.slice(0, 8)} opened`, event: 'open' })
303  await reload($)
304}
305
306const here = () =>
307  st.repo ? (st.repo.worktree?.startsWith('/') ? st.repo.worktree : st.repo.worktree ? `${st.repo.root}/${st.repo.worktree}` : st.repo.root) : undefined
308
309const refreshBranch = async ($: Engine) => {
310  const dir = here()
311  if (dir) st.branch = (await run($, ['git', '-C', dir, 'symbolic-ref', '--short', '-q', 'HEAD'])) ?? st.branch
312}
313
314const recordFact = async ($: Engine, found: Found) =>
315  record($, {
316    v: 1,
317    ...(await stamp($)),
318    kind: 'fact',
319    title: found.title,
320    fact: found.fact,
321    ...(st.activeTask ? { attachTo: st.activeTask } : {}),
322  })
323
324export const register: Register = on => {
325  let useSection = true
326  let ready: Promise<void> = Promise.resolve()
327
328  on('session.start', async ($, e, next) => {
329    st.session = await $.session.id()
330    st.home = (await $.env.get('HOME')) ?? ''
331    st.tz = tzMinutes(await run($, ['date', '+%z']))
332    try {
333      useSection = (await $.prompt.compose()).sections.some(s => s.id === 'env_info_simple')
334    } catch {
335      useSection = false
336    }
337    await $.tool.register({
338      name: 'log',
339      description:
340        'Record an entry on this repo\'s orchestration timeline. kind "talk": one-line summary of what the user asked or decided. kind "work": a task milestone with a stable kebab-case task id, done/total steps, status, how, and next. Use Simplified Technical English: short, active, no filler.',
341      inputSchema: INPUT_SCHEMA,
342    })
343    await $.command.register({ name: 'timeline', description: 'Show or hide the orchestration timeline pane' })
344    // Not awaited: reading a big repo timeline must not delay the session's first prompt. Hooks await `ready`.
345    ready = $.session.cwd().then(cwd => enterRepo($, cwd, false)).catch(() => {})
346    $.clock.every(REFRESH_MS, () => {
347      void (async () => {
348        if (await isShown($)) await reload($)
349      })().catch(() => {})
350    })
351    return next(e)
352  })
353
354  on('session.end', async ($, e, next) => {
355    await ready
356    // append, not record: the session.end chain shares one short wall-clock bound, so no redraw here.
357    if (st.store) await st.store.append({ v: 1, ...(await stamp($)), kind: 'session', title: `session ${st.session.slice(0, 8)} closed`, event: 'close' })
358    // The task list and the plan belong to the conversation that ends here.
359    if (e.reason === 'clear' || e.reason === 'resume') {
360      await update($, tasks, () => [])
361      st.planPath = undefined
362      st.plan = undefined
363      st.page = 0
364    }
365    return next(e)
366  })
367
368  on('prompt.submit', async ($, e, next) => {
369    // Only a /clear changes the id; otherwise the first prompt must not wait for the initial timeline read.
370    if ((await $.session.id()) !== st.session) {
371      await ready
372      await syncSession($)
373    }
374    return next(e)
375  })
376
377  // The log only appends to a local file: no permission prompt.
378  on('tool.check', { tool: TOOL }, () => ({ decision: 'allow' as const, reason: 'timeline log only appends to a local file' }))
379
380  on('tool.call', { tool: TOOL }, async ($, e) => {
381    await ready
382    const entry = fromLog(e as unknown as Record<string, unknown>, await stamp($, e.agentId))
383    if ('error' in entry) return { deny: entry.error }
384    // The talk side is the user's asks and decisions; a subagent that also got the main note must not write there.
385    if (entry.kind === 'talk' && entry.agentId) return { result: 'logged' }
386    if (entry.kind === 'work' && !entry.agentId) {
387      if (entry.status === 'active') st.activeTask = entry.task
388      else if (st.activeTask === entry.task) st.activeTask = undefined
389    }
390    const error = await record($, entry)
391    return { result: error ? `logged, not saved: ${error}` : 'logged' }
392  })
393
394  on('prompt.section', { name: 'env_info_simple' }, async ($, e, next) => {
395    const r = await next(e)
396    if (!useSection) return r // the note goes through prompt.context instead
397    return { text: `${r.text ?? ''}\n\n${MAIN_NOTE}`.trim() }
398  })
399
400  on('prompt.context', async ($, e, next) => {
401    const r = await next(e)
402    return useSection ? r : { ...r, blocks: [...r.blocks, { name: 'timeline', text: MAIN_NOTE }] }
403  })
404
405  on('command.run', { command: 'timeline' }, async $ => {
406    await ready
407    if (await isShown($)) {
408      await $.ui.close({ id: PANE })
409      return { text: 'Timeline closed.' }
410    }
411    await reload($)
412    await $.ui.open({ id: PANE, title: 'Timeline' })
413    return { text: 'Timeline opened.' }
414  })
415
416  let lastSnap: unknown
417  let bookkeeping: Promise<void> = Promise.resolve() // Bash bookkeeping runs one call at a time, in call order
418
419  // Bash: commit/push/PR facts from any loop (subagents make most commits in orchestration work); the main loop also
420  // follows `cd` into another repo. The bookkeeping runs after the result is returned, one call at a time, so the model never waits on it.
421  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
422    const base = await $.session.cwd() // before the command runs: a `cd` may move the session's cwd
423    const ran = await next(e)
424    if (ran.deny !== undefined) return ran
425    const command = String(e.command)
426    const output = ran.text ?? ''
427    const isError = ran.isError === true
428    bookkeeping = bookkeeping.then(async () => {
429      await ready
430      const target = lastCd(command, base)
431      if (!e.agentId && target) await enterRepo($, target, true)
432      if (!st.repo) return
433      // A subagent working in another repo: its facts belong to that repo's timeline, not this one.
434      if (e.agentId && target) {
435        const there = await identify($, target)
436        if (there.isGit && there.root !== st.repo.root) return
437      }
438      if (/\bgit\b/.test(command)) await refreshBranch($)
439      // A failed call can still have committed or pushed (`git commit && git push && gh …` failing late). PR and merge
440      // facts need success: `gh pr create` exits 1 when a PR exists and prints that PR's URL.
441      for (const found of factsFromBash(command, output)) {
442        if (isError && found.fact.type !== 'commit' && found.fact.type !== 'push') continue
443        await recordFact($, found)
444      }
445    }).catch(() => {})
446    return ran
447  })
448
449  // A subagent's own tool calls feed its live card (`now:` and the tool count), not the file.
450  on('tool.call', async ($, e, next) => {
451    const agent = e.agentId ? st.live[e.agentId] : undefined
452    if (agent && e.tool !== TOOL) {
453      agent.tools += 1
454      agent.now = `${e.tool} ${clip(mainArg(e as unknown as Record<string, unknown>), 40) ?? ''}`.trim()
455      void redraw($).catch(() => {})
456    }
457    return next(e)
458  })
459
460  // Claude's own task list and the plan it works from feed NOW / NEXT / BLOCKED and the PLAN bar.
461  // Redraws are not awaited: the model gets its result without waiting on the pane.
462  on('tool.call', { tool: [...TASK_TOOLS, ...DOC_TOOLS] }, async ($, e, next) => {
463    const result = await next(e)
464    if (e.agentId || result.deny !== undefined || result.isError === true) return result
465    if ((TASK_TOOLS as readonly string[]).includes(e.tool)) {
466      // TaskList shows the live list, so it replaces the mirror (it also catches tasks changed outside this loop's own calls).
467      const listed = e.tool === 'TaskList' ? fromTaskList(result.result) : undefined
468      if (e.tool === 'TaskList' && !listed) return result
469      const id = e.tool === 'TaskCreate' ? (createdId(result.result, result.text ?? '') ?? `c${++st.taskSeq}`) : ''
470      const list = await update($, tasks, prev => listed ?? applyTaskCall(prev, e.tool, e, id))
471      if (list.filter(t => t.status !== 'completed').length >= AUTO_OPEN_TASKS) void autoOpen($).catch(() => {})
472      void redraw($).catch(() => {})
473    } else if (typeof (e as { file_path?: unknown }).file_path === 'string') {
474      const path = (e as { file_path: string }).file_path
475      if (path === st.planPath) {
476        if (e.tool !== 'Read') void redraw($).catch(() => {}) // the plan changed: its bar moves
477      } else if (path.endsWith('.md')) {
478        try {
479          // Only a file with counted boxes (outside code fences) that is named as a plan or has 3+ boxes becomes the plan;
480          // any other .md leaves the real one alone and is not read again until it changes.
481          const { size, mtimeMs } = await $.fs.stat(path)
482          if (size <= PLAN_MAX_BYTES && st.notPlan.get(path) !== mtimeMs) {
483            const parsed = parsePlan(await $.fs.read(path))
484            if (parsed && (/plan/i.test(path) || parsed.total >= 3)) {
485              st.planPath = path
486              st.plan = { path, mtime: mtimeMs, parsed }
487              void redraw($).catch(() => {})
488            } else st.notPlan.set(path, mtimeMs)
489          }
490        } catch {} // unreadable: not a plan
491      }
492    }
493    return result
494  })
495
496  on('agent.spawn', async ($, e, next) => {
497    // Only the model's own Agent calls get the logging note; another plugin's spawn may expect its prompt untouched.
498    const isModelCall = next.origin.plugin === 'engine'
499    const result = await next(!e.fork && isModelCall ? { ...e, prompt: `${e.prompt}${AGENT_NOTE}` } : e)
500    if (result.deny !== undefined || !result.agentId) return result
501    await ready
502    st.live[result.agentId] = { tools: 0, startedAt: await $.clock.now() }
503    if (!e.parentAgentId) await autoOpen($) // a main-loop spawn
504    const prompt = clip(e.prompt, 2000)
505    await record($, {
506      v: 1,
507      ...(await stamp($)),
508      kind: 'agent',
509      title: clip(e.description, 80) ?? e.subagentType,
510      agent: {
511        id: result.agentId,
512        phase: 'start',
513        type: e.subagentType,
514        model: result.model,
515        isPinned: !e.fork && (!!e.model || result.model !== e.parentModel), // set on the call or by the agent's own definition; a fork inherits
516        isBackground: e.background,
517        ...(e.parentAgentId ? { parentAgentId: e.parentAgentId } : {}),
518        ...(st.activeTask ? { parentTask: st.activeTask } : {}),
519        ...(prompt ? { prompt } : {}),
520      },
521    })
522    return result
523  })
524
525  // A subagent's turn ended: freeze its card. An agent continued later can end more than once.
526  on('turn.complete', async ($, e, next) => {
527    const result = await next(e)
528    if (!e.agentId) return result
529    await ready
530    // Engine forks and other plugins' agents carry agent ids too: only end agents this timeline started.
531    if (!(e.agentId in st.live) && !st.entries.some(x => x.kind === 'agent' && x.agent?.id === e.agentId)) return result
532    const agent = st.live[e.agentId]
533    delete st.live[e.agentId]
534    const summary = clip(e.answer.split('\n').find(line => line.trim()) ?? '', 160)
535    const u = e.usage
536    // Cached input counts too: with prompt caching, uncached input alone is a small fraction of what the agent read.
537    const tokens = u
538      ? u.input_tokens + u.output_tokens + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
539      : undefined
540    await record($, {
541      v: 1,
542      ...(await stamp($)),
543      kind: 'agent',
544      title: 'agent end',
545      agent: {
546        id: e.agentId,
547        phase: 'end',
548        status: e.reason === 'answer' ? 'done' : 'failed', // aborted, refused or an API error
549        durationMs: e.durationMs,
550        ...(agent ? { tools: agent.tools } : {}),
551        ...(tokens !== undefined ? { tokens } : {}),
552        ...(summary ? { result: summary } : {}),
553      },
554    })
555    return result
556  })
557
558  // ship-state's snapshot for this repo went from pending CI to a result: add a CI fact.
559  on('state.set', { plugin: 'ship-state', key: 'snap' }, async ($, e, next) => {
560    const result = await next(e)
561    await ready
562    const dir = (e.value as { dir?: unknown } | null | undefined)?.dir
563    const isThisRepo =
564      !!st.repo && typeof dir === 'string' && (dir === here() || dir === st.repo.root || dir.startsWith(`${st.repo.root}/`))
565    const found = isThisRepo ? ciFact(e.previous ?? lastSnap, e.value) : undefined
566    lastSnap = e.value
567    if (found) await recordFact($, found)
568    return result
569  })
570
571  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
572    const v = await read($, view)
573    const ui = $.ui.resolve(e)
574    const { Box, Text, Button } = ui
575    // A view stored by the code before this one (no panel) reads as not drawn yet: the next redraw replaces it.
576    if (!v?.panel) return <Text dimColor>Timeline loading…</Text>
577
578    const turn = (delta: number) => async () => {
579      st.page = Math.max(0, st.page + delta)
580      await redraw($)
581    }
582    // bodyColumns is the pane's own width (a docked pane is narrower than the screen viewport).
583    // The terminal's table names Svg too but draws it as nothing: there the lanes go as text.
584    return drawPane(e.surface === 'terminal' ? { Box, Text, Button } : ui, v, e.props.bodyColumns, turn)
585  })
586}
587
hooks/layout.ts 191 lines
1import type { AgentNode, Entry, HistoryRow, LiveAgent, Node, Panel, Task, WorkNode } from '../types'
2import { elapsed } from './draw.ts'
3import { buildLanes } from './lanes.ts'
4import { currentGroup, type Plan } from './plan.ts'
5import { isBlocked } from './tasks.ts'
6
7// Entries (oldest first) → nodes on the line. `session` is this session's id; `live` holds its running agents.
8export function buildNodes(
9  entries: readonly Entry[],
10  live: Readonly<Record<string, LiveAgent>>,
11  session: string,
12  now: number,
13): Node[] {
14  const nodes: Node[] = []
15  const tags = new Map<string, number>()
16  const lastWork = new Map<string, WorkNode>()
17  const agents = new Map<string, AgentNode>()
18  const startedIn = new Map<string, string>() // agent id → session that started it
19
20  for (const e of entries) {
21    if (e.kind === 'talk' || e.kind === 'session') {
22      nodes.push({ kind: e.kind, at: e.at, title: e.title })
23      // A closed session's agents with no end entry are no longer running there.
24      if (e.kind === 'session' && e.event === 'close') {
25        for (const card of agents.values()) {
26          if (card.state === 'running' && !live[card.id] && startedIn.get(card.id) === e.session) {
27            card.state = 'unknown'
28            delete card.now
29          }
30        }
31      }
32    } else if (e.kind === 'fact') {
33      const card = e.attachTo ? lastWork.get(e.attachTo) : undefined
34      if (card) card.facts.push(e.title)
35      else nodes.push({ kind: 'fact', at: e.at, title: e.title })
36    } else if (e.kind === 'work' && e.agentId) {
37      const card = agents.get(e.agentId)
38      if (!card) continue
39      if (e.next) card.next = e.next
40      if (e.total !== undefined) {
41        card.total = e.total
42        card.done = e.done ?? 0
43      }
44    } else if (e.kind === 'work') {
45      const task = e.task ?? 'task'
46      const tag = tags.get(task) ?? tags.size + 1
47      tags.set(task, tag)
48      const card: WorkNode = { kind: 'work', at: e.at, title: e.title, task, tag, status: e.status ?? 'active', facts: [] }
49      if (e.total !== undefined) {
50        card.total = e.total
51        card.done = e.done ?? 0
52      }
53      if (e.how) card.how = e.how
54      if (e.next) card.next = e.next
55      lastWork.set(task, card)
56      nodes.push(card)
57    } else if (e.kind === 'agent' && e.agent) {
58      const a = e.agent
59      if (a.phase === 'start') {
60        const parent = a.parentAgentId ? agents.get(a.parentAgentId) : undefined
61        const run = live[a.id]
62        const card: AgentNode = {
63          kind: 'agent',
64          at: e.at,
65          id: a.id,
66          title: e.title,
67          depth: parent ? Math.min(parent.depth + 1, 4) : 1,
68          type: a.type ?? 'agent',
69          model: a.model ?? 'unknown',
70          isPinned: a.isPinned ?? false,
71          isBackground: a.isBackground ?? false,
72          // Another session's agent without an end entry is still running there; ours without live state lost it to a reload.
73          state: run || e.session !== session ? 'running' : 'unknown',
74          tools: run?.tools ?? 0,
75        }
76        if (run) {
77          card.elapsedMs = now - run.startedAt
78          if (run.now) card.now = run.now
79        }
80        if (a.prompt) card.prompt = a.prompt
81        if (a.parentTask) card.parentTask = a.parentTask
82        agents.set(a.id, card)
83        startedIn.set(a.id, e.session)
84        nodes.push(card)
85      } else {
86        const card = agents.get(a.id)
87        if (!card) continue
88        delete card.result
89        delete card.tokens
90        delete card.elapsedMs
91        card.state = a.status ?? 'done'
92        delete card.now
93        if (a.durationMs !== undefined) card.elapsedMs = a.durationMs
94        if (a.tools !== undefined) card.tools = a.tools
95        if (a.tokens !== undefined) card.tokens = a.tokens
96        if (a.result) card.result = a.result
97      }
98    }
99  }
100  return nodes
101}
102
103const NEXT_SHOWN = 5
104const DAY_MS = 24 * 60 * 60 * 1000
105const LANES_MS = 15 * 60_000
106const LANES_SHOWN = 8
107
108function historyRow(node: Node): HistoryRow {
109  if (node.kind === 'agent') {
110    const glyph = { running: '▶', done: '✓', failed: '✗', unknown: '?' }[node.state]
111    const tone = ({ running: 'run', done: 'ok', failed: 'fail', unknown: 'dim' } as const)[node.state]
112    const state = { running: '', done: '', failed: ' failed', unknown: ' (status unknown)' }[node.state]
113    const time = elapsed(node.elapsedMs)
114    return { at: node.at, glyph, text: `${node.type} · ${node.model} · ${node.title}${state}${time ? `  ${time}` : ''}`, tone, depth: 0 }
115  }
116  if (node.kind === 'work') {
117    const steps = node.total ? ` ${node.done ?? 0}/${node.total}` : ''
118    const fact = node.facts.length ? ` ↳ ${node.facts[node.facts.length - 1]}` : ''
119    const glyph = node.status === 'done' ? '✓' : node.status === 'blocked' ? '⚠' : '▶'
120    const tone = node.status === 'done' ? 'ok' : node.status === 'blocked' ? 'warn' : 'run'
121    return { at: node.at, glyph, text: `${node.title}${steps}${fact}`, tone, depth: 0 }
122  }
123  if (node.kind === 'talk') return { at: node.at, glyph: '💬', text: node.title, tone: 'normal', depth: 0 }
124  return { at: node.at, glyph: '↳', text: node.title, tone: 'dim', depth: 0 }
125}
126
127// Nodes (oldest first) + this session's task mirror + the active plan → what the pane shows.
128// History is newest first; page 0 is the newest `size` top-level rows, each with its child rows; an out-of-range page clamps.
129// `now` (ms) lets GOAL, BLOCKED and NOW ignore log entries from an earlier day; history still shows them.
130export function buildPanel(nodes: readonly Node[], tasks: readonly Task[], plan: Plan | null, page: number, size: number, now: number): Panel {
131  const latestWork = new Map<string, WorkNode>()
132  for (const n of nodes) if (n.kind === 'work') latestWork.set(n.task, n)
133  const isFresh = (n: WorkNode) => now - Date.parse(n.at) < DAY_MS
134  // Tasks whose latest entry is still active, newest first (an older 'active' entry of a task since done does not count).
135  const activeWork = [...nodes].reverse().filter((n): n is WorkNode => n.kind === 'work' && n.status === 'active' && latestWork.get(n.task) === n && isFresh(n))
136
137  const open = tasks.filter(t => t.status !== 'completed')
138  const waiting = open.filter(t => t.status === 'pending' && isBlocked(t, tasks)) // an in-progress task shows in NOW only
139  const ready = open.filter(t => t.status === 'pending' && !isBlocked(t, tasks))
140  const blocked = [
141    ...waiting.map(t => ({ title: t.subject, waitsOn: t.blockedBy.find(id => tasks.some(x => x.id === id && x.status !== 'completed')) })),
142    ...[...latestWork.values()].filter(w => w.status === 'blocked' && isFresh(w)).map(w => ({ title: w.title })),
143  ]
144
145  // An agent that ran for a task sits under that task's work row logged last before it; the rest are top-level rows.
146  const children = new Map<Node, AgentNode[]>()
147  const lastSeen = new Map<string, WorkNode>()
148  for (const n of nodes) {
149    if (n.kind === 'work') lastSeen.set(n.task, n)
150    const parent = n.kind === 'agent' && n.parentTask ? lastSeen.get(n.parentTask) : undefined
151    if (n.kind === 'agent' && parent) children.set(parent, [...(children.get(parent) ?? []), n])
152  }
153  const isChild = new Set<Node>([...children.values()].flat())
154  // Newest first; a parent's children follow it, newest first. Session open/close is bookkeeping, not history.
155  const groups = [...nodes].reverse().filter(n => n.kind !== 'session' && !isChild.has(n)).map(n => {
156    const kids = [...(children.get(n) ?? [])].reverse().map((k, i, all): HistoryRow => ({ ...historyRow(k), depth: 1, ...(i === all.length - 1 ? { isLast: true } : {}) }))
157    return [historyRow(n), ...kids]
158  })
159  const pages = Math.max(1, Math.ceil(groups.length / size))
160  const clamped = Math.min(Math.max(0, page), pages - 1)
161
162  // A running agent with no live clock (another session's, no end entry) counts only for a day: that session likely died.
163  const nowAgents = nodes.filter(
164    (n): n is AgentNode => n.kind === 'agent' && n.state === 'running' && (n.elapsedMs !== undefined || now - Date.parse(n.at) < DAY_MS),
165  )
166  const panel: Panel = {
167    nowWork: activeWork.map(w => ({ title: w.title, task: w.task, ...(w.total !== undefined ? { done: w.done ?? 0, total: w.total } : {}) })),
168    nowAgents,
169    nowTasks: open.filter(t => t.status === 'in_progress'),
170    next: ready.slice(0, NEXT_SHOWN),
171    nextMore: Math.max(0, ready.length - NEXT_SHOWN),
172    blocked,
173    // Only the running agents NOW shows draw a running lane (not a dead session's).
174    lanes: {
175      lanes: buildLanes(nodes.filter(n => n.kind !== 'agent' || n.state !== 'running' || nowAgents.includes(n)), now, LANES_MS, LANES_SHOWN),
176      from: now - LANES_MS,
177      to: now,
178    },
179    history: groups.slice(clamped * size, clamped * size + size).flat(),
180    page: clamped,
181    pages,
182  }
183  const goal = (plan && plan.done < plan.total ? plan.title : '') || activeWork[0]?.title // a finished plan is not the goal
184  if (goal) panel.goal = goal
185  if (plan && plan.done > 0) {
186    const group = currentGroup(plan)
187    panel.plan = { ...(group ? { group } : {}), done: plan.done, total: plan.total }
188  }
189  return panel
190}
191
hooks/model.ts 180 lines
1import type { Entry, Fact } from '../types'
2
3export type Stamp = { id: string; at: string; session: string; branch?: string; worktree?: string; agentId?: string }
4export type Found = { title: string; fact: Fact }
5
6// One line, trimmed, cut to max with an ellipsis; undefined for non-strings and blanks.
7export function clip(value: unknown, max: number): string | undefined {
8  if (typeof value !== 'string') return undefined
9  const text = value.replace(/\s+/g, ' ').trim()
10  if (!text) return undefined
11  return text.length > max ? `${text.slice(0, max - 1).replace(/[\uD800-\uDBFF]$/, '')}…` : text
12}
13
14export function slug(text: string): string {
15  return text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').slice(0, 40).replace(/^-+|-+$/g, '') || 'task'
16}
17
18// The model's tool input → an entry, or an error message the model reads.
19export function fromLog(input: Record<string, unknown>, stamp: Stamp): Entry | { error: string } {
20  const title = clip(input.title, 80)
21  const kind = input.kind
22  if (!title || (kind !== 'talk' && kind !== 'work')) {
23    return { error: 'timeline log needs kind ("talk" or "work") and title. Work also takes task, done, total, status, how, next.' }
24  }
25  if (kind === 'talk') return { v: 1, ...stamp, kind, title }
26
27  const entry: Entry = {
28    v: 1,
29    ...stamp,
30    kind,
31    title,
32    task: typeof input.task === 'string' && input.task.trim() ? slug(input.task) : slug(title),
33    status: input.status === 'done' || input.status === 'blocked' ? input.status : 'active',
34  }
35  if (typeof input.total === 'number' && Number.isFinite(input.total) && input.total >= 1) {
36    entry.total = Math.floor(input.total)
37    entry.done = typeof input.done === 'number' && Number.isFinite(input.done) ? Math.min(entry.total, Math.max(0, Math.floor(input.done))) : 0
38  }
39  const how = clip(input.how, 200)
40  if (how) entry.how = how
41  const next = clip(input.next, 120)
42  if (next) entry.next = next
43  return entry
44}
45
46const AT_COMMAND = String.raw`(?:^|&&|;|\|\||\n)\s*`
47const GIT = String.raw`git(?:\s+(?:-[Cc]\s+(?:"[^"]*"|'[^']*'|\S+)|--[\w-]+(?:=\S+)?))*\s+`
48const GIT_COMMIT = new RegExp(`${AT_COMMAND}${GIT}commit\\b`)
49const GIT_PUSH = new RegExp(`${AT_COMMAND}${GIT}push\\b`)
50const PR_CREATE = new RegExp(`${AT_COMMAND}gh\\s+pr\\s+create\\b`)
51const PR_MERGE = new RegExp(`${AT_COMMAND}gh\\s+pr\\s+merge\\b([^\\n;&|]*)`)
52
53// Last `cd <dir>` in a shell command, resolved against base; undefined when there is none.
54export function lastCd(command: string, base: string): string | undefined {
55  const all = [...command.matchAll(/(?:^|&&|;|\|\||\n)\s*cd\s+(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/g)]
56  const m = all.at(-1)
57  const path = m && (m[1] ?? m[2] ?? m[3])
58  if (!path || /^[~$-]/.test(path)) return undefined
59  return path.startsWith('/') ? path : `${base}/${path}`
60}
61
62// Facts a Bash command produced. Commit, push and PR facts must show in the output; a merge comes from the command.
63export function factsFromBash(command: string, output: string): Found[] {
64  const found: Found[] = []
65  if (GIT_COMMIT.test(command)) {
66    for (const m of output.matchAll(/^\[.+? ([0-9a-f]{7,40})\] (.+)$/gm)) {
67      found.push({ title: `commit ${m[1]} ${clip(m[2], 60) ?? ''}`.trim(), fact: { type: 'commit', ref: m[1]! } })
68    }
69  }
70  if (GIT_PUSH.test(command)) {
71    // Git's ref lines: " * [new branch] a -> b", "   1a2b..3c4d  a -> b", " + ... (forced update)"; not "!" rejected, "-" deleted, "=" up to date.
72    for (const m of output.matchAll(/^ [ *+] .*? -> (\S+)/gm)) found.push({ title: `push ${m[1]}`, fact: { type: 'push', ref: m[1]! } })
73  }
74  if (PR_CREATE.test(command)) {
75    const m = output.match(/https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/(\d+)/)
76    if (m) found.push({ title: `PR #${m[1]}`, fact: { type: 'pr', ref: m[1]!, url: m[0] } })
77  }
78  const merge = command.match(PR_MERGE)
79  if (merge && !/--auto\b/.test(merge[1] ?? '')) {
80    const n = merge[1]?.match(/(?:^|\s)#?(\d+)(?=\s|$)|\/pull\/(\d+)/)
81    const ref = n?.[1] ?? n?.[2]
82    found.push({ title: ref ? `merged PR #${ref}` : 'merged PR', fact: { type: 'merge', ref: ref ?? '' } })
83  }
84  return found
85}
86
87const SKIP_ARGS = new Set(['tool', 'tool_use_id', 'agentId', 'consent'])
88
89// The first string argument of a tool call: a Bash command, a file path, a pattern.
90export function mainArg(input: Record<string, unknown>): string | undefined {
91  const hit = Object.entries(input).find(([key, value]) => !SKIP_ARGS.has(key) && typeof value === 'string')
92  return hit ? (hit[1] as string) : undefined
93}
94
95type Ci = { sha: string; total: number; pending: number; failed: string[] }
96
97const ciOf = (snap: unknown): Ci | undefined => {
98  const ci = (snap as { ci?: unknown } | null | undefined)?.ci as Partial<Ci> | undefined
99  return ci && typeof ci.sha === 'string' && typeof ci.total === 'number' && typeof ci.pending === 'number' && Array.isArray(ci.failed)
100    ? (ci as Ci)
101    : undefined
102}
103
104// ship-state's snapshot went from pending to final CI on the same SHA.
105export function ciFact(previous: unknown, current: unknown): Found | undefined {
106  const a = ciOf(previous)
107  const b = ciOf(current)
108  if (!a || !b || a.sha !== b.sha || !a.pending || b.pending || !b.total) return undefined
109  const sha = b.sha.slice(0, 7)
110  return b.failed.length
111    ? { title: clip(`CI ✗ ${b.failed.join(', ')} @${sha}`, 80) ?? 'CI ✗', fact: { type: 'ci', ref: b.sha, state: 'failure' } }
112    : { title: `CI ✓ ${b.total} @${sha}`, fact: { type: 'ci', ref: b.sha, state: 'success' } }
113}
114
115// 32-bit FNV-1a as 8 hex digits: a short, stable folder suffix.
116export function fnv1a(text: string): string {
117  let hash = 0x811c9dc5
118  for (let i = 0; i < text.length; i++) {
119    hash ^= text.charCodeAt(i)
120    hash = Math.imul(hash, 0x01000193) >>> 0
121  }
122  return hash.toString(16).padStart(8, '0')
123}
124
125export function folderName(root: string): string {
126  const clean = root.replace(/\/+$/, '') || '/'
127  return `${clean.split('/').filter(Boolean).at(-1) ?? 'root'}-${fnv1a(clean)}`
128}
129
130// `git rev-parse --path-format=absolute --git-common-dir` → the root its worktrees share.
131export const repoRoot = (commonDir: string) => commonDir.replace(/\/\.git\/?$/, '') || commonDir
132
133const KINDS = new Set(['talk', 'work', 'fact', 'agent', 'session'])
134
135const isEntry = (value: unknown): value is Entry => {
136  const e = value as Partial<Entry> | null
137  return (
138    !!e &&
139    e.v === 1 &&
140    typeof e.id === 'string' &&
141    typeof e.at === 'string' &&
142    typeof e.session === 'string' &&
143    typeof e.title === 'string' &&
144    typeof e.kind === 'string' &&
145    KINDS.has(e.kind)
146  )
147}
148
149export function parseJsonl(text: string): { entries: Entry[]; bad: number } {
150  const entries: Entry[] = []
151  let bad = 0
152  for (const line of text.split('\n')) {
153    if (!line.trim()) continue
154    try {
155      const value: unknown = JSON.parse(line)
156      if (isEntry(value)) entries.push(value)
157      else bad++
158    } catch {
159      bad++
160    }
161  }
162  return { entries, bad }
163}
164
165export const toJsonl = (entries: readonly Entry[]) => entries.map(e => JSON.stringify(e)).join('\n') + '\n'
166
167// All lists into one, deduplicated by id, oldest first.
168export function mergeEntries(lists: readonly (readonly Entry[])[]): Entry[] {
169  const byId = new Map<string, Entry>()
170  for (const list of lists) for (const entry of list) byId.set(entry.id, entry)
171  return [...byId.values()].sort((a, b) => a.at.localeCompare(b.at) || a.id.localeCompare(b.id, 'en', { numeric: true }))
172}
173
174// `date +%z` output ("-0500") → minutes east of UTC.
175export function tzMinutes(text: string | undefined): number {
176  const m = text?.trim().match(/^([+-])(\d{2})(\d{2})$/)
177  if (!m) return 0
178  return (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3]))
179}
180
hooks/pane.tsx 172 lines
1import type { Elements } from 'claude-code'
2
3import type { AgentNode, View } from '../types'
4import { bar, elapsed, hhmm, tokens } from './draw'
5import { LANE_INDENT, lanesSvg, lanesText } from './lanes'
6
7// Svg only where the surface draws it (desktop, mobile, editor); the terminal draws the lanes as text.
8type UI = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> & { Svg?: Elements['desktop']['Svg'] }
9
10export const WIDE = 70 // body columns at which NEXT and BLOCKED sit side by side
11// Theme keys where the app has one, so each theme picks its own legible shade.
12const COLOR = { run: 'blue', ok: 'success', warn: 'warning', fail: 'error', normal: undefined, dim: undefined } as const
13
14const iso = (ms: number) => new Date(ms).toISOString()
15
16const stats = (a: AgentNode) =>
17  [a.type, a.model, elapsed(a.elapsedMs), a.tools ? `${a.tools} tool${a.tools === 1 ? '' : 's'}` : '', tokens(a.tokens)]
18    .filter(Boolean)
19    .join(' · ') + (a.isPinned || a.type === 'fork' ? '' : ' · ⚠ inherited model')
20
21// The whole pane from the surface's own elements: the same tree on the terminal and the desktop.
22// `page(+1)` shows older history, `page(-1)` newer. Takes no `$` (the loader rule).
23export function drawPane(ui: UI, v: View, columns: number, page: (delta: number) => () => void) {
24  const { Box, Text, Button, Svg } = ui
25  const p = v.panel
26  const { lanes, from, to } = p.lanes
27  const isWide = columns >= WIDE
28  const hasNow = p.nowWork.length > 0 || p.nowAgents.length > 0 || p.nowTasks.length > 0
29  const hasSide = p.next.length > 0 || p.blocked.length > 0
30  const isEmpty = !hasNow && !hasSide && p.history.length === 0
31  const head = [v.repo, v.branch, v.bad ? `${v.bad} unreadable` : ''].filter(Boolean).join(' · ')
32
33  return (
34    <Box flexDirection="column" rowGap={1}>
35      <Box key="head" flexDirection="column">
36        <Text bold wrap="truncate">{head}</Text>
37        {/* One Text per line, label inline: a Text beside another in a row gets squeezed on the terminal. */}
38        {p.goal && (
39          <Box key="goal">
40            <Text wrap="wrap">
41              <Text dimColor>GOAL</Text> {p.goal}
42            </Text>
43          </Box>
44        )}
45        {p.plan && (
46          <Box key="plan">
47            <Text wrap="truncate">
48              <Text dimColor>PLAN</Text> {bar(p.plan.done, p.plan.total, 12)} {p.plan.group ? `${p.plan.group} · ` : ''}
49              {p.plan.done}/{p.plan.total} steps
50            </Text>
51          </Box>
52        )}
53      </Box>
54
55      {isEmpty && (
56        <Text key="empty" dimColor wrap="wrap">
57          No activity yet. Claude's task list, subagents and plan steps show here.
58        </Text>
59      )}
60
61      {(hasNow || hasSide) && (
62        <Box key="status" flexDirection="column" rowGap={1} borderStyle="round" borderDimColor paddingX={1}>
63          {hasNow && (
64            <Box key="now" flexDirection="column">
65              <Text bold dimColor>NOW</Text>
66              {p.nowWork.map(w => (
67                <Box key={`work-${w.task}`} flexDirection="column">
68                  <Text color="blue" wrap="wrap">▶ {w.title}</Text>
69                  {w.total !== undefined && (
70                    <Text dimColor wrap="truncate">
71                      {bar(w.done ?? 0, w.total, 10)} {w.done ?? 0}/{w.total}
72                    </Text>
73                  )}
74                </Box>
75              ))}
76              {p.nowTasks.map(t => (
77                <Text key={`task-${t.id}`} color="blue" wrap="wrap">▶ {t.subject}</Text>
78              ))}
79              {p.nowAgents.map(a => (
80                <Box key={`agent-${a.id}`} flexDirection="column">
81                  {isWide ? (
82                    <Text wrap="wrap">
83                      <Text color="blue">▶ {a.title}</Text>
84                      {'  '}
85                      <Text dimColor>{stats(a)}</Text>
86                    </Text>
87                  ) : (
88                    <Text color="blue" wrap="wrap">▶ {a.title}</Text>
89                  )}
90                  {!isWide && <Text dimColor wrap="wrap">{stats(a)}</Text>}
91                  {(a.now || a.next) && (
92                    <Text dimColor wrap="wrap">
93                      {[a.now ? `now: ${a.now}` : '', a.next ? `next: ${a.next}` : ''].filter(Boolean).join(' · ')}
94                    </Text>
95                  )}
96                </Box>
97              ))}
98            </Box>
99          )}
100          {hasSide && (
101            <Box key="side" flexDirection={isWide ? 'row' : 'column'} columnGap={2} rowGap={1}>
102              {p.next.length > 0 && (
103                <Box key="next" flexDirection="column" width={isWide && p.blocked.length ? '50%' : '100%'}>
104                  <Text bold dimColor>NEXT</Text>
105                  {p.next.map(t => (
106                    <Text key={`next-${t.id}`} wrap="wrap">○ {t.subject}</Text>
107                  ))}
108                  {p.nextMore > 0 && <Text dimColor>+{p.nextMore} more</Text>}
109                </Box>
110              )}
111              {p.blocked.length > 0 && (
112                <Box key="blocked" flexDirection="column" width={isWide && p.next.length ? '50%' : '100%'}>
113                  <Text bold dimColor>BLOCKED</Text>
114                  {p.blocked.map((b, i) => (
115                    <Text key={`blocked-${i}`} color={COLOR.warn} wrap="wrap">
116                      ⚠ {b.title}{b.waitsOn ? ` — waits on #${b.waitsOn}` : ''}
117                    </Text>
118                  ))}
119                </Box>
120              )}
121            </Box>
122          )}
123        </Box>
124      )}
125
126      {lanes.length > 0 && (
127        <Box key="lanes" flexDirection="column">
128          <Text bold dimColor>AGENTS · last 15 min</Text>
129          {Svg ? (
130            <Svg
131              source={lanesSvg(lanes, from, to, columns * 7)}
132              alt={`Agent runs in the last 15 minutes: ${lanes.map(l => `${l.label} ${l.state}`).join(', ')}`}
133            />
134          ) : (
135            lanesText(lanes, from, to, columns - LANE_INDENT - 2).map((line, i) => (
136              <Text key={`lane-${i}`} dimColor wrap="truncate">{line}</Text>
137            ))
138          )}
139          <Box flexDirection="row" justifyContent="space-between" paddingLeft={LANE_INDENT} paddingRight={2}>
140            <Text dimColor>{hhmm(iso(from), v.tz)}</Text>
141            <Text dimColor>{hhmm(iso((from + to) / 2), v.tz)}</Text>
142            <Text dimColor>now</Text>
143          </Box>
144        </Box>
145      )}
146
147      {p.history.length > 0 && (
148        <Box key="history" flexDirection="column">
149          <Box flexDirection="row" justifyContent="space-between">
150            <Text bold dimColor>HISTORY</Text>
151            <Box flexDirection="row" columnGap={1}>
152              {p.page < p.pages - 1 && <Button key="older" label="◀ older" onPress={page(1)} />}
153              {p.page > 0 && <Button key="newer" label="newer ▶" onPress={page(-1)} />}
154            </Box>
155          </Box>
156          {p.history.map((r, i) =>
157            r.depth ? (
158              <Text key={`row-${i}`} color={r.tone === 'fail' ? COLOR.fail : undefined} dimColor={r.tone !== 'fail'} wrap="truncate">
159                {`  ${r.isLast ? '└' : '├'} ${r.glyph} ${r.text}`}
160              </Text>
161            ) : (
162              <Text key={`row-${i}`} color={COLOR[r.tone]} dimColor={r.tone === 'dim'} wrap="truncate">
163                {hhmm(r.at, v.tz)} {r.glyph} {r.text}
164              </Text>
165            ),
166          )}
167        </Box>
168      )}
169    </Box>
170  )
171}
172
hooks/plan.ts 46 lines
1export type PlanGroup = { name: string; done: number; total: number }
2export type Plan = { title: string; groups: PlanGroup[]; done: number; total: number }
3
4const BOX = /^\s*[-*] \[( |x|X)\]/
5
6// A markdown plan → its title and per-heading checkbox counts; null when it has no boxes.
7// Fenced code is skipped, so a `# comment` or a `- [ ]` inside a code block counts for nothing.
8export function parsePlan(markdown: string): Plan | null {
9  let title = ''
10  let fence = '' // the opening marker while inside a fenced block
11  const groups: PlanGroup[] = []
12  for (const line of markdown.split('\n')) {
13    const mark = /^\s*(`{3,}|~{3,})(.*)$/.exec(line)
14    if (mark) {
15      // Only the same character, at least as long and with nothing after it, closes a fence (so ```` can hold ```).
16      if (!fence) fence = mark[1]!
17      else if (mark[1]![0] === fence[0] && mark[1]!.length >= fence.length && !mark[2]!.trim()) fence = ''
18      continue
19    }
20    if (fence) continue
21    const h1 = /^# (.+)/.exec(line)
22    if (h1 && !title) {
23      title = h1[1]!.trim().replace(/\s+Implementation Plan$/i, '')
24      continue
25    }
26    const h = /^#{2,3} (.+)/.exec(line)
27    if (h) {
28      groups.push({ name: h[1]!.trim(), done: 0, total: 0 })
29      continue
30    }
31    const box = BOX.exec(line)
32    if (!box) continue
33    if (!groups.length) groups.push({ name: title || 'Plan', done: 0, total: 0 })
34    const group = groups[groups.length - 1]!
35    group.total += 1
36    if (box[1] !== ' ') group.done += 1
37  }
38  const counted = groups.filter(g => g.total > 0)
39  const total = counted.reduce((n, g) => n + g.total, 0)
40  if (!total) return null
41  return { title, groups: counted, done: counted.reduce((n, g) => n + g.done, 0), total }
42}
43
44// The first group with an unticked box.
45export const currentGroup = (plan: Plan) => plan.groups.find(g => g.done < g.total)?.name
46
hooks/tasks.ts 70 lines
1import type { Task, TaskStatus } from '../types'
2
3const STATUSES = new Set<string>(['pending', 'in_progress', 'completed'])
4const bare = (id: string) => id.replace(/^#/, '')
5const text = (v: unknown) => (typeof v === 'string' ? v.trim() : '')
6const asId = (v: unknown) => (typeof v === 'string' || typeof v === 'number' ? bare(String(v)) : '')
7const ids = (v: unknown) => (Array.isArray(v) ? v.map(asId).filter(Boolean) : [])
8
9// The id a TaskCreate result gives the new task: the structured `task.id`, else the "#<n>" in its text.
10export const createdId = (result: unknown, text: string): string | undefined =>
11  asId((result as { task?: { id?: unknown } } | null | undefined)?.task?.id) || /#(\d+)/.exec(text)?.[1]
12
13// One main-loop TaskCreate / TaskUpdate / TodoWrite call → the new list. `input` is the tool call's input fields;
14// `id` names the task a TaskCreate adds (see createdId). Any other tool, or a shape it does not expect, leaves the list as it was.
15export function applyTaskCall(tasks: readonly Task[], tool: string, input: object, id: string): Task[] {
16  const i = input as Record<string, unknown>
17  if (tool === 'TodoWrite') {
18    if (!Array.isArray(i.todos)) return [...tasks]
19    return i.todos.flatMap((t: unknown, n: number) => {
20      const o = (t ?? {}) as Record<string, unknown>
21      const subject = text(o.content)
22      if (!subject) return []
23      const status = STATUSES.has(String(o.status)) ? (o.status as TaskStatus) : 'pending'
24      return [{ id: `t${n}`, subject, status, blockedBy: [] }]
25    })
26  }
27  if (tool === 'TaskCreate') {
28    const subject = text(i.subject)
29    if (!subject) return [...tasks]
30    return [...tasks.filter(t => t.id !== id), { id, subject, status: 'pending', blockedBy: [] }]
31  }
32  if (tool === 'TaskUpdate') {
33    const target = asId(i.taskId)
34    if (!target) return [...tasks]
35    if (i.status === 'deleted') return tasks.filter(t => t.id !== target)
36    const subject = text(i.subject)
37    const adds = ids(i.addBlockedBy)
38    const blocks = ids(i.addBlocks) // tasks that wait on this one
39    return tasks.map(t =>
40      t.id !== target
41        ? blocks.includes(t.id) ? { ...t, blockedBy: [...new Set([...t.blockedBy, target])] } : t
42        : {
43            ...t,
44            ...(subject ? { subject } : {}),
45            ...(STATUSES.has(String(i.status)) ? { status: i.status as TaskStatus } : {}),
46            ...(adds.length ? { blockedBy: [...new Set([...t.blockedBy, ...adds])] } : {}),
47          },
48    )
49  }
50  return [...tasks]
51}
52
53// A main-loop TaskList result (`{ tasks: [...] }`) → the current list; null when it is not that shape or none of its rows parse.
54export function fromTaskList(result: unknown): Task[] | null {
55  const rows = (result as { tasks?: unknown } | null | undefined)?.tasks
56  if (!Array.isArray(rows)) return null
57  const list = rows.flatMap((r: unknown): Task[] => {
58    const o = (r ?? {}) as Record<string, unknown>
59    const id = asId(o.id)
60    const subject = text(o.subject)
61    if (!id || !subject) return []
62    return [{ id, subject, status: STATUSES.has(String(o.status)) ? (o.status as TaskStatus) : 'pending', blockedBy: ids(o.blockedBy) }]
63  })
64  return list.length || !rows.length ? list : null
65}
66
67// Waits on a task that exists and is not completed.
68export const isBlocked = (task: Task, tasks: readonly Task[]) =>
69  task.blockedBy.some(id => tasks.some(t => t.id === id && t.status !== 'completed'))
70
hooks/draw.ts 22 lines
1// ISO time → HH:MM at `tz` minutes east of UTC (the module's own clock may not know the zone).
2export function hhmm(iso: string, tz: number): string {
3  const d = new Date(Date.parse(iso) + tz * 60_000)
4  if (Number.isNaN(d.getTime())) return '--:--'
5  return `${String(d.getUTCHours()).padStart(2, '0')}:${String(d.getUTCMinutes()).padStart(2, '0')}`
6}
7
8// Never throws: a bad done/total read back from disk (negative, NaN, total 0) draws an empty or full bar.
9export function bar(done: number, total: number, width: number): string {
10  const ratio = total > 0 ? done / total : 0
11  const filled = Number.isFinite(ratio) ? Math.min(width, Math.max(0, Math.round(ratio * width))) : 0
12  return '█'.repeat(filled) + '░'.repeat(width - filled)
13}
14
15export const elapsed = (ms?: number) => {
16  if (typeof ms !== 'number' || !Number.isFinite(ms)) return ''
17  const s = Math.round(ms / 1000)
18  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`
19}
20
21export const tokens = (n?: number) => (typeof n !== 'number' || !Number.isFinite(n) ? '' : n >= 1000 ? `${Math.round(n / 1000)}k tokens` : `${n} tokens`)
22
hooks/lanes.ts 59 lines
1import type { AgentNode, Lane, Node } from '../types'
2
3const LABEL_CELLS = 14
4export const LANE_INDENT = LABEL_CELLS + 1 // label + space, in cells; the SVG uses 7 px a cell
5const GLYPH = { running: '▓', done: '█', failed: '▒', unknown: '░' } as const
6const FILL = { running: '#3b6fd8', done: '#2f9e44', failed: '#e03131', unknown: '#8b93a1' } as const
7
8// Agent runs that overlap [now - windowMs, now], newest `max`, oldest first.
9export function buildLanes(nodes: readonly Node[], now: number, windowMs: number, max: number): Lane[] {
10  const from = now - windowMs
11  const lanes: Lane[] = []
12  for (const n of nodes) {
13    if (n.kind !== 'agent') continue
14    const a = n as AgentNode
15    const start = Date.parse(a.at)
16    if (!Number.isFinite(start)) continue
17    const end = a.state === 'running' ? now : start + (a.elapsedMs ?? 0)
18    if (end < from || start > now) continue
19    lanes.push({ label: a.title, start, end: Math.max(end, start), state: a.state })
20  }
21  return lanes.slice(-max)
22}
23
24const x = (t: number, from: number, to: number, width: number) =>
25  Math.round((Math.min(Math.max(t, from), to) - from) / Math.max(1, to - from) * width)
26
27// Terminal lanes: label (LABEL_CELLS cells) + a track of `cells` cells with the run drawn on it.
28export function lanesText(lanes: readonly Lane[], from: number, to: number, cells: number): string[] {
29  const width = Math.max(10, cells)
30  return lanes.map(l => {
31    const a = Math.min(width - 1, x(l.start, from, to, width)) // a run that starts now still gets the last cell
32    const b = Math.max(a + 1, x(l.end, from, to, width))
33    const track = '·'.repeat(a) + GLYPH[l.state].repeat(Math.min(width, b) - a) + '·'.repeat(Math.max(0, width - b))
34    return `${l.label.slice(0, LABEL_CELLS).padEnd(LABEL_CELLS)} ${track}`
35  })
36}
37
38const esc = (s: string) => s.replace(/[<>&"]/g, c => `&#${c.charCodeAt(0)};`)
39
40// Desktop lanes: a small fixed-height SVG; labels on the left, one bar per run.
41export function lanesSvg(lanes: readonly Lane[], from: number, to: number, width: number): string {
42  if (!lanes.length) return ''
43  const label = LANE_INDENT * 7
44  const track = Math.max(40, width - label - 8)
45  const height = 16 * lanes.length + 8
46  const rows = lanes.map((l, i) => {
47    const y = 4 + i * 16
48    const a = label + x(l.start, from, to, track)
49    const w = Math.max(3, label + x(l.end, from, to, track) - a)
50    return `<text x="0" y="${y + 10}" fill="#8b93a1">${esc(l.label.slice(0, LABEL_CELLS))}</text><rect x="${a}" y="${y}" width="${w}" height="11" rx="3" fill="${FILL[l.state]}"/>`
51  })
52  return (
53    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" font-family="ui-sans-serif, system-ui" font-size="11">` +
54    `<line x1="${label}" y1="${16 * lanes.length + 6}" x2="${label + track}" y2="${16 * lanes.length + 6}" stroke="#8b93a1" stroke-width="1" stroke-opacity="0.6"/>` +
55    rows.join('') +
56    `</svg>`
57  )
58}
59
types/index.d.ts 119 lines
1export type Fact = { type: 'commit' | 'push' | 'pr' | 'merge' | 'ci'; ref: string; state?: string; url?: string }
2
3export type AgentInfo = {
4  id: string
5  phase: 'start' | 'end'
6  type?: string
7  model?: string
8  isPinned?: boolean
9  isBackground?: boolean
10  parentAgentId?: string
11  parentTask?: string
12  prompt?: string
13  status?: 'done' | 'failed'
14  durationMs?: number
15  tools?: number
16  tokens?: number
17  result?: string
18}
19
20export type Entry = {
21  v: 1
22  id: string
23  at: string
24  session: string
25  branch?: string
26  worktree?: string
27  kind: 'talk' | 'work' | 'fact' | 'agent' | 'session'
28  title: string
29  task?: string
30  done?: number
31  total?: number
32  status?: 'active' | 'done' | 'blocked'
33  how?: string
34  next?: string
35  agentId?: string
36  fact?: Fact
37  attachTo?: string
38  agent?: AgentInfo
39  event?: 'open' | 'close'
40}
41
42export type LiveAgent = { now?: string; tools: number; startedAt: number }
43
44export type WorkNode = {
45  kind: 'work'
46  at: string
47  title: string
48  task: string
49  tag: number
50  status: 'active' | 'done' | 'blocked'
51  done?: number
52  total?: number
53  how?: string
54  next?: string
55  facts: string[]
56}
57
58export type AgentNode = {
59  kind: 'agent'
60  at: string
61  id: string
62  title: string
63  depth: number
64  type: string
65  model: string
66  isPinned: boolean
67  isBackground: boolean
68  state: 'running' | 'done' | 'failed' | 'unknown'
69  elapsedMs?: number
70  tools: number
71  tokens?: number
72  now?: string
73  next?: string
74  done?: number
75  total?: number
76  result?: string
77  prompt?: string
78  parentTask?: string
79}
80
81export type Node = { kind: 'talk' | 'session' | 'fact'; at: string; title: string } | WorkNode | AgentNode
82
83export type View = { repo: string; branch?: string; bad: number; tz: number; panel: Panel }
84
85export type TaskStatus = 'pending' | 'in_progress' | 'completed'
86export type Task = { id: string; subject: string; status: TaskStatus; blockedBy: string[] }
87
88export type HistoryRow = {
89  at: string
90  glyph: string
91  text: string
92  tone: 'normal' | 'dim' | 'ok' | 'warn' | 'fail' | 'run'
93  depth: 0 | 1 // 1: an agent shown under the task it ran for
94  isLast?: boolean // the last child under its parent
95}
96
97export type Lane = { label: string; start: number; end: number; state: 'running' | 'done' | 'failed' | 'unknown' }
98
99export type Panel = {
100  goal?: string
101  plan?: { group?: string; done: number; total: number }
102  nowWork: { title: string; task: string; done?: number; total?: number }[]
103  nowAgents: AgentNode[]
104  nowTasks: Task[]
105  next: Task[]
106  nextMore: number
107  blocked: { title: string; waitsOn?: string }[]
108  lanes: { lanes: Lane[]; from: number; to: number }
109  history: HistoryRow[]
110  page: number
111  pages: number
112}
113
114declare module 'claude-code' {
115  interface PluginState {
116    timeline: { view: View | null; tasks: Task[] }
117  }
118}
119