SLOPSHOPPER

coding-standards

Personal coding standards: skills, hooks, and agents reusable across projects

panebandguardcommandtoolagents
★ 1v?MITupdated 2026-10-26ripta/coding_agent_standards/claude
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · coding-standards
│ ┃ work-queue ✕ › fix the failing auth test and add an audit log call │ ┃ No run has reported progress. │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ 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 │ │ › /queue │ ⎿ coding-standards: No /work-queue run has reported progress in th │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · work-queue
No run has reported progress.
README

Coding Agent Standards

Personal coding standards, best practices, and coding agent configuration for use across projects. This repo acts as a single source of truth for language conventions, development practices, project management SOPs, and AI agent behavior rules.

Structure

coding_agent_standards/
├── languages/          Language-specific standards
├── practices/          Cross-cutting practices
├── .claude/            Project-local Claude Code config (skills, settings) for this repo
├── claude/             Claude Code plugin source (exported to other projects)
│   ├── .claude-plugin/      Plugin manifest
│   ├── agents/              Subagent definitions
│   ├── commands/            Slash commands
│   ├── hooks/               hooks.json, the guard scripts it wires up, and the work-queue progress mod
│   ├── knowledge/           LLM wiki standard and the templates a wiki copies
│   ├── project-management/  Plans, proposals, design, tracking, and commit chunking standards
│   ├── rules/               Agent behavior rules
│   ├── scripts/             Standalone scripts (statusline)
│   ├── settings/            Permission whitelist templates per ecosystem
│   ├── skills/              Skill definitions
│   ├── tests/               Tests for the plugin's hooks module
│   └── types/               State contract for the plugin's hooks module
├── codex/              Codex skills with no Claude Code equivalent (exported as a Codex plugin)
├── mods/               Claude Code mods, each its own opt-in plugin in the same marketplace
├── profiles/           Composable project profiles
├── rumdl/              Shared markdown lint config and runner
├── vale/               Shared prose lint styles and runner
└── bin/                Utility scripts

Languages

Standards for each language/framework covering naming, project structure, error handling, testing, and tooling:

  • 1z (1z.md) -- stack-oriented functional language, naming conventions, testing, quotation-based control flow
  • Go (go.md) -- packages, error wrapping, concurrency, build patterns
  • CGO (cgo.md) -- C FFI bridge layers, type conversions, memory management, gomobile
  • Swift (swift.md) -- SwiftUI, async/await, SPM, Go/C library integration
  • Rust (rust.md) -- modules, workspaces, error handling with thiserror/anyhow
  • Zig (zig.md) -- allocators, error sets, build system, embedded tests
  • CSS (css.md) -- cascade layers, reset, logical properties, OKLCH tokens, fluid type and space, layout patterns
  • Svelte (svelte.md) -- SvelteKit, Svelte 5 runes, Tailwind, protobuf RPC
  • TypeScript (typescript.md) -- strict tsconfig, ESM, Biome for format and lint, pnpm
  • Phaser (phaser.md) -- scenes, pooling, atlases, isometric projection
  • PixiJS (pixijs.md) -- v8 application setup, scene graph, ticker, asset bundles
  • Protocol Buffers (protobuf.md) -- file layout, naming, schema evolution, field numbering, buf-based code generation
  • PostgreSQL (postgres.md) -- data types, database-enforced constraints, relationships, indexes, denormalization

Practices

Cross-cutting concerns that apply regardless of language:

  • Testing -- table-driven tests, golden files, HTTP handler tests, testability patterns
  • Error Handling -- wrapping, sentinel errors, structured responses, validation
  • Code Review -- review priorities, submission checklist
  • Security -- input validation, parameterized queries, secret management
  • Makefiles -- help target, per-target .PHONY, common target vocabulary
  • Game Simulation -- fixed timestep, sim/render split, determinism, offline replay

Project Management

Standards for planning and tracking work:

  • Glossary -- what each term means: proposal, milestone, queue, spike, ADR
  • Plans -- the queue that orders work, scheduling, and the rules for working and stopping a milestone
  • Eras -- the numbered styles of project management, and how to tell which one an artifact belongs to
  • Migration -- moving a project to era 3 from any earlier era, without losing what its phases recorded
  • Proposals -- feature proposal lifecycle (draft through implemented), numbering
  • Design -- Architecture Decision Records (ADRs), lifecycle, immutability rules
  • Tracking -- cross-reference conventions, metadata standards, markdown guidelines
  • Commit Chunking -- splitting a long-running integration branch into PR-sized chunks

Claude Code Configuration

Rules, hooks, settings, scripts, commands, agents, and skills for Claude Code:

  • Knowledge (knowledge/) -- the LLM wiki standard for repositories of dated reports, living topic pages, and verbatim references, plus the bin/wiki shim, git hooks, and wiki.json a wiki copies from templates/wiki/
  • Rules (rules/) -- decision-making boundaries, work discipline, git workflow, commit/PR style, writing voice, disclosure when promoting content to a more visible repo
  • Hooks (hooks/) -- hooks.json wires auto-formatting on edit and a test/lint reminder on stop. At session start it keeps the plugin link that profiles import through, and names any passed revisit hook. The block-broad-find, block-redirection, and cg-check guard scripts ship alongside it, plus opt-in hooks for project-management references, golden files, and the Zig cache; see claude/hooks/README.md for which are wired by default. hooks.json also loads work-queue-progress.tsx, a mod that shows a work-queue run's progress above the prompt and in a /queue pane
  • Settings (settings/) -- permission whitelist templates to copy into a project's .claude/settings.local.json, one per language ecosystem
  • Scripts (scripts/) -- standalone scripts not tied to a hook: the statusline; proposals.py, which checks proposals and the queue, reports progress, and lists revisit hooks for the commands and skills; and detect_era.py, which reads a project's era from its markers and inventories what a migration to era 3 moves; wiki.py, which builds and checks a wiki's generated index and topic report lists; pr_watch.py, which polls PRs for CI and review events and replies to review threads for merge-fix-loop; and batch_plan.py, which checks that land-branch's batches rebuild the branch they came from
  • Skills (skills/) -- specialized agents for code review, testing, linting, Makefile maintenance, releases, proposals, landing a branch through PRs (land-branch), driving one PR to merged (merge-fix-loop), etc.
  • Agents (agents/) -- subagent definitions invoked by name: implementer, which writes one milestone for work-queue; reviewer, for post-milestone diff review and the end-of-run ADR review; adr-impact, which checks a diff or proposal against the project's ADRs; design-critic, which critiques design options and whole proposals for proposal-reviewer; design-judge, which breaks ties when repeated critique does not converge; citation-verifier, which checks file:line citations for walkthrough and architecture-exploration; and claim-verifier, which checks a research document's factual claims against their sources for research-audit
  • Commands (commands/) -- slash commands for driving a proposal milestone (work-on), working through queue rows planned up front (work-queue), summarizing a session as a commit message (summary), chunking an integration branch into PRs (next-pr), writing a PR title and description for a branch (pr-description), iterating a design question with the critic until it converges (converge-design), migrating a project to era 3 (migrate-era), and owning a domain's changes for other sessions (guardian)

Commands stay thin. The rules they enforce live in claude/rules/ and claude/project-management/, and a command reads them at ${CLAUDE_PLUGIN_ROOT}/... rather than restating them. Keeping one copy is what stops /summary and /work-on from drifting apart on the same commit-message rules.

Note the distinction between .claude/ and claude/:

  • .claude/ is the standard Claude Code project config directory. Skills and settings here apply when working in this repo (e.g., standards-synthesizer for onboarding new languages).
  • claude/ contains skills, commands, hooks, rules, and settings exported to other projects that reference this repo via --add-dir or @import.

Codex Configuration

codex/ holds skills and integration code that only run under Codex. A skill lands here when it depends on something Codex has and Claude Code does not. expand-lore-wiki is the current example. It calls Codex's built-in imagegen skill, and Claude Code has no image generation to port it to.

Codex skills carry an agents/openai.yaml next to SKILL.md. That file holds the display name and short description Codex shows in its own UI, and Claude Code ignores it.

Codex setup scripts live in codex/scripts/, and startup hooks live in codex/hooks/, matching the layout under claude/. Their tests live beside them. The generated shared-standards plugin packages these integration files; the separate Codex-only skills plugin does not register the baseline hooks.

To build the portable subset of the Claude plugin for Codex, run:

bin/build-codex

Requires Python 3, with no third-party packages. All generated files go into the gitignored dist/codex/ directory: the plugin manifest, skills, companion scripts, and referenced standards. Rebuilding replaces that directory. The builder does not install anything or write to your home directory. Edit claude/, then rebuild; keep authored Codex-only skills in codex/.

The generated coding-standards-portable plugin includes format-checker, gitignore-maintainer, go-code-reviewer, lint-runner, makefile-helper, release, risk-assessment, session-report, and testing-specialist. It also converts summary and next-pr into explicit-only skills. Bundled paths resolve relative to each skill, so the package can be moved without depending on the source checkout.

Claude agents, hooks, mods, and orchestration workflows such as work-on are excluded. Claude model selection and tool allowlists are removed; Codex session permissions apply. The builder rejects unknown skill metadata and untranslated Claude dependencies in skill instructions. Reference documents are supporting material, not automatically loaded project rules. Install the generated directory as a local plugin in a client that supports local plugins.

Baseline standards in Codex

The same build generates dist/codex/baseline.md from the imports in profiles/baseline.md. It lists all baseline documents in their original order and supplies Codex-specific tool adaptations. The bundle includes the proposal checker referenced by the project management standards; it requires Python 3.10+. Edit the shared sources and rebuild to update it.

To build, install, and enable the baseline for your local projects, run:

bin/install-codex

The installer registers the generated marketplace, installs a snapshot into Codex's plugin cache, and creates ~/.codex/coding-standards-current pointing at that snapshot. It appends a baseline instruction to ~/.codex/AGENTS.md, preserving existing content. Repeating it does not duplicate that instruction. When a nonempty AGENTS.override.md is present, setup updates that active global instruction file instead. It honors CODEX_HOME when set. The installed baseline does not depend on this checkout remaining available.

Start a new thread after installation. Review and trust the plugin's SessionStart hook in Codex so subsequent sessions refresh the link after plugin updates. The installer creates the initial link without requiring the hook. The hook refuses to replace a regular file or directory at the link path and refuses to link a working tree.

For project-only adoption, build and install the plugin using the commands below, then put this in the project's existing AGENTS.md instead of running the installer:

Read and follow `~/.codex/coding-standards-current/baseline.md`,
including every document it lists, before working on this project.

Keep existing instructions in that file. With a custom CODEX_HOME, use its absolute path instead of ~/.codex. Trust the startup hook before starting the thread that uses the baseline.

This uses an explicit read instruction rather than Claude's @import syntax. Codex loads AGENTS.md from its global and project instruction locations. Installing the plugin alone does not activate this baseline; the instruction in AGENTS.md does. Keep the whole bundle together when distributing it so its relative references resolve.

The baseline applies to the project where Codex is working, including monorepos, submodules, and separate repos. It preserves existing spec locations and does not assume that components ship together. The startup hook maintains the stable link and checks setup. Claude enforcement hooks and orchestration commands are not enabled.

Profiles

Composable profiles that bundle the right standards for a given project type. Each profile imports a baseline plus relevant language and practice standards:

ProfileStack
go-serviceGo backend services
go-svelte-fullstackGo + Svelte + protobuf
go-cgo-libraryGo libraries with C FFI
swift-macos-appSwiftUI macOS apps
swift-cliSwift command-line tools
rust-projectRust projects
1z-project1z standalone projects
1z-interpreter1z interpreter (Zig + 1z)
zig-projectZig projects
svelte-appSvelte/SvelteKit apps
ts-gameBrowser games in TypeScript, engine-agnostic base
ts-phaser-gamets-game plus Phaser
ts-pixi-gamets-game plus PixiJS
wikiWiki repositories of reports, topics, and references
oss-contribLightweight profile for contributing to repos you don't own

Usage

Import a profile from your project's CLAUDE.md:

@~/projects/coding_agent_standards/profiles/go-service.md

For repos you don't own, use CLAUDE.local.md (auto-gitignored by Claude Code) to avoid committing personal standards:

@~/projects/coding_agent_standards/profiles/oss-contrib.md

A gitignored CLAUDE.local.md does not reach a new worktree on its own. Claude Code copies the gitignored files listed in a .worktreeinclude file at the repo root into the worktrees it creates. List CLAUDE.local.md there. In a repo you don't own, keep .worktreeinclude out of commits by adding it to .git/info/exclude.

Installing the Claude Code Plugin

The skills, hooks, and agents under claude/ are packaged as a Claude Code plugin named coding-standards. The marketplace manifest lives at the repo root (.claude-plugin/marketplace.json) and points at ./claude as the plugin source.

Only claude/ is copied into the plugin cache. An installed plugin cannot read files outside its own directory, so anything a skill needs at runtime has to live inside it. That is why project-management/ sits under claude/ rather than at the repo root, and why profiles/baseline.md imports it from there.

Install once, inside any Claude Code session. Run the two commands as separate prompts. A slash command takes the whole rest of the input as its argument. Pasting both lines at once makes /plugin marketplace add read the second line as part of the repo name, and it fails with is not a valid GitHub owner/repo shorthand.

First register the marketplace:

/plugin marketplace add ripta/coding_agent_standards

Then install the plugin from it:

/plugin install coding-standards@coding-standards

The coding-standards@coding-standards spelling is not a typo. The plugin and the marketplace share a name. The part before @ is the plugin from claude/.claude-plugin/plugin.json. The part after is the marketplace from .claude-plugin/marketplace.json.

Choose user scope when prompted so the plugin is available in all your projects. A local clone works as the marketplace source too (/plugin marketplace add ~/projects/coding_agent_standards), in which case updates track your clone instead of GitHub.

Plugin skills and commands are namespaced: invoke them as /coding-standards:<name>. If you keep a copy of a skill in ~/.claude/skills/, or a command in ~/.claude/commands/, both versions will appear -- delete the personal copy once the plugin version works for you.

Then, once per machine, let sandboxed sessions write the standards' state directory. Run this from your own terminal. It refuses to run inside a coding agent, and it shows the diff before asking to write ~/.claude/settings.json:

python3 ~/.claude/coding-standards-current/scripts/setup_permissions.py

Re-run it after updating the plugin. It is safe to repeat. --check only reports. The link moves to a new plugin version only when a session starts. /reload-plugins does not move it.

Updating

Installed plugins are cached copies, not live references. After changes land in the repo:

/plugin marketplace update coding-standards

The plugin has no pinned version; Claude Code versions it by git commit SHA, so every update pulls the latest commit.

Active Development

To iterate on a skill without the cache in the way, launch Claude Code with the plugin loaded directly from source:

claude --plugin-dir ~/projects/coding_agent_standards/claude

Edit freely, then run /reload-plugins in the session to pick up changes immediately. Once satisfied, commit and push, and installed copies catch up via /plugin marketplace update.

Installing Mods

mods/ holds mods: plugins built from TypeScript function hooks that can draw UI inside Claude Code. Each is its own plugin in the same marketplace, so none of them ride along with coding-standards. The exception is the work-queue progress mod, which serves /work-queue and so ships inside coding-standards. Install a mods/ plugin by name:

/plugin install gopher-spinner@coding-standards

gopher-spinner draws a pixel-art gopher in place of the spinner line while a turn runs. It hops during tool calls, looks around while thinking, and blinks while replying. It replaces the whole line, so the elapsed time and token count are not shown. It draws in the terminal only. /gopher opens a pane that plays every frame. Redraw the gopher by editing the pixel rows in hooks/frames.ts.

Check a mod with claude plugin validate mods/<name> and claude plugin test mods/<name>. To iterate with hot reload, launch with claude --plugin-dir ~/projects/coding_agent_standards/mods/<name>.

Installing the Codex Plugin

The skills under codex/ are packaged as a Codex plugin, also named coding-standards. Its manifest is codex/.codex-plugin/plugin.json. The marketplace manifest is .agents/plugins/marketplace.json at the repo root, pointing at ./codex.

Codex discovers ~/.agents/plugins/marketplace.json implicitly, but not a repo-local one. Register this repo once:

codex plugin marketplace add ~/projects/coding_agent_standards
codex plugin add coding-standards@coding-standards

Start a new thread afterward. That is the boundary where Codex picks up new skills.

Validate against Codex's ingestion contract before pushing a manifest change:

python3 ~/.codex/skills/.system/plugin-creator/scripts/validate_plugin.py codex

The generated shared-standards plugin has its own marketplace inside dist/codex/. bin/install-codex handles installation and global baseline setup together. To install only the plugin after building:

codex plugin marketplace add ~/projects/coding_agent_standards/dist/codex
codex plugin add coding-standards-portable@coding-standards-portable

This marketplace travels with the generated bundle. A recipient can register an unpacked bundle instead of cloning this repository. The source bundle is needed again for updates, but sessions read the installed snapshot. The root marketplace continues to expose only the separately authored Codex skills.

Two differences from the Claude Code plugin are worth knowing:

  • Codex requires strict semver in version and caches by it. There is no commit-SHA equivalent. Iterating locally means rewriting the version to 0.1.0+codex.<token> and re-running codex plugin add. The generated plugin does this automatically with a content hash; bin/install-codex rebuilds and installs changed content.
  • Codex supports trusted lifecycle hooks for manually installed desktop plugins. Hook-containing plugins cannot enter the public plugin directory. See the official hook packaging documentation.

Linting

Two linters ship as shared config plus a runner, one directory each. Both are copy-in rather than import, since neither tool supports config inheritance.

cp ~/projects/coding_agent_standards/rumdl/rumdl.toml.template .rumdl.toml
~/projects/coding_agent_standards/rumdl/lint-markdown

cp ~/projects/coding_agent_standards/vale/vale.ini.template .vale.ini
~/projects/coding_agent_standards/vale/lint-prose

rumdl/ checks markdown structure, including the 120-column prose width. vale/ checks prose shape in markdown and in code comments. They do not overlap. Each runner defaults to diff scoping against the base ref, so a repo with a backlog can adopt them without a burn-down first. See rumdl/README.md and vale/README.md.

Setup Validation

The Claude plugin checks setup at every session start, through claude/hooks/check-setup.sh. It prints nothing when all is well. Otherwise it names what is missing:

  • Settings entries that setup_permissions.py adds
  • A project with no standards import in CLAUDE.md or CLAUDE.local.md
  • A worktree missing the main checkout's CLAUDE.local.md
  • A project whose standards import is not yet approved

The generated Codex plugin follows the same pattern. codex/hooks/check-setup.py refreshes the installed link and checks the baseline reference in global or project instructions. It prints nothing when setup is complete. Otherwise it names the missing setup and the installed script that repairs it. Startup does not edit AGENTS.md.

Check Codex setup without changing anything:

python3 ~/.codex/coding-standards-current/scripts/setup.py --check

Apply setup from the installed plugin, without rebuilding or having a source checkout:

python3 ~/.codex/coding-standards-current/scripts/setup.py

The setup script repairs the stable link and adds the global baseline reference while preserving existing instructions. For project-only adoption, keep the reference in the project's AGENTS.md and use --check. If the stable link is missing, run scripts/setup.py from the installed plugin path reported by codex plugin add. Use the corresponding path under CODEX_HOME when that variable is set. Setup does not modify Codex permissions or grant hook trust; trust review remains in Codex.

Verify discovery and trust through Codex's runtime, rather than calling the hook script directly:

python3 ~/.codex/coding-standards-current/scripts/verify_hooks.py

This starts a temporary app-server process and queries hooks/list. It does not run a model turn or change trust. It fails when the installed startup hook is missing, disabled, or awaiting trust. Open /hooks in Codex CLI to review and trust the standards hook, then rerun verification. Hook trust is tied to the current definition. See the [official hook trust documentation](https://le

Source 2 files
hooks/work-queue-progress.tsx 356 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Milestone, MilestoneStatus, Row, Run, Step, Worker } from '../types'
5
6const run = atom({ plugin: 'coding-standards', key: 'run' } as const, null)
7const workers = atom({ plugin: 'coding-standards', key: 'workers' } as const, [])
8
9export const TOOL = 'work_queue_status'
10export const PANE = 'work-queue'
11const ACCENT = '#56b4e0'
12const LABEL = ' work-queue '
13const RULE_LEAD = '──'
14// The pane lists this many recent subagents.
15const WORKER_HISTORY = 8
16
17const STATUSES: readonly MilestoneStatus[] = ['QUEUED', 'IN PROGRESS', 'DONE', 'DROPPED', 'HELD', 'BLOCKED']
18const STEPS: readonly Step[] = [
19  'implementing', 'reviewing', 'fixing', 'committing', 'row-review', 'final-review', 'finished',
20]
21
22const GLYPH: Record<MilestoneStatus, string> = {
23  QUEUED: '○',
24  'IN PROGRESS': '●',
25  DONE: '✓',
26  DROPPED: '–',
27  HELD: '⏸',
28  BLOCKED: '✗',
29}
30const DIM: ReadonlySet<MilestoneStatus> = new Set(['QUEUED', 'DROPPED', 'HELD'])
31const COLOR: Partial<Record<MilestoneStatus, string>> = {
32  'IN PROGRESS': ACCENT,
33  DONE: 'green',
34  BLOCKED: 'red',
35}
36
37const INPUT_SCHEMA = {
38  type: 'object',
39  properties: {
40    rows: {
41      type: 'array',
42      description: 'Every queue row in the run, in run order',
43      items: {
44        type: 'object',
45        properties: {
46          id: { type: 'string', description: 'Milestone range, e.g. "PROJ-004 M3-M5"' },
47          title: { type: 'string' },
48          held: { type: 'string', description: 'Why the row is held, when it is' },
49          blocked: { type: 'string', description: 'Why the row is blocked, when it is' },
50          milestones: {
51            type: 'array',
52            items: {
53              type: 'object',
54              properties: {
55                id: { type: 'string', description: 'Milestone ID, e.g. "PROJ-004 M3"' },
56                title: { type: 'string' },
57                status: { type: 'string', enum: STATUSES },
58                commit: { type: 'string', description: 'Short SHA once committed' },
59              },
60              required: ['id', 'status'],
61            },
62          },
63        },
64        required: ['id', 'milestones'],
65      },
66    },
67    current: {
68      type: 'object',
69      description: 'What the coordinator is doing now',
70      properties: {
71        milestone: { type: 'string', description: 'Milestone being worked, e.g. "PROJ-004 M3"' },
72        step: { type: 'string', enum: STEPS },
73      },
74      required: ['step'],
75    },
76  },
77  required: ['rows'],
78}
79
80const DESCRIPTION = [
81  'Report /work-queue run progress so the person can see it above the prompt.',
82  'Send the whole queue every time. Each call replaces the previous snapshot.',
83  'Call it after the plan is approved, and whenever a milestone status or the current step changes.',
84  'Send step "finished" when the run is done.',
85  'Only the /work-queue coordinator may call it. Calls from a subagent are denied.',
86].join(' ')
87
88export function parseRun(input: Record<string, unknown>, now: number): Run | string {
89  if (!Array.isArray(input.rows)) return 'rows must be an array'
90  const rows: Row[] = []
91  for (const raw of input.rows as unknown[]) {
92    const p = raw as Partial<Row>
93    if (typeof p?.id !== 'string' || !Array.isArray(p.milestones)) {
94      return 'each row needs an id and a milestones array'
95    }
96    const milestones: Milestone[] = []
97    for (const m of p.milestones as Partial<Milestone>[]) {
98      if (typeof m?.id !== 'string' || !STATUSES.includes(m.status as MilestoneStatus)) {
99        return `milestone ${String(m?.id)} needs an id and a status of ${STATUSES.join(', ')}`
100      }
101      milestones.push({ id: m.id, title: m.title, status: m.status as MilestoneStatus, commit: m.commit })
102    }
103    rows.push({ id: p.id, title: p.title, held: p.held, blocked: p.blocked, milestones })
104  }
105  const cur = input.current as Run['current'] | undefined
106  if (cur !== undefined && !STEPS.includes(cur.step)) {
107    return `current.step must be one of ${STEPS.join(', ')}`
108  }
109  return { rows, current: cur, updatedAt: now }
110}
111
112export function milestonesOf(r: Run): Milestone[] {
113  return r.rows.flatMap(p => p.milestones)
114}
115
116export function countOf(r: Run, status: MilestoneStatus): number {
117  return milestonesOf(r).filter(m => m.status === status).length
118}
119
120// The headline: what runs now, then the tallies worth a glance.
121export function headline(r: Run): string {
122  const all = milestonesOf(r)
123  const parts: string[] = []
124  const step = r.current?.step
125  if (step === 'finished') {
126    parts.push('finished')
127  } else if (step !== undefined) {
128    parts.push(r.current?.milestone ? `${r.current.milestone} ${step}` : step)
129  }
130  // A dropped milestone is never work to do, so it counts toward neither side of the tally.
131  const dropped = countOf(r, 'DROPPED')
132  parts.push(`${countOf(r, 'DONE')}/${all.length - dropped} done`)
133  if (dropped > 0) parts.push(`${dropped} dropped`)
134  const held = r.rows.filter(p => p.held).length
135  const blocked = r.rows.filter(p => p.blocked).length
136  if (held > 0) parts.push(`${held} held`)
137  if (blocked > 0) parts.push(`${blocked} blocked`)
138  return parts.join(' · ')
139}
140
141// The chips that fit in `columns`, kept around the current milestone. Each
142// chip is its glyph, the id, and one column of gap.
143export function visibleChips(r: Run, columns: number): { chips: Milestone[]; before: number; after: number } {
144  const all = milestonesOf(r)
145  const width = (m: Milestone) => m.id.length + 2
146  const total = all.reduce((n, m) => n + width(m), 0)
147  if (total <= columns) return { chips: all, before: 0, after: 0 }
148
149  const room = columns - 8 // "+N " on each side
150  let at = all.findIndex(m => m.status === 'IN PROGRESS')
151  if (at < 0) at = Math.max(0, all.findIndex(m => m.status === 'QUEUED'))
152  let lo = at
153  let hi = at + 1
154  let used = width(all[at] as Milestone)
155  while (true) {
156    const next = hi < all.length ? width(all[hi] as Milestone) : Infinity
157    const prev = lo > 0 ? width(all[lo - 1] as Milestone) : Infinity
158    if (Math.min(next, prev) + used > room) break
159    if (next <= prev) {
160      used += next
161      hi += 1
162    } else {
163      used += prev
164      lo -= 1
165    }
166  }
167  return { chips: all.slice(lo, hi), before: lo, after: all.length - hi }
168}
169
170// A few words on what a subagent's tool call touched.
171export function describeCall(tool: string, input: Record<string, unknown>): string {
172  const pick = input.file_path ?? input.path ?? input.command ?? input.pattern
173  if (typeof pick !== 'string') return tool
174  const brief = typeof input.command === 'string' ? pick : (pick.split('/').pop() ?? pick)
175  return `${tool} ${brief.length > 40 ? `${brief.slice(0, 39)}…` : brief}`
176}
177
178function isStatusTool(tool: string): boolean {
179  return tool.endsWith(`__${TOOL}`)
180}
181
182export const register: Register = on => {
183  on('session.start', async ($, e, next) => {
184    await $.tool.register({ name: TOOL, description: DESCRIPTION, inputSchema: INPUT_SCHEMA })
185    await $.command.register({
186      name: 'queue',
187      description: 'Show the /work-queue run in a pane (/queue clear hides the band)',
188    })
189    return next(e)
190  })
191
192  // The run's only gate is plan approval, so the status tool never prompts.
193  on('tool.check', ($, e, next) => (isStatusTool(e.tool) ? { decision: 'allow' } : next(e)))
194
195  on('tool.call', async ($, e, next) => {
196    const tool = String(e.tool)
197    const input = e as unknown as Record<string, unknown>
198
199    if (isStatusTool(tool)) {
200      if (e.agentId !== undefined) {
201        return { deny: 'Only the /work-queue coordinator reports run status.' }
202      }
203      const parsed = parseRun(input, await $.clock.now())
204      if (typeof parsed === 'string') return { deny: `${TOOL}: ${parsed}` }
205      await update($, run, () => parsed)
206      const n = milestonesOf(parsed).length
207      return { result: `Recorded ${n} milestones in ${parsed.rows.length} rows.` }
208    }
209
210    const agentId = e.agentId
211    if (agentId !== undefined && (await read($, workers)).some(w => w.agentId === agentId)) {
212      const lastTool = describeCall(tool, input)
213      // A fix round reaches the same agent by SendMessage, so a finished one
214      // turns active again on its next call.
215      await update($, workers, list =>
216        list.map(w =>
217          w.agentId === agentId ? { ...w, isActive: true, toolCalls: w.toolCalls + 1, lastTool } : w,
218        ),
219      )
220    }
221    return next(e)
222  })
223
224  on('agent.spawn', async ($, e, next) => {
225    const spawned = await next(e)
226    const current = await read($, run)
227    const isRunning = current !== null && current.current?.step !== 'finished'
228    if (spawned.agentId !== undefined && e.parentAgentId === undefined && isRunning) {
229      const worker: Worker = {
230        agentId: spawned.agentId,
231        type: e.subagentType.replace(/^.*:/, ''),
232        description: e.description,
233        isActive: true,
234        toolCalls: 0,
235      }
236      await update($, workers, list => [...list, worker].slice(-WORKER_HISTORY))
237    }
238    return spawned
239  })
240
241  on('turn.complete', async ($, e, next) => {
242    const agentId = e.agentId
243    if (agentId !== undefined && (await read($, workers)).some(w => w.agentId === agentId)) {
244      await update($, workers, list =>
245        list.map(w => (w.agentId === agentId ? { ...w, isActive: false } : w)),
246      )
247    }
248    return next(e)
249  })
250
251  on('command.run', { command: 'queue' }, async ($, e) => {
252    if (e.args.trim() === 'clear') {
253      await update($, run, () => null)
254      await update($, workers, () => [])
255      await $.ui.close({ id: PANE })
256      return { text: 'Cleared the work-queue progress.' }
257    }
258    if ((await read($, run)) === null) {
259      return { text: 'No /work-queue run has reported progress in this session.' }
260    }
261    await $.ui.open({ id: PANE, title: 'Work queue', closeOnEscape: true })
262    return { text: 'Work queue pane opened. Esc closes it.' }
263  })
264
265  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
266    const r = await read($, run)
267    if (r === null || e.props.hasSurvey) return next(e)
268
269    const { Box, Text } = $.ui.resolve(e)
270    const columns = e.props.bodyColumns
271    const { chips, before, after } = visibleChips(r, columns)
272    const active = (await read($, workers)).filter(w => w.isActive).at(-1)
273    const rows = e.props.maxRows
274    // The headline doubles as a rule, setting the band off from the transcript.
275    const title = ` ${headline(r)} `
276    const fill = Math.max(0, columns - RULE_LEAD.length - LABEL.length - RULE_LEAD.length - title.length)
277
278    return (
279      <Box flexDirection="column">
280        <Box flexDirection="row">
281          <Text dimColor>{RULE_LEAD}</Text>
282          <Text bold color={ACCENT}>{LABEL}</Text>
283          <Text dimColor>{RULE_LEAD}</Text>
284          <Text wrap="truncate-end">{title}</Text>
285          {fill > 0 && <Text dimColor>{'─'.repeat(fill)}</Text>}
286        </Box>
287        {rows >= 2 && (
288          <Box flexDirection="row" gap={1}>
289            {before > 0 && <Text dimColor>+{before}</Text>}
290            {chips.map(m => (
291              <Text
292                key={`chip-${m.id}`}
293                color={COLOR[m.status]}
294                dimColor={DIM.has(m.status)}
295                bold={m.status === 'IN PROGRESS'}
296              >
297                {GLYPH[m.status]}{m.id}
298              </Text>
299            ))}
300            {after > 0 && <Text dimColor>+{after}</Text>}
301          </Box>
302        )}
303        {rows >= 3 && active !== undefined && (
304          <Text dimColor wrap="truncate-end">
305            ↳ {active.type} · {active.description} · {active.toolCalls} tools
306            {active.lastTool ? ` · ${active.lastTool}` : ''}
307          </Text>
308        )}
309      </Box>
310    )
311  })
312
313  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
314    const { Box, Text } = $.ui.resolve(e)
315    const r = await read($, run)
316    if (r === null) return <Text dimColor>No run has reported progress.</Text>
317    const list = await read($, workers)
318
319    return (
320      <Box flexDirection="column">
321        <Text bold>{headline(r)}</Text>
322        {r.rows.map(p => (
323          <Box key={`row-${p.id}`} flexDirection="column" marginTop={1}>
324            <Text bold color={ACCENT} wrap="truncate-end">
325              {p.id}{p.title ? ` · ${p.title}` : ''}
326            </Text>
327            {p.held && <Text dimColor wrap="wrap">⏸ held: {p.held}</Text>}
328            {p.blocked && <Text color="red" wrap="wrap">✗ blocked: {p.blocked}</Text>}
329            {p.milestones.map(m => (
330              <Text
331                key={`row-${m.id}`}
332                color={COLOR[m.status]}
333                dimColor={DIM.has(m.status)}
334                wrap="truncate-end"
335              >
336                {GLYPH[m.status]} {m.id}{m.commit ? ` ${m.commit}` : ''}{m.title ? ` ${m.title}` : ''}
337              </Text>
338            ))}
339          </Box>
340        ))}
341        {list.length > 0 && (
342          <Box flexDirection="column" marginTop={1}>
343            <Text bold>Subagents</Text>
344            {list.map(w => (
345              <Text key={`worker-${w.agentId}`} dimColor={!w.isActive} wrap="truncate-end">
346                {w.isActive ? '●' : '✓'} {w.type} · {w.description} · {w.toolCalls} tools
347                {w.lastTool ? ` · ${w.lastTool}` : ''}
348              </Text>
349            ))}
350          </Box>
351        )}
352      </Box>
353    )
354  })
355}
356
types/index.d.ts 49 lines
1export type MilestoneStatus = 'QUEUED' | 'IN PROGRESS' | 'DONE' | 'DROPPED' | 'HELD' | 'BLOCKED'
2
3export type Step =
4  | 'implementing'
5  | 'reviewing'
6  | 'fixing'
7  | 'committing'
8  | 'row-review'
9  | 'final-review'
10  | 'finished'
11
12export type Milestone = {
13  id: string
14  title?: string
15  status: MilestoneStatus
16  commit?: string
17}
18
19// A queue row in the run: one contiguous range of one proposal's milestones.
20export type Row = {
21  id: string
22  title?: string
23  held?: string
24  blocked?: string
25  milestones: Milestone[]
26}
27
28export type Run = {
29  rows: Row[]
30  current?: { milestone?: string; step: Step }
31  updatedAt: number
32}
33
34// A subagent the coordinator spawned while a run was going.
35export type Worker = {
36  agentId: string
37  type: string
38  description: string
39  isActive: boolean
40  toolCalls: number
41  lastTool?: string
42}
43
44declare module 'claude-code' {
45  interface PluginState {
46    'coding-standards': { run: Run | null; workers: Worker[] }
47  }
48}
49