diff --git a/.agents-docs/AGENTS-architecture-install.md b/.agents-docs/AGENTS-architecture-install.md index d2cf843..94b6bf3 100644 --- a/.agents-docs/AGENTS-architecture-install.md +++ b/.agents-docs/AGENTS-architecture-install.md @@ -145,6 +145,7 @@ plan2code/ | `plan2code-diagnose.md` | diagnose | Find a bug's cause under the find-the-cause-first habit (`references/building-habits.md`) and write it up as `specs//DIAGNOSIS-.md` without fixing it, then offer Quick Task to fix it, or Plan when the fix is big. The dashboard scan reports such a folder as spec state `diagnosed` ("Bug diagnosed"), which lights Quick Task (suggested) and Plan. Once Quick Task marks the diagnosis `Fixed` (nothing past it in the folder) the state is `fixed` ("Bug fixed"): no pipeline card lights, the picker never pre-selects it, and Quick Task offers to archive it with `specs.mjs archive` | | `plan2code-pr-prep.md` | pr-prep | Get a branch ready for review: pick the checks its changes need from the project's `## Test map` (or its config files), let the person trim the plan, run it, give Ready, Ready with notes or Not ready, and write a PR description to copy (following the repo's template) with the create-a-PR link; offers to save `PR-READINESS-.md` into the branch's spec folder; never commits, pushes or opens the PR | | `plan2code-test.md` | test | Write missing tests: ask where to look, find source files no test covers (matching, plus real coverage when the project already has a coverage tool, offered first), show a plan opening with how this project writes tests, then write and run unit and integration tests; escalates past 8 source files, 8 new test files or 2 runners to a PLAN-DRAFT for Plan, hands a real bug to Diagnose, never changes source code | +| `plan2code-dead-code.md` | dead-code | Find unused code and dead code: use the project's own dead-code tools, one per language that has files (Knip, vulture, cargo check and others), or search by itself, check every item for callers across the project (`references/caller-search.md`), label each Safe to remove, Check first or Warning, remove only what the person picks, then run the tests and build and put back anything that breaks them; never commits, never installs a tool. Scripts: `dead-code.mjs` (own), `test-map.mjs`, `glob.mjs`, `test-commands.mjs`, `run-check.mjs` | | `plan2code-changelog.md` | changelog | Check the CHANGELOG version against the default branch, suggest editable entries for new work, keep `package.json` aligned, offer to commit the result through Git | | `plan2code-git.md` | git | Branches, pull (with conflict help), push, publish and commits (clear message, suggested splits) on the web console's git board, or plain instructions in the terminal (`switch to main`, `commit and push`); asks before every push, publish and delete | diff --git a/.agents-docs/AGENTS-architecture-skill-scripts.md b/.agents-docs/AGENTS-architecture-skill-scripts.md index c790715..f206f35 100644 --- a/.agents-docs/AGENTS-architecture-skill-scripts.md +++ b/.agents-docs/AGENTS-architecture-skill-scripts.md @@ -17,13 +17,14 @@ Anything a workflow step decides with one correct answer (parsing a spec's check | `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff, diagnose | `list` / `status` (the dashboard state, Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `check` / `check-draft` / `metrics` / `mark` / `tick` / `archive`. `list` imports `scanProject()` from the bundled `web-console/scan.mjs`, and `status` calls `deriveSpecState()` and `pickPhaseFiles()` from `web-console/spec-files.mjs`, the one rule the scan also uses, so the dashboard and the skills never disagree on a spec's state (a phase with only blocked tasks left stays `building`, and `finalizeReady` lights Finalize once each has a written reason). `mark` writes the phase file's Status line on every move (`--to in-progress` too). `check`'s format rules (no Status line, a checkbox under Notes, a task pointing at a line number, a bare `[!]`) warn, and fail only a spec whose overview.md carries ``. `archive` that has to copy removes the source only once every file name and size at the target matches (`PLAN2CODE_ARCHIVE_FAULT` is its test seam) | | `commit-msg.mjs` | implement(-review), review, quick-task, finalize, init-update, git | The `` / `AI Assisted` commit command (two `-m` flags), with an optional `git add -- ` from `--files`. There is no add-everything option: `--add-all` was retired, and `scripts/test-script-git.mjs` fails if it returns anywhere in `src/` | | `review-scope.mjs` | review, implement(-review), quick-task, finalize, pr-prep, test | Review Mode's git fallback: files, lines, doc share, base branch | -| `glob.mjs` | init, init-update, implement(-review), quick-task, finalize, pr-prep, test | The glob subset (`**`, `*`, `?`, `{a,b}`) as a RegExp, and forward-slash path normalizing; imported by `test-map.mjs` and `test-match.mjs` | -| `test-map.mjs` | init, init-update, implement(-review), quick-task, finalize, pr-prep, test | `read` / `write` the project test map (one `\| Area \| Paths \| Run \| Shared \|` table under `## Test map` in `AGENTS.md`, or behind one link to `.agents-docs/`); every line outside the table stays byte-identical | +| `glob.mjs` | init, init-update, implement(-review), quick-task, finalize, pr-prep, test, dead-code | The glob subset (`**`, `*`, `?`, `{a,b}`) as a RegExp, and forward-slash path normalizing; imported by `test-map.mjs` and `test-match.mjs` | +| `test-map.mjs` | init, init-update, implement(-review), quick-task, finalize, pr-prep, test, dead-code | `read` / `write` the project test map (one `\| Area \| Paths \| Run \| Shared \|` table under `## Test map` in `AGENTS.md`, or behind one link to `.agents-docs/`); every line outside the table stays byte-identical | | `test-match.mjs` | implement(-review), quick-task, finalize, pr-prep, test | `covers` (changed files to the map rows and tests that cover them, plus shared-ground hints), `gaps` (source files no test covers, ranked by recent change) and `nearest` (existing tests to read for style) | -| `test-commands.mjs` | init, init-update, pr-prep, test | `discover`: the whole-suite command, per-folder runners, lint/types/build checks, coverage commands already present and the language's built-in runner, from config files only | -| `run-check.mjs` | implement(-review), quick-task, finalize, pr-prep, test | Run one command with a timeout, kill its process tree on timeout, and classify it `passed`, `failed`, `timeout` or `not-started` with the output's tail | +| `test-commands.mjs` | init, init-update, pr-prep, test, dead-code | `discover`: the whole-suite command, per-folder runners, lint/types/build checks, coverage commands already present and the language's built-in runner, from config files only | +| `run-check.mjs` | implement(-review), quick-task, finalize, pr-prep, test, dead-code | Run one command with a timeout, kill its process tree on timeout, and classify it `passed`, `failed`, `timeout` or `not-started` with the output's tail | | `pr-prep.mjs` (own) | pr-prep | `template` (the PR template and its headings), `pr-url` (the create-a-PR link through `git-repo.mjs`) and `spec` (the branch's spec folder for the save offer). Read-only | | `coverage.mjs` (own) | test | `read --lcov` / `--go-func`: coverage output as per-file lines, hits and percent, plus the total. Read-only, runs no tool | +| `dead-code.mjs` (own) | dead-code | `detect` (the dead-code tools the project already has, languages, file counts), `run --tool` (a tool's output as candidates), `narrow` (folders ranked by candidates), `keep list\|filter\|add\|remove` (the shared keep list, `.plan2code-dead-code/keep.md`; rows matched by file, name and the hash of the item's declaration line, `#n` for the n-th identical line, `file:` for a whole file; `remove` takes `--hash` or `--line` and exits 2 `ambiguous-entry` when two rows share a name), `backup` and `restore --verify` (copies outside the project and a checked put-back), `report write` (`.plan2code-dead-code/reports/DEAD-CODE-.md`; `tool` one id or a list of ids) and `gitignore-check` / `gitignore-add`. Writes only code removals the agent makes, `keep.md` and, on a yes, a report and the `.gitignore` line | | `agents-md.mjs` | init, init-update | AGENTS.md structure, budget, orphans, broken links, always-inline sections. With no AGENTS.md yet (Init's run, so said once), `notices` warns when `.gitignore` keeps `specs--completed/` out of git, since archived specs are then not backed up | | `agent-files.mjs` | init, init-update | Detect and replace other agents' config files with AGENTS.md pointers | | `pathfinder.mjs` (own) | 0-pathfinder | `init` (the map in its Step 5 state from `--destination`, `--scores` and `--fog`; refuses an existing map) and `add` (the next `questions/NN-.md` plus its map row), with the references' templates kept as the fallback, then `reconcile`, `frontier`, `claim`, `resolve`, `rule-out`, `trail`, `gate` (which also prints the exact PLAN-DRAFT status line `specs.mjs` reads), `lint`, `brief-data`. Writes rows as `[Name](link): tail` with no em dash, and still reads maps written the old way | diff --git a/.agents-docs/AGENTS-development-commands.md b/.agents-docs/AGENTS-development-commands.md index a87cc10..e2f3131 100644 --- a/.agents-docs/AGENTS-development-commands.md +++ b/.agents-docs/AGENTS-development-commands.md @@ -87,6 +87,7 @@ The fast lane is `npm run test:fast` (`scripts/test-fast.mjs`): it runs the file | One web console area (server routes, chat, git board, workspace, notepad, Implementation Loop...) | that area's `scripts/test-web-console-.mjs` (the loop's is `test-web-console-loop.mjs`), and its `test-web-console-page-.mjs` when the page changed; `node scripts/parse-check.mjs` after editing any browser module under `public/` | | The launcher (`src/launcher/`) | `node --test scripts/test-launcher.mjs` | | A skill's script | `npm run build:skills`, then `node --test scripts/test-script-.mjs` (and `test-skill-scripts.mjs` for the shared plumbing) | +| Dead Code (`src/plan2code-dead-code-scripts/`, `scripts/fixtures/dead-code/`) | `npm run build:skills`, then `node scripts/node-test.mjs scripts/test-script-dead-code.mjs` | | A workflow prompt (`src/plan2code-*.md`) | `node scripts/validate-char-count.js` and `node scripts/check-skill-table.mjs` | | A new skill or console workflow | First update the hand-written tables that list every workflow: the `SUBAGENT_WORKFLOWS` count and the meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS` in `test-web-console-logic.mjs`, `notesFor` in `test-web-console-speed.mjs`, the event list in `src/web-console/console-meter.md` (checked by `test-web-console-chat-stress.mjs`) and a `BUDGETS.notes` entry in `test-console-wire-budgets.mjs`. Then run those four suites plus `test-web-console-skills.mjs` and `test-web-console-spec-states.mjs`; the PR Prep and Test build missed all five tables and only the full suite caught them | | Docs or comments only | `node --test scripts/test-us-english.mjs scripts/test-line-endings.mjs` | diff --git a/.readme/web-console-design.md b/.readme/web-console-design.md index 66dd21c..5298e48 100644 --- a/.readme/web-console-design.md +++ b/.readme/web-console-design.md @@ -310,7 +310,7 @@ Built for a mixed product and engineering room reading one screen together. - **One width variable.** `--card-width` on `:root` in `styles/tokens.css` sets the column the card, the pager and the document tabs share (`max-width: min(var(--card-width), 100%)`, so a narrow window still wins); no fixed `720px` column rule is left outside a media query. Three presets, picked under *Card width* in the looks panel and saved as `looks.width`: `narrow` 720px, `comfortable` 880px (the default, and the variable's own value), `wide` 1080px, applied as `:root[data-width="…"]`. `CARD_WIDTHS` in `palette.js` is the same list for the page's validation and the server's first-paint `data-width`; **`palette.js` and `app.css` must agree**, which is the one place the number is written twice. The dashboard keeps its own 860px layout. Inside the card the `62ch` / `68ch` measure caps come off (`.card .md, .card .prompt { max-width: none; }`) so a wider card is not a narrow column in a wide frame; documents keep `.md`'s 68ch. - **One box grows.** On the primary card, the answer box that is being typed in — a `text` question's box, a choice's *Something else* box once picked, or the note under a verdict / confirm / recap once shown — is `textarea.grow`, and the card takes the column's full height above the pager (`.card.is-primary.has-grow { flex: 1 1 auto; }`). `fitGrowBox()` in `app.js` writes the card's free height as the box's `min-height`, **never under 160px**; a `ResizeObserver` watches the main column rather than the box, so the box growing can never retrigger it, and it writes only on a change over 1px. `resize: vertical` with that moving floor makes the handle taller-only; past the fill the card scrolls. Every other box keeps its ordinary size, and the notes panel is untouched. -- **A switch per sound.** Every cue is an event in `SOUND_EVENTS` (`palette.js`), each naming its file and rank: `startSkill` (`sounds/sound-01.mp3`, played once the dashboard's **Start** is accepted) 5, `bootup` 4, `sessionStart` / `sessionEnd` (`sounds/sound-02.mp3`) 3, `question` / `skillReady` / `chatReply` (`sounds/sound-03.mp3`) 2, `newTab` (`sounds/sound-04.mp3`) 1, `snore` (`sleeping.mp3`, looped by the wake-up outside the queue) 0. The queue, the held slot and the one-at-a-time rule in `app.js` work on events, one `Audio` per file shared by the events that use it. User Preferences shows a *Play sounds* master (`looks.sound`) over one box per event, saved flat as `sound` (`soundStartSkill`, …) because `looks.json` only holds flat values; `soundPrefs()` turns any missing or non-boolean switch on, so a file from before the switches keeps every sound. A cue plays only while the master and its own switch are both on; the master off grays the boxes but keeps their ticks, and ticking a box plays it. Seven cues (not `snore` or `bootup`) also keep a pick out of the 19 files in `public/sounds/`, saved flat as `soundFile` (`soundFileQuestion`); `soundFilePrefs()` validates it against `SOUND_FILES` and a missing or unknown value falls back to the event's default, `sound.js` plays it, and the picker's select and Play button call `previewSound()`, which cuts off what is playing and is dropped behind a still-audible ranked cue. +- **A switch per sound.** Every cue is an event in `SOUND_EVENTS` (`palette.js`), each naming its file and rank: `startSkill` (`sounds/sound-14.mp3`, played once the dashboard's **Start** is accepted) 5, `bootup` 4, `sessionStart` (`sounds/sound-07.mp3`) / `sessionEnd` (`sounds/sound-15.mp3`) 3, `question` (`sounds/sound-14.mp3`) / `skillReady` (`sounds/sound-16.mp3`) / `chatReply` (`sounds/sound-06.mp3`) 2, `newTab` (`sounds/sound-05.mp3`) 1, `snore` (`sleeping.mp3`, looped by the wake-up outside the queue) 0. The queue, the held slot and the one-at-a-time rule in `app.js` work on events, one `Audio` per file shared by the events that use it. User Preferences shows a *Play sounds* master (`looks.sound`) over one box per event, saved flat as `sound` (`soundStartSkill`, …) because `looks.json` only holds flat values; `soundPrefs()` turns any missing or non-boolean switch on, so a file from before the switches keeps every sound. A cue plays only while the master and its own switch are both on; the master off grays the boxes but keeps their ticks, and ticking a box plays it. Seven cues (not `snore` or `bootup`) also keep a pick out of the 19 files in `public/sounds/`, saved flat as `soundFile` (`soundFileQuestion`); `soundFilePrefs()` validates it against `SOUND_FILES` and a missing or unknown value falls back to the event's default, `sound.js` plays it, and the picker's select and Play button call `previewSound()`, which cuts off what is playing and is dropped behind a still-audible ranked cue. - **Send breathes.** `#btn-send:not(:disabled)` runs `send-pulse`, a soft accent ring that spreads and fades every 2.4s; a disabled Send is still, and reduced motion switches it off. - **Per-tab scroll memory.** An in-memory `Map` keyed by view id holds the scroller's position (the main column on a document or the Overview, the card on the questions view, with the item it belonged to), restored when the tab comes back. Page-local, never persisted, cleared when the session turns into or out of the dashboard. - **The Overview tab.** Appears only while `GET /overview` returns a file for the session's spec (on the dashboard: the picker's spec; gone for *start from scratch*), fetched with `no-store` on load, on a spec change and on every tab click, so it always shows the file as it is on disk. On the dashboard, a spec with no overview gets a **Map** tab (`?file=map`, `pathfinder/map.md`) and a **Plan draft** tab (`?file=draft`, the live `PLAN-DRAFT-*.md`) in its place, each while its file exists, fetched and drawn the same way; away from the dashboard only the overview is read, since a session's own map or draft is the work already in front of it. Rendered through the same DOM-only markdown path as every doc, captioned read-only. It never becomes a doc: the page is not the record. diff --git a/.readme/web-console.md b/.readme/web-console.md index 32163d8..554fc80 100644 --- a/.readme/web-console.md +++ b/.readme/web-console.md @@ -55,7 +55,7 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so - The utility cards: Quick task, Review, Handoff and Git, which notes that the folder is not a git repository yet and offers to start one. + The utility cards: Get a PR ready, Write missing tests, Clear out dead code, Changelog, Git, which notes that the folder is not a git repository yet and offers to start one, and Handoff. --- @@ -322,8 +322,8 @@ command and the app use, so all three agree): system are listed, each with a Copy button, beside an **Install page** link. **Check again** re-runs the lookup without restarting anything, so an agent you just installed -turns up. Under the list are four starter templates (GitHub Copilot CLI, OpenCode, Gemini CLI, -Pi): starting setups for agent CLIs Plan2Code does not ship, which fill in the same form as adding +turns up. Under the list are five starter templates (GitHub Copilot CLI, OpenCode, Gemini CLI, +Pi, Cursor CLI): starting setups for agent CLIs Plan2Code does not ship, which fill in the same form as adding an agent by hand and save as custom agents. The page's Help has a *Setting up an agent* topic, and signing in to the agent itself is always your own step. diff --git a/AGENTS.md b/AGENTS.md index c652c3b..f73e6be 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ This file provides guidance to AI coding agents working with code in this reposi ## Project Overview -Plan2Code is a structured 4-step workflow methodology for AI-assisted software development. It provides prompt templates (skills) that the `skills` CLI installs globally or per-project into any agent it supports (README's "Supported tools" lists them). The `plan2code` command and the desktop app launch the dashboard directly in the built-in agents of `src/launcher/agents.json` (Claude Code, Devin, Codex); Copilot CLI, OpenCode, Gemini CLI and Pi are starter templates there, and any other agent CLI can be added as a custom agent. +Plan2Code is a structured 4-step workflow methodology for AI-assisted software development. It provides prompt templates (skills) that the `skills` CLI installs globally or per-project into any agent it supports (README's "Supported tools" lists them). The `plan2code` command and the desktop app launch the dashboard directly in the built-in agents of `src/launcher/agents.json` (Claude Code, Devin, Codex); Copilot CLI, OpenCode, Gemini CLI, Pi and Cursor CLI are starter templates there, and any other agent CLI can be added as a custom agent. **Version:** Check `version.json` for current version **Author:** Justin Parker @@ -36,7 +36,7 @@ Details: [Status line](./.agents-docs/AGENTS-architecture-statusline.md) ## Web Console -Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console//` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker page of game cards once two are listed that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-.js`, and keeps a best per course, `activityBestGolf`), and one number a game may keep between sessions in `activityMemo` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 21-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, Finalize, Changelog, Git and Handoff) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the twelve helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is a card plus pointers: `console.md` (the card) once per conversation, then a topic file (`console-*.md` such as `console-docs.md`, `notes/.md`, `building*.md`) only when the console names it in its own `read` output, once per session per topic (remembered in `pointers.json` in the session folder, owned by `pointers.mjs`); the console refuses the slips it can see (a `stop` with no `finish`, a `finish` while `stopWarning` is set, with `stop --force` for a dead page) instead of the docs repeating each rule. Byte budgets for the card, every notes file and a sample session's outputs run in `npm test` (`scripts/test-console-wire-budgets.mjs`). The server never writes into a project; the one thing it deletes there is an old `specs--completed/` the person picks in Cleanup, and only when git tracks it (an untracked one is refused, with the reason on the page). +Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console//` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker page of game cards once two are listed that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-.js`, and keeps a best per course, `activityBestGolf`), and one number a game may keep between sessions in `activityMemo` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 21-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, Finalize, Changelog, Git and Handoff) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the sixteen helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is a card plus pointers: `console.md` (the card) once per conversation, then a topic file (`console-*.md` such as `console-docs.md`, `notes/.md`, `building*.md`) only when the console names it in its own `read` output, once per session per topic (remembered in `pointers.json` in the session folder, owned by `pointers.mjs`); the console refuses the slips it can see (a `stop` with no `finish`, a `finish` while `stopWarning` is set, with `stop --force` for a dead page) instead of the docs repeating each rule. Byte budgets for the card, every notes file and a sample session's outputs run in `npm test` (`scripts/test-console-wire-budgets.mjs`). The server never writes into a project; the one thing it deletes there is an old `specs--completed/` the person picks in Cleanup, and only when git tracks it (an untracked one is refused, with the reason on the page). One agent list and one lookup rule serve the launcher, the console and the app: `src/launcher/agents.json` (the built-ins and starter templates with per-OS install data) and `src/web-console/agent-lookup.mjs` (`loadAgentList()` and `findAgent()`, both copied by `install.js` into `~/.plan2code/bin/`); the app carries a Rust twin held to the same cases by `scripts/fixtures/agent-lookup-cases.json`. Building or changing an Activities game: follow the game rules in [Activities](./.agents-docs/AGENTS-architecture-activities.md) ("Building an Activities game": lives in the solid lives pill, the endless-lives code (`cheat(on)`) in every game with lives, banners placed away from the player and see-through over what matters, pausing left to the window). diff --git a/QUICK-REFERENCE.md b/QUICK-REFERENCE.md index d673ba4..ddb3ddc 100644 --- a/QUICK-REFERENCE.md +++ b/QUICK-REFERENCE.md @@ -49,6 +49,7 @@ Every command below is what a dashboard card runs. Typed on its own, each one as | diagnose | /plan2code-diagnose | A bug, or none | `DIAGNOSIS-.md` with the cause and its evidence, then Quick Task (or Plan for a big fix) to fix it | | pr-prep | /plan2code-pr-prep | Your branch | A readiness verdict (Ready, Ready with notes, Not ready) and a PR description to copy; no commits, no push | | test | /plan2code-test | An area, or none | New unit and integration tests in the project's style, run; a bug handed to Diagnose; no source changes | +| dead-code | /plan2code-dead-code | A folder, or none | Findings labeled Safe, Check first or Warning, then only the removals you pick, checked by the tests and build; no commits, no installs | | changelog | /plan2code-changelog | Your branch | `CHANGELOG.md` entries and the `package.json` version, from the default branch's latest version | | git | /plan2code-git | Your repo | Commits (`` / `AI Assisted`), branches, pull with conflict help, push, publish | diff --git a/README.md b/README.md index 632faef..823193b 100644 --- a/README.md +++ b/README.md @@ -101,8 +101,8 @@ Devin or Codex, and no working custom agent), The page lists each agent as **Found**, **Found outside PATH** or **Not found**, with its install commands for your system, a Copy button per command and an **Install page** link. Install one and press **Check again**: no restart needed. An agent found outside `PATH` gets **Use it from here**, -which saves where it was found so you never touch `PATH` yourself. Below the list sit four starter -templates (GitHub Copilot CLI, OpenCode, Gemini CLI and Pi) for agents Plan2Code does not ship. +which saves where it was found so you never touch `PATH` yourself. Below the list sit five starter +templates (GitHub Copilot CLI, OpenCode, Gemini CLI, Pi and Cursor CLI) for agents Plan2Code does not ship. **Start with this agent** carries the run straight on in the same tab, onto the new agent's dashboard. Naming a built-in that is missing with `--cli ` opens the same page on that agent (a missing custom agent prints its own steps and exits 127). In the @@ -147,7 +147,7 @@ plain `plan2code` command above, without the app, asks instead, with prompts off GitHub Copilot · Windsurf · Codex · Continue · Codeium · Zed · Amp · OpenCode · Devin · Crush · Pi · Gemini CLI · Cline · Roo · Kilo · Goose · Trae · Qwen Code. -**Launched by `plan2code`:** the `plan2code` command and the desktop app open the dashboard directly in Claude Code, Devin and Codex (the built-ins in `src/launcher/agents.json`). GitHub Copilot CLI, OpenCode, Gemini CLI and Pi come as starter templates, and you can add any other agent CLI as a custom agent in User Preferences → Agents & models. +**Launched by `plan2code`:** the `plan2code` command and the desktop app open the dashboard directly in Claude Code, Devin and Codex (the built-ins in `src/launcher/agents.json`). GitHub Copilot CLI, OpenCode, Gemini CLI, Pi and Cursor CLI come as starter templates, and you can add any other agent CLI as a custom agent in User Preferences → Agents & models. The installer keeps one canonical copy of each skill under `~/.agents/skills/` and links it into agents that maintain their own directory. To update, run `plan2code update` (or re-run the install command); to remove it all, run `plan2code uninstall`. @@ -257,6 +257,7 @@ The dashboard's cards, and when each one lights up for the spec you pick: | Diagnose a bug | Find a bug's cause and write it up, without fixing it. | Always | | Get a PR ready | Runs the checks your branch needs, says if it is ready, and writes the PR description to copy. Never commits, pushes or opens the PR. | Always | | Write missing tests | Finds code with no tests and writes unit and integration tests in your project's own style. Never changes source code. | Always | +| Clear out dead code | Finds code nothing uses, says how safe each piece is to remove, and removes only what you pick. Uses the dead-code tools your project already has, and never commits. | Always | | Changelog | Checks the CHANGELOG version against the main branch and suggests entries for what is new. | Always | | Git | Branches, pull, push and commits on one board, asking before anything leaves your machine. | Always (offers to start a repository outside one) | @@ -429,6 +430,7 @@ console or the terminal; add `--web` to skip the question and go straight to the | `/plan2code-diagnose` | Find a bug's cause and write it up as `specs//DIAGNOSIS-.md` without fixing it, then offer `/plan2code-quick-task` to fix it, or `/plan2code-1-plan` when the fix is big | | `/plan2code-pr-prep` | Before you open a pull request. Picks the checks the branch's changes need from the project's `## Test map` (or its config files), runs the ones you keep, says Ready, Ready with notes or Not ready, and writes a PR description to copy with the create-a-PR link; never commits, pushes or opens the PR | | `/plan2code-test` | Parts of the code have no tests. Asks where to look, finds the untested files (plus real coverage when the project already has a coverage tool), shows a plan in the project's own style, then writes and runs unit and integration tests; never changes source code, hands a real bug to `/plan2code-diagnose` | +| `/plan2code-dead-code` | Code nothing calls anymore. Uses the project's own dead-code tools, one per language (Knip, vulture, cargo check and others), or searches by itself, checks every item for callers across the project, labels each Safe to remove, Check first or Warning, removes only what you pick, then runs the tests and build and puts back anything that breaks them; never commits, never installs anything | | `/plan2code-changelog` | Check the CHANGELOG version against the default branch, suggest entries for new work you can edit, keep `package.json` aligned, then hand off to Git to commit | | `/plan2code-git` | Branches, pull, push and commits on one board (or plain instructions in the terminal); asks before every push, publish and delete | diff --git a/docs/screenshots/dashboard-utilities-dark.webp b/docs/screenshots/dashboard-utilities-dark.webp index 981c72f..3b5ad33 100644 Binary files a/docs/screenshots/dashboard-utilities-dark.webp and b/docs/screenshots/dashboard-utilities-dark.webp differ diff --git a/docs/screenshots/dashboard-utilities-light.webp b/docs/screenshots/dashboard-utilities-light.webp index 6a0f792..cbbff57 100644 Binary files a/docs/screenshots/dashboard-utilities-light.webp and b/docs/screenshots/dashboard-utilities-light.webp differ diff --git a/install.js b/install.js index cd17065..18335cd 100644 --- a/install.js +++ b/install.js @@ -388,6 +388,22 @@ const SOURCE_PROMPTS = [ { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' } ] }, + { + source: 'plan2code-dead-code.md', + stepNumber: 'dead-code', + name: 'dead-code', + displayName: 'Dead Code Mode', + description: 'Find unused code and dead code, show how safe each is to remove, and remove only what you pick', + // Shown to the agent in place of the generic header text: when the skill fits and its command. + skillDescription: "Use when you want unused code paths and dead code in your project found, labeled by how safe each is to remove, and removed only where you pick. Run it as /plan2code-dead-code.", + isUtility: true, + scripts: ['test-map.mjs', 'glob.mjs', 'test-commands.mjs', 'run-check.mjs'], + additionalReferences: [ + { source: 'web-console', target: 'web-console' }, + { source: 'plan2code-dead-code-references/caller-search.md', target: 'caller-search.md' }, + { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' } + ] + }, { source: 'plan2code-changelog.md', stepNumber: 'changelog', @@ -440,6 +456,7 @@ function generateStepLabel(prompt) { if (prompt.stepNumber === 'diagnose') return 'Diagnose'; if (prompt.stepNumber === 'pr-prep') return 'PR Prep'; if (prompt.stepNumber === 'test') return 'Test'; + if (prompt.stepNumber === 'dead-code') return 'Dead Code'; if (prompt.stepNumber === 'changelog') return 'Changelog'; if (prompt.stepNumber === 'quick') return 'Quick Task'; return `Step ${prompt.stepNumber}`; diff --git a/package.json b/package.json index 1053f50..3b60379 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "play": "node scripts/play.mjs", "pretest": "node scripts/fix-line-endings.mjs", "test:fast": "node scripts/test-fast.mjs", - "test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs scripts/test-check-test-lanes.mjs scripts/test-check-doc-size.mjs scripts/test-set-version.mjs scripts/test-console-stub.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-console-openings.mjs" + "test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-dead-code.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-spec-carry.mjs scripts/test-spec-carry-page.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs scripts/test-check-test-lanes.mjs scripts/test-check-doc-size.mjs scripts/test-set-version.mjs scripts/test-console-stub.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-console-openings.mjs" }, "devDependencies": { "gpt-tokenizer": "2.9.0", diff --git a/scripts/check-console-openings.mjs b/scripts/check-console-openings.mjs index 3c7650a..b965fb0 100644 --- a/scripts/check-console-openings.mjs +++ b/scripts/check-console-openings.mjs @@ -76,7 +76,7 @@ export function check(srcDir) { if (!note) problems.push(`${file}: names no /notes/.md file`); else if (!fs.existsSync(path.join(notesDir, `${note[1]}.md`))) problems.push(`${file}: notes file ${note[1]}.md is not in src/web-console/notes/`); } - if (seen !== 18) problems.push(`expected 18 skills with a console opening, found ${seen}`); + if (seen !== 19) problems.push(`expected 19 skills with a console opening, found ${seen}`); return problems; } @@ -87,5 +87,5 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me for (const p of problems) console.error(` FAIL ${p}`); process.exit(1); } - console.log("All 18 console openings share their sentences."); + console.log("All 19 console openings share their sentences."); } diff --git a/scripts/fixtures/dead-code/cargo.ndjson b/scripts/fixtures/dead-code/cargo.ndjson new file mode 100644 index 0000000..7253131 --- /dev/null +++ b/scripts/fixtures/dead-code/cargo.ndjson @@ -0,0 +1,10 @@ +{"reason":"compiler-artifact","package_id":"demo 0.1.0","target":{"name":"demo"}} +{"reason":"compiler-message","package_id":"demo 0.1.0","message":{"code":{"code":"dead_code","explanation":null},"level":"warning","message":"function `old_helper` is never used","spans":[{"file_name":"src/lib.rs","line_start":8,"line_end":8,"is_primary":true}]}} +{"reason":"compiler-message","package_id":"demo 0.1.0","message":{"code":{"code":"dead_code","explanation":null},"level":"warning","message":"function `old_helper` is never used","spans":[{"file_name":"src/lib.rs","line_start":8,"line_end":8,"is_primary":true}]}} +{"reason":"compiler-message","package_id":"demo 0.1.0","message":{"code":{"code":"unused_imports","explanation":null},"level":"warning","message":"unused import: `std::io`","spans":[{"file_name":"src/main.rs","line_start":1,"line_end":1,"is_primary":true}]}} +{"reason":"compiler-message","package_id":"demo 0.1.0","message":{"code":{"code":"E0425","explanation":"..."},"level":"error","message":"cannot find value `x` in this scope","spans":[{"file_name":"src/main.rs","line_start":5,"line_end":5,"is_primary":true}]}} +{"reason":"compiler-message","package_id":"demo 0.1.0","message":{"code":null,"level":"warning","message":"1 warning emitted","spans":[]}} +{"reason":"build-finished","success":true} +{"reason":"compiler-message","package_id":"demo 0.1.0","message":{"code":{"code":"unused_imports","explanation":null},"level":"warning","message":"unused imports: `fmt` and `io`","spans":[{"file_name":"src/net.rs","line_start":2,"line_end":2,"column_start":11,"column_end":14,"is_primary":true,"text":[{"text":"use std::{fmt, io};","highlight_start":11,"highlight_end":14}]},{"file_name":"src/net.rs","line_start":2,"line_end":2,"column_start":16,"column_end":18,"is_primary":true,"text":[{"text":"use std::{fmt, io};","highlight_start":16,"highlight_end":18}]}]}} +{"reason":"compiler-message","package_id":"demo 0.1.0","message":{"code":{"code":"dead_code","explanation":null},"level":"warning","message":"multiple fields are never read","spans":[{"file_name":"src/model.rs","line_start":3,"line_end":3,"column_start":5,"column_end":9,"is_primary":false,"text":[{"text":"pub struct Model {","highlight_start":12,"highlight_end":17}]},{"file_name":"src/model.rs","line_start":4,"line_end":4,"column_start":5,"column_end":9,"is_primary":true,"text":[{"text":" name: String,","highlight_start":5,"highlight_end":9}]},{"file_name":"src/model.rs","line_start":5,"line_end":5,"column_start":5,"column_end":8,"is_primary":true,"text":[{"text":" age: u32,","highlight_start":5,"highlight_end":8}]}]}} +{"reason":"compiler-message", broken diff --git a/scripts/fixtures/dead-code/go-deadcode.txt b/scripts/fixtures/dead-code/go-deadcode.txt new file mode 100644 index 0000000..4404d31 --- /dev/null +++ b/scripts/fixtures/dead-code/go-deadcode.txt @@ -0,0 +1,3 @@ +internal/report/format.go:12:6: unreachable func: formatLegacy +cmd/tool/main.go:40:6: unreachable func: (*server).shutdownOld +not a deadcode line diff --git a/scripts/fixtures/dead-code/knip.json b/scripts/fixtures/dead-code/knip.json new file mode 100644 index 0000000..a2896c4 --- /dev/null +++ b/scripts/fixtures/dead-code/knip.json @@ -0,0 +1 @@ +{"files":["src/old.ts"],"issues":[{"file":"src/utils.ts","dependencies":[],"devDependencies":[],"files":[],"exports":[{"name":"formatDate","line":12,"col":17,"pos":250}],"types":[{"name":"Options","line":3,"col":13,"pos":40}],"enumMembers":{"Color":[{"name":"Purple","line":20,"col":3,"pos":400}]},"classMembers":{"Cache":[{"name":"flush","line":31,"col":3,"pos":600}]},"duplicates":[[{"name":"parse","line":40,"col":17},{"name":"default","line":44,"col":1}]]},{"file":"src/dead.ts","files":true,"exports":[],"types":[]},{"file":"src/broken.ts","exports":[{"line":2}]}]} diff --git a/scripts/fixtures/dead-code/pmd.sarif b/scripts/fixtures/dead-code/pmd.sarif new file mode 100644 index 0000000..b5e025a --- /dev/null +++ b/scripts/fixtures/dead-code/pmd.sarif @@ -0,0 +1,30 @@ +{ + "$schema": "https://json.schemastore.org/sarif-2.1.0.json", + "version": "2.1.0", + "runs": [ + { + "tool": { "driver": { "name": "PMD", "version": "7.29.0" } }, + "results": [ + { + "ruleId": "UnusedPrivateMethod", + "message": { "text": "Avoid unused private methods such as 'helper(String)'." }, + "locations": [{ "physicalLocation": { "artifactLocation": { "uri": "src/main/java/app/Service.java" }, "region": { "startLine": 42 } } }] + }, + { + "ruleId": "UnusedPrivateField", + "message": { "text": "Avoid unused private fields such as 'cache'." }, + "locations": [{ "physicalLocation": { "artifactLocation": { "uri": "src/main/java/app/Store.java" }, "region": { "startLine": 7 } } }] + }, + { + "ruleId": "UseUtilityClass", + "message": { "text": "This utility class has a non-private constructor" }, + "locations": [{ "physicalLocation": { "artifactLocation": { "uri": "src/main/java/app/Util.java" }, "region": { "startLine": 3 } } }] + }, + { + "ruleId": "UnusedLocalVariable", + "message": { "text": "Avoid unused local variables such as 'tmp'." } + } + ] + } + ] +} diff --git a/scripts/fixtures/dead-code/psalm.sarif b/scripts/fixtures/dead-code/psalm.sarif new file mode 100644 index 0000000..ff0c5ee --- /dev/null +++ b/scripts/fixtures/dead-code/psalm.sarif @@ -0,0 +1,25 @@ +{ + "version": "2.1.0", + "runs": [ + { + "tool": { "driver": { "name": "Psalm", "version": "7.2.0" } }, + "results": [ + { + "ruleId": "PossiblyUnusedMethod", + "message": { "text": "Cannot find any calls to method App\\Mailer::sendLater" }, + "locations": [{ "physicalLocation": { "artifactLocation": { "uri": "file:///ROOT/src/Mailer.php" }, "region": { "startLine": 18 } } }] + }, + { + "ruleId": "UnusedClass", + "message": { "text": "Class `App\\Legacy` is never used" }, + "locations": [{ "physicalLocation": { "artifactLocation": { "uri": "src/Legacy.php" }, "region": { "startLine": 5 } } }] + }, + { + "ruleId": "UnreachableCode", + "message": { "text": "Unreachable code" }, + "locations": [{ "physicalLocation": { "artifactLocation": { "uri": "src/Flow.php" }, "region": { "startLine": 30 } } }] + } + ] + } + ] +} diff --git a/scripts/fixtures/dead-code/vulture.txt b/scripts/fixtures/dead-code/vulture.txt new file mode 100644 index 0000000..7353574 --- /dev/null +++ b/scripts/fixtures/dead-code/vulture.txt @@ -0,0 +1,5 @@ +app/models.py:3: unused import 'os' (90% confidence) +app/models.py:14: unused function 'legacy_total' (60% confidence) +app/views.py:22: unused variable 'retries' (60% confidence, 1 line) +app/views.py:40: unreachable code after 'return' (100% confidence) +this line is mangled diff --git a/scripts/test-check-console-openings.mjs b/scripts/test-check-console-openings.mjs index eb86a4a..36bc9f9 100644 --- a/scripts/test-check-console-openings.mjs +++ b/scripts/test-check-console-openings.mjs @@ -58,7 +58,7 @@ test("a wrong workflow name or a missing notes file is reported", () => { test("a skill that loses its opening is caught by the count", () => { const dir = copySrc(); fs.rmSync(path.join(dir, "plan2code-pr-prep.md")); - assert.match(check(dir).join("\n"), /expected 18 skills with a console opening, found 17/); + assert.match(check(dir).join("\n"), /expected 19 skills with a console opening, found 18/); }); test("helpers", () => { @@ -66,6 +66,7 @@ test("helpers", () => { assert.equal(workflowOf("plan2code-1b-revise-plan"), "revise-plan"); assert.equal(workflowOf("plan2code-3-implement-review"), "implement-review"); assert.equal(workflowOf("plan2code-pr-prep"), "pr-prep"); + assert.equal(workflowOf("plan2code-dead-code"), "dead-code"); }); test("the CLI exits 1 on drift", () => { diff --git a/scripts/test-console-wire-budgets.mjs b/scripts/test-console-wire-budgets.mjs index 5afd67c..cf7d004 100644 --- a/scripts/test-console-wire-budgets.mjs +++ b/scripts/test-console-wire-budgets.mjs @@ -29,6 +29,7 @@ export const BUDGETS = { // Each topic file under notes/, read when its workflow starts. notes: { "changelog.md": 1400, + "dead-code.md": 4250, "diagnose.md": 2700, "document.md": 400, "finalize.md": 2000, diff --git a/scripts/test-lanes.json b/scripts/test-lanes.json index 8412b5a..3615452 100644 --- a/scripts/test-lanes.json +++ b/scripts/test-lanes.json @@ -15,6 +15,7 @@ "test-line-endings.mjs", "test-script-changelog.mjs", "test-script-coverage.mjs", + "test-script-dead-code.mjs", "test-script-finalize.mjs", "test-script-git.mjs", "test-script-pathfinder.mjs", @@ -27,6 +28,8 @@ "test-set-version.mjs", "test-skill-scripts.mjs", "test-skill-test-runs.mjs", + "test-spec-carry-page.mjs", + "test-spec-carry.mjs", "test-us-english.mjs", "test-web-console-agents-doc.mjs", "test-web-console-git-board.mjs", diff --git a/scripts/test-script-dead-code.mjs b/scripts/test-script-dead-code.mjs new file mode 100644 index 0000000..f13233c --- /dev/null +++ b/scripts/test-script-dead-code.mjs @@ -0,0 +1,1227 @@ +// Tests for plan2code-dead-code's scripts/dead-code.mjs: detection, running a +// tool, the output readers, narrow, the keep list, backup and restore, the +// saved report and the .gitignore check. See skill-script-helpers.mjs for how +// these run. No real dead-code tool is ever called: tools are stub files on a +// temp PATH, so the suite passes on a machine with none installed. + +import { test, after } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { ROOT, SKILLS, runScript, tmp, write, read, gitInit, copyFixture, fixtureCleanup } from "./skill-script-helpers.mjs"; + +after(fixtureCleanup); + +// The script runs from the built skill, beside the shared scripts it imports +// (skill-script-helpers.mjs rebuilds skills/ when this file loads it). +const SCRIPT = path.join(SKILLS, "plan2code-dead-code", "scripts", "dead-code.mjs"); + +const dc = await import(pathToFileURL(SCRIPT).href); +const FIXTURES = path.join(ROOT, "scripts", "fixtures", "dead-code"); +const fixture = (name) => fs.readFileSync(path.join(FIXTURES, name), "utf8"); + +// An empty folder as the whole PATH, so binaries installed on this machine +// never change what detect sees. pathDir replaces it with a folder of stubs. +const EMPTY_PATH = tmp("dead-code-empty-path"); + +/** Env additions that set PATH to exactly `dir`: every case variant of the key this process has is overridden, so the scrubbed copy keeps none of the machine's own. */ +function withPath(dir, extra = {}) { + const env = { ...extra }; + for (const key of Object.keys(process.env)) if (/^path$/i.test(key)) env[key] = dir; + env.PATH = dir; + return env; +} + +/** dead-code.mjs from the built skill; `pathDir` makes that folder the whole PATH. */ +function runDeadCode(args, { cwd, env, pathDir, input } = {}) { + return runScript("plan2code-dead-code", "dead-code.mjs", args, { cwd, input, env: pathDir ? withPath(pathDir, env) : env }); +} + +/* ------------------------------------------------------------------ help */ + +test("dead-code --help names every command and every exit code", () => { + const r = runDeadCode(["--help"]); + assert.equal(r.code, 0, r.stderr); + for (const command of ["detect", "run", "narrow", "keep", "backup", "restore", "report", "gitignore-check", "gitignore-add"]) { + assert.match(r.stdout, new RegExp(`dead-code\\.mjs ${command}\\b`), command); + } + for (const exit of ["0 ok", "1 crash", "2 bad arguments", "3 not found", "4 invalid", "5 refused"]) assert.ok(r.stdout.includes(exit), exit); + assert.match(r.stdout, /--dry-run/); + assert.match(r.stdout, /PLAN2CODE_NOW/); +}); + +test("dead-code: an unknown command and a missing one exit 2", () => { + const unknown = runDeadCode(["sweep"]); + assert.equal(unknown.code, 2); + assert.equal(unknown.json.error, "unknown-command"); + const missing = runDeadCode([]); + assert.equal(missing.code, 2); + assert.equal(missing.json.error, "missing-command"); +}); + +/* ---------------------------------------------------------------- detect */ + +/** A tool stub on a stub PATH: a node script, wrapped so the shell finds it by name. */ +function stub(dir, name, body) { + const js = path.join(dir, `${name}-stub.mjs`); + fs.writeFileSync(js, body); + if (process.platform === "win32") { + fs.writeFileSync(path.join(dir, `${name}.cmd`), `@"${process.execPath}" "${js}" %*\r\n@exit /b %errorlevel%\r\n`); + } else { + const sh = path.join(dir, name); + fs.writeFileSync(sh, `#!/bin/sh\nexec "${process.execPath}" "${js}" "$@"\n`); + fs.chmodSync(sh, 0o755); + } +} + +/** A stub that prints a fixture and exits with `code`. */ +const printing = (dir, name, fixtureName, code) => + stub(dir, name, `import fs from "node:fs";\nprocess.stdout.write(fs.readFileSync(${JSON.stringify(path.join(FIXTURES, fixtureName))}, "utf8"));\nprocess.exitCode = ${code};\n`); + +test("detect: counts source files by language group and skips build and vendor folders", () => { + const dir = tmp("dc-langs"); + for (const f of ["src/a.ts", "src/b.jsx", "app/c.py", "lib/d.rs", "e.go", "F.java", "g.kt", "h.cs", "i.rb", "j.php", "README.md"]) write(dir, f, "x\n"); + for (const f of ["node_modules/x/y.js", "dist/z.js", "vendor/v.php", ".venv/v.py", "target/t.rs", "specs/s.js", "specs--completed/s.js", "bin/b.cs", "obj/o.cs"]) write(dir, f, "x\n"); + const r = runDeadCode(["detect", "--root", dir], { pathDir: EMPTY_PATH }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.languages, [ + { id: "javascript", files: 2 }, + { id: "python", files: 1 }, + { id: "rust", files: 1 }, + { id: "go", files: 1 }, + { id: "java", files: 2 }, + { id: "csharp", files: 1 }, + { id: "ruby", files: 1 }, + { id: "php", files: 1 }, + ]); + assert.equal(r.json.sourceFiles, 10); + assert.equal(r.json.scope, "."); + assert.equal(r.json.limit, 1500); + assert.equal(r.json.overLimit, false); + assert.deepEqual(r.json.tools, []); +}); + +test("detect: overLimit is true past --limit, and --scope counts only that folder", () => { + const dir = tmp("dc-limit"); + for (const f of ["src/a.js", "src/b.js", "src/c.js", "src/d.js", "other/e.js"]) write(dir, f, "x\n"); + const scoped = runDeadCode(["detect", "--root", dir, "--scope", "src", "--limit", "3"], { pathDir: EMPTY_PATH }); + assert.equal(scoped.code, 0, scoped.stderr); + assert.equal(scoped.json.scope, "src"); + assert.equal(scoped.json.sourceFiles, 4); + assert.equal(scoped.json.overLimit, true); + assert.equal(scoped.json.limit, 3); + const under = runDeadCode(["detect", "--root", dir, "--scope", "src", "--limit", "4"], { pathDir: EMPTY_PATH }); + assert.equal(under.json.overLimit, false); + assert.equal(runDeadCode(["detect", "--root", dir, "--limit", "0"]).code, 2); +}); + +test("detect: a --scope outside the root, or not a folder, exits 3", () => { + const dir = tmp("dc-scope"); + write(dir, "src/a.js", "x\n"); + for (const scope of ["..", "../elsewhere", "missing", "src/a.js"]) { + const r = runDeadCode(["detect", "--root", dir, "--scope", scope], { pathDir: EMPTY_PATH }); + assert.equal(r.code, 3, scope); + assert.equal(r.json.error, "scope-not-found", scope); + } +}); + +const MARKERS = [ + ["knip", { "knip.json": "{}" }, "knip.json", "knip-json"], + ["knip", { "package.json": '{"devDependencies":{"knip":"^6.0.0"}}' }, "package.json devDependencies", "knip-json"], + ["knip", { "package.json": '{"knip":{"entry":["src/main.ts"]}}' }, "package.json knip key", "knip-json"], + ["vulture", { "pyproject.toml": "[project]\nname = 'x'\n\n[tool.vulture]\nmin_confidence = 80\n" }, "pyproject.toml [tool.vulture]", "vulture"], + ["vulture", { "requirements-dev.txt": "pytest\nvulture==2.14\n" }, "requirements-dev.txt", "vulture"], + ["cargo-check", { "Cargo.toml": "[package]\nname = 'x'\n" }, "Cargo.toml", "cargo-json"], + ["pmd", { "pom.xml": "maven-pmd-plugin" }, "pom.xml maven-pmd-plugin", "sarif"], + ["pmd", { "build.gradle": "plugins {\n id 'pmd'\n}\n" }, "Gradle pmd plugin", "sarif"], + ["pmd", { "config/pmd/ruleset.xml": "" }, "config/pmd/ruleset.xml", "sarif"], + ["spotbugs", { "build.gradle.kts": 'plugins { id("com.github.spotbugs") version "6.0.0" }\n' }, "build.gradle.kts spotbugs plugin", "sarif"], + ["detekt", { "detekt.yml": "style:\n" }, "detekt.yml", "sarif"], + ["psalm", { "psalm.xml": "" }, "psalm.xml", "sarif"], + ["psalm", { "composer.json": '{"require-dev":{"vimeo/psalm":"^7"}}' }, "composer.json vimeo/psalm", "sarif"], + ["rubocop", { ".rubocop.yml": "AllCops:\n" }, ".rubocop.yml", "agent"], + ["debride", { Gemfile: "source 'https://rubygems.org'\ngem 'debride'\n" }, "Gemfile debride", "agent"], + ["phpstan", { "phpstan.neon.dist": "parameters:\n" }, "phpstan.neon.dist", "agent"], + ["error-prone", { "pom.xml": "error_prone_core" }, "pom.xml Error Prone", "agent"], + ["java-compile", { "build.gradle": "apply plugin: 'java'\n" }, "build.gradle", "agent"], + ["dotnet-build", { "App.csproj": "" }, "App.csproj", "agent"], +]; + +test("detect: finds each tool by its own marker, never running or installing it", () => { + for (const [id, files, marker, format] of MARKERS) { + const dir = tmp(`dc-marker-${id}`); + for (const [rel, content] of Object.entries(files)) write(dir, rel, content); + const r = runDeadCode(["detect", "--root", dir], { pathDir: EMPTY_PATH }); + assert.equal(r.code, 0, r.stderr); + const found = r.json.tools.find((t) => t.id === id); + assert.ok(found, `${id} from ${Object.keys(files).join(", ")}: got ${JSON.stringify(r.json.tools)}`); + assert.equal(found.marker, marker, id); + assert.equal(found.format, format, id); + assert.equal(found.available, false, `${id} has no binary on the empty PATH`); + assert.equal(typeof found.command, "string"); + } +}); + +test("detect: knip without node_modules/.bin/knip is unavailable, and its command never installs", () => { + const dir = tmp("dc-knip"); + write(dir, "package.json", '{"devDependencies":{"knip":"^6.0.0"}}'); + const missing = runDeadCode(["detect", "--root", dir], { pathDir: EMPTY_PATH }).json.tools.find((t) => t.id === "knip"); + assert.equal(missing.available, false); + assert.equal(missing.command, "npx --no-install knip --reporter json"); + write(dir, "node_modules/.bin/knip", ""); + const present = runDeadCode(["detect", "--root", dir], { pathDir: EMPTY_PATH }).json.tools.find((t) => t.id === "knip"); + assert.equal(present.available, true); +}); + +test("detect: tools found only on PATH, and Go deadcode only with go.mod and the binary", () => { + const dir = tmp("dc-path"); + write(dir, "go.mod", "module x\n"); + write(dir, "main.go", "package main\n"); + assert.deepEqual(runDeadCode(["detect", "--root", dir], { pathDir: EMPTY_PATH }).json.tools, [], "no deadcode binary, no tool"); + const bin = tmp("dc-path-bin"); + stub(bin, "deadcode", ""); + stub(bin, "vulture", ""); + const r = runDeadCode(["detect", "--root", dir], { pathDir: bin }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual( + r.json.tools.map((t) => [t.id, t.marker, t.available]), + [ + ["vulture", "vulture on PATH", true], + ["go-deadcode", "go.mod and deadcode on PATH", true], + ] + ); +}); + +test("detect: a SARIF tool's command shows a placeholder for the report file", () => { + const dir = tmp("dc-sarif-cmd"); + write(dir, "psalm.xml", ""); + write(dir, "detekt.yml", "style:\n"); + const tools = runDeadCode(["detect", "--root", dir], { pathDir: EMPTY_PATH }).json.tools; + assert.equal(tools.find((t) => t.id === "detekt").command, "detekt --input . --config detekt.yml --report sarif:"); + assert.equal(tools.find((t) => t.id === "psalm").command, "psalm --find-unused-code --report= ."); +}); + +/* ------------------------------------------------------------------- run */ + +test("run: a vulture stub's exit 3 is findings, not a failure, and --scope filters the result", () => { + const dir = tmp("dc-run-vulture"); + write(dir, "pyproject.toml", "[tool.vulture]\n"); + write(dir, "app/models.py", "import os\n"); + write(dir, "other/x.py", "\n"); + const bin = tmp("dc-run-vulture-bin"); + printing(bin, "vulture", "vulture.txt", 3); + const r = runDeadCode(["run", "--tool", "vulture", "--root", dir], { pathDir: bin }); + assert.equal(r.code, 0, r.stderr + r.stdout); + assert.equal(r.json.tool, "vulture"); + assert.equal(r.json.format, "vulture"); + assert.equal(r.json.exit, 3); + assert.equal(r.json.unparsed, false); + assert.equal(r.json.skipped, 1); + assert.equal(r.json.candidates.length, 4); + assert.ok(r.json.tail.includes("this line is mangled")); + assert.equal(typeof r.json.seconds, "number"); + + const app = runDeadCode(["run", "--tool", "vulture", "--root", dir, "--scope", "app"], { pathDir: bin }); + assert.equal(app.code, 0, app.stderr); + assert.equal(app.json.scope, "app"); + assert.equal(app.json.candidates.length, 4); + const other = runDeadCode(["run", "--tool", "vulture", "--root", dir, "--scope", "other"], { pathDir: bin }); + assert.equal(other.code, 0, other.stderr); + assert.deepEqual(other.json.candidates, []); +}); + +test("run: an exit the tool does not use for findings is a failure (exit 4) with the tail", () => { + const dir = tmp("dc-run-fail"); + write(dir, "pyproject.toml", "[tool.vulture]\n"); + const bin = tmp("dc-run-fail-bin"); + stub(bin, "vulture", 'console.error("vulture: bad config");\nprocess.exitCode = 1;\n'); + const r = runDeadCode(["run", "--tool", "vulture", "--root", dir], { pathDir: bin }); + assert.equal(r.code, 4); + assert.equal(r.json.error, "tool-failed"); + assert.equal(r.json.exit, 1); + assert.deepEqual(r.json.tail, ["vulture: bad config"]); +}); + +test("run: a timeout stops the tool and exits 4", () => { + const dir = tmp("dc-run-timeout"); + write(dir, "pyproject.toml", "[tool.vulture]\n"); + const bin = tmp("dc-run-timeout-bin"); + stub(bin, "vulture", "setTimeout(() => {}, 20000);\n"); + const r = runDeadCode(["run", "--tool", "vulture", "--root", dir, "--timeout", "1"], { pathDir: bin }); + assert.equal(r.code, 4, r.stdout); + assert.equal(r.json.error, "tool-timeout"); +}); + +test("run: an unknown id exits 2; a tool not set up, or set up with no binary, exits 3", () => { + const dir = tmp("dc-run-missing"); + write(dir, "pyproject.toml", "[tool.vulture]\n"); + assert.equal(runDeadCode(["run", "--tool", "sweeper", "--root", dir], { pathDir: EMPTY_PATH }).code, 2); + assert.equal(runDeadCode(["run", "--root", dir], { pathDir: EMPTY_PATH }).code, 2); + const notSetUp = runDeadCode(["run", "--tool", "knip", "--root", dir], { pathDir: EMPTY_PATH }); + assert.equal(notSetUp.code, 3); + assert.equal(notSetUp.json.error, "tool-not-detected"); + const noBinary = runDeadCode(["run", "--tool", "vulture", "--root", dir], { pathDir: EMPTY_PATH }); + assert.equal(noBinary.code, 3); + assert.equal(noBinary.json.error, "tool-unavailable"); +}); + +test("run: a SARIF tool writes its report to a temp file the script reads back", () => { + const dir = tmp("dc-run-pmd"); + write(dir, "pom.xml", "maven-pmd-plugin"); + const bin = tmp("dc-run-pmd-bin"); + // PMD exits 4 when it finds violations. + stub( + bin, + "pmd", + `import fs from "node:fs";\nconst a = process.argv.slice(2);\nfs.copyFileSync(${JSON.stringify(path.join(FIXTURES, "pmd.sarif"))}, a[a.indexOf("-r") + 1]);\nprocess.exitCode = 4;\n` + ); + const r = runDeadCode(["run", "--tool", "pmd", "--root", dir], { pathDir: bin }); + assert.equal(r.code, 0, r.stderr + r.stdout); + assert.equal(r.json.format, "sarif"); + assert.equal(r.json.exit, 4); + assert.equal(r.json.unparsed, false); + assert.deepEqual( + r.json.candidates.map((c) => [c.file, c.line, c.rule]), + [ + ["src/main/java/app/Service.java", 42, "UnusedPrivateMethod"], + ["src/main/java/app/Store.java", 7, "UnusedPrivateField"], + ["src/main/java/app/Util.java", 3, "UseUtilityClass"], + ] + ); + // PMD's exit 5 (a file it could not parse) still writes the report. + fs.writeFileSync(path.join(bin, "pmd-stub.mjs"), fs.readFileSync(path.join(bin, "pmd-stub.mjs"), "utf8").replace("process.exitCode = 4", "process.exitCode = 5")); + const recoverable = runDeadCode(["run", "--tool", "pmd", "--root", dir], { pathDir: bin }); + assert.equal(recoverable.code, 0, recoverable.stderr + recoverable.stdout); + assert.equal(recoverable.json.exit, 5); + assert.equal(recoverable.json.candidates.length, 3); +}); + +test("detect: PMD runs only its unused-code rules, whatever ruleset the project keeps", () => { + const dir = tmp("dc-pmd-rules"); + write(dir, "pmd-ruleset.xml", ""); + const pmd = runDeadCode(["detect", "--root", dir], { pathDir: EMPTY_PATH }).json.tools.find((t) => t.id === "pmd"); + assert.equal(pmd.marker, "pmd-ruleset.xml"); + const rules = ["UnusedPrivateMethod", "UnusedPrivateField", "UnusedLocalVariable", "UnusedFormalParameter", "UnusedAssignment"].map((r) => `category/java/bestpractices.xml/${r}`).join(","); + assert.equal(pmd.command, `pmd check -d . -R ${rules} -f sarif -r `); +}); + +test("run: Knip's exit 1 is findings, read from its JSON report", () => { + const dir = tmp("dc-run-knip"); + write(dir, "package.json", '{"devDependencies":{"knip":"^6.0.0"}}'); + write(dir, "node_modules/.bin/knip", ""); + const bin = tmp("dc-run-knip-bin"); + // The command is `npx --no-install knip --reporter json`; the stub stands in for npx. + stub( + bin, + "npx", + `import fs from "node:fs";\nif (process.argv.slice(2).join(" ") !== "--no-install knip --reporter json") { console.error("unexpected args"); process.exit(9); }\nprocess.stdout.write(fs.readFileSync(${JSON.stringify(path.join(FIXTURES, "knip.json"))}, "utf8"));\nprocess.exitCode = 1;\n` + ); + const r = runDeadCode(["run", "--tool", "knip", "--root", dir], { pathDir: bin }); + assert.equal(r.code, 0, r.stderr + r.stdout); + assert.equal(r.json.exit, 1); + assert.equal(r.json.format, "knip-json"); + assert.equal(r.json.unparsed, false); + assert.equal(r.json.candidates.length, 7); +}); + +test("run: Psalm's SARIF is read back from its .sarif.json report, and exit 2 is findings", () => { + const dir = tmp("dc-run-psalm"); + write(dir, "psalm.xml", ""); + const bin = tmp("dc-run-psalm-bin"); + stub( + bin, + "psalm", + `import fs from "node:fs";\nimport { pathToFileURL } from "node:url";\nconst arg = process.argv.slice(2).find((a) => a.startsWith("--report="));\nconst report = arg.slice("--report=".length);\nif (!report.endsWith(".sarif.json")) process.exit(9);\nfs.writeFileSync(report, fs.readFileSync(${JSON.stringify(path.join(FIXTURES, "psalm.sarif"))}, "utf8").replace("file:///ROOT/", pathToFileURL(process.cwd()).href + "/"));\nprocess.exitCode = 2;\n` + ); + const r = runDeadCode(["run", "--tool", "psalm", "--root", dir], { pathDir: bin }); + assert.equal(r.code, 0, r.stderr + r.stdout); + assert.equal(r.json.exit, 2); + assert.equal(r.json.unparsed, false); + assert.deepEqual( + r.json.candidates.map((c) => [c.file, c.line, c.rule]), + [ + ["src/Mailer.php", 18, "PossiblyUnusedMethod"], + ["src/Legacy.php", 5, "UnusedClass"], + ["src/Flow.php", 30, "UnreachableCode"], + ] + ); +}); + +test("run: a tool in the agent format comes back unparsed with its output tail", () => { + const dir = tmp("dc-run-agent"); + write(dir, ".rubocop.yml", "AllCops:\n"); + const bin = tmp("dc-run-agent-bin"); + stub(bin, "rubocop", 'console.log("app/models/user.rb:12:3: W: Lint/UnusedPrivateMethod: Private method legacy is unused.");\nprocess.exitCode = 1;\n'); + const r = runDeadCode(["run", "--tool", "rubocop", "--root", dir], { pathDir: bin }); + assert.equal(r.code, 0, r.stderr + r.stdout); + assert.equal(r.json.format, "agent"); + assert.equal(r.json.unparsed, true); + assert.deepEqual(r.json.candidates, []); + assert.deepEqual(r.json.tail, ["app/models/user.rb:12:3: W: Lint/UnusedPrivateMethod: Private method legacy is unused."]); +}); + +/* --------------------------------------------------------------- readers */ + +const cand = (file, line, name, kind, rule, message) => ({ file, line, name, kind, source: "tool", rule, message }); + +test("readers: SARIF from PMD, with a result that has no location counted in skipped", () => { + const r = dc.readOutput("sarif", fixture("pmd.sarif"), "/proj"); + assert.equal(r.unparsed, false); + assert.equal(r.skipped, 1); + assert.deepEqual(r.candidates, [ + cand("src/main/java/app/Service.java", 42, "helper(String)", "unused", "UnusedPrivateMethod", "Avoid unused private methods such as 'helper(String)'."), + cand("src/main/java/app/Store.java", 7, "cache", "unused", "UnusedPrivateField", "Avoid unused private fields such as 'cache'."), + cand("src/main/java/app/Util.java", 3, "", "unknown", "UseUtilityClass", "This utility class has a non-private constructor"), + ]); +}); + +test("readers: SARIF from Psalm, with a file: URI made relative to the root", () => { + const root = tmp("dc-psalm-root"); + const text = fixture("psalm.sarif").replace("file:///ROOT/", `${pathToFileURL(root).href}/`); + const r = dc.readOutput("sarif", text, root); + assert.equal(r.unparsed, false); + assert.deepEqual(r.candidates, [ + cand("src/Mailer.php", 18, "App\\Mailer::sendLater", "unused", "PossiblyUnusedMethod", "Cannot find any calls to method App\\Mailer::sendLater"), + cand("src/Legacy.php", 5, "App\\Legacy", "unused", "UnusedClass", "Class `App\\Legacy` is never used"), + cand("src/Flow.php", 30, "", "unreachable", "UnreachableCode", "Unreachable code"), + ]); + assert.equal(dc.readOutput("sarif", "{not json", root).unparsed, true); +}); + +test("readers: Knip JSON files, exports, types, enum and class members and duplicates", () => { + const r = dc.readOutput("knip-json", `npm notice something\n${fixture("knip.json")}`, "/proj"); + assert.equal(r.unparsed, false); + assert.equal(r.skipped, 1, "the export with no name"); + assert.deepEqual(r.candidates, [ + cand("src/old.ts", null, "", "file", "files", "Unused file"), + cand("src/utils.ts", 12, "formatDate", "export", "exports", "Unused export formatDate"), + cand("src/utils.ts", 3, "Options", "type", "types", "Unused type Options"), + cand("src/utils.ts", 20, "Color.Purple", "enum-member", "enumMembers", "Unused enum member Color.Purple"), + cand("src/utils.ts", 31, "Cache.flush", "class-member", "classMembers", "Unused class member Cache.flush"), + cand("src/utils.ts", 40, "parse, default", "duplicate", "duplicates", "Unused duplicate parse, default"), + cand("src/dead.ts", null, "", "file", "files", "Unused file"), + ]); + assert.equal(dc.readOutput("knip-json", "Knip crashed\n", "/proj").unparsed, true); +}); + +test("readers: vulture lines keep the confidence, and a mangled line is counted in skipped", () => { + const r = dc.readOutput("vulture", fixture("vulture.txt"), "/proj"); + assert.equal(r.skipped, 1); + assert.equal(r.unparsed, false); + assert.deepEqual(r.candidates, [ + cand("app/models.py", 3, "os", "import", "vulture-import", "unused import 'os' (90% confidence)"), + cand("app/models.py", 14, "legacy_total", "function", "vulture-function", "unused function 'legacy_total' (60% confidence)"), + cand("app/views.py", 22, "retries", "variable", "vulture-variable", "unused variable 'retries' (60% confidence)"), + cand("app/views.py", 40, "", "unreachable code", "vulture-unreachable-code", "unreachable code after 'return' (100% confidence)"), + ]); +}); + +test("readers: cargo JSON keeps dead_code and unused_* once each, and a broken record is skipped", () => { + const r = dc.readOutput("cargo-json", ` Compiling demo v0.1.0\n${fixture("cargo.ndjson")}`, "/proj"); + assert.equal(r.skipped, 1); + assert.equal(r.unparsed, false); + assert.deepEqual(r.candidates, [ + cand("src/lib.rs", 8, "old_helper", "function", "dead_code", "function `old_helper` is never used"), + cand("src/main.rs", 1, "std::io", "unused_imports", "unused_imports", "unused import: `std::io`"), + // One warning that groups two items: one candidate per primary span, named from the span. + cand("src/net.rs", 2, "fmt", "unused_imports", "unused_imports", "unused imports: `fmt` and `io`"), + cand("src/net.rs", 2, "io", "unused_imports", "unused_imports", "unused imports: `fmt` and `io`"), + cand("src/model.rs", 4, "name", "field", "dead_code", "multiple fields are never read"), + cand("src/model.rs", 5, "age", "field", "dead_code", "multiple fields are never read"), + ]); +}); + +test("readers: Go deadcode lines, with a mangled line counted in skipped", () => { + const r = dc.readOutput("go-deadcode", fixture("go-deadcode.txt"), "/proj"); + assert.equal(r.skipped, 1); + assert.deepEqual(r.candidates, [ + cand("internal/report/format.go", 12, "formatLegacy", "func", "deadcode", "unreachable func: formatLegacy"), + cand("cmd/tool/main.go", 40, "(*server).shutdownOld", "func", "deadcode", "unreachable func: (*server).shutdownOld"), + ]); +}); + +test("readers: output where every line is dropped comes back unparsed, and absolute paths are made relative", () => { + assert.deepEqual(dc.readOutput("go-deadcode", "panic: something\ngoroutine 1\n", "/proj"), { candidates: [], skipped: 2, unparsed: true }); + assert.equal(dc.readOutput("agent", "anything", "/proj").unparsed, true); + const root = tmp("dc-abs"); + const abs = path.join(root, "pkg", "a.py"); + const r = dc.readOutput("vulture", `${abs}:3: unused import 'os' (90% confidence)\n`, root); + assert.equal(r.candidates[0].file, "pkg/a.py"); +}); + +/* ---------------------------------------------------------------- narrow */ + +test("narrow: folders ranked by candidate count, ties by path, at --depth", () => { + const dir = tmp("dc-narrow"); + const files = ["src/b/x.ts", "src/b/y.ts", "src/a/q.ts", "src/a/deep/r.ts", "lib/c.ts", "top.ts", "src/c/z.ts"]; + write(dir, "run.json", JSON.stringify({ ok: true, candidates: files.map((file) => ({ file })) })); + const r = runDeadCode(["narrow", "--candidates", path.join(dir, "run.json")]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json, { + ok: true, + folders: [ + { path: "src/a", candidates: 2 }, + { path: "src/b", candidates: 2 }, + { path: ".", candidates: 1 }, + { path: "lib", candidates: 1 }, + { path: "src/c", candidates: 1 }, + ], + total: 7, + }); + write(dir, "bare.json", JSON.stringify(files.map((file) => ({ file })))); + const shallow = runDeadCode(["narrow", "--candidates", path.join(dir, "bare.json"), "--depth", "1"]); + assert.deepEqual(shallow.json.folders, [ + { path: "src", candidates: 5 }, + { path: ".", candidates: 1 }, + { path: "lib", candidates: 1 }, + ]); +}); + +test("narrow: a missing file exits 3, invalid JSON or no candidates array exits 4", () => { + const dir = tmp("dc-narrow-bad"); + assert.equal(runDeadCode(["narrow", "--candidates", path.join(dir, "none.json")]).code, 3); + write(dir, "bad.json", "{not json"); + assert.equal(runDeadCode(["narrow", "--candidates", path.join(dir, "bad.json")]).code, 4); + write(dir, "obj.json", '{"ok":true}'); + assert.equal(runDeadCode(["narrow", "--candidates", path.join(dir, "obj.json")]).code, 4); + assert.equal(runDeadCode(["narrow"]).code, 2); +}); + +/* ------------------------------------------------------------- keep list */ + +const KEEP = ".plan2code-dead-code/keep.md"; + +/** A small project: two source files with declarations to keep. */ +function keepProject(name) { + const dir = tmp(name); + write(dir, "src/a.js", "export function foo() {\n return 1;\n}\n\nexport function bar() {}\n"); + write(dir, "src/b.js", "export const gone = 1;\n"); + return dir; +} + +/** Every file under dir with its content, for "nothing was written" checks. */ +function snapshot(dir) { + const files = {}; + const walk = (d) => { + for (const entry of fs.readdirSync(d, { withFileTypes: true })) { + const p = path.join(d, entry.name); + if (entry.isDirectory()) { + if (entry.name !== ".git") walk(p); + } else files[path.relative(dir, p).split(path.sep).join("/")] = fs.readFileSync(p, "utf8"); + } + }; + walk(dir); + return files; +} + +test("keep add: writes the keep table, and a second add for the same item replaces it", () => { + const dir = keepProject("dc-keep-add"); + const first = runDeadCode(["keep", "add", "--file", "src/a.js", "--name", "foo", "--line", "1", "--reason", "Called by the | plugin loader"], { cwd: dir }); + assert.equal(first.code, 0, first.stderr); + assert.equal(first.json.replaced, false); + assert.equal(first.json.entry.date, "2026-08-03"); + assert.match(first.json.entry.hash, /^[0-9a-f]{12}$/); + const text = read(dir, KEEP); + assert.match(text, /^# Dead Code keep list/); + assert.match(text, /shared and safe to commit/); + assert.match(text, /\| File \| Name \| Hash \| Reason \| Date \|/); + assert.match(text, /\| src\/a\.js \| foo \| [0-9a-f]{12} \| Called by the \\\| plugin loader \| 2026-08-03 \|/); + + // Prose the person added survives a rewrite. + fs.appendFileSync(path.join(dir, KEEP), "\nAsk the platform team before removing anything here.\n"); + const again = runDeadCode(["keep", "add", "--file", "src/a.js", "--name", "foo", "--line", "1", "--reason", "Still needed"], { cwd: dir }); + assert.equal(again.json.replaced, true); + const list = runDeadCode(["keep", "list"], { cwd: dir }); + assert.equal(list.json.exists, true); + assert.deepEqual( + list.json.entries.map((e) => [e.file, e.name, e.reason, e.state]), + [["src/a.js", "foo", "Still needed", "current"]] + ); + assert.match(read(dir, KEEP), /Ask the platform team/); +}); + +test("keep add: an empty reason exits 2, a missing line exits 3, and keep list with no file is empty", () => { + const dir = keepProject("dc-keep-bad"); + for (const reason of ["", " "]) { + const r = runDeadCode(["keep", "add", "--file", "src/a.js", "--name", "foo", "--line", "1", "--reason", reason], { cwd: dir }); + assert.equal(r.code, 2, JSON.stringify(reason)); + assert.equal(r.json.error, "missing-reason"); + } + assert.equal(runDeadCode(["keep", "add", "--file", "src/a.js", "--name", "foo", "--line", "99", "--reason", "x"], { cwd: dir }).code, 3); + assert.equal(fs.existsSync(path.join(dir, KEEP)), false); + const list = runDeadCode(["keep", "list"], { cwd: dir }); + assert.deepEqual([list.code, list.json.exists, list.json.entries], [0, false, []]); + assert.equal(runDeadCode(["keep", "sweep"], { cwd: dir }).code, 2); +}); + +test("keep filter: hides a current entry, shows an edited one as wasKept, lists a deleted file as gone; --fresh shows all", () => { + const dir = keepProject("dc-keep-filter"); + const add = (file, name, line, reason) => assert.equal(runDeadCode(["keep", "add", "--file", file, "--name", name, "--line", String(line), "--reason", reason], { cwd: dir }).code, 0); + add("src/a.js", "foo", 1, "Plugin hook"); + add("src/a.js", "bar", 5, "Public API"); + add("src/b.js", "gone", 1, "Old reason"); + // A line added above foo moves it; only the edit to bar's line counts as a change. + write(dir, "src/a.js", "// header\nexport function foo() {\n return 1;\n}\n\nexport function bar(x) {}\n"); + fs.rmSync(path.join(dir, "src/b.js")); + + const candidates = [ + { file: "src/a.js", line: 2, name: "foo", kind: "export", source: "tool", rule: "exports", message: "" }, + { file: "src/a.js", line: 6, name: "bar", kind: "export", source: "tool", rule: "exports", message: "" }, + { file: "src/c.js", line: 1, name: "other", kind: "export", source: "tool", rule: "exports", message: "" }, + ]; + const r = runDeadCode(["keep", "filter"], { cwd: dir, input: JSON.stringify(candidates) }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.hidden.map((c) => [c.name, c.keptReason]), [["foo", "Plugin hook"]]); + assert.deepEqual(r.json.shown.map((c) => [c.name, c.wasKept || false, c.keptReason || null]), [["bar", true, "Public API"], ["other", false, null]]); + assert.equal(r.json.changed, 1); + assert.deepEqual(r.json.kept, [ + { file: "src/a.js", name: "foo", reason: "Plugin hook" }, + { file: "src/a.js", name: "bar", reason: "Public API" }, + { file: "src/b.js", name: "gone", reason: "Old reason", gone: true }, + ]); + const states = runDeadCode(["keep", "list"], { cwd: dir }).json.entries.map((e) => e.state); + assert.deepEqual(states, ["current", "changed", "gone"]); + + // run's whole output works as input too; --fresh hides nothing but still counts the list. + const fresh = runDeadCode(["keep", "filter", "--fresh"], { cwd: dir, input: JSON.stringify({ ok: true, candidates }) }); + assert.equal(fresh.json.fresh, true); + assert.deepEqual(fresh.json.hidden, []); + assert.equal(fresh.json.shown.length, 3); + assert.equal(fresh.json.kept.length, 3); + + assert.equal(runDeadCode(["keep", "filter"], { cwd: dir, input: "not json" }).code, 4); +}); + +/* -------------------------------------------- keep matching by line hash */ + +// Two classes, each with a `save` method on a different line, and two +// identical `def save(self):` lines in a third class pair. +const SAVES = ["class A:", " def save(self, path):", " pass", "", "class B:", " def save(self):", " pass", "", "class C:", " def save(self):", " pass", ""].join("\n"); + +/** keep add for an item, asserting it worked; returns the row it wrote. */ +function keepAt(dir, file, name, line, reason) { + const args = ["keep", "add", "--file", file, "--line", String(line), "--reason", reason]; + if (name !== null) args.push("--name", name); + const r = runDeadCode(args, { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + return r.json.entry; +} + +/** A row appended to the keep table by hand (the table is the file's last block). */ +function keepRowByHand(dir, { file, name, hash, reason }) { + fs.appendFileSync(path.join(dir, KEEP), `| ${file} | ${name} | ${hash} | ${reason} | 2026-08-03 |\n`); +} + +const filterKept = (dir, candidates) => { + const r = runDeadCode(["keep", "filter"], { cwd: dir, input: JSON.stringify(candidates) }); + assert.equal(r.code, 0, r.stderr); + return r.json; +}; +const keepCand = (file, line, name) => ({ file, line, name, kind: "function", source: "tool", rule: "unused", message: "" }); +const keepStates = (dir) => runDeadCode(["keep", "list"], { cwd: dir }).json.entries.map((e) => [e.hash, e.state]); + +test("keep filter: keeping one of two same-named items in a file hides only that one", () => { + const dir = tmp("dc-keep-same-name"); + write(dir, "m.py", SAVES); + keepAt(dir, "m.py", "save", 2, "Called by the plugin host"); + const r = filterKept(dir, [keepCand("m.py", 2, "save"), keepCand("m.py", 6, "save")]); + assert.deepEqual(r.hidden.map((c) => c.line), [2]); + assert.deepEqual(r.shown.map((c) => [c.line, c.wasKept || false]), [[6, false]]); +}); + +test("keep filter: keeping one of two empty-name findings in a file hides only that one", () => { + const dir = tmp("dc-keep-empty-name"); + write(dir, "u.py", "def f():\n return 1\n print('a')\n\ndef g():\n return 2\n print('b')\n"); + keepAt(dir, "u.py", null, 3, "Left for the debugger"); + const r = filterKept(dir, [keepCand("u.py", 3, ""), keepCand("u.py", 7, "")]); + assert.deepEqual(r.hidden.map((c) => c.line), [3]); + assert.deepEqual(r.shown.map((c) => c.line), [7]); +}); + +test("keep add on a repeated line writes #n, and keep filter tells the copies apart", () => { + const dir = tmp("dc-keep-repeat"); + write(dir, "m.py", SAVES); + const second = keepAt(dir, "m.py", "save", 10, "Second copy stays"); + assert.match(second.hash, /^[0-9a-f]{12}#2$/); + assert.equal(second.hash, dc.declHash(dir, "m.py", 10).hash); + const both = [keepCand("m.py", 6, "save"), keepCand("m.py", 10, "save")]; + const one = filterKept(dir, both); + assert.deepEqual([one.hidden.map((c) => c.line), one.shown.map((c) => [c.line, c.wasKept || false])], [[10], [[6, false]]]); + + const first = dc.declHash(dir, "m.py", 6); + assert.deepEqual([first.hash.endsWith("#1"), first.base, first.copies], [true, second.hash.slice(0, 12), 2]); + keepRowByHand(dir, { file: "m.py", name: "save", hash: first.hash, reason: "First copy stays" }); + const two = filterKept(dir, both); + assert.deepEqual([two.hidden.map((c) => [c.line, c.keptReason]), two.shown], [[[6, "First copy stays"], [10, "Second copy stays"]], []]); +}); + +test("keep filter: a kept item that moved down five lines stays hidden and reads current", () => { + const dir = tmp("dc-keep-moved"); + write(dir, "m.py", SAVES); + keepAt(dir, "m.py", "save", 2, "Plugin hook"); + write(dir, "m.py", "# one\n# two\n# three\n# four\n# five\n" + SAVES); + const r = filterKept(dir, [keepCand("m.py", 7, "save"), keepCand("m.py", 11, "save")]); + assert.deepEqual([r.hidden.map((c) => c.line), r.shown.map((c) => c.line)], [[7], [11]]); + assert.deepEqual(keepStates(dir).map((s) => s[1]), ["current"]); +}); + +test("keep filter: a #n row whose copies drop to one reads changed and flags the copy left", () => { + const dir = tmp("dc-keep-copy-gone"); + write(dir, "m.py", SAVES); + keepAt(dir, "m.py", "save", 10, "Second copy stays"); + // Class B goes, so class C's save is now the only `def save(self):` line. + write(dir, "m.py", SAVES.split("\n").slice(0, 4).concat(SAVES.split("\n").slice(8)).join("\n")); + assert.deepEqual(keepStates(dir).map((s) => s[1]), ["changed"]); + const r = filterKept(dir, [keepCand("m.py", 6, "save")]); + assert.deepEqual([r.hidden, r.shown.map((c) => [c.line, c.wasKept, c.keptReason]), r.changed], [[], [[6, true, "Second copy stays"]], 1]); +}); + +test("keep filter: a plain row whose line now repeats reads changed and both copies are shown", () => { + const dir = tmp("dc-keep-pasted"); + write(dir, "m.py", "class A:\n def load(self):\n pass\n"); + keepAt(dir, "m.py", "load", 2, "Loaded by name"); + fs.appendFileSync(path.join(dir, "m.py"), "\nclass B:\n def load(self):\n pass\n"); + assert.deepEqual(keepStates(dir).map((s) => s[1]), ["changed"]); + const r = filterKept(dir, [keepCand("m.py", 2, "load"), keepCand("m.py", 6, "load")]); + assert.deepEqual(r.hidden, []); + assert.deepEqual(r.shown.map((c) => [c.line, c.wasKept, c.keptReason]), [[2, true, "Loaded by name"], [6, true, "Loaded by name"]]); +}); + +test("keep filter: a whole-file row hides the whole-file finding only, not an empty-name finding inside it", () => { + const dir = keepProject("dc-keep-whole-only"); + assert.equal(runDeadCode(["keep", "add", "--file", "src/a.js", "--reason", "Loaded at runtime"], { cwd: dir }).code, 0); + const r = filterKept(dir, [{ file: "src/a.js", line: null, name: "", kind: "file" }, keepCand("src/a.js", 2, "")]); + assert.deepEqual(r.hidden.map((c) => [c.line, c.keptReason]), [[null, "Loaded at runtime"]]); + assert.deepEqual(r.shown.map((c) => [c.line, c.wasKept || false]), [[2, false]]); +}); + +test("keep filter: a keep.md written in the old format loads, reads current and hides its item", () => { + const dir = keepProject("dc-keep-old-format"); + const hash = dc.declHash(dir, "src/a.js", 1).hash; + assert.match(hash, /^[0-9a-f]{12}$/); + write(dir, KEEP, `# Dead Code keep list\n\n| File | Name | Hash | Reason | Date |\n| --- | --- | --- | --- | --- |\n| src/a.js | foo | ${hash} | Plugin hook | 2026-01-02 |\n`); + assert.deepEqual(keepStates(dir), [[hash, "current"]]); + const r = filterKept(dir, [keepCand("src/a.js", 1, "foo")]); + assert.deepEqual([r.hidden.map((c) => c.keptReason), r.shown], [["Plugin hook"], []]); +}); + +test("keep filter: a line-less named finding matches a whole-file row kept with that name, a lined one does not", () => { + const dir = keepProject("dc-keep-whole-named"); + const add = runDeadCode(["keep", "add", "--file", "src/a.js", "--name", "foo", "--reason", "Whole module stays"], { cwd: dir }); + assert.equal(add.code, 0, add.stderr); + assert.match(add.json.entry.hash, /^file:[0-9a-f]{12}$/); + const r = filterKept(dir, [keepCand("src/a.js", null, "foo"), keepCand("src/a.js", 1, "foo")]); + assert.deepEqual(r.hidden.map((c) => [c.line, c.keptReason]), [[null, "Whole module stays"]]); + assert.deepEqual(r.shown.map((c) => [c.line, c.wasKept || false]), [[1, false]]); +}); + +test("keep filter: a candidate outside the project counts as line-less, so its file is never read", () => { + const box = tmp("dc-keep-outside"); + write(box, "outside.js", "export function foo() {}\nexport function foo2() {}\n"); + const dir = path.join(box, "proj"); + write(dir, "src/a.js", "export function foo() {}\n"); + keepAt(dir, "src/a.js", "foo", 1, "Kept inside"); + // A row for line 2 of the outside file: read and hashed, line 1 would match no row and be + // shown; treated as line-less, the candidate matches the row by name and is hidden. + const line2 = dc.declHash(box, "outside.js", 2).hash; + keepRowByHand(dir, { file: "../outside.js", name: "foo", hash: line2, reason: "Outside row" }); + const r = filterKept(dir, [keepCand("../outside.js", 1, "foo")]); + assert.deepEqual([r.hidden.map((c) => [c.file, c.keptReason]), r.shown], [[["../outside.js", "Outside row"]], []]); +}); + +test("keep remove: takes an entry off, and exits 3 when it is not there", () => { + const dir = keepProject("dc-keep-remove"); + runDeadCode(["keep", "add", "--file", "src/a.js", "--name", "foo", "--line", "1", "--reason", "One"], { cwd: dir }); + runDeadCode(["keep", "add", "--file", "src/a.js", "--name", "bar", "--line", "5", "--reason", "Two"], { cwd: dir }); + const r = runDeadCode(["keep", "remove", "--file", "src/a.js", "--name", "foo"], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.removed.reason, "One"); + assert.deepEqual(runDeadCode(["keep", "list"], { cwd: dir }).json.entries.map((e) => e.name), ["bar"]); + const missing = runDeadCode(["keep", "remove", "--file", "src/a.js", "--name", "foo"], { cwd: dir }); + assert.equal(missing.code, 3); + assert.equal(missing.json.error, "not-kept"); +}); + +// Two same-named methods whose declaration lines differ. +const TWO_SAVES = ["class A:", " def save(self, path):", " pass", "", "class B:", " def save(self, other):", " pass", ""].join("\n"); +const keepRows = (dir) => runDeadCode(["keep", "list"], { cwd: dir }).json.entries; + +test("keep add: two same-named items with different lines are kept as two current rows, and both are hidden", () => { + const dir = tmp("dc-keep-add-two"); + write(dir, "m.py", TWO_SAVES); + const a = keepAt(dir, "m.py", "save", 2, "Plugin hook"); + const add = runDeadCode(["keep", "add", "--file", "m.py", "--name", "save", "--line", "6", "--reason", "Called by name"], { cwd: dir }); + assert.equal(add.code, 0, add.stderr); + assert.equal(add.json.replaced, false); + assert.deepEqual(keepRows(dir).map((e) => [e.hash, e.state]), [[a.hash, "current"], [add.json.entry.hash, "current"]]); + const r = filterKept(dir, [keepCand("m.py", 2, "save"), keepCand("m.py", 6, "save")]); + assert.deepEqual([r.hidden.map((c) => c.line), r.shown], [[2, 6], []]); +}); + +test("keep add: two identical declaration lines are kept as #1 and #2", () => { + const dir = tmp("dc-keep-add-copies"); + write(dir, "m.py", SAVES); + const first = keepAt(dir, "m.py", "save", 6, "First copy"); + const second = keepAt(dir, "m.py", "save", 10, "Second copy"); + assert.match(first.hash, /^[0-9a-f]{12}#1$/); + assert.equal(second.hash, `${first.hash.slice(0, 12)}#2`); + assert.deepEqual(keepRows(dir).map((e) => [e.hash, e.state]), [[first.hash, "current"], [second.hash, "current"]]); +}); + +test("keep add: keeping an item again after its line changed replaces the stale row", () => { + const dir = tmp("dc-keep-add-stale"); + write(dir, "m.py", "class A:\n def save(self, path):\n pass\n"); + keepAt(dir, "m.py", "save", 2, "Plugin hook"); + write(dir, "m.py", "class A:\n def save(self, path, mode):\n pass\n"); + assert.deepEqual(keepRows(dir).map((e) => e.state), ["changed"]); + const again = runDeadCode(["keep", "add", "--file", "m.py", "--name", "save", "--line", "2", "--reason", "Still a plugin hook"], { cwd: dir }); + assert.equal(again.code, 0, again.stderr); + assert.equal(again.json.replaced, true); + assert.deepEqual(keepRows(dir).map((e) => [e.hash, e.reason, e.state]), [[again.json.entry.hash, "Still a plugin hook", "current"]]); +}); + +test("keep add: keeping an unchanged item again only updates its reason", () => { + const dir = tmp("dc-keep-add-reason"); + write(dir, "m.py", TWO_SAVES); + const first = keepAt(dir, "m.py", "save", 2, "Old reason"); + const again = runDeadCode(["keep", "add", "--file", "m.py", "--name", "save", "--line", "2", "--reason", "New reason"], { cwd: dir }); + assert.equal(again.json.replaced, true); + assert.deepEqual(keepRows(dir).map((e) => [e.hash, e.reason]), [[first.hash, "New reason"]]); +}); + +test("keep remove: two rows sharing file and name exit 2 ambiguous-entry, listing both, and write nothing", () => { + const dir = tmp("dc-keep-remove-ambiguous"); + write(dir, "m.py", TWO_SAVES); + const a = keepAt(dir, "m.py", "save", 2, "Plugin hook"); + const b = keepAt(dir, "m.py", "save", 6, "Called by name"); + const before = fs.readFileSync(path.join(dir, KEEP)); + const r = runDeadCode(["keep", "remove", "--file", "m.py", "--name", "save"], { cwd: dir }); + assert.equal(r.code, 2); + assert.equal(r.json.error, "ambiguous-entry"); + assert.match(r.json.message, /matches 2 keep entries/); + for (const row of [a, b]) assert.ok(r.json.next.includes(`${row.hash} (${row.reason})`), r.json.next); + assert.match(r.json.next, /--hash/); + assert.match(r.json.next, /--line/); + assert.ok(fs.readFileSync(path.join(dir, KEEP)).equals(before), "keep.md is unchanged byte for byte"); +}); + +test("keep remove: --line and --hash each take off exactly the named row, and an unknown --hash exits 3", () => { + const dir = tmp("dc-keep-remove-pick"); + write(dir, "m.py", TWO_SAVES); + const a = keepAt(dir, "m.py", "save", 2, "Plugin hook"); + const b = keepAt(dir, "m.py", "save", 6, "Called by name"); + const byLine = runDeadCode(["keep", "remove", "--file", "m.py", "--name", "save", "--line", "6"], { cwd: dir }); + assert.equal(byLine.code, 0, byLine.stderr); + assert.equal(byLine.json.removed.hash, b.hash); + assert.deepEqual(keepRows(dir).map((e) => e.hash), [a.hash]); + + keepAt(dir, "m.py", "save", 6, "Called by name"); + const byHash = runDeadCode(["keep", "remove", "--file", "m.py", "--name", "save", "--hash", a.hash], { cwd: dir }); + assert.equal(byHash.code, 0, byHash.stderr); + assert.equal(byHash.json.removed.reason, "Plugin hook"); + assert.deepEqual(keepRows(dir).map((e) => e.hash), [b.hash]); + + const unknown = runDeadCode(["keep", "remove", "--file", "m.py", "--name", "save", "--hash", "000000000000"], { cwd: dir }); + assert.equal(unknown.code, 3); + assert.equal(unknown.json.error, "not-kept"); + assert.deepEqual(keepRows(dir).map((e) => e.hash), [b.hash]); + + const noLine = runDeadCode(["keep", "remove", "--file", "m.py", "--name", "save", "--line", "99"], { cwd: dir }); + assert.deepEqual([noLine.code, noLine.json.error], [3, "declaration-missing"]); + // With both rows kept, --hash names A's row and --line names B's: both must match, so neither comes off. + keepAt(dir, "m.py", "save", 2, "Plugin hook"); + const disagree = runDeadCode(["keep", "remove", "--file", "m.py", "--name", "save", "--hash", a.hash, "--line", "6"], { cwd: dir }); + assert.deepEqual([disagree.code, disagree.json.error], [3, "not-kept"]); + assert.deepEqual(keepRows(dir).map((e) => e.hash), [b.hash, a.hash]); +}); + +/* ------------------------------------------------------ backup, restore */ + +/** The per-user backup folder name under the temp folder (the script adds the user id). */ +const backupFolder = () => "plan2code-dead-code-" + (typeof process.getuid === "function" ? process.getuid() : os.userInfo().username.replace(/[^A-Za-z0-9._-]/g, "_")); +/** Point the script's temp folder (os.tmpdir) at `dir`. */ +const tempEnv = (dir) => ({ TEMP: dir, TMP: dir, TMPDIR: dir }); + +test("backup: copies without moving, and a second call with --run extends the manifest", () => { + const dir = keepProject("dc-backup"); + const temp = tmp("dc-backup-temp"); + const env = tempEnv(temp); + const first = runDeadCode(["backup", "src/a.js"], { cwd: dir, env }); + assert.equal(first.code, 0, first.stderr); + assert.match(first.json.run, /^20260803-140500-[0-9a-f]{4}$/); + assert.equal(path.resolve(first.json.dir), path.join(temp, backupFolder(), first.json.run)); + assert.ok(fs.existsSync(path.join(dir, "src/a.js")), "the source is still there"); + assert.equal(fs.readFileSync(path.join(first.json.dir, "files", "src", "a.js"), "utf8"), read(dir, "src/a.js")); + + // An edited file backed up again in the same run keeps its first copy. + write(dir, "src/a.js", "edited\n"); + const second = runDeadCode(["backup", "src/a.js", "src/b.js", "--run", first.json.run], { cwd: dir, env }); + assert.equal(second.code, 0, second.stderr); + assert.deepEqual(second.json.files.map((f) => f.path), ["src/b.js"]); + assert.deepEqual(second.json.already, ["src/a.js"]); + const manifest = JSON.parse(fs.readFileSync(path.join(first.json.dir, "manifest.json"), "utf8")); + assert.deepEqual(manifest.files.map((f) => f.path), ["src/a.js", "src/b.js"]); + for (const f of manifest.files) assert.match(f.sha256, /^[0-9a-f]{64}$/); + assert.notEqual(fs.readFileSync(path.join(first.json.dir, "files", "src", "a.js"), "utf8"), "edited\n"); +}); + +test("backup: a missing file exits 3 and copies nothing; a bad run id exits 2", () => { + const dir = keepProject("dc-backup-missing"); + const temp = tmp("dc-backup-missing-temp"); + const r = runDeadCode(["backup", "src/a.js", "src/none.js", "--run", "r1"], { cwd: dir, env: tempEnv(temp) }); + assert.equal(r.code, 3); + assert.equal(r.json.error, "file-missing"); + assert.equal(fs.existsSync(path.join(temp, backupFolder(), "r1")), false); + assert.equal(runDeadCode(["backup", "src/a.js", "--run", "../up"], { cwd: dir, env: tempEnv(temp) }).code, 2); + assert.equal(runDeadCode(["backup"], { cwd: dir, env: tempEnv(temp) }).code, 2); +}); + +test("restore: brings back a deleted and a changed file, byte for byte", () => { + const dir = keepProject("dc-restore"); + write(dir, "src/deep/c.js", "crlf\r\nline\r\n"); + const env = tempEnv(tmp("dc-restore-temp")); + const before = snapshot(dir); + const { run } = runDeadCode(["backup", "src/a.js", "src/deep/c.js"], { cwd: dir, env }).json; + fs.rmSync(path.join(dir, "src/deep"), { recursive: true }); + write(dir, "src/a.js", "removed foo\n"); + + const check = runDeadCode(["restore", "--run", run, "--verify"], { cwd: dir, env }); + assert.equal(check.code, 4); + assert.deepEqual(check.json.mismatched.map((m) => m.path).sort(), ["src/a.js", "src/deep/c.js"]); + + const r = runDeadCode(["restore", "--run", run], { cwd: dir, env }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.restored.sort(), ["src/a.js", "src/deep/c.js"]); + assert.deepEqual(r.json.mismatched, []); + assert.deepEqual(snapshot(dir), before); + const verify = runDeadCode(["restore", "--run", run, "--verify"], { cwd: dir, env }); + assert.equal(verify.code, 0); + assert.deepEqual(verify.json.verified.sort(), ["src/a.js", "src/deep/c.js"]); +}); + +test("restore: --files puts back only those, --verify copies nothing, and a tampered copy exits 4 as mismatched", () => { + const dir = keepProject("dc-restore-tamper"); + const env = tempEnv(tmp("dc-restore-tamper-temp")); + const { run, dir: backupDir } = runDeadCode(["backup", "src/a.js", "src/b.js"], { cwd: dir, env }).json; + write(dir, "src/a.js", "changed a\n"); + write(dir, "src/b.js", "changed b\n"); + + const verify = runDeadCode(["restore", "--run", run, "--verify"], { cwd: dir, env }); + assert.equal(verify.code, 4); + assert.equal(verify.json.ok, false); + assert.equal(read(dir, "src/a.js"), "changed a\n", "--verify copied nothing"); + + const one = runDeadCode(["restore", "--run", run, "--files", "src/b.js"], { cwd: dir, env }); + assert.deepEqual([one.code, one.json.restored], [0, ["src/b.js"]]); + assert.equal(read(dir, "src/a.js"), "changed a\n"); + assert.equal(read(dir, "src/b.js"), "export const gone = 1;\n"); + + fs.writeFileSync(path.join(backupDir, "files", "src", "a.js"), "tampered\n"); + const bad = runDeadCode(["restore", "--run", run], { cwd: dir, env }); + assert.equal(bad.code, 4); + assert.equal(bad.json.ok, false); + assert.deepEqual(bad.json.mismatched.map((m) => m.path), ["src/a.js"]); + assert.match(bad.json.mismatched[0].reason, /backup copy damaged/); + assert.deepEqual(bad.json.restored, ["src/b.js"]); + assert.equal(read(dir, "src/a.js"), "changed a\n", "a damaged copy is never copied over the project file"); +}); + +test("restore: a manifest path edited to point outside the project exits 5 and copies nothing", () => { + const dir = keepProject("dc-restore-escape"); + const env = tempEnv(tmp("dc-restore-escape-temp")); + const { run, dir: backupDir } = runDeadCode(["backup", "src/a.js", "src/b.js"], { cwd: dir, env }).json; + write(dir, "src/a.js", "changed a\n"); + const manifestFile = path.join(backupDir, "manifest.json"); + const manifest = JSON.parse(fs.readFileSync(manifestFile, "utf8")); + manifest.files[1].path = "../escaped.js"; + fs.mkdirSync(path.join(backupDir, "files", ".."), { recursive: true }); + fs.writeFileSync(path.join(backupDir, "escaped.js"), "export const gone = 1;\n"); + fs.writeFileSync(manifestFile, JSON.stringify(manifest)); + + const r = runDeadCode(["restore", "--run", run], { cwd: dir, env }); + assert.equal(r.code, 5); + assert.equal(r.json.error, "outside-root"); + assert.equal(fs.existsSync(path.join(path.dirname(dir), "escaped.js")), false); + assert.equal(read(dir, "src/a.js"), "changed a\n", "nothing was copied"); +}); + +test("a file inside the project whose name starts with .. is not outside it", () => { + const dir = keepProject("dc-dotdot"); + write(dir, "..odd.js", "export const odd = 1;\n"); + const env = tempEnv(tmp("dc-dotdot-temp")); + const backup = runDeadCode(["backup", "..odd.js"], { cwd: dir, env }); + assert.equal(backup.code, 0, backup.stderr); + assert.deepEqual(backup.json.files.map((f) => f.path), ["..odd.js"]); + assert.equal(runDeadCode(["keep", "add", "--file", "..odd.js", "--name", "odd", "--line", "1", "--reason", "r"], { cwd: dir }).code, 0); +}); + +test("restore: a run with no manifest, or a file it does not hold, exits 3", () => { + const dir = keepProject("dc-restore-missing"); + const env = tempEnv(tmp("dc-restore-missing-temp")); + assert.equal(runDeadCode(["restore", "--run", "20260101-000000-abcd"], { cwd: dir, env }).code, 3); + const { run } = runDeadCode(["backup", "src/a.js"], { cwd: dir, env }).json; + const r = runDeadCode(["restore", "--run", run, "--files", "src/b.js"], { cwd: dir, env }); + assert.equal(r.code, 3); + assert.equal(r.json.error, "not-backed-up"); + assert.equal(runDeadCode(["restore"], { cwd: dir, env }).code, 2); +}); + +test("a path outside the project root exits 5 for keep add, backup and restore", () => { + const dir = keepProject("dc-outside"); + write(path.dirname(dir), `${path.basename(dir)}-sibling.js`, "x\n"); + const outside = `../${path.basename(dir)}-sibling.js`; + const env = tempEnv(tmp("dc-outside-temp")); + assert.equal(runDeadCode(["keep", "add", "--file", outside, "--name", "x", "--line", "1", "--reason", "r"], { cwd: dir }).code, 5); + const backup = runDeadCode(["backup", outside], { cwd: dir, env }); + assert.equal(backup.code, 5); + assert.equal(backup.json.error, "outside-root"); + const { run } = runDeadCode(["backup", "src/a.js"], { cwd: dir, env }).json; + assert.equal(runDeadCode(["restore", "--run", run, "--files", outside], { cwd: dir, env }).code, 5); + fs.rmSync(path.join(path.dirname(dir), `${path.basename(dir)}-sibling.js`), { force: true }); +}); + +/* ---------------------------------------------------------------- report */ + +const FINDINGS = { + scope: "src", + mode: "verify", + tool: "knip", + ranFrom: "complete", + hidden: 2, + findings: [ + { file: "src/a.js", line: 3, name: "foo", kind: "export", source: "both", rule: "exports", label: "safe", callers: "none found", outcome: "removed" }, + { file: "src/b.js", line: null, name: "", kind: "file", source: "own", rule: null, label: "check", callers: [], outcome: "failed: npm test\nAssertionError | boom" }, + { file: "src/c.js", line: 9, name: "onLoad", kind: "function", source: "tool", rule: "exports", label: "warning", warningKind: "plugin or framework hook", outcome: "kept" }, + ], +}; + +const findingsFile = (dir, doc) => write(dir, "findings.json", JSON.stringify(doc)); + +test("report write: three sections in order with label, source, rule, reason and outcome, and a complete run says so", () => { + const dir = tmp("dc-report"); + const r = runDeadCode(["report", "write", "--findings", findingsFile(dir, FINDINGS)], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.path, ".plan2code-dead-code/reports/DEAD-CODE-2026-08-03.md"); + const text = read(dir, r.json.path); + assert.match(text, /^# Dead Code report/); + assert.match(text, /\*\*Date:\*\* 2026-08-03/); + assert.match(text, /\*\*Tool:\*\* knip/); + assert.match(text, /\*\*Full search of our own:\*\* no/); + assert.match(text, /1 Safe to remove, 1 Check first, 1 Warning/); + assert.match(text, /1 removed, 1 failed, 1 kept/); + assert.match(text, /\*\*Hidden by the keep list:\*\* 2/); + const safe = text.indexOf("## Safe to remove"); + const check = text.indexOf("## Check first"); + const warning = text.indexOf("## Warning"); + assert.ok(safe > 0 && safe < check && check < warning, "Safe, Check first, Warning in order"); + assert.match(text, /\| Item \| Location \| Source \| Rule \| Reason \| Outcome \|/); + assert.match(text, /\| foo \| src\/a\.js:3 \| both \| exports \| none found \| removed \|/); + assert.match(text, /\| \(whole file\) \| src\/b\.js \| own search \| - \| - \| failed: npm test AssertionError \\\| boom \|/); + assert.match(text, /\| onLoad \| src\/c\.js:9 \| tool \| exports \| plugin or framework hook \| kept \|/); + assert.match(text, /This run was complete/); + assert.doesNotMatch(text, /narrowed/); +}); + +test("report write: a narrowed run is stated as narrowed, and a stopped one as not complete", () => { + const dir = tmp("dc-report-narrowed"); + const narrowed = runDeadCode(["report", "write", "--findings", findingsFile(dir, { ...FINDINGS, ranFrom: "narrowed", notChecked: "lib/ and test/" })], { cwd: dir }); + assert.equal(narrowed.code, 0, narrowed.stderr); + const text = read(dir, narrowed.json.path); + assert.match(text, /This run was narrowed, not complete: only `src` was checked\. Not checked: lib\/ and test\/\./); + assert.doesNotMatch(text, /This run was complete/); + const stopped = runDeadCode(["report", "write", "--findings", findingsFile(dir, { ...FINDINGS, mode: "own", tool: null, ranFrom: "stopped", findings: [] }), "--date", "2026-08-04"], { cwd: dir }); + assert.equal(stopped.code, 0, stopped.stderr); + const stoppedText = read(dir, stopped.json.path); + assert.match(stoppedText, /stopped before it finished, not complete/); + assert.match(stoppedText, /\*\*Tool:\*\* no tool/); + assert.match(stoppedText, /\*\*Full search of our own:\*\* yes/); + assert.match(stoppedText, /## Safe to remove\n\nNone\./); +}); + +test("report write: a same-day report is refused without --replace; bad findings exit 3 or 4", () => { + const dir = tmp("dc-report-again"); + const file = findingsFile(dir, FINDINGS); + assert.equal(runDeadCode(["report", "write", "--findings", file], { cwd: dir }).code, 0); + const again = runDeadCode(["report", "write", "--findings", file], { cwd: dir }); + assert.equal(again.code, 5); + assert.equal(again.json.error, "report-exists"); + assert.match(again.json.message, /DEAD-CODE-2026-08-03\.md/); + const replaced = runDeadCode(["report", "write", "--findings", findingsFile(dir, { ...FINDINGS, ranFrom: "narrowed" }), "--replace"], { cwd: dir }); + assert.equal(replaced.code, 0); + assert.match(read(dir, replaced.json.path), /narrowed/); + + assert.equal(runDeadCode(["report", "write", "--findings", path.join(dir, "none.json")], { cwd: dir }).code, 3); + const { ranFrom, ...noRanFrom } = FINDINGS; + assert.ok(ranFrom); + assert.equal(runDeadCode(["report", "write", "--findings", findingsFile(dir, noRanFrom), "--date", "2026-09-01"], { cwd: dir }).code, 4); + assert.equal(runDeadCode(["report", "write", "--findings", findingsFile(dir, { ...FINDINGS, findings: [{ file: "a.js", label: "maybe" }] }), "--date", "2026-09-01"], { cwd: dir }).code, 4); + assert.equal(runDeadCode(["report", "write", "--findings", file, "--date", "Aug 3"], { cwd: dir }).code, 2); + assert.equal(runDeadCode(["report", "read"], { cwd: dir }).code, 2); +}); + +test("report write: a list of two or more tools prints Tools, one prints Tool, null prints no tool", () => { + const dir = tmp("dc-report-tools"); + const cases = [ + [["knip", "vulture"], /\*\*Tools:\*\* knip, vulture/, "2026-08-10"], + [["knip"], /\*\*Tool:\*\* knip\n/, "2026-08-11"], + [null, /\*\*Tool:\*\* no tool/, "2026-08-12"], + ]; + for (const [tool, line, date] of cases) { + const r = runDeadCode(["report", "write", "--findings", findingsFile(dir, { ...FINDINGS, tool }), "--date", date], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.match(read(dir, r.json.path), line); + } + assert.match(read(dir, ".plan2code-dead-code/reports/DEAD-CODE-2026-08-10.md"), /\*\*Found by:\*\* the tools' lists, verified by a caller search/); + const one = read(dir, ".plan2code-dead-code/reports/DEAD-CODE-2026-08-11.md"); + assert.doesNotMatch(one, /\*\*Tools:\*\*/); + assert.match(one, /\*\*Found by:\*\* the tool's list, verified by a caller search/); +}); + +test("report write: a tool that is not an id, a list of ids or null exits 4 and writes no report", () => { + const dir = tmp("dc-report-bad-tool"); + const r = runDeadCode(["report", "write", "--findings", findingsFile(dir, { ...FINDINGS, tool: 3 }), "--date", "2026-08-13"], { cwd: dir }); + assert.equal(r.code, 4); + assert.equal(r.json.error, "findings-invalid"); + assert.match(r.json.message, /tool must be a tool id, a list of ids, or null/); + assert.equal(fs.existsSync(path.join(dir, ".plan2code-dead-code", "reports", "DEAD-CODE-2026-08-13.md")), false); +}); + +/* ------------------------------------------------------------- gitignore */ + +/** A committed git repo with a .gitignore that does not cover the reports. */ +const gitProject = (name) => + copyFixture(name, "dead-code-git", (dir) => { + const g = gitInit(dir); + write(dir, ".gitignore", "node_modules/"); + write(dir, "src/a.js", "export const a = 1;\n"); + g("add", "-A"); + g("commit", "-q", "-m", "init"); + }); + +test("gitignore-check and gitignore-add on a git project: appends one line, never touching the others", () => { + const dir = gitProject("dc-gitignore"); + const before = runDeadCode(["gitignore-check"], { cwd: dir }); + assert.equal(before.code, 0, before.stderr); + assert.deepEqual([before.json.isGit, before.json.hasGitignore, before.json.ignored, before.json.line], [true, true, false, null]); + const add = runDeadCode(["gitignore-add"], { cwd: dir }); + assert.equal(add.code, 0, add.stderr); + assert.equal(add.json.added, true); + assert.equal(read(dir, ".gitignore"), "node_modules/\n.plan2code-dead-code/reports/\n"); + const after = runDeadCode(["gitignore-check"], { cwd: dir }); + assert.deepEqual([after.json.ignored, after.json.line, after.json.file], [true, ".plan2code-dead-code/reports/", ".gitignore"]); + const again = runDeadCode(["gitignore-add"], { cwd: dir }); + assert.deepEqual([again.json.added, again.json.already], [false, true]); + assert.equal(read(dir, ".gitignore"), "node_modules/\n.plan2code-dead-code/reports/\n"); +}); + +test("gitignore-check: reports/ in the state folder's .gitignore, or a wider rule git applies, counts as ignored", () => { + const own = gitProject("dc-gitignore-own"); + write(own, ".plan2code-dead-code/.gitignore", "reports/\n"); + const r = runDeadCode(["gitignore-check"], { cwd: own }); + assert.deepEqual([r.json.ignored, r.json.line, r.json.file], [true, "reports/", ".plan2code-dead-code/.gitignore"]); + const wide = gitProject("dc-gitignore-wide"); + write(wide, ".gitignore", ".plan2code-dead-code/\n"); + const w = runDeadCode(["gitignore-check"], { cwd: wide }); + assert.deepEqual([w.json.ignored, w.json.line], [true, null]); +}); + +test("gitignore-check and gitignore-add on a folder that is not a git repo", () => { + const dir = tmp("dc-not-git"); + const env = { GIT_CEILING_DIRECTORIES: path.dirname(dir) }; + const r = runDeadCode(["gitignore-check"], { cwd: dir, env }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual([r.json.isGit, r.json.hasGitignore, r.json.ignored], [false, false, false]); + const add = runDeadCode(["gitignore-add"], { cwd: dir, env }); + assert.equal(add.code, 5); + assert.equal(add.json.error, "not-git"); + assert.equal(fs.existsSync(path.join(dir, ".gitignore")), false); +}); + +/* --------------------------------------------------------------- dry run */ + +test("--dry-run writes nothing for every writing command", () => { + const dir = gitProject("dc-dry-run"); + write(dir, "src/a.js", "export function foo() {}\n"); + const temp = tmp("dc-dry-run-temp"); + const env = tempEnv(temp); + // One real keep entry and one real backup, so remove and restore have something to act on. + const keptHash = runDeadCode(["keep", "add", "--file", "src/a.js", "--name", "foo", "--line", "1", "--reason", "Kept"], { cwd: dir }).json.entry.hash; + const { run } = runDeadCode(["backup", "src/a.js"], { cwd: dir, env }).json; + write(dir, "src/a.js", "removed\n"); + const findings = findingsFile(tmp("dc-dry-run-findings"), FINDINGS); + const project = snapshot(dir); + const temps = snapshot(temp); + + const runs = { + "keep add": ["keep", "add", "--file", "src/a.js", "--name", "removed", "--line", "1", "--reason", "Dry", "--dry-run"], + "keep remove": ["keep", "remove", "--file", "src/a.js", "--name", "foo", "--dry-run"], + "keep remove --hash": ["keep", "remove", "--file", "src/a.js", "--name", "foo", "--hash", keptHash, "--dry-run"], + backup: ["backup", "src/a.js", "--dry-run"], + "backup --run": ["backup", "src/a.js", "--run", "dry-run-id", "--dry-run"], + restore: ["restore", "--run", run, "--dry-run"], + "report write": ["report", "write", "--findings", findings, "--dry-run"], + "gitignore-add": ["gitignore-add", "--dry-run"], + }; + for (const [label, args] of Object.entries(runs)) { + const r = runDeadCode(args, { cwd: dir, env }); + assert.equal(r.code, 0, `${label}: ${r.stderr}`); + assert.equal(r.json.dryRun, true, label); + } + assert.deepEqual(snapshot(dir), project, "the project is unchanged"); + assert.deepEqual(snapshot(temp), temps, "the backups are unchanged"); + const preview = runDeadCode(runs["report write"], { cwd: dir, env }).json; + assert.equal(preview.path, ".plan2code-dead-code/reports/DEAD-CODE-2026-08-03.md"); + assert.equal(preview.preview[0], "# Dead Code report"); +}); + +test("readers: a cargo type alias keeps its full kind name", () => { + const rec = { reason: "compiler-message", message: { code: { code: "dead_code" }, level: "warning", message: "type alias `Foo` is never used", spans: [{ file_name: "src/lib.rs", line_start: 2, line_end: 2, is_primary: true }] } }; + const r = dc.readOutput("cargo-json", JSON.stringify(rec), "/proj"); + assert.equal(r.candidates[0].kind, "type alias"); +}); + +test("keep add without --line keeps a whole file, and keep filter hides it until the file changes", () => { + const dir = keepProject("dc-keep-file"); + const add = runDeadCode(["keep", "add", "--file", "src/a.js", "--reason", "Loaded by name at runtime"], { cwd: dir }); + assert.equal(add.code, 0, add.stderr); + assert.match(add.json.entry.hash, /^file:[0-9a-f]{12}$/); + const cands = JSON.stringify([{ file: "src/a.js", line: null, name: "", kind: "file" }]); + const filter = () => runDeadCode(["keep", "filter"], { cwd: dir, input: cands }).json; + assert.deepEqual([filter().hidden.length, filter().shown.length], [1, 0]); + fs.appendFileSync(path.join(dir, "src/a.js"), "// edited\n"); + const after = filter(); + assert.deepEqual([after.hidden.length, after.shown.length, after.shown[0].wasKept], [0, 1, true]); +}); + +test("--scope accepts a folder whose name starts with two dots", () => { + const dir = keepProject("dc-scope-dots"); + fs.mkdirSync(path.join(dir, "..cache")); + const r = runDeadCode(["detect", "--scope", "..cache"], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.scope, "..cache"); +}); + +test("keep remove: a whole-file entry comes off with --file alone, or with an empty --name", () => { + const dir = keepProject("dc-keep-remove-file"); + runDeadCode(["keep", "add", "--file", "src/a.js", "--reason", "Loaded by name"], { cwd: dir }); + const first = runDeadCode(["keep", "remove", "--file", "src/a.js"], { cwd: dir }); + assert.equal(first.code, 0, first.stderr); + assert.deepEqual(runDeadCode(["keep", "list"], { cwd: dir }).json.entries, []); + runDeadCode(["keep", "add", "--file", "src/a.js", "--reason", "Loaded by name"], { cwd: dir }); + const second = runDeadCode(["keep", "remove", "--file", "src/a.js", "--name", ""], { cwd: dir }); + assert.equal(second.code, 0, second.stderr); + assert.deepEqual(runDeadCode(["keep", "list"], { cwd: dir }).json.entries, []); +}); + +test("run: each tail line is capped at 400 characters", () => { + const dir = tmp("dc-run-longline"); + write(dir, "pyproject.toml", "[tool.vulture]\n"); + const bin = tmp("dc-run-longline-bin"); + stub(bin, "vulture", 'console.log("x".repeat(5000));\nprocess.exitCode = 3;\n'); + const r = runDeadCode(["run", "--tool", "vulture", "--root", dir], { pathDir: bin }); + assert.equal(r.code, 0, r.stderr + r.stdout); + assert.equal(r.json.tail.length, 1); + assert.equal(r.json.tail[0].length, 400); +}); diff --git a/scripts/test-skill-scripts.mjs b/scripts/test-skill-scripts.mjs index f6ef778..883e9ee 100644 --- a/scripts/test-skill-scripts.mjs +++ b/scripts/test-skill-scripts.mjs @@ -70,11 +70,15 @@ test("every script a SKILL.md (or a reference it ships) runs exists beside it, a }); test("scripts are self-contained: built-ins and siblings only", () => { - for (const dir of [path.join(ROOT, "src", "skill-scripts"), ...fs.readdirSync(path.join(ROOT, "src")).filter((n) => n.endsWith("-scripts")).map((n) => path.join(ROOT, "src", n))]) { + const shared = path.join(ROOT, "src", "skill-scripts"); + for (const dir of [shared, ...fs.readdirSync(path.join(ROOT, "src")).filter((n) => n.endsWith("-scripts")).map((n) => path.join(ROOT, "src", n))]) { for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".mjs"))) { const t = fs.readFileSync(path.join(dir, f), "utf8"); for (const m of t.matchAll(/^import .* from "([^"]+)";$/gm)) { - const sibling = /^\.\/[\w-]+\.mjs$/.test(m[1]) && fs.existsSync(path.join(dir, m[1])); + // A skill's own script may import a shared script too: the build lays + // both in one scripts/ folder, and the check below holds the skill to + // shipping it. + const sibling = /^\.\/[\w-]+\.mjs$/.test(m[1]) && (fs.existsSync(path.join(dir, m[1])) || fs.existsSync(path.join(shared, m[1]))); assert.ok(m[1].startsWith("node:") || m[1] === "./common.mjs" || sibling, `${f} imports ${m[1]}`); } assert.ok(!/[\u0000-\u0008]/.test(t), `${f} contains a control character (an escape lost in an edit?)`); diff --git a/scripts/test-web-console-logic.mjs b/scripts/test-web-console-logic.mjs index 3fb285d..6dfdde8 100644 --- a/scripts/test-web-console-logic.mjs +++ b/scripts/test-web-console-logic.mjs @@ -2085,8 +2085,8 @@ test("workspace cursor never moves backwards, and only changes past it are pendi } }); -test("subagents: only the fifteen opted-in workflows offer the switch", () => { - for (const w of ["init", "init-update", "pathfinder", "plan", "revise-plan", "document", "implement", "implement-review", "quick-task", "review", "finalize", "xray", "diagnose", "pr-prep", "test"]) { +test("subagents: only the sixteen opted-in workflows offer the switch", () => { + for (const w of ["init", "init-update", "pathfinder", "plan", "revise-plan", "document", "implement", "implement-review", "quick-task", "review", "finalize", "xray", "diagnose", "pr-prep", "test", "dead-code"]) { assert.equal(offered(w), true, w); assert.ok(defaultInstruction(w).length > 0, `${w} has a default instruction`); } @@ -2094,7 +2094,7 @@ test("subagents: only the fifteen opted-in workflows offer the switch", () => { assert.equal(offered(w), false, String(w)); assert.equal(defaultInstruction(w), ""); } - assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 15); + assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 16); assert.deepEqual(defaultSetting("review"), { workflow: "review", on: true, instruction: null, max: 3, strength: "balanced" }); assert.equal(defaultSetting("changelog").on, false, "a skill without the switch is never on"); assert.equal(effectiveInstruction({ workflow: "review", instruction: " " }), defaultInstruction("review")); @@ -2384,14 +2384,14 @@ test("meter: the weights and labels built from the skill list are the ones writt "pathfinder-chart": 2, "pathfinder-question": 0, "pathfinder-research": 1, plan: 2, "revise-plan": 1, document: 2, "implement-phase": 2, "implement-review-phase": 3, review: 2, "quick-task": 1, init: 2, "init-update": 2, finalize: 1, handoff: 0, git: 1, - "git-commits": 0, "git-conflict": 1, changelog: 1, xray: 1, diagnose: 1, "pr-prep": 1, test: 1, + "git-commits": 0, "git-conflict": 1, changelog: 1, xray: 1, diagnose: 1, "pr-prep": 1, test: 1, "dead-code": 1, }); assert.deepEqual({ ...LAUNCH_LABELS }, { plan: "Plan started", "revise-plan": "Revise plan started", document: "Document started", review: "Review started", "quick-task": "Quick task started", init: "Init started", "init-update": "Init update started", finalize: "Finalize started", git: "Git started", changelog: "Changelog started", xray: "X-ray started", diagnose: "Diagnose started", - "pr-prep": "PR Prep started", test: "Test started", + "pr-prep": "PR Prep started", test: "Test started", "dead-code": "Dead Code started", }); assert.deepEqual({ ...RUN_LABELS }, { "pathfinder-chart": "Pathfinder map written", "pathfinder-question": "Pathfinder question settled", @@ -2401,7 +2401,7 @@ test("meter: the weights and labels built from the skill list are the ones writt "quick-task": "Quick task built", init: "Init run", "init-update": "Init update run", finalize: "Finalize run", handoff: "Handoff written", git: "Git run", "git-commits": "Commits in Git", "git-conflict": "Git conflict help", changelog: "Changelog run", xray: "X-ray run", diagnose: "Diagnose run", - "pr-prep": "PR Prep run", test: "Test run", + "pr-prep": "PR Prep run", test: "Test run", "dead-code": "Dead Code run", }); for (const t of [WEIGHTS, LAUNCH_LABELS, RUN_LABELS]) assert.ok(Object.isFrozen(t)); }); diff --git a/scripts/test-web-console-page-dashboard.mjs b/scripts/test-web-console-page-dashboard.mjs index 9e0781c..357574e 100644 --- a/scripts/test-web-console-page-dashboard.mjs +++ b/scripts/test-web-console-page-dashboard.mjs @@ -212,11 +212,15 @@ test("picking Start from scratch instead of a spec grays Document, and a launch const document = lightOf(main, "/plan2code-2-document"); await pickedChip(main, "demo").waitFor(); assert.equal(await document.isEnabled(), true, "Document is lit for the drafted spec"); + // The top bar names the picked spec beside the meter, and drops it from scratch. + const specTag = main.page().locator("#spec-tag"); + assert.ok(await until(async () => (await specTag.isVisible()) && (await specTag.textContent()) === "demo"), "the top bar names the spec demo"); // From scratch there is no draft to document: the card grays. await chipFor(main, "Start from scratch").click(); await pickedChip(main, "Start from scratch").waitFor(); assert.equal(await document.isDisabled(), true, "Document is grayed with no spec picked"); + assert.ok(await until(() => specTag.isHidden()), "the top bar's spec name goes from scratch"); assert.equal(await chipFor(main, "demo").getAttribute("aria-current"), "false"); // Back on the spec it is lit again; then from scratch once more to launch. @@ -232,6 +236,40 @@ test("picking Start from scratch instead of a spec grays Document, and a launch assert.ok(!launch.spec, `a launch from scratch names no spec: ${JSON.stringify(launch)}`); }); +// What a person would see break: the Dead Code card missing from Useful any +// time, drawn without its skull, grayed for want of a spec it never takes, or +// launching with the picked spec riding along. +test("the Dead Code card sits in Useful any time with its skull, is lit with or without a spec, and launches with no spec", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) }); + const main = await toTheMenu(s); + await hideUnavailable(main, false); + const card = lightOf(main, "/plan2code-dead-code"); + await card.waitFor(); + + const group = main.locator("section.dash-group").filter({ has: s.page.locator("h3", { hasText: /^Useful any time$/ }) }); + assert.equal(await group.locator("code", { hasText: /^\/plan2code-dead-code$/ }).count(), 1, "the card is in the Useful any time group"); + assert.match(await textOf(card), /Utility/i, "it wears the Utility chip (drawn in capitals)"); + assert.match(await textOf(card), /Clear out dead code/, "it has its title"); + assert.equal(await card.locator("use").getAttribute("href"), "#ci-dead-code", "its icon is the skull"); + assert.equal(await s.page.locator("symbol#ci-dead-code").count(), 1, "the skull symbol is drawn in the icon sheet"); + + // Lit with no spec picked, and with one. + await chipFor(main, "Start from scratch").click(); + await pickedChip(main, "Start from scratch").waitFor(); + assert.equal(await card.isEnabled(), true, "lit with no spec picked"); + await chipFor(main, "demo").click(); + await pickedChip(main, "demo").waitFor(); + assert.equal(await card.isEnabled(), true, "lit with a spec picked"); + + // A launch with the spec still picked names no spec: Dead Code takes none. + await card.click(); + await main.getByRole("button", { name: "Start Clear out dead code" }).click(); + const launch = collect(s).actions.find((a) => a.i === "__launch"); + assert.ok(launch, "the send carries a launch"); + assert.deepEqual({ skill: launch.skill, workflow: launch.workflow }, { skill: "plan2code-dead-code", workflow: "dead-code" }); + assert.ok(!launch.spec, `a Dead Code launch names no spec: ${JSON.stringify(launch)}`); +}); + // What a person would see break: a spec not documented yet offers nothing to // read, or its Map and Plan draft tabs stay up for a spec that has an // overview (or for no spec at all). diff --git a/scripts/test-web-console-page-prefs.mjs b/scripts/test-web-console-page-prefs.mjs index a0566c9..28484db 100644 --- a/scripts/test-web-console-page-prefs.mjs +++ b/scripts/test-web-console-page-prefs.mjs @@ -947,13 +947,13 @@ test("the Subagents dialog looks as it did before Preferences moved to tabs", as // seven pickable cues, Planny's snoring and waking keeping plain boxes. const PICK_EVENTS = ["startSkill", "sessionStart", "skillReady", "sessionEnd", "question", "chatReply", "newTab"]; const PICK_DEFAULTS = { - startSkill: "sound-01", - sessionStart: "sound-02", - skillReady: "sound-03", - sessionEnd: "sound-02", - question: "sound-03", - chatReply: "sound-03", - newTab: "sound-04", + startSkill: "sound-14", + sessionStart: "sound-07", + skillReady: "sound-16", + sessionEnd: "sound-15", + question: "sound-14", + chatReply: "sound-06", + newTab: "sound-05", }; const pickSelect = (s, event) => s.page.locator(`select[data-sound-file="${event}"]`); @@ -1017,7 +1017,7 @@ test("the sound picker: a pick plays once and persists across a reload, and Play await drawn(s.page); await openSoundsTab(s); assert.equal(await pickSelect(s, "question").inputValue(), "sound-07", "the pick did not survive a reload"); - assert.equal(await pickSelect(s, "newTab").inputValue(), "sound-04", "an untouched cue kept its default"); + assert.equal(await pickSelect(s, "newTab").inputValue(), "sound-05", "an untouched cue kept its default"); }); test("the sound picker: Play sounds off disables the selects and play buttons, and Back to default restores the defaults", async (t) => { @@ -1039,7 +1039,7 @@ test("the sound picker: Play sounds off disables the selects and play buttons, a assert.equal(await pickSelect(s, "newTab").isDisabled(), false, "switching sounds on enables the select again"); await s.page.click("#looks-reset"); - await s.page.waitForFunction(() => document.querySelector('select[data-sound-file="newTab"]').value === "sound-04"); + await s.page.waitForFunction(() => document.querySelector('select[data-sound-file="newTab"]').value === "sound-05"); for (const event of PICK_EVENTS) { assert.equal(await pickSelect(s, event).inputValue(), PICK_DEFAULTS[event], `${event} is back on its default`); } @@ -1078,7 +1078,7 @@ test("the sound picker: a preview is dropped behind a ranked cue that is still p await s.page.evaluate(() => (window.__audible = false)); await s.page.locator('[data-sound-play="newTab"]').click(); await s.page.waitForFunction(() => window.__played.length === 2); - assert.match((await played(s))[1], /\/sounds\/sound-04\.mp3$/, "the preview played once the cue had stopped"); + assert.match((await played(s))[1], /\/sounds\/sound-05\.mp3$/, "the preview played once the cue had stopped"); }); test("the sound picker: Tab reaches Play from the select, and a row stacks inside the dialog at a narrow width", async (t) => { diff --git a/scripts/test-web-console-session.mjs b/scripts/test-web-console-session.mjs index 9a73124..5056f53 100644 --- a/scripts/test-web-console-session.mjs +++ b/scripts/test-web-console-session.mjs @@ -614,7 +614,7 @@ test("the chime files are served as audio", async () => { // names a real event, and every event's file is served. A box with no event // saves a setting nothing reads; an event with no box can never be muted. test("every sound event has a preference box and a served file", async () => { - assert.equal(SOUND_EVENTS.startSkill.file, "sounds/sound-01", "starting a skill has its own sound"); + assert.equal(SOUND_EVENTS.startSkill.file, "sounds/sound-14", "starting a skill has its own default sound"); const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8"); const boxes = [...html.matchAll(/data-sound="(\w+)"/g)].map((m) => m[1]); assert.deepEqual([...boxes].sort(), Object.keys(SOUND_EVENTS).sort()); @@ -1574,6 +1574,53 @@ test("the page reads older { from, md } thread entries", () => { assert.equal(threadText({ who: "agent" }), ""); }); +/* --------------------------------- the Dead Code findings page (notes/dead-code.md) */ + +test("Dead Code's findings page: one multi in three groups with All Safe and None presets is accepted, two recommended stay refused", () => { + const opened = cli(["open", "--file", payload("dead-code-open.json", BASE), "--no-open"]); + const s = opened.json; + try { + const findings = { + id: "findings", + kind: "multi", + title: "What to remove", + required: false, + body: "- Safe to remove: 2\n- Check first: 1\n- Warning: 1\n\nNothing is removed until you send.", + options: [ + { k: "1", text: "formatDate in src/dates.js:14", detail: "Safe. Knip (exports): no caller found." }, + { k: "2", text: "src/old/legacy.js", detail: "Safe. Knip (files): no caller found." }, + { k: "3", text: "parseRow in src/csv.js:40", detail: "Check first. Own search only." }, + { k: "4", text: "onLoad in src/plugin.js:8", detail: "Warning. A framework hook: the host calls it by name." }, + ], + presets: [{ label: "All Safe", ks: ["1", "2"] }, { label: "None", ks: [] }], + }; + const ok = cli(["post", "--session", s.sid, "--file", payload("dead-code-findings.json", { items: [findings] })]); + assert.equal(ok.status, 0, ok.stderr); + const item = readState(s.session).items.find((i) => i.id === "findings"); + assert.ok(item, "the findings card is on the page"); + assert.deepEqual(item.options.map((o) => o.k), ["1", "2", "3", "4"], "Safe, Check first, Warning, in order"); + assert.deepEqual(item.presets, findings.presets, "both presets are kept for the page"); + assert.ok(!item.answer, "nothing starts ticked"); + + const twice = cli( + ["post", "--session", s.sid, "--file", payload("dead-code-twice.json", { + items: [{ id: "method", kind: "choice", title: "How to look", body: "Which?", options: [{ text: "Knip", recommended: true }, { text: "Own search", recommended: true }] }], + })], + { expectFail: true } + ); + assert.equal(twice.status, 3, "a second recommended option is still refused"); + assert.match(twice.stderr, /recommended/); + } finally { + cli(["stop", "--session", s.sid, "--force"]); + } + // The budget is read as text: importing the budgets suite would run its tests here too. + const budgets = fs.readFileSync(path.join(ROOT, "scripts", "test-console-wire-budgets.mjs"), "utf8"); + const budget = Number((budgets.match(/"dead-code\.md": (\d+)/) || [])[1]); + assert.ok(budget > 0, "notes/dead-code.md has a byte budget"); + const bytes = fs.statSync(path.join(ROOT, "src", "web-console", "notes", "dead-code.md")).size; + assert.ok(bytes <= budget, `notes/dead-code.md is ${bytes} bytes, over its ${budget} budget`); +}); + /* --------------------------------- output shape at each exit code (FR-1 to FR-3) */ test("the shape of every exit: 0 for an answer and a launch, 10, 30, 3 and 2", async (t) => { diff --git a/scripts/test-web-console-skills.mjs b/scripts/test-web-console-skills.mjs index 2c085c7..ff615aa 100644 --- a/scripts/test-web-console-skills.mjs +++ b/scripts/test-web-console-skills.mjs @@ -399,7 +399,7 @@ test("Implement's card launches Implement + Review when Review is ticked", () => assert.equal(launchVariant(quick, true), quick, "a card with no Review box is unchanged"); }); -test("helper-strength.md ships in the fifteen skills that start helpers, and in no other", () => { +test("helper-strength.md ships in the sixteen skills that start helpers, and in no other", () => { // npm test has just built skills/; a direct run builds it so the check never reads a stale tree. if (process.env.npm_lifecycle_event !== "test") { execFileSync(process.execPath, [path.join(ROOT, "install.js"), "--build-skills"], { stdio: "ignore" }); @@ -414,6 +414,7 @@ test("helper-strength.md ships in the fifteen skills that start helpers, and in "plan2code-3-implement", "plan2code-3-implement-review", "plan2code-4-finalize", + "plan2code-dead-code", "plan2code-diagnose", "plan2code-init", "plan2code-init-update", diff --git a/scripts/test-web-console-spec-states.mjs b/scripts/test-web-console-spec-states.mjs index 84c3faf..19ea783 100644 --- a/scripts/test-web-console-spec-states.mjs +++ b/scripts/test-web-console-spec-states.mjs @@ -302,6 +302,18 @@ const CARDS = { built: { on: true }, unrecognized: { on: true }, }, + "plan2code-dead-code": { + "none": { on: true }, + diagnosed: { on: true }, + fixed: { on: true }, + exploring: { on: true }, + mapped: { on: true }, + planned: { on: true }, + documented: { on: true }, + building: { on: true }, + built: { on: true }, + unrecognized: { on: true }, + }, "plan2code-changelog": { "none": { on: true }, diagnosed: { on: true }, diff --git a/scripts/test-web-console-speed.mjs b/scripts/test-web-console-speed.mjs index e592355..07901cf 100644 --- a/scripts/test-web-console-speed.mjs +++ b/scripts/test-web-console-speed.mjs @@ -498,7 +498,7 @@ test("every console workflow has its notes, and its skill's Interface reads them init: "init", "init-update": "init", pathfinder: "pathfinder", plan: "plan", "revise-plan": "revise-plan", document: "document", implement: "implement", "implement-review": "implement", "quick-task": "quick-task", review: "review", finalize: "finalize", handoff: "handoff", changelog: "changelog", git: "git", xray: "xray", - diagnose: "diagnose", "pr-prep": "pr-prep", test: "test", + diagnose: "diagnose", "pr-prep": "pr-prep", test: "test", "dead-code": "dead-code", }; const skills = fs.readdirSync(path.join(ROOT, "src")).filter((f) => /^plan2code(-.*)?\.md$/.test(f)); for (const f of skills) { diff --git a/src/plan2code-dead-code-references/caller-search.md b/src/plan2code-dead-code-references/caller-search.md new file mode 100644 index 0000000..db33893 --- /dev/null +++ b/src/plan2code-dead-code-references/caller-search.md @@ -0,0 +1,73 @@ +# Caller Search +> Part of plan2code-dead-code: read in Step 4 before the caller search, and given to every helper that searches. Never invoked as a skill. + +A candidate is dead only when nothing in the whole project reaches it. Search the whole project, never only the folder the run covers, and search for more than the plain name: the lists below are what else can reach an item in each language group. Include tests, scripts, config files, docs that act as config (an OpenAPI file, a route table, a cron file) and generated glue (bindings, stubs, registration files). + +## Every language + +- The plain name, as a whole word, in every text file, not only in source files of the same language. +- The name inside strings and templates: config keys, JSON and YAML values, SQL, HTML attributes, environment files. +- Build files, CI configs, `Dockerfile`, `Makefile`, package scripts and shell scripts that call a file or a function by name. +- A file candidate: its path and its file name without the extension, anywhere. +- Record what each search found in `callers`, even when it found nothing ("no match outside its own file"). + +## JavaScript and TypeScript + +- Re-exports: `export * from`, `export { x } from`, and the barrel files (`index.js`, `index.ts`) that pass a name on. +- Dynamic `import()` with a string or template path, and `require()` with a computed path. +- `package.json` `exports`, `main`, `module`, `bin` and `types`; a workspace's other packages that import this one. +- Framework conventions that load by file name: route folders (`pages/`, `app/`, `routes/`), `*.config.*` files, test setup files. +- Names reached by string: `obj[name]`, event names, `customElements.define`, decorators. + +## Python + +- `__all__` lists, and `from module import *` that brings them in. +- `getattr`, `importlib.import_module`, `__import__` and string paths such as `"package.module:func"`. +- Decorators that register a function (routes, CLI commands, signal handlers, pytest fixtures used by name). +- Entry points in `pyproject.toml`, `setup.cfg` and `setup.py` (`console_scripts`, plugin groups), and `manage.py` or framework settings that name a module. + +## Rust + +- `pub use` re-exports and the crate's public API in `lib.rs`. +- Macros that expand to a call (`macro_rules!` bodies, derive and attribute macros). +- `#[cfg(...)]` and feature flags: an item used only under a feature or a target is still used. +- `mod` declarations, `#[path]` attributes, `build.rs`, and binaries under `src/bin/` or `[[bin]]` in `Cargo.toml`. + +## Go + +- Exported names (capitalized) used from another package or module in the workspace. +- Interface satisfaction: a method with no direct caller may make a type meet an interface used elsewhere. +- `init()` functions, blank imports (`import _ "pkg"`) that run them, and `//go:generate` lines. +- Build tags and file-name suffixes (`_linux.go`, `_test.go`), and reflection (`reflect`, `MethodByName`, struct tags read at runtime). + +## Java and Kotlin + +- Reflection: `Class.forName`, `getMethod`, `getDeclaredField`, and names in strings. +- Annotations that register or call: `@Bean`, `@Component`, `@Controller`, `@RequestMapping`, `@Test`, `@JsonCreator`, `@Subscribe`, `main` methods. +- Spring and other dependency injection: XML configs, `application.properties` and `application.yml`, component scanning by package. +- `META-INF/services` files, `AndroidManifest.xml`, Gradle and Maven files that name a class, and Kotlin `@JvmStatic` or `companion object` members called from Java. + +## C# + +- Reflection: `Type.GetType`, `GetMethod`, `Activator.CreateInstance`, `nameof` used as a key. +- Attributes that register or call: `[HttpGet]`, `[Route]`, `[Fact]`, `[Test]`, `[JsonConstructor]`, `[DllImport]`. +- Dependency injection registration (`AddScoped`, `AddTransient`, `AddSingleton`, assembly scanning) and `appsettings.json`. +- Serialization: properties set only by a serializer, and `.csproj`, `.xaml` and `.razor` files that name a type or handler. + +## Ruby + +- `send`, `public_send`, `method`, `define_method` and `respond_to?` with a symbol or string. +- `constantize`, `const_get` and class names built from strings. +- Rails autoloading and conventions: controllers and actions reached through `config/routes.rb`, callbacks (`before_action`, `after_save`), helpers, jobs, mailers, views that call a helper, and concerns. +- Rake tasks, `Gemfile` and gemspec `executables`, and initializers. + +## PHP + +- Composer autoload (`psr-4`, `classmap`, `files`) and `bin` entries in `composer.json`. +- `class_exists`, `method_exists`, `call_user_func`, variable functions (`$fn()`) and `new $class`. +- Routes and container config: framework route files, service container definitions (YAML, XML, PHP arrays), event listeners and middleware lists. +- Templates (Blade, Twig) that call a function or helper by name, and attributes such as `#[Route]`. + +## Any other language + +Search the plain name, strings and config as in "Every language", say which of the language's dynamic features you could not cover, and leave the finding at Check first. diff --git a/src/plan2code-dead-code-scripts/dead-code.mjs b/src/plan2code-dead-code-scripts/dead-code.mjs new file mode 100644 index 0000000..6888965 --- /dev/null +++ b/src/plan2code-dead-code-scripts/dead-code.mjs @@ -0,0 +1,1612 @@ +#!/usr/bin/env node +// dead-code.mjs: find a project's dead-code tool, run it and read its output, +// for the Dead Code skill. +// +// The repeatable steps live here: which tool the project already has (by a +// config file, a build-file entry or a binary on PATH), running it with a +// timeout, and turning its output into a list of candidates; then the state a +// run keeps: the shared keep list, backups with a checked restore, the saved +// report and the .gitignore line for it. Judgment stays with the agent: it +// verifies every candidate with a caller search, labels it and runs every +// removal. This script never installs a tool and never deletes source. + +import crypto from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { EXIT, fail, out, parseArgs, run, isDir, readText, now, isoDate, compactDate, clock, eol } from "./common.mjs"; +import { runCheck } from "./run-check.mjs"; + +const USAGE = ` +dead-code.mjs: find, run and read a project's dead-code tool. JSON on stdout. +It never installs a tool and never deletes source. + + node dead-code.mjs detect [--scope ] [--root ] [--limit 1500] + node dead-code.mjs run --tool [--scope ] [--timeout 300] [--root ] + node dead-code.mjs narrow --candidates [--depth 2] + node dead-code.mjs keep list [--root ] + node dead-code.mjs keep add --file [--name ] [--line ] --reason [--root ] [--dry-run] + node dead-code.mjs keep remove --file [--name ] [--hash ] [--line ] [--root ] [--dry-run] (no --name for a whole file) + node dead-code.mjs keep filter [--fresh] [--root ] (candidates JSON on stdin) + node dead-code.mjs backup [--run ] [--root ] [--dry-run] + node dead-code.mjs restore --run [--files ...] [--verify] [--root ] [--dry-run] + node dead-code.mjs report write --findings [--date YYYY-MM-DD] [--replace] [--root ] [--dry-run] + node dead-code.mjs gitignore-check [--root ] + node dead-code.mjs gitignore-add [--root ] [--dry-run] + +detect Counts source files under --scope (default: the whole project) by + language group (javascript, python, rust, go, java, csharp, ruby, + php) and finds the dead-code tools the project already has, from + config files, build-file entries and binaries on PATH. It never + runs or installs a tool. Prints { ok, root, scope, languages: + [{ id, files }], sourceFiles, overLimit, limit, tools: [{ id, + language, marker, available, command, format }] }. overLimit is + true when sourceFiles is above --limit. +run Runs one detected tool (--tool from detect) in the project + root through the shell, stopping it and every process it started + after --timeout seconds. A tool's own "findings found" exit code + is a normal result. Prints { ok, tool, format, exit, seconds, + candidates, unparsed, skipped, tail }. Each candidate is { file, + line, name, kind, source: "tool", rule, message }; rule is the + tool's own rule id. Candidates are kept only under --scope. A + tool in the agent format, or output no reader can read, comes back + with unparsed: true and the output's last lines in tail. +narrow Groups a candidates file (the candidates array run printed, or the + whole run output) by the first --depth folder levels. Prints + { ok, folders: [{ path, candidates }], total }, the folders with + the most candidates first, ties by path. +keep The shared keep list, .plan2code-dead-code/keep.md (tracked, safe + to commit): a table | File | Name | Hash | Reason | Date |. Hash + is <12 hex>, the first 12 hex of the sha256 of the item's + declaration line, trimmed with whitespace runs collapsed; + <12 hex># when that line repeats in the file (the n-th identical + line, from the top); or file:<12 hex> for a whole file, hashed over + its full text. Rows are told apart by file, name and hash. What + the hash cannot see: which identical copy a #n row means once a + copy is added, removed or moved above it while the file still has + at least n copies. + list Prints { ok, exists, path, entries: [{ file, name, hash, reason, + date, state }] }. state is current (a plain hash while exactly + one line of the file has it; a #n hash while the line repeats + and copy n exists; a whole file while its text is unchanged), + changed (not current, but the file still names the item) or + gone (the file is missing or no longer names it). A #n row + stays current while the file has at least n copies, so after a + copy above it is added, removed or moved it points at whichever + copy is now the n-th. + add Keeps the item declared at --line (no --line and no --name: the + whole file). A row with the same file, name and hash is replaced + (its reason updated), and so is a same-named row that is no longer + current (the code changed since); a same-named row with another + hash that is still current is a different item and stays. --reason + is required and cannot be empty (exit 2). Prints { ok, entry, + replaced, path }. + remove Takes off the entry with --file and --name (exit 3 not-kept when + none is there). --hash keeps only the row with that exact + hash; --line only the row matching the declaration on line l + now (exit 3 declaration-missing when the file has no such line); + both may be passed and must both match. Several rows left: exit 2 + ambiguous-entry, nothing written, the hint listing each row's hash + and reason. Prints { ok, removed, path }. + filter Reads a candidates array (or run's output) on stdin. Prints { ok, + fresh, shown, hidden, kept: [{ file, name, reason, gone? }], + changed }. A candidate with a line matches the entry with its + file, name and its own line's hash (#n included); one with no + line matches by file and name, and a whole-file entry hides only + the whole-file finding (no line, no name). A current entry hides + its candidate (hidden carries keptReason); a changed entry does + not, and the candidate is in shown with wasKept: true and + keptReason (also when no entry has its hash but a same-named one + is changed); changed counts those. --fresh hides nothing. kept + lists every entry either way. +backup Copies files (relative to the root, inside it, else exit 5) to + /plan2code-dead-code//files/ and records each one's + path, size and sha256 in /manifest.json. --run adds to that + run (a file it already holds keeps its first copy and is listed + in already); without it a new id is made. A missing file exits 3 + and copies nothing. Prints { ok, run, dir, files, already }. +restore Copies a run's files (all, or --files) back over the project, + making folders for deleted files, then checks each against the + manifest. A backup copy that no longer matches the manifest is + never copied: it is listed in mismatched and the project file is + left as it is. Prints { ok, run, restored, mismatched: [{ path, + reason }] }; any mismatch exits 4 with ok: false. --verify copies + nothing and only checks (verified lists the matches). A run with + no manifest exits 3; a manifest path outside the project exits 5 + before anything is copied. Never deletes. +report write: .plan2code-dead-code/reports/DEAD-CODE-.md from + --findings, a JSON file { scope, mode, tool, ranFrom, findings, + hidden?, notChecked? }. mode: verify (the tool's list checked by + a caller search), full (plus a full search of our own) or own (no + tool). tool: the tool's id, a list of ids when several ran, or + null. ranFrom: complete, narrowed or stopped; the report never + calls a narrowed or stopped run complete. hidden: how many + items the keep list hid. notChecked: what a narrowed or stopped + run left out. Each finding: { file, line, name, kind, source, + rule, label (safe|check|warning), warningKind, callers, + outcome }. A report already there for the + date exits 5 unless --replace. Prints { ok, path }; --dry-run adds + preview, the first lines. +gitignore-check + Prints { ok, isGit, hasGitignore, ignored, line, file }: ignored + when .gitignore holds .plan2code-dead-code/reports/ (or + .plan2code-dead-code/.gitignore holds reports/), or git + check-ignore says another rule covers it. +gitignore-add + Appends .plan2code-dead-code/reports/ to the root .gitignore + (made if missing; no other line is touched). Not a git repo: exit + 5. Already ignored: added: false, already: true. + +Writing commands take --dry-run and then write nothing. PLAN2CODE_NOW pins +the clock. + +Exit: 0 ok · 1 crash · 2 bad arguments, or a keep remove that matches +several entries · 3 not found (a scope outside the project, a tool that is +not detected or did not start, a missing file, a keep entry or backup run +that is not there) · 4 invalid input, a tool that failed or timed out, or a +restore that does not match · 5 refused (a path outside the project, a +report already there, gitignore-add outside git). +`; + +// An engineering default, not a measured one: past this many source files the +// skill asks the person to narrow first (FR-7). Revisit once real runs show +// how long the caller search takes on big projects. +export const NARROW_LIMIT = 1500; + +const DEFAULT_TIMEOUT = 300; +const MAX_TIMEOUT = 86400; +const TAIL_LINES = 60; +const TAIL_LINE_CAP = 400; + +const SKIP_DIRS = new Set([ + "node_modules", + ".git", + "target", + "dist", + "build", + "vendor", + "venv", + ".venv", + "__pycache__", + "bin", + "obj", + "specs", + "specs--completed", +]); + +const LANGUAGES = [ + { id: "javascript", exts: [".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts"] }, + { id: "python", exts: [".py"] }, + { id: "rust", exts: [".rs"] }, + { id: "go", exts: [".go"] }, + { id: "java", exts: [".java", ".kt", ".kts"] }, + { id: "csharp", exts: [".cs"] }, + { id: "ruby", exts: [".rb"] }, + { id: "php", exts: [".php"] }, +]; +const LANGUAGE_OF = new Map(LANGUAGES.flatMap((l) => l.exts.map((e) => [e, l.id]))); + +/* ----------------------------------------------------------------- paths */ + +const slash = (p) => p.split(path.sep).join("/"); + +/** The project root: --root, or the current folder. Must exist. */ +function projectRoot(rootArg) { + const root = path.resolve(rootArg || "."); + if (!isDir(root)) fail(EXIT.NOT_FOUND, "root-missing", `${root} is not a folder.`, "Pass --root , or run from the project root."); + return root; +} + +/** --scope as a forward-slash path relative to root ("." for the whole project); a folder under root or exit 3. */ +function projectScope(root, scopeArg) { + if (!scopeArg) return "."; + const abs = path.resolve(root, scopeArg); + const relative = path.relative(root, abs); + if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative) || !isDir(abs)) { + fail(EXIT.NOT_FOUND, "scope-not-found", `--scope ${scopeArg} is not a folder under ${root}.`, "Pass a folder inside the project, or leave --scope out for the whole project."); + } + return slash(relative) || "."; +} + +/** A tool's path as forward slashes relative to root; absolute and file: paths are made relative. */ +function projectPath(root, p) { + let file = String(p).trim(); + if (/^file:/i.test(file)) { + try { + file = fileURLToPath(file); + } catch { + file = decodeURIComponent(file.replace(/^file:\/*/i, "")); + } + } + if (path.isAbsolute(file) || /^[A-Za-z]:[\\/]/.test(file)) file = path.relative(root, file); + return file.replace(/\\/g, "/").replace(/^\.\//, ""); +} + +const underScope = (scope, file) => scope === "." || file === scope || file.startsWith(`${scope}/`); + +/** Quote a path for the shell when it needs it. */ +const shellPath = (p) => (/^<[\w.]+>$/.test(p) || /^[\w./:\\-]+$/.test(p) ? p : `"${p}"`); + +// Stands in for the temp report file in the commands detect prints (left unquoted). +const SARIF_FILE = ""; + +/* -------------------------------------------------------------- counting */ + +/** Source files under dir by language group, skipping SKIP_DIRS, dot-folders (build and cache output such as .next) and coverage, and never following links. */ +function countSources(dir) { + const counts = new Map(); + const stack = [dir]; + while (stack.length) { + const d = stack.pop(); + let entries; + try { + entries = fs.readdirSync(d, { withFileTypes: true }); + } catch { + continue; + } + for (const entry of entries) { + if (entry.isDirectory()) { + if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith(".") && entry.name !== "coverage") stack.push(path.join(d, entry.name)); + } else if (entry.isFile()) { + const lang = LANGUAGE_OF.get(path.extname(entry.name).toLowerCase()); + if (lang) counts.set(lang, (counts.get(lang) || 0) + 1); + } + } + } + const languages = LANGUAGES.filter((l) => counts.has(l.id)).map((l) => ({ id: l.id, files: counts.get(l.id) })); + return { languages, sourceFiles: languages.reduce((n, l) => n + l.files, 0) }; +} + +/* ------------------------------------------------------------ tool table */ + +/** + * A binary on PATH, by name. On Windows each PATHEXT extension is tried, so a + * test can fake a tool with a stub file on a temp PATH. + * Returns the full path, or null. + */ +export function onPath(name, env = process.env) { + const dirs = (env.PATH || env.Path || "").split(path.delimiter).filter(Boolean); + const exts = process.platform === "win32" ? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""]; + for (const dir of dirs) { + for (const ext of exts) { + const candidate = path.join(dir, name + ext); + try { + if (!fs.statSync(candidate).isFile()) continue; + if (process.platform !== "win32") fs.accessSync(candidate, fs.constants.X_OK); + return candidate; + } catch {} + } + } + return null; +} + +/** What detection reads from the project, read once. */ +function projectFacts(root) { + const text = (rel) => readText(path.join(root, rel)) || ""; + const exists = (rel) => fs.existsSync(path.join(root, rel)); + let pkg = null; + try { + pkg = JSON.parse(text("package.json") || "null"); + } catch {} + let rootEntries = []; + try { + rootEntries = fs.readdirSync(root); + } catch {} + const builds = ["pom.xml", "build.gradle", "build.gradle.kts"].filter(exists); + const buildText = builds.map(text).join("\n"); + return { text, exists, pkg, rootEntries, builds, buildText, composer: text("composer.json"), gemfile: text("Gemfile") }; +} + +const firstExisting = (facts, names) => names.find((n) => facts.exists(n)) || null; + +/** + * Every tool the script knows. marker(facts) names what was found (or null); + * available(facts) says whether it can run here; command(scope, sarif, facts) + * is the shell command run from the project root. findingExits are the exit + * codes the tool uses for "found something", which are not failures. + * SARIF flags were checked against each tool's documentation (see the + * phase-1 notes): PMD -f sarif -r, SpotBugs -sarif=, detekt --report + * sarif:, Psalm --report=.sarif.json. RuboCop has no built-in SARIF + * formatter, so it runs in the agent format. + */ +const TOOLS = [ + { + id: "knip", + language: "javascript", + format: "knip-json", + findingExits: [1], + marker(f) { + const file = firstExisting(f, ["knip.json", "knip.jsonc", ".knip.json", ".knip.jsonc", "knip.ts"]); + if (file) return file; + const pkg = f.pkg || {}; + if (pkg.dependencies && pkg.dependencies.knip) return "package.json dependencies"; + if (pkg.devDependencies && pkg.devDependencies.knip) return "package.json devDependencies"; + if (pkg.knip) return "package.json knip key"; + return null; + }, + available: (f) => f.exists("node_modules/.bin/knip") || f.exists("node_modules/.bin/knip.cmd"), + // --no-install: npx must never download a tool into the person's project (NFR-1). + command: () => "npx --no-install knip --reporter json", + }, + { + id: "vulture", + language: "python", + format: "vulture", + findingExits: [3], + marker(f) { + if (/^\s*\[tool\.vulture\]/m.test(f.text("pyproject.toml"))) return "pyproject.toml [tool.vulture]"; + const listed = [...f.rootEntries.filter((n) => /^requirements.*\.txt$/i.test(n)).sort(), "setup.cfg", "tox.ini"].find((n) => /\bvulture\b/i.test(f.text(n))); + if (listed) return listed; + return onPath("vulture") ? "vulture on PATH" : null; + }, + available: () => Boolean(onPath("vulture")), + command: (scope) => `vulture ${shellPath(scope)}`, + }, + { + id: "cargo-check", + language: "rust", + format: "cargo-json", + findingExits: [], + marker: (f) => (f.exists("Cargo.toml") ? "Cargo.toml" : null), + available: () => Boolean(onPath("cargo")), + command: () => "cargo check --message-format=json --all-targets", + }, + { + id: "go-deadcode", + language: "go", + format: "go-deadcode", + findingExits: [], + // deadcode has no config file: present only as a binary on PATH. + marker: (f) => (f.exists("go.mod") && onPath("deadcode") ? "go.mod and deadcode on PATH" : null), + available: () => Boolean(onPath("deadcode")), + command: () => "deadcode ./...", + }, + { + id: "pmd", + language: "java", + format: "sarif", + // 4: violations found. 5: a recoverable error (a file PMD could not + // parse); the report is still written. + findingExits: [4, 5], + marker(f) { + const ruleset = pmdRuleset(f); + if (ruleset) return ruleset; + if (/maven-pmd-plugin/.test(f.buildText)) return "pom.xml maven-pmd-plugin"; + if (/(id\s*\(?\s*["']pmd["']|apply\s+plugin\s*:\s*["']pmd["']|^\s*pmd\s*\{)/m.test(f.buildText)) return "Gradle pmd plugin"; + return onPath("pmd") ? "pmd on PATH" : null; + }, + available: () => Boolean(onPath("pmd")), + // Only PMD's unused-code rules: a general ruleset (the project's own, or + // quickstart.xml) would bury them under style findings. + command: (scope, sarif) => `pmd check -d ${shellPath(scope)} -R ${PMD_RULES} -f sarif -r ${shellPath(sarif)}`, + }, + { + id: "spotbugs", + language: "java", + format: "sarif", + findingExits: [], + marker(f) { + if (/spotbugs/i.test(f.buildText)) return `${f.builds.find((b) => /spotbugs/i.test(f.text(b)))} spotbugs plugin`; + return onPath("spotbugs") ? "spotbugs on PATH" : null; + }, + available: () => Boolean(onPath("spotbugs")), + command: (scope, sarif) => `spotbugs -textui -sarif=${shellPath(sarif)} ${shellPath(scope)}`, + }, + { + id: "detekt", + language: "java", + format: "sarif", + findingExits: [2], + marker(f) { + const config = firstExisting(f, ["detekt.yml", "config/detekt/detekt.yml", "config/detekt.yml"]); + if (config) return config; + if (/detekt/i.test(f.buildText)) return "Gradle detekt plugin"; + return onPath("detekt") ? "detekt on PATH" : null; + }, + available: () => Boolean(onPath("detekt")), + command(scope, sarif, f) { + const config = firstExisting(f, ["detekt.yml", "config/detekt/detekt.yml", "config/detekt.yml"]); + return `detekt --input ${shellPath(scope)}${config ? ` --config ${shellPath(config)}` : ""} --report sarif:${shellPath(sarif)}`; + }, + }, + { + id: "psalm", + language: "php", + format: "sarif", + findingExits: [2], + marker(f) { + const config = firstExisting(f, ["psalm.xml", "psalm.xml.dist"]); + if (config) return config; + if (/"vimeo\/psalm"/.test(f.composer)) return "composer.json vimeo/psalm"; + return onPath("psalm") ? "psalm on PATH" : null; + }, + available: (f) => Boolean(vendorBin(f, "psalm") || onPath("psalm")), + // Psalm picks the report format by the file's extension. + command: (scope, sarif, f) => `${vendorBin(f, "psalm") || "psalm"} --find-unused-code --report=${shellPath(psalmReport(sarif))} ${shellPath(scope)}`, + reportFile: (sarif) => psalmReport(sarif), + }, + { + id: "rubocop", + language: "ruby", + // No built-in SARIF formatter in RuboCop (its formatter list has none), so + // the agent reads its output. + format: "agent", + findingExits: [1], + marker(f) { + if (f.exists(".rubocop.yml")) return ".rubocop.yml"; + if (/['"]rubocop['"]/.test(f.gemfile)) return "Gemfile rubocop"; + return onPath("rubocop") ? "rubocop on PATH" : null; + }, + available: () => Boolean(onPath("rubocop")), + command: (scope) => `rubocop --only Lint/UnusedPrivateMethod,Lint/UselessAssignment ${shellPath(scope)}`, + }, + { + id: "debride", + language: "ruby", + format: "agent", + findingExits: [], + marker(f) { + if (/['"]debride['"]/.test(f.gemfile)) return "Gemfile debride"; + return onPath("debride") ? "debride on PATH" : null; + }, + available: () => Boolean(onPath("debride")), + command: (scope) => `debride ${shellPath(scope)}`, + }, + { + id: "phpstan", + language: "php", + format: "agent", + findingExits: [1], + marker(f) { + const config = firstExisting(f, ["phpstan.neon", "phpstan.neon.dist", "phpstan.dist.neon"]); + if (config) return config; + if (/"phpstan\/phpstan"/.test(f.composer)) return "composer.json phpstan/phpstan"; + return onPath("phpstan") ? "phpstan on PATH" : null; + }, + available: (f) => Boolean(vendorBin(f, "phpstan") || onPath("phpstan")), + // Level 4 is where PHPStan's unused private member rules start. + command: (scope, sarif, f) => `${vendorBin(f, "phpstan") || "phpstan"} analyse --level 4 --no-progress ${shellPath(scope)}`, + }, + { + id: "error-prone", + language: "java", + format: "agent", + findingExits: [], + marker: (f) => (/error_prone|errorprone/i.test(f.buildText) ? `${f.builds.find((b) => /error_prone|errorprone/i.test(f.text(b)))} Error Prone` : null), + available: (f) => Boolean(javaCompile(f)), + // Error Prone runs inside the project's own compile. + command: (scope, sarif, f) => javaCompile(f) || "mvn -q compile", + }, + { + id: "java-compile", + language: "java", + format: "agent", + findingExits: [], + marker: (f) => (f.builds.length ? f.builds[0] : null), + available: (f) => Boolean(javaCompile(f)), + command: (scope, sarif, f) => javaCompile(f) || "mvn -q compile", + }, + { + id: "dotnet-build", + language: "csharp", + format: "agent", + findingExits: [], + marker: (f) => f.rootEntries.filter((n) => /\.(sln|slnx|csproj)$/i.test(n)).sort()[0] || null, + available: () => Boolean(onPath("dotnet")), + command: () => "dotnet build", + }, +]; +const TOOL_BY_ID = new Map(TOOLS.map((t) => [t.id, t])); + +const PMD_RULES = ["UnusedPrivateMethod", "UnusedPrivateField", "UnusedLocalVariable", "UnusedFormalParameter", "UnusedAssignment"] + .map((rule) => `category/java/bestpractices.xml/${rule}`) + .join(","); + +/** A PMD ruleset file the project keeps (a sign PMD is set up), or null. */ +function pmdRuleset(f) { + const named = f.rootEntries.filter((n) => /pmd.*\.xml$/i.test(n)).sort()[0]; + if (named) return named; + for (const dir of ["config/pmd", "pmd"]) { + let entries = []; + try { + entries = fs.readdirSync(path.join(f.root, dir)); + } catch {} + const xml = entries.filter((n) => n.toLowerCase().endsWith(".xml")).sort()[0]; + if (xml) return `${dir}/${xml}`; + } + return null; +} + +/** Psalm's report path: the SARIF file with a .sarif.json extension. */ +const psalmReport = (sarif) => (sarif === SARIF_FILE ? "" : sarif.replace(/\.sarif$/, ".sarif.json")); + +/** A Composer-installed binary (vendor/bin/) as a native relative path, or null. */ +function vendorBin(f, name) { + const win = process.platform === "win32"; + const rel = `vendor/bin/${name}${win ? ".bat" : ""}`; + return f.exists(rel) ? path.join("vendor", "bin", name + (win ? ".bat" : "")) : null; +} + +/** The project's own Java or Kotlin compile command, or null when it cannot run here. */ +function javaCompile(f) { + const win = process.platform === "win32"; + if (f.builds.some((b) => b.startsWith("build.gradle"))) { + if (f.exists(win ? "gradlew.bat" : "gradlew")) return `${win ? "gradlew.bat" : "./gradlew"} classes`; + if (onPath("gradle")) return "gradle classes"; + } + if (f.builds.includes("pom.xml") && onPath("mvn")) return "mvn -q compile"; + return null; +} + +/** Every tool whose marker is found, in TOOLS order. */ +function detectTools(root, scope) { + const facts = { ...projectFacts(root), root }; + const found = []; + for (const tool of TOOLS) { + const marker = tool.marker(facts); + if (!marker) continue; + found.push({ + id: tool.id, + language: tool.language, + marker, + available: Boolean(tool.available(facts)), + command: tool.command(scope, SARIF_FILE, facts), + format: tool.format, + }); + } + return { facts, found }; +} + +/* --------------------------------------------------------------- readers */ + +const nonEmptyLines = (text) => String(text || "").split(/\r?\n/).map((l) => l.trimEnd()).filter((l) => l.trim()); + +/** The first quoted symbol in a message: `x`, 'x', "x" or a curly-quoted one. */ +function quotedName(text) { + const m = String(text || "").match(/`([^`]+)`|'([^']+)'|"([^"]+)"|‘([^’]+)’|“([^”]+)”/); + return m ? m.slice(1).find((g) => g !== undefined) : ""; +} + +/** The item a message ends on ("... to method App\Mailer::sendLater"), or "": a tool that quotes nothing still names it last. */ +function trailingName(text) { + const m = String(text || "").trim().match(/\b(?:method|function|property|class|constant|field|variable)\s+([\w\\]+(?:::\$?\w+)?)\.?$/i); + return m ? m[1] : ""; +} + +/** + * SARIF 2.1.0: one candidate per runs[].results[] with a location. kind comes + * from the rule id (Unused, Unreachable, Dead), else "unknown". + */ +export function readSarif(text, root = process.cwd()) { + let doc; + try { + doc = JSON.parse(text); + } catch { + return { candidates: [], skipped: 0, unparsed: true }; + } + const candidates = []; + let skipped = 0; + for (const runEntry of Array.isArray(doc && doc.runs) ? doc.runs : []) { + for (const result of Array.isArray(runEntry && runEntry.results) ? runEntry.results : []) { + const loc = result && Array.isArray(result.locations) ? result.locations[0] : null; + const physical = loc && loc.physicalLocation; + const uri = physical && physical.artifactLocation && physical.artifactLocation.uri; + if (!uri) { + skipped++; + continue; + } + const rule = result.ruleId || (result.rule && result.rule.id) || null; + const message = (result.message && (result.message.text || result.message.markdown)) || ""; + const kind = /unused/i.test(rule || "") ? "unused" : /unreachable/i.test(rule || "") ? "unreachable" : /dead/i.test(rule || "") ? "dead" : "unknown"; + candidates.push({ + file: projectPath(root, uri), + line: (physical.region && physical.region.startLine) || null, + name: quotedName(message) || trailingName(message), + kind, + source: "tool", + rule, + message, + }); + } + } + return { candidates, skipped }; +} + +const KNIP_KINDS = { exports: "export", types: "type", enumMembers: "enum-member", classMembers: "class-member", duplicates: "duplicate" }; + +/** The items of one Knip issue type: an array, or an object of arrays keyed by parent (enum or class). */ +function knipItems(value) { + if (Array.isArray(value)) return value.map((v) => ({ item: v, parent: null })); + if (value && typeof value === "object") return Object.entries(value).flatMap(([parent, list]) => (Array.isArray(list) ? list.map((v) => ({ item: v, parent })) : [])); + return []; +} + +/** + * Knip's --reporter json: unused files become kind "file", and each issue's + * exports, types, enumMembers, classMembers and duplicates become candidates + * with rule set to the issue type. + */ +export function readKnip(text, root = process.cwd()) { + // npx may print notices around the report; the report is the JSON object line. + let doc = null; + for (const line of [String(text || "").trim(), ...nonEmptyLines(text).filter((l) => l.trim().startsWith("{"))]) { + try { + doc = JSON.parse(line); + break; + } catch {} + } + if (!doc || typeof doc !== "object") return { candidates: [], skipped: 0, unparsed: true }; + const candidates = []; + let skipped = 0; + const seenFiles = new Set(); + const addFile = (file) => { + const f = projectPath(root, file); + if (seenFiles.has(f)) return; + seenFiles.add(f); + candidates.push({ file: f, line: null, name: "", kind: "file", source: "tool", rule: "files", message: "Unused file" }); + }; + for (const file of Array.isArray(doc.files) ? doc.files : []) { + if (typeof file === "string") addFile(file); + else if (file && file.name) addFile(file.name); + else skipped++; + } + for (const issue of Array.isArray(doc.issues) ? doc.issues : []) { + if (!issue || typeof issue.file !== "string") { + skipped++; + continue; + } + if (issue.files === true || (Array.isArray(issue.files) && issue.files.length)) addFile(issue.file); + for (const [type, kind] of Object.entries(KNIP_KINDS)) { + for (const { item, parent } of knipItems(issue[type])) { + // A duplicates entry is a group of names exported twice. + const group = Array.isArray(item) ? item : [item]; + const names = group.map((g) => (g && typeof g === "object" ? g.name : g)).filter((n) => typeof n === "string" && n); + if (!names.length) { + skipped++; + continue; + } + const first = group.find((g) => g && typeof g === "object") || {}; + const name = parent ? `${parent}.${names.join(", ")}` : names.join(", "); + candidates.push({ + file: projectPath(root, issue.file), + line: Number.isInteger(first.line) ? first.line : null, + name, + kind, + source: "tool", + rule: type, + message: `Unused ${kind.replace("-", " ")} ${name}`, + }); + } + } + } + return { candidates, skipped }; +} + +const VULTURE_LINE = /^(.+?):(\d+): (.+?) \((\d+)% confidence[^)]*\)$/; + +/** vulture: `path:line: unused '' (% confidence)`, and its unreachable-code lines. */ +export function readVulture(text, root = process.cwd()) { + const candidates = []; + let skipped = 0; + for (const line of nonEmptyLines(text)) { + const m = line.match(VULTURE_LINE); + if (!m) { + skipped++; + continue; + } + const what = m[3]; + const unused = what.match(/^unused (.+?) '(.+)'$/); + const kind = unused ? unused[1] : /^unreachable code/.test(what) ? "unreachable code" : what.replace(/'.*$/, "").trim(); + candidates.push({ + file: projectPath(root, m[1]), + line: Number(m[2]), + // An unreachable-code line quotes the statement before it, not a symbol. + name: unused ? unused[2] : kind === "unreachable code" ? "" : quotedName(what), + kind, + source: "tool", + rule: `vulture-${kind.replace(/\s+/g, "-")}`, + message: `${what} (${m[4]}% confidence)`, + }); + } + return { candidates, skipped }; +} + +/** + * cargo check --message-format=json: compiler-message records whose code is + * dead_code or unused_*, at the primary span. Lines that are not JSON records + * (cargo's own progress text) are not findings and are not counted. + */ +export function readCargo(text, root = process.cwd()) { + const candidates = []; + let skipped = 0; + const seen = new Set(); + for (const line of nonEmptyLines(text)) { + if (!line.trim().startsWith("{")) continue; + let record; + try { + record = JSON.parse(line); + } catch { + skipped++; + continue; + } + if (!record || record.reason !== "compiler-message") continue; + const message = record.message || {}; + const code = message.code && message.code.code; + if (!code || !(code === "dead_code" || code.startsWith("unused_"))) continue; + // rustc groups items in one warning ("unused imports: `fmt` and `io`"), + // one primary span per item: each becomes its own candidate. + const primaries = (Array.isArray(message.spans) ? message.spans : []).filter((s) => s && s.is_primary && s.file_name); + if (!primaries.length) { + skipped++; + continue; + } + const text = message.message || ""; + const kind = code === "dead_code" ? deadCodeKind(text) : code; + for (const span of primaries) { + const file = projectPath(root, span.file_name); + // --all-targets builds a crate more than once and repeats each warning. + const key = `${file}:${span.line_start}:${span.column_start}:${code}:${text}`; + if (seen.has(key)) continue; + seen.add(key); + const name = spanText(span) || (primaries.length === 1 ? quotedName(text) : ""); + candidates.push({ file, line: span.line_start || null, name, kind, source: "tool", rule: code, message: text }); + } + } + return { candidates, skipped }; +} + +/** The item a dead_code warning names: "function `x` is never used" and "multiple fields are never read" give function and field. */ +function deadCodeKind(text) { + const head = text.includes("`") ? text.split("`")[0] : (text.match(/^(.+?) (?:is|are) never\b/) || [])[1] || ""; + return ( + head + .trim() + .replace(/^multiple\s+/, "") + .replace(/aliases$/, "alias") + .replace(/(? 0); + return { candidates: result.candidates, skipped: result.skipped, unparsed }; +} + +/* ------------------------------------------------------------- keep file */ + +// The shared keep list (FR-13): tracked in the person's project, safe to +// commit. One table row per kept item; prose around the table is the +// person's and is never rewritten. +export const STATE_DIR = ".plan2code-dead-code"; +const KEEP_REL = `${STATE_DIR}/keep.md`; +const KEEP_COLUMNS = ["File", "Name", "Hash", "Reason", "Date"]; +const KEEP_HEADER_LINE = /^\|\s*File\s*\|\s*Name\s*\|\s*Hash\s*\|\s*Reason\s*\|\s*Date\s*\|\s*$/i; +const KEEP_INTRO = [ + "# Dead Code keep list", + "", + "This list is shared and safe to commit. Each row is code the Dead Code skill found unused that was kept on purpose, with the reason. A kept item stays hidden in later runs until its declaration line changes; take a row out to have it checked again.", + "", +]; + +/** A table cell: one line, pipes escaped. */ +const cell = (value) => String(value ?? "").replace(/\s+/g, " ").trim().replace(/\|/g, "\\|"); +/** A table row's cells, split on unescaped pipes and unescaped. */ +const rowCells = (line) => + line + .trim() + .replace(/^\|/, "") + .replace(/(? c.trim().replace(/\\\|/g, "|")); + +/** Where the keep table sits in the file's lines: { header, end } (end exclusive), or null. */ +function keepTableSpan(lines) { + const header = lines.findIndex((l) => KEEP_HEADER_LINE.test(l)); + if (header === -1) return null; + let end = header + 1; + while (end < lines.length && lines[end].trim().startsWith("|")) end++; + return { header, end }; +} + +/** The keep list: { entries: [{ file, name, hash, reason, date }], path, exists }. A missing file or one with no table has no entries. */ +export function readKeep(root) { + const file = path.join(root, KEEP_REL); + const text = readText(file); + if (text === null) return { entries: [], path: file, exists: false }; + const lines = text.split(/\r?\n/); + const span = keepTableSpan(lines); + const entries = []; + if (span) { + for (const line of lines.slice(span.header + 1, span.end)) { + if (/^\|[\s:|-]+\|?\s*$/.test(line.trim())) continue; // the separator row + const [f = "", name = "", hash = "", reason = "", date = ""] = rowCells(line); + if (!f) continue; + entries.push({ file: f.replace(/\\/g, "/"), name, hash, reason, date }); + } + } + return { entries, path: file, exists: true }; +} + +/** The keep table's lines for `entries`. */ +function keepTable(entries) { + return [ + `| ${KEEP_COLUMNS.join(" | ")} |`, + `| ${KEEP_COLUMNS.map(() => "---").join(" | ")} |`, + ...entries.map((e) => `| ${[e.file, e.name, e.hash, e.reason, e.date].map(cell).join(" | ")} |`), + ]; +} + +/** The keep file's text with its table set to `entries`, keeping any prose; `current` null builds a new file. */ +function keepText(current, entries) { + if (current === null) return [...KEEP_INTRO, ...keepTable(entries), ""].join("\n"); + const nl = eol(current); + const lines = current.split(/\r?\n/); + const span = keepTableSpan(lines); + if (span) lines.splice(span.header, span.end - span.header, ...keepTable(entries)); + else { + while (lines.length && lines[lines.length - 1] === "") lines.pop(); + lines.push("", ...keepTable(entries), ""); + } + return lines.join(nl); +} + +/** Rewrite the keep table (creating the folder and the file on first write). Returns the file's path. */ +export function writeKeep(root, entries) { + const file = path.join(root, KEEP_REL); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, keepText(readText(file), entries)); + return file; +} + +/** Marks a keep hash that covers a whole file (an unused file has no declaration line). */ +const WHOLE_FILE = "file:"; + +/** A declaration line as the hash sees it: trimmed, whitespace runs collapsed. */ +const normalizeDecl = (line) => line.trim().replace(/\s+/g, " "); +const hashOf = (text) => crypto.createHash("sha256").update(text).digest("hex").slice(0, 12); + +/** Every line's base hash (normalized, 12 hex), so a file is hashed once per command. */ +export const lineHashes = (text) => text.split(/\r?\n/).map((l) => hashOf(normalizeDecl(l))); + +/** A keep hash split into its 12-hex base and occurrence number: "a1b2c3d4e5f6#2" is { base, n: 2 }; any other string (a plain or file: hash) has n null. */ +export function splitHash(hash) { + const m = /^([0-9a-f]{12})#([1-9]\d*)$/.exec(String(hash)); + return m ? { base: m[1], n: Number(m[2]) } : { base: String(hash), n: null }; +} + +/** The keep hash of line `line` (1-based) given a file's lineHashes: the base, plus "#n" when the line repeats (n counts identical lines from the top). null for a line the file does not have. */ +function hashAt(hashes, line) { + if (!Number.isInteger(line) || line < 1 || line > hashes.length) return null; + const base = hashes[line - 1]; + let copies = 0; + let n = 0; + hashes.forEach((h, i) => { + if (h !== base) return; + copies++; + if (i < line) n++; + }); + return { hash: copies > 1 ? `${base}#${n}` : base, base, copies }; +} + +/** + * A file's declaration line as the keep list stores it: { hash, base, copies, + * missing }. base is the first 12 hex of the sha256 of the normalized line; + * copies is how many lines of the file share that base. hash is base for a + * line unique in its file, and base#n for the n-th (1-based, top to bottom) + * of several identical lines. missing (hash "") when the file or line is gone. + */ +export function declHash(root, file, line) { + const text = readText(path.resolve(root, file)); + const at = text === null ? null : hashAt(lineHashes(text), line); + if (!at) return { hash: "", missing: true }; + return { ...at, missing: false }; +} + +/** + * A kept entry against the code now. The table holds no line number, so a + * moved declaration is still found. A plain hash is current while exactly one + * line of the file has it (a plain row means a line unique in its file); a + * base#n hash is current while at least two lines share the base and copy n + * exists. A whole-file hash is current while the file's text is unchanged. + * Otherwise: changed when the file still names the item, gone when the file + * is missing or no longer names it. `cached` ({ text, hashes }, or null for a + * missing file) saves a read when the caller has the file already. + */ +export function keepState(root, entry, cached) { + if (cached === null) return "gone"; + const text = cached ? cached.text : readText(path.resolve(root, entry.file)); + if (text === null) return "gone"; + if (String(entry.hash).startsWith(WHOLE_FILE)) return WHOLE_FILE + hashOf(text) === entry.hash ? "current" : "changed"; + if (entry.hash) { + const hashes = cached ? cached.hashes : lineHashes(text); + const { base, n } = splitHash(entry.hash); + const copies = hashes.filter((h) => h === base).length; + if (n === null ? copies === 1 : copies >= 2 && copies >= n) return "current"; + } + // Knip names a member "Parent.member" and a duplicate group "a, b": any part found counts. + const parts = String(entry.name || "") + .split(/[\s,]+/) + .map((p) => p.split(".").pop()) + .filter(Boolean); + return parts.some((p) => text.includes(p)) ? "changed" : "gone"; +} + +/** + * A file argument as a forward-slash path relative to root. A path that + * resolves outside the project exits 5: the script reads and writes only + * inside the project it was pointed at. + */ +function insideRoot(root, file) { + if (!isInsideRoot(root, file)) fail(EXIT.REFUSED, "outside-root", `${file} is not a file inside ${slash(root)}.`, "Pass paths relative to the project root, inside it."); + const abs = path.resolve(root, String(file)); + return { abs, rel: slash(path.relative(root, abs)) }; +} + +/** Whether a file argument resolves to a path inside root (insideRoot's test, without exiting). */ +function isInsideRoot(root, file) { + const relative = path.relative(root, path.resolve(root, String(file))); + // ".." as a whole segment only: a file named "..foo.js" is inside the project. + return !(!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)); +} + +/* -------------------------------------------------------------- commands */ + +function wholeNumber(value, flag, fallback, max = Infinity) { + if (value === undefined) return fallback; + const n = Number(value); + if (!Number.isInteger(n) || n < 1 || n > max) fail(EXIT.USAGE, "bad-number", `--${flag} needs a whole number from 1${max === Infinity ? " up" : ` to ${max}`}, got "${value}".`, "Run with --help for usage."); + return n; +} + +function noPositionals(args, command) { + if (args._.length) fail(EXIT.USAGE, "unexpected-argument", `Unexpected argument "${args._[0]}" for ${command}.`, "Run with --help for usage."); +} + +function cmdDetect(argv) { + const args = parseArgs(argv, { values: ["scope", "root", "limit"] }); + noPositionals(args, "detect"); + const root = projectRoot(args.root); + const scope = projectScope(root, args.scope); + const limit = wholeNumber(args.limit, "limit", NARROW_LIMIT); + const { languages, sourceFiles } = countSources(path.join(root, scope)); + const { found } = detectTools(root, scope); + out({ ok: true, root: slash(root), scope, languages, sourceFiles, overLimit: sourceFiles > limit, limit, tools: found }); +} + +function tailLines(text) { + const lines = String(text || "").split(/\r?\n/); + if (lines.length && lines[lines.length - 1] === "") lines.pop(); + // Cap each line, as run-check.mjs does: one cargo JSON record is several KB. + return lines.slice(-TAIL_LINES).map((l) => (l.length > TAIL_LINE_CAP ? l.slice(0, TAIL_LINE_CAP) : l)); +} + +async function cmdRun(argv) { + const args = parseArgs(argv, { values: ["tool", "scope", "timeout", "root"] }); + noPositionals(args, "run"); + if (!args.tool) fail(EXIT.USAGE, "missing-tool", "run needs --tool .", "Run detect and pass one of its tools[].id."); + const tool = TOOL_BY_ID.get(args.tool); + if (!tool) fail(EXIT.USAGE, "unknown-tool", `There is no tool "${args.tool}".`, `Pass one of: ${TOOLS.map((t) => t.id).join(", ")}.`); + const root = projectRoot(args.root); + const scope = projectScope(root, args.scope); + const timeout = wholeNumber(args.timeout, "timeout", DEFAULT_TIMEOUT, MAX_TIMEOUT); + const { facts, found } = detectTools(root, scope); + const detected = found.find((t) => t.id === tool.id); + if (!detected) fail(EXIT.NOT_FOUND, "tool-not-detected", `${tool.id} is not set up in this project.`, "Run detect and pick one of the tools it lists, or search for callers without a tool."); + if (!detected.available) fail(EXIT.NOT_FOUND, "tool-unavailable", `${tool.id} is set up (${detected.marker}) but cannot run here.`, "Its binary is not installed; never install it. Search for callers without a tool."); + + const work = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-dead-code-")); + try { + const sarif = path.join(work, "report.sarif"); + const log = path.join(work, "output.log"); + const cmd = tool.command(scope, sarif, facts); + // run-check.mjs owns the spawn, the timeout and the process-tree kill. + const result = await runCheck({ cmd, cwd: root, timeout, log }); + const output = readText(log) || ""; + const base = { tool: tool.id, format: tool.format, exit: result.exit, seconds: result.seconds, tail: tailLines(output) }; + if (result.outcome === "not-started") fail(EXIT.NOT_FOUND, "tool-not-started", `${tool.id} did not start (${result.reason}).`, "Check the tool is installed in the project; never install it. Search for callers without a tool.", base); + if (result.outcome === "timeout") fail(EXIT.INVALID, "tool-timeout", `${tool.id} was stopped after ${timeout} seconds.`, "Run it again with a longer --timeout, narrow --scope, or search for callers without a tool.", base); + if (result.outcome === "failed" && !tool.findingExits.includes(result.exit)) fail(EXIT.INVALID, "tool-failed", `${tool.id} failed with exit ${result.exit}.`, "Read tail for the cause; fix the tool's setup or search for callers without a tool.", base); + + let read; + if (tool.format === "agent") read = { candidates: [], skipped: 0, unparsed: true }; + else if (tool.format === "sarif") { + const report = readText(tool.reportFile ? tool.reportFile(sarif) : sarif); + read = report === null ? { candidates: [], skipped: 0, unparsed: true } : readOutput("sarif", report, root); + } else read = output.trim() ? readOutput(tool.format, output, root) : { candidates: [], skipped: 0, unparsed: false }; + const candidates = read.candidates.filter((c) => underScope(scope, c.file)); + out({ ok: true, ...base, scope, candidates, unparsed: read.unparsed, skipped: read.skipped }); + } finally { + fs.rmSync(work, { recursive: true, force: true }); + } +} + +function cmdNarrow(argv) { + const args = parseArgs(argv, { values: ["candidates", "depth"] }); + noPositionals(args, "narrow"); + if (!args.candidates) fail(EXIT.USAGE, "missing-candidates", "narrow needs --candidates .", "Save run's output (or its candidates array) to a file and pass it."); + const depth = wholeNumber(args.depth, "depth", 2); + const text = readText(path.resolve(args.candidates)); + if (text === null) fail(EXIT.NOT_FOUND, "candidates-missing", `Cannot read ${args.candidates}.`, "Pass the file you saved run's output to."); + let doc; + try { + doc = JSON.parse(text); + } catch (err) { + fail(EXIT.INVALID, "candidates-invalid", `${args.candidates} is not valid JSON (${err.message}).`, "Save run's JSON output unchanged."); + } + const list = Array.isArray(doc) ? doc : doc && Array.isArray(doc.candidates) ? doc.candidates : null; + if (!list) fail(EXIT.INVALID, "candidates-invalid", `${args.candidates} holds no candidates array.`, "Pass run's output, or its candidates array."); + const counts = new Map(); + for (const c of list) { + const parts = String((c && c.file) || "").replace(/\\/g, "/").split("/").filter(Boolean); + const folder = parts.slice(0, -1).slice(0, depth).join("/") || "."; + counts.set(folder, (counts.get(folder) || 0) + 1); + } + const folders = [...counts].map(([p, candidates]) => ({ path: p, candidates })).sort((a, b) => b.candidates - a.candidates || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); + out({ ok: true, folders, total: list.length }); +} + +/* ------------------------------------------------------------ keep list */ + +function keepList(argv) { + const args = parseArgs(argv, { values: ["root"] }); + noPositionals(args, "keep list"); + const root = projectRoot(args.root); + const keep = readKeep(root); + const entries = keep.entries.map((e) => ({ ...e, state: keepState(root, e) })); + out({ ok: true, exists: keep.exists, path: KEEP_REL, entries }); +} + +function keepAdd(argv) { + const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "file", "name", "line", "reason"] }); + noPositionals(args, "keep add"); + if (!args.file || !String(args.file).trim()) fail(EXIT.USAGE, "missing-file", "keep add needs --file.", "Pass --file and --reason, and --name and --line for an item inside the file."); + const named = String(args.name || "").trim(); + const wholeFile = args.line === undefined; + if (wholeFile && !named) { + // no name and no line: a whole unused file, kept by its path + } else if (!wholeFile && !String(args.line).trim()) fail(EXIT.USAGE, "missing-line", "keep add needs a value for --line.", "Pass the line the declaration is on, or leave --line out to keep the whole file."); + // FR-13: every kept item carries the person's reason. + if (!args.reason || !String(args.reason).trim()) fail(EXIT.USAGE, "missing-reason", "keep add needs a --reason, and it cannot be empty.", "Ask the person why the item stays, and pass their words as --reason."); + const root = projectRoot(args.root); + const { rel } = insideRoot(root, args.file); + let hash; + if (wholeFile) { + const text = readText(path.resolve(root, rel)); + if (text === null) fail(EXIT.NOT_FOUND, "file-missing", `${rel} is not a file in the project.`, "Pass a file that exists."); + hash = WHOLE_FILE + hashOf(text); + } else { + const line = wholeNumber(args.line, "line"); + const decl = declHash(root, rel, line); + if (decl.missing) fail(EXIT.NOT_FOUND, "declaration-missing", `${rel} has no line ${line}.`, "Pass the item's file and the line its declaration is on now."); + hash = decl.hash; + } + const entry = { file: rel, name: named, hash, reason: String(args.reason).replace(/\s+/g, " ").trim(), date: isoDate() }; + const keep = readKeep(root); + // Rows are told apart by file, name and hash: a same-named row with another + // hash that is still current is a different item and stays. The same item + // (same hash) or a stale same-named row (code changed since) is replaced. + const entries = keep.entries.filter((e) => !(e.file === entry.file && e.name === entry.name && (e.hash === entry.hash || keepState(root, e) !== "current"))); + const replaced = entries.length !== keep.entries.length; + entries.push(entry); + if (args["dry-run"]) return out({ ok: true, dryRun: true, entry, replaced, path: KEEP_REL }); + writeKeep(root, entries); + out({ ok: true, entry, replaced, path: KEEP_REL }); +} + +function keepRemove(argv) { + const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "file", "name", "hash", "line"] }); + noPositionals(args, "keep remove"); + // A whole-file entry is stored with name "", so --name may be left out or empty. + if (!args.file || !String(args.file).trim()) fail(EXIT.USAGE, "missing-file", "keep remove needs --file.", "Pass the --file and --name of the entry, as keep list prints them (no --name for a whole file)."); + const root = projectRoot(args.root); + const file = String(args.file).trim().replace(/\\/g, "/").replace(/^\.\//, ""); + const name = String(args.name ?? "").trim(); + const keep = readKeep(root); + let matches = keep.entries.filter((e) => e.file === file && e.name === name); + if (args.hash !== undefined) { + const hash = String(args.hash).trim(); + matches = matches.filter((e) => e.hash === hash); + } + if (args.line !== undefined) { + const line = wholeNumber(args.line, "line"); + const decl = declHash(root, insideRoot(root, file).rel, line); + if (decl.missing) fail(EXIT.NOT_FOUND, "declaration-missing", `${file} has no line ${line}.`, "Pass the item's file and the line its declaration is on now."); + matches = matches.filter((e) => e.hash === decl.hash); + } + if (!matches.length) fail(EXIT.NOT_FOUND, "not-kept", `${file} ${name} is not on the keep list.`, "Run keep list for the entries as they are written."); + // Several rows share this file and name: never guess which one is meant. + if (matches.length > 1) { + const rows = matches.map((e) => `${e.hash} (${e.reason})`).join("; "); + fail(EXIT.USAGE, "ambiguous-entry", `${file} ${name} matches ${matches.length} keep entries.`, `Rows: ${rows}. Pass --hash or --line to pick one.`); + } + const removed = matches[0]; + if (args["dry-run"]) return out({ ok: true, dryRun: true, removed, path: KEEP_REL }); + writeKeep(root, keep.entries.filter((e) => e !== removed)); + out({ ok: true, removed, path: KEEP_REL }); +} + +/** A JSON candidates array (or run's whole output) from stdin. */ +function readCandidatesStdin() { + let text = ""; + try { + text = fs.readFileSync(0, "utf8"); + } catch {} + let doc; + try { + doc = JSON.parse(text); + } catch (err) { + fail(EXIT.INVALID, "candidates-invalid", `stdin is not valid JSON (${text.trim() ? err.message : "it was empty"}).`, "Pipe the candidates array (or run's output) into keep filter."); + } + const list = Array.isArray(doc) ? doc : doc && Array.isArray(doc.candidates) ? doc.candidates : null; + if (!list) fail(EXIT.INVALID, "candidates-invalid", "stdin holds no candidates array.", "Pipe the candidates array (or run's output) into keep filter."); + return list; +} + +/** + * Split candidates by the keep list. A candidate with a line matches the row + * for its file and name whose hash is its own line's hash (with #n when that + * line repeats), so a kept item never hides a different one with the same + * name. A line-less candidate with no name matches only a whole-file row; a + * line-less named one matches its file and name (a line row first, else a + * whole-file row kept with that name). A current row hides its + * candidate; a changed one does not, and the candidate comes back marked + * wasKept with the old reason so it is looked at again (also when no row + * matches its hash but a same-named row is changed). --fresh hides nothing. + * kept always lists every entry, so the count stays visible. Each file is + * read and hashed at most once, and a candidate outside the root is never + * read (it counts as line-less). + */ +function keepFilter(argv) { + const args = parseArgs(argv, { booleans: ["fresh"], values: ["root"] }); + noPositionals(args, "keep filter"); + const root = projectRoot(args.root); + const candidates = readCandidatesStdin(); + const norm = (file) => String(file || "").replace(/\\/g, "/").replace(/^\.\//, ""); + const cache = new Map(); + const load = (file) => { + if (!cache.has(file)) { + const text = readText(path.resolve(root, file)); + cache.set(file, text === null ? null : { text, hashes: lineHashes(text) }); + } + return cache.get(file); + }; + const entries = readKeep(root).entries.map((e) => ({ ...e, state: keepState(root, e, load(norm(e.file))) })); + const keyOf = (file, name) => `${norm(file)}\u0000${name || ""}`; + const groups = new Map(); + for (const e of entries) { + const key = keyOf(e.file, e.name); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(e); + } + const isWhole = (e) => String(e.hash).startsWith(WHOLE_FILE); + /** The row a candidate answers to (with a line and no hash match, a changed same-named row so it is flagged), or undefined. */ + const matchOf = (c) => { + const file = norm(c && c.file); + const name = (c && c.name) || ""; + const group = groups.get(keyOf(file, name)) || []; + const inside = file !== "" && isInsideRoot(root, file); + if (inside && Number.isInteger(c.line)) { + const cached = load(file); + const at = cached && hashAt(cached.hashes, c.line); + const exact = at && group.find((e) => !isWhole(e) && e.hash === at.hash); + return exact || group.find((e) => !isWhole(e) && e.state === "changed"); + } + // A named whole-file row (keep add --name without --line) still answers a line-less finding of that name. + return name === "" ? group.find(isWhole) : group.find((e) => !isWhole(e)) || group.find(isWhole); + }; + const shown = []; + const hidden = []; + let changed = 0; + for (const c of candidates) { + const entry = args.fresh ? null : matchOf(c); + if (entry && entry.state === "current") hidden.push({ ...c, keptReason: entry.reason }); + else if (entry && entry.state === "changed") { + shown.push({ ...c, wasKept: true, keptReason: entry.reason }); + changed++; + } else shown.push(c); + } + const kept = entries.map((e) => ({ file: e.file, name: e.name, reason: e.reason, ...(e.state === "gone" ? { gone: true } : {}) })); + out({ ok: true, fresh: Boolean(args.fresh), shown, hidden, kept, changed }); +} + +const KEEP_COMMANDS = { list: keepList, add: keepAdd, remove: keepRemove, filter: keepFilter }; + +function cmdKeep(argv) { + const [sub, ...rest] = argv; + const handler = KEEP_COMMANDS[sub]; + if (!handler) fail(EXIT.USAGE, sub ? "unknown-keep-command" : "missing-keep-command", sub ? `Unknown keep command "${sub}".` : "keep needs a command.", "One of: list, filter, add, remove. Run with --help for usage."); + handler(rest); +} + +/* ------------------------------------------------------ backup, restore */ + +// Backups live under the system temp folder, outside the project, so a failed +// run never leaves stray files in the person's repo (NFR-3). They are copies, +// never moves, and nothing here deletes them: the operating system cleans temp. +const backupsHome = () => path.join(os.tmpdir(), `plan2code-dead-code-${typeof process.getuid === "function" ? process.getuid() : os.userInfo().username.replace(/[^A-Za-z0-9._-]/g, "_")}`); + +/** Make the per-user backup folder private (0700) and refuse one that is not a real folder owned by this user (exit 5). POSIX only; Windows temp is already per user. */ +function privateHome(dir) { + try { + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + } catch {} + if (process.platform === "win32") return dir; + let st = null; + try { + st = fs.lstatSync(dir); + } catch {} + const uid = typeof process.getuid === "function" ? process.getuid() : null; + if (!st || !st.isDirectory() || st.isSymbolicLink() || (uid !== null && st.uid !== uid) || (st.mode & 0o077) !== 0) { + fail(EXIT.REFUSED, "backup-folder-unsafe", `${slash(dir)} is not a private folder owned by you.`, "Remove or fix that folder (it should be mode 0700 and yours), then run backup again."); + } + return dir; +} +const RUN_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; + +function runId(value) { + if (value === undefined) return `${compactDate()}-${clock()}-${crypto.randomBytes(2).toString("hex")}`; + if (!RUN_ID.test(String(value)) || String(value).includes("..")) fail(EXIT.USAGE, "bad-run", `--run "${value}" is not a run id.`, "Pass the run id backup printed."); + return String(value); +} + +const sha256File = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); +const samePath = (a, b) => (process.platform === "win32" ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b)); + +function readManifest(dir) { + const text = readText(path.join(dir, "manifest.json")); + if (text === null) return null; + try { + const doc = JSON.parse(text); + if (doc && Array.isArray(doc.files)) return doc; + } catch {} + fail(EXIT.INVALID, "manifest-invalid", `${slash(path.join(dir, "manifest.json"))} is not a backup manifest.`, "Back the files up again under a new run id."); +} + +/** + * Copy files into /plan2code-dead-code//files/ and record each + * one's size and sha256 in the run's manifest. A file the run already holds + * keeps its first copy: a later backup of it in the same run would otherwise + * replace the original with an edited version. + */ +function cmdBackup(argv) { + const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "run"] }); + if (!args._.length) fail(EXIT.USAGE, "missing-files", "backup needs the files to copy.", "Pass each file the removal will change, relative to the project root."); + const root = projectRoot(args.root); + const run = runId(args.run); + const dir = path.join(args["dry-run"] ? backupsHome() : privateHome(backupsHome()), run); + const manifest = readManifest(dir) || { run, root: slash(root), created: now().toISOString(), files: [] }; + if (!samePath(manifest.root, root)) fail(EXIT.REFUSED, "other-project", `Run ${run} backs up ${manifest.root}, not ${slash(root)}.`, "Use a new run id for this project."); + const files = [...new Set(args._.map((f) => insideRoot(root, f).rel))]; + // Every source is checked before anything is copied: a missing one writes nothing. + for (const rel of files) { + let stat = null; + try { + stat = fs.statSync(path.join(root, rel)); + } catch {} + if (!stat || !stat.isFile()) fail(EXIT.NOT_FOUND, "file-missing", `${rel} is not a file in the project; nothing was backed up.`, "Back up only files that exist, before removing anything from them."); + } + const held = new Set(manifest.files.map((f) => f.path)); + const already = files.filter((rel) => held.has(rel)); + const added = files + .filter((rel) => !held.has(rel)) + .map((rel) => { + const src = path.join(root, rel); + return { path: rel, size: fs.statSync(src).size, sha256: sha256File(src) }; + }); + if (args["dry-run"]) return out({ ok: true, dryRun: true, run, dir: slash(dir), files: added, already }); + for (const entry of added) { + const copy = path.join(dir, "files", entry.path); + fs.mkdirSync(path.dirname(copy), { recursive: true }); + fs.copyFileSync(path.join(root, entry.path), copy); + if (sha256File(copy) !== entry.sha256) fail(EXIT.INVALID, "copy-unverified", `The backup copy of ${entry.path} does not match the file.`, "Nothing was removed yet; run backup again under a new run id."); + } + manifest.files.push(...added); + fs.writeFileSync(path.join(dir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n"); + out({ ok: true, run, dir: slash(dir), files: added, already }); +} + +/** Why a project file does not match its manifest entry, or null when it does. */ +function mismatch(file, entry) { + let stat; + try { + stat = fs.statSync(file); + } catch { + return "the file is missing"; + } + if (!stat.isFile()) return "not a file"; + if (stat.size !== entry.size) return `size ${stat.size}, expected ${entry.size}`; + if (sha256File(file) !== entry.sha256) return "content differs from the backup"; + return null; +} + +/** + * Copy a run's files back over the project (all, or --files) and check each + * one against the manifest afterwards. --verify copies nothing and only + * checks, so a put-back is confirmed before the next retry. Never deletes. + */ +function cmdRestore(argv) { + const args = parseArgs(argv, { booleans: ["verify", "dry-run"], values: ["root", "run"], lists: ["files"] }); + if (!args.run) fail(EXIT.USAGE, "missing-run", "restore needs --run .", "Pass the run id backup printed."); + const root = projectRoot(args.root); + const run = runId(args.run); + const dir = path.join(args.verify || args["dry-run"] ? backupsHome() : privateHome(backupsHome()), run); + const manifest = readManifest(dir); + if (!manifest) fail(EXIT.NOT_FOUND, "run-missing", `There is no backup for run ${run}.`, "Pass the run id backup printed; restore never guesses."); + if (!samePath(manifest.root, root)) fail(EXIT.REFUSED, "other-project", `Run ${run} backs up ${manifest.root}, not ${slash(root)}.`, "Run restore from the project the backup came from, or pass that --root."); + // The manifest sits in the shared temp folder: every path in it must still + // land inside the project before anything is copied (exit 5 otherwise). + for (const e of manifest.files) { + if (!e || typeof e.path !== "string" || !e.path) fail(EXIT.INVALID, "manifest-invalid", `Run ${run}'s manifest has an entry with no path.`, "Back the files up again under a new run id."); + insideRoot(root, e.path); + } + const named = [...(args.files || []), ...args._]; + let entries = manifest.files; + if (named.length) { + const wanted = new Set(named.map((f) => insideRoot(root, f).rel)); + const unknown = [...wanted].filter((rel) => !manifest.files.some((e) => e.path === rel)); + if (unknown.length) fail(EXIT.NOT_FOUND, "not-backed-up", `Run ${run} holds no copy of ${unknown.join(", ")}.`, "Restore only files backup printed for this run."); + entries = manifest.files.filter((e) => wanted.has(e.path)); + } + if (args["dry-run"] && !args.verify) return out({ ok: true, dryRun: true, run, restored: [], wouldRestore: entries.map((e) => e.path), mismatched: [] }); + + const restored = []; + const verified = []; + const mismatched = []; + for (const entry of entries) { + const target = path.join(root, entry.path); + if (!args.verify) { + // A damaged backup copy is reported and never copied over the project file. + const damaged = mismatch(path.join(dir, "files", entry.path), entry); + if (damaged) { + mismatched.push({ path: entry.path, reason: `backup copy damaged (${damaged}); the project file was left as it is` }); + continue; + } + try { + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.copyFileSync(path.join(dir, "files", entry.path), target); + } catch (err) { + mismatched.push({ path: entry.path, reason: `copy failed (${err.code || err.message})` }); + continue; + } + } + const why = mismatch(target, entry); + if (why) mismatched.push({ path: entry.path, reason: why }); + else (args.verify ? verified : restored).push(entry.path); + } + const result = { ok: mismatched.length === 0, run, ...(args.verify ? { verify: true, verified } : {}), restored, mismatched }; + if (mismatched.length) { + out({ ...result, error: "mismatch", message: `${mismatched.length} file(s) do not match the backup: ${mismatched.map((m) => m.path).join(", ")}.`, next: "Stop the retries and tell the person which files are not back as they were." }); + process.stderr.write(`error: ${mismatched.length} file(s) do not match the backup\n`); + process.exitCode = EXIT.INVALID; + return; + } + out(result); +} + +/* ---------------------------------------------------------------- report */ + +const REPORTS_REL = `${STATE_DIR}/reports`; +const LABELS = [ + { id: "safe", title: "Safe to remove" }, + { id: "check", title: "Check first" }, + { id: "warning", title: "Warning" }, +]; +// mode: how candidates were found. ranFrom: how much of the scope was checked (NFR-2). +const MODES = { verify: "the tool's list, verified by a caller search", full: "the tool's list plus a full search of our own", own: "a search of our own (no tool)" }; +/** The Found by line, in the plural when several tools ran. */ +const foundBy = (doc) => (Array.isArray(doc.tool) && doc.tool.length > 1 ? MODES[doc.mode].replace("the tool's list", "the tools' lists") : MODES[doc.mode]); +const RAN_FROM = ["complete", "narrowed", "stopped"]; +const SOURCES = { tool: "tool", own: "own search", both: "both" }; + +/** The findings file, checked: { scope, mode, tool, ranFrom, findings, hidden, notChecked }. */ +function readFindings(file) { + const text = readText(path.resolve(file)); + if (text === null) fail(EXIT.NOT_FOUND, "findings-missing", `Cannot read ${file}.`, "Write the run's findings JSON to a file and pass it."); + let doc; + try { + doc = JSON.parse(text); + } catch (err) { + fail(EXIT.INVALID, "findings-invalid", `${file} is not valid JSON (${err.message}).`, "Write the findings as JSON."); + } + const bad = (msg) => fail(EXIT.INVALID, "findings-invalid", `${file}: ${msg}`, "See --help for the findings file's fields."); + if (!doc || typeof doc !== "object" || Array.isArray(doc)) bad("expected an object with scope, mode, tool, ranFrom and findings."); + if (!Array.isArray(doc.findings)) bad("findings must be an array."); + const toolOk = doc.tool == null || typeof doc.tool === "string" || (Array.isArray(doc.tool) && doc.tool.every((t) => typeof t === "string")); + if (!toolOk) bad("tool must be a tool id, a list of ids, or null."); + if (!Object.hasOwn(MODES, doc.mode)) bad(`mode must be one of ${Object.keys(MODES).join(", ")}.`); + // A report never calls a partial run complete: ranFrom is required. + if (!RAN_FROM.includes(doc.ranFrom)) bad(`ranFrom must be one of ${RAN_FROM.join(", ")}.`); + doc.findings.forEach((f, i) => { + if (!f || typeof f !== "object" || !f.file) bad(`finding ${i + 1} has no file.`); + if (!LABELS.some((l) => l.id === f.label)) bad(`finding ${i + 1} (${f.file}) has label "${f.label}"; use safe, check or warning.`); + }); + return doc; +} + +const textOf = (v) => (Array.isArray(v) ? v.join("; ") : v == null ? "" : String(v)).replace(/\s+/g, " ").trim(); +const outcomeKey = (f) => (textOf(f.outcome).split(":")[0] || "no outcome").trim(); + +/** The report's Markdown. */ +export function reportMarkdown(doc, date) { + const scope = textOf(doc.scope) || "."; + const findings = doc.findings; + const count = (list, key) => { + const counts = new Map(); + for (const f of list) counts.set(key(f), (counts.get(key(f)) || 0) + 1); + return counts; + }; + const byLabel = count(findings, (f) => f.label); + const byOutcome = count(findings, outcomeKey); + const hidden = Number.isInteger(doc.hidden) && doc.hidden > 0 ? doc.hidden : 0; + const lines = [ + "# Dead Code report", + "", + `**Date:** ${date}`, + "", + "## Summary", + "", + `- **Scope:** ${scope === "." ? "the whole project" : `\`${scope}\``}`, + Array.isArray(doc.tool) && doc.tool.length > 1 ? `- **Tools:** ${doc.tool.map(textOf).join(", ")}` : `- **Tool:** ${textOf(doc.tool) || "no tool"}`, + `- **Found by:** ${foundBy(doc)}`, + `- **Full search of our own:** ${doc.mode === "verify" ? "no" : "yes"}`, + `- **Findings:** ${findings.length ? LABELS.map((l) => `${byLabel.get(l.id) || 0} ${l.title}`).join(", ") : "none"}`, + `- **Outcomes:** ${byOutcome.size ? [...byOutcome].map(([k, n]) => `${n} ${k}`).join(", ") : "none"}`, + `- **Hidden by the keep list:** ${hidden}`, + ]; + for (const label of LABELS) { + const group = findings.filter((f) => f.label === label.id); + lines.push("", `## ${label.title}`, ""); + if (!group.length) { + lines.push("None."); + continue; + } + lines.push("| Item | Location | Source | Rule | Reason | Outcome |", "| --- | --- | --- | --- | --- | --- |"); + for (const f of group) { + const item = textOf(f.name) || (f.kind === "file" ? "(whole file)" : "(unnamed)"); + const location = Number.isInteger(f.line) ? `${f.file}:${f.line}` : f.file; + const reason = f.label === "warning" ? textOf(f.warningKind) || textOf(f.callers) : textOf(f.callers); + lines.push(`| ${[item, location, SOURCES[f.source] || textOf(f.source), textOf(f.rule) || "-", reason || "-", textOf(f.outcome) || "-"].map((v) => cell(v) || "-").join(" | ")} |`); + } + } + const notChecked = textOf(doc.notChecked); + const closing = { + complete: `This run was complete: every finding under ${scope === "." ? "the whole project" : `\`${scope}\``} was checked.`, + narrowed: `This run was narrowed, not complete: only ${scope === "." ? "part of the project" : `\`${scope}\``} was checked.${notChecked ? ` Not checked: ${notChecked}.` : ""}`, + stopped: `This run was stopped before it finished, not complete.${notChecked ? ` Not checked: ${notChecked}.` : ""}`, + }[doc.ranFrom]; + lines.push("", "---", "", closing, ""); + return lines.join("\n"); +} + +function cmdReport(argv) { + const [sub, ...rest] = argv; + if (sub !== "write") fail(EXIT.USAGE, sub ? "unknown-report-command" : "missing-report-command", sub ? `Unknown report command "${sub}".` : "report needs a command.", "Run report write --findings ."); + const args = parseArgs(rest, { booleans: ["dry-run", "replace"], values: ["root", "findings", "date"] }); + noPositionals(args, "report write"); + if (!args.findings) fail(EXIT.USAGE, "missing-findings", "report write needs --findings .", "Write the run's findings JSON to a file and pass it."); + if (args.date !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(args.date)) fail(EXIT.USAGE, "bad-date", `--date "${args.date}" is not YYYY-MM-DD.`, "Pass a date like 2026-08-03, or leave --date out for today."); + const root = projectRoot(args.root); + const doc = readFindings(args.findings); + const date = args.date || isoDate(); + const rel = `${REPORTS_REL}/DEAD-CODE-${date}.md`; + const file = path.join(root, rel); + if (fs.existsSync(file) && !args.replace) fail(EXIT.REFUSED, "report-exists", `${rel} already exists.`, "Ask the person whether to replace it, then pass --replace.", { path: rel }); + const text = reportMarkdown(doc, date); + if (args["dry-run"]) return out({ ok: true, dryRun: true, path: rel, preview: text.split("\n").slice(0, 14) }); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, text); + out({ ok: true, path: rel }); +} + +/* ------------------------------------------------------------- gitignore */ + +const REPORTS_LINE = `${REPORTS_REL}/`; + +/** git in root: { status, stdout }; status null when git could not start. */ +const git = (root, ...args) => { + const r = spawnSync("git", args, { cwd: root, encoding: "utf8", windowsHide: true }); + return { status: r.error ? null : r.status, stdout: r.stdout || "" }; +}; + +/** Whether the reports folder is ignored: { isGit, hasGitignore, ignored, line, file }. */ +function gitignoreState(root) { + const isGit = git(root, "rev-parse", "--is-inside-work-tree").stdout.trim() === "true"; + const rootIgnore = readText(path.join(root, ".gitignore")); + // The exact line: in the root .gitignore, or reports/ in the state folder's own .gitignore. + const lineIn = (text, wanted) => (text === null ? null : text.split(/\r?\n/).find((l) => wanted.includes(l.trim().replace(/^\//, "").replace(/\/?$/, "/"))) || null); + let line = lineIn(rootIgnore, [REPORTS_LINE]); + let file = line ? ".gitignore" : null; + if (!line) { + line = lineIn(readText(path.join(root, STATE_DIR, ".gitignore")), ["reports/"]); + if (line) file = `${STATE_DIR}/.gitignore`; + } + // Any other rule that covers the folder (a wider pattern) counts too. + const checked = isGit && git(root, "check-ignore", "-q", REPORTS_LINE).status === 0; + return { isGit, hasGitignore: rootIgnore !== null, ignored: Boolean(line) || checked, line: line ? line.trim() : null, file }; +} + +function cmdGitignoreCheck(argv) { + const args = parseArgs(argv, { values: ["root"] }); + noPositionals(args, "gitignore-check"); + out({ ok: true, ...gitignoreState(projectRoot(args.root)) }); +} + +/** Append the reports line to the root .gitignore for the first-use offer; never touches other lines. */ +function cmdGitignoreAdd(argv) { + const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root"] }); + noPositionals(args, "gitignore-add"); + const root = projectRoot(args.root); + const state = gitignoreState(root); + if (!state.isGit) fail(EXIT.REFUSED, "not-git", `${slash(root)} is not a git repository.`, "Skip the .gitignore offer: nothing here is committed."); + if (state.ignored) return out({ ok: true, added: false, already: true, line: state.line, file: state.file }); + const file = path.join(root, ".gitignore"); + const current = readText(file); + const nl = current === null ? "\n" : eol(current); + const text = current === null || current === "" ? `${REPORTS_LINE}${nl}` : `${current}${/\r?\n$/.test(current) ? "" : nl}${REPORTS_LINE}${nl}`; + if (args["dry-run"]) return out({ ok: true, dryRun: true, added: true, line: REPORTS_LINE, file: ".gitignore", created: current === null }); + fs.writeFileSync(file, text); + out({ ok: true, added: true, line: REPORTS_LINE, file: ".gitignore", created: current === null }); +} + +const COMMANDS = { + detect: cmdDetect, + run: cmdRun, + narrow: cmdNarrow, + keep: cmdKeep, + backup: cmdBackup, + restore: cmdRestore, + report: cmdReport, + "gitignore-check": cmdGitignoreCheck, + "gitignore-add": cmdGitignoreAdd, +}; + +async function main(argv) { + const [command, ...rest] = argv; + if (!command) fail(EXIT.USAGE, "missing-command", "Name a command.", `One of: ${Object.keys(COMMANDS).join(", ")}. Run with --help for usage.`); + const handler = COMMANDS[command]; + if (!handler) fail(EXIT.USAGE, "unknown-command", `Unknown command "${command}".`, `One of: ${Object.keys(COMMANDS).join(", ")}. Run with --help for usage.`); + await handler(rest); +} + +// Run as a script; imported (the tests import the readers), do nothing. +const isMain = (() => { + try { + return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url)); + } catch { + return false; + } +})(); +if (isMain) run(USAGE, main); diff --git a/src/plan2code-dead-code.md b/src/plan2code-dead-code.md new file mode 100644 index 0000000..a7e751b --- /dev/null +++ b/src/plan2code-dead-code.md @@ -0,0 +1,157 @@ +# 💀 DEAD CODE MODE + +Start all DEAD CODE MODE responses with '💀 [DEAD CODE]' + +## Role + +Finds unused code paths and dead code in the person's own project. Shows each finding with its evidence and a label that says how safe it is to remove, removes only the findings the person picks, then runs the project's tests and build. **Never commits, pushes or stages**, never installs an outside tool, and does no code review of its own (that is the Review skill's job). + +## Interface + +The FIRST thing you do, before anything else in this file, before running a script: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "/console.mjs" open --workflow dead-code` before reading (: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-dead-code/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read /console.md and /notes/dead-code.md. The start questions, the findings list, the checks, the report and the save offers all go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context. + +## Project Context + +Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything it says about slow suites or code reached by name. Dead Code still works without one, but the test map is what tells it which tests and build to run after a removal; without it the scripts read the project's config files, and the person confirms the commands. + +## Scripts + +`` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-dead-code/scripts/` globally). Run from the project root. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says. + +- `node "/dead-code.mjs" detect [--scope ]`: the dead-code tools the project already has (`tools`: `id`, `language`, `marker`, `available`, `command`, `format`), `languages` with file counts, `sourceFiles`, and `overLimit` (a very big project). +- `node "/dead-code.mjs" run --tool [--scope ]`: runs that tool with a timeout and prints `candidates` (`file`, `line`, `name`, `kind`, `rule`, `message`), or `unparsed: true` with the output's `tail`. +- `node "/dead-code.mjs" narrow --candidates `: `folders` ranked by candidate count. +- `node "/dead-code.mjs" keep list|filter|add|remove`: the shared keep list, `.plan2code-dead-code/keep.md`. `filter [--fresh]` reads candidates on stdin and prints `shown`, `hidden`, `kept` and `changed`; `add --file --reason` with `--name --line` for an item, and neither for a whole unused file; `remove --file --name`, plus `--hash` or `--line` when two rows share a name. +- `node "/dead-code.mjs" backup [--run ]` and `restore --run [--files ...] [--verify]`: copies outside the project and a checked put-back. +- `node "/dead-code.mjs" report write --findings `: saves `.plan2code-dead-code/reports/DEAD-CODE-.md`, only on a yes. +- `node "/dead-code.mjs" gitignore-check` and `gitignore-add`: whether `reports/` is ignored, and adding the line, only on a yes. +- `node "/test-map.mjs" read`: the project test map (`found`, `rows` of `area`, `paths`, `run`, `shared`, and `problems`). +- `node "/test-commands.mjs" discover`: the project's commands from its config files: `suite`, `runners` (`cmd`, `cwd`, `covers`), `checks` (`kind` lint, types or build, with `cmd`), `builtin`. +- `node "/run-check.mjs" --cmd --cwd --timeout --log `: runs one check and prints `outcome` (`passed`, `failed`, `timeout`, `not-started` with a `reason`), `exit`, `seconds` and `tail`. + +## References + +- `references/caller-search.md`: what to search besides the plain name, per language group. Read it before Step 4. +- `references/helper-strength.md`: helper strength and effort. + +## Rules + +- Follow `./AGENTS.md` when it exists. +- **Never** run `git commit`, `git push`, `git add` or `git stash`. Read-only git is fine. The changes stay unstaged for the person to look at. +- **Never install anything**: no `npm install`, `pip install`, `cargo install`, `go install` or download of a tool. A tool the project already has may be run. +- **Write only** code removals, `.plan2code-dead-code/keep.md`, and, on a yes, the saved report and the `.gitignore` line. +- **Nothing is removed before the person picks it.** Nothing is pre-ticked. +- **Silence is not proof.** A finding reaches Safe only when a tool listed it and the caller search agrees. +- **Never partial without saying so.** A narrowed or stopped run says what was and was not checked, and is never called complete. +- **Record honestly.** A check that did not run is never reported as passed. +- US English. No em dashes in any text you write (report, keep reasons, page text). Plain words: name the file, the item and the command. + +## Helpers + +When your tool can start helpers (subagents) and they are not switched off for this run (on the web console a `Subagents:` block says which, console-subagents.md): the caller search (Step 4), one helper per batch of candidates, each given `references/caller-search.md` and returning, per candidate, what it searched and what it found, never a label. Light strength, low effort, per references/helper-strength.md. Keep the labels, the Safe call, the removals, the checks and every question with you. No helpers? Do the same work yourself. + +## Process + +### Step 1: Start questions + +Run `detect` and `keep list` first, then ask on one card, answered together: + +1. **Method.** A tool counts only when its `language` has files in `detect`'s `languages`. Pick one available tool (`available: true`) per language group, preferring one the script reads (`format` other than `agent`) over one you read by hand. With a tool picked: use the project's tool or tools and verify their lists with a caller search (default), or also do a full search of our own. Say each tool used and its `marker`; with several groups each having a tool, one option names them all ("Knip and vulture, checked by a caller search"). A group with no available tool (say which and why) gets a search of our own (Step 3). When no group has one: skip this question and say the run is a search of our own, so every finding is Check first. +2. **Scope.** The whole project (default) or a folder the person names. A folder: run `detect --scope ` again and use its `overLimit` and `sourceFiles` from here on. +3. **Keep list.** When `keep list` has entries: say how many, and offer to use it (default) or do a fresh scan that ignores it. Leave this out when it has none. +4. **Size.** When `overLimit` is true: say the project has `sourceFiles` source files and that a narrow step may follow once the starting list is in (Step 2), and that picking a smaller folder skips it. + +The answers are final for the run. A this-branch-only mode is not offered yet. + +### Step 2: Scope and size + +The scope picks which findings are reported, never where callers are searched: the caller search always covers the whole project, so a folder run never calls something dead that another folder uses. + +When `overLimit` is true: run the tool (Step 3), write its `candidates` to a file in the session folder (`open` printed it; in the terminal, the OS temp folder) and run `narrow --candidates `. Ask the person to narrow first, listing the five `folders` with the most candidates, and offer the whole project with a plain warning that it takes longer and costs more. With no tool, list the five biggest top-level source folders instead. Once the person picks, keep only the candidates whose `file` is under the pick (or rerun `run --scope `), set the report's `scope` to it and put the rest in `notChecked`. Helpers split the work inside what the person picks. Whatever is chosen, the report says so: a narrowed run is `ranFrom: "narrowed"` with what was left out in `notChecked`, never complete. + +### Step 3: The starting list + +**With a tool:** `run --tool ` (add `--scope ` for a folder run), once per chosen tool. Merge their candidates into one list (the same `file`, `line` and `name` from two tools is one candidate); the merged list is what goes to `keep filter`. + +- `unparsed: true`: read the `tail` yourself, write the candidates by hand in the same shape, and say the tool's output was read by the agent, not the script. +- A tool that fails, times out or cannot start: report it as missing in one line and continue as a search of our own. +- With the full-search choice, also make your own list (below) and merge it: an item both found is source `both`. + +**With no tool, or none for a language in scope:** find candidates yourself: exports, functions, classes, methods and whole files that nothing references. Their source is `own`, every one stays Check first or Warning, and the report and the page say plainly that no tool confirmed them. + +Never install, `npm install`, `pip install` or fetch a tool to get a list. + +**The keep list, for every candidate.** Whatever the source (the script's `candidates`, ones you wrote from `tail`, the merged full search, or your own list), write the final list as one JSON array and pipe it to `keep filter` (`--fresh` when the person chose a fresh scan). Work on `shown`; the number of `hidden` entries is the hidden count. A shown candidate with `wasKept: true` was kept before but its code changed since: say so in its detail. A `kept` entry marked `gone` is offered for removal from the list in Step 8. + +### Step 4: Verify with a caller search + +Read `references/caller-search.md`. For each candidate, search the whole project for callers: the plain name, names inside strings, config files, tests, docs that act as config and generated glue, plus that language group's rules. Record what was found in `callers`. + +- **A caller found:** the item is live. Drop it from the list and count it ("12 dropped: a caller was found"). +- **No caller, and a tool listed it:** the tool and the search agree; Safe unless Step 5 says otherwise. +- **No caller, found only by our own search:** Check first. + +A tool's silence about an item is never proof that it is live or dead. On a big list, helpers search in batches (Helpers). + +### Step 5: Labels + +Every finding gets one label, with its reason: + +- **Safe to remove:** a tool listed it and the caller search found nothing. +- **Check first:** found by our own search only; listed by a tool that sees private scope only while the item is public (such a tool never vouches for an unused public item); or anything you are unsure of. +- **Warning:** always for these six kinds, with which one and why shown: + 1. called by name from a string or config + 2. a plugin or framework hook + 3. a public library export + 4. a CLI entry point or script + 5. a test helper + 6. code only tests call + +A Warning is never in the quick-removal list (the All Safe preset). The person may still remove one by picking it by hand. + +### Step 6: The findings page + +Post one `multi` item (`notes/dead-code.md` gives its shape): options grouped Safe, then Check first, then Warning, each option's `text` the item and its location (`name` in `file:line`) and its `detail` the label, the source (tool, own search or both), the tool's rule id and the reason (the six-kind reason for a Warning). Preset: `All Safe` (ticks the Safe group). Nothing is ticked to begin with: the console's `multi` cannot open ticked, so the preset is the quick pick. Above it say the tool or tools used, how many items the keep list hid (on request, list each with its reason) and how many were dropped for having a caller. In the terminal, the same as a numbered list in three groups; the person names numbers or says "all safe". + +Nothing picked → skip to Step 8. + +### Step 7: Removal and checks + +1. **Find the checks.** Run `test-map.mjs read`. With a map, every row's `run`, plus the `build` entries of `test-commands.mjs discover`'s `checks`. No map: `discover`; list its `suite`, `runners` and `checks` and confirm them on one card before anything runs; a correction replaces what was found. None at all: ask the person for the command. With nothing to run, say removal will be unchecked and continue only on the person's yes. The checks run project-wide, even on a folder run. +2. **Back up.** `backup `; keep its `run` id. +3. **Remove** the picked findings together: the item itself and anything that only existed for it in the same edit (its import line, a now-empty export list). A whole-file finding deletes the file. +4. **Check once.** Run every check through `run-check.mjs` (`--timeout 600` by default, longer when `AGENTS.md` says a suite is slow; `--log` in the session folder, or the OS temp folder), posting one `activity` line per check with `quietMinutes` sized to its timeout. +5. **All pass:** done; every pick's outcome is `removed`. +6. **Any fail** (any `outcome` other than `passed`: `failed`, `timeout` or `not-started`, with its `reason` or `tail` as the failure text): `restore --run `, then `restore --run --verify`. Never go on while it reports a mismatch: stop, say which files did not match, and leave the rest to the person. Run the checks once on the restored tree: if they still fail, the project's checks fail without any removal, so stop, mark every pick `skipped` with that reason, say so, and do not retry. Otherwise retry the picks one at a time: for each, `backup` the files it touches as a new run, remove it, run the checks; a pass keeps it, a fail restores that run and records `failed: ` as its outcome. A removal that depends on another (the second becomes unused only after the first goes) is retried with it as a pair. + +Nothing is staged or committed at any point. + +### Step 8: Report, keep list and finish + +**Report.** Always show it on the page (in the terminal, as a table): the headline says complete or narrowed (or stopped), the scope, the method and tool or tools, how many the keep list hid, how many were dropped, then each finding with its label, source, rule id, the reason for any Warning and its outcome (`removed`, `kept`, `skipped`, `failed: ...`), and whether removal was unchecked. + +Offer three things, each acted on only on a yes: + +- **Save the report.** Write the findings JSON (`scope`, `mode` of `verify`, `full` (also when any language group had no tool) or `own`, `tool` (an id, a list of ids when several ran, or null), `ranFrom`, `findings`, `hidden` as a number, `notChecked`) to the session folder, each finding `{ file, line, name, kind, source (tool, own or both), rule, label (safe, check or warning), warningKind (which of the six kinds, and why), callers, outcome }`, and run `report write --findings `. On first use, run `gitignore-check` and, when `ignored` is false, offer `gitignore-add`. +- **Keep findings.** For any finding the person keeps, ask the reason and run `keep add --file --name --line --reason` (a whole unused file: `keep add --file --reason`). It is hidden next run, shown as a count. +- **Take entries off.** List the keep list's entries with their reasons (the `gone` ones first) and run `keep remove --file --name` on the ones the person picks (a whole-file entry: `keep remove --file`). On exit 2 `ambiguous-entry`, show the rows it lists (each hash with its reason) and rerun with the `--hash` the person picks. + +## Abort + +On "stop", "cancel" or similar during a run: confirm. With removals on disk and the checks not yet passed, `restore --run ` and `--verify` first, and say so. Then show the report as far as it got with `ranFrom: "stopped"` and what was not checked, offer to save it, and stop. Never call a stopped run complete. + +## Session End + +Work summary: the scope and whether it was narrowed, the method and tool or tools, how many findings by label, how many were hidden by the keep list or dropped for a caller, what was removed, put back (with why) or left, whether removal was checked, and any file written (the report, `keep.md`, `.gitignore`). + +**Next step**, as the closing line: "Review the unstaged changes and commit them, with `keep.md`, using `/plan2code-git`." Nothing removed and no keep-list change: "Nothing to commit." + +On the console, post `finish` with the counts removed, kept and failed in `headline`, `"dashboard": true`, and `command` `/plan2code-git` for the unstaged changes and the keep list when something was removed or `keep.md` changed; otherwise leave `command` out, except a stop before anything was removed, where `command` is `/plan2code-dead-code`. Never a `commit` field: the Git skill commits. + +``` +⋅ + ╭───╮ + ╲│ ★ │╱ + │ ◡ │ Swept clean! + ╰┬─┬╯ +``` diff --git a/src/plan2code.md b/src/plan2code.md index ecfb517..7cc500e 100644 --- a/src/plan2code.md +++ b/src/plan2code.md @@ -69,6 +69,7 @@ Ground truth for menu notes and Ask-tab answers. For anything beyond this table, | diagnose | the bug, the codebase, `references/building-habits.md` | `DIAGNOSIS-.md`; no code changes | | pr-prep | git diff and status, the `AGENTS.md` test map, the project's config files, the PR template | the page report and description; `PR-READINESS-.md` on a yes; the `AGENTS.md` test map on a yes; no commits, no push | | test | the codebase, the `AGENTS.md` test map, nearby tests, coverage output when offered | new test files; the `AGENTS.md` test map on a yes; `PLAN-DRAFT-.md` when escalated; no source changes | +| dead-code | the project's source, its own dead-code tool's output, the `AGENTS.md` test map, `.plan2code-dead-code/keep.md` | code removals the person picks; `.plan2code-dead-code/keep.md`; `.plan2code-dead-code/reports/DEAD-CODE-.md` and the `.gitignore` line on a yes; no commits, no staging | ## A pick arrives @@ -105,6 +106,7 @@ If `skill` is not in the table below, say so on the page and stay the dashboard. | plan2code-git | git | | plan2code-changelog | changelog | | plan2code-xray | xray | | plan2code-diagnose | diagnose | | plan2code-pr-prep | pr-prep | | plan2code-test | test | +| plan2code-dead-code | dead-code | | | | ## A pick-up arrives diff --git a/src/shared-references/helper-strength.md b/src/shared-references/helper-strength.md index 429876d..2fce91e 100644 --- a/src/shared-references/helper-strength.md +++ b/src/shared-references/helper-strength.md @@ -1,5 +1,5 @@ # Helper Strength -> Shared by the skills that start helpers (subagents): Init, Init Update, Pathfinder, Plan, Revise Plan, Document, Quick Task, Implement, Implement + Review, Review, Finalize, X-ray and Diagnose. Read it when you first start a helper in a session. Never invoked as a skill. +> Shared by the skills that start helpers (subagents): Init, Init Update, Pathfinder, Plan, Revise Plan, Document, Quick Task, Implement, Implement + Review, Review, Finalize, X-ray, Diagnose, PR Prep, Test and Dead Code. Read it when you first start a helper in a session. Never invoked as a skill. ## The words diff --git a/src/web-console/console-meter.md b/src/web-console/console-meter.md index 3360c8f..5e38dd4 100644 --- a/src/web-console/console-meter.md +++ b/src/web-console/console-meter.md @@ -6,7 +6,7 @@ The meter is advice and never blocks. The console scores these launches itself w Per-unit work is yours: `{"run":{"event":"implement-phase","id":"phase-2","tasks":9}}`, one `run` per post, never reaching the page state. -- `event`: `pathfinder-chart`, `pathfinder-question` (scores nothing now), `pathfinder-research`, `plan`, `revise-plan`, `document`, `implement-phase`, `implement-review-phase`, `review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`, `pr-prep`, `test`, `git-commits`, `git-conflict`. An unknown event is exit 3. Post only the events your notes name: a launch the console scores already has its points. +- `event`: `pathfinder-chart`, `pathfinder-question` (scores nothing now), `pathfinder-research`, `plan`, `revise-plan`, `document`, `implement-phase`, `implement-review-phase`, `review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`, `pr-prep`, `test`, `dead-code`, `git-commits`, `git-conflict`. An unknown event is exit 3. Post only the events your notes name: a launch the console scores already has its points. - `id`: the unit (a question's slug, `phase-N`, `map`), non-empty. The same id in the same skill run is ignored. - `tasks`: only with `implement-phase` and `implement-review-phase`; the tasks completed (`[x]`, not blocked), a whole number 1 to 999. A phase scores one point per 3 tasks rounded up (Implement + Review one more for the review); without it, a flat 2 (or 3). It takes over the count from `headline.cleared`, never adding to it. - `commits`: only with `git-commits`; commits made, 1 to 999, one point per 2 rounded down. diff --git a/src/web-console/console-subagents.md b/src/web-console/console-subagents.md index 9ebb9f5..40678aa 100644 --- a/src/web-console/console-subagents.md +++ b/src/web-console/console-subagents.md @@ -1,6 +1,6 @@ # Helpers (Subagents) -The console points here when a `Subagents:` block reaches you. On the skills that offer it (`init`, `init-update`, `pathfinder`, `plan`, `revise-plan`, `document`, `implement`, `implement-review`, `quick-task`, `review`, `finalize`, `xray`, `diagnose`, `pr-prep`, `test`) the person turns helpers on or off from the top bar's Subagents button, per project and skill. It reaches you as a standing instruction, only when it changes. +The console points here when a `Subagents:` block reaches you. On the skills that offer it (`init`, `init-update`, `pathfinder`, `plan`, `revise-plan`, `document`, `implement`, `implement-review`, `quick-task`, `review`, `finalize`, `xray`, `diagnose`, `pr-prep`, `test`, `dead-code`) the person turns helpers on or off from the top bar's Subagents button, per project and skill. It reaches you as a standing instruction, only when it changes. ## What arrives diff --git a/src/web-console/console.md b/src/web-console/console.md index ea29379..2f11d45 100644 --- a/src/web-console/console.md +++ b/src/web-console/console.md @@ -6,7 +6,7 @@ A local page where the person answers your questions, reads your drafts and appr ## Start -`node "" open --workflow ` (add `--spec specs/` when known). `` is one of `dashboard`, `init`, `init-update`, `pathfinder`, `quick-task`, `plan`, `revise-plan`, `document`, `implement`, `implement-review`, `review`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`, `pr-prep`, `test`. Launched from the dashboard? The session is open: run the `resume` command the launch carried instead. +`node "" open --workflow ` (add `--spec specs/` when known). `` is one of `dashboard`, `init`, `init-update`, `pathfinder`, `quick-task`, `plan`, `revise-plan`, `document`, `implement`, `implement-review`, `review`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`, `pr-prep`, `test`, `dead-code`. Launched from the dashboard? The session is open: run the `resume` command the launch carried instead. Keep `sid`: every later command takes `--session `. `open` failing: carry on in the terminal. When `open` adds `remote` and a `note`, give the link, ask whether it opened, and move to the terminal if not. Tell the person the link (with `"inApp":true`, never print it: only how many questions are waiting) and end every terminal message with the latest `terminalLine`, verbatim. diff --git a/src/web-console/notes/dead-code.md b/src/web-console/notes/dead-code.md new file mode 100644 index 0000000..217b38b --- /dev/null +++ b/src/web-console/notes/dead-code.md @@ -0,0 +1,37 @@ +# Dead Code + +## Start questions + +One `--wait` batch, after `detect` and `keep list`. Only the first card is required; leave out any the prompt says to skip (no method card with no tool, no keep card with an empty list): + +```jsonc +{"title":"Clear out dead code","headline":{"stage":"Start","cleared":0,"total":5},"items":[{"id":"method","kind":"choice","title":"How to look","allowOther":false,"body":"This project has Knip (`knip.json`).","options":[{"text":"Knip, checked by a caller search","recommended":true},{"text":"Knip plus a full search of my own","detail":"Slower; finds what Knip cannot see."}]},{"id":"scope","kind":"choice","title":"Where to look","required":false,"body":"Callers are always searched across the whole project.","options":[{"text":"The whole project","recommended":true},{"text":"One folder","detail":"Name it in the note."}]},{"id":"keep","kind":"choice","title":"The keep list","required":false,"allowOther":false,"body":"3 findings were kept on earlier runs.","options":[{"text":"Hide them again","recommended":true},{"text":"A fresh scan that ignores them"}]}]} +``` + +## Narrow first + +Only when `overLimit` is true. One `choice`, `--wait`: the five folders from `narrow` (or the biggest top-level folders with no tool), each with its count in `detail`, then the whole project with the time and cost warning in its `detail`. + +## The findings + +One `multi`, `--wait`, `required:false`. Options in three groups, in this order: Safe, Check first, Warning. Each option's `text` is `name` in `file:line`; its `detail` starts with the label, then the source (tool, own search or both), the rule id and the reason (the six-kind reason for a Warning). The `body` gives each group's count, how many the keep list hid and how many were dropped for a caller. Nothing starts ticked: the quick pick is the preset `All Safe` (the Safe group's keys). Leave out a preset with no keys (no Safe findings, or a `None`): the page drops it, and a pressed preset clears when pressed again. + +```jsonc +{"headline":{"stage":"Findings","cleared":2},"items":[{"id":"findings","kind":"multi","title":"What to remove","required":false,"body":"- Safe to remove: 2\n- Check first: 1\n- Warning: 1\n\n4 hidden by the keep list; 9 dropped: a caller was found. Nothing is removed until you send.","options":[{"k":"1","text":"formatDate in src/dates.js:14","detail":"Safe. Knip (exports): no caller found."},{"k":"2","text":"src/old/legacy.js","detail":"Safe. Knip (files): no caller found."},{"k":"3","text":"parseRow in src/csv.js:40","detail":"Check first. Own search only."},{"k":"4","text":"onLoad in src/plugin.js:8","detail":"Warning. A framework hook: the host calls it by name."}],"presets":[{"label":"All Safe","ks":["1","2"]}]}]} +``` + +## Checks + +With no test map: one `confirm` listing each command and the folder it runs in, `--wait`, `"yesLabel":"Use these","noLabel":"Not right"`, before anything runs. A "Not right" note replaces what was found; with none, ask for the commands as a `text` card. + +One progress post per check, no `--wait`, its `activity` naming the check and `quietMinutes` sized to its timeout (600 s is 10 minutes, plus a margin). Run the `chat` check between checks, as a build does. + +## The report and the offers + +Doc `report`: one `md` block, the headline first (Complete, Narrowed or Stopped), then scope, method and tools, the hidden and dropped counts, and the findings table with each outcome. Then each offer as a `confirm`, `--wait`, `"doc":"report"`: "Save the report" (naming `.plan2code-dead-code/reports/DEAD-CODE-.md`), "Keep these findings" (the reasons asked as a `text` card after a yes), and on first save ".gitignore line". + +Helpers are reported as `helpers`, each `done` or `failed` before the findings page goes up. Labels, picks and questions stay with you. + +## The finish + +`headline` the counts removed, kept and failed; `body` the summary and any file written; `"dashboard":true`; `command` `/plan2code-git` when something was removed or `keep.md` changed, otherwise none; never `commit`. A stop before removal: `body` says nothing was removed, `"command":"/plan2code-dead-code"`. diff --git a/src/web-console/public/palette.js b/src/web-console/public/palette.js index e522644..94651d0 100644 --- a/src/web-console/public/palette.js +++ b/src/web-console/public/palette.js @@ -259,13 +259,13 @@ export const PICKABLE_SOUNDS = ["startSkill", "sessionStart", "skillReady", "ses // The file each pickable cue plays until a person picks another. export const DEFAULT_SOUND_FILE = { - startSkill: "sound-01", - sessionStart: "sound-02", - sessionEnd: "sound-02", - question: "sound-03", - skillReady: "sound-03", - chatReply: "sound-03", - newTab: "sound-04", + startSkill: "sound-14", + sessionStart: "sound-07", + sessionEnd: "sound-15", + question: "sound-14", + skillReady: "sound-16", + chatReply: "sound-06", + newTab: "sound-05", }; // Every moment the page makes a noise, each switchable on its own in User diff --git a/src/web-console/public/skills.js b/src/web-console/public/skills.js index 6a2793b..f6839dd 100644 --- a/src/web-console/public/skills.js +++ b/src/web-console/public/skills.js @@ -426,6 +426,28 @@ export const SKILLS = Object.freeze([ "When parts of the code have no tests. Test asks where to look (the branch's changes, one folder or the whole project) and finds the files no test covers, and offers a real coverage run when the project already has a coverage tool. It shows a plan that opens with how this project writes tests, so the new tests match the old ones, then writes and runs unit and integration tests. It never changes source code: a test that finds a real bug is handed to Diagnose.", }, }), + skill({ + skill: "plan2code-dead-code", + workflow: "dead-code", + label: "Dead code", + name: "Dead Code", + pose: "dead-code", + builds: false, phased: false, metered: true, templates: false, + weight: 1, started: "Dead Code started", ran: "Dead Code run", resume: null, + subagents: "Use helpers for the caller search, one batch of candidates each, returning what each searched and found, never a label. Keep the labels, the Safe call, the removals, the checks and every question with you. Light strength, low effort.", + states: "any", + greyed: null, + card: { + group: "extra", + chip: "Utility", + title: "Clear out dead code", + icon: "dead-code", + blurb: "Finds code nothing uses, says how safe each piece is to remove, and removes only what you pick.", + help: "Finds unused code, labels each piece Safe, Check first or Warning, removes only what you pick, then runs the tests and build.", + about: + "For code nothing calls anymore. Dead Code uses the project's own dead-code tool when there is one (Knip, vulture, cargo check and others), or searches by itself when there is not, then checks every item for callers across the whole project. Each one gets a label: Safe to remove, Check first or Warning, with the reason. It removes only what you pick, runs the tests and build, and puts back anything that breaks them. It never commits and never installs anything.", + }, + }), skill({ skill: "plan2code-changelog", workflow: "changelog", diff --git a/src/web-console/public/styles/poses.css b/src/web-console/public/styles/poses.css index 86aff8d..67238ea 100644 --- a/src/web-console/public/styles/poses.css +++ b/src/web-console/public/styles/poses.css @@ -473,6 +473,21 @@ 60%, 85% { transform: translate(4px, -4px); } } +/* Dead code -- the skull's jaw chatters a few times, then rests; his star + glances over at it while it talks. */ +.pose .dd-bone { fill: var(--panel-2); stroke: var(--ink-2); stroke-width: 4; stroke-linejoin: round; } +.pose .dd-jaw { animation: dd-jaw 3.6s ease-in-out infinite; } +@keyframes dd-jaw { + 0%, 10%, 60%, 100% { transform: translateY(0); } + 18%, 34%, 50% { transform: translateY(4px); } + 26%, 42% { transform: translateY(1px); } +} +.pose .dd-look { animation: dd-look 3.6s ease-in-out infinite; } +@keyframes dd-look { + 0%, 70%, 100% { transform: translate(2px, 0); } + 14%, 56% { transform: translate(5px, -2px); } +} + @media (max-width: 720px) { .dash { padding-top: 0; } .launch-stage { height: 140px; }