SLOPSHOPPER

kit

Minimal dev workflow: shape an idea into a markdown roadmap, build features, launch, commit, convert designs to code, plan and measure SEO.

panebandguardcommandtoastprompt
v0.15.24no licenseupdated 2026-10-17AirMile/claude-kit
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · kit
│ ┃ Dashboard ✕ › fix the failing auth test and add an audit log call │ ┃ │ ┃ [ ▤ Roadmap ] [ ◈ Messages ] [ ◎ Session ] ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ No docs/roadmap.md here. [ Make a roadmap ] ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ ╭────────────────────────────────────────── ⏺ Bash(bun test) │ ┃ │ ⎿ 3 pass, 1 fail │ ┃ │ Plan │ ┃ │ [ Setup ] [ Brainstorm ] [ Critique ] [ T ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ │ ┃ ╰────────────────────────────────────────── ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ › /panel │ ┃ ⎿ kit: Roadmap pane opened. │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ [ ctx 97k ] 5h 31% · NaNm [ Auto · Sonnet 5.5 · medium ♨ ] [ ⎇ Git ] [ ⚖ Ask ] [ ▤ Close ] ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
[ ctx 97k ] 5h 31% · NaNm [ Auto · Sonnet 5.5 · medium ♨ ] [ ⎇ Git ] [ ⚖ Ask ] [ ▤ Close ]
Pane · Dashboard
[ ▤ Roadmap ] [ ◈ Messages ] [ ◎ Session ] No docs/roadmap.md here. [ Make a roadmap ] ╭────────────────────────────────────────────────────────── │ │ Plan Make │ [ Setup ] [ Brainstorm ] [ Critique ] [ Theme ] [ Conve │ ╰──────────────────────────────────────────────────────────
Pane · kit-theme
Run /theme to preview a theme here.
README

kit

A small Claude Code plugin for building software with Claude. It covers the whole loop: shape an idea, turn it into a roadmap, build features one at a time (spec → code → independent verify → commit), fix bugs with discipline, and convert designs into code.

kit is the successor to claude-config v1. v1 grew to 42 skills, ~15k lines of shared instructions and its own state engine (JSON state files, a backlog server, checkpoints, a sync branch). Most of the friction came from that machinery, not from the actual work. kit keeps the workflow and drops the machinery: all state is plain markdown in your repo, and wherever Claude Code already has a native feature (plan mode, subagents, AGENTS.md loading, /simplify, /security-review) kit uses it instead of rebuilding it.

14 skills · 1 agent · 2 hooks + 1 mod (2 panes) · 3 scripts · ~1550 lines of skills · ~420 tokens always-on

Contents


Install

This repo is both the plugin and its marketplace (airmile). It's private, so installing needs a GitHub login that can read AirMile/claude-kit.

Any machine (installs a copy from GitHub):

claude plugin marketplace add AirMile/claude-kit
claude plugin install kit@airmile

Get updates later with claude plugin marketplace update airmile.

The machine you develop kit on (runs straight from your clone):

git clone https://github.com/AirMile/claude-kit ~/Projects/claude-kit
claude plugin marketplace add ~/Projects/claude-kit
claude plugin install kit@airmile

The install is a copy in ~/.claude/plugins/cache/airmile/kit/<version>/: edits in the clone take effect only after a version bump + update (see Update); /commit pushes them to GitHub.

Check with claude plugin details kit: it should list 14 skills, 1 agent and 2 hooks. Skills are available in new sessions; in a running session use /reload-plugins.

Skills are namespaced as /kit:<skill> (e.g. /kit:build). The bare name (/build) also works as long as no other skill or command uses it.

No CLAUDE.md in your projects

kit keeps project instructions in AGENTS.md, including nested ones per module. Claude Code (v2.1.277+) reads root and nested AGENTS.md files natively, but only when the project has no CLAUDE.md, .claude/CLAUDE.md or CLAUDE.local.md (docs: memory § AGENTS.md). So kit projects have none: /setup moves anything useful from an existing CLAUDE.md into AGENTS.md and removes it. Your personal ~/.claude/CLAUDE.md doesn't count and keeps working. Bonus: AGENTS.md is also read by other coding agents, so the project stays tool-agnostic.

Recommended: frontend rule

Plugins can't ship rules, so kit keeps a path-scoped rule in rules/frontend.md (simplest CSS first, use the project's tokens, check layout edits in the browser, edit pasted inspect refs in place). It loads only when Claude reads frontend files. Link it once per machine:

mkdir -p ~/.claude/rules
ln -sfn ~/Projects/claude-kit/rules/frontend.md ~/.claude/rules/frontend.md

On Windows, copy the file instead (symlinks need admin rights there).

Update / uninstall

  • Edits to this repo take effect only after you bump version in .claude-plugin/plugin.json, then claude plugin marketplace update airmile && claude plugin update kit@airmile and start a new session. Without the bump the cached copy stays as it was.
  • Try edits without installing: claude --plugin-dir ~/Projects/claude-kit.
  • Remove: claude plugin marketplace remove airmile (also uninstalls the plugin).

Codex

Codex reads the same marketplace (.claude-plugin/marketplace.json) and .codex-plugin/plugin.json, so one repo serves both tools at one version.

codex plugin marketplace add ~/Projects/claude-kit
codex plugin add kit@airmile
  • Trust the hooks once (and again after they change): Codex skips plugin hooks until you review them (docs: Hooks › Review and trust hooks). Until then push-guard is off in Codex.
  • What differs: the skills are worded for Claude Code. At session start a hook adds hooks/codex-context.md, which maps the Claude terms: questions become numbered options in chat, plan-mode approval becomes "plan shown, wait for your OK", the verifier runs as a subagent reading agents/verifier.md. No panes: /product prints the roadmap, /theme shows its table, Fresh start means /new then the build skill with the slug. The frontend rule is read from rules/frontend.md on UI work.
  • Projects are shared: AGENTS.md and docs/ are the same for both tools, so a spec started in Claude Code resumes in Codex and the other way around.
  • Update: bump version in both plugin.json files, then codex plugin add kit@airmile and start a new session.

Skill Feedback inbox

Friction points raised after a kit skill run (see /improve) go to ~/.agents/kit/feedback.md, one line per point, from both tools. Both need write access there once:

  • Codex (~/.codex/config.toml): writable_roots = ["/Users/<you>/.agents/kit"] (absolute) under [sandbox_workspace_write].
  • Claude Code (~/.claude/settings.json): allow Edit(~/.agents/kit/**).

No access → the point is shown in chat with a note that it wasn't saved.


Quick start

A brand-new idea

/setup a habit tracker for people who quit after a week
                  → /product interview, scaffold, AGENTS.md
                    (started outside a project? it makes the folder first)
/build             → builds the first roadmap item
/build             → and the next one …

An existing repo

/setup            → reads the repo, writes AGENTS.md + docs/
/product             → writes docs/product.md and the roadmap from a short interview
/build <slug>

A quick change: no skill needed. Ask for it in plain words (auto mode is fine), then:

/commit

AGENTS.md and the frontend rule load in every chat, so a plain request still follows the project's conventions. Use /build once it's a real feature or a bug whose cause isn't obvious: that's where the spec, the independent verify and resuming in a new chat pay for themselves.

A bug

/build "fix: saving a habit twice creates a duplicate"

Going live

/launch

A design

/convert https://figma.com/design/<file>/<name>?node-id=12-34 app/pricing/page.tsx

Core idea: your repo is the state

kit has no database, no JSON state, no background server and no checkpoint files. Everything a skill needs to know lives in a handful of markdown files committed to your repo:

  • They sync between your machines through git, like the rest of your code.
  • A new chat can pick up any interrupted work by reading them (/build <slug> resumes from the spec's Status: line and its checkboxes).
  • You can read and edit them by hand. Each file starts with a <!-- format: … --> header that describes its own format, so skills (and you) never need a separate schema document.

Two rules keep them small:

  1. Only write down what can't be derived from the code. Architecture summaries and file lists go stale; Claude can always re-read the code. Decisions, intent, pitfalls and conventions can't be re-derived, so those are what kit records.
  2. Every file has one owner skill that knows its format (listed below).

Files kit maintains in your project

your-project/
├── AGENTS.md              instructions: commands, conventions, pitfalls (≤100 lines)
├── .worktreeinclude       gitignored files (.env …) copied into new worktree sessions
├── src/payments/AGENTS.md module-specific pitfalls, loaded only when Claude works there
└── docs/
    ├── product.md            what, for whom, why, non-goals, stack
    ├── roadmap.md         ordered features = the backlog
    ├── decisions.md       decisions + the alternative that was rejected
    ├── seo.md             intake answers, search terms, page plan, measurements (SEO work)
    └── specs/
        └── <slug>.md      one per feature: criteria, status, verify result, later fixes
FileWritten byRead byLoaded into context
AGENTS.md (root)/setup, lessonsevery sessionalways, at session start
<dir>/AGENTS.mdlessonsevery sessionlazily, when Claude reads a file in that dir
docs/product.md/product/build, /convert, /setupon demand
docs/roadmap.md/product, /build/buildon demand
docs/specs/<slug>.md/build/build, verifieron demand
docs/decisions.md/build, /setup/buildon demand
docs/seo.md/scan, /intake, /seo/seo, /build, /audit, /launchon demand

AGENTS.md

The one instruction file Claude Code reads every session. AGENTS.md is also understood by other coding agents (Codex, Cursor, …), so your project stays tool-agnostic. Template:

# my-app

Habit tracker PWA for people who drop habits after a week.

## Commands

- Dev: `pnpm dev` → http://localhost:5173
- Test: `pnpm test` (single file: `pnpm test src/habits.test.ts`)
- Lint / typecheck: `pnpm lint && pnpm typecheck`
- Build: `pnpm build`

## Conventions

- Dates are stored as ISO strings in UTC; convert only in the view layer.

## Pitfalls

- Service worker caches /api in dev too: hard-reload after changing API responses.

## Git

- Workflow: branches
- Fresh worktree: `pnpm install` before anything else

## Docs

- Product intent: `docs/product.md` · roadmap: `docs/roadmap.md` · specs: `docs/specs/`
- Decisions and why: `docs/decisions.md`

The Commands section matters: /build and the verifier use the dev command and port from it to run browser checks.

Nested AGENTS.md files hold pitfalls that only matter in one module. Because they load only when Claude touches that directory, they cost nothing the rest of the time.

docs/product.md

Product intent, under ~60 lines. Sections: What, For whom, Why now, Core experience, Non-goals, Stack, Open questions. /build reads the non-goals before defining a feature, so scope creep is caught early.

docs/roadmap.md

The backlog. One line per item, order = priority:

# Roadmap

- [x] **scaffold** · project skeleton, dev server, test runner · spec: docs/specs/scaffold.md
- [ ] **habit-crud** · create, edit, delete habits · spec: docs/specs/habit-crud.md
- [ ] **streaks** · show current and best streak per habit
- [ ] **reminders** · daily push reminder at a chosen time

## Later

- sharing streaks with a friend

The three states are encoded in the line itself:

LineMeaning
- [ ] slug · descriptionopen, not started
- [ ] slug · description · spec: docs/specs/slug.mdin progress (spec exists)
- [x] slug · description · spec: …done

## Later holds unordered ideas that are not in the flow yet.

docs/specs/\<slug\>.md

Created by /build when you approve a feature plan. It is both the contract and the resume point:

# habit-crud

Status: building
Design: —

## Goal

Users can create, rename and delete habits; the list survives a reload.

## Acceptance criteria

- [x] Happy: adding "Read 10 pages" shows it at the top of the list
- [ ] Edge: an empty or whitespace-only name is rejected with an inline message
- [ ] Error: when storage is full, the user sees "Couldn't save" and the form keeps its input

## Out of scope

- Reordering habits

## Approach

- src/habits/store.ts (new): load/save to IndexedDB
- src/habits/HabitForm.tsx (new) …

## Tests

- src/habits/store.test.ts → happy, error
- browser: empty-name message visible

## Handoff

- Store keeps names trimmed; the form shows the raw input (user asked for that)

## Verify

<auto result, manual items and their outcome>

## Fixes

<later bugfixes: date · symptom · cause · fix>

Status moves defined → building → verifying → manual → done. A criterion is checked only when it is built and verified.

docs/decisions.md

Newest first; one block per decision where an alternative was genuinely rejected:

## 2026-10-01 · Store habits in IndexedDB, not localStorage

Why: needs >5 MB for history · Rejected: localStorage (size cap, sync API blocks UI) · Superseded by: —

This is the part of "architecture" that can't be re-derived from the code: why it is the way it is.


Skills

/product

Turn an idea into docs/product.md + docs/roadmap.md, or update them later.

/product <idea>          new project (when docs/product.md doesn't exist)
/product add <item>      update: add, reorder, remove or reword roadmap items
/product critique        stress-test product.md and the roadmap, then offer edits
/product brainstorm      find new features, then pick which go on the roadmap

New

  1. Takes your idea (or asks one open question).
  2. Enters plan mode: the draft product.md and roadmap are what you approve.
  3. Runs 1–3 rounds of clickable questions (audience, MVP size, core experience, stack, then gaps). Vision and naming are asked as open questions; visual choices are shown as small mocks; competing designs get a trade-off table first.
  4. Shows both files in the plan, and the draft roadmap in the roadmap pane. Accept writes them; reject revises.

Roadmap rules: every item is a user-visible capability buildable in one /build run (≤ ~6 acceptance criteria, otherwise split); dependencies first, then value; greenfield projects start with a scaffold item; 5–15 items for an MVP, the rest under ## Later.

Update finds the right position for a new item, checks it against the product's non-goals (conflict → asks whether the non-goal changes or the item is dropped), never touches done or in-progress items, and shows a diff before writing.

Critique and Brainstorm run one technique at a time as a dialogue. You pick a technique from 2-3 ranked for this product (critique: pre-mortem, assumption test, smaller version, audience, core loop, ...; brainstorm: what if, reversal, SCAMPER, role play, journey gaps, ...). Each round asks 4-6 questions anchored in your product.md and roadmap, plus concrete starting points; a summary follows, then another technique or the finish. Critique ends with edits to product.md and the roadmap, Brainstorm with a pick list of new items (phase or ## Later); both apply through Update, so nothing changes without your OK.

/setup

Make a project kit-ready. Idempotent: running it again only fills gaps.

It detects one of five situations:

SituationWhat happens
Not in a project (home folder, or a folder of projects)New folder: asks the name, creates the folder + git init, moves the session there; send /setup again
Empty folder, no docs/product.mdProduct first: runs the /product interview, then scaffolds
Empty folder, docs/product.md existsScaffold: runs the stack's official generator, adds a test runner, boots the dev server once, then onboards
A v1 project (.project/, no docs/roadmap.md yet)Migrate (below)
Any other existing codeOnboard

Onboard reads the manifest, scripts, test/lint config and recent git history, then:

  • writes AGENTS.md from the template, with only verified facts (no placeholders);
  • moves useful content from an existing CLAUDE.md into AGENTS.md and removes the CLAUDE.md (otherwise AGENTS.md wouldn't load);
  • creates docs/roadmap.md and docs/decisions.md with their format headers (never overwrites);
  • makes sure AGENTS.md and docs/ are not in .gitignore, and ignores .claude/worktrees/;
  • asks the git mode and prepares parallel sessions (.worktreeinclude, autoPort, database line).

Migrate (v1 → kit) moves the durable parts of v1's state and leaves .project/ untouched so you can delete it when satisfied:

v1 sourcekit destination
Generated CLAUDE.mdreal rules/runbooks/pitfalls → AGENTS.md; template sections dropped
AGENTS.md symlinked to CLAUDE.mdreplaced by a real file
.project/project-seed.mddocs/product.md
.project/backlog.json (unshipped, board order)docs/roadmap.md
.project/project-context.json learnings≤ ~15 non-derivable ones → root or nested AGENTS.md

You get a preview and one confirmation before anything is written. /setup never commits; it offers /commit.

/build

For features and real bugs. It keeps feature progress in the spec so any new chat can resume. Small changes don't need it; if it gets one anyway, it takes a light path.

/build                         resume the in-progress item, else start the next roadmap item
/build <slug>                  start or resume that feature
/build "make X do Y"           small change or feature, decided by the size gate
/build "fix: X is broken"      bugfix via the debug ladder
Routing
InputPath
slug with an existing specResume at the step matching Status
slug on the roadmap, no specFeature
no argumentin-progress roadmap item → Resume; else first open item → Feature
text describing a bugFix
other textsize gate → Small or Feature

Size gate. A change is Small only if none of these hold:

  1. It adds a capability (new page, route, endpoint, model, migration).
  2. It touches more than 3 source files.
  3. It needs a new test file or harness.
  4. It changes a shared layer used by more than 2 modules, or is a cross-cutting rename.

The gate is re-checked while working: as soon as the real scope crosses a line, /build stops, tells you, and switches to the Feature path with a spec for what's left.

Small path

Make the change → scoped tests/lint → a screenshot check if it's UI → lessons if something surprising came up → /commit.

Fix path (debug ladder)

Effort scales with how well the cause is understood, judged from observable signals, never from "confidence":

TierWhenWhat
1 Directcause and symptom both visible; a known value; 1–2 fileschange it, re-check live
2 Hypothesissymptom clear, cause unprovenreproduce → write the hypothesis and what evidence would confirm it → gather that evidence → fix the proven cause
3 Investigatespans modules, intermittent, or a lower tier failedan Explore subagent traces the causal chain with path:line evidence; the fix is presented as a plan first

Hard rule: every failed fix moves up one tier. The same fix is never retried without new evidence. The fix is done only when the reproduction passes (test green or you confirm it live). It's logged in the feature's spec under ## Fixes and committed as fix:.

Feature path
  1. Define (plan mode). Reads docs/product.md (non-goals!), decisions, the roadmap line and the code it touches. Asks only what it can't answer itself (usually 0–3 questions). Drafts the spec: criteria split into happy / edge / error, the approach with files, an ASCII wireframe for UI, and which test covers which criterion. More than 6 criteria → it proposes a split. It also flags roadmap items this feature makes obsolete. Accept writes docs/specs/<slug>.md, links it from the roadmap line (= in progress) and records real decisions in docs/decisions.md. Then the safe point: Continue here, or Fresh start, which drops the exploration and keeps the spec: the mod clears the chat after that turn and runs /build <slug> in the fresh one (without the mod: /clear, then /build <slug> yourself). Or stop early: Stop here keeps just the spec, Build, then stop builds and leaves verify for later (Status: verifying, changes uncommitted until Finish). /build <slug> or the roadmap pane picks it up at that step. The kit mod shows your context % above the prompt to help you choose.
  2. Build (inline). Test first where testable, then code, following AGENTS.md. If the spec has a Design: source, the UI is built with the
Source 27 files
hooks/register.tsx 165 lines
1import type {
2  EngineInterface,
3  Register,
4  SessionMessage,
5  SessionUsage,
6} from "claude-code";
7
8import { autoModel, modeCommand } from "./auto-model";
9import { freshStart, freshTool } from "./fresh-start";
10import { noteCompact, noteFile, resetChat } from "./chat-facts";
11import { bandCommand, bandUsage, kitBand } from "./kit-band";
12import { warmCommand } from "./keep-warm";
13import { noteLimits } from "./limit-guard";
14import { panelCommand, roadmapOpen, roadmapTool } from "./roadmap-open";
15import {
16  roadmapEdited,
17  roadmapStale,
18  roadmapView,
19} from "./roadmap-view";
20import type { Usage } from "./roadmap-parts";
21import { branchSlug, inRoot, parseSpec, type SpecState } from "./spec";
22import { themeTool, themeView } from "./theme-view";
23
24// kit's context mod. Reads the active spec (slug from the feat/ or fix/ branch); never writes.
25// - After a compaction: appends the spec's state, so the next turn re-reads it from disk.
26// - Context and plan limits as the band's second line (kit-band.tsx).
27// - The roadmap and theme panes: tools the skills call with data (roadmap-view, theme-view);
28//   the roadmap pane also opens on /panel (roadmap-open) and the band's button (kit-band).
29// - Model and effort picked per prompt and per subagent from a profile (auto-model), chosen
30//   in the band above the prompt or with /mode.
31// - A pause before the plan limit runs out, with the cache kept warm until the reset
32//   (limit-guard), and keep warm by hand for an idle chat (keep-warm, the band, /warm).
33// - fresh_start: /build's safe point clears the chat and resumes (fresh-start).
34
35type Spec = SpecState & { slug: string };
36type Figures = Pick<SessionUsage, "context" | "rateLimits">;
37type Meter = Usage;
38
39const SPEC_PATH = /docs\/specs\/[^/]+\.md$/;
40
41let meters: Meter[] = [];
42
43async function activeSpec($: EngineInterface): Promise<Spec | null> {
44  const git = await $.process
45    .run(["git", "symbolic-ref", "--short", "HEAD"], {
46      cwd: await $.session.root(),
47    })
48    .catch(() => null);
49  const slug = git?.exitCode === 0 ? branchSlug(git.stdout) : null;
50  const text = slug
51    ? await $.fs
52        .read(inRoot(await $.session.root(), `docs/specs/${slug}.md`))
53        .catch(() => null)
54    : null;
55  const state = parseSpec(text);
56  return slug && state ? { slug, ...state } : null;
57}
58
59function untilReset(iso: string | undefined, now: number): string {
60  const min = iso
61    ? Math.max(0, Math.round((Date.parse(iso) - now) / 60000))
62    : 0;
63  const [d, h, m] = [
64    Math.floor(min / 1440),
65    Math.floor(min / 60) % 24,
66    min % 60,
67  ];
68  return d ? `${d}d ${h}h` : h ? `${h}h ${m}m` : `${m}m`;
69}
70
71async function refresh($: EngineInterface, figures?: Figures) {
72  const usage = figures ?? (await $.session.usage());
73  const pct = usage.context.percent;
74  const now = await $.clock.now();
75  meters = [
76    {
77      label: "ctx",
78      pct: pct ?? 0,
79      value: `${Math.round((usage.context.tokens ?? 0) / 1000)}k`,
80    },
81  ];
82  for (const [kind, label] of [
83    ["five_hour", "5h"],
84    ["seven_day", "7d"],
85  ] as const) {
86    const rl = usage.rateLimits.find((r) => r.kind === kind);
87    if (rl)
88      meters.push({
89        label,
90        value: `${Math.round(rl.percentUsed)}%`,
91        pct: rl.percentUsed,
92        note: untilReset(rl.resetsAt, now),
93      });
94  }
95  bandUsage(meters);
96  $.ui.invalidate("ui.render");
97}
98
99export const register: Register = (on) => {
100  roadmapView(on);
101  roadmapOpen(on);
102  themeView(on);
103  freshStart(on);
104  autoModel(on);
105  kitBand(on);
106
107  on("session.start", async ($, e, next) => {
108    const started = await next(e);
109    await $.tool.register(roadmapTool);
110    await $.tool.register(themeTool);
111    await $.tool.register(freshTool);
112    await $.command.register(panelCommand);
113    await $.command.register(modeCommand);
114    await $.command.register(warmCommand);
115    await $.command.register(bandCommand);
116    await refresh($);
117    return started;
118  });
119
120  // A /clear fires no session.start or measure until the next turn: drop the old context
121  // figure now, or the dashboard keeps showing it in the fresh chat.
122  on("session.end", async ($, e, next) => {
123    if (e.reason === "clear") {
124      resetChat();
125      meters = meters.filter((m) => m.label !== "ctx");
126      bandUsage(meters);
127      $.ui.invalidate("ui.render");
128    }
129    return next(e);
130  });
131
132  on("session.measure", async ($, e, next) => {
133    roadmapStale(); // the pane reloads git and specs on its next draw
134    await refresh($, e);
135    await noteLimits($, e.rateLimits);
136    return next(e);
137  });
138
139  on("tool.call", { tool: ["Edit", "Write"] }, async ($, e, next) => {
140    const ran = await next(e);
141    if (!e.agentId) noteFile(e.file_path);
142    if (SPEC_PATH.test(e.file_path.replace(/\\/g, "/"))) await refresh($);
143    if (roadmapEdited(e.file_path)) $.ui.invalidate("ui.render");
144    return ran;
145  });
146
147  on("session.compact", async ($, e, next) => {
148    const compacted = await next(e);
149    if (e.trigger === "precompute" || e.agentId || !compacted.messages)
150      return compacted;
151    noteCompact();
152    const now = await activeSpec($);
153    if (!now) return compacted;
154    const note: SessionMessage = {
155      role: "user",
156      toolUses: [],
157      text:
158        `kit: building ${now.slug} · Status: ${now.status} · criteria ${now.done}/${now.total}. ` +
159        `Re-read docs/specs/${now.slug}.md (## Handoff first) before continuing; ` +
160        `if the /build procedure is no longer in context, run /build ${now.slug}.`,
161    };
162    return { ...compacted, messages: [...compacted.messages, note] };
163  });
164};
165
hooks/auto-model.ts 316 lines
1import type { CommandSpec, EngineInterface, On } from "claude-code";
2
3import { agentCalls, askedEffort } from "./agent-effort";
4import { limitPrompt, limitStep } from "./limit-guard";
5import {
6  agentKind,
7  carry,
8  commandKind,
9  DEFAULT_MODE,
10  displayName,
11  type Effort,
12  escalation,
13  family,
14  isMode,
15  type Kind,
16  kindOfLabel,
17  LABELS,
18  type Mode,
19  pick,
20  profileName,
21  PROFILES,
22  stretch,
23  subagentEffort,
24} from "./model-policy";
25import {
26  askFirstModel,
27  dropSwitch,
28  effortLock,
29  override,
30  reset,
31  restoreSwitch,
32  running,
33  switchTo,
34} from "./model-switch";
35import { noteAgent } from "./chat-facts";
36import { isOrchestrating, orchestrateNote } from "./orchestrate";
37
38// Picks model and effort before the model runs (it cannot change its own turn's effort):
39// - the first prompt of a chat (a new session or after /clear) picks a model from the profile,
40//   before the prompt is sent; when it differs from the session's, the user is asked to
41//   switch or stay, and a switch rewrites every main request;
42// - every prompt picks the effort (a short reply like "ja" keeps the kind of work it continues);
43//   a later prompt that needs a stronger model than the one running escalates (model-policy.ts
44//   `escalation`, `escalate` below): never a switch without asking;
45// - a subagent the engine defines gets its own model and effort for its task, unless its Agent
46//   call asked for an effort (agent-effort.ts).
47// The profile (lean, balanced, quality, off) is kept in $.store across sessions, a switch per
48// session id, so a mod reload or restart keeps it.
49
50export const modeCommand: CommandSpec = {
51  name: "mode",
52  description:
53    "Pick kit's model/effort profile: lean, balanced, quality or off",
54  argumentHint: "[lean|balanced|quality|off]",
55  immediate: true,
56};
57
58const STORE_KEY = "mode";
59const CLASSIFY_CHARS = 4000;
60
61let mode: Mode | undefined; // read from $.store on first use
62let decided = false; // the session's model question was settled
63let kept: "agent" | "stay" | undefined; // how this chat goes on when a prompt needs a far stronger model
64let escalated: string | undefined; // the subagent note for the prompt being sent
65let effort: Effort | undefined; // the effort for the current prompt's requests
66let lastKind: Kind | undefined; // the kind of work the last typed prompt ran as
67const agentEffort = new Map<string, Effort>(); // subagent id → its effort
68
69export async function getMode($: EngineInterface): Promise<Mode> {
70  if (mode === undefined) {
71    const stored = await $.store.get(STORE_KEY).catch(() => undefined);
72    mode = isMode(stored) ? stored : DEFAULT_MODE;
73  }
74  return mode;
75}
76
77export async function setMode($: EngineInterface, next: Mode) {
78  mode = next;
79  await $.store.set(STORE_KEY, next).catch(() => {});
80  if (next === "off") {
81    dropSwitch(false);
82    effort = undefined;
83  }
84  await showStatus($);
85  $.ui.invalidate("ui.render");
86}
87
88async function kindOf(
89  $: EngineInterface,
90  text: string,
91): Promise<Kind | undefined> {
92  const known = commandKind(text);
93  if (known) return known;
94  const label = await $.model
95    .classify(text.slice(0, CLASSIFY_CHARS), Object.values(LABELS), {
96      model: "haiku",
97    })
98    .catch(() => undefined);
99  return kindOfLabel(label);
100}
101
102// What the band shows: whether kit picks (auto), the model main requests really go to (the
103// picker keeps the session's) and the effort they run at: kit's pick, or with the profile off
104// the band's effort (undefined: the session's own).
105export async function runState($: EngineInterface) {
106  const auto = (await getMode($)) !== "off";
107  return {
108    auto,
109    model: await running($),
110    effort: auto ? effort : await effortLock($),
111  };
112}
113
114async function showStatus($: EngineInterface) {
115  $.ui.invalidate("ui.render");
116}
117
118type Way = "agent" | "now" | "compact" | "clear" | "stay";
119
120// What a later prompt that needs `want`, above the model running, does. One tier short it runs at
121// the stretch effort. Further short the user picks, none marked as recommended: a subagent on
122// `want` for the hard part (the chat keeps its model and cache), switch now (light context only: a switch reads the whole
123// chat again without the cache), compact or clear and then switch and send it again, or stay at
124// the stretch effort. A subagent or stay holds for the rest of the chat, without asking again.
125// Returns why the prompt is held (`drop`) or a note that rides along with it.
126async function escalate(
127  $: EngineInterface,
128  text: string,
129  want: string,
130  mayAsk: boolean,
131): Promise<{ drop?: string; note?: string }> {
132  const have = await running($);
133  const usage = await $.session.usage().catch(() => undefined);
134  const step = escalation(have, want, usage?.context?.percent);
135  if (step.step === "none") return {};
136  if (step.step === "effort" || kept === "stay" || !mayAsk) {
137    effort = stretch(have);
138    return {};
139  }
140  const to = displayName(step.want);
141  const from = displayName(have);
142  const note = `kit: this prompt needs ${to}; ${from} runs this chat. Hand its hard part (the diagnosis, the design, the tricky change) to a subagent with the Agent tool, model "${family(step.want)}": give it the goal, the constraints and the relevant files, then carry out its answer here. Do the rest yourself.`;
143  if (kept === "agent") return { note };
144  const ways = new Map<string, Way>();
145  ways.set(`Ask a ${to} subagent`, "agent");
146  // A question holds four options: with a light context a switch now beats compacting first.
147  if (step.switchNow) ways.set(`Switch to ${to} now`, "now");
148  else ways.set(`Compact, then ${to}`, "compact");
149  ways.set(`Clear, then ${to}`, "clear");
150  ways.set(`Stay on ${from} at ${stretch(have)} effort`, "stay");
151  const answer = await $.ui
152    .ask(`This prompt needs ${to}; ${from} is running. How to go on?`, {
153      header: "Model",
154      options: [...ways.keys()],
155    })
156    .catch(() => undefined);
157  const way = (answer !== undefined && ways.get(answer)) || "stay";
158  if (way === "agent") {
159    kept = "agent";
160    return { note };
161  }
162  if (way === "now") {
163    await switchTo($, step.want);
164    return {};
165  }
166  if (way === "stay") {
167    kept = "stay";
168    effort = stretch(have);
169    return {};
170  }
171  const level = effort;
172  // Outside the hook: a clear or compact rejects inside the hook the prompt waits on.
173  $.clock.after(300, () => resend($, way, step.want, text, level));
174  return {
175    drop: `kit: ${way === "clear" ? "clearing" : "compacting"}, then ${to} runs your prompt`,
176  };
177}
178
179// Clears or compacts, switches to `want` and sends the held prompt again. On a failure the
180// prompt goes back into the input box, so nothing typed is lost.
181async function resend(
182  $: EngineInterface,
183  way: "compact" | "clear",
184  want: string,
185  text: string,
186  level: Effort | undefined,
187) {
188  if (!(await reset($, way))) {
189    await $.prompt.fill({ text }).catch(() => {}); // the prompt is back in the input box
190    return;
191  }
192  decided = true;
193  await switchTo($, want);
194  effort = level;
195  await showStatus($);
196  await $.prompt.submit({ text, asUser: true }).catch(async (err) => {
197    $.ui.toast(`kit: could not send your prompt (${String(err)})`);
198    await $.prompt.fill({ text }).catch(() => {});
199  });
200}
201
202export function autoModel(on: On) {
203  // A new chat (startup or /clear) asks again; a resume keeps the model it ran on.
204  on(
205    "classic.SessionStart",
206    { source: /^(startup|clear)$/ },
207    async ($, e, next) => {
208      const started = await next(e);
209      if (e.agent_type) return started;
210      decided = false;
211      kept = undefined;
212      dropSwitch(true); // a new chat: nothing stored to pick up
213      effort = undefined;
214      lastKind = undefined;
215      agentEffort.clear();
216      await showStatus($);
217      return started;
218    },
219  );
220
221  on("prompt.submit", async ($, e, next) => {
222    const held = await limitPrompt($, e.text);
223    if (held) {
224      $.ui.toast(held, { timeoutMs: 10_000 });
225      return { drop: held };
226    }
227    const now = await getMode($);
228    const typed = e.origin.kind === "composer" || e.origin.kind === "bridge";
229    const orchestrating = typed && (await isOrchestrating($));
230    if (!typed || (now === "off" && !orchestrating)) return next(e);
231    const kind = (await kindOf($, e.text)) ?? "routine";
232    if (now !== "off") {
233      // A command's kind is explicit; a thin reply keeps the work's kind.
234      const ran = commandKind(e.text) ? kind : carry(kind, lastKind, e.text);
235      lastKind = ran;
236      const p = pick(now, ran);
237      if (await restoreSwitch($)) decided = true; // a reload kept the switch
238      let asked = false;
239      if (!decided) {
240        decided = true;
241        // An orchestrator keeps its model: handing work off is what makes it cheaper.
242        asked = !orchestrating && (await askFirstModel($, p.model));
243      }
244      effort = p.effort;
245      // The first prompt's question just settled the model: no second one for it.
246      const step = await escalate($, e.text, p.model, !asked);
247      await showStatus($);
248      if (step.drop) {
249        $.ui.toast(step.drop, { timeoutMs: 10_000 });
250        return { drop: step.drop };
251      }
252      if (step.note) escalated = step.note;
253    }
254    // Orchestrate (the band's ⑂): a note for this kind of work rides along with the prompt.
255    const notes = [
256      escalated,
257      orchestrating ? orchestrateNote(kind) : undefined,
258    ].filter((n): n is string => n !== undefined);
259    escalated = undefined;
260    return next(
261      notes.length ? { ...e, context: [...(e.context ?? []), ...notes] } : e,
262    );
263  });
264
265  // A streaming event: the hook is a generator that forwards the chunks beneath.
266  on("turn.step", async function* ($, e, next) {
267    const stopped = await limitStep($, e); // the plan limit is nearly used up
268    if (stopped) return stopped;
269    let step = e;
270    const isOn = (await getMode($)) !== "off";
271    if (e.agentId) {
272      const own = agentEffort.get(e.agentId);
273      if (isOn && own && e.effort !== undefined) step = { ...e, effort: own };
274    } else {
275      // Auto picks the effort; with the profile off the band's effort holds, if one is set.
276      const model = isOn ? ((await override($)) ?? e.model) : e.model;
277      const want = isOn ? effort : await effortLock($);
278      const level = want && e.effort !== undefined ? want : e.effort;
279      step = { ...e, model, effort: level };
280    }
281    return yield* next(step);
282  });
283
284  on("agent.spawn", async ($, e, next) => {
285    noteAgent(e.subagentType);
286    const now = await getMode($);
287    if (now === "off" || e.fork) return next(e);
288    const isEngine = e.provider.plugin === "engine";
289    const known = agentKind(e.subagentType);
290    // A plugin's or user's agent keeps its own definition unless kit knows its work.
291    if (!isEngine && !known) return next(e);
292    const kind = known ?? (await kindOf($, e.prompt)) ?? "routine";
293    const p = pick(now, kind);
294    const spawned = await next(
295      isEngine && !e.model ? { ...e, model: p.model } : e,
296    );
297    const own = subagentEffort(askedEffort(e.tool_use_id), p.effort);
298    if (spawned.agentId && own) agentEffort.set(spawned.agentId, own);
299    return spawned;
300  });
301
302  agentCalls(on);
303
304  on("command.run", { command: "mode" }, async ($, e) => {
305    const arg = e.args.trim().toLowerCase();
306    if (isMode(arg)) {
307      await setMode($, arg);
308      return { text: `kit profile: ${profileName(arg)}.` };
309    }
310    const now = await getMode($);
311    return {
312      text: `kit profile: ${profileName(now)}. Pick one: /mode ${[...PROFILES, "off"].join("|")}`,
313    };
314  });
315}
316
hooks/fresh-start.ts 66 lines
1import type { On, ToolSpec } from "claude-code";
2
3// /build's safe point, automated: the model calls fresh_start after the user picked
4// "Fresh start"; when that turn ends, the chat clears and /kit:build <slug> resumes from the
5// spec in the fresh one. Same chain as the roadmap pane's Pick up, but run from turn.complete.
6
7const TOOL = "mcp__kit__fresh_start";
8const SLUG = /^[a-z0-9][a-z0-9-]*$/;
9
10let armed: string | null = null;
11
12export const freshTool: ToolSpec = {
13  name: "fresh_start",
14  description:
15    "kit /build safe point: after this turn ends, clear the chat and run /kit:build <slug> " +
16    "in the fresh one. Call it only after the user chose Fresh start, then end the turn.",
17  inputSchema: {
18    type: "object",
19    properties: { slug: { type: "string" } },
20    required: ["slug"],
21  },
22};
23
24export function freshStart(on: On) {
25  on("tool.check", { tool: TOOL }, () => ({ decision: "allow" }));
26
27  on("tool.call", { tool: TOOL }, async (_$, e) => {
28    const slug = String((e as unknown as { slug?: unknown }).slug ?? "");
29    if (!SLUG.test(slug))
30      return { result: `Not armed: invalid slug "${slug}".` };
31    armed = slug;
32    return {
33      result: `Armed: when this turn ends, the chat clears and /kit:build ${slug} starts. End the turn now.`,
34    };
35  });
36
37  on("turn.complete", async ($, e, next) => {
38    const done = await next(e);
39    if (!armed || e.agentId) return done;
40    const slug = armed;
41    armed = null;
42    if (e.reason !== "answer") {
43      $.ui.toast(`kit: fresh start for ${slug} cancelled`);
44      return done;
45    }
46    // Outside the hook: $.command.run rejects inside a hook the turn waits on.
47    $.clock.after(300, async () => {
48      try {
49        await $.command.run({ command: "clear" });
50      } catch (err) {
51        // Building on in this same chat would defeat the point: leave it to the user.
52        $.ui.toast(
53          `kit: could not clear (${String(err)}). Run /clear, then /build ${slug}`,
54        );
55        return;
56      }
57      await $.command
58        .run({ command: "kit:build", args: slug })
59        .catch((err) =>
60          $.ui.toast(`kit: could not start /build ${slug}: ${String(err)}`),
61        );
62    });
63    return done;
64  });
65}
66
hooks/chat-facts.ts 95 lines
1import type { EngineInterface } from "claude-code";
2
3import { runState } from "./auto-model";
4import type { Chat, Excerpt } from "./roadmap-parts";
5
6// What the roadmap pane's Chat tab shows. register.tsx and auto-model.ts note what this chat
7// touched (files written or edited, subagents, compactions) as it happens, so it counts from
8// when the mod loaded; a /clear starts over.
9
10const files = new Set<string>();
11const agents = new Map<string, number>();
12let compactions = 0;
13
14export function noteFile(path: string) {
15  files.add(path.replace(/\\/g, "/"));
16}
17
18export function noteAgent(type: string) {
19  agents.set(type, (agents.get(type) ?? 0) + 1);
20}
21
22export function noteCompact() {
23  compactions += 1;
24}
25
26export function resetChat() {
27  files.clear();
28  agents.clear();
29  compactions = 0;
30}
31
32// The run, the session's usage (the context by category, as /context estimates it) and
33// what this chat touched, paths relative to the project.
34export async function readChat($: EngineInterface): Promise<Chat> {
35  const run = await runState($);
36  const usage = await $.session
37    .usage({ breakdown: "summary" })
38    .catch(() => undefined);
39  const b = usage?.context.breakdown;
40  const root = (await $.session.root().catch(() => "")).replace(/\\/g, "/");
41  const now = await $.clock.now();
42  return {
43    model: run.model,
44    effort: run.effort,
45    locked: !run.auto && run.effort !== undefined, // the band's effort, Auto off
46    turns: await $.session.turns().catch(() => 0),
47    minutes: usage
48      ? Math.max(0, Math.round((now - usage.startedAt) / 60000))
49      : 0,
50    usd: usage?.cost?.usd,
51    context: (b?.categories ?? [])
52      .filter((c) => !c.isDeferred && c.tokens > 0 && !/free/i.test(c.name))
53      .map((c) => ({ name: c.name, tokens: c.tokens })),
54    used: b?.totalTokens ?? usage?.context.tokens ?? 0,
55    max: b?.maxTokens ?? usage?.context.window ?? 0,
56    files: [...files].map((f) =>
57      root && f.startsWith(`${root}/`) ? f.slice(root.length + 1) : f,
58    ),
59    agents: [...agents].map(([type, n]) => ({ type, n })),
60    compactions,
61  };
62}
63
64// The Messages tab: this chat's latest messages with text, newest first, on one line each.
65// Injected context (a text that opens with a tag) is left out.
66export async function readMessages($: EngineInterface): Promise<Excerpt[]> {
67  const messages = await $.session.messages().catch(() => []);
68  return messages
69    .map((m) => ({
70      role: m.role === "user" ? ("you" as const) : ("claude" as const),
71      text: m.text.replace(/\s+/g, " ").trim(),
72    }))
73    .filter((m) => m.text && !m.text.startsWith("<"))
74    .slice(-12)
75    .reverse();
76}
77
78let remembered = 0; // when Remember was last pressed: a press within 2s is a double click
79
80// Remember: sent as the person's own prompt (they pressed it), just after the press; the
81// kit:lessons skill decides whether it qualifies and where it goes.
82export async function remember($: EngineInterface, text: string) {
83  const now = await $.clock.now();
84  if (now - remembered < 2000) return;
85  remembered = now;
86  const prompt =
87    "Remember this as a project lesson through the kit:lessons skill, only if it qualifies " +
88    `there:\n\n> ${text.slice(0, 1200)}`;
89  $.clock.after(50, async () => {
90    await $.prompt
91      .submit({ text: prompt, asUser: true })
92      .catch((err) => $.ui.toast(`kit: could not send it (${String(err)})`));
93  });
94}
95
hooks/kit-band.tsx 385 lines
1import type { CommandSpec, EngineInterface, On } from "claude-code";
2
3import { getMode, runState, setMode } from "./auto-model";
4import { GIT_ITEMS, gitAction } from "./git-menu";
5import { isWarm, setWarm, warmCommandRun, warmInfo } from "./keep-warm";
6import { limitInfo, resumeNow } from "./limit-guard";
7import {
8  displayName,
9  EFFORTS,
10  type Mode,
11  PROFILES,
12  profileName,
13  runLine,
14} from "./model-policy";
15import { reset, setEffortLock } from "./model-switch";
16import { isOrchestrating, setOrchestrating } from "./orchestrate";
17import { openRoadmap } from "./roadmap-open";
18import type { Usage } from "./roadmap-parts";
19import { PANE } from "./roadmap-view";
20import {
21  type Ask,
22  ASKS,
23  askOpinion,
24  CLAUDE,
25  GPT,
26  whoName,
27} from "./second-opinion";
28
29// The band above the prompt, one line that wraps when narrow, an open menu (a bordered block)
30// above it: shown while the pointer rests on its button, kept open by a press. Left: context and plan usage (register.tsx measures it after each turn); the
31// context figure is a button opening Compact and Clear, run just after the press. Right: the run
32// (`Auto · model · effort` while a profile picks them, else the model; ⑂ and ♨ while orchestrate
33// and keep cache are on) opening Auto (the profile from auto-model.ts, or Off) and the
34// Orchestrate (orchestrate.ts) and Keep cache (keep-warm.ts) toggles; with Auto off, the effort
35// (Default: the session's own); Git (⎇, git-menu.ts) with /commit first; a second opinion (⚖,
36// second-opinion.ts: a row per Opinion, Review, Stuck, a press per model); the dashboard pane
37// (▤). With Auto off the model is the app's own picker's. The plan-limit pause with Resume now
38// (limit-guard.ts) follows on its own line. It yields to a survey. /band draws it again; /warm
39// toggles keep warm.
40
41export const bandCommand: CommandSpec = {
42  name: "band",
43  description:
44    "Show kit's band above the prompt (usage, run, git, second opinion, dashboard)",
45  immediate: true,
46};
47
48type Menu = "run" | "effort" | "ctx" | "git" | "opinion";
49
50let menu: Menu | null = null; // the unfolded menu row
51let usage: Usage[] = []; // context and plan limits, from register.tsx
52
53// Context and plan limits, as register.tsx measures them after each turn.
54export function bandUsage(figures: Usage[]): void {
55  usage = figures;
56}
57
58// Compact and clear run just after the press: inside it they can be refused.
59function soon($: EngineInterface, work: () => Promise<unknown>) {
60  $.clock.after(50, async () => {
61    await work();
62    $.ui.invalidate("ui.render");
63  });
64}
65
66function unfold($: EngineInterface, next: Menu | null) {
67  menu = menu === next ? null : next;
68  $.ui.invalidate("ui.render");
69}
70
71export function kitBand(on: On) {
72  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
73    if (e.props.hasSurvey) return next(e);
74    const { Box, Button, Text } = $.ui.resolve(e);
75    const panes = await $.ui.panes().catch(() => []);
76    const isOpen = panes.some((p) => p.id === PANE && p.isPlaced);
77    const now = await getMode($);
78    const run = await runState($);
79    const pause = await limitInfo($);
80    const warm = isWarm();
81    const orch = await isOrchestrating($);
82    const warmed = warmInfo();
83    const ctx = usage.find((u) => u.label === "ctx");
84    const meters = usage.filter((u) => u !== ctx);
85    const done = () => unfold($, null);
86    const close = (
87      <Button key="kit-menu-close" label="×" dimColor onPress={done} />
88    );
89
90    // A line of the run menu: its name in a narrow column, its choices beside it.
91    const line = (name: string, items: unknown[]) => (
92      <Box key={`kit-line-${name}`} gap={1}>
93        <Box width={8} flexShrink={0}>
94          <Text dimColor>{name}</Text>
95        </Box>
96        <Box gap={1} flexWrap="wrap">
97          {items as never}
98        </Box>
99      </Box>
100    );
101
102    const bodyOf = (m: Menu) => {
103      let body = null;
104      if (m === "run") {
105        const modes: Mode[] = [...PROFILES, "off"];
106        body = (
107          <Box flexDirection="column" flexGrow={1} gap={1}>
108            {line(
109              "Auto",
110              modes.map((m) => (
111                <Button
112                  key={`kit-mode-${m}`}
113                  label={profileName(m)}
114                  dimColor={now !== m}
115                  onPress={() => {
116                    void setMode($, m).then(done);
117                  }}
118                />
119              )),
120            )}
121            {line("Mode", [
122              <Button
123                key="kit-orchestrate"
124                label="⑂ Orchestrate"
125                dimColor={!orch}
126                onPress={() => {
127                  void setOrchestrating($, !orch).then(() =>
128                    $.ui.invalidate("ui.render"),
129                  );
130                }}
131              />,
132              <Button
133                key="kit-warm"
134                label="♨ Keep cache"
135                dimColor={!warm}
136                onPress={() => {
137                  void setWarm($, !warm);
138                }}
139              />,
140            ])}
141          </Box>
142        );
143      } else if (m === "effort") {
144        const levels = ["default", ...EFFORTS] as const;
145        body = (
146          <Box flexDirection="column" flexGrow={1} gap={1}>
147            {line(
148              "Effort",
149              levels.map((l) => (
150                <Button
151                  key={`kit-effort-${l}`}
152                  label={l === "default" ? "Default" : l}
153                  dimColor={(run.effort ?? "default") !== l}
154                  onPress={() => {
155                    void setEffortLock($, l === "default" ? undefined : l).then(
156                      done,
157                    );
158                  }}
159                />
160              )),
161            )}
162          </Box>
163        );
164      } else if (m === "ctx") {
165        body = (
166          <Box flexDirection="column" flexGrow={1} gap={1}>
167            {line("Context", [
168              <Button
169                key="kit-compact"
170                label="⇲ Compact"
171                onPress={() => {
172                  done();
173                  soon($, () => reset($, "compact"));
174                }}
175              />,
176              <Button
177                key="kit-clear"
178                label="⌫ Clear"
179                onPress={() => {
180                  done();
181                  soon($, () => reset($, "clear"));
182                }}
183              />,
184            ])}
185          </Box>
186        );
187      } else if (m === "git") {
188        body = (
189          <Box flexDirection="column" flexGrow={1} gap={1}>
190            {line("Git", [
191              <Button
192                key="kit-git-Commit"
193                label="✓ Commit"
194                onPress={() => {
195                  done();
196                  void $.command
197                    .run({ command: "kit:commit" })
198                    .catch((err) =>
199                      $.ui.toast(
200                        `kit: could not start /commit: ${String(err)}`,
201                      ),
202                    );
203                }}
204              />,
205              ...GIT_ITEMS.map((g) => (
206                <Button
207                  key={`kit-git-${g}`}
208                  label={g}
209                  onPress={() => {
210                    done();
211                    void gitAction($, g);
212                  }}
213                />
214              )),
215            ])}
216          </Box>
217        );
218      } else if (m === "opinion") {
219        // One row per ask, GPT then Claude: a press sends at once.
220        const sendTo = (a: Ask, who: string) => (
221          <Button
222            key={`kit-opinion-${a}-${who}`}
223            label={whoName(who)}
224            onPress={() => {
225              done();
226              void askOpinion($, who, a);
227            }}
228          />
229        );
230        body = (
231          <Box flexDirection="column" flexGrow={1} gap={1}>
232            {ASKS.map((a) =>
233              line(a, [
234                ...GPT.map((g) => sendTo(a, g)),
235                <Text key={`kit-opinion-${a}-sep`} dimColor>
236                  │
237                </Text>,
238                ...CLAUDE.map((c) => sendTo(a, c)),
239              ]),
240            )}
241          </Box>
242        );
243      }
244
245      return body;
246    };
247
248    // Each menu is drawn: the pressed one open, the others hidden until the pointer rests on
249    // their button (or on the menu itself), which shares its hover scope. A press still opens
250    // it for the keyboard.
251    const MENUS: Menu[] = ["run", "effort", "ctx", "git", "opinion"];
252    const menus = MENUS.map((m) => {
253      const body = bodyOf(m);
254      if (!body) return null;
255      const open = menu === m;
256      // The blank line below the block belongs to the hovered Box (padding, not margin), so the
257      // pointer crossing it from the button keeps the menu shown.
258      return (
259        <Box
260          key={`kit-menu-${m}`}
261          flexDirection="column"
262          paddingBottom={1}
263          display={open ? "flex" : "none"}
264          hover={open ? undefined : { scope: `kit-${m}`, display: "flex" }}
265        >
266          <Box gap={1} borderStyle="round" borderColor="#334155" paddingX={1}>
267            {body}
268            {open ? close : null}
269          </Box>
270        </Box>
271      );
272    });
273    // A trigger button in a Box that joins its menu's hover scope.
274    const trigger = (m: Menu, button: unknown) => (
275      <Box
276        key={`kit-trigger-${m}`}
277        hover={{ scope: `kit-${m}`, backgroundColor: "#1e293b" }}
278      >
279        {button as never}
280      </Box>
281    );
282
283    return (
284      <Box flexDirection="column">
285        {menus}
286        <Box justifyContent="space-between" gap={2} flexWrap="wrap">
287          <Box key="kit-usage" gap={2} flexWrap="wrap">
288            {trigger(
289              "ctx",
290              <Button
291                key="kit-ctx"
292                label={ctx ? `ctx ${ctx.value}` : "ctx"}
293                onPress={() => unfold($, "ctx")}
294              />,
295            )}
296            {meters.map((u) => (
297              <Text key={`kit-usage-${u.label}`}>
298                <Text dimColor>{`${u.label} `}</Text>
299                <Text bold>{u.value}</Text>
300                {u.note ? <Text dimColor>{` · ${u.note}`}</Text> : null}
301              </Text>
302            ))}
303          </Box>
304          <Box key="kit-actions" gap={1} flexWrap="wrap">
305            {trigger(
306              "run",
307              <Button
308                key="kit-run"
309                label={`${run.auto ? `Auto · ${runLine(run.model, run.effort)}` : displayName(run.model)}${
310                  orch || warm ? ` ${orch ? "⑂" : ""}${warm ? "♨" : ""}` : ""
311                }`}
312                onPress={() => unfold($, "run")}
313              />,
314            )}
315            {run.auto
316              ? null
317              : trigger(
318                  "effort",
319                  <Button
320                    key="kit-effort"
321                    label={run.effort ?? "effort"}
322                    dimColor={!run.effort}
323                    onPress={() => unfold($, "effort")}
324                  />,
325                )}
326            {trigger(
327              "git",
328              <Button
329                key="kit-git"
330                label="⎇ Git"
331                onPress={() => unfold($, "git")}
332              />,
333            )}
334            {trigger(
335              "opinion",
336              <Button
337                key="kit-opinion"
338                label="⚖ Ask"
339                onPress={() => unfold($, "opinion")}
340              />,
341            )}
342            <Button
343              key="kit-roadmap"
344              label={isOpen ? "▤ Close" : "▤"}
345              onPress={() => {
346                const toggle = isOpen
347                  ? $.ui.close({ id: PANE })
348                  : openRoadmap($);
349                void toggle.then(() => $.ui.invalidate("ui.render"));
350              }}
351            />
352          </Box>
353        </Box>
354        {warmed || pause ? (
355          <Box gap={1} flexWrap="wrap">
356            {warmed ? <Text dimColor>{warmed}</Text> : null}
357            {pause ? <Text color="#f59e0b">{pause}</Text> : null}
358            {pause ? (
359              <Button
360                key="kit-resume"
361                label="Resume now"
362                onPress={() => {
363                  void resumeNow($);
364                }}
365              />
366            ) : null}
367          </Box>
368        ) : null}
369      </Box>
370    );
371  });
372
373  on("command.run", { command: "warm" }, async ($, e) => ({
374    text: await warmCommandRun($, e.args),
375  }));
376
377  // There is no call that unfolds a band the person folded; a redraw is what a plugin has.
378  on("command.run", { command: "band" }, async ($) => {
379    $.ui.invalidate("ui.render");
380    return {
381      text: "kit band drawn above the prompt. Folded ([+])? ctrl+x ctrl+a unfolds it.",
382    };
383  });
384}
385
hooks/keep-warm.ts 92 lines
1import type { CommandSpec, EngineInterface } from "claude-code";
2
3import { PING_EVERY_MS, shouldPing } from "./limit-policy";
4
5// Keeps this chat's prompt cache warm: after 50 idle minutes (the cache lives an hour) a
6// tiny fork of the chat ("reply with only ok") reads the whole cached prefix again, which
7// renews it. Each ping costs a cache read of the context, never zero.
8// - On by hand: the band's Keep warm button or /warm, for a long chat you return to later.
9// - During a plan-limit pause (limit-guard.ts): while the reset is near.
10
11export const warmCommand: CommandSpec = {
12  name: "warm",
13  description: "Keep this chat's prompt cache warm while it is idle (on/off)",
14  argumentHint: "[on|off]",
15  immediate: true,
16};
17
18const PING_PROMPT =
19  "Keep-alive ping from the kit plugin to keep this chat's prompt cache warm. " +
20  "Reply with only: ok";
21const TICK_MS = 5 * 60_000; // a ping lands within 55 idle minutes
22
23type Timer = ReturnType<EngineInterface["clock"]["after"]>;
24
25let warm = false;
26let pauseUntil: number | null = null; // set while limit-guard holds the chat
27let pauseRefused = false; // a ping during the pause hit the limit: no more
28let lastActive = 0; // when the chat last made a request
29let pings = 0;
30let ticker: Timer | null = null;
31
32// A response arrived (session.measure): the cache was just renewed.
33export async function noteActive($: EngineInterface) {
34  lastActive = await $.clock.now();
35}
36
37export const isWarm = () => warm;
38
39export async function setWarm($: EngineInterface, on: boolean) {
40  warm = on;
41  if (on && !lastActive) lastActive = await $.clock.now();
42  ensureTicker($);
43  $.ui.invalidate("ui.render");
44}
45
46export function warmForPause($: EngineInterface, until: number) {
47  pauseUntil = until;
48  pauseRefused = false;
49  ensureTicker($);
50}
51
52export function endPauseWarm() {
53  pauseUntil = null;
54}
55
56// The band's note: how often the cache was kept warm, empty before the first ping.
57export const warmInfo = () => (pings ? `cache kept warm ×${pings}` : "");
58
59function ensureTicker($: EngineInterface) {
60  if (!ticker) ticker = $.clock.every(TICK_MS, () => void tick($));
61}
62
63async function tick($: EngineInterface) {
64  const now = await $.clock.now();
65  if (now - lastActive < PING_EVERY_MS) return;
66  const wanted =
67    pauseUntil !== null ? !pauseRefused && shouldPing(pauseUntil, now) : warm;
68  if (!wanted) return;
69  const r = await $.model.fork({ prompt: PING_PROMPT }).catch(() => null);
70  if (r?.isAnswered) {
71    lastActive = now;
72    pings += 1;
73  } else if (r?.reason === "api-error") {
74    // The limit (or the API) refused it: retrying every 5 minutes would not help.
75    if (pauseUntil !== null) pauseRefused = true;
76    else {
77      warm = false;
78      $.ui.toast("kit: keep warm stopped, a ping failed (api error).");
79    }
80  }
81  $.ui.invalidate("ui.render");
82}
83
84export async function warmCommandRun($: EngineInterface, args: string) {
85  const arg = args.trim().toLowerCase();
86  const on = arg === "on" ? true : arg === "off" ? false : !warm;
87  await setWarm($, on);
88  return on
89    ? "Keep warm on: after 50 idle minutes a tiny request renews the prompt cache."
90    : "Keep warm off.";
91}
92
hooks/limit-guard.ts 118 lines
1import type {
2  EngineInterface,
3  TurnStepInput,
4  TurnStepResult,
5} from "claude-code";
6
7import { endPauseWarm, noteActive, warmForPause } from "./keep-warm";
8import { clockTime, overLimit, type Reading, rise, stopAt } from "./limit-policy";
9
10// Pauses this chat before the 5-hour plan limit runs out, has keep-warm.ts keep
11// its prompt cache warm while the reset is near, and resumes at the reset.
12// - register.tsx feeds every usage reading to noteLimits;
13// - auto-model.ts asks limitStep before each model request (main and subagents) and
14//   limitPrompt before a prompt enters; a paused prompt is queued and sent at the reset;
15// - the band shows limitInfo and offers resumeNow.
16
17const RESUME_PROMPT =
18  "kit: the plan limit has reset. Continue where you stopped before the pause.";
19
20type Pause = { until: number; percent: number; cut: boolean };
21
22const last = new Map<string, Reading>();
23let rises: number[] = []; // recent rises per reading, all windows
24let paused: Pause | null = null;
25let queued: string[] = [];
26type Timer = ReturnType<EngineInterface["clock"]["after"]>;
27
28let resumeTimer: Timer | null = null;
29
30export async function noteLimits(
31  $: EngineInterface,
32  readings: readonly Reading[],
33) {
34  await noteActive($);
35  for (const r of readings) {
36    const d = rise(last.get(r.kind), r);
37    if (d !== null) rises = [...rises, d].slice(-5);
38    last.set(r.kind, r);
39  }
40  if (paused) return;
41  const now = await $.clock.now();
42  const hit = overLimit(readings, stopAt(rises), now);
43  if (hit) await pause($, hit.until, hit.percent, now);
44}
45
46async function pause(
47  $: EngineInterface,
48  until: number,
49  percent: number,
50  now: number,
51) {
52  paused = { until, percent, cut: false };
53  $.ui.toast(
54    `kit: plan limit at ${Math.round(percent)}%, paused until ${clockTime(until, now)}. ` +
55      "Prompts you send now are kept and sent then.",
56    { timeoutMs: 10_000 },
57  );
58  // A tick past the reset, so the first reading after it is fresh.
59  resumeTimer = $.clock.after(until - now + 60_000, () => void resumeNow($));
60  warmForPause($, until);
61  $.ui.invalidate("ui.render");
62}
63
64// Ends the pause: at the reset, or by hand from the band (into extra usage, say).
65export async function resumeNow($: EngineInterface) {
66  if (!paused) return;
67  const { cut } = paused;
68  resumeTimer?.cancel();
69  resumeTimer = null;
70  endPauseWarm();
71  paused = null;
72  rises = [];
73  const waiting = queued;
74  queued = [];
75  $.ui.invalidate("ui.render");
76  if (cut) await $.prompt.submit({ text: RESUME_PROMPT }).catch(() => {});
77  for (const text of waiting) await $.prompt.submit({ text }).catch(() => {});
78}
79
80// Before a model request: while paused, end the turn here instead (no request is made).
81export async function limitStep(
82  $: EngineInterface,
83  e: TurnStepInput,
84): Promise<TurnStepResult | null> {
85  if (!paused) return null;
86  paused.cut = true;
87  const when = clockTime(paused.until, await $.clock.now());
88  return {
89    turnId: e.turnId,
90    index: e.index,
91    answer: `kit: paused for the plan limit until ${when}; this continues then.`,
92    toolUses: [],
93    stopReason: "end_turn",
94    usage: null,
95  };
96}
97
98// Before a prompt enters: while paused, keep it for the reset; the reason says so.
99export async function limitPrompt(
100  $: EngineInterface,
101  text: string,
102): Promise<string | null> {
103  if (!paused) return null;
104  queued = [...queued, text];
105  const when = clockTime(paused.until, await $.clock.now());
106  return `kit: paused for the plan limit; this prompt is sent at ${when}.`;
107}
108
109// The band's line while paused, empty otherwise.
110export async function limitInfo($: EngineInterface): Promise<string> {
111  if (!paused) return "";
112  const parts = [
113    `paused until ${clockTime(paused.until, await $.clock.now())}`,
114  ];
115  if (queued.length) parts.push(`${queued.length} queued`);
116  return parts.join(" · ");
117}
118
hooks/roadmap-open.ts 107 lines
1import type { CommandSpec, EngineInterface, On, ToolSpec } from "claude-code";
2
3import type { Card } from "./roadmap-parts";
4import { PANE, roadmapOpened } from "./roadmap-view";
5import { inRoot } from "./spec";
6import { list } from "./theme-view";
7
8// Opens the roadmap pane (roadmap-view.tsx draws it): the tool /product calls, with items for
9// a read-only draft (plan mode) or none for docs/roadmap.md live. It never opens on its own:
10// the band's Roadmap button (kit-band.tsx) and /panel open it by hand, /panel anywhere
11// (without docs/roadmap.md the pane says to run /product).
12
13export const roadmapTool: ToolSpec = {
14  name: "roadmap_view",
15  description:
16    "Open kit's roadmap pane. No items → it shows docs/roadmap.md live and editable. With " +
17    "items → a read-only draft (plan mode): items in order, ## Later excluded; state open, " +
18    "progress (spec linked, unchecked) or done; phase = the item's heading without '## '.",
19  inputSchema: {
20    type: "object",
21    properties: {
22      product: { type: "string" },
23      items: list({
24        slug: "string",
25        description: "string",
26        state: "string",
27        phase: "string",
28      }),
29      later: { type: "array", items: { type: "string" } },
30    },
31  },
32};
33
34export const panelCommand: CommandSpec = {
35  name: "panel",
36  description: "Open kit's roadmap pane (project dashboard)",
37  immediate: true,
38};
39
40// docs/product.md's `# <name>`, or "Dashboard" without one.
41async function productName($: EngineInterface): Promise<string> {
42  const root = await $.session.root();
43  const text = await $.fs.read(inRoot(root, "docs/product.md")).catch(() => "");
44  return /^# (.+)$/m.exec(String(text))?.[1]?.trim() || "Dashboard";
45}
46
47// Opens the pane, a draft or the live roadmap; says whether a surface drew it.
48async function show(
49  $: EngineInterface,
50  draft: { product: string; cards: Card[]; later: string[] } | null,
51): Promise<{ isPlaced: boolean; reason?: string }> {
52  const name = draft ? draft.product : await productName($);
53  roadmapOpened(draft, name);
54  // The pane is titled with the project's name (an open pane is retitled).
55  const opened = await $.ui.open({
56    id: PANE,
57    title: draft ? `${name} · draft` : name,
58  });
59  $.ui.invalidate("ui.render");
60  return opened;
61}
62
63// The live roadmap, opened by a press or a command (asked, so placed at any width).
64export function openRoadmap($: EngineInterface) {
65  return show($, null);
66}
67
68export function roadmapOpen(on: On) {
69  on("command.run", { command: "panel" }, async ($) => {
70    const opened = await openRoadmap($);
71    return {
72      text: opened.isPlaced
73        ? "Roadmap pane opened."
74        : `Roadmap pane not shown (${opened.reason}).`,
75    };
76  });
77
78  on("tool.check", { tool: "mcp__kit__roadmap_view" }, () => ({
79    decision: "allow",
80  }));
81
82  on("tool.call", { tool: "mcp__kit__roadmap_view" }, async ($, e) => {
83    const input = e as unknown as {
84      product?: string;
85      items?: Card[];
86      later?: string[];
87    };
88    const draft = Array.isArray(input.items)
89      ? {
90          product: input.product ?? "Roadmap",
91          cards: input.items.map((i) => ({
92            ...i,
93            phase: i.phase ?? "",
94            editable: false,
95          })),
96          later: input.later ?? [],
97        }
98      : null;
99    const opened = await show($, draft);
100    return {
101      result: opened.isPlaced
102        ? "Roadmap pane shown."
103        : `Roadmap pane not shown (${opened.reason}).`,
104    };
105  });
106}
107
hooks/roadmap-view.tsx 282 lines
1import type { ElementTable, EngineInterface, On } from "claude-code";
2
3import { readChat, readMessages, remember } from "./chat-facts";
4import * as file from "./roadmap-file";
5import { body } from "./roadmap-dashboard";
6import { pressOnFocus, tracked } from "./roadmap-press";
7import type { Card, Chat, Excerpt, Tab } from "./roadmap-parts";
8import * as wt from "./roadmap-worktree";
9import { inRoot, parseSpec, type SpecState } from "./spec";
10
11// The roadmap pane, opened by /product, /panel and the band's button (roadmap-open.ts): a
12// project dashboard, also where there is no docs/roadmap.md (then the dashboard alone). Live: reads docs/roadmap.md, the
13// open features' specs, and edits open items in place (roadmap-file.ts keeps
14// every other line as is); its buttons run kit's skills in the chat. Draft: /product in plan
15// mode passes items as data, read-only. Drawing: roadmap-dashboard.tsx + roadmap-parts.tsx; done and in-progress
16// state stays /build's.
17
18export const PANE = "kit-roadmap";
19const PATH = "docs/roadmap.md";
20
21export type Draft = { product: string; cards: Card[]; later: string[] };
22let draft: Draft | null = null;
23let product = "Dashboard"; // docs/product.md's name, read when the pane opens (roadmap-open.ts)
24let live: file.Roadmap | null = null;
25let specs: Record<string, SpecState | null> = {};
26let away: Record<string, string> = {}; // open features running elsewhere (roadmap-worktree.ts)
27let isSetUp = true;
28let tab: Tab = "roadmap"; // the pane's shown tab
29let chat: Chat | null = null; // the Chat tab's facts, read on each draw while it shows
30let messages: Excerpt[] | null = null; // the Messages tab's recent messages, likewise
31let needsLoad = true;
32let note = "";
33let added = 0;
34let adding: string | null = null; // the phase whose "+ Add" field is open
35let menuOpen: string | null = null; // the card or Later idea whose ⋯ row is open
36let confirming: string | null = null; // an armed Clear or Remove, waiting for its 2nd press
37let sent = 0; // when a button last ran a command: presses right after it are a double click
38// Phases the user folded or unfolded against the default (a finished phase starts folded).
39const toggled = new Set<string>();
40
41// Called when the pane opens (/product or session start): a draft (plan mode), or null for the live roadmap.
42export function roadmapOpened(next: Draft | null, name: string): void {
43  [draft, product, needsLoad, note] = [next, name, true, ""];
44  [specs, away] = [{}, {}]; // a draft's cards must not show the live pane's specs
45}
46
47// Called on every Write/Edit: a change to docs/roadmap.md or a spec reloads the live pane.
48export function roadmapEdited(path: string): boolean {
49  if (!/docs\/(roadmap\.md|specs\/[^/]+\.md)$/.test(path.replace(/\\/g, "/")))
50    return false;
51  return (needsLoad = true);
52}
53
54// Called after every turn (session.measure): it may have committed, built or launched.
55export function roadmapStale(): void {
56  needsLoad = true;
57}
58
59
60function cards(r: file.Roadmap): Card[] {
61  return r.items.map((i) => ({
62    slug: i.slug,
63    description: i.description,
64    state: i.done ? "done" : i.spec ? "progress" : "open",
65    phase: i.phase,
66    editable: file.isEditable(i),
67  }));
68}
69
70// Open features sent to a worktree (a $.store mark per project) or claimed on another branch
71// (a spec commit there), plus the live spec of a claim checked out in a worktree here. Ended
72// marks are dropped. Best effort: a failing call shows nothing.
73async function readAway($: EngineInterface, root: string, open: string[]) {
74  const git = (args: string[]) =>
75    $.process.run(["git", ...args], { cwd: root }).catch(() => null);
76  const r = await git(wt.CLAIMS_GIT);
77  const t = await git(wt.WORKTREES_GIT);
78  const all = ((await $.store.get(wt.STORE_KEY).catch(() => null)) ??
79    {}) as wt.Marks;
80  const mine = all[root] ?? {};
81  const claimed = r?.exitCode === 0 ? wt.claims(r.stdout) : {};
82  const trees = t?.exitCode === 0 ? wt.worktrees(t.stdout) : {};
83  const now = await $.clock.now();
84  const { lines, specs: at, keep } = wt.away(open, claimed, mine, now, trees);
85  if (Object.keys(keep).length !== Object.keys(mine).length) {
86    const rest = { ...all, [root]: keep };
87    if (!Object.keys(keep).length) delete rest[root];
88    await $.store.set(wt.STORE_KEY, rest).catch(() => {});
89  }
90  const read: Record<string, SpecState | null> = {};
91  for (const [slug, path] of Object.entries(at))
92    read[slug] = parseSpec(await $.fs.read(path).catch(() => null));
93  return { lines, specs: read };
94}
95
96export function roadmapView(on: On) {
97  pressOnFocus(on);
98  on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
99    const el = $.ui.resolve(e);
100    if (needsLoad && !draft) {
101      needsLoad = false;
102      const root = await $.session.root();
103      const text = await $.fs.read(inRoot(root, PATH)).catch(() => null);
104      live = typeof text === "string" ? file.parse(text) : null;
105      specs = {};
106      for (const i of live?.items ?? [])
107        if (i.spec && !i.done)
108          specs[i.slug] = parseSpec(
109            await $.fs.read(inRoot(root, i.spec)).catch(() => null),
110          );
111      const open = (live?.items ?? []).filter((i) => !i.done && !i.spec);
112      const elsewhere = await readAway(
113        $,
114        root,
115        open.map((i) => i.slug),
116      );
117      away = elsewhere.lines;
118      Object.assign(specs, elsewhere.specs); // their /build step, from the worktree
119      isSetUp = await $.fs.exists(inRoot(root, "AGENTS.md")).catch(() => true);
120    }
121    chat = tab === "chat" && !draft ? await readChat($) : null;
122    messages = tab === "messages" && !draft ? await readMessages($) : null;
123    // No docs/roadmap.md: the dashboard alone, as an action pad.
124    const view = draft ??
125      (live && { product, cards: cards(live), later: live.later }) ?? {
126        product,
127        cards: [],
128        later: [],
129      };
130
131    const redraw = (message?: string) => {
132      if (message !== undefined) note = message;
133      $.ui.invalidate("ui.render");
134    };
135    // Runs a slash command at once (a feature's button clears the chat first, as fresh-start.ts
136    // does), outside the press: inside it, $.command.run waits on the turn. A press within 2s
137    // of the last is a double click and dropped; not "until the run settles": /compact's run
138    // may not settle, which held every button. Failing, the line goes in the prompt box.
139    const run = async (command: string, args: string, fresh: boolean) => {
140      const line = `/${command}${args ? ` ${args}` : ""}`;
141      const now = await $.clock.now();
142      if (now - sent < 2000) return;
143      sent = now;
144      $.clock.after(50, async () => {
145        let cleared = !fresh;
146        try {
147          if (fresh) await $.command.run({ command: "clear" });
148          cleared = true;
149          await $.command.run(args ? { command, args } : { command });
150        } catch (err) {
151          // Not cleared: building on in this chat would defeat the point.
152          if (cleared) await $.prompt.fill({ text: line });
153          const todo = `${cleared ? "" : "/clear, then "}${line}`;
154          $.ui.toast(`kit: run ${todo} yourself (${String(err)})`);
155        }
156      });
157    };
158    // Starts a linked session in its own worktree (ccd_session's start_session; the chip of
159    // spawn_task when refused) for /kit:build <slug>,
160    // marked first so the card asks "Again?" at once. Failing: the old mark comes back.
161    const toWorktree = async (slug: string) => {
162      const now = await $.clock.now();
163      if (now - sent < 2000) return;
164      sent = now;
165      const root = await $.session.root();
166      const all = ((await $.store.get(wt.STORE_KEY).catch(() => null)) ??
167        {}) as wt.Marks;
168      const mine = { ...all[root] };
169      const before = mine[slug];
170      const mark = { ...all, [root]: { ...mine, [slug]: now } };
171      await $.store.set(wt.STORE_KEY, mark).catch(() => {});
172      away = { ...away, [slug]: away[slug] ?? "sent to worktree" };
173      redraw();
174      const call = (tool: string, args: Record<string, unknown>) =>
175        $.mcp
176          .call("ccd_session", tool, args)
177          .then(wt.failure, (err) => String(err));
178      // A linked session in its own worktree first; the chip when the app refuses it.
179      let why = await call("start_session", wt.session(slug));
180      if (why !== null) why = await call("spawn_task", wt.chip(slug));
181      if (why !== null) {
182        if (before === undefined) delete mine[slug];
183        const back = { ...all, [root]: mine };
184        await $.store.set(wt.STORE_KEY, back).catch(() => {});
185        $.ui.toast(`kit: could not start a worktree session (${why})`);
186      }
187      needsLoad = true;
188      redraw();
189    };
190    const edit = async (done: string, change: (text: string) => string) => {
191      const path = inRoot(await $.session.root(), PATH);
192      const text = String(await $.fs.read(path).catch(() => ""));
193      try {
194        const next = change(text);
195        if (next !== text) await $.fs.write(path, next);
196        note = next === text ? "nothing to change" : done;
197      } catch (err) {
198        note = err instanceof Error ? err.message : String(err);
199      }
200      needsLoad = true;
201      menuOpen = null;
202      redraw();
203    };
204
205    return body({
206      el: tracked(el, e.surface),
207      // Input and Select: terminal and desktop only.
208      ui:
209        e.surface === "terminal" || e.surface === "desktop"
210          ? (el as ElementTable<"terminal" | "desktop">)
211          : null,
212      ...view,
213      draft: !!draft,
214      hasRoadmap: !!draft || !!live,
215      specs,
216      away,
217      canWorktree: e.surface === "desktop",
218      isSetUp,
219      note,
220      adding,
221      added,
222      menuOpen,
223      confirming,
224      toggled,
225      tab,
226      chat,
227      messages,
228      rows: e.props.placement === "dock" ? e.props.scroll.bodyRows : 0,
229      act: {
230        remember: (text) => void remember($, text),
231        tab: (next) => {
232          tab = next;
233          needsLoad = true;
234          redraw();
235        },
236        build: (slug) => void run("kit:build", slug, true),
237        worktree: (slug) => void toWorktree(slug),
238        run: (command, args = "") => void run(command, args, false),
239        edit: (done, change) => void edit(done, change),
240        fold: (phase) => {
241          if (!toggled.delete(phase)) toggled.add(phase);
242          redraw();
243        },
244        toggleAdd: (phase, folded) => {
245          adding = adding === phase ? null : phase;
246          // Unfold the phase so the new card shows up where it lands.
247          if (adding && folded && !toggled.delete(phase)) toggled.add(phase);
248          redraw();
249        },
250        confirm: (key, run) => {
251          if (confirming === key) {
252            confirming = null;
253            run();
254            return;
255          }
256          confirming = key;
257          redraw();
258          $.clock.after(4000, () => {
259            if (confirming !== key) return;
260            confirming = null;
261            redraw();
262          });
263        },
264        menu: (key) => {
265          menuOpen = menuOpen === key ? null : key;
266          redraw();
267        },
268        addLater: (idea) => {
269          added += 1;
270          adding = null;
271          void edit("added to Later", (t) => file.addLater(t, idea));
272        },
273        add: (phase, title) => {
274          added += 1; // a new key draws a fresh, empty field
275          adding = null;
276          void edit(`added to ${phase}`, (t) => file.add(t, phase, title));
277        },
278      },
279    });
280  });
281}
282
hooks/roadmap-parts.tsx 102 lines
1import type { ElementTable } from "claude-code";
2
3import type { SpecState } from "./spec";
4
5// The roadmap pane's shared shapes: the data and actions every drawing file gets (`Parts`),
6// colors and small helpers. The drawing is pure: no `$` (it never crosses an import), so
7// every press goes through `Actions`, which roadmap-view.tsx builds. Files: dashboard (top),
8// phase (a phase and its cards), card (one card and its ⋯ row), later (## Later).
9
10export type State = "open" | "progress" | "done";
11export type Card = {
12  slug: string;
13  description: string;
14  state: State;
15  phase: string;
16  editable: boolean;
17};
18// One usage figure: "ctx 266k", "session 70% · 1h18m"; pct colors it from 60% and 85%.
19export type Usage = {
20  label: string;
21  value: string;
22  note?: string;
23  pct: number;
24};
25export type Tab = "roadmap" | "chat" | "messages";
26// One recent message of this chat, for the Messages tab: whose, and its text on one line.
27export type Excerpt = { role: "you" | "claude"; text: string };
28// The Chat tab: the run, the session's usage with the context by category, what it touched.
29export type Chat = {
30  model: string;
31  effort: string | undefined;
32  locked: boolean;
33  turns: number;
34  minutes: number;
35  usd: number | undefined;
36  context: { name: string; tokens: number }[];
37  used: number;
38  max: number;
39  files: string[];
40  agents: { type: string; n: number }[];
41  compactions: number;
42};
43export type Actions = {
44  tab: (tab: Tab) => void; // shows another tab of the pane
45  remember: (text: string) => void; // asks the model to keep it as a lesson (kit:lessons)
46  build: (slug: string) => void; // runs /clear, then /kit:build <slug> in the fresh chat
47  worktree: (slug: string) => void; // raises the desktop's chip: /kit:build <slug> in a worktree
48  run: (command: string, args?: string) => void; // runs the slash command at once
49  edit: (done: string, change: (text: string) => string) => void;
50  fold: (phase: string) => void;
51  toggleAdd: (phase: string, folded: boolean) => void;
52  add: (phase: string, title: string) => void;
53  addLater: (idea: string) => void;
54  menu: (key: string) => void; // open or close one ⋯ row (a slug, or later-<index>)
55  // A press that can't be undone from the pane: the first arms it (its label asks), a second
56  // press within a few seconds runs it.
57  confirm: (key: string, run: () => void) => void;
58};
59export type Parts = {
60  el: ElementTable;
61  ui: ElementTable<"terminal" | "desktop"> | null; // Input lives only there
62  menuOpen: string | null;
63  confirming: string | null;
64  product: string;
65  cards: Card[];
66  later: string[];
67  draft: boolean;
68  hasRoadmap: boolean; // false: no docs/roadmap.md, the pane is the dashboard alone
69  specs: Record<string, SpecState | null>;
70  away: Record<string, string>; // open features running elsewhere: "runs on <branch>", …
71  canWorktree: boolean; // the desktop app, which has the worktree chip (ccd_session)
72  isSetUp: boolean;
73  note: string;
74  adding: string | null;
75  added: number;
76  toggled: Set<string>;
77  tab: Tab;
78  chat: Chat | null;
79  messages: Excerpt[] | null; // the Messages tab's recent messages, newest first
80  rows: number; // the docked pane's body rows, so the pad sits at the bottom; 0 inline
81  act: Actions;
82};
83
84export const ICON: Record<State, string> = {
85  done: "✓",
86  progress: "●",
87  open: "○",
88};
89export const COLOR: Record<State, string> = {
90  done: "#22c55e",
91  progress: "#f59e0b",
92  open: "#94a3b8",
93};
94export const BAND = "#1e293b"; // section headings
95export const LATER = "\u0000later"; // `adding` key for Later: never a phase name
96
97export const doneOf = (cs: Card[]) =>
98  cs.filter((c) => c.state === "done").length;
99export const phaseNames = (p: Parts) => [
100  ...new Set(p.cards.map((c) => c.phase)),
101];
102
hooks/spec.ts 27 lines
1// Parses one spec's state; the only kit file the mod reads (see AGENTS.md § Budgets).
2// Pure functions: the engine only follows `$` within one file, so callers do the reading.
3
4export type SpecState = { status: string; done: number; total: number };
5
6export function parseSpec(text: unknown): SpecState | null {
7  if (typeof text !== "string") return null;
8  const criteria =
9    text.split(/^## /m).find((s) => s.startsWith("Acceptance criteria")) ?? "";
10  const done = criteria.match(/^- \[x\]/gim)?.length ?? 0;
11  const open = criteria.match(/^- \[ \]/gm)?.length ?? 0;
12  const status = /^Status:\s*(\S+)/m.exec(text)?.[1] ?? "?";
13  return { status, done, total: done + open };
14}
15
16// `git symbolic-ref --short HEAD` output → the feat/ or fix/ slug, or null.
17export function branchSlug(head: string | undefined): string | null {
18  return /^(?:feat|fix)\/(.+)$/.exec(head?.trim() ?? "")?.[1] ?? null;
19}
20
21// A project path against the session's root ($.session.root()), not the shell's cwd: a `cd`
22// during the session must not hide docs/ or AGENTS.md. Absolute paths pass through.
23export function inRoot(root: string, path: string): string {
24  if (/^(\/|[a-zA-Z]:[\\/])/.test(path)) return path;
25  return `${root.replace(/[\\/]+$/, "")}/${path}`;
26}
27
hooks/theme-view.tsx 354 lines
1import type { EngineInterface, On, ToolSpec } from "claude-code";
2
3// The theme pane. /theme passes its proposal as data (it is shown in plan mode, before
4// anything is written). The mod computes WCAG contrast and returns it to the model. Desktop
5// draws an Svg with the real fonts (a glyph subset fetched and embedded: the Svg sandbox
6// loads nothing itself); the terminal gets swatches and text.
7
8type Colors = Record<string, string>;
9type Font = {
10  role: string;
11  family: string;
12  google?: boolean;
13  weights?: number[];
14};
15type Named = { name: string; px: number };
16type Theme = {
17  colors: { light: Colors; dark?: Colors };
18  fonts?: Font[];
19  typeScale?: { step: string; size: number; lineHeight: number }[];
20  spacing?: Named[];
21  radius?: Named[];
22  shadow?: { name: string; value: string }[];
23};
24type Pair = { fg: string; bg: string; ratio: number | null };
25
26const PANE = "kit-theme";
27const SAMPLE = "The quick brown fox jumps";
28const BODY = "Body text in the muted role, on the surface.";
29const W = 600;
30const GREY = "#64748b";
31const MONO = "ui-monospace, monospace";
32
33let shown: Theme | null = null;
34let svg = "";
35const fontCss = new Map<string, string>();
36
37// JSON schema for an array of flat objects: list({ name: "string", px: "number" }).
38export const list = (fields: Record<string, string>) => ({
39  type: "array",
40  items: {
41    type: "object",
42    properties: Object.fromEntries(
43      Object.entries(fields).map(([k, t]) => [
44        k,
45        t.endsWith("[]")
46          ? { type: "array", items: { type: t.slice(0, -2) } }
47          : { type: t },
48      ]),
49    ),
50  },
51});
52
53export const themeTool: ToolSpec = {
54  name: "theme_view",
55  description:
56    "Show a proposed theme in kit's theme pane and get WCAG contrast for every text pair. " +
57    "Colors are semantic roles → hex (#rrggbb): bg, surface, fg, muted, border, primary, " +
58    "primary-fg, …; sizes in px. Display only.",
59  inputSchema: {
60    type: "object",
61    required: ["colors"],
62    properties: {
63      colors: {
64        type: "object",
65        properties: { light: { type: "object" }, dark: { type: "object" } },
66      },
67      fonts: list({
68        role: "string",
69        family: "string",
70        google: "boolean",
71        weights: "number[]",
72      }),
73      typeScale: list({ step: "string", size: "number", lineHeight: "number" }),
74      spacing: list({ name: "string", px: "number" }),
75      radius: list({ name: "string", px: "number" }),
76      shadow: list({ name: "string", value: "string" }),
77    },
78  },
79};
80
81// Google Fonts CSS with its files inlined as data URIs (Node 18+ fetch; $.http.fetch is text-only).
82const INLINE_FONTS = `(async () => {
83  let css = await (await fetch(process.argv[1])).text();
84  for (const url of [...new Set(css.match(/https:[^)]+/g) || [])]) {
85    const b = Buffer.from(await (await fetch(url)).arrayBuffer()).toString("base64");
86    css = css.split(url).join("data:font/ttf;base64," + b);
87  }
88  process.stdout.write(css);
89})().catch((e) => { console.error(String(e)); process.exit(1); })`;
90
91function luminance(hex: string): number | null {
92  const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})([0-9a-f]{2})?$/i.exec(hex.trim());
93  if (!m?.[1]) return null;
94  const h = m[1].length === 3 ? [...m[1]].map((c) => c + c).join("") : m[1];
95  const [r = 0, g = 0, b = 0] = [0, 2, 4].map((i) => {
96    const c = parseInt(h.slice(i, i + 2), 16) / 255;
97    return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
98  });
99  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
100}
101
102export function contrast(a: string, b: string): number | null {
103  const [la, lb] = [luminance(a), luminance(b)];
104  if (la === null || lb === null) return null;
105  return (
106    Math.floor(((Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05)) * 100) /
107    100
108  );
109}
110
111// Text pairs that need 4.5:1: fg and muted on bg and surface, and every `<x>-fg` on `<x>`.
112export function pairs(c: Colors): Pair[] {
113  const list: [string, string][] = [];
114  for (const fg of ["fg", "muted"])
115    for (const bg of ["bg", "surface"]) list.push([fg, bg]);
116  for (const role of Object.keys(c))
117    if (role.endsWith("-fg")) list.push([role, role.slice(0, -3)]);
118  return list
119    .filter(([fg, bg]) => c[fg] && c[bg])
120    .map(([fg, bg]) => ({ fg, bg, ratio: contrast(c[fg] ?? "", c[bg] ?? "") }));
121}
122
123const mark = (p: Pair) => (p.ratio === null ? "?" : p.ratio >= 4.5 ? "✓" : "✗");
124const esc = (s: string | number) =>
125  String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;");
126
127async function embedFonts($: EngineInterface, fonts: Font[]): Promise<string> {
128  const glyphs = encodeURIComponent(`${SAMPLE}${BODY}Primary0123456789/`);
129  const css: string[] = [];
130  for (const font of fonts.filter((f) => f.google !== false).slice(0, 3)) {
131    const weights = [...new Set(font.weights ?? [400])]
132      .sort((a, b) => a - b)
133      .join(";");
134    const family = font.family.replace(/ /g, "+");
135    const url = `https://fonts.googleapis.com/css2?family=${family}:wght@${weights}&text=${glyphs}`;
136    if (!fontCss.has(url)) {
137      const ran = await $.process
138        .run(["node", "-e", INLINE_FONTS, url])
139        .catch(() => null);
140      fontCss.set(url, ran?.exitCode === 0 ? ran.stdout : "");
141    }
142    css.push(fontCss.get(url) ?? "");
143  }
144  const joined = css.join("\n");
145  return joined.length < 90_000 ? joined : ""; // the Svg source caps at 131 072 characters
146}
147
148// box-shadow "0 4px 12px 0 rgba(…)" → drop-shadow "0 4px 12px rgba(…)" (it has no spread).
149function dropShadow(value: string): string {
150  const first = value.split(/,(?![^(]*\))/)[0] ?? "";
151  const color =
152    /(rgba?|hsla?)\([^)]*\)|#[0-9a-f]{3,8}/i.exec(first)?.[0] ??
153    "rgba(0,0,0,.2)";
154  return `${first.replace(color, "").trim().split(/\s+/).slice(0, 3).join(" ")} ${color}`;
155}
156
157function drawSvg(t: Theme, fontFaces: string): string {
158  const fam = (role: RegExp) => {
159    const f = t.fonts?.find((x) => role.test(x.role)) ?? t.fonts?.[0];
160    return f
161      ? `'${esc(f.family)}', system-ui, sans-serif`
162      : "system-ui, sans-serif";
163  };
164  const [head, body] = [fam(/display|head/i), fam(/sans|body|text/i)];
165  const out: string[] = [];
166  const text = (
167    x: number,
168    y: number,
169    size: number,
170    fill: string,
171    s: string,
172    font = body,
173    extra = "",
174  ) =>
175    out.push(
176      `<text x="${x}" y="${y}" font-family="${font}" font-size="${size}" fill="${esc(fill)}" ${extra}>${esc(s)}</text>`,
177    );
178  const rect = (x: number, y: number, w: number, h: number, attrs: string) =>
179    out.push(`<rect x="${x}" y="${y}" width="${w}" height="${h}" ${attrs}/>`);
180  let y = 0;
181  const title = (s: string) => (
182    text(0, (y += 28), 13, GREY, s, body, 'font-weight="700"'),
183    (y += 10)
184  );
185
186  for (const [mode, c] of [
187    ["Light", t.colors.light],
188    ["Dark", t.colors.dark],
189  ] as const) {
190    if (!c) continue;
191    title(`${mode} colors`);
192    Object.entries(c).forEach(([role, hex], i) => {
193      const [x, top] = [(i % 8) * 74, y + Math.floor(i / 8) * 74];
194      rect(x, top, 66, 40, `rx="8" fill="${esc(hex)}" stroke="#94a3b844"`);
195      text(x, top + 54, 11, GREY, role);
196      text(x, top + 66, 10, "#94a3b8", hex, MONO);
197    });
198    y += Math.ceil(Object.keys(c).length / 8) * 74 + 4;
199    text(
200      0,
201      y,
202      11,
203      GREY,
204      pairs(c)
205        .map((p) => `${p.fg}/${p.bg} ${p.ratio ?? "?"} ${mark(p)}`)
206        .join("   "),
207    );
208    const r = t.radius?.find((x) => /md|base/.test(x.name))?.px ?? 10;
209    const card = y + 14;
210    rect(
211      0,
212      card,
213      W,
214      110,
215      `rx="${r}" fill="${esc(c.surface ?? c.bg ?? "#fff")}" stroke="${esc(c.border ?? "none")}"`,
216    );
217    text(20, card + 36, 22, c.fg ?? "#000", SAMPLE, head, 'font-weight="700"');
218    text(20, card + 60, 14, c.muted ?? c.fg ?? "#555", BODY);
219    rect(
220      20,
221      card + 72,
222      104,
223      28,
224      `rx="${Math.min(r, 14)}" fill="${esc(c.primary ?? "#333")}"`,
225    );
226    text(
227      72,
228      card + 91,
229      13,
230      c["primary-fg"] ?? "#fff",
231      "Primary",
232      body,
233      'text-anchor="middle" font-weight="600"',
234    );
235    y = card + 110;
236  }
237  if (t.typeScale?.length) title("Type scale");
238  for (const s of [...(t.typeScale ?? [])].sort((a, b) => b.size - a.size)) {
239    const size = Math.min(s.size, 44);
240    y += Math.max(s.lineHeight, s.size) * (size / s.size);
241    text(0, y, 10, "#94a3b8", `${s.step} ${s.size}/${s.lineHeight}`, MONO);
242    text(72, y, size, "#334155", SAMPLE, s.size >= 24 ? head : body);
243  }
244  if (t.spacing?.length) title("Spacing");
245  for (const s of t.spacing ?? []) {
246    rect(72, y, Math.min(s.px, W - 80), 12, 'rx="2" fill="#6366f1"');
247    text(0, (y += 18) - 8, 10, "#94a3b8", `${s.name} ${s.px}`, MONO);
248  }
249  const boxes = [
250    ...(t.radius ?? []).map((r) => [
251      `${r.name} ${r.px}`,
252      `rx="${Math.min(r.px, 24)}" fill="#e2e8f0"`,
253    ]),
254    ...(t.shadow ?? []).map((s) => [
255      s.name,
256      `rx="8" fill="#fff" style="filter: drop-shadow(${esc(dropShadow(s.value))})"`,
257    ]),
258  ];
259  if (boxes.length) title("Radius · shadow");
260  boxes.forEach(([label = "", attrs = ""], i) => {
261    const [x, top] = [(i % 6) * 98 + 4, y + 8 + Math.floor(i / 6) * 84];
262    rect(x, top, 80, 52, attrs);
263    text(x, top + 70, 11, GREY, label);
264  });
265  y += Math.ceil(boxes.length / 6) * 84 + 16;
266  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${y}" viewBox="-4 0 ${W + 8} ${y}"><style>${fontFaces}</style>${out.join("")}</svg>`;
267}
268
269export function themeView(on: On) {
270  on("tool.check", { tool: "mcp__kit__theme_view" }, () => ({
271    decision: "allow",
272  }));
273
274  on("tool.call", { tool: "mcp__kit__theme_view" }, async ($, e) => {
275    const t = e as unknown as Theme;
276    if (!t.colors?.light) return { result: "error: colors.light is required" };
277    shown = t;
278    const isDesktop = (await $.session.surface()) === "desktop";
279    svg = isDesktop ? drawSvg(t, await embedFonts($, t.fonts ?? [])) : "";
280    const opened = await $.ui.open({ id: PANE, title: "Theme" });
281    $.ui.invalidate("ui.render");
282    const lines = (["light", "dark"] as const).flatMap((mode) =>
283      pairs(t.colors[mode] ?? {}).map(
284        (p) => `${mode} ${p.fg}/${p.bg}: ${p.ratio ?? "not hex"} ${mark(p)}`,
285      ),
286    );
287    const pane = opened.isPlaced ? "shown" : `not shown (${opened.reason})`;
288    return {
289      result: `Theme pane ${pane}. Contrast (min 4.5):\n${lines.join("\n") || "no text pairs"}`,
290    };
291  });
292
293  on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
294    const { Box, Text } = $.ui.resolve(e);
295    if (!shown)
296      return <Text dimColor>Run /theme to preview a theme here.</Text>;
297    if (e.surface === "desktop" && svg) {
298      const { Svg } = $.ui.resolve(e);
299      return (
300        <Svg
301          source={svg}
302          alt="Theme preview: colors, contrast, type, spacing, radius, shadow"
303        />
304      );
305    }
306    const t = shown;
307    const row = (label: string, items?: string[]) =>
308      items?.length ? (
309        <Text>
310          {label}: {items.join(" · ")}
311        </Text>
312      ) : null;
313    return (
314      <Box flexDirection="column">
315        {(["light", "dark"] as const).map((mode) =>
316          Object.entries(t.colors[mode] ?? {}).map(([role, hex]) => (
317            <Text key={`${mode}-${role}`}>
318              <Text backgroundColor={hex}>{"    "}</Text> {mode} {role}{" "}
319              <Text dimColor>{hex}</Text>
320            </Text>
321          )),
322        )}
323        {row(
324          "contrast",
325          (["light", "dark"] as const).flatMap((m) =>
326            pairs(t.colors[m] ?? {}).map(
327              (p) => `${m} ${p.fg}/${p.bg} ${p.ratio ?? "?"} ${mark(p)}`,
328            ),
329          ),
330        )}
331        {row(
332          "fonts",
333          t.fonts?.map((f) => `${f.role} ${f.family}`),
334        )}
335        {row(
336          "type",
337          t.typeScale?.map((s) => `${s.step} ${s.size}/${s.lineHeight}`),
338        )}
339        {row(
340          "spacing",
341          t.spacing?.map(
342            (s) =>
343              `${s.name} ${"▇".repeat(Math.max(1, Math.min(12, s.px / 4)))} ${s.px}`,
344          ),
345        )}
346        {row(
347          "radius",
348          t.radius?.map((r) => `${r.name} ${r.px}`),
349        )}
350      </Box>
351    );
352  });
353}
354