Live pane and band showing the work left in the current repo's cpm-next epics (docs/epics), in recommended order of execution, with an on-demand next-steps…

A Claude Code plugin marketplace whose main offering is cpm-next: a planning and building method for Claude Code, plus the mods that keep its model, effort and progress in view. It also holds smaller development tools.
cpm-next turns an idea into working, tested code through a short chain of artefacts kept in your repository's docs/ folder: a discussion record, a product brief, a specification, and epics made of stories with acceptance criteria. Six skills cover the whole path:
| Skill | What it does | Finished when |
|---|---|---|
/cpm-next:party | Discussion with named specialist personas (PM, Architect, Developer, UX, QA and others) | A discussion record is saved and the next step is named |
/cpm-next:plan | Writes whatever is missing of brief, spec and epics, from whatever already exists | The artefacts down to the epics exist and trace upward |
/cpm-next:review | Independent challenge of the epics before they are built | Critical and Warning findings are fixed or waiting on you |
/cpm-next:do | Builds stories, verifies each acceptance criterion with evidence, and has each story audited | Every story in scope is Complete and the tests pass |
/cpm-next:library | Curates reference documents in docs/library/ that planning and building read | Documents carry complete front-matter |
/cpm-next:status | Read-only report of where things stand and the next command to run | Nothing is written |
Each skill declares its model and effort: Opus plans and reviews, Sonnet builds, an Opus auditor agent checks every story before it closes, a Haiku scout agent answers lookups, and status runs on Haiku. The artefact formats are defined in cpm-next/shared/artifacts.md; the plugin's own log of changes is in cpm-next/README.md.
Training material (open in a browser):
cpm-next-onboarding.html — install it and run your first spec in an afternooncpm-next-presentation.html — a slide deck introducing the methodcpm-next-training-guide.html — the full guide: every skill, the artefacts, the mods and day-to-day practiceCPM and DPM, the earlier planning plugins, were withdrawn on 2026-10-08. Their source is in this repository's git history.
Inside Claude Code:
/plugin marketplace add ninthspace/claude-code-marketplace
The suffix is the marketplace's name, not the repository's. marketplace.json declares ninthspace-marketplace, and every installed plugin is keyed by it, so cpm-next@claude-code-marketplace resolves to nothing.
Install these at user scope (the default), so one install serves every repository:
/plugin install cpm-next@ninthspace-marketplace # the six skills, the auditor and scout agents
/plugin install cpm-next-models@ninthspace-marketplace # mod: holds each skill's model and effort, per-story effort
/plugin install cpm-next-progress@ninthspace-marketplace # mod: /progress-tracker, claude.ai trackers per spec and an overview of every project
/plugin install whats-next@ninthspace-marketplace # mod: /next, a live pane of the work left in the repository
/plugin install plugin-sync@ninthspace-marketplace # mod: reloads open sessions when a plugin here is updated
/reload-plugins
Only cpm-next is required. The four mods are optional, and each adds one thing:
| Plugin | Kind | Without it |
|---|---|---|
cpm-next | Skills and agents | — |
cpm-next-models | Mod (function hooks) | A skill's model and effort last only for the turn that invoked it; later turns of a do run fall back to the session model, and stories are not given their own effort |
cpm-next-progress | Mod, adds /progress-tracker | No shareable progress pages or cross-project overview; read the epic docs or run /cpm-next:status |
whats-next | Mod, adds /next | No live pane; run /cpm-next:status |
plugin-sync | Mod | After an update, run /reload-plugins in each open session |
Mods are plugins of function hooks that run inside Claude Code. They load like any plugin, run no model calls of their own unless stated, and are switched off and on with the plugin. A session that was open before you installed one needs /reload-plugins to load it.
Per-project setup for /progress-tracker. In a repository whose spec has epics in docs/epics/, run /progress-tracker 01 (the spec's number). The mod writes the page and asks Claude to publish it, then saves the tracker's link and keeps the table in step with the epic docs from then on. /progress-tracker all then shows every project's trackers in a pane, and /progress-tracker all publish puts the same overview on a claude.ai page. Details under CPM Next Progress.
Keeping up to date. The marketplace auto-updates when Claude Code starts. plugin-sync then reloads sessions that were already open. To update straight away, from any directory:
claude plugin marketplace update ninthspace-marketplace
claude plugin update cpm-next@ninthspace-marketplace # and each other plugin that changed
/plugin install noteplan@ninthspace-marketplace
/plugin install php-lsp@ninthspace-marketplace
/plugin install js-simplifier@ninthspace-marketplace
/plugin install filament-mockup@ninthspace-marketplace
/plugin install generated-files@ninthspace-marketplace
/plugin install weather@ninthspace-marketplace
Plan and build with six skills: party, plan, review, do, library, status
The skills read and write Markdown artefacts under docs/: discussions/, briefs/, architecture/, specifications/, epics/, reviews/, retros/, quick/ and library/. The artefacts are the only state; there are no progress files to clean up. A typical path:
/cpm-next:party to talk an idea through (optional)./cpm-next:plan to write the brief, spec and epics. It reads what exists, asks its questions in one batch, and fills only the gaps. In a brownfield project it grounds every requirement in the current code./cpm-next:review before a large or risky epic (optional)./cpm-next:do to build: one story (/cpm-next:do 3), one epic, or all, which runs unattended and marks a blocked story instead of stopping. Each acceptance criterion gets an Evidence line, and each story is audited before it closes. Before the audit, do checks the story the way the auditor will: the full suite, tests that would fail without the change, unexpected inputs, and the words it wrote against the code. A failed audit gets one more after its fixes, and that one audits the fix code as new code; a story still failing is marked blocked. --parallel builds unblocked stories together in git worktrees, one subagent each, even when they touch the same files, and merges them; it covers code and tests, and stories that need the running app, a lock-file change or a shared migration still go one at a time. --parallel check says what it would do, and whether the test suite is isolated enough for it, without building anything. Without the flag, do makes the same check whenever two or more stories are unblocked at once, and names any batch that qualifies./cpm-next:status whenever you return to the project.Story effort. plan gives a story Effort: high where a mistake is costly or hard to see, and Effort: low for mechanical edits; with cpm-next-models installed, do builds each story at that effort and raises it for a fix after a failed audit. A low story marked Model: haiku is built by a Haiku subagent.
Agents: auditor (Opus, read-only) checks a finished story's evidence, diff, scope, tests, unexpected inputs and user-facing text, reading the full-suite result do hands it rather than running the suite again; scout (Haiku, read-only) answers lookups such as where something is used or what a read-only query returns.
Quick Start:
/plugin install cpm-next@ninthspace-marketplace
/reload-plugins
/cpm-next:plan a CSV export for the bookings report
Holds each cpm-next skill's model and effort for its whole run
A Claude Code mod. A skill's model and effort frontmatter normally lasts only for the turn that invoked it. This mod keeps them for every later turn of the run, including your replies to the skill's questions, until another skill runs, you switch model or effort yourself, or /clear. It runs do all at high effort, and gives /cpm-next:do a set_story_effort tool so each story is built at its own Effort, never below high in a do all run. The footer shows what is held, for example cpm-next:do · story 3 · sonnet · low.
Commands: /cpm-models shows what is held; /cpm-models off releases it.
Works under sec-default. Claude Code's built-in sec-default mod sends classic.* and skill.prompt events past every user-installed plugin, so the mod reads skills from the typed prompt and the Skill tool instead. A typed built-in such as /cost leaves the hold alone. No managed settings are needed: seating the mod in the prepend tier through prependPlugins works only when the marketplace is a local folder declared in managed extraKnownMarketplaces.
Quick Start:
/plugin install cpm-next-models@ninthspace-marketplace
/reload-plugins
Develop: claude plugin validate cpm-next-models and claude plugin test cpm-next-models.
claude.ai progress trackers for cpm-next specs, kept in step with the epic docs, and an overview of every project's
A Claude Code mod (a plugin of function hooks). Name a spec and the mod writes a build order for its stories to a small JSON file, which you can edit; Claude then publishes a private claude.ai artifact showing that order as a table, grouped by phase. The mod compares the table with the epic docs in docs/epics/ whenever they change, and tells Claude which rows to update. Status, titles and outstanding blockers come from the epic docs; the order, phase labels, notes and open decisions come from the build-order file. Every check also saves each tracker's counts to the mod's own store, which feeds a pane and an overview page showing all projects at once. A project that keeps its CPM documents under docs/cpm/ instead, with a docs/cpm/specifications/ folder and no docs/specifications/, is read from there; the paths below then start docs/cpm/.
The mod only reads. It lists the artifact's rows through the ArtifactData tool, which auto mode does not ask about, and never writes to it. Claude's own ArtifactData calls do the writing, so no permission rule is needed. An earlier version wrote to the artifact itself, and auto mode refused those calls intermittently with "The server-side auto mode classifier gave no verdict for ArtifactData".
Build-order file: docs/specifications/NN-build-order.json:
{
"title": "01-Series Build Order",
"spec": "docs/specifications/01-spec-requirements-matrix-todos.md",
"decisions": ["Questions still open, shown in a box above the table"],
"phases": [
{ "label": "No visible change", "items": [
{ "epic": "01-05", "story": 1, "note": "Default value keeps today's text" },
{ "epic": "01-05", "task": "3.1" }
] },
{ "label": "Waiting on input", "note": "Shown beside the phase label", "items": [
{ "epic": "01-05", "story": 2, "waitingOn": "new name from the client" }
] }
]
}
An item is a story (story) or one task (task) of an epic, named by the epic's number prefix. waitingOn shows the item as Waiting on input until it is removed from the file or the item starts. artifact holds the tracker's link; the mod adds it when Claude publishes the page.
The first build order is written from the spec's epics (those whose number starts with the spec's): one phase per epic, epics ordered by their Blocked by epics, each epic's stories ordered by their Blocked by stories and then by number. Superseded and withdrawn epics and stories are left out. Edit the file afterwards to reorder, regroup, split a story into tasks or add waitingOn.
Statuses: Complete, In progress (the story says so, or one of its tasks has started), Waiting on input, Pending. The page shows a Pending row with no blockers as Ready, as whats-next does; the stored status stays Pending. A row's date moves only when its status changes. Blockers shown are the story's and epic's Blocked by items not yet Complete, earlier unfinished tasks of the same story, and any waitingOn.
How it works:
.claude/cpm-next-progress/NN-build-order.pending.json, shows you a one-line notice, and gives Claude a note with the artifact link and the writes. Claude applies them with one ArtifactData batch. More than eight writes stay in the file, and Claude hands them to a Haiku subagent, which reads the file and applies each batch, so they never enter the main conversation.Epics with no spec. Epics planned straight from a discussion, numbered 00-01 and so on with no 00-spec-*.md, still get a tracker: /progress-tracker 00 writes docs/specifications/00-build-order.json from the 00- epics, titled from the first of them, with its Source spec line as the source.
A deleted tracker. Once a spec's work is done you can delete its artifact. The mod then reports that tracker as no longer existing, in one line, and stops reading it; nothing else is checked differently. /progress-tracker 01 for that spec removes the dead link from the build-order file and publishes a new tracker. To stop the line instead, delete the artifact entry from the build-order file yourself.
Finished work costs nothing. A tracker whose rows are all Complete and in step, or whose artifact was deleted, is settled: later checks skip it without reading its build-order file or its artifact, until that build-order file changes. A bare /progress-tracker still checks it. So a story reopened in a finished spec reaches its tracker only through /progress-tracker or an edit to the build-order file. The epic docs are read once per check, not once per tracker.
The folder .claude/cpm-next-progress/ holds generated files (the pages and the pending writes, including overview.html and overview.pending.json); /progress-tracker 01 and /progress-tracker all publish add it to the project's .gitignore.
Commands:
/progress-tracker — checks every tracker in the repository now and prints what differs, or "up to date". In a repository with one spec and no tracker yet, it prepares that spec's tracker instead./progress-tracker all — opens the pane of every project's trackers; /progress-tracker all finished includes the finished ones./progress-tracker times — how long this project's stories have taken and how long each story in progress has run (see Story timings)./progress-tracker all publish — writes the overview page and asks Claude to publish it, or to republish it to its link if it has one./progress-tracker 01 (or a spec file, or a build-order file) — writes docs/specifications/01-build-order.json from the spec's epics if it does not exist yet, writes the page to .claude/cpm-next-progress/, and adds that folder to .gitignore. It then submits a prompt asking Claude to publish the page. When Claude does, the mod saves the link to the build-order file and gives Claude the rows to write. init before the name still works. For a spec that already has a tracker, it rewrites the page from the current template and asks Claude to republish it to the same link, keeping the rows.Every project at a glance. /progress-tracker all opens a pane with one row per tracker in every project, grouped by project, those with work left first: the title, a bar, done of total, and the stories in progress, or the date the counts last moved. The rows fit the pane's own width: in a narrow pane, such as one side of a split, each title gets a line of its own with the bar beneath it. Finished and deleted trackers are counted under their project rather than listed; /progress-tracker all finished lists them too. Each check saves its tracker's counts to the mod's own store, so the pane reads no repository and no artifact; it is redrawn as checks run and once a minute while open, to show other sessions' checks. A project appears once a session there has run a check, and one whose build-order file was removed is dropped when the pane opens.
The overview as a claude.ai page. /progress-tracker all publish writes .claude/cpm-next-progress/overview.html and asks Claude to publish it; the mod keeps its link in its own store, since the page belongs to no one project. The page shows a card per project with a row per tracker, linked to that tracker, and totals across all of them. Finished trackers are counted under each project, with a button to list them; the choice is remembered in that browser. Its rows (collection trackers, one document per project and spec, such as slate--01) are copied from the index and carry the project's folder name, never its path. They are kept in step as the trackers are: a check that changes the index works out the rows the page lacks, and Claude writes them. The page is read only when the index changed since its rows last matched. A bare /progress-tracker brings the page in line from any folder, and asks Claude to write what it found at once. If the page is deleted, the mod forgets the link and says so once; /progress-tracker all publish makes a new one.
Story timings. Each check that sees an epic doc change records the stories whose status moved, stamped with the time the doc was written. A story is timed from the check that sees it go from Pending to In Progress to the one that sees it Complete; a story already under way when timing began, or one seen to jump straight from Pending to Complete, gets no time, and a reopened story goes on from its first start. Only projects with a build-order file are checked, so only they are timed. Once a project has 10 timed stories, /progress-tracker times gives the middle half of their times and the median, overall and for each Effort with 10 of its own, and for each story in progress, how long it has run and roughly how long is left. An estimate counts as a prediction only while the slower quartile is within three times the quicker one; past that the times are shown but no time left is given. The pane adds the time in to each story in progress, and the typical range when it is a prediction; so do the tracker page, under the story's status, and the overview page, beside each story in progress. The pages' rows carry only the story's start and range, which change when a story starts or finishes, and each page works out the time in itself and redraws it every minute. Pages published before 0.7.0 need their template again: /progress-tracker 04 for a tracker and /progress-tracker all publish for the overview republish to the same links. Times run from the first start to the close, so a story left In Progress overnight takes the night with it; the median and quartiles keep one such story from moving the estimate much.
Asking in words. Claude has a publish_tracker tool that does what /progress-tracker 01 does, so "publish the progress tracker" in a prompt gets the plugin's page and not one Claude writes by hand. A story_times tool answers "how long until story 5 is done?" from the timings, as /progress-tracker times does, rather than from Claude's guess at the steps left.
Data layout (in the artifact's database, readable by anyone it is shared with, writable by editors): collection items, one document per row (01-05-s1, 01-05-t3.1), a timed story in progress with started (epoch ms) and, when steady, typical; document meta/tracker with the title, spec, last update and decisions. The overview page has one collection, trackers, one document per project and spec (slate--01), with timings (story, started, typical) for its timed stories in progress.
Mod store ($.store, on this machine only): index:<root>/<file> per tracker, settled: and gone: for finished and deleted trackers, checked:, behind: and times: (each story's status, effort, start and finish) per project, and overview:url and overview:synced for the overview page.
Quick Start:
/plugin install cpm-next-progress@ninthspace-marketplace
/reload-plugins
/progress-tracker 01
/progress-tracker all
/progress-tracker all publish
/progress-tracker times
The mod asks Claude to publish each page. The spec needs its epics in docs/epics/ first.
Reads: the cpm-next epic format (cpm-next/shared/artifacts.md), as What's Next does.
Develop: claude plugin validate cpm-next-progress and claude plugin test cpm-next-progress. To run the working tree, start Claude Code with --plugin-dir cpm-next-progress. Both commands run on the newest Claude Code installed, while open sessions may run an older one; see docs/maintenance/README.md for loading the mod under each.
A live pane and band showing the cpm-next work left in the current repository
A Claude Code mod (a plugin of function hooks). It reads the docs/epics/ and docs/specifications/ folders of the repository the session runs in — or the nearest folder above it that has either, up to the repository's top and never the home folder; a project that keeps its CPM documents under docs/cpm/ is read from there — and shows every story not yet Complete, in the order to build them, and every spec no epic has been planned from yet. It reads the files directly, with no model calls, so it stays current as /cpm-next:do or you edit the epics.
What it shows:
doing, ready, or after Story 1 / after Epic …), and each open epic's story count. Opens by itself in a repository with work left when the terminal is at least 144 columns wide; /next opens it at any width.docs/specifications/ that no epic was planned from, in number order. A spec counts as planned when an epic is numbered after it (03-spec-… → 03-01-epic-…) or an epic names its file in Source spec; a spec whose own Status is Complete, Superseded or Withdrawn is left out, as is a withdrawal notice (a Withdrawn or Superseded by field, or WITHDRAWN / SUPERSEDED in its title).Ask Claude button (hotkey a) that asks Sonnet for a short note on what to do next, from the ordered list and the first two stories in full. The note is kept per repository across sessions and dimmed once hooks/register.tsx 323 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { NextNote, NextPlan, NextStory } from '../types'
5import { buildPlan, describePlan, hasWork, storyText } from './plan'
6import type { EpicFile, SpecFile } from './plan'
7
8const PANE = 'whats-next'
9const POLL_MS = 3000
10const NOTE_MODEL = 'sonnet'
11
12const plan = atom({ plugin: 'whats-next', key: 'plan' } as const, null)
13const note = atom({ plugin: 'whats-next', key: 'note' } as const, null)
14const isNoteBusy = atom({ plugin: 'whats-next', key: 'isNoteBusy' } as const, false)
15const noteError = atom({ plugin: 'whats-next', key: 'noteError' } as const, null)
16
17const EPIC_FILE = /-epic-.*\.md$/
18const SPEC_FILE = /^\d+-spec-.*\.md$/
19const WRITING_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Bash'])
20
21type Listing = { name: string; mtimeMs: number; size: number }
22
23const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`
24
25/** Each project's docs folder: `docs`, or `docs/cpm` in a project that keeps its CPM documents there. */
26const docsFolders = new Map<string, string>()
27const docs = (root: string) => `${root}/${docsFolders.get(root) ?? 'docs'}`
28
29async function findRoot($: EngineInterface): Promise<string | null> {
30 const home = await $.env.get('HOME')
31 let dir = await $.session.cwd()
32 for (;;) {
33 for (const folder of ['docs', 'docs/cpm']) {
34 if (!(await $.fs.exists(`${dir}/${folder}/epics`)) && !(await $.fs.exists(`${dir}/${folder}/specifications`))) continue
35 docsFolders.set(dir, folder)
36
37 return dir
38 }
39 // The climb ends at the repo's top and never enters the home folder, so docs above a project are not taken for its own.
40 if (await $.fs.exists(`${dir}/.git`)) return null
41 const cut = dir.lastIndexOf('/')
42 if (cut <= 0) return null
43 dir = dir.slice(0, cut)
44 if (dir === home) return null
45 }
46}
47
48async function listDocs($: EngineInterface, dir: string, pattern: RegExp): Promise<Listing[]> {
49 if (!(await $.fs.exists(dir))) return []
50 const entries = await $.fs.list(dir)
51
52 return entries.filter(e => e.kind === 'file' && pattern.test(e.name)).sort((a, b) => a.name.localeCompare(b.name))
53}
54
55// Active and archived epics, and active specs; the signature covers all three folders. A `docs/cpm`
56// project may keep its archive in `docs/archive` all the same.
57async function archiveOf($: EngineInterface, root: string): Promise<string> {
58 const own = `${docs(root)}/archive/epics`
59
60 return (await $.fs.exists(own)) ? own : `${root}/docs/archive/epics`
61}
62
63async function listAll($: EngineInterface, root: string) {
64 const active = await listDocs($, `${docs(root)}/epics`, EPIC_FILE)
65 const archived = await listDocs($, await archiveOf($, root), EPIC_FILE)
66 const specs = await listDocs($, `${docs(root)}/specifications`, SPEC_FILE)
67
68 return { active, archived, specs, signature: signatureOf(root, active, archived, specs) }
69}
70
71async function readDocs($: EngineInterface, root: string): Promise<{ files: EpicFile[]; specs: SpecFile[]; signature: string }> {
72 const listed = await listAll($, root)
73 const files: EpicFile[] = []
74 for (const e of listed.active) files.push({ name: e.name, text: await $.fs.read(`${docs(root)}/epics/${e.name}`), isArchived: false })
75 const archive = await archiveOf($, root)
76 for (const e of listed.archived) files.push({ name: e.name, text: await $.fs.read(`${archive}/${e.name}`), isArchived: true })
77 const specs: SpecFile[] = []
78 for (const s of listed.specs) specs.push({ name: s.name, text: await $.fs.read(`${docs(root)}/specifications/${s.name}`), path: `${docs(root).slice(root.length + 1)}/specifications/${s.name}` })
79
80 return { files, specs, signature: listed.signature }
81}
82
83function signatureOf(root: string, ...lists: Listing[][]): string {
84 return [root, ...lists.map(list => list.map(e => `${e.name}:${e.mtimeMs}:${e.size}`).join(','))].join('|')
85}
86
87let isRefreshing = false
88let openedFor: string | null = null
89
90// Re-reads the docs only when an epic or spec file was added, removed or changed.
91async function refresh($: EngineInterface): Promise<NextPlan | null> {
92 if (isRefreshing) return read($, plan)
93 isRefreshing = true
94 try {
95 const root = await findRoot($)
96 const current = await read($, plan)
97 if (root === null) {
98 if (current !== null) await update($, plan, () => null)
99 return null
100 }
101 if (current !== null && current.signature === (await listAll($, root)).signature) return current
102
103 const { files, specs, signature } = await readDocs($, root)
104 const next = buildPlan(root, files, signature, specs)
105 await update($, plan, () => next)
106 if (current?.root !== root) {
107 const saved = (await $.store.get(`note:${root}`)) as NextNote | undefined
108 await update($, note, () => saved ?? null)
109 await update($, noteError, () => null)
110 }
111 await maybeOpen($, next)
112
113 return next
114 } finally {
115 isRefreshing = false
116 }
117}
118
119// Opens the pane unasked once per repo, when that repo has work left.
120async function maybeOpen($: EngineInterface, next: NextPlan) {
121 if (!hasWork(next) || openedFor === next.root) return
122 openedFor = next.root
123 await $.ui.open({ id: PANE, title: "What's next" })
124}
125
126async function askForNote($: EngineInterface) {
127 if (await read($, isNoteBusy)) return
128 const current = await refresh($)
129 if (current === null || !hasWork(current)) return
130 await update($, isNoteBusy, () => true)
131 await update($, noteError, () => null)
132 try {
133 const { files } = await readDocs($, current.root)
134 const focus = current.order.slice(0, 2).map(s => {
135 const file = files.find(f => f.name.replace(/\.md$/, '') === s.epicId)
136 return file === undefined ? '' : `### ${s.epicId} (${s.epicTitle})\n${storyText(file, s.number)}`
137 })
138 const result = await $.model.complete({
139 model: NOTE_MODEL,
140 effort: 'medium',
141 maxTokens: 900,
142 system:
143 'You read cpm-next planning docs (epics with stories, tasks and acceptance criteria) and tell a developer what to do next. ' +
144 'Answer in at most 8 short markdown bullets. Name the story and task, the concrete next steps, and any risk or ' +
145 'dependency to watch. Write literally: no preamble, no metaphor, no closing line.',
146 prompt: focus.length > 0
147 ? `${describePlan(current, 20)}\n\nThe first stories in full:\n\n${focus.join('\n\n')}`
148 : `${describePlan(current, 20)}\n\nNo stories are left; say which spec to plan into epics first and why.`,
149 })
150 if (result.isAnswered) {
151 const saved: NextNote = { root: current.root, signature: current.signature, text: result.text.trim(), at: await $.clock.now() }
152 await update($, note, () => saved)
153 await $.store.set(`note:${current.root}`, saved)
154 } else {
155 await update($, noteError, () => `The note failed: ${result.reason}`)
156 }
157 } finally {
158 await update($, isNoteBusy, () => false)
159 }
160}
161
162let isStarted = false
163
164// Registers /next, reads the docs and starts the poll, once per load.
165async function start($: EngineInterface) {
166 if (isStarted) return
167 isStarted = true
168 await $.command.register({ name: 'next', description: "Show what's left to do in this repo's cpm-next epics, in order, and specs with no epics yet" })
169 await refresh($)
170 $.clock.every(POLL_MS, () => void refresh($))
171}
172
173export const register: Register = on => {
174 on('session.start', async ($, e, next) => {
175 await start($)
176
177 return next(e)
178 })
179
180 // A plugin loaded by /reload-plugins (an install or update mid-session) sees no session.start; start on the first prompt.
181 on('prompt.submit', async ($, e, next) => {
182 await start($)
183
184 return next(e)
185 })
186
187 on('command.run', { command: 'next' }, async $ => {
188 const current = await refresh($)
189 if (current === null) return { text: 'No docs/epics or docs/specifications folder (or the same under docs/cpm) in this directory or above it.' }
190 await $.ui.open({ id: PANE, title: "What's next" })
191
192 return { text: describePlan(current) }
193 })
194
195 // Edits made by tools show up at once rather than at the next poll.
196 on('tool.call', async ($, e, next) => {
197 const result = await next(e)
198 if (WRITING_TOOLS.has(String(e.tool))) await refresh($).catch(() => undefined)
199
200 return result
201 })
202
203 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
204 const current = await read($, plan)
205 const first = current?.order[0]
206 const spec = current?.specs[0]
207 if (e.props.hasSurvey || current === null || (first === undefined && spec === undefined)) return next(e)
208 const { Box, Text } = $.ui.resolve(e)
209
210 if (first === undefined && spec !== undefined) {
211 return (
212 <Box>
213 <Text wrap="truncate-end">
214 <Text color="cyan">Plan next </Text>
215 <Text bold>spec {spec.id.split('-spec-')[0]}</Text>
216 <Text> {spec.title}</Text>
217 <Text dimColor> ({current.specs.length} {current.specs.length === 1 ? 'spec' : 'specs'} without epics · /next)</Text>
218 </Text>
219 </Box>
220 )
221 }
222 if (first === undefined) return next(e)
223 const task = first.nextTask === null ? '' : ` → ${first.nextTask.id} ${first.nextTask.title}`
224
225 return (
226 <Box>
227 <Text wrap="truncate-end">
228 <Text color="cyan">Next </Text>
229 <Text bold>{first.epicId.split('-epic-')[0]} S{first.number}</Text>
230 <Text> {first.title}{task}</Text>
231 <Text dimColor> ({current.order.length} stories left · /next)</Text>
232 </Text>
233 </Box>
234 )
235 })
236
237 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
238 const { Box, Text, Button, Markdown } = $.ui.resolve(e)
239 const current = await read($, plan)
240 const saved = await read($, note)
241 const isBusy = await read($, isNoteBusy)
242 const error = await read($, noteError)
243
244 if (current === null) return <Text dimColor>No docs/epics or docs/specifications folder (or the same under docs/cpm) in this directory or above it.</Text>
245 if (!hasWork(current)) return <Text dimColor>{current.repo}: no stories left and every spec has epics.</Text>
246
247 const label = (s: NextStory) => `${s.epicId.split('-epic-')[0]} S${s.number}`
248 // "Epic 34-01-epic-coupons-overview" reads as "34-01" and "Story 2" as "S2", matching the row labels;
249 // an epic named by both the epic and the story appears once.
250 const after = (tokens: string[]) => {
251 const short = tokens.map(t => t.replace(/^story\s+(\d+)$/i, 'S$1').replace(/^epic\s+/i, '').replace(/-epic-.*$/, ''))
252
253 return `after ${[...new Set(short)].join(', ')}`
254 }
255 const stateOf = (s: NextStory) => (s.status === 'In Progress' ? 'doing' : s.isReady ? 'ready' : after(s.waitsOn))
256 const colourOf = (s: NextStory) => (s.status === 'In Progress' ? 'yellow' : s.isReady ? 'green' : 'red')
257 const first = current.order[0]
258 const isStale = saved !== null && saved.signature !== current.signature
259 const specCount = `${current.specs.length} ${current.specs.length === 1 ? 'spec' : 'specs'} without epics`
260 const summary = [
261 current.order.length > 0 ? `${plural(current.order.length, 'story', 'stories')} · ${plural(current.epics.length, 'epic', 'epics')} left` : '',
262 current.specs.length > 0 ? specCount : '',
263 ].filter(Boolean).join(' · ')
264
265 return (
266 <Box flexDirection="column">
267 <Text bold>{current.repo}<Text dimColor> {summary}</Text></Text>
268 <Text> </Text>
269 {first !== undefined && (
270 <Box flexDirection="column">
271 <Text color="cyan" bold>Now</Text>
272 <Text wrap="truncate-end">{label(first)} {first.title}</Text>
273 {first.nextTask !== null && (
274 <Text wrap="truncate-end" dimColor> task {first.nextTask.id} {first.nextTask.title} ({first.tasksDone}/{first.tasksTotal} done)</Text>
275 )}
276 <Text> </Text>
277 <Text color="cyan" bold>Order</Text>
278 {current.order.slice(0, 30).map((s, i) => (
279 <Text wrap="truncate-end">
280 <Text dimColor={!s.isReady && s.status !== 'In Progress'}>{String(i + 1).padStart(2)} {label(s)} {s.title} </Text>
281 <Text color={colourOf(s)}>{stateOf(s)}</Text>
282 </Text>
283 ))}
284 {current.order.length > 30 && <Text dimColor> … {current.order.length - 30} more</Text>}
285 <Text> </Text>
286 <Text color="cyan" bold>Epics</Text>
287 {current.epics.map(epic => (
288 <Text wrap="truncate-end">
289 {epic.id.split('-epic-')[0]} {epic.title} <Text dimColor>{epic.storiesDone}/{epic.storiesTotal} stories</Text>
290 {epic.waitsOn.length > 0 && <Text color="red"> {after(epic.waitsOn)}</Text>}
291 </Text>
292 ))}
293 <Text> </Text>
294 </Box>
295 )}
296 {current.specs.length > 0 && (
297 <Box flexDirection="column">
298 <Text color="cyan" bold>Specs without epics</Text>
299 {current.specs.map(spec => (
300 <Text wrap="truncate-end">
301 {spec.id.split('-spec-')[0]} {spec.title} <Text color="magenta">plan</Text>
302 </Text>
303 ))}
304 <Text> </Text>
305 </Box>
306 )}
307 <Box>
308 <Text color="cyan" bold>Next steps </Text>
309 <Button
310 key="ask"
311 hotkey="a"
312 label={isBusy ? 'asking…' : saved === null ? 'Ask Claude' : 'Refresh'}
313 onPress={() => void askForNote($)}
314 />
315 </Box>
316 {error !== null && <Text color="red">{error}</Text>}
317 {saved !== null && isStale && <Text dimColor>The epics or specs changed since this note was written.</Text>}
318 {saved !== null && <Markdown text={saved.text} dimColor={isStale} />}
319 </Box>
320 )
321 })
322}
323hooks/plan.ts 302 lines1import type { NextEpic, NextPlan, NextSpec, NextStory, NextTask, WorkStatus } from '../types'
2
3// Reads cpm-next epic docs (shared/artifacts.md in the plugin) tolerantly:
4// field case, trailing hard-break spaces and "Done" for "Complete" all pass.
5
6export type EpicFile = { name: string; text: string; isArchived: boolean }
7
8type ParsedStory = {
9 number: number
10 title: string
11 status: WorkStatus
12 blockedBy: string[]
13 tasks: NextTask[]
14 text: string
15}
16
17type ParsedEpic = {
18 id: string
19 title: string
20 status: WorkStatus
21 blockedBy: string[]
22 stories: ParsedStory[]
23 sortKey: number[]
24 isArchived: boolean
25}
26
27const FIELD = /^\*\*([A-Za-z ]+)\*\*:\s*(.*?)\s*$/
28
29export function normaliseStatus(raw: string | undefined): WorkStatus {
30 const value = (raw ?? '').trim().toLowerCase()
31 if (value.startsWith('complete') || value.startsWith('done')) return 'Complete'
32 if (value.startsWith('in progress')) return 'In Progress'
33 if (value.startsWith('superseded')) return 'Superseded'
34 if (value.startsWith('withdrawn')) return 'Withdrawn'
35 return 'Pending'
36}
37
38export function parseBlockers(raw: string | undefined): string[] {
39 const value = (raw ?? '').trim()
40 if (value === '' || /^[—–-]+$/.test(value) || /^none$/i.test(value)) return []
41
42 return value.split(/[,;]/).map(item => item.trim()).filter(item => item !== '')
43}
44
45function sortKeyOf(id: string): number[] {
46 const prefix = id.split('-epic-')[0] ?? id
47
48 return prefix.split('-').map(Number).filter(n => !Number.isNaN(n))
49}
50
51function compareKeys(a: number[], b: number[]): number {
52 for (let i = 0; i < Math.max(a.length, b.length); i++) {
53 const diff = (a[i] ?? -1) - (b[i] ?? -1)
54 if (diff !== 0) return diff
55 }
56
57 return 0
58}
59
60export function parseEpic(file: EpicFile): ParsedEpic {
61 const id = file.name.replace(/\.md$/, '')
62 const epic: ParsedEpic = {
63 id,
64 title: id,
65 status: 'Pending',
66 blockedBy: [],
67 stories: [],
68 sortKey: sortKeyOf(id),
69 isArchived: file.isArchived,
70 }
71 let story: (ParsedStory & { hasNumber: boolean }) | null = null
72 let task: (NextTask & { hasId: boolean }) | null = null
73 const stories: (ParsedStory & { hasNumber: boolean })[] = []
74
75 for (const line of file.text.split(/\r?\n/)) {
76 if (line.startsWith('# ') && epic.title === id) {
77 epic.title = line.slice(2).trim()
78 continue
79 }
80 if (line.startsWith('## ')) {
81 task = null
82 story = { number: 0, title: line.slice(3).trim(), status: 'Pending', blockedBy: [], tasks: [], text: '', hasNumber: false }
83 stories.push(story)
84 }
85 if (story !== null) story.text += `${line}\n`
86 if (line.startsWith('### ') && story !== null) {
87 task = { id: '', title: line.slice(4).trim(), status: 'Pending', hasId: false }
88 story.tasks.push(task)
89 continue
90 }
91
92 const field = FIELD.exec(line)
93 if (field === null) continue
94 const name = (field[1] ?? '').trim().toLowerCase()
95 const value = field[2] ?? ''
96
97 if (task !== null) {
98 if (name === 'task') { task.id = value; task.hasId = true }
99 if (name === 'status') task.status = normaliseStatus(value)
100 } else if (story !== null) {
101 if (name === 'story') { story.number = Number.parseInt(value, 10); story.hasNumber = true }
102 if (name === 'status') story.status = normaliseStatus(value)
103 if (name === 'blocked by') story.blockedBy = parseBlockers(value)
104 } else {
105 if (name === 'status') epic.status = normaliseStatus(value)
106 if (name === 'blocked by') epic.blockedBy = parseBlockers(value)
107 }
108 }
109
110 // A "## " section without a **Story** field is prose (notes, context), not a story.
111 epic.stories = stories
112 .filter(s => s.hasNumber && !Number.isNaN(s.number))
113 .map(({ hasNumber: _, ...s }) => ({
114 ...s,
115 tasks: s.tasks.filter(t => (t as NextTask & { hasId: boolean }).hasId)
116 .map(({ id, title, status }) => ({ id, title, status })),
117 }))
118
119 return epic
120}
121
122function effectiveStatus(story: ParsedStory): WorkStatus {
123 if (story.status === 'Complete') return 'Complete'
124 const isStarted = story.tasks.some(t => t.status !== 'Pending')
125
126 return story.status === 'In Progress' || isStarted ? 'In Progress' : 'Pending'
127}
128
129const storyKey = (epicId: string, n: number) => `${epicId}#${n}`
130
131export type SpecFile = { name: string; text: string; path?: string }
132
133/**
134 * Specs no epic has been planned from: no cpm-next epic numbered after the spec
135 * (`03-spec-x` → `03-01-epic-y`), and no epic naming the spec's file in its
136 * `**Source spec**`. A spec whose own Status is Complete, Superseded or Withdrawn is left out.
137 */
138export function unplannedSpecs(specs: SpecFile[], epics: EpicFile[]): NextSpec[] {
139 const sources = epics.map(e => /^\*\*Source spec\*\*:\s*(.*)$/im.exec(e.text)?.[1] ?? '')
140
141 return specs
142 .filter(spec => {
143 const number = Number.parseInt(spec.name, 10)
144 const status = normaliseStatus(/^\*\*Status\*\*:\s*(.*)$/im.exec(spec.text)?.[1])
145 if (status === 'Complete' || status === 'Superseded' || status === 'Withdrawn') return false
146 // A withdrawal notice: `**Withdrawn**:` or `**Superseded by**:` fields, or the word in the title.
147 if (/^\*\*(Withdrawn|Superseded by)\*\*:/im.test(spec.text)) return false
148 if (/^#\s+.*\b(WITHDRAWN|SUPERSEDED)\b/m.test(spec.text)) return false
149 const isNumberedAfter = epics.some(e => {
150 const parent = /^(\d+)-\d+-epic-/.exec(e.name)?.[1]
151 return parent !== undefined && Number(parent) === number
152 })
153
154 return !isNumberedAfter && !sources.some(source => source.includes(spec.name))
155 })
156 .sort((a, b) => Number.parseInt(a.name, 10) - Number.parseInt(b.name, 10))
157 .map(spec => ({
158 id: spec.name.replace(/\.md$/, ''),
159 // "# Spec: X" and "# Spec 16: X" both read as "X"; the number is already in the row label.
160 title: /^#\s+(?:Spec(?:ification)?(?:\s+\d+)?:\s*)?(.+)$/im.exec(spec.text)?.[1]?.trim() ?? spec.name,
161 path: spec.path ?? `docs/specifications/${spec.name}`,
162 }))
163}
164
165export function buildPlan(root: string, files: EpicFile[], signature: string, specs: SpecFile[] = []): NextPlan {
166 const epics = files.map(parseEpic).sort((a, b) => compareKeys(a.sortKey, b.sortKey))
167 const isTerminal = (e: ParsedEpic) => e.status === 'Superseded' || e.status === 'Withdrawn'
168
169 const findEpic = (token: string): ParsedEpic | undefined => {
170 const ref = token.replace(/^epic\s+/i, '').trim()
171
172 return epics.find(e => e.id === ref || e.id.startsWith(`${ref}-`))
173 }
174
175 const done = new Set<string>()
176 for (const epic of epics) {
177 for (const story of epic.stories) {
178 if (epic.status === 'Complete' || story.status === 'Complete') done.add(storyKey(epic.id, story.number))
179 }
180 }
181
182 const isEpicDone = (epic: ParsedEpic, finished: Set<string>) =>
183 !isTerminal(epic) &&
184 (epic.status === 'Complete' ||
185 (epic.stories.length > 0 && epic.stories.every(s => finished.has(storyKey(epic.id, s.number)))))
186
187 const outstanding = (epic: ParsedEpic, tokens: string[], finished: Set<string>): string[] =>
188 tokens.filter(token => {
189 const story = /^story\s+(\d+)$/i.exec(token)
190 if (story !== null) return !finished.has(storyKey(epic.id, Number(story[1])))
191 const target = findEpic(token)
192
193 return target === undefined || !isEpicDone(target, finished)
194 })
195
196 type Candidate = { epic: ParsedEpic; story: ParsedStory; status: WorkStatus }
197 const open = epics.filter(e => !e.isArchived && !isTerminal(e) && e.status !== 'Complete')
198 let remaining: Candidate[] = open.flatMap(epic =>
199 epic.stories
200 .filter(story => !done.has(storyKey(epic.id, story.number)))
201 .map(story => ({ epic, story, status: effectiveStatus(story) })),
202 )
203
204 // A story often repeats its epic's dependency; list each one once.
205 const waitsOnNow = (c: Candidate, finished: Set<string>) => [
206 ...new Set([...outstanding(c.epic, c.epic.blockedBy, finished), ...outstanding(c.epic, c.story.blockedBy, finished)]),
207 ]
208
209 const toStory = (c: Candidate): NextStory => {
210 const waitsOn = waitsOnNow(c, done)
211 const nextTask = c.story.tasks.find(t => t.status !== 'Complete') ?? null
212
213 return {
214 epicId: c.epic.id,
215 epicTitle: c.epic.title,
216 number: c.story.number,
217 title: c.story.title,
218 status: c.status,
219 isReady: waitsOn.length === 0,
220 waitsOn,
221 tasksDone: c.story.tasks.filter(t => t.status === 'Complete').length,
222 tasksTotal: c.story.tasks.length,
223 nextTask,
224 }
225 }
226
227 // An epic is under way when its own Status says In Progress or one of its stories is in progress.
228 // Completed stories alone don't count: an epic paused after them is not the current one.
229 const isEpicStarted = (epic: ParsedEpic) =>
230 epic.status === 'In Progress' ||
231 epic.stories.some(s => !done.has(storyKey(epic.id, s.number)) && effectiveStatus(s) === 'In Progress')
232 const tier = (c: Candidate) => (c.status === 'In Progress' ? 0 : isEpicStarted(c.epic) ? 1 : 2)
233
234 // Walk the work forward: take the best ready story, treat it as done, repeat.
235 // Stories in progress first, then the rest of started epics, then epic number, then story number.
236 const rank = (a: Candidate, b: Candidate) =>
237 tier(a) - tier(b) ||
238 compareKeys(a.epic.sortKey, b.epic.sortKey) ||
239 a.story.number - b.story.number
240
241 const simulated = new Set(done)
242 const order: NextStory[] = []
243 while (remaining.length > 0) {
244 const ready = remaining.filter(c => waitsOnNow(c, simulated).length === 0).sort(rank)
245 const pick = ready[0]
246 if (pick === undefined) break
247 order.push(toStory(pick))
248 simulated.add(storyKey(pick.epic.id, pick.story.number))
249 remaining = remaining.filter(c => c !== pick)
250 }
251 // Whatever is left can never become ready from the docs alone (a cycle or an unknown dependency).
252 order.push(...remaining.sort(rank).map(toStory))
253
254 const nextEpics: NextEpic[] = open.map(epic => ({
255 id: epic.id,
256 title: epic.title,
257 status: epic.stories.some(s => effectiveStatus(s) !== 'Pending') ? 'In Progress' : epic.status,
258 storiesDone: epic.stories.filter(s => done.has(storyKey(epic.id, s.number))).length,
259 storiesTotal: epic.stories.length,
260 waitsOn: outstanding(epic, epic.blockedBy, done),
261 }))
262
263 return {
264 root,
265 repo: root.split('/').filter(Boolean).at(-1) ?? root,
266 epics: nextEpics,
267 order,
268 specs: unplannedSpecs(specs, files),
269 signature,
270 }
271}
272
273/** The plan as plain text: what /next prints and what the AI note is asked about. */
274export function describePlan(plan: NextPlan, limit = 12): string {
275 const lines: string[] = []
276 if (plan.order.length === 0) {
277 lines.push(`${plan.repo}: no cpm-next stories left in its epics.`)
278 } else {
279 lines.push(`${plan.repo}: ${plan.order.length} stories left across ${plan.epics.length} epics, in recommended order:`)
280 plan.order.slice(0, limit).forEach((s, i) => {
281 const state = s.status === 'In Progress' ? 'in progress' : s.isReady ? 'ready' : `waits on ${s.waitsOn.join(', ')}`
282 const next = s.nextTask === null ? '' : ` — next task ${s.nextTask.id} ${s.nextTask.title}`
283 lines.push(`${i + 1}. ${s.epicId} Story ${s.number}: ${s.title} (${state}; ${s.tasksDone}/${s.tasksTotal} tasks)${next}`)
284 })
285 if (plan.order.length > limit) lines.push(`… and ${plan.order.length - limit} more.`)
286 }
287 if (plan.specs.length > 0) {
288 lines.push('', `Specs with no epics yet (plan them with /cpm-next:plan <path>):`)
289 for (const spec of plan.specs) lines.push(`- ${spec.path}: ${spec.title}`)
290 }
291
292 return lines.join('\n')
293}
294
295/** True when there is anything to show: stories left or specs not yet planned. */
296export const hasWork = (plan: NextPlan) => plan.order.length > 0 || plan.specs.length > 0
297
298/** The markdown of one story, for the AI note's context. */
299export function storyText(file: EpicFile, number: number): string {
300 return parseEpic(file).stories.find(s => s.number === number)?.text ?? ''
301}
302types/index.d.ts 56 lines1export type WorkStatus = 'Pending' | 'In Progress' | 'Complete' | 'Superseded' | 'Withdrawn'
2
3export type NextTask = { id: string; title: string; status: WorkStatus }
4
5export type NextStory = {
6 epicId: string
7 epicTitle: string
8 number: number
9 title: string
10 status: WorkStatus
11 /** True when nothing it depends on is outstanding right now. */
12 isReady: boolean
13 /** Dependencies not yet Complete, as written in the epic doc. */
14 waitsOn: string[]
15 tasksDone: number
16 tasksTotal: number
17 nextTask: NextTask | null
18}
19
20export type NextEpic = {
21 id: string
22 title: string
23 status: WorkStatus
24 storiesDone: number
25 storiesTotal: number
26 waitsOn: string[]
27}
28
29/** A spec in docs/specifications that no epic has been planned from yet. */
30export type NextSpec = { id: string; title: string; path: string }
31
32export type NextPlan = {
33 root: string
34 repo: string
35 /** Epics with work left, in number order. */
36 epics: NextEpic[]
37 /** Every story left, in recommended order of execution. */
38 order: NextStory[]
39 /** Specs with no epics yet, in number order. */
40 specs: NextSpec[]
41 signature: string
42}
43
44export type NextNote = { root: string; signature: string; text: string; at: number }
45
46declare module 'claude-code' {
47 interface PluginState {
48 'whats-next': {
49 plan: NextPlan | null
50 note: NextNote | null
51 isNoteBusy: boolean
52 noteError: string | null
53 }
54 }
55}
56