A verification-first development pipeline for Claude Code: brainstorm to plan to phased implementation, with quality gates (verification-loop, code-review…

Custom skills and agents for Claude Code that enhance codebase research, context management, and implementation planning workflows.
New to this workflow? See the Workflow Overview for a step-by-step guide.
Installing? This repo ships as the
devflowClaude Code plugin — see Installation and Plugin Distribution.
This skill collection uses Claude Code's native Task tools for progress tracking.
Progress tracking is handled entirely through Claude Code's built-in Task system:
| Tool | Purpose |
|---|---|
TaskCreate | Create tasks for each phase with dependencies |
TaskUpdate | Mark tasks as in_progress or completed |
TaskList | View all tasks with status and blockers |
TaskGet | Get full task details including description |
Benefits:
Plans remain pure specification documents. See Progress Tracking for details.
This collection uses modern Claude Code skill features (v2.1.16+):
| Feature | Skills Using It | Purpose |
|---|---|---|
context: fork | codebase-research | Run in isolated subagent context. Only for skills that run to completion without the user and don't wait on agents of their own: agent reports arrive in the top-level session, so the phase leads (implement-phase, tt-implement-phase) run inline. |
agent: Explore/Plan | (none) | Subagent type for a forked skill. Both built-ins are read-only and lack the Agent tool, so any skill that writes files or spawns subagents must leave this unset. |
allowed-tools | code-review, verification-loop, security-review, adversarial-reviewer, codebase-research, strategic-compact | Restrict available tools (read-only enforcement) |
argument-hint | implement-plan, implement-phase, adr, e2e-testing, code-review, adversarial-reviewer, context-saver, prompt-generator | Show usage hints in autocomplete |
disable-model-invocation | context-saver, prompt-generator | User-only invocation (no auto-trigger) |
user-invocable: false | implement-phase | Hide from user menu (internal skill) |
Never add context: fork to an interactive skill. A forked skill runs in a subagent with no access to the conversation history, and since Claude Code v2.1.218 it is backgrounded by default — so a skill that asks the user questions and waits for answers (brainstorm) simply never reaches the user. agent: Explore compounds it: that agent type is read-only, so the skill cannot write its output document either. tests/test-interactive-skills.sh guards this.
Skills support the new argument syntax:
$0, $1, $2 - Positional arguments$ARGUMENTS - All arguments${CLAUDE_SESSION_ID} - Session trackingExample: /implement-plan docs/plans/my-feature.md passes the path as $0.
The core workflow for implementing features follows this hierarchy:
┌─────────────────┐
│ brainstorm │
│ (ideation) │
└────────┬────────┘
│
┌───────────┴───────────┐
▼ ▼
┌─────────────────┐ ┌──────────────────┐
│ adr │ │ user-story │
│ (decisions) │ │ (requirements) │
└────────┬────────┘ └──────────┬───────┘
└────────────┬──────────┘
│
▼
┌─────────────────┐
│ create-plan │
│ (spec → phases) │
└────────┬────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────────┐
│ implement-plan │
│ (orchestrates all phases) │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Phase 1 │───▶│ Phase 2 │───▶│ Phase N │───▶ Complete │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ implement-phase (per phase) │ │
│ │ ┌────────────────────────────────────────────────────────────┐ │ │
│ │ │ Step 1: Implementation (subagents) [TDD mode: tests first] │ │ │
│ │ │ Step 2: verification-loop (6-phase exit conditions) ─────┐│ │ │
│ │ │ Step 3: Integration Testing (API/UI via Playwright) ││ │ │
│ │ │ Step 4: code-review ─────────────────────────────────────┼┼──┐ │ │
│ │ │ ├─► security-review (optional OWASP audit) ──────┼┼──┼─┐│ │
│ │ │ Step 5: ADR Compliance ──────────────────────────────────┼┼──┼─┼┤ │
│ │ │ Step 6: Plan Sync ││ │ ││ │
│ │ │ Step 7: Prompt Archival ││ │ ││ │
│ │ │ Step 8: Completion Report ││ │ ││ │
│ │ └──────────────────────────────────────────────────────────┼┼──┼─┼┘ │
│ └─────────────────────────────────────────────────────────────┼┼──┼─┼─────┘
│ ││ │ │ │
│ ┌───────────────────────────────────────────────────────┘│ │ │ │
│ │ ┌─────────────────────────────────────────┘ │ │ │
│ │ │ ┌──────────────────────────────┘ │ │
│ │ │ │ ┌─────────────────┘ │
│ ▼ ▼ ▼ ▼ │
│ ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌─────────────────┐ │
│ │verification│ │code-review│ │security- │ │ adr │ │
│ │ -loop │ │ │ │ review │ │ │ │
│ └───────────┘ └───────────┘ └───────────┘ └─────────────────┘ │
│ (default) (optional) │
└───────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────┐
│ e2e-testing │
│ (validation) │
└────────┬────────┘
│
▼
┌──────────────────────────┐
│ continuous-learning │
│ (extract session patterns)│
└──────────────────────────┘
| Stage | Skill | Purpose |
|---|---|---|
| Ideation | brainstorm | Refine rough ideas through Socratic questioning |
| Requirements | user-story | Generate hierarchical user stories with acceptance criteria |
| Planning | create-plan | Create detailed, phased implementation plans |
| Iteration | iterate-plan | Update plans based on feedback |
| Execution | implement-plan | Orchestrate full plan execution |
| Phase Work | implement-phase | Execute single phase with quality gates |
| Quality | code-review | Verify code quality, patterns, ADR compliance |
| Adversarial Quality | adversarial-reviewer | Subagent-based hostile review (Saboteur, New Hire, Security Auditor) to break self-review blind spots |
| Comprehensive Audit | codebase-audit | Long-running full-codebase audit — partitions the repo, delegates to adversarial-reviewer per partition, synthesizes a written remediation report |
| Security | security-review | OWASP-aligned security audit (optional step) |
| Verification | verification-loop | 6-phase verification: build, type, lint, test, security, diff |
| Metrics Gate | code-quality-audit | Coverage, complexity, module size, deps, mutation — gate or on-demand |
| Decisions | adr | Document architectural decisions |
| Testing | e2e-testing | End-to-end validation with Playwright |
| Evaluation | eval-harness | Formal capability/regression testing with metrics |
| Learning | continuous-learning | Extract patterns from sessions for reuse |
Skills are invoked via the Skill tool or /skill-name shorthand.
| Skill | Trigger | Description |
|---|---|---|
| brainstorm | /brainstorm, "explore this idea" | Interactive idea refinement using Socratic questioning, written to docs/brainstorms/ for create-plan or tt-create-plan |
| user-story | /user-story, "create user stories" | Generate hierarchical user stories (epics/features/tasks) with Given/When/Then acceptance criteria |
| create-plan | /create-plan, "plan the implementation" | Creates detailed implementation plans through research |
| iterate-plan | "update the plan", "iterate on this plan" | Updates existing plans based on feedback |
| implement-plan | /implement-plan, "implement the plan" | Orchestrates execution of complete plans (subagent mode) |
| implement-phase | Called by implement-plan | Executes single phase with all quality gates |
| tt-create-plan | /tt-create-plan, "plan this in tasktracker" | TaskTracker-native planning: requirements with acceptance criteria and phase tasks from templates instead of a docs/plans/*.md file |
| tt-implement-plan | /tt-implement-plan, "execute the tasktracker plan" | Runs a TaskTracker plan phase by phase, delegating each phase to tt-implement-phase, with active-task time tracking and insight logging |
| tt-workflow-run | /tt-workflow-run, "drive the backlog to done" | Autonomous gated run over a TaskTracker backlog: next ready slice → tt-implement-phase → drift and defect gates → measured-time projection, until the backlog drains |
| tt-workflow-build | /tt-workflow-build, "parallel build (tasktracker)" | Parallel build of a TaskTracker project, on the Workflow tool when it is enabled and on parallel subagents otherwise, driven to done |
| tt-create-build-loop | /tt-create-build-loop, "set up an autonomous build loop" | Writes prompts/autonomous-build-loop.md, the prompt a /loop re-reads every iteration to plan, implement and verify TaskTracker phases unattended under a zero-error gate, with a human-only queue and a per-phase cost ledger. Detects the repo, stack, CI and TaskTracker phases, asks only what it can't, creates missing queue/ledger phases, optionally installs the bundled token-usage tooling, and installs a clean-worktree gate runner |
| workflow-guide | /workflow-guide, "which workflow should I use" | Routes work to a lane: file-based or TaskTracker pipeline, autonomous run, unattended loop, parallel build or audit, or issue-to-merge |
| Skill | Trigger | Description |
|---|---|---|
| code-review | /devflow:code-review (bare /code-review is Claude Code's built-in review), Step 4 of implement-phase and tt-implement-phase | Systematic review: SRP, patterns, ADR compliance |
| adversarial-reviewer | /adversarial-reviewer, "adversarial review", "critical review", "audit this repo" | Spawns three hostile-persona subagents (Saboteur, New Hire, Security Auditor) in parallel; each must find ≥1 issue; cross-persona findings get severity-promoted. Default mode reviews a diff; --codebase [path] reviews a whole repo/subtree with strategic per-persona deep-dives |
| grumpy-reviewer | /grumpy-reviewer, "structural review", "is this well factored" | One isolated-subagent reviewer that judges only maintainability (separation of concerns, helper extraction, small files, the rule of 7) and never learns how the code was produced |
| codebase-audit | /codebase-audit, "comprehensive codebase review", "thorough audit", "code due diligence" | Long-running full-coverage audit. Partitions the repo, delegates to /adversarial-reviewer --codebase per partition, synthesizes systemic findings, produces written remediation report. Resumable. Pairs with code-quality-audit for qualitative + quantitative picture |
| tt-workflow-audit | /tt-workflow-audit, "parallel audit (tasktracker)" | Read-only parallel audit of a TaskTracker project's repo, backlog or architecture: a ranked risk register, with fix tasks written back by the parent on approval. Resumable |
| adr | /adr, "document decision" | Creates Architecture Decision Records |
| e2e-testing | /e2e-testing, "test my webapp" | E2E testing with Playwright MCP |
| security-review | /devflow:security-review (bare /security-review is the built-in), auth/input code | 10-category OWASP-aligned security audit |
| verification-loop | /verification-loop, "verify implementation" | 6-phase verification: build, type, lint, test, security, diff |
| code-quality-audit | /code-quality-audit, "audit code quality", "run mutation testing" | Coverage + complexity + module size + dependency cycles + mutation score. Gate or on-demand modes |
| eval-harness | /eval-harness, "run evals" | Formal evaluation framework with pass@k metrics |
| Skill | Trigger | Description |
|---|---|---|
| codebase-research | "how does X work" | Parallel codebase research with sub-agents |
| context-saver | /context-saver, "save context" | Preserves session state for continuation |
| prompt-generator | /prompt, "generate prompt" | Creates implementation prompts for phases |
| Skill | Trigger | Description |
|---|---|---|
| continuous-learning | "save what we learned", /continuous-learning | Promotes reusable procedures from a session into learned skills at ~/.claude/skills/learned-<slug>/ (on demand; one-liners go to auto-memory) |
| strategic-compact | PreToolUse hook | Suggests /compact at logical boundaries, not arbitrary thresholds |
| skill-visualizer | /skill-visualizer, "visualize skills" | Generate interactive HTML visualizations of skills and codebase |
| Skill | Trigger | Description |
|---|---|---|
| agent-creator | "create agent", "build agent" | Creates composable AI agent systems in NestJS |
| design-language | "design my own design language", "build my design system", "I want my own look not the Claude default" | Guided design-brief → living-styleguide compiler. Reaction-first elicitation (web research + real references + live archetypes rendered in your own tokens → you react → targeted refinement) with a per-dimension 1–5 "safeness" gradient (conventional→experimental) across the entire system (color, type, spacing, shape, elevation, motion, imagery, components, patterns, voice). Resumable multi-phase flow; emits a self-contained, portable ./design-system/ (interactive dashboard + css/tokens.css single-source-of-truth + W3C design-tokens.json + DESIGN_LANGUAGE.md contract with an explicit anti-Claude reference + pre-ship checklist + a default-vs-yours compare.html) that future sessions read and build from. Different from frontend-design (which styles one UI in the moment). |
| Skill | Trigger | Description |
|---|---|---|
| video-explainer | /video-explainer <url-or-path>, "make an HTML explainer for this video", "turn this talk into visual notes" | Turns a video (YouTube, any yt-dlp URL, or a local file) into one self-contained HTML explainer page: headline + TL;DR, key takeaways, a section per part of the video, and diagrams built in pure HTML + CSS (17 components: flows, timelines, bar/line/dumbbell charts, threshold scales, comparisons, cycles, layers…). Watches the video via the watch plugin (frames + transcript), adds screenshots only when the video's own image is the information, renders the page headless at desktop and phone width to check its own layout, and links every claim to its timestamp. Requires the watch plugin: see the Video Explainer Guide for install and usage. |
| Skill | Trigger | Description |
|---|---|---|
| ship-issue | /ship-issue <issue-number-or-url> | One-command GitHub issue → merged PR pipeline across nine stages (preflight, plan, implement, review, ci, cloud_review, deploy, e2e, logs) with exactly two human gates — plan approval and merge confirmation. Model-tiered: Fable 5 plans, orchestrates, and runs the merge-gate review; Opus 4.8 implements (TDD); Sonnet 4.6 runs staging E2E and log checks. File-based run state gives lossless crash-resume; per-stage time tracking (work / gate-wait / crash-gap, with a per-model-tier rollup) is embedded in the Gate 2 merge brief. Pair with the single-file dashboard.py for a live view. |
Overview page: open
skills/ship-issue/pipeline.htmlin a browser for a one-page tour — the skill, its five agents, and the full stage-flow diagram with model-tier colour-coding (self-contained, no dependencies).
Agents are specialized subagents launched with the Agent tool. When the collection is installed as a plugin they are named devflow:<agent>.
| Agent | Purpose |
|---|---|
| implementer | sonnet, medium effort: writes code and tests for one briefed unit of work; used by tt-implement-phase for implementation and fix rounds |
| mechanic | haiku, low effort: runs build/type/lint/test checks and verification-loop, report-only, never edits |
| reviewer | opus, high effort (callers pass fable for security reviews): runs code-review / security-review on code it did not write |
| codebase-analyzer | Traces implementation with file:line references |
| codebase-locator | Finds files by topic/feature ("Super Grep/Glob") |
| codebase-pattern-finder | Finds concrete code examples and patterns |
| docs-analyzer | Extracts insights from docs, ADRs, design docs |
| docs-locator | Finds documentation and research notes |
| web-search-researcher | Web research for APIs, libraries, troubleshooting |
| browser-verification-agent | UI testing via Playwright MCP with screenshot evidence |
| design-researcher | claude-sonnet-4-6 — per-dimension inspiration research for the design-language skill (WebSearch → Playwright screenshots → cached manifest), steering away from the default Claude look |
Each agent pins its model in frontmatter — the tier is part of the contract, never switched mid-task (prompt caches are model-scoped; ADR-0007). A fix cycle is always a fresh task on the same tier, never a resumed task on a different model.
| Agent | Model | Purpose |
|---|---|---|
| issue-planner | claude-fable-5 (Fable 5) | Turns a GitHub issue + codebase into the plan presented at Gate 1. Outcome-prompted (ADR-0008). |
| merge-gate-reviewer | claude-fable-5 (Fable 5) | Last-line diff review at the merge gate; verdict contract APPROVE / FIX (itemized blockers). Outcome-prompted. |
| tdd-implementer | claude-opus-4-8 (Opus 4.8) | Tests-first implementation, UI components, API routes; receives reviewer/CI/E2E blockers verbatim on fix cycles. |
| staging-e2e-verifier | claude-sonnet-4-6 (Sonnet 4.6) | Runs the plan's E2E scenarios against the live staging URL via Playwright MCP; PASS/FAIL/FLAKY/BLOCKED with screenshot evidence. |
| staging-log-verifier | claude-sonnet-4-6 (Sonnet 4.6) | Scans staging service logs over the deploy window; CLEAN vs ERRORS_FOUND with cited lines. |
This repository is distributed exclusively as a Claude Code plugin named devflow, published through a marketplace named mhylle. Inside Claude Code:
/plugin marketplace add mhylle/claude-skills-collection
/plugin install devflow@mhylle
Then /reload-plugins (or restart) if the install summary asks for it.
Plugin skills are namespaced, so every skill is invoked as /devflow:<skill>:
/devflow:brainstorm
/devflow:create-plan
/devflow:implement-plan
Nothing is copied into ~/.claude/ — the plugin lives in Claude Code's plugin cache, carries a version, and updates in place:
/plugin marketplace update mhylle
To remove it: /plugin uninstall devflow.
See Plugin Distribution for the manifest layout, versioning, publishing, and local development.
Earlier versions shipped an install.sh that copied skills, agents, and hooks into ~/.claude/. It is gone (ADR-0011).
Those copies do not disappear on their own, and plugin skills do not override same-named personal skills — so until you remove them you will have both /brainstorm and /devflow:brainstorm pointing at two copies that drift apart, with Claude free to auto-invoke either. Remove the copies once, after installing the plugin:
# from a checkout of this repo
for s in $(ls skills); do rm -rf "$HOME/.claude/skills/$s"; done
for a in agents/*.md; do rm -f "$HOME/.claude/agents/$(basename "$a")"; done
~/.claude/hooks.json is your own user configuration, not a copy of this repo's file. The old script overwrote it (leaving hooks.json.backup); the plugin no longer touches it. Review it by hand and delete only the entries you recognise from this collection.
Skills, agents, and these hooks — all discovered automatically from the plugin's default component locations (skills/, agents/, hooks/hooks.json).
Hooks (automatic behaviors):
/devflow:strategic-compact is invoked on demand rather than by a hook — see ADR-0011.
| Hook Type | Name | Trigger | Purpose |
|---|---|---|---|
| PreToolUse | tmux-dev-block | npm run dev etc. | Block dev servers outside tmux |
| PreToolUse | tmux-reminder | Long-running commands | Suggest tmux for session persistence |
| PreToolUse | git-push-review | git push | Reminder to review before push |
| PreToolUse | doc-file-warn | .md/.txt creation | Warn about docs outside docs/ structure |
| PostToolUse | pr-url-logger | gh pr create | Log PR URL and review command |
| PostToolUse | prettier-format | JS/TS file edits | Auto-format with Prettier |
| PostToolUse | typescript-check | .ts/.tsx edits | Run tsc --noEmit and show errors |
| PostToolUse | console-log-warn | JS/TS file edits | Wa
hooks/register.tsx 695 lines1// devflow HUD (part of the devflow plugin): a progress band and a /hud pane for the devflow TaskTracker skills, and the functions
2// the skills lean on: the orchestrator guard, the in-flight watch, the time-tracking heartbeat and
3// pause, the booked time of the phase, and the test-run alarms. See docs/guides/devflow-hud.md.
4
5import { atom, read, update } from 'claude-code'
6import type { EngineInterface, Register, ToolCallResult } from 'claude-code'
7
8import type { HudAgent, HudCheck, HudGuard, HudPhase, HudRequirement, HudTask, HudTime } from '../types'
9import {
10 formatDuration,
11 isGuardExempt,
12 linksTask,
13 parseBuildSummary,
14 parseCriteria,
15 parseRequirements,
16 parseSlnTestProjects,
17 parseTask,
18 parseTaskList,
19 parseTestRuns,
20 parseTestSummaries,
21 parseTimeSummary,
22 shapeOf,
23} from './parse'
24import { isRunning, PANE } from './state'
25import { band, hasContent, pane, type HudView } from './view'
26
27// Every function that takes `$`, and every state atom, lives in this file: the engine follows `$` and reads
28// `$.state` references only where they are declared in the file that uses them.
29
30// The session state the band and the pane draw from (declared in ../types, PluginState).
31const phaseAtom = atom({ plugin: 'devflow', key: 'phase' } as const, null as HudPhase | null)
32const activeTaskAtom = atom({ plugin: 'devflow', key: 'activeTaskId' } as const, null as string | null)
33const agentsAtom = atom({ plugin: 'devflow', key: 'agents' } as const, [] as HudAgent[])
34const checksAtom = atom({ plugin: 'devflow', key: 'checks' } as const, [] as HudCheck[])
35const guardAtom = atom({ plugin: 'devflow', key: 'guard' } as const, { isEnabled: true, isActive: false, skill: '' } as HudGuard)
36const bandHiddenAtom = atom({ plugin: 'devflow', key: 'isBandHidden' } as const, false)
37const tickAtom = atom({ plugin: 'devflow', key: 'tick' } as const, 0)
38
39/** How often the background tick polls the agents and runs a wanted refresh. */
40const TICK_MS = 2_000
41
42/** TaskTracker closes a time segment after ~5 minutes without a call; heartbeat inside that. */
43const HEARTBEAT_MS = 240_000
44
45/** TaskTracker tools after which the view is read again. */
46const WRITES = new Set([
47 'updateTaskStatus',
48 'batchUpdateStatus',
49 'createTask',
50 'batchCreateTasks',
51 'updateTask',
52 'batchUpdateTasks',
53 'archiveTask',
54 'deleteTask',
55 'reparentTask',
56 'completeWithCaveat',
57 'addAcceptanceCriterion',
58 'updateAcceptanceCriterion',
59 'deleteAcceptanceCriterion',
60])
61
62/** Writes that change which requirements a phase links (the cached links are read again). */
63const LINK_WRITES = new Set(['linkRequirementToTask', 'unlinkRequirementFromTask'])
64
65const PREFIX = 'mcp__tasktracker__tasktracker_'
66
67const USAGE = '/hud opens the pane. /hud refresh | guard on|off | band on|off | project <uuid>'
68
69/** Module state; a reload starts it over (what is drawn lives in $.state). */
70const hud = {
71 orchestrator: /implement-plan|implement-phase|tt-workflow-run/,
72 projectId: '',
73 /** After an automatic pause: no TaskTracker call of ours until the next turn, or it would book the wait. */
74 isQuiet: false,
75 isRefreshWanted: false,
76 isForcedRefresh: false,
77 isUserRefresh: false,
78 isTicking: false,
79 lastHeartbeat: 0,
80 lastRedraw: 0,
81 slnTests: new Map<string, string[]>(),
82 /** Booked ms of completed tasks that aren't active: their time no longer changes, so it is read once. */
83 bookedDone: new Map<string, number>(),
84}
85
86// TaskTracker, through the session's own MCP connection. Every call heartbeats the active task (TaskTracker
87// books time from calls), so none is made during a wait for the person (hud.isQuiet).
88
89/** One TaskTracker tool call; its text blocks joined. Rejects when the server reports an error. */
90async function call($: EngineInterface, tool: string, args: Record<string, unknown>): Promise<string> {
91 const result = await $.mcp.call('tasktracker', `tasktracker_${tool}`, args)
92 const text = result.content.map(block => block.text ?? '').join('\n')
93 if (result.isError) {
94 throw new Error(`${tool}: ${text.slice(0, 200)}`)
95 }
96
97 return text
98}
99
100/** The requirements linked to a phase, cached in $.store for an hour (links rarely change). */
101async function linkedRequirements($: EngineInterface, phaseId: string, isForced: boolean): Promise<{ id: string; slug: string }[]> {
102 const key = `links:${phaseId}`
103 const cached = (await $.store.get(key)) as { at: number; requirements: { id: string; slug: string }[] } | undefined
104 const now = await $.clock.now()
105 if (cached && !isForced && now - cached.at < 3_600_000) {
106 return cached.requirements
107 }
108
109 const all = parseRequirements(await call($, 'listRequirements', { projectId: hud.projectId, status: 'approved' }))
110 const linked: { id: string; slug: string }[] = []
111 for (const requirement of all) {
112 if (linksTask(await call($, 'listRequirementTaskLinks', { requirementId: requirement.id }), phaseId)) {
113 linked.push(requirement)
114 }
115 }
116
117 await $.store.set(key, { at: now, requirements: linked })
118 return linked
119}
120
121/** The phase of task `taskId` with its sub-tasks and (when the project is known) its requirements' ACs. */
122async function loadPhase($: EngineInterface, taskId: string, isForced: boolean): Promise<HudPhase> {
123 const task = parseTask(await call($, 'getTask', { taskId }))
124 if (task === null) {
125 throw new Error(`getTask ${taskId}: unexpected answer`)
126 }
127
128 let phase: HudTask = task
129 if (task.type !== 'phase') {
130 phase = parseTaskList(await call($, 'getTaskAncestors', { taskId })).find(t => t.type === 'phase') ?? task
131 }
132
133 const subtasks = parseTaskList(await call($, 'getChildTasks', { taskId: phase.id }))
134 const requirements: HudRequirement[] = []
135 if (hud.projectId !== '' && phase.type === 'phase') {
136 for (const requirement of await linkedRequirements($, phase.id, isForced)) {
137 const criteria = parseCriteria(await call($, 'listAcceptanceCriteria', { requirementId: requirement.id }))
138 requirements.push({ ...requirement, criteria })
139 }
140 }
141
142 const time = await bookedTime($, phase, task)
143 return { phase, active: task.id === phase.id ? null : task, subtasks, requirements, time, refreshedAt: await $.clock.now(), isIdle: false }
144}
145
146/** One task's own booked ms (getTimeSummary counts closed segments of that task alone); null when unreadable. */
147async function ownBooked($: EngineInterface, task: HudTask, activeId: string): Promise<number | null> {
148 const isSettled = task.status === 'completed' && task.id !== activeId
149 const cached = hud.bookedDone.get(task.id)
150 if (isSettled && cached !== undefined) {
151 return cached
152 }
153
154 const ms = parseTimeSummary(await call($, 'getTimeSummary', { taskId: task.id }).catch(() => ''))
155 if (isSettled && ms !== null) {
156 hud.bookedDone.set(task.id, ms)
157 }
158
159 return ms
160}
161
162/** The phase's booked time: its own plus every descendant's, since TaskTracker sums neither. */
163async function bookedTime($: EngineInterface, phase: HudTask, active: HudTask): Promise<HudTime | undefined> {
164 if (phase.type !== 'phase') {
165 return undefined
166 }
167
168 const descendants = parseTaskList(await call($, 'getTaskDescendants', { taskId: phase.id }).catch(() => ''))
169 let totalMs = 0
170 let isPartial = false
171 let activeMs: number | null = null
172 for (const task of [phase, ...descendants]) {
173 const ms = await ownBooked($, task, active.id)
174 if (ms === null) {
175 isPartial = true
176 continue
177 }
178
179 totalMs += ms
180 if (task.id === active.id && active.id !== phase.id) {
181 activeMs = ms
182 }
183 }
184
185 return { totalMs, activeMs, isPartial }
186}
187
188function requestRefresh(isForced: boolean, isUser: boolean) {
189 hud.isRefreshWanted = true
190 hud.isForcedRefresh ||= isForced
191 hud.isUserRefresh ||= isUser
192}
193
194async function viewOf($: EngineInterface): Promise<HudView> {
195 return {
196 phase: await read($, phaseAtom),
197 agents: await read($, agentsAtom),
198 checks: await read($, checksAtom),
199 guard: await read($, guardAtom),
200 now: await $.clock.now(),
201 }
202}
203
204/** Reads the phase of the active task (or, on a user's refresh with none active, of the last phase seen). */
205async function refresh($: EngineInterface) {
206 const active = await read($, activeTaskAtom)
207 const shown = await read($, phaseAtom)
208 const target = active ?? (hud.isUserRefresh ? (shown?.phase.id ?? null) : null)
209 const wasQuiet = hud.isQuiet
210 const isForced = hud.isForcedRefresh
211 hud.isRefreshWanted = false
212 hud.isForcedRefresh = false
213 hud.isUserRefresh = false
214 if (target === null) {
215 return
216 }
217
218 try {
219 const phase: HudPhase = { ...(await loadPhase($, target, isForced)), isIdle: active === null }
220 await update($, phaseAtom, () => phase)
221 await $.store.set('lastPhase', phase)
222 } catch (error) {
223 const message = error instanceof Error ? error.message : String(error)
224 await update($, phaseAtom, p => (p === null ? p : { ...p, error: message }))
225 }
226
227 if (wasQuiet) {
228 // A refresh the person asked for during a wait: close the segment its calls opened.
229 await call($, 'pauseActiveTask', {}).catch(() => undefined)
230 }
231}
232
233/** Mirrors $.agent.list() into the state; a toast for each agent that finished. */
234async function pollAgents($: EngineInterface) {
235 const listed = await $.agent.list()
236 const known = await read($, agentsAtom)
237 const now = await $.clock.now()
238 const byId = new Map(known.map(agent => [agent.id, agent]))
239 const finished: HudAgent[] = []
240 let isChanged = false
241 for (const info of listed) {
242 const previous = byId.get(info.id)
243 if (previous === undefined) {
244 byId.set(info.id, {
245 id: info.id,
246 description: info.description,
247 type: info.type,
248 status: info.status,
249 startedAt: now,
250 ...(isRunning(info) ? {} : { endedAt: now }),
251 })
252 isChanged = true
253 } else if (previous.status !== info.status) {
254 const changed: HudAgent = { ...previous, status: info.status }
255 if (isRunning(previous) && !isRunning(info)) {
256 changed.endedAt = now
257 finished.push(changed)
258 }
259
260 byId.set(info.id, changed)
261 isChanged = true
262 }
263 }
264
265 for (const previous of known) {
266 if (isRunning(previous) && !listed.some(info => info.id === previous.id)) {
267 const ended: HudAgent = { ...previous, status: 'completed', endedAt: now }
268 byId.set(previous.id, ended)
269 finished.push(ended)
270 isChanged = true
271 }
272 }
273
274 if (isChanged) {
275 await update($, agentsAtom, () => [...byId.values()].sort((a, b) => a.startedAt - b.startedAt).slice(-30))
276 }
277
278 for (const agent of finished) {
279 const mark = agent.status === 'completed' ? '✔' : '✗'
280 $.ui.toast(`${mark} ${agent.type} "${agent.description}" ${agent.status} after ${formatDuration((agent.endedAt ?? now) - agent.startedAt)}`)
281 }
282}
283
284/** The background tick: agents, elapsed-time redraws, wanted refreshes and the heartbeat. */
285async function tick($: EngineInterface) {
286 if (hud.isTicking) {
287 return
288 }
289
290 hud.isTicking = true
291 try {
292 await pollAgents($)
293 const now = await $.clock.now()
294 const isAnyRunning = (await read($, agentsAtom)).some(isRunning)
295 if (isAnyRunning && now - hud.lastRedraw >= 30_000) {
296 hud.lastRedraw = now
297 await update($, tickAtom, n => n + 1)
298 }
299
300 if (hud.isRefreshWanted && (!hud.isQuiet || hud.isUserRefresh)) {
301 await refresh($)
302 }
303
304 const active = await read($, activeTaskAtom)
305 if (!hud.isQuiet && isAnyRunning && active !== null && now - hud.lastHeartbeat >= HEARTBEAT_MS) {
306 // Agents work while the main thread waits for them: keep the active task's segment open.
307 hud.lastHeartbeat = now
308 await call($, 'getCurrentTimer', { taskId: active }).catch(() => undefined)
309 }
310 } finally {
311 hud.isTicking = false
312 }
313}
314
315/** Pauses the active task's timer before a wait for the person, unless agents still work. */
316async function pauseIfIdle($: EngineInterface) {
317 if (hud.isQuiet || (await read($, activeTaskAtom)) === null) {
318 return
319 }
320
321 if ((await $.agent.list()).some(isRunning)) {
322 return
323 }
324
325 await call($, 'pauseActiveTask', {}).catch(() => undefined)
326 hud.isQuiet = true
327}
328
329async function agentLabel($: EngineInterface, agentId: string | undefined): Promise<string> {
330 if (agentId === undefined) return 'main'
331 const agent = (await read($, agentsAtom)).find(a => a.id === agentId)
332 return agent === undefined ? 'agent' : `${agent.type} "${agent.description}"`
333}
334
335async function testProjectsOf($: EngineInterface, sln: string): Promise<string[]> {
336 let projects = hud.slnTests.get(sln)
337 if (projects === undefined) {
338 projects = parseSlnTestProjects(await $.fs.read(sln))
339 hud.slnTests.set(sln, projects)
340 }
341
342 return projects
343}
344
345/** Reads build, test and verify results from a shell command's output; notes for the model when a project did not run. */
346async function readChecks($: EngineInterface, command: string, agentId: string | undefined, ran: ToolCallResult): Promise<ToolCallResult> {
347 if (ran.deny !== undefined) {
348 return ran
349 }
350
351 const text = typeof ran.text === 'string' ? ran.text : ''
352 const shape = shapeOf(command)
353 const summaries = parseTestSummaries(text)
354 const build = parseBuildSummary(text)
355 if (summaries.length === 0 && build === null && !shape.isVerify) {
356 return ran
357 }
358
359 const now = await $.clock.now()
360 const loop = await agentLabel($, agentId)
361 const checks: HudCheck[] = []
362 const notes: string[] = []
363 if (build !== null && summaries.length === 0 && !shape.isVerify) {
364 checks.push({
365 label: 'build',
366 isOk: build.errors === 0 && build.warnings === 0,
367 failed: 0,
368 passed: 0,
369 warnings: build.warnings,
370 errors: build.errors,
371 missing: [],
372 projects: 0,
373 at: now,
374 loop,
375 })
376 }
377
378 if (summaries.length > 0) {
379 let missing: string[] = []
380 const started = parseTestRuns(text)
381 if (shape.isDotnetTest && shape.sln !== null && (!shape.isPartial || started.length > 0)) {
382 const expected = await testProjectsOf($, shape.sln).catch(() => [] as string[])
383 const seen = new Set([...summaries.map(s => s.project), ...started])
384 missing = expected.filter(project => !seen.has(project))
385 }
386
387 const failed = summaries.reduce((n, s) => n + s.failed, 0)
388 checks.push({
389 label: 'tests',
390 isOk: failed === 0 && missing.length === 0,
391 failed,
392 passed: summaries.reduce((n, s) => n + s.passed, 0),
393 missing,
394 projects: summaries.length,
395 at: now,
396 loop,
397 })
398 if (missing.length > 0) {
399 notes.push(
400 `devflow-hud: ${missing.length} test project(s) of ${shape.sln} reported no result: ${missing.join(', ')}. ` +
401 'dotnet test can skip a project (for example while a test project it references fails): run each one separately before counting the totals.',
402 )
403 }
404 }
405
406 if (shape.isVerify) {
407 const summary = text.split('\n').reverse().find(line => /\b(passed|failed|FAIL)\b/i.test(line))?.trim()
408 checks.push({ label: 'verify', isOk: ran.isError !== true, failed: 0, passed: 0, missing: [], projects: 0, at: now, loop, summary })
409 }
410
411 await update($, checksAtom, list => [...list, ...checks].slice(-20))
412 const bad = checks.find(check => !check.isOk)
413 if (bad !== undefined) {
414 const detail = bad.missing.length > 0 ? `not run: ${bad.missing.join(', ')}` : bad.label === 'tests' ? `${bad.failed} failed` : bad.label
415 $.ui.toast(`✗ ${bad.label} (${loop}): ${detail}`)
416 }
417
418 return notes.length === 0 ? ran : { ...ran, context: [...(ran.context ?? []), ...notes] }
419}
420
421/** The guard's refusal of a main-thread write while an orchestrator skill leads, or undefined. */
422async function guardRefusal($: EngineInterface, path: string, agentId: string | undefined): Promise<string | undefined> {
423 if (agentId !== undefined || isGuardExempt(path)) {
424 return undefined
425 }
426
427 const guard = await read($, guardAtom)
428 if (!guard.isEnabled || !guard.isActive) {
429 return undefined
430 }
431
432 return (
433 `devflow-hud orchestrator guard: ${guard.skill} leads this session, and a plan orchestrator never writes code itself. ` +
434 'Dispatch this change to the implementer role agent (devflow:implementer), as /tt-implement-phase describes; do not work around this with shell commands. ' +
435 'Only the user can switch the guard off, with /hud guard off.'
436 )
437}
438
439/** Notifies when a task goes blocked or the shown phase completes. */
440async function notifyStatus($: EngineInterface, taskId: string, status: unknown) {
441 const phase = await read($, phaseAtom)
442 const task = [phase?.phase, phase?.active, ...(phase?.subtasks ?? [])].find(t => t?.id === taskId)
443 const title = task?.title ?? taskId
444 if (status === 'blocked') {
445 await $.ui.notify(`Blocked: ${title}`, { title: 'devflow' })
446 } else if (status === 'completed' && phase?.phase.id === taskId) {
447 await $.ui.notify(`Phase completed: ${title}`, { title: 'devflow' })
448 }
449}
450
451/** Reminder for the model of the agents still running, or undefined when none. */
452async function runningNote($: EngineInterface, lead: string): Promise<string | undefined> {
453 const running = (await $.agent.list()).filter(isRunning)
454 if (running.length === 0) {
455 return undefined
456 }
457
458 const names = running.map(agent => `${agent.type} "${agent.description}"`).join(', ')
459 return `devflow-hud: ${lead} ${running.length} agent(s) still run: ${names}. Their reports arrive in this session as messages when they finish; do not report on their work, predict it, or start work that depends on it before then.`
460}
461
462async function openPane($: EngineInterface) {
463 await $.ui.open({ id: PANE, title: 'devflow HUD' })
464}
465
466async function setGuardEnabled($: EngineInterface, isEnabled: boolean) {
467 await update($, guardAtom, guard => ({ ...guard, isEnabled }))
468 await $.store.set('guardEnabled', isEnabled)
469}
470
471async function toggleGuard($: EngineInterface) {
472 await setGuardEnabled($, !(await read($, guardAtom)).isEnabled)
473}
474
475async function toggleBand($: EngineInterface) {
476 await update($, bandHiddenAtom, isHidden => !isHidden)
477}
478
479/** Loads what the HUD keeps across sessions and starts the background tick. */
480async function start($: EngineInterface) {
481 await $.command.register({
482 name: 'hud',
483 description: 'devflow HUD: the TaskTracker phase, agents and checks',
484 argumentHint: '[refresh|guard on|off|band on|off|project <id>]',
485 })
486 const storedProject = await $.store.get('projectId')
487 if (hud.projectId === '' && typeof storedProject === 'string') {
488 hud.projectId = storedProject
489 }
490
491 const isGuardEnabled = await $.store.get('guardEnabled')
492 if (typeof isGuardEnabled === 'boolean') {
493 await update($, guardAtom, guard => ({ ...guard, isEnabled: isGuardEnabled }))
494 }
495
496 if ((await read($, phaseAtom)) === null) {
497 const last = (await $.store.get('lastPhase')) as HudPhase | undefined | null
498 if (last !== undefined && last !== null) {
499 await update($, phaseAtom, () => ({ ...last, isIdle: true }))
500 }
501 }
502
503 $.clock.every(TICK_MS, () => {
504 void tick($)
505 })
506}
507
508/** Follows a TaskTracker call: the project, the active task, refreshes after writes, status notifications. */
509async function followTaskTracker($: EngineInterface, tool: string, args: Record<string, unknown>, ran: ToolCallResult): Promise<ToolCallResult> {
510 if (ran.deny !== undefined || ran.isError === true) {
511 return ran
512 }
513
514 const name = tool.slice(PREFIX.length)
515 hud.isQuiet = name === 'pauseActiveTask'
516 if (typeof args.projectId === 'string' && /^[0-9a-f-]{36}$/.test(args.projectId) && args.projectId !== hud.projectId) {
517 hud.projectId = args.projectId
518 await $.store.set('projectId', hud.projectId)
519 }
520
521 if (name === 'setActiveTask' && typeof args.taskId === 'string') {
522 const taskId = args.taskId
523 await update($, activeTaskAtom, () => taskId)
524 requestRefresh(false, false)
525 } else if (name === 'clearActiveTask') {
526 await update($, activeTaskAtom, () => null)
527 await update($, phaseAtom, p => (p === null ? p : { ...p, isIdle: true }))
528 } else if (WRITES.has(name) || LINK_WRITES.has(name)) {
529 requestRefresh(LINK_WRITES.has(name), false)
530 }
531
532 if (name === 'updateTaskStatus' && typeof args.taskId === 'string') {
533 await notifyStatus($, args.taskId, args.status)
534 }
535
536 return ran
537}
538
539/** Orchestrator mode follows the main thread's skills; a fork that returns with agents still running is said so. */
540async function followSkill($: EngineInterface, skill: string, ran: ToolCallResult, before: Set<string>): Promise<ToolCallResult> {
541 if (ran.deny !== undefined) {
542 return ran
543 }
544
545 const started = (await $.agent.list()).filter(agent => isRunning(agent) && !before.has(agent.id))
546 if (started.length === 0) {
547 return ran
548 }
549
550 const names = started.map(agent => `${agent.type} "${agent.description}"`).join(', ')
551 return {
552 ...ran,
553 context: [
554 ...(ran.context ?? []),
555 `devflow-hud: the skill ${skill} returned while ${started.length} agent(s) it dispatched still run: ${names}. ` +
556 'Their reports arrive in this session as messages when they finish. Do not report on their work, or start work that depends on it, before then.',
557 ],
558 }
559}
560
561async function noteSkill($: EngineInterface, skill: string): Promise<Set<string>> {
562 if (hud.orchestrator.test(skill)) {
563 await update($, guardAtom, guard => ({ ...guard, isActive: true, skill }))
564 } else if (!/(^|:)(tt-|adr$|continuous-learning$)/.test(skill)) {
565 await update($, guardAtom, guard => ({ ...guard, isActive: false, skill: '' }))
566 }
567
568 return new Set((await $.agent.list()).filter(isRunning).map(agent => agent.id))
569}
570
571async function runCommand($: EngineInterface, args: string): Promise<{ text: string }> {
572 const [verb = '', arg = ''] = args.trim().split(/\s+/)
573 switch (verb) {
574 case '':
575 await openPane($)
576 requestRefresh(false, true)
577 return { text: 'devflow HUD pane opened.' }
578 case 'refresh':
579 requestRefresh(true, true)
580 return { text: 'devflow HUD: reading TaskTracker again.' }
581 case 'guard':
582 if (arg !== 'on' && arg !== 'off') return { text: USAGE }
583 await setGuardEnabled($, arg === 'on')
584 return { text: `devflow HUD: orchestrator guard ${arg}.` }
585 case 'band':
586 if (arg !== 'on' && arg !== 'off') return { text: USAGE }
587 await update($, bandHiddenAtom, () => arg === 'off')
588 return { text: `devflow HUD: band ${arg === 'on' ? 'shown' : 'hidden'}.` }
589 case 'project':
590 if (!/^[0-9a-f-]{36}$/.test(arg)) return { text: USAGE }
591 hud.projectId = arg
592 await $.store.set('projectId', hud.projectId)
593 requestRefresh(true, true)
594 return { text: `devflow HUD: project ${arg}.` }
595 default:
596 return { text: USAGE }
597 }
598}
599
600export const register: Register = (on, options) => {
601 hud.orchestrator = new RegExp(String(options.orchestratorSkills || 'implement-plan|implement-phase|tt-workflow-run'))
602 hud.projectId = String(options.projectId ?? '')
603
604 on('session.start', async ($, e, next) => {
605 await start($)
606 return next(e)
607 })
608
609 on('tool.call', async ($, e, next) => {
610 const tool = String(e.tool)
611 if (!tool.startsWith(PREFIX)) {
612 return next(e)
613 }
614
615 return followTaskTracker($, tool, e as unknown as Record<string, unknown>, await next(e))
616 }).catch(($, e, next) => next(e))
617
618 on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
619 if (e.agentId !== undefined) {
620 return next(e)
621 }
622
623 const before = await noteSkill($, e.skill)
624 return followSkill($, e.skill, await next(e), before)
625 }).catch(($, e, next) => next(e))
626
627 // The orchestrator guard: main-thread file writes are refused while an orchestrator skill leads.
628 on('tool.call', { tool: 'Write' }, async ($, e, next) => {
629 const deny = await guardRefusal($, e.file_path, e.agentId)
630 return deny === undefined ? next(e) : { deny }
631 }).catch(($, e, next) => next(e))
632
633 on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
634 const deny = await guardRefusal($, e.file_path, e.agentId)
635 return deny === undefined ? next(e) : { deny }
636 }).catch(($, e, next) => next(e))
637
638 on('tool.call', { tool: 'NotebookEdit' }, async ($, e, next) => {
639 const deny = await guardRefusal($, e.notebook_path, e.agentId)
640 return deny === undefined ? next(e) : { deny }
641 }).catch(($, e, next) => next(e))
642
643 // A question to the person is a wait: pause the active task's timer first.
644 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
645 if (e.agentId === undefined) {
646 await pauseIfIdle($)
647 }
648
649 return next(e)
650 }).catch(($, e, next) => next(e))
651
652 // Check alarms: build, test and verify results in any loop's shell output.
653 on('tool.call', { tool: 'Bash' }, async ($, e, next) => readChecks($, e.command, e.agentId, await next(e))).catch(($, e, next) => next(e))
654 on('tool.call', { tool: 'PowerShell' }, async ($, e, next) => readChecks($, e.command, e.agentId, await next(e))).catch(($, e, next) => next(e))
655
656 // The end of a main-thread turn is a wait for the person, unless agents still work.
657 on('turn.complete', async ($, e, next) => {
658 if (e.agentId === undefined) {
659 await pauseIfIdle($)
660 }
661
662 return next(e)
663 })
664
665 // The person's prompt ends the wait; it reminds the model of agents still running.
666 on('prompt.submit', async ($, e, next) => {
667 hud.isQuiet = false
668 const note = await runningNote($, 'as this prompt arrives,')
669 return next(note === undefined ? e : { ...e, context: [...(e.context ?? []), note] })
670 }).catch(($, e, next) => next(e))
671
672 on('command.run', { command: 'hud' }, async ($, e) => runCommand($, e.args))
673
674 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
675 if (e.props.hasSurvey || (await read($, bandHiddenAtom))) {
676 return next(e)
677 }
678
679 await read($, tickAtom)
680 const view = await viewOf($)
681 return hasContent(view) ? band($.ui.resolve(e), view, e.props.bodyColumns) : next(e)
682 })
683
684 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
685 await read($, tickAtom)
686 const actions = {
687 refresh: () => requestRefresh(true, true),
688 toggleGuard: () => void toggleGuard($),
689 toggleBand: () => void toggleBand($),
690 }
691
692 return pane($.ui.resolve(e), await viewOf($), actions, await read($, bandHiddenAtom))
693 })
694}
695hooks/parse.ts 162 lines1// Pure parsers: TaskTracker MCP texts, dotnet test/build output, .sln files and shell commands.
2// No `$` here, so every function is unit-tested in parse.test.ts.
3
4import type { HudCriterion, HudTask } from '../types'
5
6const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
7
8/** Capture group `i` of a match; '' when it did not take part. */
9function group(m: RegExpMatchArray, i: number): string {
10 return m[i] ?? ''
11}
12
13/** `Task "<title>" (id <uuid>) v<n> [<type>/<status>/<priority>]`, the head of getTask's answer. */
14export function parseTask(text: string): HudTask | null {
15 const m = new RegExp(`^Task "(.*)" \\(id (${UUID})\\) v\\d+ \\[([a-z_]+)/([a-z_]+)`, 'm').exec(text)
16 return m ? { title: group(m, 1), id: group(m, 2), type: group(m, 3), status: group(m, 4) } : null
17}
18
19/** The `- [<type>/<status>] <title> (id <uuid>)` lines of getChildTasks and getTaskAncestors. */
20export function parseTaskList(text: string): HudTask[] {
21 const line = new RegExp(`^\\s*-\\s+\\[([a-z_]+)/([a-z_]+)\\]\\s+(.*?)\\s+\\(id (${UUID})\\)\\s*$`, 'gm')
22 return [...text.matchAll(line)].map(m => ({ type: group(m, 1), status: group(m, 2), title: group(m, 3), id: group(m, 4) }))
23}
24
25/** The `- [<status>/<priority>] <slug>: <title> (id <uuid>)` lines of listRequirements. */
26export function parseRequirements(text: string): { id: string; slug: string }[] {
27 const line = new RegExp(`^\\s*-\\s+\\[[a-z_]+/[a-z_]+\\]\\s+([^:\\s]+):.*\\(id (${UUID})\\)\\s*$`, 'gm')
28 return [...text.matchAll(line)].map(m => ({ slug: group(m, 1), id: group(m, 2) }))
29}
30
31/** The `- [x] (<n>) <text> (id <uuid>)` lines of listAcceptanceCriteria; any mark but a space is satisfied. */
32export function parseCriteria(text: string): HudCriterion[] {
33 const line = new RegExp(`^\\s*-\\s+\\[(.)\\]\\s+\\(\\d+\\)\\s+(.*?)\\s+\\(id ${UUID}\\)\\s*$`, 'gm')
34 return [...text.matchAll(line)].map(m => ({ isSatisfied: group(m, 1) !== ' ', text: group(m, 2) }))
35}
36
37const UNIT_MS: Record<string, number> = { h: 3_600_000, m: 60_000, s: 1_000 }
38
39/**
40 * Milliseconds from getTimeSummary's `<duration> measured across <n> completed segment(s)`, where the duration
41 * reads like `36 min`, `2h 32m` or `24s`; null for any other answer. Only closed segments are counted.
42 */
43export function parseTimeSummary(text: string): number | null {
44 const m = /^(.*?)\bmeasured across\b/m.exec(text)
45 if (!m) return null
46 let ms = 0
47 let isFound = false
48 for (const t of group(m, 1).matchAll(/(\d+(?:\.\d+)?)\s*(h(?:ours?|rs?)?|m(?:in(?:utes?|s)?)?|s(?:ec(?:onds?|s)?)?)\b/g)) {
49 ms += Number(group(t, 1)) * (UNIT_MS[group(t, 2).charAt(0)] ?? 0)
50 isFound = true
51 }
52 return isFound ? Math.round(ms) : null
53}
54
55/** Whether listRequirementTaskLinks' answer links the requirement to task `taskId`. */
56export function linksTask(text: string, taskId: string): boolean {
57 return new RegExp(`\\btask ${taskId}\\b`).test(text)
58}
59
60export type TestSummary = { project: string; failed: number; passed: number; skipped: number }
61
62/** dotnet test's `Passed!/Failed! - Failed: n, Passed: n, Skipped: n, Total: n, Duration: … - X.dll` lines, last per project. */
63export function parseTestSummaries(text: string): TestSummary[] {
64 const line = /^[^\S\n]*(?:\d+[:-])?\s*(?:Passed!|Failed!)\s+-\s+Failed:\s+(\d+),\s+Passed:\s+(\d+),\s+Skipped:\s+(\d+),\s+Total:\s+\d+,.*?-\s+([^\s\\/]+?)\.dll\b/gm
65 const byProject = new Map<string, TestSummary>()
66 for (const m of text.matchAll(line)) {
67 byProject.set(group(m, 4), { project: group(m, 4), failed: Number(group(m, 1)), passed: Number(group(m, 2)), skipped: Number(group(m, 3)) })
68 }
69
70 return [...byProject.values()].sort((a, b) => (a.project < b.project ? -1 : a.project > b.project ? 1 : 0))
71}
72
73/** The projects dotnet test started: `Test run for <path>/<X>.dll (…)`. */
74export function parseTestRuns(text: string): string[] {
75 return [...new Set([...text.matchAll(/Test run for .*?[\\/]([^\\/\s]+?)\.dll\b/g)].map(m => group(m, 1)))].sort()
76}
77
78/** MSBuild's closing `n Warning(s)` / `n Error(s)` lines (the last of each). */
79export function parseBuildSummary(text: string): { warnings: number; errors: number } | null {
80 const warnings = [...text.matchAll(/^\s*(\d+) Warning\(s\)\s*$/gm)].at(-1)
81 const errors = [...text.matchAll(/^\s*(\d+) Error\(s\)\s*$/gm)].at(-1)
82 return warnings && errors ? { warnings: Number(group(warnings, 1)), errors: Number(group(errors, 1)) } : null
83}
84
85/** The test projects a .sln lists: projects whose name contains "Test". */
86export function parseSlnTestProjects(sln: string): string[] {
87 const line = /^Project\("\{[^}]+\}"\)\s*=\s*"([^"]+)",\s*"([^"]+\.(?:cs|fs|vb)proj)"/gm
88 return [...sln.matchAll(line)].map(m => group(m, 1)).filter(name => /test/i.test(name)).sort()
89}
90
91/** What a shell command runs, for the check alarms. */
92export type CommandShape = {
93 isDotnetTest: boolean
94 isBuild: boolean
95 isVerify: boolean
96 /** The solution `dotnet test` names, resolved against a leading `cd <dir> &&`; null when none. */
97 sln: string | null
98 /** A filter, a pipe or a redirect: the output may not show every project. */
99 isPartial: boolean
100}
101
102/** Reads a Bash or PowerShell command line. */
103export function shapeOf(command: string): CommandShape {
104 const test = /\bdotnet\s+test\b([^|&;>]*)/.exec(command)
105 const testArgs = test === null ? '' : group(test, 1)
106 let sln: string | null = null
107 const named = /(\S+\.slnx?)\b/.exec(testArgs)
108 if (named) {
109 sln = group(named, 1).replace(/^["']|["']$/g, '')
110 const cd = /^\s*cd\s+(["']?)([^"'&;]+?)\1\s*&&/.exec(command)
111 if (cd && !isAbsolute(sln)) {
112 sln = `${group(cd, 2).replace(/[\\/]+$/, '')}/${sln}`
113 }
114
115 sln = fromGitBash(sln)
116 }
117
118 return {
119 isDotnetTest: test !== null,
120 isBuild: /\bdotnet\s+build\b/.test(command),
121 isVerify: /verify\.ps1\b/.test(command),
122 sln,
123 isPartial: test !== null && (/--filter\b/.test(testArgs) || /[|>]/.test(command.slice(test.index))),
124 }
125}
126
127function isAbsolute(path: string): boolean {
128 return /^([a-zA-Z]:)?[\\/]/.test(path)
129}
130
131/** `/c/projects/x` (Git Bash) as `C:/projects/x`; other paths unchanged. */
132export function fromGitBash(path: string): string {
133 return path.replace(/^\/([a-zA-Z])\//, (_, drive: string) => `${drive.toUpperCase()}:/`)
134}
135
136/** Whether a Write/Edit path is outside the orchestrator guard: Claude's own folders (memory, plans, scratchpad). */
137export function isGuardExempt(path: string): boolean {
138 const p = path.replace(/\\/g, '/').toLowerCase()
139 return p.includes('/.claude/') || p.includes('/appdata/local/temp/claude/') || p.startsWith('/tmp/claude')
140}
141
142/** `12m`, `1h05m`, `40s`. */
143export function formatDuration(ms: number): string {
144 const s = Math.max(0, Math.round(ms / 1000))
145 if (s < 60) return `${s}s`
146 const m = Math.floor(s / 60)
147 if (m < 60) return `${m}m`
148 return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
149}
150
151/** `▮▮▯▯` for done of total, `width` cells. */
152export function progressBar(done: number, total: number, width = 5): string {
153 if (total <= 0) return ''
154 const full = Math.round((done / total) * width)
155 return '▮'.repeat(full) + '▯'.repeat(width - full)
156}
157
158/** A title cut to `max` characters with an ellipsis. */
159export function short(text: string, max: number): string {
160 return text.length <= max ? text : `${text.slice(0, Math.max(1, max - 1))}…`
161}
162hooks/state.ts 10 lines1// Shared constants and pure helpers. The state atoms themselves are declared in register.tsx: the engine
2// reads `$.state` references only where they are written in the file that uses them.
3
4export const PANE = 'devflow-hud'
5
6/** Statuses of an agent whose loop still works (a HudAgent or a $.agent.list() row). */
7export function isRunning(agent: { status: string }): boolean {
8 return agent.status === 'pending' || agent.status === 'running' || agent.status === 'waiting'
9}
10hooks/view.tsx 201 lines1// The band above the prompt (one line) and the /hud pane: drawn from the session state alone.
2
3import type { ElementTable } from 'claude-code'
4
5import type { HudAgent, HudCheck, HudGuard, HudPhase } from '../types'
6import { formatDuration, progressBar, short } from './parse'
7import { isRunning } from './state'
8
9export type HudView = {
10 phase: HudPhase | null
11 agents: HudAgent[]
12 checks: HudCheck[]
13 guard: HudGuard
14 now: number
15}
16
17/** Done and total of the phase's direct sub-tasks (archived ones are not listed by TaskTracker). */
18function subtaskProgress(phase: HudPhase): { done: number; total: number } {
19 return { done: phase.subtasks.filter(t => t.status === 'completed').length, total: phase.subtasks.length }
20}
21
22function acProgress(phase: HudPhase): { done: number; total: number } {
23 const all = phase.requirements.flatMap(r => r.criteria)
24 return { done: all.filter(c => c.isSatisfied).length, total: all.length }
25}
26
27function checkLabel(check: HudCheck): string {
28 if (check.label === 'build') return `build ${check.warnings ?? 0}w/${check.errors ?? 0}e`
29 if (check.label === 'verify') return 'verify.ps1'
30 return `tests ${check.failed}✗/${check.passed}✓`
31}
32
33/** Whether there is anything to show. */
34export function hasContent(view: HudView): boolean {
35 return view.phase !== null || view.agents.some(isRunning) || view.checks.length > 0 || (view.guard.isActive && view.guard.isEnabled)
36}
37
38/** The one-line band, drawn with the surface's element table. */
39export function band(elements: ElementTable, view: HudView, columns: number) {
40 const { Box, Text } = elements
41 const { phase, agents, checks, guard, now } = view
42 const running = agents.filter(isRunning)
43 const first = running[0]
44 const last = checks.at(-1)
45 const titleRoom = Math.max(12, Math.floor(columns / 4))
46
47 return (
48 <Box flexDirection="row">
49 <Text wrap="truncate-end">
50 {phase !== null && (
51 <Text color={phase.isIdle ? 'subtle' : 'claude'} bold={!phase.isIdle}>
52 ◆ {short(phase.phase.title, titleRoom)}
53 </Text>
54 )}
55 {phase?.active && <Text dimColor> › {short(phase.active.title, titleRoom)}</Text>}
56 {phase !== null && phase.subtasks.length > 0 && (
57 <Text>
58 {' '}
59 {progressBar(subtaskProgress(phase).done, subtaskProgress(phase).total)} {subtaskProgress(phase).done}/
60 {subtaskProgress(phase).total}
61 </Text>
62 )}
63 {phase !== null && acProgress(phase).total > 0 && (
64 <Text color={acProgress(phase).done === acProgress(phase).total ? 'success' : undefined}>
65 {' '}AC {acProgress(phase).done}/{acProgress(phase).total}
66 </Text>
67 )}
68 {phase?.time !== undefined && phase.time.totalMs > 0 && (
69 <Text dimColor>
70 {' '}⏱ {phase.time.isPartial ? '≥' : ''}
71 {formatDuration(phase.time.totalMs)}
72 </Text>
73 )}
74 {first !== undefined && (
75 <Text color="suggestion">
76 {' '}⚙ {running.length > 1 ? `${running.length}× ` : ''}
77 {short(first.type, 14)} "{short(first.description, 28)}" {formatDuration(now - first.startedAt)}
78 </Text>
79 )}
80 {last !== undefined && (
81 <Text color={last.isOk ? 'success' : 'error'}>
82 {' '}
83 {last.isOk ? '✔' : '✗'} {checkLabel(last)}
84 <Text dimColor> {formatDuration(now - last.at)}</Text>
85 </Text>
86 )}
87 {last !== undefined && last.missing.length > 0 && <Text color="warning"> ⚠ {last.missing.length} not run</Text>}
88 {guard.isActive && guard.isEnabled && <Text color="permission">{' '}◈ orchestrator</Text>}
89 </Text>
90 </Box>
91 )
92}
93
94const STATUS_GLYPH: Record<string, string> = {
95 completed: '✔',
96 in_progress: '▶',
97 pending: '·',
98 blocked: '⛔',
99}
100
101/** The /hud pane: the phase tree, every AC, the agents, the checks and the guard. */
102export function pane(
103 elements: ElementTable,
104 view: HudView,
105 actions: { refresh: () => void; toggleGuard: () => void; toggleBand: () => void },
106 isBandHidden: boolean,
107) {
108 const { Box, Text, Button } = elements
109 const { phase, agents, checks, guard, now } = view
110
111 return (
112 <Box flexDirection="column">
113 <Box flexDirection="row" gap={1}>
114 <Button key="refresh" hotkey="r" label="Refresh" onPress={actions.refresh} />
115 <Button key="guard" hotkey="g" label={guard.isEnabled ? 'Guard: on' : 'Guard: off'} onPress={actions.toggleGuard} />
116 <Button key="band" hotkey="b" label={isBandHidden ? 'Band: hidden' : 'Band: shown'} onPress={actions.toggleBand} />
117 </Box>
118
119 <Text bold> </Text>
120 {phase === null ? (
121 <Text dimColor>No TaskTracker phase seen yet. It appears when a task is activated (setActiveTask), or press Refresh.</Text>
122 ) : (
123 <Box flexDirection="column">
124 <Text bold color="claude">
125 {STATUS_GLYPH[phase.phase.status] ?? '?'} {phase.phase.title} <Text dimColor>({phase.phase.status}{phase.isIdle ? ', no active task' : ''})</Text>
126 </Text>
127 {phase.error && <Text color="error"> last refresh failed: {phase.error}</Text>}
128 {phase.time !== undefined && (
129 <Text>
130 {' '}⏱ {phase.time.isPartial ? 'at least ' : ''}
131 {formatDuration(phase.time.totalMs)} booked for the phase and its tasks
132 {phase.active !== null && phase.time.activeMs !== null && `; ${formatDuration(phase.time.activeMs)} on ${phase.active.title}`}
133 <Text dimColor> (closed time segments; the open one counts once it closes)</Text>
134 </Text>
135 )}
136 {phase.subtasks.map(task => (
137 <Text color={phase.active?.id === task.id ? 'suggestion' : undefined} dimColor={task.status === 'completed'}>
138 {' '}
139 {STATUS_GLYPH[task.status] ?? '?'} {task.title}
140 {phase.active?.id === task.id ? ' ← active' : ''}
141 </Text>
142 ))}
143 {phase.requirements.length === 0 && (
144 <Text dimColor> No linked requirements read (set the projectId option, or let a TaskTracker call with a projectId pass).</Text>
145 )}
146 {phase.requirements.map(requirement => (
147 <Box flexDirection="column">
148 <Text bold>
149 {' '}
150 {requirement.slug} {requirement.criteria.filter(c => c.isSatisfied).length}/{requirement.criteria.length}
151 </Text>
152 {requirement.criteria.map(criterion => (
153 <Text wrap="truncate-end" dimColor={criterion.isSatisfied} color={criterion.isSatisfied ? 'success' : undefined}>
154 {' '}
155 {criterion.isSatisfied ? '[x]' : '[ ]'} {criterion.text}
156 </Text>
157 ))}
158 </Box>
159 ))}
160 <Text dimColor> read {formatDuration(now - phase.refreshedAt)} ago</Text>
161 </Box>
162 )}
163
164 <Text bold> </Text>
165 <Text bold>Agents</Text>
166 {agents.length === 0 && <Text dimColor> none this session</Text>}
167 {agents.slice(-12).map(agent => (
168 <Text color={isRunning(agent) ? 'suggestion' : agent.status === 'completed' ? undefined : 'error'} dimColor={!isRunning(agent) && agent.status === 'completed'}>
169 {' '}
170 {isRunning(agent) ? '⚙' : agent.status === 'completed' ? '✔' : '✗'} {agent.type} "{agent.description}" {agent.status}{' '}
171 {formatDuration((agent.endedAt ?? now) - agent.startedAt)}
172 </Text>
173 ))}
174
175 <Text bold> </Text>
176 <Text bold>Checks</Text>
177 {checks.length === 0 && <Text dimColor> none read yet (dotnet build/test and verify.ps1 output is read from shell commands)</Text>}
178 {checks.slice(-10).map(check => (
179 <Text color={check.isOk ? undefined : 'error'}>
180 {' '}
181 {check.isOk ? '✔' : '✗'} {checkLabel(check)} <Text dimColor>({check.loop}, {formatDuration(now - check.at)} ago{check.projects > 0 ? `, ${check.projects} projects` : ''})</Text>
182 {check.missing.length > 0 && <Text color="warning"> ⚠ not run: {check.missing.join(', ')}</Text>}
183 {check.summary && <Text dimColor> {check.summary}</Text>}
184 </Text>
185 ))}
186
187 <Text bold> </Text>
188 <Text>
189 <Text bold>Guard </Text>
190 {!guard.isEnabled ? (
191 <Text dimColor>off (/hud guard on)</Text>
192 ) : guard.isActive ? (
193 <Text color="permission">active: {guard.skill} leads the main thread; its Write/Edit/NotebookEdit are refused</Text>
194 ) : (
195 <Text dimColor>armed; turns on when an orchestrator skill is invoked</Text>
196 )}
197 </Text>
198 </Box>
199 )
200}
201types/index.d.ts 79 lines1/** A TaskTracker task as the HUD shows it. */
2export type HudTask = { id: string; title: string; type: string; status: string }
3
4/** One acceptance criterion of a requirement linked to the phase. */
5export type HudCriterion = { text: string; isSatisfied: boolean }
6
7/** A requirement linked to the phase, with its acceptance criteria. */
8export type HudRequirement = { id: string; slug: string; criteria: HudCriterion[] }
9
10/** The phase the active task belongs to, as last read from TaskTracker. */
11export type HudPhase = {
12 phase: HudTask
13 /** The active task when it is a task under the phase; null when the phase itself is active. */
14 active: HudTask | null
15 subtasks: HudTask[]
16 requirements: HudRequirement[]
17 refreshedAt: number
18 /** True when no task is active any more (the view is the last one seen). */
19 isIdle: boolean
20 /** Time TaskTracker has booked; absent until first read. */
21 time?: HudTime
22 error?: string
23}
24
25/** Booked time from TaskTracker's summaries, which count closed time segments only. */
26export type HudTime = {
27 /** The phase and every task under it. */
28 totalMs: number
29 /** The active task's own time; null when the phase itself is active. */
30 activeMs: number | null
31 /** True when a task's summary could not be read, so the total is a lower bound. */
32 isPartial: boolean
33}
34
35/** A subagent of this session. */
36export type HudAgent = {
37 id: string
38 description: string
39 type: string
40 status: string
41 startedAt: number
42 endedAt?: number
43}
44
45/** A build, test or verify result read from a shell command's output. */
46export type HudCheck = {
47 label: string
48 isOk: boolean
49 failed: number
50 passed: number
51 warnings?: number
52 errors?: number
53 /** Test projects of the solution that reported no result. */
54 missing: string[]
55 projects: number
56 at: number
57 /** "main" or the agent's description. */
58 loop: string
59 summary?: string
60}
61
62/** The orchestrator guard: on while an orchestrator skill leads the main thread. */
63export type HudGuard = { isEnabled: boolean; isActive: boolean; skill: string }
64
65declare module 'claude-code' {
66 interface PluginState {
67 devflow: {
68 phase: HudPhase | null
69 activeTaskId: string | null
70 agents: HudAgent[]
71 checks: HudCheck[]
72 guard: HudGuard
73 isBandHidden: boolean
74 /** Bumped every 30 s while agents run, so elapsed times redraw. */
75 tick: number
76 }
77 }
78}
79