Keeps a cpm-next skill's frontmatter model and effort for every turn of its run, including your replies to its questions, and runs `do all` at high effort…

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.ts 164 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { ModelPin, PendingSkill } from '../types'
5import {
6 effortFor, effortStep, floorFor, isHeldSkill, isPersonsSwitch, isStoryEffort, overrideFor, parseFrontmatter,
7 pickInstall, resolveModel, skillFiles, skillName, slashCommand, statusText, storyStep,
8} from './pin'
9
10const STORY_TOOL = 'set_story_effort'
11
12const pin = atom({ plugin: 'cpm-next-models', key: 'pin' } as const, null)
13const pending = atom({ plugin: 'cpm-next-models', key: 'pending' } as const, null)
14
15async function setPin($: EngineInterface, value: ModelPin) {
16 await update($, pin, () => value)
17}
18
19async function release($: EngineInterface) {
20 await update($, pending, () => null)
21 await setPin($, null)
22}
23
24// A skill is seen by up to two events (the typed prompt, the Skill tool); the first one to name it sets
25// the pending skill and the other leaves it be.
26async function capture($: EngineInterface, name: string, args: string) {
27 const skill = skillName(name)
28 if (!isHeldSkill(skill)) return
29 const waiting: PendingSkill = await read($, pending)
30 if (waiting?.skill === skill) return
31 await update($, pending, () => ({ skill, args }))
32}
33
34// A built-in such as /cost has no file and leaves the hold alone; a plugin's command always has a prefix.
35async function isSkill($: EngineInterface, name: string) {
36 if (name.includes(':')) return true
37 const roots = [await $.session.root(), await $.env.get('HOME')].filter((r): r is string => typeof r === 'string')
38 for (const path of skillFiles(name, roots)) if (await $.fs.exists(path)) return true
39
40 return false
41}
42
43// The engine doesn't pass a skill's frontmatter effort on to the request, and passes its model only in the
44// Skill tool's result, so both are read from the installed SKILL.md.
45async function frontmatterOf($: EngineInterface, skill: string) {
46 try {
47 const home = await $.env.get('HOME')
48 const [plugin, name] = skill.split(':')
49 const installed = JSON.parse(await $.fs.read(`${home}/.claude/plugins/installed_plugins.json`)) as {
50 plugins?: Record<string, { scope?: string; projectPath?: string; installPath: string }[]>
51 }
52 const key = Object.keys(installed.plugins ?? {}).find(k => k.startsWith(`${plugin}@`))
53 const path = pickInstall(installed.plugins?.[key ?? ''] ?? [], await $.session.root())
54
55 return path === undefined ? {} : parseFrontmatter(await $.fs.read(`${path}/skills/${name}/SKILL.md`))
56 } catch {
57 return {}
58 }
59}
60
61export const register: Register = on => {
62 // classic.UserPromptExpansion and skill.prompt would serve here, but sec-default sends both past the user tier.
63 on('prompt.submit', async ($, e, next) => {
64 const typed = slashCommand(e.text)
65 if (typed === null) return next(e)
66 if (isHeldSkill(typed.skill)) await capture($, typed.skill, typed.args)
67 else if (await isSkill($, typed.skill)) await release($)
68
69 return next(e)
70 })
71
72 on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
73 if (isHeldSkill(skillName(e.skill))) await capture($, e.skill, e.args ?? '')
74 else await release($)
75
76 return next(e)
77 })
78
79 // Main loop only: subagents keep the model and effort their spawn chose.
80 on('turn.step', async function* ($, e, next) {
81 if (e.agentId !== undefined) return yield* next(e)
82
83 const waiting = await read($, pending)
84 if (waiting !== null) {
85 await update($, pending, () => null)
86 const found = await frontmatterOf($, waiting.skill)
87 const model = resolveModel(found.model, e.model)
88 const effort = effortFor(waiting.skill, waiting.args, found.effort ?? e.effort)
89 const floor = floorFor(waiting.skill, waiting.args)
90 await setPin($, { skill: waiting.skill, model, effort, turnId: e.turnId, ...(floor === undefined ? {} : { floor }) })
91 return yield* next({ ...e, model, effort })
92 }
93
94 const held = await read($, pin)
95 const stepped = effortStep(held, e.turnId, e.effort)
96 if (stepped.pin !== held) await setPin($, stepped.pin)
97 const model = overrideFor(held, e.model) ?? e.model
98
99 return yield* next({ ...e, model, effort: stepped.effort })
100 })
101
102 on('classic.PostModelSwitch', async ($, e, next) => {
103 if (isPersonsSwitch(e.source)) await release($)
104
105 return next(e)
106 })
107
108 on('session.end', async ($, e, next) => {
109 if (e.reason === 'clear') await release($)
110
111 return next(e)
112 })
113
114 on('session.start', async ($, e, next) => {
115 await $.command.register({ name: 'cpm-models', description: 'Show which cpm-next skill model and effort are held, or "off" to release them' })
116 await $.tool.register({
117 name: STORY_TOOL,
118 description: 'Sets the effort the current /cpm-next:do run builds at, for the story it is starting or the fix it is making. Changes nothing outside a do run, never goes below the run\'s floor, and leaves an effort the person set with /effort alone.',
119 inputSchema: {
120 type: 'object',
121 properties: {
122 effort: { type: 'string', enum: ['low', 'medium', 'high', 'xhigh'] },
123 story: { type: 'string', description: 'The story number, e.g. "3"' },
124 },
125 required: ['effort'],
126 },
127 })
128 // A status entry pinned by an earlier load outlives a reload; this mod draws in the footer instead.
129 $.ui.status(undefined)
130
131 return next(e)
132 })
133
134 // Drawn as one of the footer's mode labels, beside the session model that the status line keeps showing.
135 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
136 const label = statusText(await read($, pin))
137 if (label === undefined) return next(e)
138
139 return next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } })
140 })
141
142 // Unfiltered: a registered tool's name is not in the typed tool list until the mod has reloaded once.
143 on('tool.call', async ($, e, next) => {
144 if (String(e.tool) !== `mcp__cpm-next-models__${STORY_TOOL}`) return next(e)
145 const { effort, story } = e as unknown as { effort?: unknown; story?: unknown }
146 if (!isStoryEffort(effort)) return { deny: 'effort must be one of low, medium, high, xhigh.' }
147 const held = await read($, pin)
148 const step = storyStep(held, effort, typeof story === 'string' && story !== '' ? story : undefined)
149 if (step.pin !== held) await setPin($, step.pin)
150
151 return { result: step.text }
152 }).catch(($, e, next) => (next.called ? next(e) : { deny: `${STORY_TOOL} failed; build at the current effort.` }))
153
154 on('command.run', { command: 'cpm-models' }, async ($, e) => {
155 if (e.args.trim() === 'off') {
156 await release($)
157 return { text: 'Released: turns now run on the session model.' }
158 }
159 const held = await read($, pin)
160
161 return { text: held === null ? 'Nothing held: turns run on the session model.' : `Holding ${held.model}${held.effort === undefined ? '' : ` at ${held.effort} effort`} for ${held.skill}. "/cpm-models off" releases it.` }
162 })
163}
164hooks/pin.ts 126 lines1import type { Effort, ModelPin } from '../types'
2
3const PREFIX = 'cpm-next:'
4
5/** `/cpm-next:do` → `cpm-next:do`: slash expansions and the Skill tool spell the name differently. */
6export function skillName(name: string): string {
7 return name.replace(/^\//, '')
8}
9
10/** Whether a skill's model is held across turns: every cpm-next skill, so one without a model releases the last one's. */
11export function isHeldSkill(skill: string): boolean {
12 return skillName(skill).startsWith(PREFIX)
13}
14
15/**
16 * The effort to hold for a skill: `high` for an unattended `do all` run, where Sonnet tends to stop and
17 * check in at `medium`; otherwise the frontmatter's, as the engine resolved it for the skill's first request.
18 */
19export function effortFor(skill: string, args: string, resolved: Effort | undefined): Effort | undefined {
20 return floorFor(skill, args) ?? resolved
21}
22
23/** The lowest effort a story may set in this run: `high` for `do all`, so a `low` story can't bring back the check-ins. */
24export function floorFor(skill: string, args: string): Effort | undefined {
25 return skillName(skill) === 'cpm-next:do' && /^\s*all\b/i.test(args) ? 'high' : undefined
26}
27
28const STORY_LEVELS = ['low', 'medium', 'high', 'xhigh'] as const
29
30/** Whether a value is an effort a story may set: one of the four build levels. */
31export function isStoryEffort(value: unknown): value is (typeof STORY_LEVELS)[number] {
32 return typeof value === 'string' && (STORY_LEVELS as readonly string[]).includes(value)
33}
34
35/**
36 * The pin after `do` sets a story's effort, and what the tool tells the model. Only a `do` run's held effort
37 * changes, never below its floor; a person's `/effort` (which clears the held effort) is left to stand.
38 */
39export function storyStep(pin: ModelPin, effort: Effort, story: string | undefined): { pin: ModelPin; text: string } {
40 if (pin === null || pin.skill !== 'cpm-next:do') return { pin, text: 'No /cpm-next:do run is held; the session effort applies.' }
41 if (pin.effort === undefined) return { pin, text: 'The person set /effort during this run; their effort applies.' }
42 const floor = pin.floor
43 const level = floor !== undefined && rank(effort) < rank(floor) ? floor : effort
44 const next = { ...pin, effort: level, ...(story === undefined ? {} : { story }) }
45 const raised = level === effort ? '' : ` (raised from ${effort}: this run's floor is ${floor})`
46
47 return { pin: next, text: `Effort ${level}${raised}${story === undefined ? '' : ` for story ${story}`}.` }
48}
49
50const rank = (effort: Effort) => typeof effort === 'number' ? effort : LEVELS.indexOf(effort)
51
52/** The model a main-loop request should be sent on instead of `stepModel`, or undefined to leave it. */
53export function overrideFor(pin: ModelPin, stepModel: string): string | undefined {
54 return pin !== null && pin.model !== stepModel ? pin.model : undefined
55}
56
57/**
58 * The effort a main-loop request should carry, and the pin as it stands afterwards. Inside the skill's own
59 * turn the held effort applies. On the first request of a later turn the session's effort is recorded as the
60 * baseline; a later request whose effort differs from it means the person ran `/effort`, which wins.
61 */
62export function effortStep(pin: ModelPin, turnId: string, stepEffort: Effort | undefined): { effort: Effort | undefined; pin: ModelPin } {
63 if (pin === null || pin.effort === undefined) return { effort: stepEffort, pin }
64 if (turnId === pin.turnId) return { effort: pin.effort, pin }
65 if (pin.baseline === undefined) return { effort: pin.effort, pin: stepEffort === undefined ? pin : { ...pin, baseline: stepEffort } }
66 if (stepEffort !== pin.baseline) return { effort: stepEffort, pin: { ...pin, effort: undefined } }
67
68 return { effort: pin.effort, pin }
69}
70
71/** Whether a model switch is the person's own choice, which releases the hold; a fallback or resume does not. */
72export function isPersonsSwitch(source: string): boolean {
73 return source === 'command' || source === 'picker' || source === 'sdk'
74}
75
76/** `claude-sonnet-5-5` → `sonnet`; an id with no family name is shown whole. */
77export function familyOf(model: string): string {
78 return /opus|sonnet|haiku|fable/.exec(model)?.[0] ?? model
79}
80
81/** The footer label, e.g. "cpm-next:do · story 3 · sonnet · high"; undefined when nothing is held. */
82export function statusText(pin: ModelPin): string | undefined {
83 if (pin === null) return undefined
84 const story = pin.story === undefined ? '' : ` · story ${pin.story}`
85 const effort = pin.effort === undefined ? '' : ` · ${pin.effort}`
86
87 return `${pin.skill}${story} · ${familyOf(pin.model)}${effort}`
88}
89
90const LEVELS = ['low', 'medium', 'high', 'xhigh', 'max']
91
92/** The `model` and `effort` lines of a SKILL.md's frontmatter; absent keys, or an unknown effort, are left out. */
93export function parseFrontmatter(text: string): { model?: string; effort?: Effort } {
94 const block = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1]
95 if (block === undefined) return {}
96 const get = (key: string) => new RegExp(`^${key}:\\s*(\\S+)\\s*$`, 'm').exec(block)?.[1]
97 const effort = get('effort')
98
99 return { model: get('model'), effort: LEVELS.includes(effort ?? '') ? (effort as Effort) : undefined }
100}
101
102/** Where a typed name without a plugin prefix is defined, if it is a skill or custom command rather than a built-in. */
103export function skillFiles(name: string, roots: string[]): string[] {
104 return roots.flatMap(root => [`${root}/.claude/skills/${name}/SKILL.md`, `${root}/.claude/commands/${name}.md`])
105}
106
107/** `/cpm-next:do all` → `{ skill: 'cpm-next:do', args: 'all' }`; null for a prompt that isn't a slash command. */
108export function slashCommand(text: string): { skill: string; args: string } | null {
109 const found = /^\/([\w:-]+)(?:\s+([\s\S]*))?$/.exec(text.trim())
110
111 return found === null ? null : { skill: found[1] ?? '', args: found[2] ?? '' }
112}
113
114/** A frontmatter model as a request can name it: a bare family (`sonnet`) takes the session model's version. */
115export function resolveModel(requested: string | undefined, sessionModel: string): string {
116 if (requested === undefined || requested === 'inherit') return sessionModel
117 if (!/^(opus|sonnet|haiku|fable)$/.test(requested)) return requested
118
119 return sessionModel.replace(/opus|sonnet|haiku|fable/, requested)
120}
121
122/** Which install of a plugin the session runs: the project's own, else the user-scope one, else the first. */
123export function pickInstall(installs: { scope?: string; projectPath?: string; installPath: string }[], root: string): string | undefined {
124 return (installs.find(i => i.projectPath === root) ?? installs.find(i => i.scope === 'user') ?? installs[0])?.installPath
125}
126types/index.d.ts 28 lines1/** An effort level as a model request carries it. */
2export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max' | number
3
4/**
5 * The cpm-next skill whose model and effort are held; null when nothing is held.
6 * `turnId` is the turn the skill started in. `baseline` is the session's effort as first seen after that
7 * turn, so a later `/effort` shows up as a difference from it and releases the held effort.
8 * `floor` is the lowest effort a story may set (`high` in a `do all` run); `story` is the story `do` is building.
9 */
10export type ModelPin = {
11 skill: string
12 model: string
13 effort?: Effort
14 turnId: string
15 baseline?: Effort
16 floor?: Effort
17 story?: string
18} | null
19
20/** A cpm-next skill just invoked, with its arguments and, from the Skill tool, its frontmatter model. */
21export type PendingSkill = { skill: string; args: string; model?: string } | null
22
23declare module 'claude-code' {
24 interface PluginState {
25 'cpm-next-models': { pin: ModelPin; pending: PendingSkill }
26 }
27}
28