Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be31f6af89 | ||
|
|
7a4b7c6db8 | ||
|
|
086c735c65 | ||
|
|
d4adb53a3a | ||
|
|
50acdc8216 | ||
|
|
2075d235d8 | ||
|
|
452d8e3895 | ||
|
|
d32925cccf | ||
|
|
f8b54ef708 | ||
|
|
a19dc6c5df | ||
|
|
124beb46db | ||
|
|
1121157938 | ||
|
|
e3aba0a637 | ||
|
|
3edb4468a8 | ||
|
|
699a827cae | ||
|
|
765e374584 | ||
|
|
2ab57d9a7e | ||
|
|
17dffac1ea | ||
|
|
36843e4bc9 | ||
|
|
33a0dbd34a | ||
|
|
80ae3decdd | ||
|
|
caef9a0ee3 | ||
|
|
72c827dddf | ||
|
|
498e09bb15 | ||
|
|
68d1f82a2e | ||
|
|
fdf43b197f |
No files matched your search
@@ -15,10 +15,13 @@ plan2code/
|
||||
│ │ ├── resolve.md # Per-type resolution + graduating the fog
|
||||
│ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff
|
||||
│ │ └── trail.md # Every-response map visual + pathed resume command
|
||||
│ ├── shared-references/ # Reference files shared across skills
|
||||
│ │ └── building-habits.md # Find the cause, test first, pin behaviour (quick-task, implement, implement-review)
|
||||
│ ├── plan2code-review-references/ # Reference files for review skill
|
||||
│ │ ├── verification-protocol.md # Deep verification + confidence calibration
|
||||
│ │ ├── dimensions.md # 11 dimensions with detailed checklists
|
||||
│ │ ├── false-positives.md # Known false-positive patterns
|
||||
│ │ ├── reviewer-brief.md # Fill-in brief for the one fresh helper that runs the analysis
|
||||
│ │ └── session-end.md # Next-step routing at review session end
|
||||
│ ├── plan2code-init-update-references/ # Reference files for init-update skill
|
||||
│ │ └── ai-agent-file-sync.md # Step 7: replace AI configs with AGENTS.md refs
|
||||
@@ -41,16 +44,19 @@ plan2code/
|
||||
│ └── plan2code.ico # Desktop shortcut icon (Windows)
|
||||
├── src/web-console/ # Local browser UI bundled into every skill (Node.js, zero deps, no build)
|
||||
│ ├── console.mjs # CLI the agent drives: open, post, wait, chat, keep, status, stop, help
|
||||
│ ├── server.mjs, lib.mjs, picker.mjs
|
||||
│ ├── server.mjs, routes.mjs, static.mjs, cmd-*.mjs, picker.mjs, and the by-job files (files, sessions, patches, scan, inbox, workspace, settings)
|
||||
│ ├── console.md, console-*.md, notes/, building*.md # Agent-facing contract (console.md read once, the rest on demand)
|
||||
│ └── public/ # Page assets served to the browser
|
||||
├── scripts/ # Development scripts
|
||||
│ ├── bench-web-console.mjs # Start-path timing
|
||||
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs puppeteer-core)
|
||||
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs a local Chrome or Edge, through `playwright-core`)
|
||||
│ ├── browser.mjs # The one place a browser is launched (Chrome, then Edge, through `playwright-core`; `PLAN2CODE_TEST_BROWSER` forces one); page tests, the screenshots and the bench use it
|
||||
│ ├── css-snapshot.mjs # Dev-only: every element's computed style on every screen, both themes; take one before a stylesheet move and `--compare` after
|
||||
│ ├── vendor-codemirror.mjs # Dev-only: bundles the pinned CodeMirror 6 packages with esbuild into `public/vendor/codemirror.esm.js` (installed in a temp folder from `vendor-codemirror-lock.json`, never in the repo)
|
||||
│ ├── check-skill-table.mjs # src/plan2code.md "What each skill reads and writes" table vs each skill's prompt and references
|
||||
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
|
||||
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
|
||||
│ ├── test-web-console-*.mjs, web-console-test-helpers.mjs # Web console suites, split by area, and their shared setup
|
||||
│ ├── test-web-console-*.mjs, web-console-test-helpers.mjs # Web console suites, split by area (the page tests are `-page-*`, the source shape `-shape`), and their shared setup
|
||||
│ ├── test-launcher.mjs, test-getting-started.mjs # Launcher suite; newcomer docs kept in step
|
||||
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, test-git-repo.mjs, skill-script-helpers.mjs, fixture-helpers.mjs # Skill script suites and fixtures
|
||||
│ └── validate-char-count.js # Pre-commit character count validator
|
||||
@@ -102,9 +108,11 @@ plan2code/
|
||||
| `plan2code-2-document.md` | 2 | Create implementation specs |
|
||||
| `plan2code-3-implement.md` | 3 | Execute implementation (phase by phase) |
|
||||
| `plan2code-3-implement-review.md` | 3 | Execute one phase, run focused review and fixes, then request approval |
|
||||
| `plan2code-review.md` | review | Post-implementation comprehensive review |
|
||||
| `plan2code-review.md` | review | Post-implementation comprehensive review, analysed by one fresh helper when the tool has one (verified in session; the report says who reviewed) |
|
||||
| `plan2code-4-finalize.md` | 4 | Validate, summarize, feedback, archive (steps 1–7, +optional 6.5) |
|
||||
| `plan2code-handoff.md` | handoff | Compact the conversation into a self-contained handoff document for a fresh session |
|
||||
| `plan2code-xray.md` | xray | Explain how and why an area works (files, commits, PRs via `gh` when present), or rank the rough spots worth fixing into `ARCHITECTURE-BRIEF-<date>.md` for Pathfinder or Plan; never edits code |
|
||||
| `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/<bug-name>/DIAGNOSIS-<YYYYMMDD>.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-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 |
|
||||
|
||||
@@ -124,7 +132,7 @@ Examples:
|
||||
|
||||
Some workflows use companion reference files for depth that does not need to load on every invocation. The orchestrator (main workflow file) loads them via `Read` directives during execution.
|
||||
|
||||
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`)
|
||||
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`). A file several skills read lives in `src/shared-references/` instead and ships to each through `additionalReferences` (e.g., `building-habits.md` into Quick Task, Implement and Implement + Review).
|
||||
|
||||
**How the installer handles them:** the directory is copied verbatim to `skills/<skill-name>/references/`, so `Read references/<file>.md` resolves consistently for every agent. There is one output format, with no flat-file sibling directory or path rewrite.
|
||||
|
||||
@@ -143,14 +151,14 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
|
||||
|
||||
| Script | Skills | Does |
|
||||
|---|---|---|
|
||||
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff | `list` / `status` (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `metrics` / `mark` / `archive`. Imports `scanProject()` from the bundled `web-console/lib.mjs`, so the dashboard and the skills share one spec classifier |
|
||||
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff | `list` / `status` (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `metrics` / `mark` / `archive`. Imports `scanProject()` from the bundled `web-console/scan.mjs`, so the dashboard and the skills share one spec classifier |
|
||||
| `commit-msg.mjs` | implement(-review), review, quick-task, finalize, init-update, git | The `<subject>` / `AI Assisted` commit command (two `-m` flags), with optional `git add` |
|
||||
| `review-scope.mjs` | review, implement(-review), quick-task | Review Mode's git fallback: files, lines, doc share, base branch |
|
||||
| `agents-md.mjs` | init, init-update | AGENTS.md structure, budget, orphans, broken links, always-inline sections |
|
||||
| `agent-files.mjs` | init, init-update | Detect and replace other agents' config files with AGENTS.md pointers |
|
||||
| `pathfinder.mjs` (own) | 0-pathfinder | `reconcile`, `frontier`, `claim`, `resolve`, `rule-out`, `trail`, `gate`, `lint`, `brief-data` |
|
||||
| `feedback-payload.mjs` (own) | 4-finalize | STEP 6.5's payload (real sha256 prompt hashes) and the gh / browser / print submission tiers |
|
||||
| `handoff-path.mjs` (own) | handoff | Timestamped path, OS temp dir, git ignore check |
|
||||
| `xray.mjs` (own) | xray | `hotspots` (churn, files changed together, often-changed files with no test, from `git log` over a capped window) and `history <path>` (commits following renames, a blame summary, PR titles and first paragraphs through `gh` when signed in, and which sources were used). Read-only |
|
||||
| `changelog-state.mjs` (own) | changelog | `state`, `bump`, `set-package-version`: the default branch's version, whether the branch's entry can be extended (not released, not on another branch), the file's heading style, the gap since the entry was last touched; only `set-package-version` writes, and only the version field |
|
||||
| `git.mjs` (own) | git | `state`, `plan`, `branch-check`, `init-check`, `delete-check`, `cleanup-list`, `conflicts`, `pr-url`, `classify-error`: the repo snapshot, each action's exact command and confirm text (shared by the terminal and the board), branch-name, delete, cleanup and git init checks, a stopped rebase's conflicts, the pull-request link and git's errors sorted into kinds with a next step. Read-only: the agent runs every command it prints, and `guard()` refuses force push, hook skipping, amend, remote delete and blanket add |
|
||||
|
||||
@@ -171,93 +179,161 @@ Do not run `skills add` against the repository root: recursive discovery also fi
|
||||
|
||||
## Web Console
|
||||
|
||||
Optional local browser UI shipped with **every** skill. Source lives in `src/web-console/` and is fanned into each skill by an `additionalReferences: [{ source: 'web-console', target: 'web-console' }]` entry in `SOURCE_PROMPTS`, landing at `skills/<skill>/references/web-console/`. The bare `plan2code` skill is the hub: it opens the console as `--workflow dashboard`, the page draws the skill menu itself (from `SKILL_CATALOG` in `public/answers.js`, kept in sync with the install set by a test), and a card click reaches the agent as a `{ "i": "__launch", "skill": ..., "workflow": ... }` send — the dashboard then **resumes its own session** under the launched skill's workflow (`open --resume <sid> --workflow <w>` restates `workflow`/`title`/`specDir` on the live server) and runs that skill's file. `plan2code-review` now has a console of its own AND still runs inside builds on the page (a `review` verdict on Implementation's sign-off card, or the **Review it now** button on a finished quick task), so `plan2code-3-implement` and `plan2code-quick-task` also carry `review.md` and the review references, the same way `implement-review` does. The list of skills with a console is duplicated as `CONSOLE_WORKFLOWS` in `public/answers.js` (it decides whether a copied hand-off asks the next session for the console); a test fails if the two disagree.
|
||||
Optional local browser UI shipped with **every** skill. Source lives in `src/web-console/` and is fanned into each skill by an `additionalReferences: [{ source: 'web-console', target: 'web-console' }]` entry in `SOURCE_PROMPTS`, landing at `skills/<skill>/references/web-console/`. The bare `plan2code` skill is the hub: it opens the console as `--workflow dashboard`, the page draws the skill menu itself (from each `SKILLS` entry's `card` in `public/skills.js`, through `SKILL_CATALOG` in `public/answers.js`, kept in sync with the install set by a test), and a card click reaches the agent as a `{ "i": "__launch", "skill": ..., "workflow": ... }` send — the dashboard then **resumes its own session** under the launched skill's workflow (`open --resume <sid> --workflow <w>` restates `workflow`/`title`/`specDir` on the live server) and runs that skill's file. `plan2code-review` now has a console of its own AND still runs inside builds on the page (a `review` verdict on Implementation's sign-off card, or the **Review it now** button on a finished quick task), so `plan2code-3-implement` and `plan2code-quick-task` also carry `review.md` and the review references, the same way `implement-review` does. `CONSOLE_WORKFLOWS` in `public/answers.js`, built from the same `SKILLS` list, decides whether a copied hand-off asks the next session for the console.
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`; `help <topic>` prints one contract file, `help topics` lists them). `post --wait <N>` posts and waits in one command |
|
||||
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `delete-spec`, `handoff new`, `delete-handoff` (both on `handoffs.mjs`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`; `help <topic>` prints one contract file, `help topics` lists them). `post --wait <N>` posts and waits in one command |
|
||||
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
|
||||
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()`; plus `cleanupFindings()` / `removeCleanup()` for User Preferences → Cleanup |
|
||||
| `public/` | `index.html`, `app.js`, `answers.js`, `labels.js`, `boot.js`, `chat.js`, `help.js`, `starters.js`, `workspace.js`, `meter.js`, `subagents.js`, `mentions.js`, `favicon.js`, `git-board.js`, `pr-url.js`, `app.css`, `render.js`, `palette.js`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server and the tests import `answers.js`, `palette.js`, `labels.js`, `boot.js`, `chat.js`, `help.js` and `starters.js`) parses them as ES modules without a reparse warning |
|
||||
| `public/` (other files) | `index.html`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server and the tests import the pure modules) parses them as ES modules without a reparse warning. The stylesheet is the files in `public/styles/`, joined by the server into the one `/app.css` the page asks for |
|
||||
| `cmd-chat.mjs` | the `chat` command: hand over Quick questions now, never waiting |
|
||||
| `cmd-help.mjs` | the `help` command: the CLI's usage and the contract's topic files; the usage's workflow list and its build sessions come from `WORKFLOWS` and `isBuild()` in `skills.js` |
|
||||
| `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser; refuses a `--workflow` that `isWorkflow()` does not know (exit 2, naming the valid ones), and asks `startsClean()` (`public/hops.js`) whether a resume blanks the page |
|
||||
| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent |
|
||||
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does |
|
||||
| `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share |
|
||||
| `inbox.mjs` | the Quick question chat's inbox beside the card slot |
|
||||
| `patches.mjs` | checking and merging an agent's patch into the session state: `validate()` (the house rules; allows `templates` only as `"idea"` on a `text` item, anything else exits 3), the patch merge, `resolveDocFiles()` and `applyPatch()` |
|
||||
| `routes.mjs` | every URL the page can call, in one ordered list (`ROUTES`, walked by `handle()`); `server.mjs` hands each request to it |
|
||||
| `scan.mjs` | what the dashboard knows about the repo: `scanProject()`, `classifySpec()` (a folder's files to a spec state), `TASK_LINE_RE` (re-exported from `spec-files.mjs`) and `removeSpec()` |
|
||||
| `sessions.mjs` | a session's roots and handle files (`repoRoots()`, `healthOk()`, `attachmentName()`: the kept-file name `<slug>-<id8>.<ext>`, the same upload always gets the same name, `readOverview()`) and the console folder's housekeeping: the three sweeps `open` runs fire-and-forget after it prints (`sweepUploads()`, `staleSessions()` / `removeSessions()`, `staleScratch()` / `removeScratch()`) and `cleanupFindings()` / `removeCleanup()` for User Preferences → Cleanup |
|
||||
| `settings.mjs` | the person's saved console settings: Subagents and pull-request hosts |
|
||||
| `spec-files.mjs` | no imports: how a spec's markdown files are read, `MARKERS`, `TASK_LINE_RE`, `TASK_ID_RE`, `CHECKBOX_RE`, `STATUS_RE`, `statusOf()` and `countTasks()`; shared by `scan.mjs`, `patches.mjs` and `src/skill-scripts/specs.mjs` (through `consoleModule()`) |
|
||||
| `static.mjs` | serving the page's own files: `SERVABLE` (the allow-list), `TYPES`, caching and ETags, the accent colors, and `CSS_ORDER` + `joinedStyles()`, the one place the cascade order is stated |
|
||||
| `workspace.mjs` | the session's extra folders, and the folders remembered per project and spec |
|
||||
| `public/app.js` | the page's entry and the only page file that starts anything: the start-up block. `index.html` loads it; it imports `screens/core.js` and the screens beside it |
|
||||
| `public/doc-files.js` | a document as the page shows it, and as a file: blocks, Markdown and HTML download |
|
||||
| `public/hops.js` | no imports: the hop rule, `startsClean(from, to)`, which says whether a hop from one workflow to another starts the new skill on a clean page (to or from the dashboard, into Git, or from one skill into another off a finished screen, but never out of Git or into Review); shared by `cmd-open.mjs`, `server.mjs` (its Ask reset) and `screens/core.js` |
|
||||
| `public/looks.js` | how the page looks and sounds: the saved looks, their sync, and the preferences dialog's swatches |
|
||||
| `public/mention-box.js` | the @name suggestions popover under a text box |
|
||||
| `public/net.js` | the page talking to its own server |
|
||||
| `public/palette.js` | the highlight colors, the sound events and the card widths, as data (importable by Node so a test can check every shade in both themes) |
|
||||
| `public/render.js` | Markdown to DOM, safely: no HTML string is ever produced, only nodes built with `createElement` and `textContent`; also the shared page helpers (`el`, `md`, `copyButton`, `lightDismiss`) |
|
||||
| `public/selectors.js` | what the page reads off its state: the questions, the finish, the scan, who has the ball |
|
||||
| `public/send-state.js` | whether Send is available, and what its button says |
|
||||
| `public/skills.js` | the skill list: every per-skill fact the console uses (card, order, start pose, launch scoring, subagent opt-in, which spec states light its card), data only, imported by the page and by Node; the older tables (`SKILL_CATALOG`, `START_POSES`, `CONSOLE_WORKFLOWS` and the rest, in `answers.js`) are lookups on it. Each entry also carries `weight` (what its launch and `run` score on the meter, or null), `started` and `ran` (the meter's labels for them, or null), `resume` (`"overview"`, `"folder"` or null: what the resume command takes after the skill's command) and an optional `card.help` (Help's line for the card when it differs from `blurb`). `WORKFLOWS` (every entry's workflow, in order) and `isWorkflow()` are what the CLI checks a `--workflow` against. The meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS`, `resumeCommand()`, Help's card list and `cmd-help`'s workflow list are all derived from it, so a new skill is one entry here, not an edit to each of those |
|
||||
| `public/sound.js` | the sound cues: which plays, one at a time, held until the first click |
|
||||
| `public/spec-states.js` | the spec states (`diagnosed`, `fixed`, `exploring`, `mapped`, `planned`, `documented`, `building`, `built`, `unrecognized`): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in `skills.js`, how a folder maps to a state in `classifySpec()` in `scan.mjs` |
|
||||
| `public/state.js` | the page's shared state (`page.S` the server's truth, `page.local` what is staged) and the `redraw()` / save hooks every screen calls; defines only |
|
||||
| `public/uploads.js` | pictures and documents attached to a note: chips, trays, re-encoding, upload, retry |
|
||||
| `public/screens/ask.js` | the Ask chat, the Subagents tab, and attaching files to notes |
|
||||
| `public/screens/cards.js` | question cards: every kind, the pager, settled and in-flight records |
|
||||
| `public/screens/cleanup.js` | User Preferences, Cleanup tab |
|
||||
| `public/screens/core.js` | the core every screen sits inside: connection, the render loop, the page chrome and Send; the only file that imports the screens, and only `app.js` imports it |
|
||||
| `public/screens/dashboard.js` | the dashboard: cards, the spec picker, handoff chips, delete, and the first-open wake-up |
|
||||
| `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button |
|
||||
| `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home |
|
||||
| `public/screens/git-host.js` | hosts the git board: tabs, panels and what each click sends |
|
||||
| `public/screens/help-dialog.js` | the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js) |
|
||||
| `public/screens/looks.js` | User Preferences: looks, sounds and the launcher's model menus |
|
||||
| `public/screens/starting.js` | the launching, starting and waiting screens, with Planny's poses |
|
||||
| `public/screens/workspace.js` | the read-only Workspace of extra folders, and @mentions |
|
||||
| `public/styles/ask.css` | The Ask pane and its Quick question chat |
|
||||
| `public/styles/dashboard.css` | The dashboard: the menu, the spec picker, its confirm and the launching pane |
|
||||
| `public/styles/docs.css` | Documents and the doc tools |
|
||||
| `public/styles/ending.css` | The end of a session: the hand-off and the stopping screen |
|
||||
| `public/styles/git.css` | The git board |
|
||||
| `public/styles/help.css` | The help dialog, its diagrams and its tabs |
|
||||
| `public/styles/looks.css` | The looks button and the highlight swatches |
|
||||
| `public/styles/pieces.css` | Shared pieces: cards, options, settled answers, pager, forms, checklist, markdown and the modal |
|
||||
| `public/styles/planny.css` | Planny the mascot: the flight, his moods and variants, and the wake-up |
|
||||
| `public/styles/poses.css` | The start-screen poses, one per skill. After the dashboard on purpose: its narrow-window rules override the dashboard's |
|
||||
| `public/styles/responsive.css` | Print, then the narrow-window rules: last, so its overrides come after everything they override |
|
||||
| `public/styles/shell.css` | The page shell: banner, top bar and meter, layout, sidebar, aside, footer, waiting and arrival |
|
||||
| `public/styles/tokens.css` | Colours, type, sizes and the light and dark themes: the variables every other file reads |
|
||||
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (18 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; The git board sits right after Watching a build), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
|
||||
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `console.mjs` and `lib.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
|
||||
| `public/git-board.js` | PURE, one import (`pr-url.js`): the git board's rules from a `state.git` snapshot: branch order and the Remote only fold at `REMOTE_FOLD` 50, whether a new branch name is free, which buttons show and are enabled, whether the board still waits on the agent (`boardAwaiting()`: from a click until the agent's next post, not just until `wait` collects it), the plain sentence each click sends as `reply`, the "Last refreshed" line, which files start ticked in the commit dialog, and the pull-request link. `app.js` only renders what it says |
|
||||
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `cmd-open.mjs`, `cmd-post-wait.mjs` and `sessions.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
|
||||
| `public/git-board.js` | PURE, one import (`pr-url.js`): the git board's rules from a `state.git` snapshot: branch order and the Remote only fold at `REMOTE_FOLD` 50, whether a new branch name is free, which buttons show and are enabled, whether the board still waits on the agent (`boardAwaiting()`: from a click until the agent's next post, not just until `wait` collects it), the plain sentence each click sends as `reply`, the "Last refreshed" line, which files start ticked in the commit dialog, and the pull-request link; the next step (ten rules, `nextStep()`), the tab that owns it, per-tab badges (`tabBadges()`), the busy mode and per-control gate (`busyMode()`, `controlAllowed()`), the tab to show (`pickTab()`), and the create-panel sources and clean-up groups. `app.js` only renders what it says |
|
||||
| `public/git-board-view.js` | No DOM access of its own: `drawGitBoard(ctx)` draws the tabbed board (header, tab strip with Done with git, the card slot, step strip, Changes / Branches / Sync) from the helpers it is handed (`el`, `md`, `copyButton`), every control through one gate; `screens/git-host.js` hosts it, and `scripts/test-web-console-git-board.mjs` drives it with a recording fake `el` |
|
||||
| `public/pr-url.js` | PURE, no imports: `prUrl()`, the "open a pull request" link for the GitHub, GitLab, Azure DevOps and Bitbucket shapes (`null` for an unknown kind, no web address, or a non-https result). `git-repo.mjs` re-exports it, and the board's base picker rebuilds the link in the browser with the same code |
|
||||
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `console.mjs`, `lib.mjs` and the page |
|
||||
| `public/meter.js` | PURE, no imports: the session meter. `WEIGHTS` (the one place per-event points live; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
|
||||
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `cmd-chat.mjs`, `cmd-post-wait.mjs`, `workspace.mjs` and the page |
|
||||
| `public/meter.js` | PURE, imports only `skills.js`: the session meter. `WEIGHTS` (the events that are not a skill's own launch, merged with each skill's `weight` from `skills.js`; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
|
||||
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
|
||||
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
|
||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, `console.mjs`, `lib.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
|
||||
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
|
||||
| `public/notepad.js` | PURE, no imports: the Notebook's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `TAB_NAME_MAX` / `NOTEPAD_MAX_TABS` / `IMAGE_ID_RE` / `TAB_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `tabSwitch()` (whether leaving a tab must save it first), `NOT_LOADED`, `EDITOR_NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), the tab rules `cleanTabName()`, `nameTaken()`, `tabNameProblem()`, `moveTab()`, `dropTab()` and the two-confirm delete `nextDelete()` / `DELETE_STAGES`, and `step()` (wrapping through the pictures) |
|
||||
| `public/screens/notepad.js` | the Notebook: `#btn-notepad` in the top bar on every screen (disabled while the server is gone, `renderNotepadButton()` in the render pass), `#notepad-modal`, the one CodeMirror editor (made on first open by a dynamic import of `notepad-editor.js`), the page's view of the notepad as `{ tabs, activeId }`, the name form (New tab and Rename, never `window.prompt`), the in-modal two-step delete, and autosave through `nextSave()` to `POST /notepad/text?tab=<id>`, flushed on close, when the page is hidden and before a switch. The editor stays read-only until the first read lands, so nothing typed into an empty editor is saved over a note. **Every save and every picture is bound to the tab it was made in**: `saveTab` is fixed when the change is made, a picture entry carries its `tab`, and a switch waits for the save (`settled()`), stays put with "Not saved yet, so staying on this tab." when it cannot, and drops a deleted tab's unsaved text without sending it |
|
||||
| `public/notepad-tabs.js` | the tab bar: `createTabs({ onSwitch, onChange })` with `draw(tabs, activeId)` (`role="tab"` buttons, roving `tabindex`, arrow keys, Alt+arrows to reorder, F2 and double-click to rename, native drag and drop with an `.is-drop-before` mark that only a tab drag lights, focus kept across redraws, `#notepad-empty` and `#notepad-body` toggled) and `focusTab()`. No fetches: it calls back, and `screens/notepad.js` owns every request |
|
||||
| `public/notepad-editor.js` | the Notebook's live-preview editor on CodeMirror 6 (`makeCodeMirrorEditor(parent, { onChange, label })` returning `{ getValue, setValue, setReadOnly, focus, destroy }`). A `ViewPlugin` decorates only the lines in view from the Markdown syntax tree: heading line classes `cm-h1` to `cm-h6`, bullets drawn as a widget, the marks around bold, links, quotes and a heading hidden on every line the selection is not on. The editor sits in a shadow root (`.notepad-cm-host`), because CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, and adopts them as a constructed stylesheet inside a shadow root. `setValue()` is `setState()`: not reported through `onChange`, and the undo history is cleared (so each tab starts with a clean one) |
|
||||
| `public/notepad-editor.css` | the one stylesheet of that shadow root, linked from `notepad-editor.js` (a `<link>` inside the root, in `SERVABLE`, not in `CSS_ORDER`): heading sizes, bullets, quote, code and link looks on the console's tokens (custom properties inherit across the boundary, so both themes work). Rules that meet CodeMirror's own base theme use `div.cm-editor` for the specificity |
|
||||
| `public/vendor/codemirror.esm.js` | CodeMirror 6 (state, view, language, commands, lang-markdown, MIT), bundled into one minified ES module by `scripts/vendor-codemirror.mjs` (sha256 `4ff96d58fc1a5497eb933426bd2d160d2fb0cf490de8bb9302c304096c71c1d4`, the six top-level versions in the script and the file's header comment, everything they pull in pinned by `scripts/vendor-codemirror-lock.json` and installed with `npm ci`, so the same lock gives the same bytes). Never edited by hand: change a version in the script and run `node scripts/vendor-codemirror.mjs --update-lock` (needs npm and network; the packages install in a temp folder, never in the repo), or without the flag to rebuild from the lock |
|
||||
| `public/styles/notepad.css` | the notebook's own rules: the top bar button, the dialog, the tab bar and its tools, the name form, the delete question, the empty state and the pictures. The editor's look is `notepad-editor.css`, inside its shadow root |
|
||||
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
|
||||
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network |
|
||||
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) |
|
||||
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
|
||||
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by `app.js` and the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
|
||||
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Split out of `app.js` because `app.js` cannot be imported outside a browser, so anything left in it is untestable. The `scripts/test-web-console-*.mjs` tests import it directly. |
|
||||
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by the page's looks and screens and by the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
|
||||
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Kept out of the page's entry because `app.js` cannot be imported outside a browser, so anything left in it is untestable. The `scripts/test-web-console-*.mjs` tests import it directly. |
|
||||
| `public/labels.js` | `taskLabel()` / `activityLabel()`: rewrites a build's `Task 4.2 of 6` activity line to `Task 2 of 6` (only for `implement` / `implement-review`; a plan's `Task 2.1` is a real section number). A separate module for the same reason as `answers.js`: pure, so `node --test` can import it |
|
||||
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `app.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of `app.js`'s render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
|
||||
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `screens/dashboard.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of the screens' render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
|
||||
| `console.md` | the core of the agent-facing contract, read once per conversation (every skill ships the same copy, so a dashboard hop never re-reads it): starting, the turn (`post --wait`, the exit codes, handling a send, `settle`), posting, the payload and its kinds, documents (including `file` blocks), the house rules, and an index of the topic files below with the moment each is read. A test caps it at 24,000 characters |
|
||||
| `console-finish.md` · `console-stop.md` · `console-chat.md` · `console-workspace.md` · `console-subagents.md` · `console-launches.md` · `console-meter.md` · `console-attachments.md` · `console-trouble.md` | topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, `stopWarning`, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's `run` events (read only when a `run` is refused: the notes inline every `run`), keeping a cited note attachment, and recovery |
|
||||
| `notes/<workflow>.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`). Each skill's Interface line reads `<D>/console.md` and its own notes file right after `open`; a test checks every skill names one that exists |
|
||||
| `notes/<workflow>.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`). Each skill's Interface line reads `<D>/console.md` and its own notes file right after `open`; a test checks every skill names one that exists |
|
||||
| `building.md` · `building-review.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`, `file` blocks re-read with `refresh`), the chat check between tasks, questions mid-build and stop requests; `building-review.md` is the review run on the page (the sign-off's `review` verdict, **Review it now**, Implement + Review's Stage 2), read only when asked for |
|
||||
|
||||
Key design points:
|
||||
|
||||
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `app.js`.
|
||||
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `screens/help-dialog.js`.
|
||||
- **Top-bar icons.** `#btn-looks` (gear) opens `#looks-modal`, titled User Preferences: Role, Theme, Card width, Highlight color, Sounds and Models. `#btn-feedback` (megaphone) is a plain link to `https://github.com/jparkerweb/plan2code/issues/new/choose`, backed by `.github/ISSUE_TEMPLATE/bug.yml` and `idea.yml` (`config.yml` sets `blank_issues_enabled: false`). `DEFAULT_ACCENT` in `palette.js` is `ocean`.
|
||||
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (`server.mjs` `/version` route). `renderHelpVersion()` in `app.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
|
||||
- **Models in User Preferences.** `GET` / `POST /models` in `server.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `lib.mjs`). `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
|
||||
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (the `/version` route in `routes.mjs`). `renderHelpVersion()` in `screens/help-dialog.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
|
||||
- **Models in User Preferences.** `GET` / `POST /models` in `routes.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `files.mjs`). `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
|
||||
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (cancelled). The agent loops. Nothing blocks for the whole time a person takes.
|
||||
- **A turn is one command, and the CLI does the bookkeeping.** Agent speed is model round trips and typed tokens, not the console (`bench-web-console.mjs --roundtrip`: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: `consume()` marks the agent `working` when it hands over a submit (`markWorking()`), and `wait` hands the turn back (`markWaiting()`) when it starts with an open question, a finish, or on the dashboard or git board; `post --wait <N>` posts and waits in one process; `settle: true | [ids]` (`settleItems()` in `lib.mjs`) records the latest send's cards as answered from their `submitted`; a new or reopened question with no stated status sets `waiting` and waiting drops `quietMinutes` (`settleAgent()`); a doc whose content changed with no `version` moves up one (`mergeDocs()`); a chat reply with no `id` is `r<re>`; doc blocks with `file` (and `select: "tasks"`, doc-level `refresh: true`) are read from the worktree by `resolveDocFiles()` before the merge, refusing paths outside it; and a hop (`__launch`, `__dashboard`, `__commit`) comes with `resume` (the exact `open --resume` command) and `skillFile` (`hopFor()`). The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. `help <topic>` prints any contract file; `help topics` lists them. `token` defaults to the option key in the page's `tokenFor()`, and nothing reads `fallbackText`, so the contract no longer asks for either.
|
||||
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `console.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch }` when it found anything to clean.
|
||||
- **A turn is one command, and the CLI does the bookkeeping.** Agent speed is model round trips and typed tokens, not the console (`bench-web-console.mjs --roundtrip`: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: `consume()` marks the agent `working` when it hands over a submit (`markWorking()`), and `wait` hands the turn back (`markWaiting()`) when it starts with an open question, a finish, or on the dashboard or git board; `post --wait <N>` posts and waits in one process; `settle: true | [ids]` (`settleItems()` in `patches.mjs`) records the latest send's cards as answered from their `submitted`; a new or reopened question with no stated status sets `waiting` and waiting drops `quietMinutes` (`settleAgent()`); a doc whose content changed with no `version` moves up one (`mergeDocs()`); a chat reply with no `id` is `r<re>`; doc blocks with `file` (and `select: "tasks"`, doc-level `refresh: true`) are read from the worktree by `resolveDocFiles()` before the merge, refusing paths outside it; and a hop (`__launch`, `__dashboard`, `__commit`, `__pickup`) comes with `resume` (the exact `open --resume` command) and `skillFile` (`hopFor()`), a pick-up also with `handoffFile`. The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. `help <topic>` prints any contract file; `help topics` lists them. `token` defaults to the option key in the page's `tokenFor()`, and nothing reads `fallbackText`, so the contract no longer asks for either.
|
||||
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `sessions.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean.
|
||||
- **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `<gitdir>/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it.
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `server.mjs`, which paints `data-width` on first load; `app.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
|
||||
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
|
||||
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes }], bytes }`, ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `models.json`) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
||||
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`), `notepad:<key>` (a month-old notepad, whole; see Notebook below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
||||
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
|
||||
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `app.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `app.css`; `START_POSES`/`startPose()` in `answers.js` is the list, and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
||||
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never greyed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `lib.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
|
||||
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; each `SKILLS` entry's `pose` in `skills.js` is the list (`START_POSES`/`startPose()` in `answers.js` read it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
||||
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never greyed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
|
||||
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
|
||||
- **No git process.** `repoRoots()` in `lib.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
|
||||
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `lib.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
|
||||
- **The first paint needs no fetch.** `server.mjs` renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to `app.css`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
|
||||
- **No git process.** `repoRoots()` in `sessions.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
|
||||
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `sessions.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
|
||||
- **The first paint needs no fetch.** `routes.mjs` (`renderIndex()`) renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to the joined stylesheet by `static.mjs`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
|
||||
- **Reads are stat-gated.** `fileStamp()` (mtime:size:ino) decides whether `state.json`, `result.json` and `looks.json` changed before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (`readState()` returns it; `/submit` clones before editing). `wait` stats `result.json` every 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
|
||||
- **The Workspace and the session meter live beside `state.json`, one writer each, and outlive every hop.** Three session files, none of which `switchWorkflow()` ever touches, so both survive dashboard → skill → dashboard (a new console session starts with a count of 0, and with the folders remembered for its folder and spec, below):
|
||||
|
||||
| File | Writer | Holds |
|
||||
|---|---|---|
|
||||
| `workspace.json` | `server.mjs` | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()`, now in `lib.mjs`, computed by the server at boot) |
|
||||
| `workspace.json` | the server (`workspace.mjs`) | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()` in `sessions.mjs`, computed by the server at boot) |
|
||||
| `ledger.ndjson` | `console.mjs` | append-only, one JSON line per entry. Meter events: `launch` (every fresh `open` and every resume into another workflow), `run` (a post's `run`, id scoped by launch, with `tasks` when a built phase reports one) and `answer` (one per item the person answered in a collected send, written by `ledgerAnswers()`, id `<launch>:answer:<send stamp>:<item>`). Also `folder-issue` reports |
|
||||
| `workspace-cursor.json` | `console.mjs` | the last workspace `version` handed to the agent; advanced after the print, never backwards |
|
||||
|
||||
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `lib.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console-workspace.md` and `console-meter.md`, and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
|
||||
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `workspace.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console-workspace.md` and `console-meter.md`, and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
|
||||
- **The Subagents switch is a standing instruction, injected only on change.** The page's icon button (`#btn-subagents`, after Write a brief) and `#subagents-modal` show only when the frame's `subagents` block says `offered && supported`. `offered` comes from `public/subagents.js`; `supported` means the latest `{ "type": "open" }` line in `events.ndjson` carries `caps: ["subagents"]` (`latestOpenCaps()`), so an older skill copy's `open` hides the button. Four places hold it, one writer each:
|
||||
|
||||
| File | Writer | Holds |
|
||||
|---|---|---|
|
||||
| `~/.plan2code/console/subagents.json` | `server.mjs` | per project folder → workflow: `{ on, instruction, max }`, `instruction: null` being the shipped default; on `PROTECTED_CONSOLE_FILES` |
|
||||
| `<session>/subagents-setting.json` | `server.mjs` | `{ workflow, on, instruction, max, revision }`: synced from the store at boot and on any workflow change (`syncSubagentSetting()`), `revision` bumped only by a real change |
|
||||
| `<session>/subagents-setting.json` | the server (`settings.mjs`) | `{ workflow, on, instruction, max, revision }`: synced from the store at boot and on any workflow change (`serverSubagents().sync` in `settings.mjs`), `revision` bumped only by a real change |
|
||||
| `<session>/subagents-cursor.json` | `console.mjs` | `{ revision, state }`, the last block handed over; `open` resets it, and it moves only after the print |
|
||||
| `state.json` → `helpers` | `console.mjs post` | the helpers the agent reports, merged by `id`, checked by `checkHelpers()` plus the prose scan; dropped by `switchWorkflow()` on a dashboard hop |
|
||||
|
||||
`POST /subagents` (origin-checked; `400` `not-offered` / `bad` / `too-long` / `max`) saves the store and bumps the session setting. `consume()`, `cmdChat()`, `deliverChat()` and `open` append `blockFor()`'s lines last in `reply` and the `subagents` field; a change alone never ends a `wait` slice. The page's Subagents tab (before Ask) draws `state.helpers` through `helperRows()`. Helpers never reach the meter ledger. Contract: `console-subagents.md`.
|
||||
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or the loop's marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
|
||||
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `server.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `lib.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
|
||||
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `routes.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `sessions.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
|
||||
- **Answers carry their terminal token.** Each item ships `fallbackText` and `token`, so a click resolves to the literal word the prompt already expects (`approved`, `a`, `skip`). No workflow needs a second code path, and declining the console degrades to prose with nothing lost.
|
||||
- **A build tells the page how long silence is normal.** The page calls a working agent stuck after two minutes without a post, which is right for a conversation and wrong for a twenty-minute build task. `agent.quietMinutes` (1 to 60, counted only while `working`) stretches the stuck, adrift and Send-grace thresholds; `quietLimitMs()` in `answers.js` is the one rule.
|
||||
- **A finished quick task's review button is a request through the wait loop**, like the brief: `{ "i": "__review" }` or `{ "i": "__done" }`. The agent keeps waiting after posting a finish that carries `review`, and takes the review up by posting `"finish": null`, which puts the session back to work. Implementation's review needs no such machinery: it is a verdict on the sign-off card, asked before approval, so the session never left work to take it up.
|
||||
- **Back to the dashboard is the same kind of post-finish request.** A finish with `finish.dashboard: true` shows the button; a press arrives as `{ "i": "__dashboard", "type": "dashboard" }`, and the agent runs `open --resume <sid> --no-open --workflow dashboard` then posts `"finish": null` with a fresh `menu`. The agent waits ~10 minutes after the finish for it (alongside `__review` / `__done` on a quick task); after that the page swaps the button for the `/plan2code` command. `finish.command` is optional — without one the page shows the "All done" line — and `validate()` rejects a `<placeholder>` command and a non-boolean `dashboard`. The session-level actions are therefore `__brief`, `__stop`, `__launch`, `__review`, `__done` and `__dashboard`; a new post-finish button should copy this precedent.
|
||||
- **Continue here, Update CHANGELOG first and Ask prompt blocks.** Three small additions on the same pattern. **Continue here** is page-only: `continueOffer(fin)` (`public/answers.js`) reads `finish.command`, and when it starts with a Plan2Code skill (and the finish is not a pause) `screens/ending.js` draws a button beside the Next step block, hidden when the session meter is red; the press is the dashboard's own `{ "i": "__launch", ... }` through `sendAfterBuild("launch", offer)`, so the agent writes nothing new (`startsClean()` cleans the page for the hop, except out of Git and into Review; a same-skill next step keeps the workflow, so the agent posts `"finish": null`). **Update CHANGELOG first** is `finish.changelog: true`, accepted by `validate()` only on `quick-task` and `finalize` (a paused finish is exempt from that check and the page ignores the flag), and it belongs with `commit: true`; the press is `__changelog`, a `HOP_ACTIONS` entry in `cmd-post-wait.mjs` that resumes as `changelog`, whose "Commit this now?" yes carries on to Git. **Ask prompt blocks** are contract only (`console-chat.md` → Prompts to carry away): the page already draws a Copy button on every fenced block.
|
||||
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
|
||||
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `lib.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
|
||||
- **`validate()` in `lib.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
|
||||
- **Handoffs live outside every repo, in `~/.plan2code/handoffs/`, and the console owns them** (`handoffs.mjs`; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it through `console.mjs`). `handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]` claims one for this checkout and prints `{ ok, id, path, meta }` (exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers **Stop with a handoff** (`#stop-handoff`, suggested) above **Just stop and save** (`#stop-go`); the first sends `__stop` with `handoff: true` and `STOP_HANDOFF_REPLY`, and `wait` adds `handoffSkill` (the built Handoff skill's `SKILL.md`, `handoffFor()`); console-stop.md gives the order (answers, save, `handoff new --from-stop`, write, paused finish naming the file, `stop`). On a dashboard, `cmdOpen()` adds `scan.handoffs` (`listHandoffs(worktree)`) and `scan.handoffsDir` after `scanProject()`, which stays handoff-free because `specs.mjs list` shares it. The picker draws them as dashed `.spec-chip.is-handoff` chips after the specs (`specSel = "handoff:<id>"`); a picked one replaces the skill cards with `renderHandoffPreview()`: **Pick it up here**, **Read it all** (`GET /handoff?id=`, served only for an id in the dashboard's own `state.scan.handoffs`), **Copy for a new conversation** (`handoffCopyText()`) and **Delete** (`openHandoffDelete()`, one step). Pick it up sends `{ "i": "__pickup", "type": "pickup", "handoff": <id> }`; `HOP_ACTIONS.pickup` (`pickupHop()`) reads the stored `.json` only, never the page, and falls back to Quick Task with `fallback: true` when the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff); `markPickedUp()` stamps `usedAt` as the hop is printed, so the next scan drops the chip. Delete sends `__delete` with `handoff` in place of `spec`, and the agent runs `delete-handoff --handoff <id>` (`removeHandoff()`, exit 3 on a refusal, nothing touched). `open` sweeps handoffs untouched for 30 days (`staleHandoffs()`, the `.json`'s mtime, else the `.md`'s), picked up or not, and reports them in `swept.handoffs`; Cleanup never lists the folder (`KEPT_PLAN2CODE_ENTRIES`).
|
||||
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and never the agent's.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** eleven, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) and `/notepad/tab/last` (`{ id }`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The ten POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` never imports `notepads.mjs`, so nothing in a notepad reaches `state.json` or anything `wait` prints. **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notepad.js` binds every save and picture to the tab it was made in (a switch waits for the save, and stays put when it cannot), `public/notepad-tabs.js` draws the bar, and `public/notepad.js` holds the name, order and delete rules as pure code. **Cleanup.** No sweep at `open` touches a notepad, and `notepads` is in `KEPT_PLAN2CODE_ENTRIES`, so the folder is never a stray. `cleanupFindings()` lists a notepad as one `notepad:<key>` item (with `folder` from `meta.json`, labelled "Notebook for <folder>"Line truncated
|
||||
- **A Bug fixed spec deletes in one step.** Its chip shows a visible **Delete** (`.spec-chip-del-label`) instead of the hover ✕, `openDeleteConfirm()` gives it a fixed-bug warning and a **Delete it** button, and `deleteStep()` sends `__delete` on the first press, with no name to type. `chipDetail()` drops the scan's repeated "bug fixed" detail under the label.
|
||||
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `inbox.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
|
||||
- **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
|
||||
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
|
||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 17 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed, so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `app.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 18 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed (except the dashboard topic's card list: `buildHelp()` fills its `.help-cards` from `SKILL_CATALOG` and `CATALOG_GROUPS` at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
||||
- **Stuck sessions are explained twice, in Help and on the status line.** `stuck` ("When something looks stuck") is the second tab in `HELP_TABS`; its panel opens with a `help-callout` ("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (`openHelpOn("stuck")`) inside the existing `role="status"` element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel from `renderCloseGuide()` in `renderHandoff()` (Safe to close, Start fresh, Carry on). Tests in `scripts/test-web-console-source.mjs` check the tab order, the callout and rows, and the `renderCloseGuide` call.
|
||||
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
|
||||
|
||||
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-git`, `-qa`, `-speed`, `-hardening`). Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
||||
|
||||
**Adding a file under `public/` needs three edits, not one:** the file itself, the `SERVABLE` allow-list in `server.mjs`, and (for a module the page imports) a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a new module missing from it 404s and the page dies at import with no useful error (a test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint.
|
||||
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files table above, which the docs-table test (same file) checks.
|
||||
|
||||
## Status Line
|
||||
|
||||
@@ -293,10 +369,10 @@ Typing `plan2code` in any directory opens the dashboard skill against the curren
|
||||
| Devin | `devin --permission-mode bypass [args] -- /plan2code` |
|
||||
| Codex | `codex --dangerously-bypass-approvals-and-sandbox [args] $plan2code` (Codex starts a skill with `$name`; the launch line follows Codex's documentation) |
|
||||
|
||||
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it exits 127 and prints `SKILL_STEPS`: how to install an agent, `cd` into the project, and type `/plan2code` (`$plan2code` in Codex). An uninstalled `--cli` pick prints that CLI's own steps after its error (its install command, `cd` into the project, then `plan2code --cli <id>` or its prompt). `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=` (or, for Codex, `-m`), it asks `Which model should <CLI> use?` from `models.json` plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin`/`codex` commands and a temp home.
|
||||
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it exits 127 and prints `SKILL_STEPS`: how to install an agent, `cd` into the project, and type `/plan2code` (`$plan2code` in Codex). An uninstalled `--cli` pick prints that CLI's own steps after its error (its install command, `cd` into the project, then `plan2code --cli <id>` or its prompt). `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=` (or, for Codex, `-m`), it asks `Which model should <CLI> use?` from `models.json` plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. `plan2code update` is the one subcommand: it is never forwarded and opens no agent, it runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists. On every other start, before spawning the CLI, it prints one line when a newer release is out (`Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`), compared against `~/.plan2code/bin/version.json` and read from the console's cached release check (`~/.plan2code/console/update-check.json`); it never waits on the network, and when the cache is missing or stale it refreshes it in a detached background process so the next start knows. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin`/`codex` commands and a temp home.
|
||||
|
||||
**Design constraints:**
|
||||
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. Beside it go `update-check.mjs` (the web console's release check, for the terminal notice) and a `version.json` (the installed version). (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||
- **npm-style shims** — written into npm's global bin (`npm config get prefix`; `<prefix>/bin` off Windows): an sh shim everywhere, plus `.cmd` and `.ps1` on Windows, so cmd.exe, PowerShell and Git Bash all resolve it. On macOS/Linux, when the npm bin isn't writable (system Node), it falls back to `~/.local/bin`.
|
||||
- **Marker-based ownership** — every shim contains `plan2code-launcher`; `uninstallLauncher()` removes only files carrying it, leaving any other `plan2code` bin alone.
|
||||
- **Resolving the CLI** — the launcher walks `PATH` (+ `PATHEXT` on Windows) itself. An `.exe` is spawned directly; a `.cmd`/`.bat` wrapper goes through `cmd.exe /d /s /c` with quoted args, since Node refuses to spawn batch files without a shell. The installer warns only when neither `claude` nor `devin` is on `PATH`.
|
||||
@@ -313,4 +389,4 @@ On a terminal it first prints a Planny banner (`renderBanner()`). With more than
|
||||
|
||||
The macOS and Linux shortcuts carry the `plan2code-launcher` marker as a comment line. A `.lnk` has nowhere to hide one (its Description is the hover tooltip), so it's recognized by what it runs: the UTF-16 strings `plan2code.ps1` and `--pick-folder` stored in the file (`plan2code.cmd` also matches, so shortcuts from before the PowerShell switch get refreshed). `uninstallLauncher()` removes only a recognized shortcut, plus the icons (`plan2code.ico`, `plan2code.png`), `bin/models.json` and `launcher.json` (never the user's `~/.plan2code/models.json`). A shortcut failure prints a warning and never fails the command install.
|
||||
|
||||
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
|
||||
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. Every global install writes `~/.plan2code/install.json`, the install record listing the pieces installed (skills, launcher, statusline, loop, metrics, bot); `install.js --update` (what `plan2code update` runs) reinstalls exactly those, with no menu and never uninstalling, or with no record the skills and the `plan2code` command. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
## Gotchas / Pitfalls
|
||||
|
||||
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. `README.md` and `docs/index.html` (footer `Version X.Y.Z`) also carry the version. `version.json` is copied into every skill's `references/web-console/` (the console's Help shows it), so after a bump run `npm run build:skills` or `npm test` (`--verify-skills`) fails. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number.
|
||||
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. `README.md` (the `Version X.Y.Z` line near the top) also carries the version, and `version.json`'s `releaseDate` moves with it. `version.json` is copied into every skill's `references/web-console/` (the console's Help shows it), so after a bump run `npm run build:skills` or `npm test` (`--verify-skills`) fails. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number.
|
||||
- **CHANGELOG ordering:** Entries in `CHANGELOG.md` must be in reverse-chronological order — newest version at the top, oldest at the bottom. New entries are always inserted immediately after the file header.
|
||||
- **CHANGELOG house format is not Keep a Changelog:** version headings are `## vX.Y.Z` — with a `v` prefix and **no date**. The release date is recorded only in `version.json`'s `releaseDate`. Category headings carry emoji: `### ✨ Added`, `### 🔧 Changed`, `### 🐛 Fixed`, `### 💥 Breaking`, `### 🗑️ Removed`, `### 📚 Documentation`. Older entries contain one-off variants (`🎁 Added`, `📦 Updated`, `📝 Documentation`, `🏎️ Improved`, `🧪 Testing`) — do not introduce new ones. The `.claude/skills/plan2code-changelog/` skill automates version selection and formatting; use it rather than hand-rolling an entry.
|
||||
- **PowerShell mangles the CHANGELOG emoji:** `Get-Content` / `Select-String` render the `###` heading emoji as `?` under the default Windows console encoding, so a heading audit done that way reports garbage. Read `CHANGELOG.md` with a file-read or grep tool instead.
|
||||
@@ -26,12 +26,12 @@
|
||||
- **Metrics internal prompts have no char limit:** Files in `plan2code-metrics/src/prompts/` are NOT subject to the 20,000 char limit — only `src/plan2code-*.md` consumer-facing prompts are.
|
||||
- **User Feedback table format:** The `## User Feedback` markdown table in `overview.md` has a strict format the collector regex depends on. Field names must be exactly `Rating`, `Reason`, `Went Well`, `Went Poorly`. Pipe characters in values must be escaped as `\|`.
|
||||
- **PLAN-DRAFT confidence numbers are scraped by regex:** `collector.ts` scrapes the latest `specs/<feature>/PLAN-DRAFT-*.md` prose. Overall confidence falls back to prose only when `<!-- METRICS_JSON ... -->` lacks `confidence` (`collector.ts:186-196`): `Confidence: 95%`, or a table row `| Confidence | 95` with no `%`. The four *breakdown* patterns (`collector.ts:200-203`) run on every draft, METRICS_JSON or not: `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep `Confidence` followed by a number (with `%`, or as a table row) **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class.
|
||||
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `lib.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
|
||||
- **Web console oversized bodies:** `readBody()` in `server.mjs` calls `req.destroy()` past `MAX_BODY`, so an oversized JSON body gets no response at all: the client sees a connection reset, never a status code. A route that must answer 413 has to stop buffering and drain the rest of the body instead, as `readRaw()` (the `POST /upload` reader) does; memory still stays capped.
|
||||
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `lib.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console`, or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
|
||||
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `patches.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
|
||||
- **Web console oversized bodies:** `readBody()` and `readRaw()` (the `POST /upload` reader) in `routes.mjs` drain the rest of the body past `MAX_BODY` instead of calling `req.destroy()`, so an oversized body gets a 413 rather than a connection reset, and memory still stays capped. A new body reader must drain the same way.
|
||||
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `sessions.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console`, or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
|
||||
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalises its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
|
||||
- **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`.
|
||||
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/app.css`. No test ties them together.
|
||||
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/styles/tokens.css`. No test ties them together.
|
||||
- **Reference file sizing guideline:** Files in `src/plan2code-*-references/` directories target ~100-200 lines each (soft guideline; evaluate splitting above 300). They are NOT subject to the 20,000 character limit. The pre-commit hook (`validate-char-count.js`) only checks `src/plan2code-*.md` flat files — subdirectory contents are automatically excluded.
|
||||
- **The splitting guideline has a hard ceiling — reference files cannot always be split:** each new reference costs the orchestrator a `Read references/<file>.md` line plus its fallback blockquote (~150-200 chars), which adds up across a prompt's 20,000-char budget. When a reference legitimately exceeds 300 lines (e.g. `plan2code-0-pathfinder-references/chart.md`), that is an accepted trade-off, not an oversight. Nested folders under `-references/` work: `references/` is the real path on every agent.
|
||||
- **Windows global bins for loop, metrics and bot are wrappers, not `npm link`:** on win32 the installer writes `<name>.cmd` and `<name>.ps1` into `npm config get prefix`, each running `node <package>/dist/bin/<name>.js` (`install.js:1302-1323` for the loop; the metrics and bot installers do the same). After a source change, `npm run build` in the package is enough; no reinstall.
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
|
||||
```bash
|
||||
# Install dev dependencies (sets up husky pre-commit hooks only; each sub-package
|
||||
# below needs its own npm install, Node 18+)
|
||||
# below needs its own npm install. Running `npm test` needs Node 20+; users of
|
||||
# the installed skills still need only Node 18+)
|
||||
npm install
|
||||
|
||||
# Run the interactive installer
|
||||
@@ -21,16 +22,22 @@ npm test
|
||||
# One web console or launcher test
|
||||
node --test --test-name-pattern "<regex>" scripts/test-web-console-<area>.mjs
|
||||
|
||||
# Web console start-up benchmark (puppeteer-core optional)
|
||||
# Web console start-up benchmark (the paint columns use a local Chrome or Edge through
|
||||
# playwright-core, which `npm install` already provides)
|
||||
node scripts/bench-web-console.mjs [--runs 7] [--workflow dashboard]
|
||||
|
||||
# Refresh the web console screenshots in docs/screenshots/ (needs a local Chrome or Edge).
|
||||
# Rerun after any change a person would see on the console page, and open every image
|
||||
# before committing: right screen, both themes, no username or home path in frame.
|
||||
npm i --no-save puppeteer-core # once; never added to package.json
|
||||
# PLAN2CODE_TEST_BROWSER=chrome|msedge forces which browser the page tests and these scripts use
|
||||
node scripts/capture-screenshots.mjs # every screen
|
||||
node scripts/capture-screenshots.mjs --only dashboard # one screen (dashboard-utilities scrolls to the utility cards)
|
||||
|
||||
# Compare every element's computed style on every screen before and after a stylesheet change
|
||||
# (dev-only, not in npm test): take a baseline first, then compare after each move
|
||||
node scripts/css-snapshot.mjs --out before.json
|
||||
node scripts/css-snapshot.mjs --compare before.json
|
||||
|
||||
# Plan2Code Loop
|
||||
cd plan2code-loop && npm install # First time setup
|
||||
cd plan2code-loop && npm run build # Build the CLI
|
||||
@@ -51,7 +58,7 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
|
||||
|
||||
| Variable | Effect |
|
||||
|----------|--------|
|
||||
| `PLAN2CODE_CONSOLE_HOME` | Replaces `~/.plan2code/console`: sessions, `looks.json` and the runtime handle dir all move under it (`src/web-console/lib.mjs`). Always set it for scratch runs so `stop --all` cannot reach real sessions. |
|
||||
| `PLAN2CODE_CONSOLE_HOME` | Replaces `~/.plan2code/console`: sessions, `looks.json` and the runtime handle dir all move under it (`src/web-console/files.mjs`). Always set it for scratch runs so `stop --all` cannot reach real sessions. |
|
||||
| `PLAN2CODE_NO_BROWSER` | `open` does not launch a browser (`NO_BROWSER` also works). |
|
||||
| `PLAN2CODE_BROWSER` | Browser command line to run with the link appended, instead of the system default. |
|
||||
| `PLAN2CODE_MODELS_DIR` | Moves the launcher model menus (`bin/models.json`, `models.json`) away from `~/.plan2code`, for tests. |
|
||||
@@ -84,12 +91,13 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
|
||||
|
||||
## Non-Interactive Flags
|
||||
|
||||
`install.js` takes no arguments for normal use, but exposes two build hooks. Any argument other than these two (when neither is present) exits 1 with usage; extra arguments beside either flag are ignored.
|
||||
`install.js` takes no arguments for normal use, but exposes two build hooks and the non-interactive update. Any argument other than these three (when none is present) exits 1 with usage; extra arguments beside `--build-skills` or `--verify-skills` are ignored, while `--update` must be the only argument.
|
||||
|
||||
| Flag | Action |
|
||||
|------|--------|
|
||||
| `--build-skills` | Regenerate `skills/` from `src/`, pruning stale skills and reference files |
|
||||
| `--verify-skills` | Diff local `skills/` against `src/`; exits 1 on drift. Diagnostic only, the installer rebuilds anyway |
|
||||
| `--update` | No menu: reinstall what `~/.plan2code/install.json` lists (skills, launcher, statusline, loop, metrics, bot), never uninstalling; with no record, the skills and the `plan2code` command. `plan2code update` runs it through npx |
|
||||
|
||||
## How the Installer Works
|
||||
|
||||
@@ -134,6 +142,15 @@ See the `skills/` build-artifact gotcha in [Code Style & Gotchas](./AGENTS-code-
|
||||
## Adding a New Workflow Prompt / Skill
|
||||
|
||||
1. Create `src/plan2code-<name>.md` with body content only and keep it under 20,000 characters.
|
||||
2. Register it in `SOURCE_PROMPTS` in `install.js` (with the web-console `additionalReferences` entry every skill carries); add a `generateStepLabel()` case when needed. List any shared scripts it runs in `scripts: [...]`, and put its own scripts in `src/plan2code-<name>-scripts/`. Add it to the skill/workflow table and the "What each skill reads and writes" table in `src/plan2code.md` (the latter is checked by `scripts/check-skill-table.mjs`), and to the workflow lists in `src/web-console/public/answers.js`, `public/meter.js` and the `console.mjs` usage text.
|
||||
3. Update command inventories in `README.md`, `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture.md`, and `CHANGELOG.md`. Update `docs/index.html` only for core pipeline steps.
|
||||
4. Run `npm run build:skills` and `npm test`.
|
||||
2. Register it in `SOURCE_PROMPTS` in `install.js` (with the web-console `additionalReferences` entry every skill carries); add a `generateStepLabel()` case when needed. List any shared scripts it runs in `scripts: [...]`, and put its own scripts in `src/plan2code-<name>-scripts/` (with a `scripts/test-script-<name>.mjs` added to `package.json`'s `test` list).
|
||||
3. Register it with the web console. The meter's points and labels, the resume command, Help's card list and `console.mjs help`'s workflow list are all derived from `skills.js`, so the edits are `skills.js`, `install.js` (step 2), the skill's prompt (step 1), its pose and its notes; `npm test` names anything else left out:
|
||||
- `src/web-console/public/skills.js`: one entry (workflow, label, start pose, flags, subagents line, the meter's `weight`, `started` and `ran`, and `resume`) with its card (plus `help` when Help's line should differ from the blurb), and the card's `states` and `greyed`. Utilities go in group `"extra"` before Changelog.
|
||||
- `src/web-console/public/index.html`: its start pose, an `<svg class="pose pose-<workflow>" data-pose="<workflow>">` in `<template id="start-poses">` (pose CSS in `public/styles/poses.css`), unless its `pose` borrows an existing one (as Implement + Review borrows Implement's).
|
||||
- Its help topic: a `src/web-console/notes/<workflow>.md` (named in the skill's Interface line) or a `HELP_TOPICS` alias in `src/web-console/cmd-help.mjs`.
|
||||
- `src/plan2code.md`: the skill/workflow table and "What each skill reads and writes" (`scripts/check-skill-table.mjs`: every backticked token must appear in the skill's prompt).
|
||||
- `console.md` (the `open --workflow` list and the `notes/<workflow>.md` row).
|
||||
- Optional: `STARTER_SET_FOR` in `public/starters.js` (unlisted gets "general").
|
||||
|
||||
**Adding a spec state** is shorter: one entry in `src/web-console/public/spec-states.js`, the detection in `classifySpec()` in `src/web-console/scan.mjs`, the `states` of each card in `skills.js` that takes it, and a line in the dashboard skill (`src/plan2code.md`); then `npm test`.
|
||||
4. Update command inventories in `README.md` (dashboard-card and command tables), `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture.md` (prompt table, own-script rows, notes list), and `CHANGELOG.md`. Update `docs/index.html` for core pipeline steps, and for a utility only when it is a headline change (its `.utils` block).
|
||||
5. Run `npm run build:skills` and `npm test`.
|
||||
@@ -1 +1 @@
|
||||
U0VOQwFAFRnj5vy/mnmGUHUOrq/i1kg2DXIDYOvtqs3nU3Zr6vo320sUGDuFT2Bicjmgrzt+z9L/byaoHJlHgsY7t7OIRAp0wLV2zlNhr6E0rkAdx6ZZf7kYjh9eJqyc3sgun533cQGwb4uIMaBvqqBBFPsCWrQv8Eveyj5SgDQRSGsTrfFfhZYJ9Yy9x1bxizThrs0A0WTwqxhEodPJJGN2t+rr2ZLNKrJ+7rHaQGQO7lOIjQXnf1gi3oNYS9m3rF1xq4jHKDun+P6kPJvQwn7YNe5tP3ZpKfzYqzXa6XggT0D7wiXsiwwpJKqhvH0rFxv1Cw4AlVuQva7aJZerjLY86RwhUEX6sHvj/xiWtOJirXG4Tonl0bLfNMZYPDiBMh3tP4nexik3pPjm7ya6cfcagckIjLT8CqBjY7IaxEJXc0DXRmOH0zbQ+cJfRlQHcE10CI9DnP03bUoyQ87/bADggbVKyo1aE/OfbPRRfF3idVOqjWyMrfaZYimh+kcLmv/jwB7YUlaFrlG1koHzK6Ecl57f6JLFxbFOXvjXJ3Dms0irsDxQTFizWOuvxgdgzq2BapB98iXJvqIjK0zRXpX5CDNsywN7WEAsCv/BQyEXUQykTi0ZU790DdhmSR0FyHegHKUCOaiYnQ92u6S74bKY4KXLkXZQBdm9FY4cUazjXVtdvyQo2c7T2tVrtejnExeaaCGeDmPRWuX6a21iHwvBGDBxEyVwG/Mu+sTHytXI0dV7lFZ0vcgiVs8lCnicC9Mt/Pr8c9hFR7eUO/OMzX6kRtmgqrXiFgnsYOE7CrxqULFEkdNgnEfqKz3G4XyQpFEhXz0Y043Y/NmIdf9C6pwt7BhUMY5256tEwM0p02FkavTI8Bbza9vQQWNIcI4YYkQSkJqbmuauGuYaDabxY26wwqwIN/I/nhN2HnpfPkopBq9O/jv+sAyA9vQ3V6p5SPxX+EiYpwzsTJ98hZHgWUCq+U13JL4vn3PRbZ476RiqVSG+B3VmckNCYbf/5IGi3QwLcD1SZ6Q226IH9HqwHqhKDs1MDcqiri/B4dQYZ127kRpfD0fMCJlHgBEmi+I29FnNg+tUFws4AoiYyOBH77XVFykelHNEoNi0RHScKxNQBs3L1E7Z9nMED9NmAAraxaWEakCMYFShQ7uKrm0GJYFjWV6thl5t1erjsjxz8qvKIdQkkDmNgJsElcgK7+wdstceulDiTBoYksEeL4mNyjY5NO0m4IKsYbPcPfGhbp3HGPM4hfJvYPPF2cZP8wLB7L2/5GW8r8ndA1SBsetwSmnlmks56oJ/L9yM3NbCZ4tUD+WyObPIkfrZkrOIOPvKmGdU4S5AzwceVglnOJ37zty1PNQB+t4Zd33CsZM0LpW/5v/8ESaGgVgy5SCqmfXhqeLxZRPpshkNmaOr9AKSLGxl25bvOslnSoFhkociK7EtaPdJ86NSU0eAKrht67SYp56wz++8VUl18XljmUJqsgyyW0c25EXjS1LxL27MNrMkV3pUX+NVYss910+KYH2VFoT2QLKfjaON1iB94ow3jUUNXZmfSj+YGNtWLgrtEUlPEA3bRnRINldyOoPCPioZVTNuMrfNTaBFdFLmKDRU6xb0taehRwvSkF7hepEDk3fYhJTaPqS4dVD0a2zsl6D4hhdNs0pw2hx4WZtATMfWYSXYyQ49GHGkJrbReQ9qqXqucTcWymNwfy9me8ytcK39ioBrRi+6uBJGSlMXYjSjLpGF2sOC+h/ghZDi4ut3tQ/SQYIJED+HDwJppODWo/G4KFrKbXJfP1syxstKQELKOWvX1IY1czQmIXcQycZPFvjEd8bNgqtHZRpxbbvNJ9Ii/yBJCfY/IA3jyuqrle29nhMlWMWSnzDOv1EbeBQKQik/dNG3MDEbmU85fbU59PFvytpnc2nOehEhF7yMmK5kvpo07wZD4JrV9f9hqSAccx0sBZ8Lu6UI2g+FRe5g0190cg2BZIV9coHlGUdadPQfi1LJM+2yjjAtweHxaA1Ynye9/SNFCUUPbwNo4KRMF7ICUHFLOsqEuaY5EMjOxE1M5A1jZKy2e3/yt9AXoLhsH7pbhnzc0tlgo6aCKKOoz6JaXKJqonNpC3gQYxDl1SeDx81BpyGyuGipRcxZx/UhYq7E9y5vUUSf9D+J1Ht1MjQRrlToR9UKdpH6ILKx+2nK8rUUMNwJFb5VA1XOligKvp54vN/uY9zXTSzRpNFJ5FftRncMlgnhpQ5rcQB6Dnq6kurgVdCD+TjWGwxijtc3kjhVwPUbY6P3BcJryjIhK470i+8s7w0jGWm7954kUDl5jI4NFmeS7mD3wEbDYf5eIRsHlaJZP06IgNleQBOesabSl5DwQWvwyJX+JQARJdQs4N0nhSiFZ1MyeiKRvJNrHqmHIfcbeTFdCkR031Qs5lT+09iVMB99pWHqbuUQSFBUXghZm6pXrh6sFJyyDfszBzmpvCHzYUdHmXs3Re/hyjJQTYHirRKLTPAasyxwXSD03Xw9Fje+kld7fYMbJRaj9H3lDHgl7AZ0CZFiDMgQgWEafmAmgfoU5IZUUFfZgTUu6fXACz2nyR0zKmlXLgsOtAWb0MWo/3twlz4kb/OFdIe1hd6MtbXnl0QBIexPxC+uDHieTRgVE9w8Hu0X9kjRGVp7VAmmlJSh0jjI5OSHvTMTHwTOaUVR3+74qLYokxHS2KqtZAnUioRT3pgBlTORft8CeJyoSJe4QdlZ3Ws8rhKsUF0SbPKCvOb2g/G4S2zECxH51Oj/s5T9meevo1vlHwznuth2rUMIMV+nVfiCjTOL0CoLvOVCICKUa67QvM0tjZPAggFXzZZ5CIvqBLsMm97SK7EjdAIrPmGNDpMy2HWf3LXnJXYVunsVi0zv6Jmr2usgUo2ks+4Lx/8pifkdf7JxE3jlPYNesTEhTYrPOKaRBdnPTuv0vhSTDZnsOSgnFPyFT/mQxMvcNUizjwvpVWrJZexVICl68gCW4WNTpymc5xLHQIZVa5ZTVeBF1yLqQOOSVD8ftQpIMzpREUx3lCuwK3iG/Hpnd0Yvlb0FwVl1pglKcF5JS7Au2lnXpoeu7LY4O8SMfILsrIsB194wlOQxDD6/B4Z30rTeuaQ+j7Nis6VdFiSuBo1WcqmrEPGkRlz/zRuhP7fdRaZOTFIyP7lesKKfOKDoRNs7z2f9v4Ide6RP/bB3nYEPX7czEZGQj7XQdwM3MS81Lg70Phuzj2Hu0KschT6WrgU0gVXK3w50EZWxF3fD4uj4rLFkIsZD9BOAfyWS9gkoAGXkthoaFb1ttwCG82EWQJwNOBToGzdUkPI22RTaw6bywd5xY1pvHMJVHbpsh3zK0NfTVfhkYN2KqGIHHO3I7wwEJDnPc1zpbKSfQOqCyu0xaozwfWio0iVFAsdIXXyNe5rqTBHcX4+eYx0+EpVH3BFkN+t0BmiYZtMjNhehOMDjwCQ7nWDVD5JNbRRB56modlYiMk89M1W/Xw3Y56Wkx4R3GQZ7sWyscTlW5tEJmk8XXBpnp9W7ujcsAc+CoHcKdHpluRP2fftlMp866hb8fhOGY/KKldKrtgoIa+mYzmmBQ9OOIEMEyCQvPihQhxZ2AJEg1mOJjKJ3TtaTPLxno6Dv/RbZQGroR2GZMcQubrgmCRx90vIQLOl78MeDoLa8K322rfM7B1BUIRWQVsAbdPrmFZic0qit7shIfsdiX5hUpuV5Pmm6sjXQ0bRZqvKtp+ofNXnP9XqlyuxrYTJtrpoYQ+9dE7Mdrq5C+hLThnmEgZaAXrVX1jnqwdN7PyM7KNPBiWJGF9+a4J/sdLmhC3MI1jIKdOKbsMWLpJxux5X9PknqCS5yUS7IXw805yj0g4+QdUbM5a+zFujzcA/CFwjzrLQ+9QtTzVlO1jTFWdecH+lduQvUOcN2HAkH8AuhlzlrJgpfP5n+Rvg6xCX7LFT2KXOh+w3PodSkaGEmkudbypy61Qiv8VSRruloX3HimLVyiIDCPNaw9xNb3vKrDzIyKNiar3ZmZqvkVMCAlk6STYFy4wszXBfPUasNo+zElboRklAoKyMmRBS40VfHe2dgLXPNFljKiRjayUENc4NzSKlS9bDbKgmmxjfi+o7smCOkBYyKHaEkufGx/ouby+awJVHPF6WtR3IsrFFxwJjJW8Ukspe+rfuEuBpvfS/bxn6JaNrrXpna7cbavGjN27ox6PGYGF8yE7IyzZq32L7RLVeuc7wQ4hXBVFqTvBRW2xKEyZr5U6YmFOQs7Op+v1yy5/Mva7/Zb3LDWo4CFs9QgFqL2teMI1holzJWZZi2ACuUZMI3jvpEdU7z+F6WkxEp16FjOfczSGE3XxdlSVO3Lfa4b3g55ojMcJGN69hGeQVKyUw5233voFG98b/aCmYbngCU2ZZkjTvpTTspbVox22RsKO2mBtMLqZtauRIz4AFiYU1ymB3VobnXkSGherbB+0AlTvUB+dmWzPJz8/eQregUjEdCcJHFYdEvrVBKlcSOGEnYsrdFgX/z6XbU6QjCDNPOttozQc+scULV59500H1cnEAua3TSrYC4tZ0GXJKU4oD8wv/VFw17dQr0snZwpHlJytRiEZcIM8YURGk+aNKQYgX+fEipW1zfBFJShIoVoX9JLZljbvnZZTiC+/G9sqNrPKba4L0wbeisO6w7VmxbOe09A4X35+3T7NMXva7FRZV+sQgGOgz1p21DwdLxRldPOVIrHFBtHYGrrXgPdWLtjTRTCuE0G8C6jh5bMKz0L5C1T04m/IivNcQtGE2erhDGKqQoEDdOz4IjfZDnVMnCF8KjNwONittNPgJoTJ7UdmAm3Ja2D3EXrxE0TF3Zog4K9ZTskebLSW7Fr1oF81/N+yk3W8frekIf9nUj+sUOwlj3Al62cTU49naWKAroQLxkh5DU6YZXla+cvZWvaRP7tY12tzD0cgEq6dSBVssdKnAdHba3fVxJj7Yl94SvoBAYuA+yAUU57WoLine truncated
|
||||
U0VOQwFCLraZiofXGk3ma3rfAp+AwimbD2xmPARjOXLQKQDASKq6WUdAn5Xu24Z6rJgFAocX+aoaxr7aEcSFrlFujCdvGz8V8xc24n8bf5xsAEXkLEYouPry356TXt0FXr6hMN0uJvih1b0zJQI2g0NP0Nqjb6W3QsusKfvxJdVSWCC6fXd8YVGjqXIBBB0TnReajLcbE6innfSbpK9bPioIuychW0VEPtytUTo/+z8xxIwZphis8Wx4zVUUm2b6CZVgbh/Uhxq54dkicULYd58KfsBgRaUscASNvjwgw6ggjvo7R1Wj47xm0L0nSFDPoERuOomxW0lI4ib5wfJ+3j2hBoueX5dHVMpVaGOZpL7RLvJf0AbBE8kwCL4hLxjBuatt95R+sfCpxHXu8hga1AzFKa2gL/IE6nzq5GMC5UKJ9JIhjmM6GxekM3c5yh+AbBgUxfv4Fa2OnRzNBvICB+xJfDSP3G0lE+OwkenYURIzMrW+gS24NXJ12rzhlyhEp0iAvr6wGAskcTpe9nXShyL9M69FXmCJuNZdenQv8pPr9zuw0M5b6BdKG9Tcp8j1Qm4BBA8J22Vd0uF7D6ByjpKkknbPdQMh3A/s09qix7t20eP/OGTh1JBZkOXxbSt5N/mjYUeLXAzqCYN0c3GsX6Za45OU618l4PO+kC223EdAjD4dWbN1CW65uJY0m2XckZr+2p3f9ow00BHnfzIZVG+aMSicaIJdGGudWdABVCsb7zvFr/Pv2pRWZjSOtSh2OrIkFeobEuqOFra1ifRCn6Y2/LChsPJBUqDwV4qDNjFouWL1JR59XntCn/Vcn94S9HmeP1gFS0ceOWGDDnaocbqCF3RL6SW9PN7GZCORjiyYhVZn6i7gIBIvmlg8mqmYYAaTGm9abwB278V2UJEn/YD/Hbr2krnVZEoEG73pk+oFGDRiY+G+cA2bpWhVt0bXKluanQJV1UTby0/RhbGGjhFMr+dPqHLRoeuLbnYkvcvLbdjz3vRXRbJdO3GARy81hWjPEZnvEaT0SR0683uMsCzCz3pWqL8BMIN2GuMIIsn7D0lZwb5eKrDjEZIkyVZhYiwX1kSsjK+JfIweRvxRoa2fCZ20tP5alIozh6m+Q2eWyzdxyRqXCHZkd8kUUT+XbLj5cw9tl3oINfwRUFYxAPwq/bhJS3bpl5ElPdo/ZKOKQuHpjt2nLdyXDYjXtpY9nUMKDO5in/bkqzSnSM52Va++1vaaYBtZnYx0v1HFoPtepx34pwkX0yjKIqIsHOzQVNNAYL5cQlzATMNISYsmne8c8ioRRuK07nyHGZhLroVaxJ2fgL6VQVjlxWmyeI9b+tBf3fRGtYwP3SwS1B4SYySFZ70bNZyROaQdE8Rin8mH7Pw8WquuCEE+LR63KLdC0QnV3iAr8d4aJSsYlDjqMXMASgtqof/jKCE2KZtCR+T2DrnXMhvgsRVwZ18Iufd9clv8hxrEUYx8D0sP+Ao9LJYAWGJ0Kt7GSfdwDLaRjL4jkToeFIImwIZPDpckCsraOcWD+vuR+kuuOBCtSxN+rm9pZ1VulMAG0KkkpydTeNPlbRuLbgfmwk8o7QQnmjcWL96sLQszm0JnYlQDHLRfAmaBj7L4JbsiGhCe5+2SfIrfqDCZhUYF+OwILtwXbhBGl5DcbCeRUSz9NUrz3ywF8TZa8TgBM89PiJb/pvMNrE7m+SmDJugiQ6UWcoYD9eC/katecM+b7KLGBYpO5qFx2+QpJff/YRhmHpz5O8UjJVKJK+xLAbvyiVs44OL+yJ5MIq8TUB7ojZDaTkpuwLKeezycktpzUENMbona5GbjvSaJWmD97TgBgAY9iP38h6lOHzKh0Mda5aVSWVn1Rq1pJ3IsZBPSC9QQe/p4DItw5aXeiMQwdozY5j95qICXfxvfnZP/MSIAyj9SZWKhNIuCDvOUxDHj2h4EZ6X+sCBAvhQG4YFAIzPqS8nnUIdgBtbStZBkQoY+n+m8qPsaYf7QdWeGPRI2vcfcCXyR9DvePV6ER3sTI2GKUUr61peCejc+cBwIWvqacr7Xl5QqTgTXGYvgu/Sh3FMws9iEPNScfd9K/hRbqTpJv4CeDu4fyFwTzuP/BHRQuv5pqJvzHdmTppwAfqAmo5pAWig9WpglQc+rWmlJYAtUvF7SIop/uXcH3r0xmlMilpc4PDMzaw3gu6kLIec63jrS0+cX5CD0DjfuT9nSgsdR8plkFi7UwtIRGhFO3B0gCIG+frznPAFUpm5KtnjjG1jIKsAXcfB1ZViS7/yHVcC4FeO4XOOJyVZSAImWKJ7ljGtpjLCK8BtiqrCuf26wlj3iw9jMm8wS5f+G+INg7bFgnlNRfqId2EeYJ21q9rODCCLMf2DUjJmVEuqk/grPparL3OgIV579+RUhXMUechv3zwkSdk/w5zyKyCc4j6tbAERg2KJP3CEQnCrdUeqMSdy06/prdkHnByPAX+7tx3JzVjOPxv3L7FNmahhTW6lWSJX2IR2VRwsP1UL6kf4pPeT9T5Ou47mmRy3CP+JLFDYt+3cQs9qYry+Xz2MfTJnyNJb7vGfPaQv/rPfJZyOmlFhQSzXfGtAPVF8srKnUNgdX6EJsw08rDZQhr0pCcu92VkNvNigzDtxIb+u+WYNprGb+sJFT+rtPQbP5v9+akyBw1Op7+Kek+S1XgK4PF+29QiEHKfPq4pgYnO5BLaUvNJVEImZV4nXM1ve2+YRDjtxRB0f2zBau0CfI+QpSfAHPk/COZojZU5Pdd/IiVPttEaSo7dvlhINIbmvTmHIA/XcHuOERmTpIZycVumSeKhDXxnahJzEeWZwDoxIkxIhFM94hLH6rc13fcAUvo3T+jKt7d9k13rF6dw+rd63+Bq83bBDHFero8tZmWdQ0Tpnv231EbSwv4L16N7J7ALtvPbnyNWR5wWzN9bc2/xglGys4txTcBt32P/dBR8QsBQ26CISfoElUR+vWQyo+OTOMP9sXyWPN0q2jC+EA/j+xg0TT2dW7RtkpjLR9uEMZpvJSMYnep+HtWw+6fns+W8kTV8zjv9cwod0TOA+qLbd3VCaQr/TDImqHigciRLV4NCLOTWGYuZiWbHCfikIyG4HBJlRgFumVTlgGKsVPRtdx5gqZBvZqaE2CSAtESC/O7q6ocoGx7cyLEs5Oq9sp2JZQPfxyLTtfG77OdAsr4KFFwGvgjH1Laz6rqw+DL15Ysj/WTl7yJ6toQ0KaRVTUf+3pNhpyCsqfWOLy4A8bMWAoPTdvh4sN+lOgNmHfe5Wym/UfR/UTz6cDGSrQgbSN3PXFzzSBM/Lm77MRljbBbFp0qXJAsteajVeXJX2JVFhGhQ8TzAUL3jhblbY0psVHuBoW9oyQ+UREc5/fH9hbRSDVcCr/5BWnY3Og3YOESOhHFx+lNFT+v96QU5lkat8b80llUwM/aJ8t+tzK+nyKhQwGgXpek6hVwnDhAFuwGXbxaCJNR5XJWrvChcn+m/5TDEm/U7mRblkiwEBm+i3mBDEioH9vHcRTu7wB+FoR6Q0FJbr1tm2lG3tvBg05pEglHkXrz//3iH61NjH251++zW93BFzngQLoRRBcreFfdiEP6VoHsVC5cFjzcnymLEdUtBp/ihbDZ3Tzn72c0oOzV8td4lgDDzxlJLZglwqj2Yx0yJLAPUAG7hJCWk+NbvyDsYSLWxn+ywOMH2onyh3pnPV7S3nKuJ3k6o52gdLmBOM6kHZvDmyTl4yua5zABGr6UWSHlgtCS1BRs8bH+RV79irRp1F8LUl8C+aENK1OlvD37kRRrlbZlqUV0cFib1ItRy2I69E2H1MfjgPE8gwksVmvX/JSGR6GC1SOFEqRRaGQtVAgSNrZ9W+qVpevtsK7Eytg2HVo8ZmPifWRZe5YOawhE7fFaih0/4gEoegRa6hDGK+X0uWao+95Vgtf1DosETrxlICRbDZT6oyqqWjGrIHi4X3ZSAgXF7VsZ+EeYRLRbJ84H8l552PnjXXPufQkOP3o6fFJYCMEnqowtqRhTIl5stzBbHLWVmQ6UCKPlhUHePsjI5snYy8/zuw6HRxYY+p6odEi0sn31PXO3RCeRBMtNQ5xWhddJK2KX33Ygc+qXBLSe3LG1PcbTCCf1H+E8x06JM5tVGG1WsmZnEIBxCpQUZN3/fUe65B37QYyxBwZDFwxetjthnT2E4WR1INRVUgJySBYrgHJr9PJF84dAdyrbXJsh2TckR4rCRYpOC4Yf4p/GqQim69YA09EIHA+9PgywDyiZ3lSKYHwrLgGZliiJx0envl2YlL9udzPcLzpjGOLzwTj2vpOAe3cDgscYGLPSUK76yqS1cPCXfz+xpmrvVFgUxRSx5i/hj4TFQotyI9sTfHTSXBJBvywpxC2GMoZrTSR+4ksLv2kLatRtVGnUHSAA/Lx6fbFKQleOqN3sFn9exSQAo3EWEA1wT/Uep6uSBWAg12Laf8l9hgoIniThbqv3D1AgfRth3aXfY5sK0S7HQfwCfbMWr2HSU0JydhxufKFV3z6aV1fCpXAgkXoZ151Brrpgi4urtwgFWfD4Cvlrq1SXM8aW2F84EpvOkADhrEvpzf2ZJ8w7mOzZxZCxoQ3CbBhjHjyfnoPMUMldvYctLobZxOBUqfwxC2SlcCyQCvlRLDs+M6z/qONNOhg29pZK368WHEbzUNmevtq7cleE4MGk2NU88Br99YPFc0qaxY+xDSaZKFDhERe+2QRNY3jTC07aK8tfoChkK4uahAghWDImK50i3DCLnUI5TlOaxkOaujA40QtEmnt5CNQuLeSCKtduT4rmDn2zDdep+BCCJlS1lJfonIhtDl/fCUT1Zj4Q/JWOlwUJDs+3yalPC78fqWTgHrNOREN/o5VRkOegZDz36eE6sFr4cpKfjSdeeojMb8MMKAFRAJce3MR6HflkKqEpTyVPMkeB/u48Z2wANGcYDwhqzi9c54DDjbSh1Vw4BbkuxgFUgdREipn1NJLine truncated
|
||||
@@ -90,12 +90,12 @@ Both are cheap to enforce mechanically in the server's write path.
|
||||
```
|
||||
src/web-console/
|
||||
console.mjs CLI: open | post | wait | status | stop
|
||||
server.mjs the HTTP server (spawned detached by `open`)
|
||||
lib.mjs paths, atomic writes, patch merge, validate()
|
||||
server.mjs the HTTP server (spawned detached by `open`); routes.mjs lists its URLs
|
||||
files.mjs, sessions.mjs, patches.mjs, scan.mjs, ... paths, atomic writes, patch merge, validate(), the repo scan
|
||||
console.md the agent-facing contract
|
||||
public/index.html markup shell only
|
||||
public/app.js the client (no inline script, see CSP below)
|
||||
public/app.css
|
||||
public/app.js the client's entry (no inline script, see CSP below); screens/ and state.js hold the rest
|
||||
public/styles/ the stylesheet, joined by the server into /app.css
|
||||
public/render.js markdown tokens to DOM nodes
|
||||
public/vendor/marked.esm.js pinned 15.0.7, MIT, lexer only
|
||||
```
|
||||
@@ -223,7 +223,7 @@ Recovery matrix:
|
||||
}
|
||||
```
|
||||
|
||||
Note `recommended` is **optional per option**. Handoff explicitly wants its inferred task offered as the recommendation; the `.gitignore` question in handoff explicitly does not ("present it, don't force it").
|
||||
Note `recommended` is **optional per option**. Handoff explicitly wants its inferred task offered as the recommendation.
|
||||
|
||||
### 4.2 Primitives
|
||||
|
||||
@@ -308,7 +308,7 @@ Three panes, plus view tabs, closer to pathfinder's own vocabulary than to a gri
|
||||
|
||||
Built for a mixed product and engineering room reading one screen together.
|
||||
|
||||
- **One width variable.** `--card-width` on `:root` in `app.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 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` (`start-skill.mp3`, played once the dashboard's **Start** is accepted) 5, `bootup` 4, `sessionStart` / `sessionEnd` (`start-stop.mp3`) 3, `question` / `skillReady` / `chatReply` (`next.mp3`) 2, `newTab` (`insert.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<Event>` (`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 greys the boxes but keeps their ticks, and ticking a box plays it.
|
||||
- **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.
|
||||
|
||||
@@ -15,7 +15,8 @@ inside it, or add `--web` to a skill (`/plan2code-1-plan --web plan a lunch voti
|
||||
- **Tabs** show the document taking shape, the build progress and, always last, **Ask**, where you can
|
||||
put a quick question to the running agent.
|
||||
- **Sign-off** asks for your approval at the end of a phase. You can run the code review first from
|
||||
the same card.
|
||||
the same card, or press **Show me it working** to have the agent start the app and show you
|
||||
screenshots of the change right on the page.
|
||||
|
||||
**Where next.** [walkthrough.md](walkthrough.md) follows one feature from the first idea to the
|
||||
last phase. The rest of this file is the reference: every card, button and rule. Prefer the terminal?
|
||||
@@ -145,6 +146,9 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so
|
||||
- **Files in your notes.** Show instead of describe: attach a screenshot, a
|
||||
photo or a document to any note or quick question (see *Attachments in notes
|
||||
and questions* below).
|
||||
- **A notebook of your own.** One per project folder, in named tabs, for
|
||||
jottings and screenshots that are yours, not the agent's (see *Your notebook*
|
||||
below).
|
||||
- **A nudge when it might be waiting on you.** Your agent may stop in the
|
||||
terminal to ask permission for something, and the page cannot see that. So
|
||||
the dashboard and every starting screen carry a one-line tip about hands-off
|
||||
@@ -176,6 +180,8 @@ review has already reviewed the code, so its card has no review button.
|
||||
</picture>
|
||||
|
||||
The **Ask** tab is a chat beside the cards, for a quick question at any point.
|
||||
When a question is really a new task, the answer ends with a ready-to-paste
|
||||
prompt in a block with a Copy button, to take into a new conversation.
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/ask-dark.webp">
|
||||
@@ -194,12 +200,37 @@ A page opens with every skill laid out as cards — the setup pair, the pipeline
|
||||
in order, and the utilities alongside — with a note about what it made of your
|
||||
project (no AGENTS.md yet, a spec waiting on Phase 2) and a *Suggested* flag on
|
||||
the card it would pick. **Git** is among the utilities, always available: it opens
|
||||
the git board, with your branches, pull, push and commits on one page (Help's
|
||||
*The git board* topic walks through it), and asks before every push, publish and
|
||||
delete. In a folder that is not a git repository its card says *Not a git
|
||||
repository yet: it offers to start one*, and clicking it still works. Click
|
||||
one and Planny flies while it gets ready; a few seconds later the same page
|
||||
is that skill's console, already running. No command names to remember.
|
||||
the git board, three tabs — Changes, Branches and Sync — that open on the
|
||||
likely next step (Help's *The git board* topic walks through it), and asks
|
||||
before every push, publish and delete. In a folder that is not a git
|
||||
repository its card says *Not a git repository yet: it offers to start one*,
|
||||
and clicking it still works. **Codebase X-ray** is always available too: it
|
||||
explains how and why an area works, or ranks its rough spots into
|
||||
`specs/<name>/ARCHITECTURE-BRIEF-<date>.md`, and never changes code.
|
||||
**Diagnose a bug** sits beside it, also always
|
||||
available: it finds a bug's cause and writes it up as
|
||||
`specs/<bug-name>/DIAGNOSIS-<date>.md` without fixing it. Pick such a spec in
|
||||
the picker and it reads *Bug diagnosed*: Quick Task (suggested) and Plan light
|
||||
up, while Document, Implement, Implement + Review and Finalize stay greyed. Once
|
||||
Quick Task has fixed it, the folder reads *Bug fixed*: Quick Task offers to
|
||||
archive it to `specs--completed/`, and until then the picker never opens on it
|
||||
and hides it while *Hide unavailable workflows* is on. Its chip has a visible
|
||||
**Delete** button in place of the hover ✕ other specs carry, and one confirm
|
||||
removes the folder (any other spec also asks you to type its name). Click a card and Planny
|
||||
flies while it gets ready;
|
||||
a few seconds later the same page is that skill's console, already running. No
|
||||
command names to remember.
|
||||
|
||||
Handoffs this checkout has not picked up yet follow the specs in the picker as
|
||||
dashed **Handoff** chips, each with its title and age. Select one and the skill
|
||||
cards give way to a preview: when it was written, its spec, the skill it came
|
||||
from and its Next task. **Pick it up here** carries on in that skill and spec
|
||||
in this same session (Quick Task takes over, and says so, when the skill or
|
||||
spec is gone), and the chip is gone from the next dashboard. **Read it all**
|
||||
opens the whole document, **Copy for a new conversation** copies a one-line
|
||||
prompt that points a fresh conversation at the file, and **Delete** removes it
|
||||
for good after one confirm. Handoffs from *Stop with a handoff* (below) and
|
||||
from the Handoff skill land in the same place, `~/.plan2code/handoffs/`.
|
||||
|
||||
A freshly opened dashboard starts with Planny asleep in the middle of the page.
|
||||
Click to wake him: he snores once while he gets a gentle shake side to side,
|
||||
@@ -380,6 +411,48 @@ Pathfinder, the agent can hand independent pieces of work to helpers
|
||||
- **Pathfinder's research** always uses helpers, whatever the switch says, and
|
||||
they show in the tab too.
|
||||
|
||||
### Your notebook
|
||||
|
||||
The **Notebook** icon in the top bar, on the dashboard, every skill and the
|
||||
finished screen, opens a large dialog with a scratch pad for the folder you are
|
||||
working in.
|
||||
|
||||
- **Tabs.** A row of named tabs sits across the top, each with its own text and
|
||||
its own pictures. **+ New tab** asks for a name first (1 to 40 characters, no
|
||||
two the same in any case, up to 20 tabs), in a small dialog. There is no
|
||||
toolbar under the row: a double-click (or **F2**) on a tab renames it, the **x**
|
||||
beside its name deletes it (the **Delete** key does too), and tabs are moved
|
||||
only by dragging them. The tab you left open is the one you come back to.
|
||||
Delete opens a dialog that asks twice and takes the tab's text and pictures
|
||||
with it; with no tab left, the dialog asks you to make one. A notebook from before tabs opens
|
||||
as one tab called **Notes**.
|
||||
- **Markdown, styled as you type.** The editor shows Markdown in place:
|
||||
headings grow, bullets draw, bold, code, quotes and links take their look, and
|
||||
the marks come back on the line you are on. The text itself stays plain
|
||||
Markdown (saved as the tab's `note.md`, up to 1 MB).
|
||||
- **Pictures beside it.** Paste a screenshot, drop files on the dialog or press
|
||||
**Add image**: each becomes a thumbnail in a strip under the text (up to 200
|
||||
per tab). Click one for a full-screen preview (arrow keys step through, Esc
|
||||
closes); its **X** asks before it deletes.
|
||||
- **It saves itself**, about a second after you stop typing, when you close the
|
||||
dialog and before you switch tabs. If a tab's text cannot be saved, switching
|
||||
is refused ("Not saved yet, so staying on this tab") rather than losing it.
|
||||
If the connection drops, your text stays in the page and is retried, and the
|
||||
browser tab warns before you close it with something unsaved.
|
||||
- **One per folder, kept between sessions.** Every session started in the same
|
||||
folder (each git worktree counts as its own) opens the same notebook, in
|
||||
`~/.plan2code/notepads/<folder-name>-<12 hex>/`: `meta.json` (which folder it
|
||||
belongs to), `tabs.json` (the tabs, their order and the last one open) and one
|
||||
folder per tab, `tabs/<id>/`, holding its `note.md` and `images/`. Two pages
|
||||
open on one folder share it, and the last save wins.
|
||||
- **Private.** It never goes into your project, your session or anything the
|
||||
agent reads, so the agent never sees it. It stays on this machine.
|
||||
- **Removed only when you say.** No automatic cleanup touches it. Once the
|
||||
newest file in a notebook is 30 days old or more, *User Preferences →
|
||||
Cleanup* offers it as one item named after its folder's full path
|
||||
(*Notebook for /home/sam/code/shop*),
|
||||
and deleting it removes the whole notebook, every tab's text and pictures.
|
||||
|
||||
### Session meter
|
||||
|
||||
A small ring pill in the top bar — **Session: fresh** (green), **Session:
|
||||
@@ -455,6 +528,23 @@ A finished session says so, and ends in one of three shapes:
|
||||
- **Paused.** You pressed *Stop session*. The card names what was saved and
|
||||
gives the command that picks it up later. Nothing else is offered.
|
||||
|
||||
*Stop session* offers two ways to stop (on the dashboard, where nothing has
|
||||
started, it is a plain Stop). **Stop with a handoff**, the suggested one,
|
||||
saves your place as usual and also has the agent write a handoff: where the
|
||||
work stands and the next task, kept in `~/.plan2code/handoffs/` rather than in
|
||||
your project. The paused card names the file, and the dashboard offers it as a
|
||||
chip until it is picked up. **Just stop and save** saves your place and gives
|
||||
the resume command, nothing more; where the step has nothing saved yet it reads
|
||||
*Stop anyway*, under a warning about what is lost.
|
||||
|
||||
When the next step is another Plan2Code skill, the screen also has a
|
||||
**Continue here** button beside it: one press starts that skill in the same
|
||||
conversation, as a dashboard card would. It disappears once the session meter is
|
||||
red, when a fresh conversation is the better choice. A finished Quick Task or
|
||||
Finalize that ends on a commit can also offer **Update CHANGELOG first**, beside
|
||||
**Commit it now**: it opens Changelog right there, and Changelog's yes to
|
||||
*Commit this now?* carries on to Git.
|
||||
|
||||
The first two also carry a **Back to the dashboard** button (beside the next
|
||||
step, or as the main button under "All done"). Press it and the same page turns
|
||||
back into the skill menu, in the same conversation, so the next skill starts
|
||||
@@ -568,9 +658,19 @@ chimes once (if sounds are on).
|
||||
|
||||
When a newer Plan2Code release is out, the dashboard shows an **UPDATE
|
||||
AVAILABLE** banner at the top. Click it for the details: the version you
|
||||
have, the new one (linked to its Releases page) and the exact command that
|
||||
updates you, with a Copy button. **×** hides the banner for this session; the
|
||||
next dashboard shows it again until you update.
|
||||
have, the new one (linked to its Releases page) and the command that updates
|
||||
you, `plan2code update`, with a Copy button. It updates everything that was
|
||||
installed (the skills, the `plan2code` command and any extras you added), with
|
||||
no menu, and never uninstalls anything. If the `plan2code` command is not
|
||||
installed, the dialog also shows the install command,
|
||||
`npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git`, to run
|
||||
instead. **×** hides the banner for this session; the next dashboard shows it
|
||||
again until you update.
|
||||
|
||||
The `plan2code` command tells you too: before it starts your agent it prints
|
||||
one line, `Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`.
|
||||
It reads the same saved check, so it never waits on the network; when that
|
||||
check is missing or old, it refreshes it in the background for next time.
|
||||
|
||||
The check uses your own git login to read the repo's release tags, once an
|
||||
hour at most. If git cannot reach the repo (no git, no access, offline), you
|
||||
@@ -661,6 +761,8 @@ exception being the note attachments the agent keeps for a spec, above):
|
||||
| `~/.plan2code/console/sessions/<id>/` | the questions, your draft, your answers | 30 days after the session was last touched |
|
||||
| `~/.plan2code/console/sessions/<id>/workspace.json`, `ledger.ndjson`, `workspace-cursor.json` | the workspace's folders (paths, names, descriptions — never their contents), the session meter's events, and how far the agent has been told of workspace changes. Kept beside the session, so they outlive every dashboard hop | with the session |
|
||||
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
|
||||
| `~/.plan2code/handoffs/<id>.md`, `<id>.json` | each handoff's document, and which checkout, spec and skill it belongs to and whether it was picked up (`handoffs.mjs` is their one owner) | 30 days after it was last touched, picked up or not |
|
||||
| `~/.plan2code/notepads/<folder-name>-<12 hex>/` | your notebook for one folder: `meta.json`, `tabs.json` and, per tab, `tabs/<id>/note.md` and `tabs/<id>/images/` (`notepads.mjs` is their one owner; the agent never reads them) | until you delete it through Cleanup, which offers it once its newest file is 30 days old |
|
||||
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width | always |
|
||||
| `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always |
|
||||
| `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session |
|
||||
@@ -680,7 +782,8 @@ reads), `public/meter.js` and `public/mentions.js` (the `@name` popover) — and
|
||||
**Old sessions clean themselves up.** Each time a session opens, whole session
|
||||
folders nobody has touched for 30 days are deleted — questions, drafts,
|
||||
answers, uploads and all, paused or not — along with stray scratch files
|
||||
(`.json` / `.mjs`) left at the top of `~/.plan2code/console/` for as long.
|
||||
(`.json` / `.mjs`) left at the top of `~/.plan2code/console/` for as long, and
|
||||
handoffs in `~/.plan2code/handoffs/` untouched for as long, both files each.
|
||||
Your `looks.json` and the `console-dir` pointer are never touched, and neither
|
||||
is the session being opened. Nothing of value goes with them: the page is
|
||||
never the record, `specs/` in your project is.
|
||||
@@ -690,7 +793,11 @@ clean up** lists, with sizes, everything in `~/.plan2code/` that is not
|
||||
needed: sessions untouched for 30 days (never the one you are in), anything at
|
||||
the top of `~/.plan2code/console/` other than `sessions/`, `looks.json`,
|
||||
`workspaces.json`, `subagents.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` other than
|
||||
`console/`, `bin/`, `launcher.json` and `models.json`. It also lists each
|
||||
`console/`, `bin/`, `launcher.json`, `install.json` (what you installed, which
|
||||
`plan2code update` reads), `models.json`, `handoffs/` (old handoffs go by
|
||||
age, above) and `notepads/`. Each notebook whose newest file is 30 days old or
|
||||
more is listed as one item, *Notebook for* its folder, and goes whole; no
|
||||
automatic sweep ever removes one. It also lists each
|
||||
folder in the project's `specs--completed/` whose newest file is more than 30
|
||||
days old: archived specs Finalize moved there. Deleting one is permanent:
|
||||
`specs--completed/` is usually gitignored, so git can't restore it. A stray is listed once
|
||||
@@ -729,7 +836,7 @@ this:
|
||||
|
||||
### Routes
|
||||
|
||||
The upload routes, the send, the overview read and the workspace. Like every page route, they are on `127.0.0.1`
|
||||
The upload routes, the send, the overview and handoff reads, the workspace and the notebook. Like every page route, they are on `127.0.0.1`
|
||||
behind the session cookie, and the ones that write also check the request's
|
||||
origin.
|
||||
|
||||
@@ -742,25 +849,37 @@ origin.
|
||||
| `POST /chat` | A Quick question `{ text, about?, images?, files?, conversation }`, or `{ reset: true, conversation }` for New conversation. Appended to the session's `chat.ndjson`. 400 `too-long` (over 4,000 characters), `image`, `file` or `bad`; 409 `offline`, `stale` or `limit` (10 per conversation). Never refused because a card send is still uncollected. |
|
||||
| `POST /chat/decision` | Approve or Decline on an edit the agent proposed: `{ re, decision, text?, conversation }`. Once per proposal; does not count toward the 10. |
|
||||
| `GET /overview?spec=specs/<name>` | The Overview tab's read of `<spec>/overview.md`, as `text/markdown` with `cache-control: no-store`. On the dashboard `spec` must be one of the scanned specs; elsewhere the session's own spec is used. The file's real path must stay inside the project, so `../`, absolute paths and symlinks pointing out all get 404. |
|
||||
| `GET /handoff?id=<id>` | *Read it all*: the handoff's `.md` from `~/.plan2code/handoffs/`, as `text/markdown` with `cache-control: no-store`. A dashboard only, and only an id its own scan listed: a used, unknown or malformed id is 404. |
|
||||
| `GET /workspace` | The Workspace dialog's list: folders, `missing`, `remote` and the agent's folder `issues`. `?check=1` re-checks every folder on disk first. |
|
||||
| `POST /workspace/add` | `{ path, name?, description? }`. The path is resolved against the folder the session started in (`~` expanded) and must be a folder: 400 `not-a-folder`, `duplicate` (with its `name`; compared case-insensitively on Windows and macOS), `bad-name`, or `name-taken` with a `suggest`. Answers the new entry, `nested: true` when it sits inside another folder in the list. |
|
||||
| `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. |
|
||||
| `POST /workspace/remove` | `{ id }`. 400 `original` for the folder the session started in, 404 `unknown`. |
|
||||
| `POST /workspace/browse` | Opens the system folder picker and answers `{ path }` or `{ cancelled: true }`; never adds anything itself. 409 `busy` while one is open, 404 `no-picker` when the session looks remote or no picker exists. |
|
||||
| `GET /notepad[?tab=<id>]` | The notepad for the folder this session runs in: `{ tabs: [{ id, name }], last, tab: { id, text, savedAt, images: [{ id, url, thumb }] } | null }`, with the tab's `text`, `savedAt` and `images` repeated at the top. Without `tab` it answers the last one used; 404 `no-such-tab` for an id it does not have. A notepad in the first shape answers one virtual tab, Notes. Reading never creates or moves a file. |
|
||||
| `POST /notepad/text?tab=<id>` | `{ text }`. Saves that tab's `note.md` and answers `{ ok, savedAt }`; 400 `bad`, 404 `no-such-tab`, 413 `too-long` (over 1 MB). |
|
||||
| `POST /notepad/image?tab=<id>` | Raw `image/jpeg` (the page re-encodes every picture first). Writes the tab's `images/<uuid>.jpg` and answers `{ ok, id, url }`; 415 `not-jpeg`, 413 `too-large` (over 4 MB), 409 `too-many` (200 pictures in the tab). |
|
||||
| `POST /notepad/thumb?id=<uuid>&tab=<id>` | Raw `image/jpeg`: that picture's thumbnail. 404 `not-found` or `no-such-tab`, 415 `not-jpeg`, 413 `too-large`. |
|
||||
| `POST /notepad/image/delete?tab=<id>` | `{ id }`. Deletes a picture and its thumbnail; 404 `not-found` or `no-such-tab`. |
|
||||
| `POST /notepad/tab` | `{ name }`. Makes a tab, which becomes the last one used, and answers `{ ok, id, name }`; 400 `bad-name`, 409 `duplicate-name` (any case) or `too-many-tabs` (20). |
|
||||
| `POST /notepad/tab/rename` | `{ id, name }`. Answers `{ ok, id, name }`; 400 `bad-name`, 404 `no-such-tab`, 409 `duplicate-name`. |
|
||||
| `POST /notepad/tab/delete` | `{ id }`. Removes the tab from the index, then its folder (text and pictures); 404 `no-such-tab`. |
|
||||
| `POST /notepad/tab/order` | `{ order: [id] }`, every current id exactly once; 400 `bad` otherwise. |
|
||||
| `POST /notepad/tab/last` | `{ id }`. Remembers the open tab; 404 `no-such-tab`. |
|
||||
| `GET /notepad/images/<tab>/<uuid>.jpg`, `<uuid>.thumb.jpg` | Serves a picture or its thumbnail as `image/jpeg`, only by a tab id and a UUID name, a regular file (never a link) whose real path stays inside `~/.plan2code/notepads/`; anything else is 404. |
|
||||
| `POST /subagents` | `{ on, instruction, max }` (`instruction: null` for the shipped default). Saves the switch for this project and skill and answers `{ ok, setting }`; 400 `not-offered` on a skill without the switch, `bad`, `too-long` (over 2,000 characters) or `max` (outside 1 to 20). |
|
||||
|
||||
## For maintainers
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Source | `src/web-console/` |
|
||||
| Source | `src/web-console/` (one row per file in the files table of `.agents-docs/AGENTS-architecture.md`; a test keeps it complete) |
|
||||
| Ships as | `skills/<every skill>/references/web-console/` |
|
||||
| Wiring | one `additionalReferences` entry per skill in `install.js`; the dashboard's menu lives in `public/answers.js` (`SKILL_CATALOG`) |
|
||||
| Wiring | one `additionalReferences` entry per skill in `install.js`; the dashboard's menu lives in `public/skills.js` (each entry's `card`; `SKILL_CATALOG` in `public/answers.js` is a lookup on it) |
|
||||
| Agent contract | `src/web-console/console.md` (read once), its topic files (`console-*.md`), `notes/<workflow>.md`, and `building.md` / `building-review.md` for the builds; `console.mjs help <topic>` prints any of them |
|
||||
| Tests | `node --test scripts/test-web-console-*.mjs` (split by area, shared setup in `scripts/web-console-test-helpers.mjs`), also run by `npm test` |
|
||||
| Start-up benchmark | `node scripts/bench-web-console.mjs` (needs `puppeteer-core` and a local Chrome or Edge for the paint columns; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) |
|
||||
| Screenshots | `node scripts/capture-screenshots.mjs` (needs `puppeteer-core` and a local Chrome or Edge) |
|
||||
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only |
|
||||
| Start-up benchmark | `node scripts/bench-web-console.mjs` (needs a local Chrome or Edge for the paint columns, driven through `playwright-core` from `npm install`; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) |
|
||||
| Screenshots | `node scripts/capture-screenshots.mjs` (needs a local Chrome or Edge, driven through `playwright-core` from `npm install`; `PLAN2CODE_TEST_BROWSER=chrome|msedge` forces one) |
|
||||
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only, and CodeMirror 6 (MIT) for the notebook's editor as one bundled file, `public/vendor/codemirror.esm.js`, made by the dev-only `node scripts/vendor-codemirror.mjs` from a pinned lock (about 500 KB, loaded only when the Notebook is first opened); the page's policy blocks the `<style>` element CodeMirror writes, so the editor lives in a shadow root where it adopts its rules as a constructed stylesheet (steps in the architecture doc's Notebook point) |
|
||||
|
||||
Edit `src/` only. `skills/` is a committed build artifact: regenerate it with
|
||||
`npm run build:skills` and commit it with the source change, since `npm test`
|
||||
@@ -832,7 +951,6 @@ after any change a person would see on the page: a new layout, a renamed
|
||||
button, a different colour.
|
||||
|
||||
```bash
|
||||
npm i --no-save puppeteer-core # once; never added to package.json
|
||||
node scripts/capture-screenshots.mjs # every screen
|
||||
node scripts/capture-screenshots.mjs --only dashboard # one screen
|
||||
```
|
||||
|
||||
@@ -42,8 +42,7 @@ Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line
|
||||
|
||||
## Web Console
|
||||
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. 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 (branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), a built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) 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`); 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`). The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
|
||||
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. 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`, never shown to the agent, removed only through Cleanup once a month untouched), a built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) 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`); 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 read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
|
||||
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
|
||||
|
||||
## Skill Scripts
|
||||
@@ -68,7 +67,7 @@ Details: [Code Style & Gotchas](./.agents-docs/AGENTS-code-style.md)
|
||||
|
||||
The project has a mascot called "Planny": a box with a star for an eye, stick arms and two small feet. He appears in installer output, workflow prompts, the loop, the Claude Code status line (box, star and feet, no arms) and the web console. ASCII variants are defined in the `MASCOT` constant in `install.js` (and `plan2code-loop/src/utils/logger.ts`) and appear in workflow markdown files: arms down at rest, one arm waving when he is asking something, both arms up when he is celebrating. The eye is always the star.
|
||||
|
||||
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight colour and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `app.js` switches mood with a single class, so the drawing stays in the markup and the styling in `app.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
|
||||
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight colour and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `screens/core.js` switches mood with a single class, so the drawing stays in the markup and the styling in `styles/planny.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
|
||||
|
||||
```
|
||||
╭───╮
|
||||
@@ -87,6 +86,9 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
2. Keep it specific to this repo. General advice belongs nowhere.
|
||||
3. If this fix is a workflow rather than a rule, put it in `.claude/skills/` and link it from here.
|
||||
4. Include the change in the same commit and mention it in your summary.
|
||||
5. A skill rule broken twice becomes a script check (a `scripts/` test or a skill-script check), not more prose.
|
||||
6. Before adding a line, look for one on the same topic: sharpen or extend that one rather than adding a near-duplicate.
|
||||
7. Keep the log to 17 entries at most. Over the cap, first merge entries that share a cause, then drop the lowest-value ones: one-offs unlikely to recur, rules a test or script now enforces, and entries about code that no longer exists.
|
||||
|
||||
## Failure log
|
||||
|
||||
@@ -94,8 +96,13 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
- Sync upstream only through `/sync-repo`, and verify its baseline against the real tree before porting: an earlier sync silently skipped a whole upstream release (the `3-implement-review` skill) while the recorded version froze. Update the baseline with `.claude/skills/sync-repo/set-synced.mjs`, never with a shell pipe over the decrypted body.
|
||||
- After a sync merge, run `npm test` before trusting a "clean" file: when upstream and plan2code fixed the same bug, `git merge-file` keeps both copies without a conflict (a sync once left `let pattern` declared twice in `app.js`, caught only by `parse-check`).
|
||||
- When extracting upstream files in Git Bash, run `git show <ref>:<path>` with `MSYS_NO_PATHCONV=1` and `C:/` style paths (never `/c/`): path conversion rewrites `origin/main:.readme/x.md` into `origin\main;.readme\x.md`, the show fails, and the merge silently runs against an empty "theirs". Check every extracted file is non-empty before merging.
|
||||
- After a sync, grep the result for the upstream owner slug and company name in any case (the `/sync-repo` body lists them): the rebrand map only rewrites URLs, so a bare owner slug once slipped through into `feedback-payload.mjs` (and its test) until it was fixed by hand to `jparkerweb/plan2code`. No upstream name may appear in plain text anywhere in this repo.
|
||||
- After a sync, grep the result for every upstream name the rebrand map can miss (the `/sync-repo` body lists them): the owner slug and company name in any case, the bare brand word inside identifiers and fixtures, and the ticket key followed by anything, not only digits. Each slipped through once: an owner slug in `feedback-payload.mjs` and its test (fixed by hand to `jparkerweb/plan2code`); in v2.7.0 a `KEPT_<BRAND>_ENTRIES` constant, a `<brand>Dir` option, a `"<brand>"` test folder and an owner slug in a git remote URL; in v2.8.0 git board fixtures built as `` `feature/<KEY>-${11000 + i}-…` `` template literals, which a digits-only rewrite to `ABC-<n>` misses. No upstream name may appear in plain text anywhere in this repo.
|
||||
- Keep plan2code's ticket-free `commit-msg.mjs` (`<subject>`, `AI Assisted`) in every `/sync-repo`: upstream's ticket-from-branch rule was ported by mistake once and removed in v2.6.0.
|
||||
- When a new first-run dialog is added to the web console, set its seen flag in `scripts/capture-screenshots.mjs`'s `looks.json` too: the Welcome dialog once covered the regenerated dashboard screenshots until `welcomeSeen: true` was added.
|
||||
- After a sync, grep for the upstream brand word on its own too, not only the full product name: the rebrand map misses a bare brand word inside identifiers and fixtures (a `KEPT_<BRAND>_ENTRIES` constant, a `<brand>Dir` option, a `"<brand>"` test folder, an owner slug in a git remote URL), and v2.7.0's sync let all four through until the residual grep caught them.
|
||||
- Import `scripts/skill-script-helpers.mjs` in any test that builds git fixtures for a skill script or `git-repo.mjs`: it scrubs the whole test process's git config, so fixtures, imported modules and spawned scripts agree. Mixed configs broke `git plan switch` once (a global `core.autocrlf=true` checked fixtures out with CRLF the scrubbed script read as changed).
|
||||
- Before deleting a test file that upstream split or removed, diff plan2code's copy against the rebranded upstream base and port the plan2code-only tests: v2.7.0's split of the web console suite would otherwise have dropped seven hardening tests (now in `scripts/test-web-console-hardening.mjs`).
|
||||
- Register a new skill in `install.js` `SOURCE_PROMPTS` before running its `scripts/test-script-<name>.mjs`: importing `scripts/skill-script-helpers.mjs` rebuilds `skills/` and prunes any skill folder `install.js` does not list, so the script under test vanishes.
|
||||
- When a `CHANGELOG.md` heading gets a version number, set the same number in `version.json` (with its `releaseDate`), the root `package.json` and README's `Version X.Y.Z` line in the same change, then run `npm run build:skills`. The changelog skill only touches `package.json`: v2.9.0 nearly shipped with `version.json` at 2.8.1, and README's line sat at 2.6.0 for three releases.
|
||||
- When `npm test` fails only timing-bound suites (the chat stress test, the page-cards redraw test "a redraw keeps the place of...", then a cascade in the session suite starting at "no submitted frame within 5s") while the machine is busy, rerun those files alone, and the `node --test` list with `--test-concurrency=4`, before suspecting the change: they failed that way on untouched code under load during the web console file split, and the redraw test did again in three phases of web-console-health. In web-console-notepad, four more failed only in full runs and passed alone: the Workspace page's @-mention test, the dashboard page's handoff chip test, the session suite's document route (`connect ETIMEDOUT`) and the notepad page's 200 KB typing test (why its budget there is 200 ms, not the 92 ms it takes alone).
|
||||
- Post a helper as `done` or `failed` in the same turn its completion notice arrives: its row stays `running` on the Subagents tab until a post says otherwise (a build once reached its sign-off with one row spinning). A `finish` is now refused while any helper is `running`.
|
||||
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
|
||||
@@ -2,6 +2,121 @@
|
||||
|
||||
All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
## v2.11.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **web console**: the Notebook has named **tabs**. Each tab is its own Markdown note with its own pictures, kept in its own folder under the notebook's (`tabs/<id>/note.md` and `images/`, with a `tabs.json` index). **+ New tab** asks for a name (1 to 40 characters, no two alike in any case, up to 20 tabs). A tab can be renamed (button, double-click or F2), reordered (drag, Move left and Move right, or Alt with the arrow keys) and deleted, which asks twice and removes its text and pictures. The tab left open is the one that opens next, and with no tab left the dialog offers to make one. Saves and pictures are bound to the tab they were made in, so switching never moves either; a switch that cannot save first stays put and says why.
|
||||
- **web console**: five routes (`POST /notepad/tab`, `/tab/rename`, `/tab/delete`, `/tab/order`, `/tab/last`), `?tab=` on the text and picture routes, and picture addresses that carry the tab (`/notepad/images/<tab>/<uuid>.jpg`).
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **web console**: the Notepad is now called the **Notebook** (the icon is unchanged), in the top bar, the dialog, the Help, the docs and the screenshots. Code names, routes and the `~/.plan2code/notepads/` folder keep their names, so nothing already saved moves. The dialog's line about it being never shared to the AI Agent is bold, in the highlight color.
|
||||
- **web console**: every document tab and the Overview has a **Back to Questions** button (Dashboard or Git on those screens) left of Print and Download, with a highlight border, and that header row stays at the top of the pane while the document scrolls.
|
||||
- **web console**: the Notebook editor is now CodeMirror 6 with live in-place Markdown: headings grow, bullets draw and the marks come back on the line the cursor is on. It replaces OverType after a spike showed typing in a 200 KB note about four times faster. The editor ships as one vendored file loaded only when the Notebook first opens, and runs in a shadow root so the page's content-security policy stays as strict as before.
|
||||
- **web console**: an existing notebook opens as one tab called **Notes**. Reading it writes nothing; the first edit moves the note and pictures into the tab, and a crash part way is finished by the next write.
|
||||
- **contributors**: `scripts/vendor-codemirror.mjs` and its lock file build the editor bundle reproducibly; the OverType vendor script, its CSS and its page helpers are gone.
|
||||
|
||||
## v2.10.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **web console**: a private **Notepad** in the top bar, on every screen. It opens a modal with a Markdown editor that styles as you type (OverType 2.6.1, vendored, MIT) and saves as you go, with pictures: paste, drag and drop or **Add image**, each shrunk to JPEG in the browser, shown as a thumbnail strip with an X that asks before deleting, and a full-screen preview. There is one notepad per project folder, kept in `~/.plan2code/notepads/` (`notepads.mjs`) and never shown to the agent. User Preferences → Cleanup offers a notepad for removal only when its newest file is 30 days old or more, as one item that removes the whole folder; the automatic sweep at open never touches it.
|
||||
|
||||
- **web console**: a finished screen whose next step is a Plan2Code skill has a **Continue here** button beside the Next step block. One press starts that skill in the same session, as a dashboard card would, on a clean page. It is hidden when the session meter is red (a fresh conversation is the better choice), on a pause and for a git command. The page does it alone: the agent only handles the `__launch` the dashboard already sends, and posts `finish: null` first when the next step is the same skill (Implement to Implement).
|
||||
- **web console**: a finished Quick Task or Finalize can offer **Update CHANGELOG first** beside **Commit it now** (`finish.changelog: true`, refused on any other workflow). It hops into Changelog in the same session, and Changelog's yes to *Commit this now?* carries on to Git. The press arrives as `__changelog`.
|
||||
- **web console**: the Ask contract (`console-chat.md`, *Prompts to carry away*) tells the agent to answer a new-task question, or a request for a prompt, with the explanation and one self-contained prompt in a fenced block. The page already gave every fenced block a Copy button, so there is no page change.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **web console**: the dashboard has one Implement card instead of Implement and Implement + Review. Its confirm pane has a Review checkbox, ticked by default, that launches Implement + Review when ticked and plain Implement when not; the command shown follows the box.
|
||||
- **web console**: `open` and `handoff new` refuse a `--workflow` the console does not know (exit 2, naming the valid ones), instead of opening a session no skill answers. `open` with no `--workflow` still opens Pathfinder.
|
||||
- **web console**: Help's list of dashboard cards is built from the cards themselves, so it can never name a card the dashboard lacks: it follows the dashboard's order (Handoff last under *Useful any time*), and X-ray's line is its card's.
|
||||
- **web console**: a hop into Git from any skill now starts the page clean on both sides. The server always cleared it; the page kept the last skill's tab and staged answers.
|
||||
- **contributors**: the per-skill tables that were still kept by hand now come from `public/skills.js`: the meter's weights and labels (`WEIGHTS`, `LAUNCH_LABELS`, `RUN_LABELS` in `meter.js`), `resumeCommand()`'s switch in `answers.js`, Help's card list in `index.html` (now filled by `buildHelp()` in `screens/help-dialog.js`) and `cmd-help.mjs`'s workflow list. Each entry gains `weight`, `started`, `ran`, `resume` and an optional `card.help`, and `skills.js` exports `WORKFLOWS` and `isWorkflow()`. A test fails, naming the file and the name, when `console.md`, `src/plan2code.md` or the CLI's help drift from the list.
|
||||
- **contributors**: two new shared modules. `src/web-console/spec-files.mjs` holds the task markers and the task-line, checkbox and Status-line patterns with `statusOf()` and `countTasks()`, read by `scan.mjs` and the `specs.mjs` skill script, which no longer keep copies of their own; `patches.mjs` now takes `TASK_LINE_RE` from it instead of from `scan.mjs`. `src/web-console/public/hops.js` holds `startsClean()`, the rule for which hops start the page clean, called by `cmd-open.mjs`, `server.mjs` and `screens/core.js`.
|
||||
- **contributors**: for the upstream port, these moved: the meter tables, `resumeCommand()`'s switch, Help's card markup and `cmd-help`'s workflow list into `skills.js` fields; the markers and patterns in `scan.mjs` and `specs.mjs` into `spec-files.mjs` (and `TASK_LINE_RE` tightened on the way: exactly one space before the box and a case-sensitive `Task`, matching `TASK_ID_RE`; keep that when porting); the hop test in `cmd-open.mjs`, `server.mjs` and `screens/core.js` into `hops.js`. Port upstream's changes to those tables into `skills.js` and the two modules, not back into the old files.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web console**: Workspace's Browse… folder picker (and the launcher's) no longer opens behind the browser on Windows. Windows refused the picker's `SetForegroundWindow`, because the picker is spawned by the detached console server and is not the process that last had input; the existing topmost flag is ignored by that dialog. It now waits until the dialog is visible, taps Alt (which lifts the foreground lock for the next call), and takes the foreground.
|
||||
- **dashboard**: an assumed task (`[?]`) counts as done and is named in the spec's line ("3 of 4 tasks done, 1 assumed"). It used to be left out of the count altogether, so that phase read "2 of 3 tasks done", and a spec whose tasks were all assumed read as not started. Numbered task lines (`1. [x] **Task ...`) count too, on the dashboard and in the `specs.mjs` skill script.
|
||||
|
||||
## v2.9.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **building habits**: Quick Task, Implement and Implement + Review now read one shared reference file, `references/building-habits.md`, at three moments. When a bug or an unexpected failing test turns up, they find the cause first: build a command that fails on the bug before changing code (or say why they cannot, rank their guesses with the evidence and let you decide), then keep the reproduction as a regression test in the project's existing test runner. When the plan asks for it, they build test first: write the test, see it fail for the right reason, then write the code. Before a restructure meant to change no behaviour, they pin the behaviour with tests that must pass unchanged afterwards. Adapted from Matt Pocock's [`diagnose`, `tdd` and `improve-codebase-architecture`](https://github.com/mattpocock/skills) skills and pstack's debugging playbook (both MIT).
|
||||
- **plan**: the testing question gains a fourth choice, **Approach**: code first (the default) or test first. Test first is recorded in the PLAN-DRAFT's Testing Strategy table, and Document then orders each task's test before its code with a `Test:` line under the task naming where the test drives the behaviour.
|
||||
- **review**: reviews run in a fresh helper that never saw the build; reports say how they ran. Wherever the tool can start a helper and the web console's Subagents switch is not off, every review (`/plan2code-review`, Implement + Review's Stage 2, Implement's "review" at sign-off and Quick Task's "Review it now") hands its analysis to one helper briefed only with the spec and the change set (the new `references/reviewer-brief.md`). The main session checks every finding in the source before you see it and drops what it cannot confirm. Each report carries a **Reviewed by** line: a fresh helper (with how many findings were checked and dropped), or this session, said once as not independent. Adapted from pstack's independent reviewer and Matt Pocock's [`code-review`](https://github.com/mattpocock/skills) guidance (both MIT).
|
||||
- **xray**: a new skill, **Codebase X-ray** (`/plan2code-xray`), on the dashboard under *Useful any time*. Explain an area: how it works and why it is that way, citing files and the commits and pull requests behind it (git history always, `gh` when it is installed and signed in, and it says once which sources it could not use). Or find the rough spots: files that always change together, thin wrappers, tangled boundaries and busy code with no tests, ranked with a concrete "to change X today you must touch..." example each. You tick the ones worth fixing and only those go into `specs/<name>/ARCHITECTURE-BRIEF-<date>.md`, ready for Pathfinder or Plan. A new script, `xray.mjs`, does the counting from git history. Pathfinder and Plan point at it when the code is unfamiliar. Adapted from Matt Pocock's [`improve-codebase-architecture`](https://github.com/mattpocock/skills) skill (MIT) and pstack's codebase survey, `how` and `why`.
|
||||
- **diagnose**: a new skill, **Diagnose a bug** (`/plan2code-diagnose`), on the dashboard under *Useful any time*. It finds a bug's cause and writes it up without fixing it, under the find-the-cause-first habit: a command that fails on the bug first (or, when it cannot build one, its guesses ranked with the evidence), then the cause in `specs/<bug-name>/DIAGNOSIS-<date>.md`. It then offers `/plan2code-quick-task` to fix it, or `/plan2code-1-plan` when the fix is big. The dashboard shows such a folder as a new spec state, **Bug diagnosed**, which lights Quick Task (suggested) and Plan and keeps Document, Implement, Implement + Review and Finalize greyed. Adapted from Matt Pocock's [`diagnose`](https://github.com/mattpocock/skills) skill and pstack's debugging playbook (both MIT).
|
||||
- **quick-task**: asks "Write the test first?" when the change alters behaviour and the project already has a test runner, and names the test spot in the plan's Verify section. A bug fix starts with its reproduction.
|
||||
- **show me it working**: Implement, Implement + Review, Quick Task and Finalize offer to show the change running before you approve, never required: reply `show me` in the terminal, or press **Show me it working** on the web console. The agent starts the app the way `AGENTS.md` says (working it out from the project and offering the line for `AGENTS.md` when it is missing, or asking you), looks at the change, stops what it started and records one line saying what was run and what was seen. Screenshots appear on the page only, never under `specs/`. Init and Init Update now ask how to start the app and where to view it. Adapted from pstack's proof-on-the-running-app idea (MIT).
|
||||
- **web console**: a doc can show a picture. An image block (`"image": "shots/<name>.png"`) shows a PNG, JPEG or WebP the agent saved under the session's `shots/` folder; anything outside that folder, over 5 MB or not really an image is refused.
|
||||
- **launcher**: `plan2code update` updates everything that was installed (the skills, the `plan2code` command and any of the status line, `plan2code-loop`, `plan2code-metrics` and `plan2code-bot`), with no menu and never uninstalling. Every global install now writes `~/.plan2code/install.json` listing what it installed, which `install.js --update` reads; with no record it updates the skills and the `plan2code` command.
|
||||
- **launcher**: `plan2code` prints one line before it starts your agent when a newer release is out: `Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`. It reads the web console's saved release check, so it never waits on the network; when that check is missing or old it refreshes it in the background for the next start.
|
||||
- **web console**: **Stop session** gains a second way to stop, **Stop with a handoff**. It saves the skill's place as before and also writes a Handoff document, so a quick task, a review or a half-done changelog keeps its context; the paused screen names the file.
|
||||
- **dashboard**: this checkout's unused handoffs show as chips in the spec picker. **Pick it up here** carries on in the skill that stopped (a handoff from the Handoff skill carries on in Quick Task), in the same session, and the chip is gone afterwards; **Read it all**, **Copy for a new conversation** and **Delete** sit beside it.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **implement**, **quick-task**, **plan**, **document**: tightened as they took on the habits, so each stays well under 15,000 characters.
|
||||
- **pathfinder**: tightened to stay under 15,000 characters as it took on the X-ray pointer.
|
||||
- **quick-task**, **implement**: when the cause is unclear or the fix big, they stop and suggest `/plan2code-diagnose`.
|
||||
- **finalize**: its archive confirmation now reads "yes / no / show me", the last chance to look at the whole feature running before the spec moves.
|
||||
- **dashboard**: Handoff is now the last card in *Useful any time*, after Git.
|
||||
- **contributors**: the add-a-skill checklist in `.agents-docs/AGENTS-development-commands.md` now lists every place a new skill must be registered (it missed about a dozen).
|
||||
- **contributors**: `AGENTS.md` gains a rule that a skill rule broken twice becomes a script check, not more prose.
|
||||
- **web console**: the UPDATE AVAILABLE dialog now gives `plan2code update` as the command, keeping the install command beside it for a machine without the `plan2code` command. User Preferences → Cleanup never lists `~/.plan2code/install.json`.
|
||||
- **docs**: README, the quick reference and the web console guide say to update with `plan2code update` (or re-run the install command).
|
||||
- **handoff**: every handoff now lives in `~/.plan2code/handoffs/` (a Markdown file plus a small `.json` beside it), owned by the web console, and handoffs older than 30 days are swept when the console opens. The Handoff skill writes there with no folder or `.gitignore` question, and Cleanup never lists the folder. Handoffs written to the OS temp folder or a `handoffs/` folder before this change are not listed.
|
||||
- **dashboard**: a **Bug fixed** spec has a visible **Delete** that needs one confirm, and its chip no longer repeats the "bug fixed" line.
|
||||
- **web console**: the review sign-off card lists **Approve this phase** before **Show me it working**, with the approve button outlined in the accent colour.
|
||||
- **web console**: a sign-off's **yes** button (Quick Task's **Build it**, Finalize's **Archive it**) is outlined in your highlight colour too, like **Approve**. So is the yes of a yes/no question (such as Plan's **Write the plan**) and a recap's **Yes, that is right**, except on a question marked dangerous, whose yes stays red.
|
||||
- **web console**: **Skip this one** (and **Do not skip**) on an optional question is a small button in your highlight colour, like a comment box's **No changes**, instead of an underlined link.
|
||||
- **init**, **init-update**: the *Keeping this file current* section they write into `AGENTS.md` gains three rules: a rule broken twice becomes an automated check, a new Failure log line first looks for one on the same topic to sharpen instead, and the log holds 17 entries at most (over the cap, merge entries that share a cause, then drop the lowest-value ones). Init update offers the missing rules to an existing section and tidies the log on every run, showing each merge and removal for a yes before it writes.
|
||||
- **contributors**: this repo's `AGENTS.md` follows the same Failure log rules, and its three post-sync grep entries are merged into one.
|
||||
- **contributors**: the web console's source is split by job: `lib.mjs`, `server.mjs`, `console.mjs`, `app.js` and `app.css` become `routes.mjs`, `static.mjs`, `cmd-*.mjs`, the by-job Node files, `public/screens/` and `public/styles/`. Nothing a person sees changes, and the page starts faster (ready in about 280 ms, was 450 ms).
|
||||
- **contributors**: the per-skill and per-spec-state tables live in two data files, `public/skills.js` and `public/spec-states.js`, so adding a skill or a state is a short list in `.agents-docs/AGENTS-development-commands.md` and `npm test` names anything missed. This replaces the long add-a-skill checklist noted above.
|
||||
- **contributors**: page tests drive the real console in Chrome or Edge through `playwright-core` inside `npm test` (running it needs Node 20 or newer; installed skills still need only Node 18). The screenshot and speed scripts use it too, with no hand install, and `scripts/css-snapshot.mjs` compares every computed style across a stylesheet change.
|
||||
- **contributors**: a test keeps the files table in `.agents-docs/AGENTS-architecture.md` complete: every console file needs a one-line row.
|
||||
- **contributors**: `post` now refuses a `finish` (exit 3) while any reported helper still shows `running`, so a finished page never keeps a spinning row. The agent contract in `console-finish.md` says to mark each helper `done` or `failed` first.
|
||||
|
||||
### 🗑️ Removed
|
||||
|
||||
- **handoff**: the Handoff skill's `handoff-path.mjs` script is retired in favour of `console.mjs handoff new`, which every skill can reach.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web console**: a short card on the git board (a confirm such as *Delete 2 branches?*) fills the board's width instead of sitting narrow in the middle.
|
||||
- **web console**: a redraw no longer throws you back to the top of the finished screen, a doc tab, the Overview or the dashboard menu (pressing **Review it now**, or an agent update landing while you read). The page kept your place only on question cards; it now keeps it for whatever is scrolling, as long as the same thing is still on screen.
|
||||
- **dashboard**: a bug folder whose diagnosis Quick Task had marked `Fixed` no longer sits on the dashboard forever as *Files on disk*, pre-selected as the most recent spec with no card to clear it. The scan reports it as a new spec state, **Bug fixed**: no pipeline card lights for it, the picker never opens on it (it opens on the most recent spec still in play, or *Start from scratch*), and it is hidden while *Hide unavailable workflows* is on, dimmed otherwise. Quick Task, right after marking a diagnosis-only folder `Fixed`, offers to archive it to `specs--completed/<bug>/` with the same `specs.mjs archive` Finalize uses (a confirm card on the web console).
|
||||
|
||||
## v2.8.1
|
||||
|
||||
### 📚 Documentation
|
||||
|
||||
- **docs**: the docs site now shows the git board, with a light and dark screenshot under the pipeline's "Any time" cards: the Changes, Branches and Sync tabs, opening on the likely next step, the tab badges, the single block for a stopped rebase or merge, and asking before every push, publish or delete.
|
||||
- **docs**: `scripts/capture-screenshots.mjs` gains a `git` shot. It builds a sample repository with a pushed feature branch and three changes to commit, so `node scripts/capture-screenshots.mjs --only git` regenerates the images.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **tests**: `npm test` no longer fails `git plan switch` on a machine with a global `core.autocrlf=true`. `scripts/skill-script-helpers.mjs` now strips back the git config for the whole test process, so test fixtures, imported modules and the scripts under test always use the same settings.
|
||||
|
||||
## v2.8.0
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **git**: the web console's git board is now three tabs, **Changes**, **Branches** and **Sync**, and opens on the tab holding the likely next step. Ten fixed rules pick that step from the repository's state (fix or continue a stopped rebase or merge, make the first commit, make a branch on a detached HEAD, commit or start a branch for your changes, pull, push, publish, open a pull request, clean up branches) and show it as one main button with at most one quieter one beside it. Each tab badges what is waiting on it, and the other tabs say "Next step is on ‹tab›" with a link to it. Your own click moves you to the next step's tab once it lands; a refresh or a commit from the terminal leaves you where you are, and a reload keeps your tab.
|
||||
- **git**: held-back files (secrets, files over 5 MB) no longer keep Commit as the next step forever. They get a quiet "held back" line and an **Add … to .gitignore** offer, which commits only `.gitignore`.
|
||||
- **git**: a busy board is read-only. While a git command runs or the agent has not picked up your last click, every button, tick and picker greys out (switching tabs, search and folds still work), and what is running shows where the next step usually sits. Plan2Code's questions now appear under the tab strip.
|
||||
- **git**: a rebase or merge stopped on conflicts shows one block on Sync with the files marked *markers left* or *resolved*, one main button and **Abort** once; Changes and Branches wait until it is finished or aborted.
|
||||
- **git**: **Done with git** is a normal button at the right of the tab strip. It greys while a git command runs (Stop session in the top bar still works), and while one of Plan2Code's questions waits it cancels that question and finishes.
|
||||
- **web-console**: Help → *The git board* is rewritten for the tabs, badges, the next step, the busy rules and Done with git. Handoff is described as packing the current session, not this conversation.
|
||||
- **docs**: the docs site's "Any time" skills now list **Changelog** and **Git** beside Quick task, Review and Handoff.
|
||||
- **tests**: `scripts/test-web-console-git-board.mjs` checks every sample repository state's next step, tab and badges, proves no control on a busy board is clickable, and that every board function is reachable on some tab.
|
||||
|
||||
## v2.7.1
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
@@ -15,13 +15,16 @@ The web console is the main way in: a local page where questions, documents, bui
|
||||
| ------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------- |
|
||||
| From your project (shell) | `plan2code` | Opens Claude Code, Devin or Codex on the dashboard (`--cli claude` / `devin` / `codex` to choose) |
|
||||
| Inside any agent | `/plan2code` (`$plan2code` in Codex) | Opens the dashboard: a card for every skill, launched on the same page |
|
||||
| Install / update | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git` | Installs the skills and the `plan2code` command; re-run it to update |
|
||||
| Install | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git` | Installs the skills and the `plan2code` command (re-run it to update without the `plan2code` command) |
|
||||
| Update | `plan2code update` | Updates everything that was installed, with no menu; never uninstalls anything |
|
||||
| Straight into a skill | `/plan2code-1-plan --web` (any step) | Skips the "web console or terminal?" question and opens the page |
|
||||
|
||||
The install command always opens a menu. Back at your prompt with no output at all? npm could not reach the repository and hid the reason: run `git ls-remote https://github.com/jparkerweb/plan2code.git` to see it (usually the network, a proxy or the VPN).
|
||||
|
||||
Pick a skill on the dashboard and the same page becomes that session. Details: [.readme/web-console.md](.readme/web-console.md) · worked example: [.readme/walkthrough.md](.readme/walkthrough.md).
|
||||
|
||||
The **Notebook** icon in the top bar opens a private scratch pad for the folder you are in (Markdown and pictures, kept in `~/.plan2code/notepads/`, never shown to the agent).
|
||||
|
||||
## Commands
|
||||
|
||||
Every command below is what a dashboard card runs. Typed on its own, each one asks "web console or terminal?" first.
|
||||
@@ -41,6 +44,8 @@ Every command below is what a dashboard card runs. Typed on its own, each one as
|
||||
| 3+review | /plan2code-3-implement-review | overview.md | Reviewed implementation ready for approval (alternative to `/plan2code-3-implement`) |
|
||||
| 4 | /plan2code-4-finalize | overview.md | Archived specs |
|
||||
| handoff | /plan2code-handoff | Conversation | Self-contained handoff doc (OS temp dir by default, or a folder you pick such as `handoffs/`) |
|
||||
| xray | /plan2code-xray | An area, or none | An explanation citing files and commits, or `ARCHITECTURE-BRIEF-<date>.md` with the rough spots you picked |
|
||||
| diagnose | /plan2code-diagnose | A bug, or none | `DIAGNOSIS-<date>.md` with the cause and its evidence, then Quick Task (or Plan for a big fix) to fix it |
|
||||
| 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 (`<subject>` / `AI Assisted`), branches, pull with conflict help, push, publish |
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ the next engineer all start from the same specs.
|
||||
|
||||
One command opens it, every step is a card, and the terminal is always there if you prefer it.
|
||||
|
||||
Version 2.6.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
Version 2.11.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
|
||||
---
|
||||
|
||||
@@ -37,7 +37,7 @@ The dashboard, in a project halfway through a build. It suggests the next step f
|
||||
- **Ways in.** `plan2code` (Claude Code, Devin or Codex), or type `/plan2code` in your agent (`$plan2code` in Codex).
|
||||
- **No agent yet?** Install Claude Code, Codex or Devin first.
|
||||
|
||||
Installation needs network access and runs through the [skills CLI](https://skills.sh). To update, re-run the install command.
|
||||
Installation needs network access and runs through the [skills CLI](https://skills.sh). To update, run `plan2code update` (or re-run the install command).
|
||||
|
||||
```bash
|
||||
npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git
|
||||
@@ -93,7 +93,7 @@ GitHub Copilot · Windsurf · Codex · Continue · Codeium · Zed · Amp · Open
|
||||
Gemini CLI · Cline · Roo · Kilo · Goose · Trae · Qwen Code.
|
||||
|
||||
The installer keeps one canonical copy of each skill under `~/.agents/skills/` and links it into
|
||||
agents that maintain their own directory. To update, re-run the install command.
|
||||
agents that maintain their own directory. To update, run `plan2code update` (or re-run the install command).
|
||||
|
||||
Use the installer rather than calling `skills add` against the repository root: recursive discovery
|
||||
would also find maintainer-only skills under `.claude/skills/`. The installer targets `skills/`
|
||||
@@ -150,7 +150,8 @@ next check-in, and it never holds up your answers.
|
||||
|
||||
There is more on the page when you need it. Notes on any question can carry screenshots and
|
||||
documents. The folder label in the bottom bar opens your workspace, where you add other folders
|
||||
as read-only context and point at them by `@name`. The session meter in the top bar turns from green
|
||||
as read-only context and point at them by `@name`. The **Notebook** in the top bar is a private pad of your own for the
|
||||
folder, in Markdown with pictures, that the agent never sees. The session meter in the top bar turns from green
|
||||
to red as a session grows long and suggests a fresh one. **Stop session** saves your place and gives
|
||||
you the command to carry on later, and **Back to the dashboard** takes you home to pick the next
|
||||
step in the same session.
|
||||
@@ -184,15 +185,17 @@ The dashboard's cards, and when each one lights up for the spec you pick:
|
||||
| Set up this project | Reads your project and writes AGENTS.md, the guide every later step works from. | The project has no AGENTS.md yet |
|
||||
| Refresh AGENTS.md | Brings AGENTS.md and its notes up to date with what the project has learned lately. | The project has an AGENTS.md |
|
||||
| Pathfinder | A foggy idea becomes a clear list of decisions, settled one question at a time. | You start fresh, or the spec is still being explored |
|
||||
| Plan | Requirements, technical design and your approval: the shape of what gets built. | You start fresh, or the spec has a finished Pathfinder map or a drafted plan |
|
||||
| Plan | Requirements, technical design and your approval: the shape of what gets built. | You start fresh, or the spec has a finished Pathfinder map, a drafted plan or a bug diagnosis |
|
||||
| Revise the plan | Requirements changed mid-build? Adjust the plan without starting over. | The spec is written up into phases and not fully built |
|
||||
| Document | The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do. | The spec has a drafted plan |
|
||||
| Implement | Builds the next phase, task by task, with a report and your sign-off at the end. | The spec has phases with tasks still to build |
|
||||
| Implement + review | One phase built, then a careful review of the changes, then your sign-off. All in one run. | The spec has phases with tasks still to build |
|
||||
| Finalize | Checks the work, writes the summary, files the specs away and suggests the commit message. | Every task in the spec is done |
|
||||
| Quick task | Too small for the full process? A quick plan, then it just builds it. | Always |
|
||||
| Quick task | Too small for the full process? A quick plan, then it just builds it. | Always (suggested when the spec is a diagnosed bug) |
|
||||
| Review | A second opinion on the changes. Problems ranked, and you pick what gets fixed. | Always |
|
||||
| Handoff | Pack this conversation into a document a fresh session can pick up cold. | Always |
|
||||
| Handoff | Pack this conversation into a document a fresh session can pick up cold. Any skill's **Stop with a handoff** writes one too, and the dashboard lists them to pick up. | Always |
|
||||
| Codebase X-ray | Explain how and why an area works, or find the rough spots worth fixing. | Always |
|
||||
| Diagnose a bug | Find a bug's cause and write it up, without fixing it. | 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) |
|
||||
|
||||
@@ -360,7 +363,9 @@ console or the terminal; add `--web` to skip the question and go straight to the
|
||||
| `/plan2code-init-update` | Fold what you learned this session back into `AGENTS.md` |
|
||||
| `/plan2code-quick-task` | A small change that doesn't warrant the full sequence |
|
||||
| `/plan2code-1b-revise-plan` | Requirements moved mid-build. Revise the specs, not the code |
|
||||
| `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from |
|
||||
| `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from, saved in `~/.plan2code/handoffs/` and listed on the dashboard to pick up |
|
||||
| `/plan2code-xray` | Explain how and why an area of the code works (citing files, commits and PRs), or rank the rough spots worth fixing into a brief for Pathfinder or Plan; never edits code |
|
||||
| `/plan2code-diagnose` | Find a bug's cause and write it up as `specs/<bug-name>/DIAGNOSIS-<date>.md` without fixing it, then offer `/plan2code-quick-task` to fix it, or `/plan2code-1-plan` when the fix is big |
|
||||
| `/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 |
|
||||
|
||||
@@ -413,7 +418,7 @@ edits out through the skills CLI.
|
||||
|
||||
Core reference:
|
||||
|
||||
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off
|
||||
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off, including the private Notebook in the top bar
|
||||
- **[QUICK-REFERENCE.md](QUICK-REFERENCE.md)** — the one-page card: commands, inputs, outputs, decision tree
|
||||
- **[.readme/walkthrough.md](.readme/walkthrough.md)** — one feature from a sentence to archived specs, session by session
|
||||
- **[AGENTS.md](AGENTS.md)** — architecture and contributor guide for this repo
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<link rel="icon" href="favicon.svg" type="image/svg+xml">
|
||||
<link rel="apple-touch-icon" href="apple-touch-icon.png">
|
||||
<style>
|
||||
/* The web console's palette and type (src/web-console/public/app.css), so the
|
||||
/* The web console's palette and type (src/web-console/public/styles/tokens.css), so the
|
||||
site and the product look like one thing, with the Plan2Code blue as the
|
||||
accent: #2455a4 in light, and the console's Ocean highlight (palette.js),
|
||||
which the screenshots use, in dark. System fonts only, like the console. */
|
||||
@@ -306,7 +306,22 @@ footer a { color: inherit; }
|
||||
<div class="utils">
|
||||
<div class="util"><span class="chip">Any time</span><h3>Quick task</h3><p>Too small for the full process? A quick plan, then it just builds it.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Review</h3><p>A second opinion on the changes. Problems ranked, and you pick what gets fixed.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Handoff</h3><p>Pack this conversation into a document a fresh session can pick up cold.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Handoff</h3><p>Pack the current session into a document a fresh session can pick up cold.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Codebase X-ray</h3><p>Explains how and why an area works, or ranks the rough spots worth fixing into a brief for planning.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Diagnose a bug</h3><p>Finds a bug's cause and writes it up without fixing it, then hands the fix to Quick task, or to Plan when it is big.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Changelog</h3><p>Picks the next version and drafts the entries, which you edit before Git commits them.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Git</h3><p>A board for branches, pull, push and commits that opens on the likely next step.</p></div>
|
||||
</div>
|
||||
|
||||
<div class="row" id="git-board">
|
||||
<picture class="shot">
|
||||
<source media="(prefers-color-scheme: dark)" srcset="screenshots/git-dark.webp">
|
||||
<img src="screenshots/git-light.webp" width="2560" height="1600" loading="lazy" alt="The git board on feature/task-endpoints: the Changes tab, badged 3, opens on a Next step card reading Commit 3 files, above the three changed files ticked for the commit. Branches and Sync tabs and a Done with git button sit beside it.">
|
||||
</picture>
|
||||
<div>
|
||||
<h3>The git board</h3>
|
||||
<p>Three tabs, <strong>Changes</strong>, <strong>Branches</strong> and <strong>Sync</strong>, and it opens on the one holding your likely next step: commit, pull, push, publish, open a pull request or tidy up branches. That step is one main button. Each tab badges what is waiting on it, a stopped rebase or merge gets one block with every file marked, and nothing is pushed, published or deleted without asking. It never force-pushes.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -320,6 +335,7 @@ footer a { color: inherit; }
|
||||
<div><h3>Review before you approve</h3><p>Review the code first, on the sign-off card, reviews exactly the files the phase changed. You tick which findings get fixed, then approve.</p></div>
|
||||
<div><h3>The Ask tab</h3><p>A chat beside the cards for anything you want to know. It is answered at the agent's next check-in and never holds up your answers.</p></div>
|
||||
<div><h3>Attachments on notes</h3><p>Paste a screenshot or attach a document to a note on any question, and show instead of describe.</p></div>
|
||||
<div><h3>A notebook of your own</h3><p>A private pad for each project folder, in Markdown with pictures. It never goes into your project, and the agent never sees it.</p></div>
|
||||
<div><h3>Workspace folders</h3><p>Add a shared library or a design folder as read-only context, and point at it by its <code>@name</code>.</p></div>
|
||||
<div><h3>Session meter</h3><p>A ring in the top bar turns from green to red as a session grows long, and suggests when a fresh one would serve you better.</p></div>
|
||||
<div><h3>Runs on your machine</h3><p>A small program Plan2Code starts for you serves the page on <code>127.0.0.1</code>. No account, no dependencies, and nothing leaves your computer.</p></div>
|
||||
@@ -339,6 +355,13 @@ footer a { color: inherit; }
|
||||
</picture>
|
||||
<figcaption>Every ending says what to run next.</figcaption>
|
||||
</figure>
|
||||
<figure style="grid-column:1/-1;max-width:calc(50% - 12px);justify-self:center">
|
||||
<picture class="shot">
|
||||
<source media="(prefers-color-scheme: dark)" srcset="screenshots/notepad-dark.webp">
|
||||
<img src="screenshots/notepad-light.webp" width="2560" height="1600" loading="lazy" alt="The Notebook open over a question: two named tabs, and a heading, bullets and bold styled in place as they are typed.">
|
||||
</picture>
|
||||
<figcaption>Your own notebook, private to the folder.</figcaption>
|
||||
</figure>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
Before Width: | Height: | Size: 95 KiB After Width: | Height: | Size: 99 KiB |
|
Before Width: | Height: | Size: 104 KiB After Width: | Height: | Size: 107 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 110 KiB |
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 114 KiB |
|
Before Width: | Height: | Size: 81 KiB After Width: | Height: | Size: 89 KiB |
|
Before Width: | Height: | Size: 87 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 83 KiB After Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 90 KiB After Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 115 KiB After Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 94 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 100 KiB After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 67 KiB |
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 106 KiB |
|
Before Width: | Height: | Size: 113 KiB After Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 86 KiB After Width: | Height: | Size: 96 KiB |
|
Before Width: | Height: | Size: 95 KiB After Width: | Height: | Size: 104 KiB |
@@ -174,6 +174,7 @@ const SOURCE_PROMPTS = [
|
||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||
{ source: 'plan2code-review-references' }
|
||||
]
|
||||
@@ -216,6 +217,7 @@ const SOURCE_PROMPTS = [
|
||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||
{ source: 'plan2code-review-references' }
|
||||
]
|
||||
@@ -230,6 +232,7 @@ const SOURCE_PROMPTS = [
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'plan2code-3-implement.md', target: 'implement.md' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||
{ source: 'plan2code-review-references' }
|
||||
]
|
||||
@@ -263,6 +266,29 @@ const SOURCE_PROMPTS = [
|
||||
scripts: ['specs.mjs'],
|
||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-xray.md',
|
||||
stepNumber: 'xray',
|
||||
name: 'xray',
|
||||
displayName: 'X-ray Mode',
|
||||
description: 'Explain how and why an area of the code works, or find the rough spots worth fixing',
|
||||
isUtility: true,
|
||||
scripts: [],
|
||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-diagnose.md',
|
||||
stepNumber: 'diagnose',
|
||||
name: 'diagnose',
|
||||
displayName: 'Diagnose Mode',
|
||||
description: 'Find and write up a bug\'s cause without fixing it',
|
||||
isUtility: true,
|
||||
scripts: ['specs.mjs'],
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' }
|
||||
]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-changelog.md',
|
||||
stepNumber: 'changelog',
|
||||
@@ -309,6 +335,8 @@ function generateStepLabel(prompt) {
|
||||
if (prompt.stepNumber === 'review') return 'Review';
|
||||
if (prompt.stepNumber === 'handoff') return 'Handoff';
|
||||
if (prompt.stepNumber === 'git') return 'Git';
|
||||
if (prompt.stepNumber === 'xray') return 'X-ray';
|
||||
if (prompt.stepNumber === 'diagnose') return 'Diagnose';
|
||||
if (prompt.stepNumber === 'changelog') return 'Changelog';
|
||||
if (prompt.stepNumber === 'quick') return 'Quick Task';
|
||||
return `Step ${prompt.stepNumber}`;
|
||||
@@ -900,9 +928,10 @@ function removeInstalledSkills(scope, { quiet = false } = {}) {
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Execute installation
|
||||
* Execute installation. `unattended` (plan2code update) asks nothing and skips the getting-started
|
||||
* steps; `outcome` receives `skills` and `launcher` as true or false for update's per-piece report.
|
||||
*/
|
||||
async function install() {
|
||||
async function install({ unattended = false, outcome = {} } = {}) {
|
||||
displaySectionHeader(' INSTALLING SKILLS ');
|
||||
if (!buildSkills(true)) {
|
||||
console.log(`${COLORS.RED}${SYMBOLS.ERROR} Failed to build ${SKILLS_DIR_NAME}/ from src/${COLORS.RESET}`);
|
||||
@@ -946,10 +975,13 @@ async function install() {
|
||||
console.log('');
|
||||
reportSkillsOutput(result);
|
||||
const failed = !result.ok;
|
||||
outcome.skills = !failed;
|
||||
if (!failed) recordInstalled('skills');
|
||||
|
||||
// The `plan2code` command opens the dashboard skill, so it's only worth adding once the
|
||||
// skills themselves are in place.
|
||||
const launcherFailed = failed ? false : (await installLauncher({ quiet: true })) !== 0;
|
||||
const launcherFailed = failed ? false : (await installLauncher({ quiet: true, unattended })) !== 0;
|
||||
outcome.launcher = !failed && !launcherFailed;
|
||||
|
||||
// Summary
|
||||
console.log(`${COLORS.CYAN}╔═══════════════════════════════════════════════════════════════════════════╗${COLORS.RESET}`);
|
||||
@@ -977,7 +1009,7 @@ async function install() {
|
||||
}
|
||||
|
||||
// The steps come first: where to start, the ways in, and what to do without an agent.
|
||||
printGettingStarted({ commandInstalled: !launcherFailed });
|
||||
if (!unattended) printGettingStarted({ commandInstalled: !launcherFailed });
|
||||
console.log(`${COLORS.GREEN} ╭───╮${COLORS.RESET} ${COLORS.BRIGHT}All done! Happy coding!${COLORS.RESET}`);
|
||||
console.log(`${COLORS.GREEN} ╲│ ${COLORS.CYAN}★${COLORS.GREEN} │╱${COLORS.RESET}`);
|
||||
console.log(`${COLORS.GREEN} │ ${COLORS.BRIGHT}◡${COLORS.GREEN} │${COLORS.RESET}`);
|
||||
@@ -1049,6 +1081,7 @@ function uninstallSkills() {
|
||||
} else {
|
||||
errors++;
|
||||
}
|
||||
if (errors === 0) forgetInstalled('skills');
|
||||
|
||||
console.log(`\n${COLORS.YELLOW}${SYMBOLS.ACTIVE} CLEANING LEGACY PATHS${COLORS.RESET}\n`);
|
||||
const legacy = cleanLegacyPaths();
|
||||
@@ -1520,6 +1553,7 @@ function installPlan2CodeLoop() {
|
||||
}
|
||||
|
||||
console.log('');
|
||||
recordInstalled('loop');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-loop installed successfully!${COLORS.RESET}`);
|
||||
console.log('');
|
||||
console.log(`${COLORS.CYAN}Usage:${COLORS.RESET}`);
|
||||
@@ -1539,6 +1573,7 @@ function uninstallPlan2CodeLoop() {
|
||||
displaySectionHeader('PLAN2CODE-LOOP', '[ UNINSTALL ]');
|
||||
|
||||
removeGlobalSymlink();
|
||||
forgetInstalled('loop');
|
||||
|
||||
console.log('');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-loop uninstalled${COLORS.RESET}`);
|
||||
@@ -1756,6 +1791,7 @@ function installPlan2CodeMetrics() {
|
||||
}
|
||||
|
||||
console.log('');
|
||||
recordInstalled('metrics');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-metrics installed successfully!${COLORS.RESET}`);
|
||||
console.log('');
|
||||
console.log(`${COLORS.CYAN}Usage:${COLORS.RESET}`);
|
||||
@@ -1772,6 +1808,7 @@ function uninstallPlan2CodeMetrics() {
|
||||
displaySectionHeader('PLAN2CODE-METRICS', '[ UNINSTALL ]');
|
||||
|
||||
removeMetricsGlobalSymlink();
|
||||
forgetInstalled('metrics');
|
||||
|
||||
console.log('');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-metrics uninstalled${COLORS.RESET}`);
|
||||
@@ -1795,9 +1832,10 @@ function getStatusLineSrcDir() {
|
||||
|
||||
/**
|
||||
* Install status line (copy + configure settings).
|
||||
* Async because it may prompt when a custom (non-plan2code) statusLine exists.
|
||||
* Async because it may prompt when a custom (non-plan2code) statusLine exists. `unattended`
|
||||
* (plan2code update) never prompts: a custom statusLine is kept as it is.
|
||||
*/
|
||||
async function installStatusLine({ quiet = false } = {}) {
|
||||
async function installStatusLine({ quiet = false, unattended = false } = {}) {
|
||||
if (!quiet) {
|
||||
displaySectionHeader('CLAUDE STATUS LINE', '[ INSTALL ]');
|
||||
} else {
|
||||
@@ -1873,6 +1911,13 @@ async function installStatusLine({ quiet = false } = {}) {
|
||||
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} Existing statusLine detected in settings.json:`);
|
||||
console.log(` ${COLORS.DIM} ${existingCmd}${COLORS.RESET}`);
|
||||
|
||||
// The person chose that status line when they last installed; an update keeps it.
|
||||
if (unattended) {
|
||||
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} Kept it: scripts updated, settings.json unchanged${COLORS.RESET}`);
|
||||
recordInstalled('statusline');
|
||||
return 0;
|
||||
}
|
||||
|
||||
const rl2 = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
const answer = await new Promise(resolve => {
|
||||
rl2.question(` ${COLORS.CYAN}Replace with Plan2Code status line?${COLORS.RESET} (Y/n): `, resolve);
|
||||
@@ -1882,6 +1927,7 @@ async function installStatusLine({ quiet = false } = {}) {
|
||||
if (answer.trim().toLowerCase() === 'n') {
|
||||
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} Skipped — scripts installed but settings.json unchanged${COLORS.RESET}`);
|
||||
console.log('');
|
||||
recordInstalled('statusline');
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1919,6 +1965,7 @@ async function installStatusLine({ quiet = false } = {}) {
|
||||
}
|
||||
|
||||
if (settingsOk) {
|
||||
recordInstalled('statusline');
|
||||
if (!quiet) {
|
||||
console.log('');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} Claude Status Line installed successfully!${COLORS.RESET}`);
|
||||
@@ -2000,6 +2047,7 @@ function uninstallStatusLine() {
|
||||
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No status line files found${COLORS.RESET}`);
|
||||
}
|
||||
|
||||
forgetInstalled('statusline');
|
||||
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} Preserved: statusline-config.json${COLORS.RESET}`);
|
||||
console.log('');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} Status line uninstalled${COLORS.RESET}`);
|
||||
@@ -2217,6 +2265,7 @@ function installPlan2CodeBot() {
|
||||
}
|
||||
|
||||
console.log('');
|
||||
recordInstalled('bot');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-bot installed successfully!${COLORS.RESET}`);
|
||||
console.log('');
|
||||
console.log(`${COLORS.CYAN}Usage:${COLORS.RESET}`);
|
||||
@@ -2233,6 +2282,7 @@ function uninstallPlan2CodeBot() {
|
||||
displaySectionHeader('PLAN2CODE-BOT', '[ UNINSTALL ]');
|
||||
|
||||
removeBotGlobalSymlink();
|
||||
forgetInstalled('bot');
|
||||
|
||||
console.log('');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-bot uninstalled${COLORS.RESET}`);
|
||||
@@ -2260,7 +2310,55 @@ const MODELS_SRC = path.join(__dirname, 'src', 'launcher', 'models.json');
|
||||
const MODELS_DEST = path.join(os.homedir(), '.plan2code', 'bin', 'models.json');
|
||||
const LAUNCHER_DEST = path.join(os.homedir(), '.plan2code', 'bin', 'plan2code.js');
|
||||
const LAUNCHER_STATE = path.join(os.homedir(), '.plan2code', 'launcher.json');
|
||||
// The release notice: the launcher reads the console's cached check through this copy, and
|
||||
// compares it with the version.json written beside it.
|
||||
const UPDATE_CHECK_SRC = path.join(__dirname, 'src', 'web-console', 'update-check.mjs');
|
||||
const UPDATE_CHECK_DEST = path.join(path.dirname(LAUNCHER_DEST), 'update-check.mjs');
|
||||
const LAUNCHER_VERSION_DEST = path.join(path.dirname(LAUNCHER_DEST), 'version.json');
|
||||
// What a global install put on this machine, so `plan2code update` reinstalls exactly that.
|
||||
const INSTALL_RECORD = path.join(os.homedir(), '.plan2code', 'install.json');
|
||||
const INSTALL_PIECES = ['skills', 'launcher', 'statusline', 'loop', 'metrics', 'bot'];
|
||||
const LAUNCHER_PICK_FOLDER_FLAG = '--pick-folder';
|
||||
|
||||
/** `~/.plan2code/install.json` as `{ version, scope, pieces }`, or null when missing or unparsable. */
|
||||
function readInstallRecord() {
|
||||
try {
|
||||
const record = JSON.parse(fs.readFileSync(INSTALL_RECORD, 'utf8'));
|
||||
if (record && typeof record === 'object' && Array.isArray(record.pieces)) return record;
|
||||
} catch {}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Temp file, then rename, so a crash never leaves a half-written record. A failure only skips the record. */
|
||||
function writeInstallRecord(pieces) {
|
||||
const record = {
|
||||
version: projectVersion.version,
|
||||
scope: 'global',
|
||||
pieces: [...new Set(pieces)].filter((piece) => INSTALL_PIECES.includes(piece)).sort(),
|
||||
};
|
||||
const tmp = `${INSTALL_RECORD}.${process.pid}.tmp`;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(INSTALL_RECORD), { recursive: true });
|
||||
fs.writeFileSync(tmp, JSON.stringify(record, null, 2) + '\n');
|
||||
fs.renameSync(tmp, INSTALL_RECORD);
|
||||
} catch {
|
||||
try {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/** Add a piece after a successful global install. */
|
||||
function recordInstalled(piece) {
|
||||
const record = readInstallRecord();
|
||||
writeInstallRecord([...(record ? record.pieces : []), piece]);
|
||||
}
|
||||
|
||||
/** Drop a piece after its uninstall; no record means nothing to forget. */
|
||||
function forgetInstalled(piece) {
|
||||
const record = readInstallRecord();
|
||||
if (record) writeInstallRecord(record.pieces.filter((p) => p !== piece));
|
||||
}
|
||||
const SHORTCUT_NAME = 'Plan2Code';
|
||||
const SHORTCUT_ICON_SRC = path.join(__dirname, 'src', 'launcher', 'plan2code.ico');
|
||||
const SHORTCUT_ICON_DEST = path.join(path.dirname(LAUNCHER_DEST), 'plan2code.ico');
|
||||
@@ -2539,9 +2637,10 @@ async function offerDesktopShortcut(binDir) {
|
||||
|
||||
/**
|
||||
* Install the global `plan2code` command, then offer the desktop shortcut. `quiet` prints
|
||||
* compact lines for use inside the skills install instead of a section of its own.
|
||||
* compact lines for use inside the skills install instead of a section of its own;
|
||||
* `unattended` (plan2code update) skips the shortcut offer and leaves any shortcut as it is.
|
||||
*/
|
||||
async function installLauncher({ quiet = false } = {}) {
|
||||
async function installLauncher({ quiet = false, unattended = false } = {}) {
|
||||
if (quiet) {
|
||||
console.log(`${COLORS.YELLOW}${SYMBOLS.ACTIVE} INSTALLING THE ${LAUNCHER_COMMAND.toUpperCase()} COMMAND${COLORS.RESET}`);
|
||||
} else {
|
||||
@@ -2559,6 +2658,8 @@ async function installLauncher({ quiet = false } = {}) {
|
||||
// The curated model menu is the authors' source of truth, so it is overwritten on every install.
|
||||
// Models the user added in User Preferences live in ~/.plan2code/models.json and are untouched.
|
||||
fs.copyFileSync(MODELS_SRC, MODELS_DEST);
|
||||
fs.copyFileSync(UPDATE_CHECK_SRC, UPDATE_CHECK_DEST);
|
||||
fs.writeFileSync(LAUNCHER_VERSION_DEST, JSON.stringify(projectVersion, null, 2) + '\n');
|
||||
if (process.platform !== 'win32') fs.chmodSync(LAUNCHER_DEST, 0o755);
|
||||
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Installed: ${LAUNCHER_DEST}`);
|
||||
} catch (error) {
|
||||
@@ -2592,8 +2693,9 @@ async function installLauncher({ quiet = false } = {}) {
|
||||
if (!isDirOnPath(binDir)) {
|
||||
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} ${binDir} is not on your PATH — add it to use ${COLORS.BRIGHT}${LAUNCHER_COMMAND}${COLORS.RESET} from any directory`);
|
||||
}
|
||||
recordInstalled('launcher');
|
||||
// The shortcut is a convenience on top of the command, so a failure here only warns.
|
||||
await offerDesktopShortcut(binDir);
|
||||
if (!unattended) await offerDesktopShortcut(binDir);
|
||||
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} The ${LAUNCHER_COMMAND} command starts the agent with permission prompts off (${COLORS.CYAN}--permission-mode bypassPermissions${COLORS.RESET} in Claude Code, ${COLORS.CYAN}bypass${COLORS.RESET} in Devin, ${COLORS.CYAN}--dangerously-bypass-approvals-and-sandbox${COLORS.RESET} in Codex). Run ${COLORS.CYAN}claude /plan2code${COLORS.RESET} yourself if you want prompts.`);
|
||||
console.log('');
|
||||
// Inside install() the final summary prints the steps once, after everything else.
|
||||
@@ -2627,7 +2729,8 @@ function uninstallLauncher() {
|
||||
}
|
||||
const shortcut = getShortcutFile();
|
||||
if (isOurShortcut(shortcut)) remove(shortcut);
|
||||
for (const file of [LAUNCHER_DEST, MODELS_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE]) {
|
||||
forgetInstalled('launcher');
|
||||
for (const file of [LAUNCHER_DEST, MODELS_DEST, UPDATE_CHECK_DEST, LAUNCHER_VERSION_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE, INSTALL_RECORD]) {
|
||||
if (fs.existsSync(file)) remove(file);
|
||||
}
|
||||
try {
|
||||
@@ -2642,26 +2745,99 @@ function uninstallLauncher() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// UPDATE (`plan2code update` runs the npx install with --update)
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* The install function for each recorded piece, in the order update runs them. Install
|
||||
* functions only: an update never uninstalls anything. install() covers the skills and the
|
||||
* plan2code command together.
|
||||
*/
|
||||
const UPDATE_STEPS = {
|
||||
skills: install,
|
||||
launcher: installLauncher,
|
||||
statusline: installStatusLine,
|
||||
loop: installPlan2CodeLoop,
|
||||
metrics: installPlan2CodeMetrics,
|
||||
bot: installPlan2CodeBot,
|
||||
};
|
||||
|
||||
/**
|
||||
* Reinstall whatever ~/.plan2code/install.json lists, without the menu or any prompt. Returns
|
||||
* the exit code: 0 when every piece updated, 1 naming the pieces that failed.
|
||||
*/
|
||||
async function update({ steps = UPDATE_STEPS } = {}) {
|
||||
displaySectionHeader(' UPDATING PLAN2CODE ');
|
||||
console.log(`${COLORS.BLUE}${COLORS.BRIGHT}Installing:${COLORS.RESET} ${projectVersion.name} ${projectVersion.version}`);
|
||||
console.log('');
|
||||
|
||||
const record = readInstallRecord();
|
||||
const pieces = record ? record.pieces : ['skills', 'launcher'];
|
||||
if (!record) {
|
||||
console.log(`${COLORS.YELLOW}${SYMBOLS.INFO}${COLORS.RESET} No install record found (installed before v${projectVersion.version}); updating the skills and the plan2code command.`);
|
||||
console.log('');
|
||||
}
|
||||
|
||||
const results = {};
|
||||
for (const piece of INSTALL_PIECES) {
|
||||
if (!pieces.includes(piece) || piece in results) continue;
|
||||
const outcome = {};
|
||||
try {
|
||||
const code = await steps[piece]({ quiet: true, unattended: true, outcome });
|
||||
results[piece] = code === 0 ? 'updated' : 'failed: see the messages above';
|
||||
} catch (error) {
|
||||
results[piece] = `failed: ${error.message}`;
|
||||
}
|
||||
// install() returns 1 when only the command failed, so its outcome says how the skills
|
||||
// themselves went; a command it put in place has updated the launcher too, and one it
|
||||
// could not is retried on its own as the next piece.
|
||||
if (piece === 'skills' && typeof outcome.skills === 'boolean') {
|
||||
results.skills = outcome.skills ? 'updated' : 'failed: see the messages above';
|
||||
}
|
||||
if (piece === 'skills' && outcome.launcher === true) results.launcher = 'updated';
|
||||
console.log('');
|
||||
}
|
||||
|
||||
console.log(`${COLORS.BRIGHT}UPDATE SUMMARY${COLORS.RESET}`);
|
||||
const failed = [];
|
||||
for (const piece of INSTALL_PIECES.filter((p) => p in results)) {
|
||||
const ok = results[piece] === 'updated';
|
||||
if (!ok) failed.push(piece);
|
||||
console.log(` ${ok ? COLORS.GREEN + SYMBOLS.SUCCESS : COLORS.RED + SYMBOLS.ERROR}${COLORS.RESET} ${piece}: ${results[piece]}`);
|
||||
}
|
||||
console.log('');
|
||||
if (failed.length > 0) {
|
||||
console.log(`${COLORS.RED}${SYMBOLS.ERROR} Update failed for: ${failed.join(', ')}${COLORS.RESET}\n`);
|
||||
return 1;
|
||||
}
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} Plan2Code is up to date (v${projectVersion.version})${COLORS.RESET}\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// MAIN
|
||||
// ============================================================================
|
||||
|
||||
// Non-interactive build hooks for the generated skills/ artifact.
|
||||
const argv = process.argv.slice(2);
|
||||
// Run only when invoked directly; requiring the file (the update tests do) is load-only.
|
||||
if (require.main === module) {
|
||||
// Non-interactive build hooks for the generated skills/ artifact.
|
||||
const argv = process.argv.slice(2);
|
||||
|
||||
if (argv.includes('--build-skills')) {
|
||||
process.exit(buildSkills() ? 0 : 1);
|
||||
if (argv.includes('--build-skills')) {
|
||||
process.exit(buildSkills() ? 0 : 1);
|
||||
} else if (argv.includes('--verify-skills')) {
|
||||
process.exit(verifySkillsSync() ? 0 : 1);
|
||||
} else if (argv.length === 1 && argv[0] === '--update') {
|
||||
update().then((code) => process.exit(code));
|
||||
} else if (argv.length > 0) {
|
||||
console.error(`Unknown option(s): ${argv.join(' ')}`);
|
||||
console.error('Usage: node install.js [--build-skills | --verify-skills | --update]');
|
||||
console.error('Run with no options for the interactive installer.');
|
||||
process.exit(1);
|
||||
} else {
|
||||
runInteractive();
|
||||
}
|
||||
}
|
||||
|
||||
if (argv.includes('--verify-skills')) {
|
||||
process.exit(verifySkillsSync() ? 0 : 1);
|
||||
}
|
||||
|
||||
if (argv.length > 0) {
|
||||
console.error(`Unknown option(s): ${argv.join(' ')}`);
|
||||
console.error('Usage: node install.js [--build-skills | --verify-skills]');
|
||||
console.error('Run with no options for the interactive installer.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
runInteractive();
|
||||
module.exports = { update, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName };
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code",
|
||||
"version": "2.7.1",
|
||||
"version": "2.11.0",
|
||||
"private": true,
|
||||
"bin": {
|
||||
"plan2code-install": "./install.js"
|
||||
@@ -8,9 +8,10 @@
|
||||
"scripts": {
|
||||
"prepare": "husky",
|
||||
"build:skills": "node install.js --build-skills",
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.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-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-script-handoff.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs"
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.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-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-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.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"
|
||||
},
|
||||
"devDependencies": {
|
||||
"husky": "^9.0.0"
|
||||
"husky": "^9.0.0",
|
||||
"playwright-core": "1.64.1"
|
||||
}
|
||||
}
|
||||
@@ -16,15 +16,17 @@
|
||||
// fcp first contentful paint: the person sees something
|
||||
// ready the session is drawn from real state (the menu, or a question)
|
||||
//
|
||||
// plus the bytes and request count the page cost. Needs puppeteer-core in
|
||||
// node_modules and a local Chrome or Edge for the browser columns; without
|
||||
// them it still reports url/cliExit and an HTTP-only waterfall.
|
||||
// plus the bytes and request count the page cost. The browser columns need
|
||||
// playwright-core (from `npm install`) and a local Chrome or Edge, picked by
|
||||
// scripts/browser.mjs; without a browser it still reports url/cliExit and an
|
||||
// HTTP-only waterfall.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { findBrowser, launchBrowser } from "./browser.mjs";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
@@ -44,20 +46,6 @@ const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER
|
||||
// so a slow GitHub never colours the timings.
|
||||
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
|
||||
|
||||
function findBrowser() {
|
||||
if (args.browser === "none") return null;
|
||||
if (typeof args.browser === "string") return args.browser;
|
||||
const candidates = [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
];
|
||||
return candidates.find((p) => fs.existsSync(p)) || null;
|
||||
}
|
||||
|
||||
// Resolves at the first stdout line carrying a url, and again at exit.
|
||||
// --launch hook (default): `open` launches "the browser" the way it would for
|
||||
// a person, through PLAN2CODE_BROWSER, and the hook just writes the link to
|
||||
@@ -211,18 +199,22 @@ async function roundtrip() {
|
||||
|
||||
async function main() {
|
||||
if (args.roundtrip) return roundtrip();
|
||||
const browserPath = findBrowser();
|
||||
let puppeteer = null;
|
||||
if (browserPath) {
|
||||
// --browser none: no launch at all. --browser <path>: that executable.
|
||||
// Otherwise the helper's pick; a browser problem is one line, then the
|
||||
// HTTP-only waterfall.
|
||||
let browser = null;
|
||||
let browserName = null;
|
||||
if (args.browser !== "none") {
|
||||
const custom = typeof args.browser === "string" ? args.browser : null;
|
||||
try {
|
||||
puppeteer = (await import("puppeteer-core")).default;
|
||||
} catch {
|
||||
console.error("puppeteer-core not installed; browser columns skipped");
|
||||
browser = await launchBrowser(custom ? { executablePath: custom } : {});
|
||||
const found = custom ? null : findBrowser();
|
||||
browserName = found ? `${found.channel} (${found.path})` : custom;
|
||||
} catch (e) {
|
||||
if (!e.browserProblem) throw e;
|
||||
console.error(e.message);
|
||||
}
|
||||
}
|
||||
const browser = puppeteer
|
||||
? await puppeteer.launch({ executablePath: browserPath, headless: true, args: ["--no-first-run", "--no-default-browser-check"] })
|
||||
: null;
|
||||
|
||||
const rows = [];
|
||||
// One throwaway run so disk caches and the Node binary are warm; the person
|
||||
@@ -231,7 +223,7 @@ async function main() {
|
||||
stopAll();
|
||||
// The tab exists before the clock starts: a person's browser is already
|
||||
// running, and creating a context is the harness's cost, not the page's.
|
||||
const ctx = browser ? await browser.createBrowserContext() : null;
|
||||
const ctx = browser ? await browser.newContext() : null;
|
||||
const page = ctx ? await ctx.newPage() : null;
|
||||
const { t0, urlP, exitP, openP } = runOpen();
|
||||
const o = await openP;
|
||||
@@ -246,7 +238,7 @@ async function main() {
|
||||
page.on("response", async (res) => {
|
||||
requests++;
|
||||
try {
|
||||
bytes += (await res.buffer()).length;
|
||||
bytes += (await res.body()).length;
|
||||
} catch {}
|
||||
});
|
||||
if (BROWSER_DELAY) await new Promise((r) => setTimeout(r, Math.max(0, o.at + BROWSER_DELAY - Date.now())));
|
||||
@@ -303,7 +295,7 @@ async function main() {
|
||||
};
|
||||
const summary = Object.fromEntries(cols.map((k) => [k, stat(k)]));
|
||||
console.log(`web console start-up, ${RUNS} runs, workflow=${WORKFLOW}, cwd=${CWD}`);
|
||||
console.log(`browser: ${browser ? browserPath : "none (HTTP-only waterfall)"}`);
|
||||
console.log(`browser: ${browser ? browserName : "none (HTTP-only waterfall)"}`);
|
||||
console.log("metric".padEnd(10) + "median".padStart(9) + "min".padStart(9) + "max".padStart(9));
|
||||
for (const k of cols) {
|
||||
const s = summary[k];
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// Picks and launches the browser for page tests and the dev scripts. Dev-only:
|
||||
// lives in scripts/ so it never ships inside a skill.
|
||||
//
|
||||
// The first installed of Chrome then Edge, through playwright-core (a root
|
||||
// devDependency); PLAN2CODE_TEST_BROWSER=chrome or msedge forces one. Every
|
||||
// failure is one line in our own words, never Playwright's install hint.
|
||||
|
||||
import fs from "node:fs";
|
||||
|
||||
// The fixed places each browser installs to, probed in order on every
|
||||
// platform (a path that cannot exist here is simply not found).
|
||||
export const BROWSER_PATHS = {
|
||||
chrome: [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/google-chrome-stable",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
],
|
||||
msedge: [
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
"/usr/bin/microsoft-edge",
|
||||
"/usr/bin/microsoft-edge-stable",
|
||||
],
|
||||
};
|
||||
|
||||
const CHANNELS = Object.keys(BROWSER_PATHS);
|
||||
|
||||
// Returns { channel, path } for the first browser found, or null. Either way
|
||||
// findBrowser.checked lists every path this call looked at.
|
||||
export function findBrowser({ env = process.env, exists = fs.existsSync } = {}) {
|
||||
const forced = env.PLAN2CODE_TEST_BROWSER;
|
||||
if (forced && !CHANNELS.includes(forced)) {
|
||||
throw new Error(`PLAN2CODE_TEST_BROWSER must be ${CHANNELS.join(" or ")} (it is "${forced}").`);
|
||||
}
|
||||
findBrowser.checked = [];
|
||||
for (const channel of forced ? [forced] : CHANNELS) {
|
||||
for (const p of BROWSER_PATHS[channel]) {
|
||||
findBrowser.checked.push(p);
|
||||
if (exists(p)) return { channel, path: p };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
findBrowser.checked = [];
|
||||
|
||||
// null when page tests can run here, otherwise the one line that says why
|
||||
// not. `checked` defaults to the paths the last findBrowser() call probed.
|
||||
export function browserProblem({ nodeVersion = process.versions.node, found, checked = findBrowser.checked } = {}) {
|
||||
if (Number(nodeVersion.split(".")[0]) < 20) {
|
||||
return `Page tests need Node 20 or newer (this is ${nodeVersion}). Users of Plan2Code still only need Node 18.`;
|
||||
}
|
||||
if (!found) {
|
||||
return `Page tests need Chrome or Edge. Looked in: ${checked.join(", ")}. Install either one, or set PLAN2CODE_TEST_BROWSER.`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Launches the browser findBrowser() picks, headless. `options` go to
|
||||
// Playwright's chromium.launch() as they are (an `executablePath` there skips
|
||||
// the pick); `find` hands findBrowser() its env and exists, for tests. A
|
||||
// problem rejects with an Error whose message is our one line and whose
|
||||
// `browserProblem` is true, never Playwright's own launch text.
|
||||
export async function launchBrowser(options = {}, find = {}) {
|
||||
const found = options.executablePath ? { channel: null, path: options.executablePath } : findBrowser(find);
|
||||
const problem = browserProblem({ found });
|
||||
if (problem) throw Object.assign(new Error(problem), { browserProblem: true });
|
||||
let chromium;
|
||||
try {
|
||||
({ chromium } = await import("playwright-core"));
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error("Page tests need playwright-core: run npm install.", { cause: e }), { browserProblem: true });
|
||||
}
|
||||
try {
|
||||
return await chromium.launch({
|
||||
executablePath: found.path,
|
||||
headless: true,
|
||||
args: ["--no-first-run", "--no-default-browser-check"],
|
||||
...options,
|
||||
});
|
||||
} catch (e) {
|
||||
// Playwright's own text stays out of the message, but is kept as the
|
||||
// cause for whoever needs to debug a real launch failure.
|
||||
const line = `Page tests could not start the browser at ${found.path}. Install Chrome or Edge, or set PLAN2CODE_TEST_BROWSER.`;
|
||||
throw Object.assign(new Error(line, { cause: e }), { browserProblem: true });
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
// it never ships inside a skill.
|
||||
//
|
||||
// node scripts/capture-screenshots.mjs [--only <shot>] [--browser <path>]
|
||||
// [--out <dir>]
|
||||
// [--out <dir>] [--compare]
|
||||
//
|
||||
// Every shot is staged with no agent: a throwaway sample project called
|
||||
// `task-api`, a throwaway console home (PLAN2CODE_CONSOLE_HOME), then
|
||||
@@ -13,17 +13,28 @@
|
||||
// The shots use the console's Ocean highlight rather than its default orange:
|
||||
// it is the console's nearest to the Plan2Code blue the site and README use.
|
||||
//
|
||||
// Shots: dashboard, dashboard-utilities, question, doc, build, signoff, finish, ask.
|
||||
// Shots: dashboard, dashboard-utilities, question, doc, build, signoff, finish, ask, git.
|
||||
// --compare adds workspace, stop, delete, help, prefs and cleanup: screens the
|
||||
// docs never show, for checking a change by eye against a "before" set. Its
|
||||
// --out must be outside docs/screenshots/, so the set is never published.
|
||||
//
|
||||
// Needs puppeteer-core (`npm i --no-save puppeteer-core`, never added to
|
||||
// package.json) and a local Chrome or Edge. Writes nothing outside its temp
|
||||
// folders and --out.
|
||||
// --snapshot <file> (used by scripts/css-snapshot.mjs) takes no pictures: it
|
||||
// writes every element's computed style, per screen, theme and width, to <file>.
|
||||
// It sees what these shots stage: choice, multi, text, review and confirm cards;
|
||||
// a checklist, list, recap or menu card is not staged, so a rule only they use
|
||||
// is not covered.
|
||||
//
|
||||
// Needs playwright-core (a root devDependency, so `npm install` brings it) and
|
||||
// a local Chrome or Edge, launched through scripts/browser.mjs. Playwright has
|
||||
// no WebP screenshots, so each shot is taken over CDP. Writes nothing outside
|
||||
// its temp folders and --out.
|
||||
|
||||
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 { launchBrowser } from "./browser.mjs";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
@@ -67,6 +78,128 @@ const SHOTS = {
|
||||
signoff: { workflow: "implement", posts: ["signoff"] },
|
||||
finish: { workflow: "implement", posts: ["signoff", "finish"] },
|
||||
ask: { workflow: "plan", posts: ["question"], ask: "Where are tasks paged?" },
|
||||
// The git board draws itself from a real repository, so this shot runs in
|
||||
// its own git sample project; the post only hands the board back to you.
|
||||
git: { workflow: "git", posts: ["git"], repo: true },
|
||||
// The Notebook dialog over the plan question, with two named tabs: Call notes
|
||||
// (a heading, bullets and bold, shown live) and Ideas, with the first one
|
||||
// open. The store is the scratch folder's, never the real one.
|
||||
notepad: {
|
||||
workflow: "plan",
|
||||
posts: ["question"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-notepad");
|
||||
await page.waitForSelector("#notepad-modal[open]", { timeout: 10000 });
|
||||
const editor = page.locator("#notepad-editor .cm-content");
|
||||
const newTab = async (name) => {
|
||||
await page.click((await page.locator("#notepad-empty").isVisible()) ? "#notepad-empty-new" : "#notepad-tab-new");
|
||||
await page.fill("#notepad-name", name);
|
||||
await page.keyboard.press("Enter");
|
||||
await page.waitForFunction(
|
||||
(n) => [...document.querySelectorAll("#notepad-tabs .notepad-tab")].some((b) => b.textContent === n && b.getAttribute("aria-selected") === "true"),
|
||||
name,
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
await editor.click();
|
||||
};
|
||||
// The second theme's run finds the first one's tabs, kept in the same store.
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector("#notepad-tabs .notepad-tab") || !document.getElementById("notepad-empty").hidden,
|
||||
null,
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
if (!(await page.locator("#notepad-tabs .notepad-tab").count())) {
|
||||
// The list marker is typed once: the editor carries a list on at Enter.
|
||||
await newTab("Call notes");
|
||||
await page.keyboard.type(
|
||||
"# Before the call\n\n- Ask about **paging**: cursor or offset?\nWho signs in to the API?\nCheck the `/tasks` limit with the team\n\n"
|
||||
);
|
||||
await newTab("Ideas");
|
||||
await page.keyboard.type("Retry policy for the export job.\nWhat should the page size cap be?");
|
||||
}
|
||||
await sleep(1000);
|
||||
await page.locator("#notepad-tabs .notepad-tab", { hasText: /^Call notes$/ }).click();
|
||||
await page.locator("#notepad-editor .cm-h1").waitFor({ timeout: 10000 });
|
||||
await page.locator("#notepad-editor .cm-line").last().click();
|
||||
await sleep(1800);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// --compare only: the screens the docs never show, shot so a change to the
|
||||
// console can be checked against a "before" set by eye. `open` runs on the
|
||||
// page after every load and clicks through to the screen. Never published.
|
||||
const COMPARE_SHOTS = {
|
||||
// The confirm dialog, with the handoff choice beside plain stop.
|
||||
stop: {
|
||||
workflow: "implement",
|
||||
posts: ["stop"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-stop");
|
||||
await page.waitForSelector("#stop-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
// The first step of a spec chip's delete.
|
||||
delete: {
|
||||
workflow: "dashboard",
|
||||
posts: ["delete"],
|
||||
open: async (page) => {
|
||||
await page.locator(".spec-chip-del").first().click({ force: true });
|
||||
await page.waitForSelector("#delete-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
// Help on its first tab, whatever topic it opened on.
|
||||
help: {
|
||||
workflow: "plan",
|
||||
posts: ["help"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-about");
|
||||
await page.locator("#help-tabs .help-tab").first().click();
|
||||
await page.waitForSelector("#help-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
prefs: {
|
||||
workflow: "plan",
|
||||
posts: ["prefs"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-looks");
|
||||
await page.waitForSelector("#looks-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
// Preferences scrolled to Cleanup once its scan has answered.
|
||||
cleanup: {
|
||||
workflow: "plan",
|
||||
posts: ["cleanup"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-looks");
|
||||
await page.waitForSelector("#looks-modal[open]", { timeout: 10000 });
|
||||
await page.locator(".looks-cleanup").scrollIntoViewIfNeeded();
|
||||
await page.click("#cleanup-scan");
|
||||
await page.waitForFunction(() => document.getElementById("cleanup-status").textContent.trim() !== "", null, { timeout: 15000 }).catch(() => {});
|
||||
},
|
||||
},
|
||||
// The panel open with two folders: the project and a sibling added once.
|
||||
// Last, since the console remembers the folder for the project and every
|
||||
// later shot's footer would count it.
|
||||
workspace: {
|
||||
workflow: "plan",
|
||||
posts: ["workspace"],
|
||||
open: async (page) => {
|
||||
const extra = makeExtraFolder();
|
||||
await page.evaluate(async (dir) => {
|
||||
const now = await (await fetch("/workspace", { cache: "no-store" })).json();
|
||||
if ((now.folders || []).length < 2) {
|
||||
await fetch("/workspace/add", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ path: dir, name: "task-web", description: "The web app that calls the API" }),
|
||||
});
|
||||
}
|
||||
}, extra);
|
||||
await page.click("#footer-where");
|
||||
await page.waitForSelector("#workspace-modal[open] #workspace-list li:nth-child(2)", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// On Windows the temp dir sits under the user's profile, and the page can
|
||||
@@ -86,21 +219,6 @@ function fail(message) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function findBrowser() {
|
||||
if (typeof args.browser === "string") return fs.existsSync(args.browser) ? args.browser : null;
|
||||
const candidates = [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
];
|
||||
return candidates.find((p) => fs.existsSync(p)) || null;
|
||||
}
|
||||
|
||||
function phaseFile(n, name, tasks, done) {
|
||||
const lines = tasks.map((t, i) => `- [${done ? "x" : " "}] **Task ${n}.${i + 1}:** ${t}`).join("\n");
|
||||
return `# Phase ${n}: ${name}\n\n**Status:** ${done ? "Complete" : "Not Started"}\n\n## Tasks\n\n${lines}\n`;
|
||||
@@ -166,6 +284,54 @@ function makeSampleProject() {
|
||||
return project;
|
||||
}
|
||||
|
||||
// The Workspace shot's second folder, beside the sample project.
|
||||
function makeExtraFolder() {
|
||||
const dir = path.join(SCRATCH, "task-web");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "README.md"), "# task-web\n\nThe web app that lists and edits a team's tasks.\n");
|
||||
return dir;
|
||||
}
|
||||
|
||||
function git(cwd, ...gitArgs) {
|
||||
const r = spawnSync("git", gitArgs, { cwd, env: ENV, encoding: "utf8" });
|
||||
if (r.status !== 0) throw new Error(`git ${gitArgs.join(" ")} failed: ${(r.stderr || "").trim()}`);
|
||||
}
|
||||
|
||||
// The git shot's project: the same sample in a repository whose feature branch
|
||||
// is pushed to a local bare "origin" and has three changes to commit, so the
|
||||
// board opens on Changes with Commit as the next step. It sits in its own
|
||||
// folder so the other shots never see a repository.
|
||||
let GIT_PROJECT = null;
|
||||
function makeGitProject() {
|
||||
if (GIT_PROJECT) return GIT_PROJECT;
|
||||
const parent = path.join(SCRATCH, "git");
|
||||
fs.mkdirSync(parent, { recursive: true });
|
||||
const origin = path.join(parent, "origin.git");
|
||||
git(parent, "init", "--bare", "--initial-branch=main", origin);
|
||||
const prev = SCRATCH;
|
||||
SCRATCH = parent;
|
||||
const project = makeSampleProject();
|
||||
SCRATCH = prev;
|
||||
const id = ["-c", "user.name=Sam Rivera", "-c", "user.email=sam@example.com", "-c", "commit.gpgsign=false"];
|
||||
git(project, "init", "--initial-branch=main");
|
||||
git(project, "remote", "add", "origin", origin);
|
||||
git(project, "add", "-A");
|
||||
git(project, ...id, "commit", "-m", "Scaffold the task API and its specs");
|
||||
git(project, "push", "-u", "origin", "main");
|
||||
git(project, "switch", "-c", "feature/task-endpoints");
|
||||
fs.writeFileSync(path.join(project, "src", "tasks", "routes.js"), "// The /tasks routes.\nexport default async function routes(app) {}\n");
|
||||
git(project, "add", "-A");
|
||||
git(project, ...id, "commit", "-m", "Register the /tasks routes plugin");
|
||||
git(project, "push", "-u", "origin", "feature/task-endpoints");
|
||||
// A fetch stamps FETCH_HEAD, so the board says "Last refreshed" rather than "Never".
|
||||
git(project, "fetch", "origin");
|
||||
fs.appendFileSync(path.join(project, "src", "tasks", "paginate.js"), "\nexport const MAX_LIMIT = 50;\n");
|
||||
fs.writeFileSync(path.join(project, "src", "tasks", "schema.js"), "// The Zod schema for a task.\nexport const taskSchema = {};\n");
|
||||
fs.appendFileSync(path.join(project, "specs", "task-api", "phase-3.md"), "\n<!-- Task 3.1 in progress -->\n");
|
||||
GIT_PROJECT = project;
|
||||
return project;
|
||||
}
|
||||
|
||||
function cli(cwd, ...cliArgs) {
|
||||
const r = spawnSync(process.execPath, [CONSOLE_CLI, ...cliArgs], { cwd, env: ENV, encoding: "utf8" });
|
||||
const line = (r.stdout || "").trim().split("\n").pop() || "";
|
||||
@@ -182,8 +348,7 @@ function post(project, sid, name) {
|
||||
}
|
||||
|
||||
// Opens a session for the shot and posts its payloads. Returns { sid, url }.
|
||||
function stage(project, shot) {
|
||||
const spec = SHOTS[shot];
|
||||
function stage(project, spec) {
|
||||
const r = cli(project, "open", "--workflow", spec.workflow, "--no-open");
|
||||
if (r.code !== 0 || !r.out || !r.out.url) throw new Error(`open failed (${r.code}): ${r.err.trim()}`);
|
||||
for (const name of spec.posts) post(project, r.out.sid, name);
|
||||
@@ -193,9 +358,9 @@ function stage(project, shot) {
|
||||
// Waits for the page to draw real state, then lets the animations finish
|
||||
// (the dashboard's wake-up is the longest).
|
||||
async function settle(page) {
|
||||
await page.waitForNetworkIdle({ idleTime: 500, timeout: 15000 }).catch(() => {});
|
||||
await page.waitForSelector(".dash-card, .card, .handoff, .ask-pane, .doc", { timeout: 15000 }).catch(() => {});
|
||||
await sleep(3500);
|
||||
await page.waitForLoadState("networkidle", { timeout: 15000 }).catch(() => {});
|
||||
await page.waitForSelector(".dash-card, .card, .handoff, .ask-pane, .doc, .git-board", { timeout: 15000 }).catch(() => {});
|
||||
await sleep(args.snapshot ? 1800 : 3500);
|
||||
}
|
||||
|
||||
async function openTab(page, label) {
|
||||
@@ -208,7 +373,7 @@ async function openTab(page, label) {
|
||||
|
||||
async function scrollTo(page, { scrollTo: top, mustShow }) {
|
||||
const problem = await page.evaluate(
|
||||
(topSel, showSel) => {
|
||||
([topSel, showSel]) => {
|
||||
const find = (sel) =>
|
||||
sel.startsWith("cmd:")
|
||||
? [...document.querySelectorAll(".dash-card")].find((c) => c.querySelector(".dash-card-cmd")?.textContent.trim() === sel.slice(4))
|
||||
@@ -222,24 +387,95 @@ async function scrollTo(page, { scrollTo: top, mustShow }) {
|
||||
const r = show.getBoundingClientRect();
|
||||
return r.top >= 0 && r.bottom <= window.innerHeight ? null : `${showSel} is not wholly in view`;
|
||||
},
|
||||
top,
|
||||
mustShow || null
|
||||
[top, mustShow || null]
|
||||
);
|
||||
if (problem) console.log(` warning: ${problem}`);
|
||||
await sleep(300);
|
||||
}
|
||||
|
||||
// The properties that change how a stylesheet move would look.
|
||||
const SNAP_PROPS = [
|
||||
"display", "position", "top", "right", "bottom", "left", "width", "height", "min-width", "max-width", "min-height", "max-height",
|
||||
"margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left",
|
||||
"color", "background-color", "background-image", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
|
||||
"border-top-style", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "border-top-left-radius",
|
||||
"font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-align", "text-transform",
|
||||
"gap", "grid-template-columns", "grid-template-rows", "grid-column-start", "grid-column-end", "grid-row-start", "grid-row-end",
|
||||
"flex-direction", "flex-wrap", "flex-grow", "flex-shrink", "flex-basis", "align-items", "justify-content", "align-self",
|
||||
"overflow-x", "overflow-y", "opacity", "visibility", "transform", "z-index", "box-shadow", "cursor", "pointer-events", "white-space",
|
||||
"content", "outline-style", "transform-origin", "fill", "stroke",
|
||||
];
|
||||
// Recorded after the properties above, for every element: what names its animation.
|
||||
// A property a running animation is moving is recorded as "~" (it differs from run
|
||||
// to run), so a rule that adds or removes an animation shows in these fields instead.
|
||||
const SNAP_ANIMATION = ["animation-name", "animation-duration", "animation-delay", "animation-iteration-count", "animation-timing-function", "animation-direction", "animation-fill-mode"];
|
||||
|
||||
const SNAP = {};
|
||||
|
||||
async function snapshotNow(page) {
|
||||
return page.evaluate(
|
||||
([props, animation]) => {
|
||||
const out = {};
|
||||
const seen = new Map();
|
||||
for (const el of document.querySelectorAll("*")) {
|
||||
const parent = el.parentElement;
|
||||
const key = parent ? (seen.get(parent) || "") : "";
|
||||
const sib = parent ? [...parent.children].indexOf(el) : 0;
|
||||
const cls = typeof el.className === "string" ? el.className.trim().split(/\s+/).filter(Boolean).slice(0, 3).join(".") : "";
|
||||
const path = (parent ? key + ">" : "") + el.tagName.toLowerCase() + (el.id ? "#" + el.id : "") + (cls ? "." + cls : "") + "[" + sib + "]";
|
||||
seen.set(el, path);
|
||||
const cs = getComputedStyle(el);
|
||||
const moving = new Set();
|
||||
for (const a of el.getAnimations ? el.getAnimations() : []) {
|
||||
for (const kf of a.effect && a.effect.getKeyframes ? a.effect.getKeyframes() : []) {
|
||||
for (const k of Object.keys(kf)) if (!["offset", "easing", "composite", "computedOffset"].includes(k)) moving.add(k.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()));
|
||||
}
|
||||
}
|
||||
out[path] = props.map((p) => (moving.has(p) ? "~" : cs.getPropertyValue(p))).concat(animation.map((p) => cs.getPropertyValue(p))).join("|");
|
||||
}
|
||||
return out;
|
||||
},
|
||||
[SNAP_PROPS, SNAP_ANIMATION]
|
||||
);
|
||||
}
|
||||
|
||||
async function snapshotShot(page, name, theme) {
|
||||
for (const [w, h] of [[1280, 800], [390, 844]]) {
|
||||
await page.setViewportSize({ width: w, height: h });
|
||||
await sleep(1500);
|
||||
SNAP[`${name}/${theme}/${w}`] = await snapshotNow(page);
|
||||
}
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
}
|
||||
|
||||
async function shoot(page, name) {
|
||||
const written = [];
|
||||
// Math.random picks Planny's mood variants; pinned so two runs draw the same page.
|
||||
if (args.snapshot) await page.addInitScript(() => { Math.random = () => 0.5; });
|
||||
for (const theme of THEMES) {
|
||||
await page.emulateMediaFeatures([{ name: "prefers-color-scheme", value: theme }]);
|
||||
await page.emulateMedia({ colorScheme: theme });
|
||||
// The theme is applied at load, so reload rather than trust a live switch.
|
||||
await page.reload({ waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
if (page.__tab) await openTab(page, page.__tab);
|
||||
if (page.__scroll && page.__scroll.scrollTo) await scrollTo(page, page.__scroll);
|
||||
if (page.__open) {
|
||||
await page.__open(page);
|
||||
await sleep(600);
|
||||
}
|
||||
if (args.snapshot) {
|
||||
await snapshotShot(page, name, theme);
|
||||
continue;
|
||||
}
|
||||
const file = path.join(OUT, `${name}-${theme}.webp`);
|
||||
await page.screenshot({ type: "webp", quality: QUALITY, path: file });
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
// Without a clip the capture comes out in CSS pixels; a clip of the
|
||||
// viewport at scale 2 is the twice-density shot (byte for byte what
|
||||
// Playwright's own PNG screenshot takes).
|
||||
const clip = { x: 0, y: 0, width: 1280, height: 800, scale: 2 };
|
||||
const { data } = await cdp.send("Page.captureScreenshot", { format: "webp", quality: QUALITY, captureBeyondViewport: false, clip });
|
||||
await cdp.detach();
|
||||
fs.writeFileSync(file, Buffer.from(data, "base64"));
|
||||
const kb = Math.round(fs.statSync(file).size / 1024);
|
||||
console.log(`${path.basename(file)} ${kb} KB`);
|
||||
if (kb > WARN_KB) console.log(` warning: ${path.basename(file)} is over ${WARN_KB} KB`);
|
||||
@@ -249,15 +485,15 @@ async function shoot(page, name) {
|
||||
}
|
||||
|
||||
// Opens the page for a staged session and saves both themes.
|
||||
async function capture(browser, url, name, { tab, scrollTo: top, mustShow }) {
|
||||
const ctx = await browser.createBrowserContext();
|
||||
async function capture(browser, url, name, { tab, scrollTo: top, mustShow, open }) {
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });
|
||||
try {
|
||||
const page = await ctx.newPage();
|
||||
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
page.__tab = tab || null;
|
||||
page.__scroll = { scrollTo: top, mustShow };
|
||||
page.__open = open || null;
|
||||
return await shoot(page, name);
|
||||
} finally {
|
||||
await ctx.close();
|
||||
@@ -267,15 +503,14 @@ async function capture(browser, url, name, { tab, scrollTo: top, mustShow }) {
|
||||
// The Ask shot: a question typed and sent on the page, collected with `chat`
|
||||
// the way an agent would, and answered with a posted reply.
|
||||
async function captureAsk(browser, project, sid, url, question) {
|
||||
const ctx = await browser.createBrowserContext();
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });
|
||||
try {
|
||||
const page = await ctx.newPage();
|
||||
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
await openTab(page, "Ask");
|
||||
await page.waitForSelector("#ask-input:not([disabled])", { timeout: 10000 });
|
||||
await page.type("#ask-input", question);
|
||||
await page.locator("#ask-input").pressSequentially(question);
|
||||
await page.evaluate(() => {
|
||||
const send = [...document.querySelectorAll(".ask-composer button")].find((b) => b.textContent.trim() === "Send");
|
||||
if (send) send.click();
|
||||
@@ -317,21 +552,18 @@ async function captureAsk(browser, project, sid, url, question) {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const names = args.only ? [args.only] : Object.keys(SHOTS);
|
||||
for (const n of names) if (!SHOTS[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(SHOTS).join(", ")}`);
|
||||
|
||||
let puppeteer;
|
||||
try {
|
||||
puppeteer = (await import("puppeteer-core")).default;
|
||||
} catch {
|
||||
fail("puppeteer-core is not installed. Run: npm i --no-save puppeteer-core");
|
||||
const docs = path.join(ROOT, "docs", "screenshots");
|
||||
const fold = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
|
||||
if (args.compare && (fold(OUT) === fold(docs) || fold(OUT).startsWith(fold(docs) + path.sep))) {
|
||||
fail(`--compare never writes into ${path.relative(ROOT, docs)}: pass --out with a folder outside it.`);
|
||||
}
|
||||
const browserPath = findBrowser();
|
||||
if (!browserPath) fail("No Chrome or Edge found. Pass one with --browser <path>.");
|
||||
const table = args.compare ? { ...SHOTS, ...COMPARE_SHOTS } : SHOTS;
|
||||
const names = args.only ? [args.only] : Object.keys(table);
|
||||
for (const n of names) if (!table[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(table).join(", ")}`);
|
||||
|
||||
SCRATCH = fs.mkdtempSync(path.join(SCRATCH_ROOT, "p2c-shots-"));
|
||||
HOME = path.join(SCRATCH, "console-home");
|
||||
ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER: "1" };
|
||||
ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NOTEPADS_DIR: path.join(SCRATCH, "notepads"), PLAN2CODE_NO_BROWSER: "1" };
|
||||
fs.mkdirSync(HOME, { recursive: true });
|
||||
fs.mkdirSync(OUT, { recursive: true });
|
||||
let browser = null;
|
||||
@@ -342,20 +574,21 @@ async function main() {
|
||||
// and the Ocean highlight is the console's nearest to the Plan2Code blue
|
||||
// the landing page uses.
|
||||
fs.writeFileSync(path.join(HOME, "looks.json"), JSON.stringify({ looks: { role: "engineer", accent: "ocean", welcomeSeen: true } }));
|
||||
browser = await puppeteer.launch({
|
||||
executablePath: browserPath,
|
||||
headless: true,
|
||||
browser = await launchBrowser({
|
||||
...(typeof args.browser === "string" ? { executablePath: args.browser } : {}),
|
||||
args: ["--no-first-run", "--no-default-browser-check", "--mute-audio"],
|
||||
});
|
||||
for (const name of names) {
|
||||
const { sid, url } = stage(project, name);
|
||||
const where = table[name].repo ? makeGitProject() : project;
|
||||
const { sid, url } = stage(where, table[name]);
|
||||
try {
|
||||
if (SHOTS[name].ask) await captureAsk(browser, project, sid, url, SHOTS[name].ask);
|
||||
else await capture(browser, url, name, SHOTS[name]);
|
||||
if (table[name].ask) await captureAsk(browser, where, sid, url, table[name].ask);
|
||||
else await capture(browser, url, name, table[name]);
|
||||
} finally {
|
||||
cli(project, "stop", "--session", sid);
|
||||
cli(where, "stop", "--session", sid);
|
||||
}
|
||||
}
|
||||
if (args.snapshot) fs.writeFileSync(path.resolve(String(args.snapshot)), JSON.stringify(SNAP));
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
if (project) cli(project, "stop", "--all");
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
// The console's stylesheet as the tests read it: the files under
|
||||
// public/styles/ joined in the server's own order, without the accent rules.
|
||||
// A rule moving between files never breaks a test; only a rule that changes
|
||||
// or vanishes does.
|
||||
|
||||
import { joinedStyles } from "../src/web-console/static.mjs";
|
||||
|
||||
export function joinedCss() {
|
||||
return joinedStyles().toString("utf8");
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env node
|
||||
// The cheapest check for a stylesheet move: every element's computed style, on
|
||||
// every screen the console has, in both themes, at desktop and phone width.
|
||||
// Dev-only, not in `npm test`. Stages the screens the way
|
||||
// scripts/capture-screenshots.mjs does (its --snapshot mode), so the sample
|
||||
// project and payloads are the same.
|
||||
//
|
||||
// node scripts/css-snapshot.mjs [--out <file>] write a snapshot
|
||||
// node scripts/css-snapshot.mjs --compare <file> take one now and print every difference
|
||||
//
|
||||
// Take a baseline before moving any rule, then compare after each move. Two
|
||||
// runs in a row on the same stylesheet report nothing: Math.random is pinned,
|
||||
// a property a running animation is moving is recorded as "~" (its animation
|
||||
// fields are still compared), and heights within 4px are ignored (see jitter).
|
||||
|
||||
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";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CAPTURE = path.join(ROOT, "scripts", "capture-screenshots.mjs");
|
||||
|
||||
const args = {};
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const a = process.argv[i];
|
||||
if (a.startsWith("--")) args[a.slice(2)] = process.argv[i + 1] && !process.argv[i + 1].startsWith("--") ? process.argv[++i] : true;
|
||||
}
|
||||
|
||||
function take(file) {
|
||||
// The screenshot script wants a folder to exist for --compare; nothing is written to it.
|
||||
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-css-snap-"));
|
||||
try {
|
||||
const r = spawnSync(process.execPath, [CAPTURE, "--compare", "--snapshot", file, "--out", out], { stdio: ["ignore", "inherit", "inherit"] });
|
||||
if (r.status !== 0) {
|
||||
console.error("the snapshot run failed");
|
||||
process.exit(1);
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
const NAMES = [
|
||||
"display", "position", "top", "right", "bottom", "left", "width", "height", "min-width", "max-width", "min-height", "max-height",
|
||||
"margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left",
|
||||
"color", "background-color", "background-image", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
|
||||
"border-top-style", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "border-top-left-radius",
|
||||
"font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-align", "text-transform",
|
||||
"gap", "grid-template-columns", "grid-template-rows", "grid-column-start", "grid-column-end", "grid-row-start", "grid-row-end",
|
||||
"flex-direction", "flex-wrap", "flex-grow", "flex-shrink", "flex-basis", "align-items", "justify-content", "align-self",
|
||||
"overflow-x", "overflow-y", "opacity", "visibility", "transform", "z-index", "box-shadow", "cursor", "pointer-events", "white-space",
|
||||
"content", "outline-style", "transform-origin", "fill", "stroke",
|
||||
];
|
||||
const ANIMATION = ["animation-name", "animation-duration", "animation-delay", "animation-iteration-count", "animation-timing-function", "animation-direction", "animation-fill-mode"];
|
||||
|
||||
// A growing answer box at phone width settles a few pixels either way from one
|
||||
// run to the next with the same stylesheet; the heights it carries up the page
|
||||
// (and the transform origin, which is half of one) are not a stylesheet's doing.
|
||||
const JITTER = new Set(["height", "min-height", "transform-origin"]);
|
||||
function jitter(name, a, b) {
|
||||
if (!JITTER.has(name)) return false;
|
||||
const na = a.match(/-?\d+(?:\.\d+)?/g);
|
||||
const nb = b.match(/-?\d+(?:\.\d+)?/g);
|
||||
return !!na && !!nb && na.length === nb.length && na.every((n, i) => Math.abs(n - nb[i]) <= 4);
|
||||
}
|
||||
|
||||
function compare(before, after) {
|
||||
const diffs = [];
|
||||
for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
|
||||
const a = before[key];
|
||||
const b = after[key];
|
||||
if (!a || !b) {
|
||||
diffs.push(`${key}: screen ${a ? "missing from the new run" : "is new"}`);
|
||||
continue;
|
||||
}
|
||||
for (const el of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
||||
if (a[el] === b[el] || el.includes("p.dock-say")) continue; // the one line of Planny that types itself in, so its width moves
|
||||
if (a[el] === undefined || b[el] === undefined) {
|
||||
diffs.push(`${key} ${el}: element ${a[el] === undefined ? "added" : "gone"}`);
|
||||
continue;
|
||||
}
|
||||
const x = a[el].split("|");
|
||||
const y = b[el].split("|");
|
||||
const names = NAMES.concat(ANIMATION);
|
||||
x.forEach((v, i) => {
|
||||
if (v !== y[i] && v !== "~" && y[i] !== "~" && !jitter(names[i], v, y[i])) diffs.push(`${key} ${el} ${names[i] ?? i}: ${v} -> ${y[i]}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
return diffs;
|
||||
}
|
||||
|
||||
if (args.compare === true) {
|
||||
console.error("usage: node scripts/css-snapshot.mjs --compare <snapshot file> (or --out <file> to take one)");
|
||||
process.exit(1);
|
||||
} else if (typeof args.compare === "string") {
|
||||
const tmp = path.join(os.tmpdir(), `p2c-css-snap-${process.pid}.json`);
|
||||
take(tmp);
|
||||
const diffs = compare(JSON.parse(fs.readFileSync(args.compare, "utf8")), JSON.parse(fs.readFileSync(tmp, "utf8")));
|
||||
fs.rmSync(tmp, { force: true });
|
||||
for (const d of diffs.slice(0, 200)) console.log(d);
|
||||
if (diffs.length > 200) console.log(`... and ${diffs.length - 200} more`);
|
||||
console.log(diffs.length ? `${diffs.length} difference(s)` : "no differences");
|
||||
process.exit(diffs.length ? 1 : 0);
|
||||
} else {
|
||||
const out = path.resolve(typeof args.out === "string" ? args.out : "css-snapshot.json");
|
||||
take(out);
|
||||
console.log(`wrote ${out} (${Math.round(fs.statSync(out).size / 1024)} KB)`);
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
// Git board fixture: canned state.git snapshots, one per journey step and edge case.
|
||||
//
|
||||
// A copy of specs/git-board-redesign/pathfinder/sketch-00/states.js, the repo
|
||||
// states every Pathfinder sketch moved between. Shape follows
|
||||
// src/web-console/git-repo.mjs snapshot(). `expect` is [primary op, secondary
|
||||
// op] under the agreed next-step rules (nextStep() in git-board.js), and
|
||||
// `expectTab` the tab that owns that step. Times are relative to a fixed NOW,
|
||||
// so ages read the same on every run.
|
||||
|
||||
export const NOW = Date.parse("2026-10-14T12:00:00Z");
|
||||
const ago = (mins) => new Date(NOW - mins * 60000).toISOString();
|
||||
|
||||
const ORIGIN = {
|
||||
name: "origin",
|
||||
url: "git@github.com:jparkerweb/plan2code.git",
|
||||
host: "github.com",
|
||||
web: "https://github.com/jparkerweb/plan2code",
|
||||
kind: "github",
|
||||
};
|
||||
|
||||
const pr = (head) => `https://github.com/jparkerweb/plan2code/compare/main...${head}?expand=1`;
|
||||
|
||||
const last = (subject, author, mins) => ({ subject, author, at: ago(mins) });
|
||||
|
||||
function local(name, extra = {}) {
|
||||
return {
|
||||
name,
|
||||
current: false,
|
||||
default: name === "main",
|
||||
remote: null,
|
||||
upstream: `origin/${name}`,
|
||||
upstreamRemote: "origin",
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
gone: false,
|
||||
merged: false,
|
||||
last: last("Update README", "Justin Parker", 60 * 24),
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
function remoteOnly(name, subject, author, mins) {
|
||||
return { name, current: false, default: false, remote: "origin", upstream: null, upstreamRemote: null, ahead: null, behind: null, gone: false, merged: false, last: last(subject, author, mins) };
|
||||
}
|
||||
|
||||
// The branches every journey shares; `current` and the current row's tracking are set per state.
|
||||
function branches(current, row = {}) {
|
||||
const rows = [
|
||||
local("main", { last: last("Release 4.12.0", "Justin Parker", 60 * 5) }),
|
||||
local("feature/ABC-12001-export-csv", { last: last("Add CSV export button to the audit view", "Justin Parker", 40) }),
|
||||
local("feature/ABC-11980-audit-filter", { last: last("Filter audit events by actor", "Priya Raman", 60 * 26) }),
|
||||
local("fix/ABC-11890-null-ticket", { merged: true, last: last("Guard against a null ticket id", "Sam Okafor", 60 * 24 * 6) }),
|
||||
local("chore/bump-deps", { merged: true, last: last("Bump dev dependencies", "Justin Parker", 60 * 24 * 9) }),
|
||||
remoteOnly("feature/ABC-12010-sso-banner", "Show SSO expiry banner", "Dana Whitfield", 60 * 3),
|
||||
remoteOnly("docs/readme-console", "Document the console's Ask tab", "Priya Raman", 60 * 24 * 2),
|
||||
];
|
||||
if (!rows.some((b) => b.name === current)) rows.splice(1, 0, local(current, { upstream: null, upstreamRemote: null, ahead: null, behind: null }));
|
||||
return rows.map((b) => (b.name === current && !b.remote ? { ...b, current: true, ...row } : b));
|
||||
}
|
||||
|
||||
const NO_CHANGES = { count: 0, heldBack: 0, files: [], untrackedDirs: [] };
|
||||
|
||||
const DIRTY_FEATURE = {
|
||||
count: 4,
|
||||
heldBack: 1,
|
||||
files: [
|
||||
{ path: "src/web-console/public/audit-export.js", state: "modified", staged: false, risky: false },
|
||||
{ path: "src/web-console/public/app.css", state: "modified", staged: false, risky: false },
|
||||
{ path: ".env.local", state: "new", staged: false, risky: true },
|
||||
],
|
||||
untrackedDirs: [{ path: "scripts/fixtures/audit/", files: 6 }],
|
||||
};
|
||||
|
||||
const DIRTY_MAIN = {
|
||||
count: 2,
|
||||
heldBack: 0,
|
||||
files: [
|
||||
{ path: "src/web-console/public/login.js", state: "modified", staged: false, risky: false },
|
||||
{ path: "scripts/test-login.mjs", state: "new", staged: false, risky: false },
|
||||
],
|
||||
untrackedDirs: [],
|
||||
};
|
||||
|
||||
function snap({ branch, ahead = 0, behind = 0, upstream, gone = false, changes = NO_CHANGES, inProgress = null, conflicted = [], lastFetch = ago(5), remotes = [ORIGIN], rows, prUrl = null, hasCommits = true, detached = null, rebasing }) {
|
||||
const up = upstream === undefined ? (branch ? `origin/${branch}` : null) : upstream;
|
||||
return {
|
||||
at: new Date(NOW).toISOString(),
|
||||
repo: true,
|
||||
hasCommits,
|
||||
head: { branch, detached, ...(rebasing ? { rebasing } : {}), upstream: up, gone, ahead: up ? ahead : null, behind: up ? behind : null },
|
||||
defaultBranch: "main",
|
||||
inProgress,
|
||||
conflicted,
|
||||
changes,
|
||||
remotes,
|
||||
lastFetch,
|
||||
refreshFailed: false,
|
||||
branches: rows || branches(branch, { upstream: up, upstreamRemote: up ? "origin" : null, ahead: up ? ahead : null, behind: up ? behind : null, gone }),
|
||||
prUrl,
|
||||
};
|
||||
}
|
||||
|
||||
const EXPORT = "feature/ABC-12001-export-csv";
|
||||
const LOGIN = "fix/ABC-12044-login-redirect";
|
||||
const FILTER = "feature/ABC-11980-audit-filter";
|
||||
|
||||
/** The three journeys, in click order. */
|
||||
export const JOURNEYS = [
|
||||
{ id: "commit-push", title: "Commit & push", states: ["cp-dirty", "cp-committing", "cp-ahead", "cp-pushing", "cp-pushed"] },
|
||||
{ id: "new-branch", title: "Start a new branch", states: ["nb-main-dirty", "nb-creating", "nb-unpublished", "nb-publishing", "nb-published"] },
|
||||
{ id: "pull-conflict", title: "Recover from a pull conflict", states: ["pc-diverged", "pc-pulling", "pc-conflict", "pc-resolved", "pc-continuing", "pc-rebased", "pc-pushing", "pc-pushed"] },
|
||||
];
|
||||
|
||||
/**
|
||||
* Every state: `git` (the snapshot), `journey` and `step` (or "edge"), `title`,
|
||||
* `expect` (primary op, secondary op or null), `expectTab` (the tab owning the
|
||||
* next step), `expectLine` where the line itself is pinned, `busy` (what is
|
||||
* running, when a git command is), `result` (the git-result notice after the
|
||||
* last action), and `on` (board op -> next state id) for the clicks a journey
|
||||
* takes.
|
||||
*/
|
||||
export const STATES = {
|
||||
/* Commit & push, on a published feature branch */
|
||||
"cp-dirty": {
|
||||
journey: "commit-push", step: 1, title: "4 changes on a feature branch (one held back)",
|
||||
git: snap({ branch: EXPORT, changes: DIRTY_FEATURE, prUrl: pr(EXPORT) }),
|
||||
expect: ["commit", "pr"],
|
||||
expectTab: "changes",
|
||||
on: { commit: "cp-committing" },
|
||||
},
|
||||
"cp-committing": {
|
||||
journey: "commit-push", step: 2, title: "Committing (busy)", busy: "Committing 3 files on feature/ABC-12001-export-csv",
|
||||
git: snap({ branch: EXPORT, changes: DIRTY_FEATURE, prUrl: pr(EXPORT) }),
|
||||
expect: ["commit", "pr"],
|
||||
expectTab: "changes",
|
||||
on: { done: "cp-ahead" },
|
||||
},
|
||||
"cp-ahead": {
|
||||
journey: "commit-push", step: 3, title: "Committed, 1 to push",
|
||||
result: { title: "Committed 3 files", body: "`9f3c2ab` Add CSV export button to the audit view. `.env.local` was held back." },
|
||||
git: snap({ branch: EXPORT, ahead: 1, changes: { count: 1, heldBack: 1, files: [DIRTY_FEATURE.files[2]], untrackedDirs: [] }, prUrl: pr(EXPORT) }),
|
||||
expect: ["push", "pr"],
|
||||
expectTab: "sync",
|
||||
on: { push: "cp-pushing" },
|
||||
},
|
||||
"cp-pushing": {
|
||||
journey: "commit-push", step: 4, title: "Pushing (busy)", busy: "Pushing 1 commit to origin",
|
||||
git: snap({ branch: EXPORT, ahead: 1, changes: { count: 1, heldBack: 1, files: [DIRTY_FEATURE.files[2]], untrackedDirs: [] }, prUrl: pr(EXPORT) }),
|
||||
expect: ["push", "pr"],
|
||||
expectTab: "sync",
|
||||
on: { done: "cp-pushed" },
|
||||
},
|
||||
"cp-pushed": {
|
||||
journey: "commit-push", step: 5, title: "Pushed, pull request ready",
|
||||
result: { title: "Pushed 1 commit to origin/feature/ABC-12001-export-csv", body: `\`9f3c2ab\`. [Open pull request](${pr(EXPORT)})` },
|
||||
git: snap({ branch: EXPORT, changes: { count: 1, heldBack: 1, files: [DIRTY_FEATURE.files[2]], untrackedDirs: [] }, prUrl: pr(EXPORT) }),
|
||||
expect: ["pr", "cleanup"],
|
||||
expectTab: "sync",
|
||||
on: {},
|
||||
},
|
||||
|
||||
/* Start a new branch, from changes made on main */
|
||||
"nb-main-dirty": {
|
||||
journey: "new-branch", step: 1, title: "2 changes on main",
|
||||
git: snap({ branch: "main", changes: DIRTY_MAIN }),
|
||||
expect: ["create-commit", "commit"],
|
||||
expectTab: "changes",
|
||||
on: { "create-commit": "nb-creating", create: "nb-creating" },
|
||||
},
|
||||
"nb-creating": {
|
||||
journey: "new-branch", step: 2, title: "Creating the branch and committing (busy)", busy: "Creating fix/ABC-12044-login-redirect from origin/main, then committing 2 files",
|
||||
git: snap({ branch: "main", changes: DIRTY_MAIN }),
|
||||
expect: ["create-commit", "commit"],
|
||||
expectTab: "changes",
|
||||
on: { done: "nb-unpublished" },
|
||||
},
|
||||
"nb-unpublished": {
|
||||
journey: "new-branch", step: 3, title: "New branch with 1 commit, not published",
|
||||
result: { title: "Created fix/ABC-12044-login-redirect and committed 2 files", body: "`4e7d1c0` Redirect to the login page after SSO expiry." },
|
||||
git: snap({ branch: LOGIN, upstream: null }),
|
||||
expect: ["publish", "cleanup"],
|
||||
expectTab: "sync",
|
||||
on: { publish: "nb-publishing" },
|
||||
},
|
||||
"nb-publishing": {
|
||||
journey: "new-branch", step: 4, title: "Publishing (busy)", busy: "Publishing fix/ABC-12044-login-redirect to origin",
|
||||
git: snap({ branch: LOGIN, upstream: null }),
|
||||
expect: ["publish", "cleanup"],
|
||||
expectTab: "sync",
|
||||
on: { done: "nb-published" },
|
||||
},
|
||||
"nb-published": {
|
||||
journey: "new-branch", step: 5, title: "Published, pull request ready",
|
||||
result: { title: "Published fix/ABC-12044-login-redirect to origin", body: `[Open pull request](${pr(LOGIN)})` },
|
||||
git: snap({ branch: LOGIN, prUrl: pr(LOGIN) }),
|
||||
expect: ["pr", "cleanup"],
|
||||
expectTab: "sync",
|
||||
on: {},
|
||||
},
|
||||
|
||||
/* Recover from a pull conflict */
|
||||
"pc-diverged": {
|
||||
journey: "pull-conflict", step: 1, title: "1 ahead, 3 behind",
|
||||
git: snap({ branch: FILTER, ahead: 1, behind: 3, prUrl: pr(FILTER) }),
|
||||
expect: ["pull", "push"],
|
||||
expectTab: "sync",
|
||||
on: { pull: "pc-pulling" },
|
||||
},
|
||||
"pc-pulling": {
|
||||
journey: "pull-conflict", step: 2, title: "Pulling (busy)", busy: "Pulling origin/feature/ABC-11980-audit-filter (rebase)",
|
||||
git: snap({ branch: FILTER, ahead: 1, behind: 3, prUrl: pr(FILTER) }),
|
||||
expect: ["pull", "push"],
|
||||
expectTab: "sync",
|
||||
on: { done: "pc-conflict" },
|
||||
},
|
||||
"pc-conflict": {
|
||||
journey: "pull-conflict", step: 3, title: "Rebase stopped on 2 conflicts, 1 with markers left",
|
||||
result: { title: "Pull stopped on 2 conflicts", body: "Replaying `b81e9d4` Filter audit events by actor (1 of 1). Plan2Code resolved `src/web-console/public/audit.js`; `src/web-console/public/audit.css` still has markers." },
|
||||
git: snap({
|
||||
branch: null, detached: "b81e9d4", rebasing: FILTER, upstream: null, inProgress: "rebase",
|
||||
conflicted: [
|
||||
{ path: "src/web-console/public/audit.js", markers: false },
|
||||
{ path: "src/web-console/public/audit.css", markers: true },
|
||||
],
|
||||
rows: branches(FILTER, { ahead: 1, behind: 3 }),
|
||||
}),
|
||||
expect: ["fix", "abort"],
|
||||
expectTab: "sync",
|
||||
on: { continue: "pc-conflict", abort: "pc-diverged", fix: "pc-resolved" },
|
||||
},
|
||||
"pc-resolved": {
|
||||
journey: "pull-conflict", step: 4, title: "Every conflict resolved",
|
||||
git: snap({
|
||||
branch: null, detached: "b81e9d4", rebasing: FILTER, upstream: null, inProgress: "rebase",
|
||||
conflicted: [
|
||||
{ path: "src/web-console/public/audit.js", markers: false },
|
||||
{ path: "src/web-console/public/audit.css", markers: false },
|
||||
],
|
||||
rows: branches(FILTER, { ahead: 1, behind: 3 }),
|
||||
}),
|
||||
expect: ["continue", "abort"],
|
||||
expectTab: "sync",
|
||||
on: { continue: "pc-continuing", abort: "pc-diverged" },
|
||||
},
|
||||
"pc-continuing": {
|
||||
journey: "pull-conflict", step: 5, title: "Continuing the rebase (busy)", busy: "Continuing the rebase",
|
||||
git: snap({
|
||||
branch: null, detached: "b81e9d4", rebasing: FILTER, upstream: null, inProgress: "rebase",
|
||||
conflicted: [
|
||||
{ path: "src/web-console/public/audit.js", markers: false },
|
||||
{ path: "src/web-console/public/audit.css", markers: false },
|
||||
],
|
||||
rows: branches(FILTER, { ahead: 1, behind: 3 }),
|
||||
}),
|
||||
expect: ["continue", "abort"],
|
||||
expectTab: "sync",
|
||||
on: { done: "pc-rebased" },
|
||||
},
|
||||
"pc-rebased": {
|
||||
journey: "pull-conflict", step: 6, title: "Rebased, 1 to push",
|
||||
result: { title: "Pull finished", body: "1 commit replayed on top of origin. Resolved `audit.js` (kept both filters) and `audit.css` (you fixed it). 1 commit ready to push." },
|
||||
git: snap({ branch: FILTER, ahead: 1, prUrl: pr(FILTER) }),
|
||||
expect: ["push", "pr"],
|
||||
expectTab: "sync",
|
||||
on: { push: "pc-pushing" },
|
||||
},
|
||||
"pc-pushing": {
|
||||
journey: "pull-conflict", step: 7, title: "Pushing (busy)", busy: "Pushing 1 commit to origin",
|
||||
git: snap({ branch: FILTER, ahead: 1, prUrl: pr(FILTER) }),
|
||||
expect: ["push", "pr"],
|
||||
expectTab: "sync",
|
||||
on: { done: "pc-pushed" },
|
||||
},
|
||||
"pc-pushed": {
|
||||
journey: "pull-conflict", step: 8, title: "Pushed, pull request ready",
|
||||
result: { title: `Pushed 1 commit to origin/${FILTER}`, body: `\`c42d7e1\`. [Open pull request](${pr(FILTER)})` },
|
||||
git: snap({ branch: FILTER, prUrl: pr(FILTER) }),
|
||||
expect: ["pr", "cleanup"],
|
||||
expectTab: "sync",
|
||||
on: {},
|
||||
},
|
||||
|
||||
/* Edges that break layouts */
|
||||
"e-caught-up": {
|
||||
journey: "edge", title: "All caught up on main",
|
||||
git: snap({ branch: "main", rows: branches("main").map((b) => ({ ...b, merged: false })) }),
|
||||
expect: [null, "create"],
|
||||
expectTab: "sync",
|
||||
expectLine: "All caught up on main · checked 5 min. ago",
|
||||
on: {},
|
||||
},
|
||||
"e-stale": {
|
||||
journey: "edge", title: "All caught up, but last checked 3 hours ago",
|
||||
git: snap({ branch: "main", lastFetch: ago(180), rows: branches("main").map((b) => ({ ...b, merged: false })) }),
|
||||
expect: [null, "create"],
|
||||
expectTab: "sync",
|
||||
expectLine: "All caught up on main · checked 3 hr. ago",
|
||||
on: { refresh: "e-caught-up" },
|
||||
},
|
||||
"e-held-only": {
|
||||
journey: "edge", title: "Caught up except a held-back file",
|
||||
git: snap({ branch: "main", changes: { count: 1, heldBack: 1, files: [{ path: ".env.local", state: "new", staged: false, risky: true }], untrackedDirs: [] }, rows: branches("main").map((b) => ({ ...b, merged: false })) }),
|
||||
expect: [null, "ignore"],
|
||||
expectTab: "changes",
|
||||
on: {},
|
||||
},
|
||||
"e-gone": {
|
||||
journey: "edge", title: "Remote copy deleted",
|
||||
git: snap({ branch: "feature/ABC-11702-old-banner", gone: true }),
|
||||
expect: ["publish", "cleanup"],
|
||||
expectTab: "sync",
|
||||
on: {},
|
||||
},
|
||||
"e-no-remote": {
|
||||
journey: "edge", title: "No remote at all",
|
||||
git: snap({ branch: "main", upstream: null, remotes: [], lastFetch: null, rows: [local("main", { current: true, upstream: null, upstreamRemote: null, ahead: null, behind: null })] }),
|
||||
expect: [null, "create"],
|
||||
expectTab: "sync",
|
||||
expectLine: "Nothing to commit on main · no remote yet",
|
||||
on: {},
|
||||
},
|
||||
"e-first-commit": {
|
||||
journey: "edge", title: "No commits yet",
|
||||
git: snap({
|
||||
branch: "main", hasCommits: false, upstream: null, remotes: [], lastFetch: null, rows: [],
|
||||
changes: { count: 3, heldBack: 0, files: [{ path: "README.md", state: "new", staged: false, risky: false }, { path: "package.json", state: "new", staged: false, risky: false }], untrackedDirs: [{ path: "src/", files: 12 }] },
|
||||
}),
|
||||
expect: ["commit", null],
|
||||
expectTab: "changes",
|
||||
on: {},
|
||||
},
|
||||
"e-detached": {
|
||||
journey: "edge", title: "Detached at a commit",
|
||||
git: snap({ branch: null, detached: "a1b2c3d", upstream: null, rows: branches("main").map((b) => ({ ...b, current: false })) }),
|
||||
expect: ["create", "cleanup"],
|
||||
expectTab: "branches",
|
||||
on: {},
|
||||
},
|
||||
"e-many-branches": {
|
||||
journey: "edge", title: "300 branches, 40 merged",
|
||||
git: snap({
|
||||
branch: "main",
|
||||
rows: [
|
||||
local("main", { current: true }),
|
||||
...Array.from({ length: 120 }, (_, i) =>
|
||||
local(`feature/ABC-${11000 + i}-${["export", "filter", "banner", "login", "audit", "sso"][i % 6]}-${i}`, {
|
||||
merged: i < 40,
|
||||
ahead: i % 7 === 0 ? 2 : 0,
|
||||
behind: i % 5 === 0 ? 4 : 0,
|
||||
last: last(`Work on ABC-${11000 + i}`, ["Justin Parker", "Priya Raman", "Sam Okafor", "Dana Whitfield"][i % 4], 60 * (i + 1)),
|
||||
}),
|
||||
),
|
||||
...Array.from({ length: 179 }, (_, i) => remoteOnly(`feature/ABC-${12100 + i}-remote-${i}`, `Remote work ${i}`, "Dana Whitfield", 60 * 24 + i * 30)),
|
||||
],
|
||||
}),
|
||||
expect: ["cleanup", null],
|
||||
expectTab: "branches",
|
||||
on: {},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,127 @@
|
||||
// Start a real console and open its page in a real browser, for the page tests
|
||||
// (scripts/test-web-console-page-*.mjs).
|
||||
//
|
||||
// One browser per test file (pageSuite), a fresh console session and browser
|
||||
// context per test (openSession). Sessions run against the file's own console
|
||||
// home from web-console-test-helpers.mjs, in a temp project unless a test
|
||||
// names one. Any uncaught error on the page fails the test that opened it, so
|
||||
// a later split that breaks a screen shows as a named error, not a blank page.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { cli, payload, until, HOME, REMEMBERED } from "./web-console-test-helpers.mjs";
|
||||
import { launchBrowser } from "./browser.mjs";
|
||||
|
||||
// `test` is node:test's test function (or any context with .after): the
|
||||
// browser is launched the first time a test asks for it and closed once the
|
||||
// file is done.
|
||||
export function pageSuite(test) {
|
||||
let launching = null;
|
||||
test.after(async () => {
|
||||
if (launching) await (await launching).close();
|
||||
});
|
||||
return {
|
||||
browser: () => (launching ??= launchBrowser()),
|
||||
};
|
||||
}
|
||||
|
||||
let projects = 0;
|
||||
let payloads = 0;
|
||||
|
||||
// A fresh project folder under the file's console home, removed with it.
|
||||
export function tempProject(files = {}) {
|
||||
const dir = path.join(HOME, "projects", `p${++projects}`);
|
||||
for (const [rel, text] of Object.entries(files)) {
|
||||
fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, rel), text);
|
||||
}
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
// Opens a console session the way an agent does (`console.mjs open`, then
|
||||
// `post`), and its page in a new browser context. Resolves once the page has
|
||||
// drawn from the session's real state, not the boot pane in the markup.
|
||||
// `t` is the test's context: stop() is registered with t.after, so a failing
|
||||
// test still cleans up, and a page error fails the test. `clock: true` gives
|
||||
// the page Playwright's fake clock before it loads (s.page.clock), so a test
|
||||
// can jump past the page's silence limits instead of sitting through them.
|
||||
export async function openSession(browser, { t, workflow, payload: first, project, open = [], clock = false }) {
|
||||
fs.rmSync(REMEMBERED, { force: true });
|
||||
const cwd = project || tempProject();
|
||||
const opened = cli(["open", "--workflow", workflow, "--no-open", ...open], { cwd }).json;
|
||||
const s = {
|
||||
sid: opened.sid,
|
||||
session: opened.session,
|
||||
url: opened.url,
|
||||
project: cwd,
|
||||
errors: [],
|
||||
context: null,
|
||||
page: null,
|
||||
};
|
||||
|
||||
// The agent's side, run from the project like an agent would.
|
||||
s.post = (patch) => {
|
||||
const r = cli(["post", "--session", s.sid, "--file", payload(`page-post-${++payloads}.json`, patch)], { cwd });
|
||||
if (r.status !== 0) throw new Error(`post failed (${r.status}): ${r.stderr}`);
|
||||
return r.json;
|
||||
};
|
||||
s.wait = (seconds = 10) => {
|
||||
const r = cli(["wait", "--session", s.sid, "--seconds", String(seconds)], { cwd });
|
||||
return { code: r.status, ...(r.json || {}) };
|
||||
};
|
||||
// Whether the session's server still answers on its port.
|
||||
s.answers = async () => {
|
||||
try {
|
||||
await fetch(new URL("/health", s.url), { signal: AbortSignal.timeout(1000) });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
let stopped = false;
|
||||
s.stop = async () => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
cli(["stop", "--session", s.sid], { cwd });
|
||||
if (s.context) await s.context.close().catch(() => {});
|
||||
await until(async () => !(await s.answers()), 5000);
|
||||
};
|
||||
t.after(async () => {
|
||||
await s.stop();
|
||||
if (s.errors.length) throw new Error(`uncaught error on the page: ${s.errors[0]}`);
|
||||
});
|
||||
|
||||
if (first) s.post(first);
|
||||
s.context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
if (clock) await s.context.clock.install();
|
||||
s.page = await s.context.newPage();
|
||||
s.page.on("pageerror", (e) => s.errors.push(e.message));
|
||||
await s.page.goto(s.url, { waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
return s;
|
||||
}
|
||||
|
||||
// The page has adopted a state frame: app.js has replaced the boot pane the
|
||||
// markup ships with.
|
||||
export async function drawn(page) {
|
||||
await page.waitForFunction(() => !document.querySelector("#main .boot-pane"), null, { timeout: 15000 });
|
||||
}
|
||||
|
||||
// Presses Send on the page and collects the send the way an agent's `wait`
|
||||
// does: the same JSON an agent receives.
|
||||
export async function sendAndCollect(s) {
|
||||
await s.page.click("#btn-send");
|
||||
const got = s.wait(10);
|
||||
if (got.code !== 0) throw new Error(`nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
// The card for one item id.
|
||||
export const itemCard = (page, id) => page.locator(`[data-item="${id}"]`).first();
|
||||
|
||||
// A locator's visible text, trimmed.
|
||||
export const textOf = async (locator) => (await locator.innerText()).trim();
|
||||
|
||||
// The scroll offset of the first element matching `selector`.
|
||||
export const scrollTopOf = (page, selector) => page.$eval(selector, (el) => el.scrollTop);
|
||||
@@ -10,7 +10,19 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const DIR = path.join(ROOT, "src", "web-console", "public");
|
||||
const FILES = ["app.js", "answers.js", "render.js", "palette.js", "starters.js", "favicon.js"];
|
||||
// Every page module (vendored code aside), found by walking public/ so a new
|
||||
// screen is guarded without editing a list.
|
||||
function pageModules(dir, rel = "") {
|
||||
const out = [];
|
||||
for (const e of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
|
||||
const p = rel ? `${rel}/${e.name}` : e.name;
|
||||
if (e.isDirectory()) {
|
||||
if (p !== "vendor") out.push(...pageModules(dir, p));
|
||||
} else if (e.name.endsWith(".js")) out.push(p);
|
||||
}
|
||||
return out.sort();
|
||||
}
|
||||
const FILES = pageModules(DIR);
|
||||
|
||||
let bad = 0;
|
||||
for (const name of FILES) {
|
||||
@@ -20,7 +32,7 @@ for (const name of FILES) {
|
||||
console.log(` ok ${name}`);
|
||||
} catch (err) {
|
||||
// A module that parses but cannot run here (app.js touches `document` at
|
||||
// import) is fine; only a parse failure is a real problem.
|
||||
// import, and relative imports cannot resolve from a data: URL) is fine; only a parse failure is a real problem.
|
||||
const parseFailure = err instanceof SyntaxError;
|
||||
if (parseFailure) {
|
||||
bad++;
|
||||
|
||||
@@ -13,6 +13,24 @@ and dark WebP images in `docs/screenshots/`.
|
||||
| `build.json` | A phase being built: the progress bar, the task list and the current task |
|
||||
| `signoff.json` | The completion report and the sign-off card |
|
||||
| `finish.json` | The finished screen after sign-off (posted after `signoff.json`) |
|
||||
| `git.json` | The git board, handed back to you in a sample repository with three changes to commit (the script builds the repository) |
|
||||
|
||||
Refresh every image with `node scripts/capture-screenshots.mjs`, or one with
|
||||
`--only <shot>`.
|
||||
|
||||
## Comparison-only shots
|
||||
|
||||
`--compare` adds the screens the docs never show, so a change to the console
|
||||
can be checked by eye against a "before" set. They are never published: the
|
||||
script refuses `--compare` with an `--out` inside `docs/screenshots/`.
|
||||
|
||||
| File | Stages |
|
||||
| --- | --- |
|
||||
| `stop.json` | A build with a question open, behind the Stop dialog and its handoff choice |
|
||||
| `delete.json` | The dashboard, behind the first step of a spec chip's Delete |
|
||||
| `help.json` | A Plan question, behind Help on its first tab |
|
||||
| `prefs.json` | A Plan question, behind User Preferences |
|
||||
| `cleanup.json` | A Plan question, behind User Preferences scrolled to Cleanup after a scan |
|
||||
| `workspace.json` | A Plan question, behind the Workspace panel with a second folder added (shot last: the console remembers the folder) |
|
||||
|
||||
`node scripts/capture-screenshots.mjs --compare --out <folder outside the repo>`
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 3 of 7: Signing in",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q4",
|
||||
"kind": "text",
|
||||
"title": "How callers sign in",
|
||||
"body": "Do callers sign in as a person, or as an app with a key?",
|
||||
"placeholder": "For example: apps use an API key per team."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"menu": {
|
||||
"note": "task-api is built up to Phase 2 of 4. Phase 3 is next.",
|
||||
"recommend": "plan2code-3-implement",
|
||||
"details": {
|
||||
"plan2code-3-implement": "Phase 3 of 4 is next"
|
||||
}
|
||||
},
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"reread": true,
|
||||
"board": { "describe": "task-schema-and-paging" },
|
||||
"agent": { "status": "waiting" }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 2 of 7: Who calls it",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q3",
|
||||
"kind": "text",
|
||||
"title": "Who calls the API",
|
||||
"body": "Which apps call the task API first, and what does each need from it?",
|
||||
"placeholder": "For example: the web app lists tasks, the mobile app only updates their status."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 3 of 7: Signing in",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q4",
|
||||
"kind": "text",
|
||||
"title": "How callers sign in",
|
||||
"body": "Do callers sign in as a person, or as an app with a key?",
|
||||
"placeholder": "For example: apps use an API key per team."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"workflow": "implement",
|
||||
"title": "task-api: Phase 3",
|
||||
"specDir": "specs/task-api",
|
||||
"headline": {
|
||||
"stage": "Phase 3: API endpoints",
|
||||
"cleared": 2,
|
||||
"total": 4
|
||||
},
|
||||
"docs": [
|
||||
{
|
||||
"id": "phase",
|
||||
"title": "Phase 3 tasks",
|
||||
"blocks": [
|
||||
{
|
||||
"id": "tasks",
|
||||
"state": "settled",
|
||||
"md": "- [x] **Task 3.1:** Add GET /tasks with cursor paging\n- [x] **Task 3.2:** Add POST /tasks\n- [ ] **Task 3.3:** Add PATCH /tasks/:id\n- [ ] **Task 3.4:** Add DELETE /tasks/:id"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"items": [
|
||||
{
|
||||
"id": "keep",
|
||||
"kind": "confirm",
|
||||
"title": "Tests are failing",
|
||||
"body": "Two paging tests fail after Task 3.2. Fix them before going on?",
|
||||
"yesLabel": "Fix them now",
|
||||
"noLabel": "Note them and go on"
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 2 of 7: Who calls it",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q3",
|
||||
"kind": "text",
|
||||
"title": "Who calls the API",
|
||||
"body": "Which apps call the task API first, and what does each need from it?",
|
||||
"placeholder": "For example: the web app lists tasks, the mobile app only updates their status."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,13 @@ export function scrubbedEnv(extra = {}) {
|
||||
return { ...e, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG, ...extra };
|
||||
}
|
||||
|
||||
// Every git in a test process that imports this file runs under that same
|
||||
// scrubbed config: fixture commands, the modules a test imports and the
|
||||
// scripts it spawns. Mixed configs disagree: a global core.autocrlf=true once
|
||||
// checked fixtures out with CRLF that the scrubbed scripts read as changed.
|
||||
for (const k of AMBIENT_GIT_ENV) delete process.env[k];
|
||||
Object.assign(process.env, { GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG });
|
||||
|
||||
export function runScript(skill, script, args, { cwd, env } = {}) {
|
||||
const r = spawnSync(process.execPath, [path.join(SKILLS, skill, "scripts", script), ...args], {
|
||||
cwd: cwd || ROOT,
|
||||
@@ -83,7 +90,7 @@ export function write(root, rel, content) {
|
||||
|
||||
export const read = (root, rel) => fs.readFileSync(path.join(root, rel), "utf8");
|
||||
|
||||
/** A git runner for `dir`. */
|
||||
/** A git runner for `dir`, under the scrubbed config set beside `scrubbedEnv`. */
|
||||
export const gitIn = (dir) => (...a) => execFileSync("git", a, { cwd: dir, stdio: "pipe", encoding: "utf8" });
|
||||
|
||||
export function gitInit(dir, branch = "main") {
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
// Tests for the shared browser helper (scripts/browser.mjs) and the two dev
|
||||
// scripts that launch a browser through it. Run with:
|
||||
// node --test scripts/test-browser-helper.mjs
|
||||
//
|
||||
// The unit cases hand findBrowser() a fake `exists`, so they run anywhere. The
|
||||
// live cases launch a real Chrome or Edge and skip when none is installed.
|
||||
|
||||
import test 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 { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
test("playwright-core is pinned exactly in the root devDependencies", () => {
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8"));
|
||||
assert.equal(pkg.devDependencies["playwright-core"], "1.64.1");
|
||||
});
|
||||
|
||||
// A fake file system holding only `present`.
|
||||
const only = (...present) => (p) => present.includes(p);
|
||||
|
||||
test("findBrowser picks Chrome, then Edge, and honours PLAN2CODE_TEST_BROWSER", async () => {
|
||||
const { findBrowser, BROWSER_PATHS } = await import("./browser.mjs");
|
||||
const chrome = BROWSER_PATHS.chrome[0];
|
||||
const edge = BROWSER_PATHS.msedge[0];
|
||||
|
||||
assert.deepEqual(findBrowser({ env: {}, exists: only(edge) }), { channel: "msedge", path: edge });
|
||||
assert.deepEqual(findBrowser({ env: {}, exists: only(chrome, edge) }), { channel: "chrome", path: chrome });
|
||||
assert.deepEqual(findBrowser({ env: { PLAN2CODE_TEST_BROWSER: "msedge" }, exists: only(chrome, edge) }), { channel: "msedge", path: edge });
|
||||
assert.deepEqual(findBrowser({ env: { PLAN2CODE_TEST_BROWSER: "chrome" }, exists: only(edge) }), null);
|
||||
assert.deepEqual(findBrowser.checked, BROWSER_PATHS.chrome);
|
||||
assert.throws(() => findBrowser({ env: { PLAN2CODE_TEST_BROWSER: "firefox" }, exists: only(chrome) }), (e) => /chrome/.test(e.message) && /msedge/.test(e.message));
|
||||
|
||||
assert.equal(findBrowser({ env: {}, exists: only() }), null);
|
||||
assert.deepEqual(findBrowser.checked, [...BROWSER_PATHS.chrome, ...BROWSER_PATHS.msedge]);
|
||||
});
|
||||
|
||||
test("browserProblem says what is missing in one line of our own words", async () => {
|
||||
const { browserProblem } = await import("./browser.mjs");
|
||||
const found = { channel: "chrome", path: "C:\chrome.exe" };
|
||||
|
||||
const oldNode = browserProblem({ nodeVersion: "18.19.0", found });
|
||||
assert.equal(oldNode, "Page tests need Node 20 or newer (this is 18.19.0). Users of Plan2Code still only need Node 18.");
|
||||
|
||||
const checked = ["C:\a\chrome.exe", "/usr/bin/microsoft-edge"];
|
||||
const none = browserProblem({ nodeVersion: "24.12.0", found: null, checked });
|
||||
assert.match(none, /^Page tests need Chrome or Edge\. Looked in: /);
|
||||
for (const p of checked) assert.ok(none.includes(p), `names ${p}`);
|
||||
assert.ok(none.endsWith("Install either one, or set PLAN2CODE_TEST_BROWSER."));
|
||||
|
||||
assert.equal(browserProblem({ nodeVersion: "24.12.0", found }), null);
|
||||
for (const line of [oldNode, none]) {
|
||||
assert.ok(!line.includes("\n"));
|
||||
assert.ok(!line.includes("playwright install"));
|
||||
}
|
||||
});
|
||||
|
||||
test("launchBrowser fails with our one line when the forced browser is missing", async () => {
|
||||
const { launchBrowser, BROWSER_PATHS } = await import("./browser.mjs");
|
||||
const edgeOnly = only(BROWSER_PATHS.msedge[0]);
|
||||
await assert.rejects(launchBrowser({}, { env: { PLAN2CODE_TEST_BROWSER: "chrome" }, exists: edgeOnly }), (e) => {
|
||||
assert.equal(e.browserProblem, true);
|
||||
assert.match(e.message, /^Page tests need Chrome or Edge\. Looked in: /);
|
||||
assert.ok(!e.message.includes("\n"));
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
test("launchBrowser opens a page in the installed browser", async (t) => {
|
||||
const { launchBrowser, findBrowser } = await import("./browser.mjs");
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await page.goto("data:text/html,<p>ok</p>");
|
||||
assert.equal(await page.textContent("p"), "ok");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
|
||||
// Width and height from a WebP file's first chunk (lossy VP8, lossless VP8L,
|
||||
// or the extended VP8X header).
|
||||
function webpSize(buf) {
|
||||
assert.equal(buf.toString("ascii", 0, 4), "RIFF");
|
||||
assert.equal(buf.toString("ascii", 8, 12), "WEBP");
|
||||
const chunk = buf.toString("ascii", 12, 16);
|
||||
if (chunk === "VP8 ") return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };
|
||||
if (chunk === "VP8L") {
|
||||
const bits = buf.readUInt32LE(21);
|
||||
return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
|
||||
}
|
||||
if (chunk === "VP8X") return { width: buf.readUIntLE(24, 3) + 1, height: buf.readUIntLE(27, 3) + 1 };
|
||||
throw new Error(`unknown WebP chunk ${chunk}`);
|
||||
}
|
||||
|
||||
const CAPTURE = path.join(ROOT, "scripts", "capture-screenshots.mjs");
|
||||
|
||||
test("capture-screenshots writes both themes as 2560x1600 WebP (slow)", { timeout: 120000 }, async (t) => {
|
||||
const { findBrowser } = await import("./browser.mjs");
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shots-test-"));
|
||||
try {
|
||||
const r = spawnSync(process.execPath, [CAPTURE, "--only", "question", "--out", out], { encoding: "utf8", timeout: 110000 });
|
||||
assert.equal(r.status, 0, r.stderr || r.stdout);
|
||||
for (const theme of ["light", "dark"]) {
|
||||
const buf = fs.readFileSync(path.join(out, `question-${theme}.webp`));
|
||||
assert.deepEqual(webpSize(buf), { width: 2560, height: 1600 });
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("capture-screenshots --compare refuses to write into docs/screenshots", () => {
|
||||
// A shot that does not exist: were the guard ever to break, the run would
|
||||
// stop at "Unknown shot" (which never names docs/screenshots) rather than
|
||||
// shoot every screen into the published folder.
|
||||
const argv = [CAPTURE, "--compare", "--only", "__no-such-shot__", "--out", path.join(ROOT, "docs", "screenshots")];
|
||||
const r = spawnSync(process.execPath, argv, { encoding: "utf8", timeout: 30000 });
|
||||
assert.notEqual(r.status, 0);
|
||||
const lines = r.stderr.trim().split("\n");
|
||||
assert.equal(lines.length, 1, r.stderr);
|
||||
assert.match(lines[0], /docs[\\/]screenshots/);
|
||||
});
|
||||
|
||||
test("capture-screenshots --compare shoots the comparison-only screens (slow)", { timeout: 120000 }, async (t) => {
|
||||
const { findBrowser } = await import("./browser.mjs");
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-compare-test-"));
|
||||
try {
|
||||
const r = spawnSync(process.execPath, [CAPTURE, "--compare", "--only", "help", "--out", out], { encoding: "utf8", timeout: 110000 });
|
||||
assert.equal(r.status, 0, r.stderr || r.stdout);
|
||||
for (const theme of ["light", "dark"]) assert.ok(fs.statSync(path.join(out, `help-${theme}.webp`)).size > 0);
|
||||
} finally {
|
||||
fs.rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
// Tests for `node install.js --update` and the install record (~/.plan2code/install.json).
|
||||
// Run with: node --test scripts/test-install-update.mjs
|
||||
//
|
||||
// install.js reads the home directory once, at load, so HOME and USERPROFILE point at a temp
|
||||
// folder before it is required. update() takes its install steps as an argument: the tests
|
||||
// pass stand-ins that record their calls, so nothing reaches the skills CLI, npm or the network.
|
||||
|
||||
import test 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 { spawnSync } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const INSTALL = path.join(ROOT, "install.js");
|
||||
const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version;
|
||||
|
||||
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-install-update-"));
|
||||
process.env.HOME = HOME;
|
||||
process.env.USERPROFILE = HOME;
|
||||
const installer = require(INSTALL);
|
||||
test.after(() => fs.rmSync(HOME, { recursive: true, force: true }));
|
||||
|
||||
const RECORD = path.join(HOME, ".plan2code", "install.json");
|
||||
|
||||
function writeRecord(pieces) {
|
||||
fs.mkdirSync(path.dirname(RECORD), { recursive: true });
|
||||
fs.writeFileSync(RECORD, JSON.stringify({ version: "1.0.0", scope: "global", pieces }));
|
||||
}
|
||||
|
||||
function clearRecord() {
|
||||
fs.rmSync(RECORD, { force: true });
|
||||
}
|
||||
|
||||
/** Stand-in install steps: each logs its piece and options, then returns `codes[piece]` (default 0) or throws `throws[piece]`. */
|
||||
function fakeSteps({ codes = {}, throws = {}, launcherWithSkills = true } = {}) {
|
||||
const calls = [];
|
||||
const steps = {};
|
||||
for (const piece of installer.INSTALL_PIECES) {
|
||||
steps[piece] = async (options) => {
|
||||
calls.push({ piece, options });
|
||||
if (throws[piece]) throw new Error(throws[piece]);
|
||||
let code = codes[piece] ?? 0;
|
||||
if (piece === "skills") {
|
||||
// As the real install(): the skills first, then the command, and 1 if either failed.
|
||||
options.outcome.skills = code === 0;
|
||||
options.outcome.launcher = code === 0 && launcherWithSkills;
|
||||
if (code === 0 && !launcherWithSkills) code = 1;
|
||||
}
|
||||
return code;
|
||||
};
|
||||
}
|
||||
return { steps, calls, ran: () => calls.map((c) => c.piece) };
|
||||
}
|
||||
|
||||
/** Run update() with console output captured: `{ code, out }`. */
|
||||
async function runUpdate(steps) {
|
||||
const lines = [];
|
||||
const log = console.log;
|
||||
console.log = (...args) => lines.push(args.join(" "));
|
||||
try {
|
||||
const code = await installer.update({ steps });
|
||||
return { code, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") };
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
}
|
||||
|
||||
test("install record: recordInstalled and forgetInstalled round trip a sorted set", () => {
|
||||
clearRecord();
|
||||
assert.equal(installer.INSTALL_RECORD, RECORD);
|
||||
assert.equal(installer.readInstallRecord(), null);
|
||||
installer.recordInstalled("loop");
|
||||
installer.recordInstalled("skills");
|
||||
installer.recordInstalled("skills");
|
||||
installer.recordInstalled("not-a-piece");
|
||||
assert.deepEqual(installer.readInstallRecord(), { version: VERSION, scope: "global", pieces: ["loop", "skills"] });
|
||||
installer.forgetInstalled("loop");
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, ["skills"]);
|
||||
installer.forgetInstalled("skills");
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, []);
|
||||
// No temp file is left beside the record.
|
||||
assert.deepEqual(fs.readdirSync(path.dirname(RECORD)), ["install.json"]);
|
||||
});
|
||||
|
||||
test("install record: a missing or unparsable record reads as null, and forgetting needs none", () => {
|
||||
clearRecord();
|
||||
installer.forgetInstalled("skills");
|
||||
assert.equal(fs.existsSync(RECORD), false);
|
||||
fs.writeFileSync(RECORD, "{ not json");
|
||||
assert.equal(installer.readInstallRecord(), null);
|
||||
fs.writeFileSync(RECORD, JSON.stringify({ pieces: "skills" }));
|
||||
assert.equal(installer.readInstallRecord(), null);
|
||||
});
|
||||
|
||||
test("update: with no record it says so and updates the skills and the plan2code command", async () => {
|
||||
clearRecord();
|
||||
const fake = fakeSteps();
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 0, out);
|
||||
assert.match(out, new RegExp(`No install record found \\(installed before v${VERSION.replace(/\./g, "\\.")}\\); updating the skills and the plan2code command\\.`));
|
||||
// install() covers the command with the skills, so the launcher step does not run again.
|
||||
assert.deepEqual(fake.ran(), ["skills"]);
|
||||
assert.match(out, /skills: updated/);
|
||||
assert.match(out, /launcher: updated/);
|
||||
});
|
||||
|
||||
test("update: a partial record runs only the listed pieces, in order, unattended", async () => {
|
||||
writeRecord(["loop", "statusline"]);
|
||||
const fake = fakeSteps();
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 0, out);
|
||||
assert.deepEqual(fake.ran(), ["statusline", "loop"]);
|
||||
for (const call of fake.calls) assert.equal(call.options.unattended, true, call.piece);
|
||||
assert.doesNotMatch(out, /No install record/);
|
||||
assert.doesNotMatch(out, /skills:/);
|
||||
});
|
||||
|
||||
test("update: a failing piece exits 1 naming it, and the others still run", async () => {
|
||||
writeRecord(["skills", "launcher", "loop", "metrics", "bot"]);
|
||||
const fake = fakeSteps({ codes: { loop: 1 }, throws: { metrics: "npm exploded" } });
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 1, out);
|
||||
assert.deepEqual(fake.ran(), ["skills", "loop", "metrics", "bot"]);
|
||||
assert.match(out, /loop: failed: /);
|
||||
assert.match(out, /metrics: failed: npm exploded/);
|
||||
assert.match(out, /bot: updated/);
|
||||
assert.match(out, /Update failed for: loop, metrics/);
|
||||
});
|
||||
|
||||
test("update: when the skills install leaves the command out, the launcher step runs on its own", async () => {
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const fake = fakeSteps({ launcherWithSkills: false });
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 0, out);
|
||||
assert.deepEqual(fake.ran(), ["skills", "launcher"]);
|
||||
// install() returned 1 for the command alone: the skills still read as updated.
|
||||
assert.match(out, /skills: updated/);
|
||||
assert.match(out, /launcher: updated/);
|
||||
});
|
||||
|
||||
test("update: a command that fails on the retry is the only piece named", async () => {
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const fake = fakeSteps({ launcherWithSkills: false, codes: { launcher: 1 } });
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 1, out);
|
||||
assert.match(out, /skills: updated/);
|
||||
assert.match(out, /Update failed for: launcher\b/);
|
||||
});
|
||||
|
||||
test("update: the real status line step keeps a custom statusLine without asking", async () => {
|
||||
const claudeDir = path.join(HOME, ".claude");
|
||||
const settingsFile = path.join(claudeDir, "settings.json");
|
||||
fs.mkdirSync(claudeDir, { recursive: true });
|
||||
const settings = JSON.stringify({ statusLine: { type: "command", command: "my-own-status-line" } }, null, 2);
|
||||
fs.writeFileSync(settingsFile, settings);
|
||||
clearRecord();
|
||||
// stdin is not a TTY here: a prompt would hang the test until it times out.
|
||||
const log = console.log;
|
||||
console.log = () => {};
|
||||
let code;
|
||||
try {
|
||||
code = await installer.UPDATE_STEPS.statusline({ quiet: true, unattended: true });
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
assert.equal(code, 0);
|
||||
assert.equal(fs.readFileSync(settingsFile, "utf8"), settings);
|
||||
assert.ok(fs.existsSync(path.join(claudeDir, "plan2code-statusline.js")));
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, ["statusline"]);
|
||||
});
|
||||
|
||||
test("update: every step is an install function, never an uninstall", () => {
|
||||
assert.deepEqual(Object.keys(installer.UPDATE_STEPS), installer.INSTALL_PIECES);
|
||||
for (const [piece, fn] of Object.entries(installer.UPDATE_STEPS)) {
|
||||
assert.match(fn.name, /^install/, piece);
|
||||
}
|
||||
});
|
||||
|
||||
test("install.js: --update is in the usage line, and an unknown option still exits 1", () => {
|
||||
const result = spawnSync(process.execPath, [INSTALL, "--bogus"], { encoding: "utf8" });
|
||||
assert.equal(result.status, 1);
|
||||
assert.ok(result.stderr.includes("Usage: node install.js [--build-skills | --verify-skills | --update]"), result.stderr);
|
||||
});
|
||||
@@ -20,13 +20,28 @@ const LAUNCHER = path.join(ROOT, "src", "launcher", "plan2code.js");
|
||||
const IS_WINDOWS = process.platform === "win32";
|
||||
const NOTICE = "will use the model you last used in it";
|
||||
|
||||
/** A temp home and a bin dir holding stand-ins for `clis`; each writes its args to <bin>/<cli>.json. */
|
||||
function sandbox(clis) {
|
||||
/**
|
||||
* A temp home and a bin dir holding stand-ins for `clis`; each writes its args to <bin>/<cli>.json.
|
||||
* `installed: "X.Y.Z"` runs an installed copy instead, as install.js lays it out: the launcher,
|
||||
* models.json and update-check.mjs in <home>/.plan2code/bin/ beside a version.json saying X.Y.Z.
|
||||
*/
|
||||
function sandbox(clis, { installed } = {}) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-launcher-"));
|
||||
const home = path.join(dir, "home");
|
||||
const bin = path.join(dir, "bin");
|
||||
fs.mkdirSync(home);
|
||||
fs.mkdirSync(bin);
|
||||
const consoleHome = path.join(home, ".plan2code", "console");
|
||||
let launcher = LAUNCHER;
|
||||
if (installed) {
|
||||
const binCopy = path.join(home, ".plan2code", "bin");
|
||||
fs.mkdirSync(binCopy, { recursive: true });
|
||||
launcher = path.join(binCopy, "plan2code.js");
|
||||
fs.copyFileSync(LAUNCHER, launcher);
|
||||
fs.copyFileSync(path.join(path.dirname(LAUNCHER), "models.json"), path.join(binCopy, "models.json"));
|
||||
fs.copyFileSync(path.join(ROOT, "src", "web-console", "update-check.mjs"), path.join(binCopy, "update-check.mjs"));
|
||||
fs.writeFileSync(path.join(binCopy, "version.json"), JSON.stringify({ name: "Plan2Code", version: installed }));
|
||||
}
|
||||
const recorder = path.join(bin, "record.js");
|
||||
fs.writeFileSync(
|
||||
recorder,
|
||||
@@ -45,21 +60,31 @@ function sandbox(clis) {
|
||||
return {
|
||||
home,
|
||||
stateFile: path.join(home, ".plan2code", "launcher.json"),
|
||||
cacheFile: path.join(consoleHome, "update-check.json"),
|
||||
run: (args, env = {}) =>
|
||||
spawnSync(process.execPath, [LAUNCHER, ...args], {
|
||||
spawnSync(process.execPath, [launcher, ...args], {
|
||||
cwd: dir,
|
||||
input: "",
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, PATH: bin, HOME: home, USERPROFILE: home, ...env },
|
||||
env: { ...process.env, PATH: bin, HOME: home, USERPROFILE: home, PLAN2CODE_CONSOLE_HOME: consoleHome, ...env },
|
||||
}),
|
||||
argsOf: (cli) => {
|
||||
const file = path.join(bin, `${cli}.json`);
|
||||
return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
|
||||
},
|
||||
cleanup: () => fs.rmSync(dir, { recursive: true, force: true }),
|
||||
// A detached release-check refresh may still be writing its cache; retry rather than fail.
|
||||
cleanup: () => fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }),
|
||||
};
|
||||
}
|
||||
|
||||
const NOTICE_LINE = /is out \(you have v/;
|
||||
|
||||
/** Write the console's cached release check, `ageMs` old. */
|
||||
function writeCache(box, latest, ageMs = 0) {
|
||||
fs.mkdirSync(path.dirname(box.cacheFile), { recursive: true });
|
||||
fs.writeFileSync(box.cacheFile, JSON.stringify({ checkedAt: Date.now() - ageMs, latest }));
|
||||
}
|
||||
|
||||
test("launcher: Claude Code gets the prompt first, then bypassPermissions and the forwarded args", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
@@ -263,6 +288,65 @@ test("launcher: the CLI's non-zero exit code is passed through", (t) => {
|
||||
assert.equal(result.status, 7, result.stderr);
|
||||
assert.notEqual(box.argsOf("claude"), null);
|
||||
});
|
||||
test("launcher: update runs the npx install and starts no agent", (t) => {
|
||||
const box = sandbox(["npx", "claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["update"]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code\.\.\./);
|
||||
const args = box.argsOf("npx");
|
||||
assert.ok(args, "npx was not run");
|
||||
assert.ok(args.includes("--update"), args.join(" "));
|
||||
assert.ok(args.includes("git+https://github.com/jparkerweb/plan2code.git"), args.join(" "));
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
});
|
||||
|
||||
test("launcher: update passes npx's exit code through", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["update"], { P2C_TEST_EXIT: "3" }).status, 3);
|
||||
});
|
||||
|
||||
test("launcher: release notice prints from a fresh cache", (t) => {
|
||||
const box = sandbox(["claude"], { installed: "1.0.0" });
|
||||
t.after(box.cleanup);
|
||||
writeCache(box, "9.9.9");
|
||||
const result = box.run([]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.ok(result.stdout.includes("Plan2Code v9.9.9 is out (you have v1.0.0). Run: plan2code update"), result.stdout);
|
||||
assert.notEqual(box.argsOf("claude"), null);
|
||||
});
|
||||
|
||||
test("launcher: no notice when current, stale or missing, and the start does not wait", (t) => {
|
||||
// PATH holds only the stand-ins, so the detached refresh finds no git: nothing may wait on it.
|
||||
const cases = [
|
||||
["current", (box) => writeCache(box, "1.0.0")],
|
||||
["stale", (box) => writeCache(box, "9.9.9", 2 * 60 * 60 * 1000)],
|
||||
["missing", () => {}],
|
||||
];
|
||||
for (const [name, setup] of cases) {
|
||||
const box = sandbox(["claude"], { installed: "1.0.0" });
|
||||
t.after(box.cleanup);
|
||||
setup(box);
|
||||
const started = Date.now();
|
||||
const result = box.run([]);
|
||||
const took = Date.now() - started;
|
||||
assert.equal(result.status, 0, `${name}: ${result.stderr}`);
|
||||
assert.doesNotMatch(result.stdout, NOTICE_LINE, name);
|
||||
assert.notEqual(box.argsOf("claude"), null, name);
|
||||
assert.ok(took < 5000, `${name}: the start took ${took} ms`);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher: compareVersions orders X.Y.Z numerically and refuses anything else", () => {
|
||||
const { compareVersions } = require(LAUNCHER);
|
||||
assert.equal(compareVersions("1.9.0", "1.10.0"), -1);
|
||||
assert.equal(compareVersions("2.0.0", "2.0.0"), 0);
|
||||
assert.equal(compareVersions("3.0.0", "2.9.9"), 1);
|
||||
assert.equal(compareVersions("1.0.0", null), null);
|
||||
assert.equal(compareVersions("v1.0.0", "1.0.0"), null);
|
||||
});
|
||||
|
||||
test("launcher: renderBanner draws Planny and the name, colored only through paint", () => {
|
||||
const { renderBanner, paint } = require(LAUNCHER);
|
||||
const plain = renderBanner(paint(false));
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
// Tests for plan2code-handoff's scripts/handoff-path.mjs.
|
||||
//
|
||||
// See skill-script-helpers.mjs for how these run.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { ROOT, SKILLS, NOW, runScript, tmp, write, read, gitInit, phase } from "./skill-script-helpers.mjs";
|
||||
|
||||
/* =========================================================== handoff-path.mjs */
|
||||
|
||||
test("handoff-path: timestamped name, no overwrite, git ignore check", () => {
|
||||
const repo = tmp("handoff");
|
||||
gitInit(repo);
|
||||
const H = (...a) => runScript("plan2code-handoff", "handoff-path.mjs", a, { cwd: repo });
|
||||
const first = H("--dir", "handoffs");
|
||||
assert.equal(first.code, 0, first.stderr);
|
||||
assert.equal(path.basename(first.json.path), "2026-08-03-1405-handoff.md");
|
||||
assert.equal(first.json.created, true);
|
||||
assert.equal(first.json.git.inRepo, true);
|
||||
assert.equal(first.json.git.ignored, false);
|
||||
assert.match(first.json.warning, /handoffs\//);
|
||||
fs.writeFileSync(first.json.path, "x");
|
||||
assert.equal(path.basename(H("--dir", "handoffs").json.path), "2026-08-03-1405-2-handoff.md");
|
||||
write(repo, ".gitignore", "handoffs/\n");
|
||||
assert.equal(H("--dir", "handoffs").json.git.ignored, true);
|
||||
const temp = H();
|
||||
assert.equal(temp.json.git.inRepo, false);
|
||||
assert.equal(temp.json.git.ignored, null);
|
||||
const dry = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "later", "--dry-run"], { cwd: repo });
|
||||
assert.equal(dry.json.created, false);
|
||||
assert.ok(!fs.existsSync(path.join(repo, "later")));
|
||||
});
|
||||
|
||||
/* ================================================= verification regressions */
|
||||
|
||||
test("handoff-path: the repo root itself is never the line to ignore", () => {
|
||||
const repo = tmp("handoff2");
|
||||
gitInit(repo);
|
||||
const j = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "."], { cwd: repo }).json;
|
||||
assert.equal(j.git.inRepo, true);
|
||||
assert.equal(j.git.ignoreLine, "*-handoff.md");
|
||||
});
|
||||
|
||||
test("handoff-path: --dir naming an existing file is refused", () => {
|
||||
const repo = tmp("handoff3");
|
||||
write(repo, "notes.txt", "x");
|
||||
const r = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "notes.txt"], { cwd: repo });
|
||||
assert.equal(r.code, 5);
|
||||
assert.equal(r.json.ok, false);
|
||||
assert.equal(r.json.error, "not-a-folder");
|
||||
assert.match(r.json.next, /--dir temp/);
|
||||
assert.equal(runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "notes.txt", "--dry-run"], { cwd: repo }).code, 5, "dry-run refuses it too");
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
// Tests for plan2code-xray's scripts/xray.mjs.
|
||||
//
|
||||
// See skill-script-helpers.mjs for how these run.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { runScript, tmp, write, gitInit } from "./skill-script-helpers.mjs";
|
||||
|
||||
const X = (cwd, args, env) => runScript("plan2code-xray", "xray.mjs", args, { cwd, env });
|
||||
|
||||
// One fixture for the file: a.js and b.js always change together, hot.js
|
||||
// changes in most commits and has no test, the others are tested, and
|
||||
// old1.js and old2.js changed together before they were deleted.
|
||||
let fixture;
|
||||
function repo() {
|
||||
if (fixture) return fixture;
|
||||
const dir = tmp("xray");
|
||||
const g = gitInit(dir);
|
||||
const commit = (msg, files) => {
|
||||
for (const [rel, content] of Object.entries(files)) write(dir, rel, content);
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", msg);
|
||||
};
|
||||
commit("Start", { "a.js": "a1\n", "b.js": "b1\n", "hot.js": "h1\n", "c.js": "c1\n", "tests/a.test.js": "t\n", "tests/b.test.js": "t\n", "tests/c.test.js": "t\n" });
|
||||
commit("Change a and b (#12)", { "a.js": "a2\n", "b.js": "b2\n", "hot.js": "h2\n", "package-lock.json": "{}\n" });
|
||||
commit("Change a and b again", { "a.js": "a3\n", "b.js": "b3\n", "hot.js": "h3\n", "package-lock.json": "{ }\n" });
|
||||
commit("Change hot and c", { "hot.js": "h4\nmore\n", "c.js": "c2\n" });
|
||||
commit("Change hot alone", { "hot.js": "h5\nmore\n", "dist/out.js": "x\n" });
|
||||
// Without hot.js, so a-b (support 1) outranks a-hot and b-hot on support, not on name.
|
||||
commit("Change a and b only", { "a.js": "a4\n", "b.js": "b4\n" });
|
||||
for (let i = 1; i <= 3; i++) commit(`Change the old pair ${i}`, { "old1.js": `o${i}\n`, "old2.js": `p${i}\n` });
|
||||
g("rm", "-q", "old1.js", "old2.js");
|
||||
g("commit", "-q", "-m", "Delete the old pair");
|
||||
fixture = dir;
|
||||
return dir;
|
||||
}
|
||||
|
||||
// PATH with git (and node) but no gh: git's own exec dir holds a git binary
|
||||
// on every platform, so the directory that also holds gh is never needed.
|
||||
function pathWithoutGh() {
|
||||
const gitDir = execFileSync("git", ["--exec-path"], { encoding: "utf8" }).trim();
|
||||
const dirs = [path.resolve(gitDir)];
|
||||
const nodeDir = path.dirname(process.execPath);
|
||||
const hasGh = ["gh", "gh.exe"].some((n) => fs.existsSync(path.join(nodeDir, n)));
|
||||
if (!hasGh) dirs.push(nodeDir);
|
||||
const value = dirs.join(path.delimiter);
|
||||
// Windows keys env case-insensitively but a child gets both spellings: set both.
|
||||
return { PATH: value, Path: value };
|
||||
}
|
||||
|
||||
test("xray hotspots: the always-together pair ranks first, the hot file without a test is listed", () => {
|
||||
const r = X(repo(), ["hotspots"]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.equal(r.json.ok, true);
|
||||
assert.deepEqual(r.json.window, { commits: 10, capped: false });
|
||||
assert.deepEqual(r.json.churn[0], { file: "hot.js", commits: 5 });
|
||||
assert.ok(!r.json.churn.some((c) => c.file === "package-lock.json" || c.file.startsWith("dist/")), "lockfiles and dist/ are skipped");
|
||||
assert.deepEqual(r.json.pairs[0], { a: "a.js", b: "b.js", together: 4, support: 1 });
|
||||
assert.ok(r.json.pairs[1].support < 1, JSON.stringify(r.json.pairs));
|
||||
assert.ok(r.json.pairs.every((p) => p.together >= 3));
|
||||
const untested = r.json.untested.map((u) => u.file);
|
||||
assert.ok(untested.includes("hot.js"), JSON.stringify(r.json.untested));
|
||||
for (const tested of ["a.js", "b.js", "c.js"]) assert.ok(!untested.includes(tested), `${tested} has a test`);
|
||||
});
|
||||
|
||||
test("xray hotspots: files deleted since drop out of churn and pairs", () => {
|
||||
const r = X(repo(), ["hotspots"]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
const named = [...r.json.churn.map((c) => c.file), ...r.json.pairs.flatMap((p) => [p.a, p.b])];
|
||||
assert.ok(!named.some((f) => f.startsWith("old")), JSON.stringify(named));
|
||||
});
|
||||
|
||||
test("xray hotspots: --max-commits below the history sets capped", () => {
|
||||
const r = X(repo(), ["hotspots", "--max-commits", "2"]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.deepEqual(r.json.window, { commits: 2, capped: true });
|
||||
assert.equal(X(repo(), ["hotspots", "--top", "1"]).json.churn.length, 1);
|
||||
});
|
||||
|
||||
test("xray history: commits, blame and gh missing when gh is not on PATH", () => {
|
||||
const r = X(repo(), ["history", "hot.js"], pathWithoutGh());
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
assert.equal(r.json.path, "hot.js");
|
||||
assert.equal(r.json.commits.length, 5);
|
||||
assert.equal(r.json.commits[0].subject, "Change hot alone");
|
||||
assert.equal(r.json.commits[0].author, "Test");
|
||||
assert.match(r.json.commits[0].hash, /^[0-9a-f]{40}$/);
|
||||
assert.equal(r.json.blame.lines, 2);
|
||||
assert.deepEqual(r.json.blame.authors, [{ author: "Test", lines: 2, share: 1 }]);
|
||||
assert.match(r.json.blame.oldest, /^\d{4}-\d{2}-\d{2}$/);
|
||||
assert.deepEqual(r.json.prs, [{ number: 12, subject: "Change a and b (#12)", title: null, summary: null }]);
|
||||
assert.deepEqual(r.json.sources, { git: true, blame: true, gh: "missing" });
|
||||
});
|
||||
|
||||
test("xray: a folder outside any repository is exit 3 not-a-repo", () => {
|
||||
const plain = tmp("xray-plain");
|
||||
for (const args of [["hotspots"], ["history", "x.js"]]) {
|
||||
const r = X(plain, args);
|
||||
assert.equal(r.code, 3);
|
||||
assert.equal(r.json.ok, false);
|
||||
assert.equal(r.json.error, "not-a-repo");
|
||||
assert.match(r.json.next, /explain mode/);
|
||||
}
|
||||
});
|
||||
|
||||
test("xray: --help documents the exit codes", () => {
|
||||
const r = X(repo(), ["--help"]);
|
||||
assert.equal(r.code, 0);
|
||||
assert.match(r.stdout, /Exit:/);
|
||||
});
|
||||
@@ -29,6 +29,17 @@ test("every skill with scripts ships common.mjs and version.json; dashboard ship
|
||||
assert.equal(JSON.parse(fs.readFileSync(path.join(SKILLS, "plan2code-4-finalize", "scripts", "version.json"), "utf8")).version, v);
|
||||
});
|
||||
|
||||
test("the Handoff skill writes through the console's handoff new, with no folder or gitignore step", () => {
|
||||
const skill = fs.readFileSync(path.join(SKILLS, "plan2code-handoff", "SKILL.md"), "utf8");
|
||||
assert.match(skill, /console\.mjs" handoff new/);
|
||||
assert.doesNotMatch(skill, /handoff-path\.mjs/);
|
||||
assert.doesNotMatch(skill, /--dir temp/);
|
||||
assert.doesNotMatch(skill, /\.gitignore/);
|
||||
// handoff-path.mjs is retired: the build ships only the shared specs.mjs.
|
||||
assert.ok(!fs.existsSync(path.join(SKILLS, "plan2code-handoff", "scripts", "handoff-path.mjs")), "handoff-path.mjs is not shipped");
|
||||
assert.ok(fs.existsSync(path.join(SKILLS, "plan2code-handoff", "scripts", "specs.mjs")), "specs.mjs still is");
|
||||
});
|
||||
|
||||
test("every script a SKILL.md (or a reference it ships) runs exists beside it, and answers --help", () => {
|
||||
for (const skill of fs.readdirSync(SKILLS)) {
|
||||
const dir = path.join(SKILLS, skill);
|
||||
@@ -115,6 +126,27 @@ test("specs list: active specs with state, drafts and archives, never specs--com
|
||||
assert.equal(r.json.hasAgents, true);
|
||||
});
|
||||
|
||||
test("specs list: a folder holding only Diagnose's write-up is diagnosed", () => {
|
||||
const root = specFixture();
|
||||
write(root, "specs/csv-drops-rows/DIAGNOSIS-20261016.md", "# Diagnosis: CSV drops rows\n\n**Status:** Diagnosed\n");
|
||||
const r = runScript("plan2code-diagnose", "specs.mjs", ["list", "--root", root]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
const bug = r.json.specs.find((s) => s.name === "csv-drops-rows");
|
||||
assert.equal(bug.state, "diagnosed");
|
||||
assert.equal(bug.detail, "bug diagnosed, not fixed");
|
||||
assert.equal(bug.phaseFiles, 0);
|
||||
});
|
||||
|
||||
test("specs list: a diagnosis Quick Task marked Fixed is a fixed bug", () => {
|
||||
const root = specFixture();
|
||||
write(root, "specs/csv-drops-rows/DIAGNOSIS-20261016.md", "# Diagnosis: CSV drops rows\n\n**Status:** Fixed\n");
|
||||
const r = runScript("plan2code-quick-task", "specs.mjs", ["list", "--root", root]);
|
||||
assert.equal(r.code, 0, r.stderr);
|
||||
const bug = r.json.specs.find((s) => s.name === "csv-drops-rows");
|
||||
assert.equal(bug.state, "fixed");
|
||||
assert.equal(bug.detail, "bug fixed");
|
||||
});
|
||||
|
||||
test("specs status: checklist formats, groups, task markers, numbering, totals, checks", () => {
|
||||
const root = specFixture();
|
||||
const r = runScript("plan2code-3-implement", "specs.mjs", ["status", "specs/lunch-vote/overview.md", "--root", root]);
|
||||
@@ -140,6 +172,25 @@ test("specs status: checklist formats, groups, task markers, numbering, totals,
|
||||
assert.deepEqual(j.pending.map((p) => p.number), [2, 3, 4]);
|
||||
});
|
||||
|
||||
test("specs status: a plain ` - Test:` sub-bullet under a task is not counted or flagged", () => {
|
||||
const plain = specFixture();
|
||||
const withTests = specFixture();
|
||||
// The shape Document writes: a task line followed directly by a non-checkbox sub-bullet.
|
||||
for (const [n, ids] of [[2, ["2.1", "2.2"]], [3, ["3.1", "3.4"]]]) {
|
||||
const rel = `specs/lunch-vote/phase-${n}.md`;
|
||||
let text = read(withTests, rel);
|
||||
for (const id of ids) text = text.replace(`**Task ${id}:** Do ${id}\n`, `**Task ${id}:** Do ${id}\n - Test: through \`POST /votes\`\n`);
|
||||
assert.match(text, /\n - Test: through/);
|
||||
write(withTests, rel, text);
|
||||
}
|
||||
const status = (root) => runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
||||
const a = status(plain);
|
||||
const b = status(withTests);
|
||||
assert.deepEqual(b.phases.map((p) => p.tasks), a.phases.map((p) => p.tasks));
|
||||
assert.deepEqual(b.totals, a.totals);
|
||||
assert.deepEqual(b.checks, a.checks);
|
||||
});
|
||||
|
||||
test("specs status: the implement selection table", () => {
|
||||
const root = specFixture();
|
||||
const ov = (m1, m2, m3, m4) => OVERVIEW.replace("- [x] **[Phase 1", `- [${m1}] **[Phase 1`).replace("- [/] [Phase 2", `- [${m2}] [Phase 2`).replace("- [ ] **Phase 3", `- [${m3}] **Phase 3`).replace("- [ ] [Phase 4", `- [${m4}] [Phase 4`);
|
||||
@@ -194,6 +245,29 @@ test("specs: open tasks under approved phases are a checkoff, and tick checks th
|
||||
assert.equal(S("tick", "lunch-vote", "--task", "nope").code, 2);
|
||||
});
|
||||
|
||||
test("specs: numbered task lines are tasks, counted by status and ticked by tick", () => {
|
||||
const root = specFixture();
|
||||
// phase() writes "- [m]" lines; renumber phase 1 as a numbered list.
|
||||
write(root, "specs/lunch-vote/phase-1.md", phase(1, "In Progress", [["x", "1.1"], [" ", "1.2"]]).replace("- [x] **Task 1.1:**", "1. [x] **Task 1.1:**").replace("- [ ] **Task 1.2:**", "2. [ ] **Task 1.2:**"));
|
||||
assert.match(read(root, "specs/lunch-vote/phase-1.md"), /^1\. \[x\] \*\*Task 1\.1:\*\* Do 1\.1\n2\. \[ \] \*\*Task 1\.2:\*\* Do 1\.2$/m);
|
||||
const S = (...a) => runScript("plan2code-3-implement", "specs.mjs", [...a, "--root", root]);
|
||||
const st = S("status", "lunch-vote");
|
||||
assert.equal(st.code, 0, st.stderr);
|
||||
const p1 = st.json.phases.find((p) => p.number === 1);
|
||||
assert.equal(p1.tasks.total, 2);
|
||||
assert.equal(p1.tasks.complete, 1);
|
||||
assert.deepEqual(p1.openTasks, ["1.2"]);
|
||||
assert.ok(!st.json.checks.some((c) => c.code === "uncounted-task" && /phase-1/.test(c.message)), JSON.stringify(st.json.checks));
|
||||
|
||||
const t = S("tick", "lunch-vote", "--task", "1.2");
|
||||
assert.equal(t.code, 0, t.stderr);
|
||||
assert.equal(t.json.changed, true);
|
||||
assert.match(read(root, "specs/lunch-vote/phase-1.md"), /^2\. \[x\] \*\*Task 1\.2:\*\* Do 1\.2\n > Confirmed done by the user on \d{4}-\d{2}-\d{2}\.$/m);
|
||||
const after = S("status", "lunch-vote").json.phases.find((p) => p.number === 1);
|
||||
assert.equal(after.tasks.complete, 2);
|
||||
assert.deepEqual(after.openTasks, []);
|
||||
});
|
||||
|
||||
test("specs status: drift between the checklist and the phase files is an error", () => {
|
||||
const root = specFixture();
|
||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("- [/] [Phase 2", "- [x] [Phase 2"));
|
||||
@@ -465,7 +539,9 @@ test("specs: --set cannot override computed fields; empty overview exists; uncou
|
||||
assert.equal(runScript("plan2code-2-document", "specs.mjs", ["metrics", "lunch-vote", "--step", "document", "--set", "verification_items_added=1", "--set", "total_tasks=99", "--root", root]).code, 2);
|
||||
write(root, "specs/lunch-vote/phase-2.md", read(root, "specs/lunch-vote/phase-2.md") + "- [ ] **Task 2.4A:** odd\n1. [ ] **Task 2.5:** numbered\n");
|
||||
const j = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
||||
assert.equal(j.checks.filter((c) => c.code === "uncounted-task").length, 2);
|
||||
// Task 2.4A is flagged; a numbered task line is counted like any other (spec-files.mjs).
|
||||
assert.equal(j.checks.filter((c) => c.code === "uncounted-task").length, 1);
|
||||
assert.ok(j.phases.find((p) => p.number === 2).openTasks.includes("2.5"));
|
||||
write(root, "specs/lunch-vote/overview.md", "");
|
||||
const e = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
||||
assert.equal(e.overview, "overview.md");
|
||||
@@ -473,6 +549,173 @@ test("specs: --set cannot override computed fields; empty overview exists; uncou
|
||||
assert.ok(!e.checks.some((c) => c.code === "no-overview"));
|
||||
});
|
||||
|
||||
// A spec with nothing for check to find: a checklist row per phase file,
|
||||
// sequential task numbers, a Test-first sub-bullet and plain-bullet criteria.
|
||||
function cleanSpec(root) {
|
||||
write(root, "specs/clean/overview.md", "# Clean\n\n## Phase Checklist\n\n- [ ] [Phase 1: Data model](./phase-1.md)\n- [ ] [Phase 2: API](./phase-2.md)\n");
|
||||
write(root, "specs/clean/phase-1.md", phase(1, "Not Started", [[" ", "1.1"], [" ", "1.2"]]).replace("**Task 1.1:** Do 1.1\n", "**Task 1.1:** Do 1.1\n - Test: through `POST /votes`\n"));
|
||||
write(root, "specs/clean/phase-2.md", phase(2, "Not Started", [[" ", "2.1"]]));
|
||||
return root;
|
||||
}
|
||||
|
||||
test("specs check: a well-formed spec passes", () => {
|
||||
const root = cleanSpec(specFixture());
|
||||
assert.match(read(root, "specs/clean/phase-1.md"), /\n - Test: through/);
|
||||
const r = runScript("plan2code-2-document", "specs.mjs", ["check", "clean", "--root", root]);
|
||||
assert.equal(r.code, 0, r.stdout);
|
||||
assert.equal(r.json.ok, true);
|
||||
assert.equal(r.json.errors, 0);
|
||||
assert.deepEqual(r.json.checked, ["specs/clean/overview.md", "specs/clean/phase-1.md", "specs/clean/phase-2.md"]);
|
||||
assert.deepEqual(r.json.problems, []);
|
||||
});
|
||||
|
||||
test("specs check: a bad task line, a checklist row with no phase file, a loop token and a bare metric word each fail", () => {
|
||||
const root = cleanSpec(specFixture());
|
||||
write(root, "specs/clean/overview.md", read(root, "specs/clean/overview.md") + "- [ ] [Phase 3: Docs](./phase-3.md)\n");
|
||||
write(root, "specs/clean/phase-1.md", read(root, "specs/clean/phase-1.md").replace("- [ ] **Task 1.2:** Do 1.2", "- [ ] Task 1.2 without the bold"));
|
||||
write(root, "specs/clean/phase-2.md", read(root, "specs/clean/phase-2.md") + "\n## Notes\n\nPrint TASK_COMPLETE when done. Risk: 3 of 5.\n");
|
||||
const r = runScript("plan2code-2-document", "specs.mjs", ["check", "clean", "--root", root]);
|
||||
assert.equal(r.code, 4, r.stdout);
|
||||
assert.equal(r.json.ok, false);
|
||||
assert.equal(r.json.error, "check-failed");
|
||||
assert.match(r.json.next, /rerun check/);
|
||||
assert.match(r.stderr, /^error: check found \d+ errors?\.\nnext: /);
|
||||
const errs = r.json.problems.filter((p) => p.level === "error");
|
||||
assert.equal(r.json.errors, errs.length);
|
||||
const by = (code) => errs.filter((p) => p.code === code);
|
||||
assert.deepEqual(by("bad-task-line").map((p) => p.file), ["specs/clean/phase-1.md"]);
|
||||
assert.deepEqual(by("missing-phase-file").map((p) => p.file), ["specs/clean/overview.md"]);
|
||||
assert.deepEqual(by("loop-token").map((p) => p.file), ["specs/clean/phase-2.md"]);
|
||||
assert.deepEqual(by("metric-word").map((p) => p.file), ["specs/clean/phase-2.md"]);
|
||||
for (const p of r.json.problems) assert.deepEqual(Object.keys(p), ["level", "file", "code", "message"]);
|
||||
assert.equal(runScript("plan2code-2-document", "specs.mjs", ["check", "nope", "--root", root]).code, 3);
|
||||
// A status problem names the phase file by its real name, not phase-N.md.
|
||||
fs.renameSync(path.join(root, "specs/clean/phase-2.md"), path.join(root, "specs/clean/phase-2-api.md"));
|
||||
write(root, "specs/clean/phase-2-api.md", phase(2, "Not Started", [[" ", "2.2"]]));
|
||||
const named = runScript("plan2code-2-document", "specs.mjs", ["check", "clean", "--root", root]).json;
|
||||
assert.deepEqual(named.problems.filter((p) => p.code === "task-numbering").map((p) => p.file), ["specs/clean/phase-2-api.md"]);
|
||||
});
|
||||
|
||||
// A draft in the shape Plan's Phase 7 writes, with every heading Document reads.
|
||||
const COMPLETE_DRAFT = `# Lunch vote - Implementation Plan
|
||||
|
||||
**Created:** 2026-08-01
|
||||
**Status:** Complete
|
||||
**Confidence:** 92% (Requirements-clarity 24/25 · Feasibility-technical 23/25 · Integration-points 23/25 · Risk-assessment 22/25)
|
||||
|
||||
## 1. Executive Summary
|
||||
|
||||
A lunch vote.
|
||||
|
||||
## 2. Requirements
|
||||
|
||||
### 2.1 Functional Requirements
|
||||
|
||||
- [ ] FR-1: People vote
|
||||
|
||||
### 2.4 Testing Strategy
|
||||
|
||||
| Type | Phase Testing | Coverage |
|
||||
|------|---------------|----------|
|
||||
|
||||
## 3. Tech Stack
|
||||
|
||||
Node.
|
||||
|
||||
## 4. Architecture
|
||||
|
||||
One server.
|
||||
|
||||
## 5. Implementation Phases
|
||||
|
||||
### Phase 1: Votes
|
||||
|
||||
Build the vote (FR-1).
|
||||
|
||||
## 6. Risks and Mitigations
|
||||
|
||||
| Risk | Likelihood | Impact | Mitigation |
|
||||
|
||||
## 7. Success Criteria
|
||||
|
||||
- [ ] Votes count
|
||||
|
||||
## 9. Assumptions
|
||||
|
||||
- People eat lunch
|
||||
|
||||
## Planning Metrics
|
||||
<!-- METRICS_JSON {"confidence": 92, "confidence_breakdown": {"requirements": 24, "risk": 22}} -->
|
||||
`;
|
||||
|
||||
test("specs check-draft: a complete draft passes", () => {
|
||||
const root = specFixture();
|
||||
write(root, "specs/lunch-vote/PLAN-DRAFT-20260801.md", COMPLETE_DRAFT);
|
||||
for (const arg of ["lunch-vote", "specs/lunch-vote/PLAN-DRAFT-20260801.md"]) {
|
||||
const r = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", arg, "--root", root]);
|
||||
assert.equal(r.code, 0, r.stdout);
|
||||
assert.equal(r.json.errors, 0);
|
||||
assert.equal(r.json.warnings, 0);
|
||||
assert.equal(r.json.status, "Complete");
|
||||
assert.deepEqual(r.json.checked, ["specs/lunch-vote/PLAN-DRAFT-20260801.md"]);
|
||||
}
|
||||
// A newer -prev copy is archived, never the one checked.
|
||||
write(root, "specs/lunch-vote/PLAN-DRAFT-20260802-prev.md", "# old\n");
|
||||
assert.equal(runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "lunch-vote", "--root", root]).code, 0);
|
||||
// Untraced requirements only warn.
|
||||
write(root, "specs/lunch-vote/PLAN-DRAFT-20260801.md", COMPLETE_DRAFT.replace("Build the vote (FR-1).", "Build the vote."));
|
||||
const w = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "lunch-vote", "--root", root]);
|
||||
assert.equal(w.code, 0, w.stdout);
|
||||
assert.deepEqual(w.json.problems.map((p) => [p.level, p.code]), [["warn", "untraced-requirements"]]);
|
||||
});
|
||||
|
||||
test("specs check-draft: a missing section, a bad status, no metrics, a loop token each fail", () => {
|
||||
const root = specFixture();
|
||||
const check = (text) => {
|
||||
write(root, "specs/lunch-vote/PLAN-DRAFT-20260801.md", text);
|
||||
const r = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "lunch-vote", "--root", root]);
|
||||
assert.equal(r.code, 4, r.stdout);
|
||||
assert.equal(r.json.error, "check-draft-failed");
|
||||
return r.json.problems.filter((p) => p.level === "error").map((p) => p.code);
|
||||
};
|
||||
const noTech = check(COMPLETE_DRAFT.replace("## 3. Tech Stack", "## 3. Tools"));
|
||||
assert.deepEqual(noTech, ["missing-section"]);
|
||||
assert.deepEqual(check(COMPLETE_DRAFT.replace("**Status:** Complete", "**Status:** Finished")), ["bad-status"]);
|
||||
assert.deepEqual(check(COMPLETE_DRAFT.replace("**Status:** Complete\n", "")), ["bad-status"]);
|
||||
assert.deepEqual(check(COMPLETE_DRAFT.replace(/## Planning Metrics\n<!--.*-->\n/, "")), ["no-metrics"]);
|
||||
assert.deepEqual(check(COMPLETE_DRAFT.replace('{"confidence": 92,', '{"confidence": 92')), ["no-metrics"]);
|
||||
assert.deepEqual(check(COMPLETE_DRAFT.replace("METRICS_JSON {", "METRICS_JSON{")), ["no-metrics"], "the collector needs whitespace after METRICS_JSON");
|
||||
assert.deepEqual(check(COMPLETE_DRAFT.replace("### Phase 1: Votes", "Phase 1, votes")), ["no-phases"]);
|
||||
assert.deepEqual(check(COMPLETE_DRAFT.replace("Node.", "Node. Then say PHASE_COMPLETE.")), ["loop-token"]);
|
||||
assert.deepEqual(check(COMPLETE_DRAFT.replace("One server.", "One server. Integration: 4 services.")), ["metric-word"]);
|
||||
const missing = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "specs/lunch-vote/PLAN-DRAFT-nope.md", "--root", root]);
|
||||
assert.equal(missing.code, 3);
|
||||
assert.equal(runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "idea-only", "--root", root]).json.error, "no-draft");
|
||||
});
|
||||
|
||||
test("specs check-draft: a pathfinder draft at Resume at Phase 4 is checked lightly", () => {
|
||||
const root = specFixture();
|
||||
const draft = "# Idea - Implementation Plan\n\n*Written by /plan2code-0-pathfinder.*\n\n**Status:** Phase 3 Complete - Resume at Phase 4\n\n## 1. Executive Summary\n\nTBD\n";
|
||||
write(root, "specs/idea-only/PLAN-DRAFT-20260801.md", draft);
|
||||
const r = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "idea-only", "--root", root]);
|
||||
assert.equal(r.code, 0, r.stdout);
|
||||
assert.deepEqual(r.json.problems, [], "no section, phase or metrics checks before Plan's Phase 4");
|
||||
// Status, loop tokens and every metric pattern still apply, confidence included.
|
||||
write(root, "specs/idea-only/PLAN-DRAFT-20260801.md", draft + "\n**Confidence:** 80%\n\nSay WORK_COMPLETE.\n");
|
||||
const bad = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "idea-only", "--root", root]);
|
||||
assert.equal(bad.code, 4);
|
||||
assert.deepEqual(bad.json.problems.map((p) => p.code).sort(), ["loop-token", "metric-word"]);
|
||||
});
|
||||
|
||||
test("common.mjs exports the shared loop-token and scrape patterns", async () => {
|
||||
const common = await import(new URL(`file:///${path.join(SKILLS, "plan2code-2-document", "scripts", "common.mjs").replace(/\\/g, "/")}`).href);
|
||||
assert.ok(common.LOOP_TOKENS instanceof RegExp);
|
||||
assert.ok(common.LOOP_TOKENS.test("then TASK_COMPLETE"));
|
||||
assert.equal(common.SCRAPE.length, 6);
|
||||
assert.deepEqual(common.scrapeHits("Risk: 3"), ['bare Risk + number: "Risk: 3"']);
|
||||
assert.deepEqual(common.scrapeHits("Risk-assessment 22/25"), []);
|
||||
});
|
||||
|
||||
test("commit-msg: a repo with no commits, stray arguments, and paths quoted for every shell", () => {
|
||||
const repo = tmp("commit2");
|
||||
gitInit(repo, "feature/ABC-12-x");
|
||||
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
unreadDot,
|
||||
} from "../src/web-console/public/chat.js";
|
||||
import { WEIGHTS } from "../src/web-console/public/meter.js";
|
||||
import { readChat } from "../src/web-console/lib.mjs";
|
||||
import { readChat } from "../src/web-console/inbox.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
|
||||
@@ -9,7 +9,8 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { readChat, terminalLine } from "../src/web-console/lib.mjs";
|
||||
import { terminalLine } from "../src/web-console/sessions.mjs";
|
||||
import { readChat } from "../src/web-console/inbox.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
@@ -431,3 +432,17 @@ test("a reply proposing an edit under the running spec is refused; a valid reply
|
||||
cli(["stop", "--session", s.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
// The Ask tab's prompt blocks are contract only: the page already draws Copy on a
|
||||
// fenced block, so the agent has to be told when and how to write one.
|
||||
test("console-chat.md teaches the prompt block: when, what it holds, and not to open it with a command word", () => {
|
||||
const text = fs.readFileSync(path.join(ROOT, "src", "web-console", "console-chat.md"), "utf8");
|
||||
const section = text.split(/^## /m).find((s) => s.startsWith("Prompts to carry away"));
|
||||
assert.ok(section, "console-chat.md has no 'Prompts to carry away' section");
|
||||
assert.match(section, /fenced block/);
|
||||
assert.match(section, /Copy/);
|
||||
assert.match(section, /paste it into the Ask tab/);
|
||||
assert.match(section, /out of scope/);
|
||||
assert.match(section, /files to read/);
|
||||
assert.doesNotMatch(section, /\u2014/, "no em dash in the section");
|
||||
});
|
||||
@@ -12,7 +12,10 @@ import path from "node:path";
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import http from "node:http";
|
||||
import { meterView } from "../src/web-console/public/meter.js";
|
||||
import { cwdHash, readLedger, repoRoots, STATE_LOCK_FILE, validate, WORKSPACE_FILE } from "../src/web-console/lib.mjs";
|
||||
import { STATE_LOCK_FILE } from "../src/web-console/files.mjs";
|
||||
import { cwdHash, readLedger, repoRoots } from "../src/web-console/sessions.mjs";
|
||||
import { validate } from "../src/web-console/patches.mjs";
|
||||
import { WORKSPACE_FILE } from "../src/web-console/workspace.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
@@ -47,7 +50,11 @@ test("helpers: a dashboard hop clears them, a same-workflow or paused resume kee
|
||||
cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]);
|
||||
assert.equal(readState(s.session).helpers.length, 2, "a resume into the same workflow keeps them");
|
||||
|
||||
assert.equal(postPatch(s, { finish: { headline: "Paused at Task 2" } }).status, 0);
|
||||
// A finish is refused while a helper still shows as running, so the pause settles them.
|
||||
assert.equal(
|
||||
postPatch(s, { helpers: [reportedHelper("h1", { state: "done" }), reportedHelper("h2", { state: "failed" })], finish: { headline: "Paused at Task 2" } }).status,
|
||||
0
|
||||
);
|
||||
cli(["open", "--resume", s.sid, "--no-open"]);
|
||||
const resumed = readState(s.session);
|
||||
assert.equal("finish" in resumed, false, "the pause came down");
|
||||
@@ -240,7 +247,7 @@ test("stop never kills a live process that does not answer /health as ours", ()
|
||||
const bystander = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
|
||||
const sidForged = "20000101-000000-beef01";
|
||||
// Under the test home, as the CLI sees it: this process has no override of
|
||||
// its own, and lib.mjs would name the real runtime dir.
|
||||
// its own, and files.mjs would name the real runtime dir.
|
||||
const dir = path.join(HOME, "runtime", cwdHash(repoRoots(ROOT).project));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const forged = path.join(dir, `${sidForged}.json`);
|
||||
|
||||
@@ -0,0 +1,532 @@
|
||||
// Web console tests, the tabbed git board's rules: next step, tabs, badges, busy.
|
||||
// Run with: node --test scripts/test-web-console-git-board.mjs
|
||||
//
|
||||
// Every sample repo state the Pathfinder sketches moved between lives in
|
||||
// scripts/fixtures/git-board-states.mjs, each with the next step it must
|
||||
// produce. The rules are pure (git-board.js), so no browser is needed.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import { JOURNEYS, NOW, STATES } from "./fixtures/git-board-states.mjs";
|
||||
import {
|
||||
BRANCH_TYPES,
|
||||
GIT_TABS,
|
||||
busyMode,
|
||||
commitTicks,
|
||||
controlAllowed,
|
||||
createSources,
|
||||
gitReply,
|
||||
nextStep,
|
||||
pickTab,
|
||||
tabBadges,
|
||||
} from "../src/web-console/public/git-board.js";
|
||||
import { drawGitBoard } from "../src/web-console/public/git-board-view.js";
|
||||
|
||||
const VIEW_SRC = fs.readFileSync(new URL("../src/web-console/public/git-board-view.js", import.meta.url), "utf8");
|
||||
|
||||
const MODES = ["offline", "running", "card", "idle"];
|
||||
const ROLES = ["nav", "action", "done"];
|
||||
const TAB_IDS = GIT_TABS.map((t) => t.id);
|
||||
|
||||
const step = (id) => nextStep(STATES[id].git, { now: NOW });
|
||||
const badges = (id) => {
|
||||
const s = step(id);
|
||||
return tabBadges(STATES[id].git, { now: NOW, stepTab: s.tab });
|
||||
};
|
||||
|
||||
test("git board rules: every sample state gives its expected primary, secondary and tab", () => {
|
||||
for (const [id, s] of Object.entries(STATES)) {
|
||||
const n = nextStep(s.git, { now: NOW });
|
||||
const got = [n.primary ? n.primary.op : null, n.secondary[0] ? n.secondary[0].op : null];
|
||||
assert.deepEqual(got, s.expect, `${id}: primary and secondary`);
|
||||
assert.equal(n.tab, s.expectTab, `${id}: owning tab`);
|
||||
if (s.expectLine) assert.equal(n.line, s.expectLine, `${id}: line`);
|
||||
assert.ok(n.secondary.length <= (n.primary ? 1 : 2), `${id}: at most one secondary beside a primary`);
|
||||
for (const st of [n.primary, ...n.secondary].filter(Boolean)) assert.ok(TAB_IDS.includes(st.tab), `${id}: ${st.op} has a tab`);
|
||||
}
|
||||
});
|
||||
|
||||
test("git board rules: every journey names states that exist", () => {
|
||||
for (const j of JOURNEYS) for (const id of j.states) assert.ok(STATES[id], `${j.id} names ${id}`);
|
||||
});
|
||||
|
||||
test("git board rules: held-back files never drive the step, and fill an empty secondary with the ignore offer", () => {
|
||||
const held = step("e-held-only");
|
||||
assert.equal(held.primary, null);
|
||||
assert.deepEqual(held.secondary.map((s) => s.op), ["ignore", "refresh"]);
|
||||
assert.equal(held.secondary[0].label, "Add `.env.local` to .gitignore");
|
||||
assert.deepEqual(held.secondary[0].files, [".env.local"]);
|
||||
assert.equal(held.held, "`.env.local` held back");
|
||||
assert.equal(held.tab, "changes");
|
||||
|
||||
const dirty = step("cp-dirty");
|
||||
assert.equal(dirty.primary.label, "Commit 3 files", "4 changes minus the held-back .env.local");
|
||||
assert.equal(dirty.held, "`.env.local` held back");
|
||||
|
||||
const two = nextStep({
|
||||
...STATES["e-held-only"].git,
|
||||
changes: {
|
||||
count: 2,
|
||||
heldBack: 2,
|
||||
files: [
|
||||
{ path: ".env.local", state: "new", risky: true },
|
||||
{ path: "dump.sql", state: "new", risky: true },
|
||||
],
|
||||
untrackedDirs: [],
|
||||
},
|
||||
}, { now: NOW });
|
||||
assert.equal(two.held, "2 files held back");
|
||||
assert.equal(two.secondary[0].label, "Add 2 held-back files to .gitignore");
|
||||
assert.equal(two.secondary[0].why, "Keep them out of every commit.");
|
||||
assert.equal(held.secondary[0].why, "Keep it out of every commit.");
|
||||
});
|
||||
|
||||
test("git board rules: no default branch means no clean-up step or badge, as boardActions() offers none", () => {
|
||||
const git = STATES["e-gone"].git;
|
||||
assert.equal(step("e-gone").secondary[0].op, "cleanup");
|
||||
const noDefault = { ...git, defaultBranch: null, branches: git.branches.map((b) => ({ ...b, default: false, merged: false, gone: b.current ? b.gone : b.name === "chore/bump-deps" })) };
|
||||
const n = nextStep(noDefault, { now: NOW });
|
||||
assert.ok(![n.primary, ...n.secondary].some((s) => s && s.op === "cleanup"));
|
||||
assert.equal(tabBadges(noDefault, { now: NOW, stepTab: n.tab }).branches, null);
|
||||
});
|
||||
|
||||
test("git board badges: no 'not published' badge before the first commit, even with a remote", () => {
|
||||
const git = { ...STATES["e-first-commit"].git, remotes: STATES["cp-dirty"].git.remotes, lastFetch: STATES["cp-dirty"].git.lastFetch };
|
||||
const n = nextStep(git, { now: NOW });
|
||||
assert.equal(n.primary.op, "commit");
|
||||
assert.equal(tabBadges(git, { now: NOW, stepTab: n.tab }).sync, null);
|
||||
});
|
||||
|
||||
test("git board rules: the stale line never changes the step, and needs a remote", () => {
|
||||
const fresh = step("e-caught-up");
|
||||
const stale = step("e-stale");
|
||||
assert.equal(fresh.stale, null);
|
||||
assert.equal(stale.stale, "Checked 3 hr. ago — Refresh?");
|
||||
assert.deepEqual(stale.primary, fresh.primary);
|
||||
assert.deepEqual(stale.secondary.map((s) => s.op), fresh.secondary.map((s) => s.op));
|
||||
assert.equal(step("e-no-remote").stale, null);
|
||||
const never = nextStep({ ...STATES["e-caught-up"].git, lastFetch: null }, { now: NOW });
|
||||
assert.equal(never.stale, "Never checked — Refresh?");
|
||||
});
|
||||
|
||||
test("git board rules: no remote reads 'Nothing to commit … no remote yet', and still offers Refresh", () => {
|
||||
const n = step("e-no-remote");
|
||||
assert.equal(n.line, "Nothing to commit on main · no remote yet");
|
||||
assert.deepEqual(n.secondary.map((s) => [s.op, s.label]), [["create", "New branch"], ["refresh", "Refresh"]]);
|
||||
});
|
||||
|
||||
test("git board rules: a pushed branch on an unknown host gets no pull request step", () => {
|
||||
const git = STATES["pc-pushed"].git;
|
||||
const unknown = { ...git, remotes: git.remotes.map((r) => ({ ...r, kind: null })) };
|
||||
assert.equal(step("pc-pushed").primary.op, "pr");
|
||||
assert.ok(step("pc-pushed").primary.url.startsWith("https://"));
|
||||
const n = nextStep(unknown, { now: NOW });
|
||||
assert.notEqual(n.primary && n.primary.op, "pr");
|
||||
assert.ok(![n.primary, ...n.secondary].some((s) => s && s.op === "pr"));
|
||||
});
|
||||
|
||||
test("git board rules: mid-operation, Fix the files while markers remain, then Continue, Abort once", () => {
|
||||
const fix = step("pc-conflict");
|
||||
assert.equal(fix.primary.label, "Fix the files");
|
||||
assert.equal(fix.secondary[0].label, "Abort the rebase");
|
||||
assert.equal(step("pc-resolved").primary.op, "continue");
|
||||
const am = nextStep({ ...STATES["pc-resolved"].git, inProgress: "am" }, { now: NOW });
|
||||
assert.equal(am.secondary[0].label, "Abort the git am");
|
||||
});
|
||||
|
||||
test("git board rules: on the default branch, a branch is suggested and committing there is the secondary", () => {
|
||||
const n = step("nb-main-dirty");
|
||||
assert.equal(n.primary.label, "Start a branch for 2 files");
|
||||
assert.equal(n.secondary[0].label, "Commit on main");
|
||||
assert.equal(n.secondary[0].tab, "changes");
|
||||
});
|
||||
|
||||
test("git board badges: each tab badges what it has waiting, and the next step's tab is filled", () => {
|
||||
const dirty = badges("cp-dirty");
|
||||
assert.deepEqual([dirty.changes.text, dirty.changes.kind, dirty.changes.next], ["3", "count", true]);
|
||||
assert.equal(dirty.changes.label, "3 waiting, next step");
|
||||
assert.equal(dirty.branches.text, "2");
|
||||
assert.equal(dirty.branches.next, false);
|
||||
assert.equal(dirty.sync, null);
|
||||
|
||||
const held = badges("e-held-only");
|
||||
assert.deepEqual([held.changes.kind, held.changes.text, held.changes.next], ["dot", "·", false], "no primary, so no filled badge");
|
||||
|
||||
assert.equal(badges("e-many-branches").branches.text, "40");
|
||||
assert.equal(badges("pc-diverged").sync.text, "↑1 ↓3");
|
||||
assert.equal(badges("pc-diverged").sync.label, "1 to push, 3 to pull, next step");
|
||||
assert.equal(badges("nb-unpublished").sync.text, "↑");
|
||||
assert.equal(badges("e-gone").sync.text, "↑");
|
||||
assert.equal(badges("e-stale").sync.text, "?");
|
||||
assert.equal(badges("e-caught-up").sync, null);
|
||||
|
||||
const conflict = badges("pc-conflict");
|
||||
assert.equal(conflict.sync.kind, "warn");
|
||||
assert.equal(conflict.sync.text, "!");
|
||||
assert.equal(conflict.changes, null);
|
||||
assert.equal(conflict.branches, null);
|
||||
});
|
||||
|
||||
test("git board badges: a tab owning the step with nothing of its own gets a filled dot", () => {
|
||||
const b = badges("cp-pushed");
|
||||
assert.deepEqual([b.sync.kind, b.sync.text, b.sync.next], ["dot", "·", true]);
|
||||
assert.equal(b.sync.label, "next step");
|
||||
});
|
||||
|
||||
test("git board busy: offline beats running beats a waiting card", () => {
|
||||
for (let bits = 0; bits < 16; bits++) {
|
||||
const f = { running: Boolean(bits & 1), cardWaiting: Boolean(bits & 2), gone: Boolean(bits & 4), pending: Boolean(bits & 8) };
|
||||
const want = f.gone || f.pending ? "offline" : f.running ? "running" : f.cardWaiting ? "card" : "idle";
|
||||
assert.equal(busyMode(f), want, JSON.stringify(f));
|
||||
}
|
||||
assert.equal(busyMode(), "idle");
|
||||
});
|
||||
|
||||
test("git board busy: nav always works, actions only when idle, Done with git while idle or a card waits", () => {
|
||||
const want = {
|
||||
nav: { offline: true, running: true, card: true, idle: true },
|
||||
action: { offline: false, running: false, card: false, idle: true },
|
||||
done: { offline: false, running: false, card: true, idle: true },
|
||||
};
|
||||
for (const role of ROLES) for (const mode of MODES) assert.equal(controlAllowed(mode, role), want[role][mode], `${role} in ${mode}`);
|
||||
assert.equal(controlAllowed("idle", "nonsense"), false);
|
||||
});
|
||||
|
||||
test("git board tabs: a landed click and arriving go to the step's tab; reload and background keep yours", () => {
|
||||
for (const current of ["changes", "branches", "sync"]) {
|
||||
assert.equal(pickTab({ current, stepTab: "branches", reason: "landed" }), "branches");
|
||||
assert.equal(pickTab({ current, stepTab: "branches", reason: "arrival" }), "branches");
|
||||
assert.equal(pickTab({ current, stepTab: "branches", reason: "reload" }), current);
|
||||
assert.equal(pickTab({ current, stepTab: "branches", reason: "background" }), current);
|
||||
}
|
||||
for (const current of [null, "nonsense"]) {
|
||||
assert.equal(pickTab({ current, stepTab: "changes", reason: "reload" }), "changes");
|
||||
assert.equal(pickTab({ current, stepTab: "changes", reason: "background" }), "changes");
|
||||
}
|
||||
assert.equal(pickTab({ current: null, stepTab: null, reason: "arrival" }), "sync");
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------ the view */
|
||||
|
||||
// The node API git-board-view.js may use (its header comment, phase 2 Task
|
||||
// 2.1), and nothing else: touching any other property throws, so the view
|
||||
// cannot drift onto something the real DOM has and this fake does not.
|
||||
const NODE_API = new Set([
|
||||
"appendChild", "append", "replaceChildren", "setAttribute", "removeAttribute", "addEventListener", "classList",
|
||||
"className", "id", "type", "value", "checked", "disabled", "textContent", "placeholder", "title", "open", "href",
|
||||
"target", "rel", "tabIndex",
|
||||
]);
|
||||
// What the test itself reads off a recorded node.
|
||||
const TEST_ONLY = new Set(["tag", "children", "attrs", "listeners", "parent", "classes", "text"]);
|
||||
|
||||
function fakeNode(tag) {
|
||||
const n = {
|
||||
tag, children: [], attrs: {}, listeners: {}, parent: null, classes: new Set(), text: "",
|
||||
id: "", type: "", value: "", checked: false, disabled: false, placeholder: "", title: "", open: false,
|
||||
href: "", target: "", rel: "", tabIndex: 0,
|
||||
appendChild(c) {
|
||||
c.parent = proxy;
|
||||
n.children.push(c);
|
||||
return c;
|
||||
},
|
||||
append(...cs) {
|
||||
for (const c of cs) proxy.appendChild(c);
|
||||
},
|
||||
replaceChildren(...cs) {
|
||||
n.children = [];
|
||||
n.text = "";
|
||||
proxy.append(...cs);
|
||||
},
|
||||
setAttribute(k, v) {
|
||||
n.attrs[k] = String(v);
|
||||
},
|
||||
removeAttribute(k) {
|
||||
delete n.attrs[k];
|
||||
},
|
||||
addEventListener(type, fn) {
|
||||
(n.listeners[type] ||= []).push(fn);
|
||||
},
|
||||
classList: {
|
||||
add: (...c) => c.forEach((x) => n.classes.add(x)),
|
||||
remove: (...c) => c.forEach((x) => n.classes.delete(x)),
|
||||
toggle: (c, force) => {
|
||||
const on = force === undefined ? !n.classes.has(c) : Boolean(force);
|
||||
if (on) n.classes.add(c);
|
||||
else n.classes.delete(c);
|
||||
return on;
|
||||
},
|
||||
contains: (c) => n.classes.has(c),
|
||||
},
|
||||
};
|
||||
const proxy = new Proxy(n, {
|
||||
get(t, key) {
|
||||
if (typeof key !== "string" || TEST_ONLY.has(key)) return t[key];
|
||||
if (!NODE_API.has(key)) throw new Error(`the view used .${key}, which is not in its node API`);
|
||||
if (key === "className") return [...t.classes].join(" ");
|
||||
if (key === "textContent") return t.text + t.children.map((c) => c.textContent).join("");
|
||||
return t[key];
|
||||
},
|
||||
set(t, key, v) {
|
||||
if (typeof key === "string" && !NODE_API.has(key) && !TEST_ONLY.has(key)) throw new Error(`the view set .${key}, which is not in its node API`);
|
||||
if (key === "className") t.classes = new Set(String(v || "").split(/\s+/).filter(Boolean));
|
||||
else if (key === "textContent") {
|
||||
t.children = [];
|
||||
t.text = v == null ? "" : String(v);
|
||||
} else t[key] = v;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
return proxy;
|
||||
}
|
||||
|
||||
/** The helpers the view is handed, recording every node made. */
|
||||
function fakeH() {
|
||||
const all = [];
|
||||
const el = (tag, className, text) => {
|
||||
const n = fakeNode(tag);
|
||||
if (className) n.className = className;
|
||||
if (text != null) n.textContent = text;
|
||||
all.push(n);
|
||||
return n;
|
||||
};
|
||||
return { el, md: (text, cls) => el("div", cls, text), copyButton: (text, cls) => el("button", cls, "Copy"), all };
|
||||
}
|
||||
|
||||
/** ctx.on, recording every call as [name, ...args]. */
|
||||
function fakeOn() {
|
||||
const calls = [];
|
||||
const rec = (name) => (...args) => calls.push([name, ...args]);
|
||||
return {
|
||||
calls,
|
||||
send: rec("send"), redraw: rec("redraw"), pickTab: rec("pickTab"), openPanel: rec("openPanel"),
|
||||
closePanel: rec("closePanel"), pickPrHost: rec("pickPrHost"), persist: rec("persist"),
|
||||
};
|
||||
}
|
||||
|
||||
// The Create prompt's fields as openCreate() in app.js seeds them.
|
||||
const seedCreate = (git, commit = false) => ({
|
||||
from: createSources(git, commit).preset,
|
||||
type: BRANCH_TYPES[0],
|
||||
description: "",
|
||||
name: null,
|
||||
commit,
|
||||
files: commit ? [...commitTicks(git.changes)] : null,
|
||||
ignore: [],
|
||||
});
|
||||
|
||||
// The panels each tab can draw; "create-commit" is the create panel in commit mode, on Changes.
|
||||
const PANELS = { changes: [null, "commit", "create-commit"], branches: [null, "create", "cleanup"], sync: [null] };
|
||||
|
||||
function draw(id, { mode = "idle", tab = null, panel = null, create = null } = {}) {
|
||||
const s = STATES[id];
|
||||
const git = s.git;
|
||||
const step = nextStep(git, { now: NOW });
|
||||
const badges = tabBadges(git, { now: NOW, stepTab: step.tab });
|
||||
const board = {
|
||||
tab,
|
||||
panel: panel === "create-commit" ? "create" : panel,
|
||||
create: create || (panel === "create" ? seedCreate(git) : panel === "create-commit" ? seedCreate(git, true) : null),
|
||||
ticks: null, ignore: new Set(), sweep: null, query: "", showAll: false, remoteOpen: null, base: null,
|
||||
};
|
||||
const h = fakeH();
|
||||
const on = fakeOn();
|
||||
const out = drawGitBoard({
|
||||
git, board, now: NOW, mode, step, badges, notice: s.result || null, activity: s.busy || null,
|
||||
hasCard: false, offlineReason: "gone", h, on,
|
||||
});
|
||||
return { ...out, h, on, board, step };
|
||||
}
|
||||
|
||||
function walk(node, out = []) {
|
||||
out.push(node);
|
||||
for (const c of node.children) walk(c, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
const isControl = (n) => ["button", "input", "select"].includes(n.tag) || (["a", "span"].includes(n.tag) && n.classes.has("git-pr-open"));
|
||||
const controls = (node) => walk(node).filter(isControl);
|
||||
const isOff = (n) => (n.tag === "span" ? n.attrs["aria-disabled"] === "true" : Boolean(n.disabled));
|
||||
// A control's words: its own text, or for a bare box, the label around it.
|
||||
const words = (n) => n.textContent.trim() || (n.parent && n.parent.tag === "label" ? n.parent.textContent.trim() : "");
|
||||
|
||||
function* everyRender(modes = ["idle", "running", "card", "offline"]) {
|
||||
for (const id of Object.keys(STATES)) {
|
||||
for (const mode of modes) {
|
||||
for (const tab of TAB_IDS) for (const panel of PANELS[tab]) yield { id, mode, tab, panel, r: draw(id, { mode, tab, panel }) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("git board view: no control leaks the busy lock, in any state, mode, tab or panel", () => {
|
||||
let checked = 0;
|
||||
for (const { id, mode, tab, panel, r } of everyRender()) {
|
||||
const where = `${id} · ${mode} · ${tab} · ${panel}`;
|
||||
const all = controls(r.node);
|
||||
for (const c of all) {
|
||||
const gate = c.attrs["data-gate"];
|
||||
assert.ok(["nav", "action", "done"].includes(gate), `${where}: "${words(c)}" (${c.tag}) has no data-gate`);
|
||||
const own = c.attrs["data-own"] === "true";
|
||||
if (!controlAllowed(mode, gate)) assert.ok(isOff(c), `${where}: "${words(c)}" is live while busy`);
|
||||
else assert.equal(isOff(c), own, `${where}: "${words(c)}" is ${isOff(c) ? "greyed with no reason of its own" : "live despite its own reason"}`);
|
||||
checked++;
|
||||
}
|
||||
const done = all.filter((c) => c.textContent === "Done with git");
|
||||
assert.equal(done.length, 1, `${where}: exactly one Done with git`);
|
||||
assert.equal(!done[0].disabled, mode === "idle" || mode === "card", `${where}: Done with git live only while idle or a card waits`);
|
||||
}
|
||||
assert.ok(checked > 1000, "the guard looked at the board's controls");
|
||||
});
|
||||
|
||||
test("git board view: every function of today's board is reachable on some tab", () => {
|
||||
const texts = new Set();
|
||||
const ids = { select: new Set(), input: new Set() };
|
||||
const take = (r) => {
|
||||
for (const c of controls(r.node)) {
|
||||
texts.add(words(c));
|
||||
if (c.id && ids[c.tag]) ids[c.tag].add(c.id);
|
||||
}
|
||||
};
|
||||
for (const { r } of everyRender(["idle"])) take(r);
|
||||
// A name that is taken offers Switch to it.
|
||||
take(draw("cp-dirty", { tab: "branches", panel: "create", create: { ...seedCreate(STATES["cp-dirty"].git), name: "main" } }));
|
||||
|
||||
// Exact, except the labels that carry a count ("Commit 3 files", "Show all 179").
|
||||
const has = (want, prefix = false) => [...texts].some((t) => t === want || (prefix && t.startsWith(`${want} `)));
|
||||
for (const want of [
|
||||
"Add to .gitignore", "Create branch", "New branch", "Create", "Switch", "Delete", "Choose which to clean up…",
|
||||
"Refresh", "Pull", "Publish", "Open pull request", "Copy", "Abort the rebase", "Continue", "Done with git",
|
||||
"Switch to it",
|
||||
]) {
|
||||
assert.ok(has(want), `"${want}" is drawn somewhere`);
|
||||
}
|
||||
for (const want of ["Commit", "Show all", "Clean up", "Push"]) assert.ok(has(want, true), `"${want} …" is drawn somewhere`);
|
||||
for (const id of ["git-pr-base", "git-new-from", "git-new-type"]) assert.ok(ids.select.has(id), `select #${id}`);
|
||||
for (const id of ["git-search", "git-new-desc", "git-new-name"]) assert.ok(ids.input.has(id), `input #${id}`);
|
||||
|
||||
for (const [id, s] of Object.entries(STATES)) {
|
||||
const head = draw(id).node.children.find((c) => c.tag === "header");
|
||||
if (s.git.head.branch) assert.ok(head.textContent.includes(s.git.head.branch), `${id}: the header names the branch`);
|
||||
}
|
||||
assert.ok(draw("e-no-remote").node.children[0].textContent.includes("git remote add origin <url>"));
|
||||
});
|
||||
|
||||
test("git board view: pins on its source and on a few states", () => {
|
||||
for (const word of ["document", "window", "querySelector", "getBoundingClientRect", ".style"]) {
|
||||
assert.ok(!VIEW_SRC.includes(word), `git-board-view.js never names ${word}`);
|
||||
}
|
||||
const imports = [...VIEW_SRC.matchAll(/\bfrom\s+["']([^"']+)["']/g)].map((m) => m[1]);
|
||||
assert.deepEqual(imports, ["./git-board.js"], "it imports only ./git-board.js");
|
||||
assert.doesNotMatch(VIEW_SRC, /\bimport\s*\(/, "and nothing dynamically");
|
||||
|
||||
const conflict = controls(draw("pc-conflict").node).filter((c) => c.textContent.startsWith("Abort"));
|
||||
assert.equal(conflict.length, 1, "mid-rebase, Abort is offered once");
|
||||
|
||||
const held = draw("e-held-only", { tab: "changes" });
|
||||
const strip = walk(held.node).find((n) => n.classes.has("git-step"));
|
||||
assert.ok(strip, "the step strip is on Changes");
|
||||
assert.ok(walk(strip).find((n) => n.classes.has("git-held")).textContent.includes("`.env.local` held back"));
|
||||
assert.ok(controls(strip).some((c) => c.textContent === "Add `.env.local` to .gitignore"), "the ignore offer is the secondary");
|
||||
|
||||
const away = draw("cp-dirty", { tab: "sync" });
|
||||
const hint = walk(away.node).find((n) => n.classes.has("git-hint"));
|
||||
assert.ok(hint, "a tab that does not own the step points at it");
|
||||
assert.ok(hint.textContent.includes("Commit 3 files"));
|
||||
assert.ok(hint.textContent.startsWith("Next step is on Changes:"));
|
||||
});
|
||||
|
||||
const click = (n) => n.listeners.click.forEach((fn) => fn());
|
||||
const stepButtons = (r) => controls(walk(r.node).find((n) => n.classes.has("git-step")));
|
||||
|
||||
test("git board view: each step's click goes out as the board offers it", () => {
|
||||
const held = draw("e-held-only");
|
||||
click(stepButtons(held).find((c) => c.textContent.startsWith("Add ")));
|
||||
assert.deepEqual(held.on.calls, [["openPanel", "commit", { ignore: [".env.local"], ticks: [] }]]);
|
||||
|
||||
const unpublished = draw("nb-unpublished");
|
||||
click(stepButtons(unpublished).find((c) => c.textContent === "Publish"));
|
||||
assert.deepEqual(unpublished.on.calls, [["send", "publish", { remote: "origin" }]]);
|
||||
|
||||
const main = draw("nb-main-dirty");
|
||||
const [branch, onMain] = stepButtons(main);
|
||||
click(branch);
|
||||
click(onMain);
|
||||
assert.deepEqual(main.on.calls, [["openPanel", "create", { commit: true }], ["openPanel", "commit"]]);
|
||||
|
||||
const away = draw("pc-conflict", { tab: "changes" });
|
||||
click(walk(away.node).find((n) => n.classes.has("git-hint")));
|
||||
assert.deepEqual(away.on.calls, [["pickTab", "sync"]]);
|
||||
|
||||
const op = draw("pc-conflict");
|
||||
const opButtons = controls(walk(op.node).find((n) => n.classes.has("git-op")));
|
||||
opButtons.forEach(click);
|
||||
assert.deepEqual(op.on.calls, [["send", "continue", {}, { operation: "rebase" }], ["send", "abort", {}, { operation: "rebase" }]]);
|
||||
});
|
||||
|
||||
test("git board view: a .gitignore-only pick commits just .gitignore, and never on a detached HEAD", () => {
|
||||
const ignoreHeld = (git) => ({ ...git, changes: STATES["e-held-only"].git.changes });
|
||||
const opened = (git) => {
|
||||
const step = nextStep(git, { now: NOW });
|
||||
const board = { tab: "changes", panel: "commit", create: null, ticks: new Set(), ignore: new Set([".env.local"]), sweep: null, query: "", showAll: false, remoteOpen: null, base: null };
|
||||
const h = fakeH();
|
||||
const on = fakeOn();
|
||||
const { node } = drawGitBoard({ git, board, now: NOW, mode: "idle", step, badges: tabBadges(git, { now: NOW, stepTab: step.tab }), notice: null, activity: null, h, on });
|
||||
return { node, on };
|
||||
};
|
||||
|
||||
const onMain = opened(STATES["e-held-only"].git);
|
||||
const add = controls(onMain.node).find((c) => c.textContent === "Add 1 to .gitignore");
|
||||
assert.ok(add && !add.disabled);
|
||||
click(add);
|
||||
assert.deepEqual(onMain.on.calls, [["send", "commit", { files: [], ignore: [".env.local"] }]]);
|
||||
|
||||
const detached = opened(ignoreHeld(STATES["e-detached"].git));
|
||||
assert.ok(!controls(detached.node).some((c) => c.textContent === "Add 1 to .gitignore"), "no commit straight onto a detached HEAD");
|
||||
const make = controls(detached.node).find((c) => c.textContent === "Create branch");
|
||||
assert.ok(make && !make.disabled, "the branch comes first, .gitignore pick and all");
|
||||
click(make);
|
||||
assert.deepEqual(detached.on.calls, [["openPanel", "create", { commit: true, files: [], ignore: [".env.local"] }]]);
|
||||
|
||||
assert.equal(gitReply("commit", { files: [], ignore: [".env.local"] }), "Add .env.local to .gitignore and commit just .gitignore.");
|
||||
assert.equal(
|
||||
gitReply("create", { name: "fix/x", from: "a1b2c3d", then: "commit", files: [], ignore: [".env.local"] }),
|
||||
"Create fix/x from a1b2c3d. Then add .env.local to .gitignore and commit just .gitignore."
|
||||
);
|
||||
assert.equal(gitReply("commit", { files: ["a.js"], ignore: ["dist/"] }), "Commit this file: a.js. Add dist/ to .gitignore.");
|
||||
});
|
||||
|
||||
test("git board host: the host draws the board only through drawGitBoard, and the server serves the view", () => {
|
||||
const host = fs.readFileSync(new URL("../src/web-console/public/screens/git-host.js", import.meta.url), "utf8");
|
||||
for (const gone of ["gitActionBar", "gitBranches", "smallButton", "gitHeader", "gitCommitPanel"]) {
|
||||
assert.ok(!host.includes(`function ${gone}(`), `git-host.js no longer defines ${gone}()`);
|
||||
}
|
||||
const drawCalls = [...host.matchAll(/\bdrawGitBoard\(/g)].length;
|
||||
assert.equal(drawCalls, 1, "one call to drawGitBoard");
|
||||
const body = host.slice(host.indexOf("function renderGitBoard("), host.indexOf("function rememberGitTabScroll("));
|
||||
assert.ok(body.includes("drawGitBoard("), "renderGitBoard is the one that calls it");
|
||||
const server = fs.readFileSync(new URL("../src/web-console/static.mjs", import.meta.url), "utf8");
|
||||
const servable = server.slice(server.indexOf("const SERVABLE = new Set(["), server.indexOf("]);", server.indexOf("const SERVABLE = new Set([")));
|
||||
assert.ok(servable.includes('"git-board-view.js"'), "SERVABLE includes git-board-view.js");
|
||||
assert.ok(servable.includes('"screens/git-host.js"'), "SERVABLE includes screens/git-host.js");
|
||||
});
|
||||
|
||||
// The commit table's ticks and the click that re-seeds them are page tests now
|
||||
// ("the commit table keeps the person's ticks across an agent post, and a click
|
||||
// re-seeds them" and its neighbours in test-web-console-page-git.mjs).
|
||||
|
||||
test("git board docs: the agent prose, Help topic and readme describe the tabbed board", () => {
|
||||
const read = (p) => fs.readFileSync(new URL(p, import.meta.url), "utf8");
|
||||
const notes = read("../src/web-console/notes/git.md");
|
||||
const finishing = notes.slice(notes.indexOf("**Finishing**"));
|
||||
assert.ok(finishing.includes("Done with git"), "notes/git.md Finishing names Done with git");
|
||||
assert.ok(finishing.includes("cancel"), "notes/git.md Finishing cancels an open card");
|
||||
assert.ok(!finishing.includes('"settle": ["<id>"]'), "the cancel rule never settles a card nothing was sent to");
|
||||
assert.ok(notes.includes("`files[]` may be empty"), "notes/git.md allows a .gitignore-only commit");
|
||||
assert.ok(read("../src/plan2code-git.md").includes("Done with git"), "plan2code-git.md names Done with git");
|
||||
const html = read("../src/web-console/public/index.html");
|
||||
const start = html.indexOf('<section class="help-panel" data-tab="git">');
|
||||
const help = html.slice(start, html.indexOf("</section>", start));
|
||||
for (const word of ["Changes", "Branches", "Sync", "Done with git"]) assert.ok(help.includes(word), `Help's git topic mentions ${word}`);
|
||||
for (const old of ["one board", "one page"]) assert.ok(!help.includes(old), `Help's git topic no longer says "${old}"`);
|
||||
assert.ok(!read("../.readme/web-console.md").includes("commits on one page"), "the readme no longer says commits on one page");
|
||||
});
|
||||
@@ -14,12 +14,11 @@ import { spawnSync } from "node:child_process";
|
||||
// is exactly why this lives in its own file.
|
||||
import {
|
||||
cardAvailability,
|
||||
CONSOLE_WORKFLOWS,
|
||||
GIT_INIT_NOTE,
|
||||
resumeCommand,
|
||||
SKILL_CATALOG,
|
||||
START_POSES,
|
||||
} from "../src/web-console/public/answers.js";
|
||||
import { SKILLS } from "../src/web-console/public/skills.js";
|
||||
import { breakdownFrom, pointsFrom } from "../src/web-console/public/meter.js";
|
||||
import {
|
||||
BRANCH_TYPES,
|
||||
@@ -38,7 +37,7 @@ import {
|
||||
refreshedLine,
|
||||
} from "../src/web-console/public/git-board.js";
|
||||
import { prUrl } from "../src/web-console/public/pr-url.js";
|
||||
import { PROTECTED_CONSOLE_FILES, readLedger } from "../src/web-console/lib.mjs";
|
||||
import { PROTECTED_CONSOLE_FILES, readLedger } from "../src/web-console/sessions.mjs";
|
||||
import {
|
||||
CONSOLE_CLI,
|
||||
HOME,
|
||||
@@ -290,8 +289,6 @@ test("git: the Git card is never greyed, and its resume command is /plan2code-gi
|
||||
assert.deepEqual(cardAvailability(entry, { hasAgents: true, isGit: true, pending: 0 }, null), { on: true });
|
||||
assert.deepEqual(cardAvailability(entry, { hasAgents: true, isGit: true, pending: null }, null), { on: true });
|
||||
assert.equal(resumeCommand({ workflow: "git" }), "/plan2code-git");
|
||||
assert.ok(CONSOLE_WORKFLOWS.includes("/plan2code-git"));
|
||||
assert.ok(START_POSES.includes("git"));
|
||||
});
|
||||
|
||||
test("git: the Git card's copy, place and availability are pinned (FR-58, FR-59)", async () => {
|
||||
@@ -303,7 +300,11 @@ test("git: the Git card's copy, place and availability are pinned (FR-58, FR-59)
|
||||
);
|
||||
assert.equal(entry.group, "extra");
|
||||
assert.equal(entry.chip, "Utility");
|
||||
assert.equal(SKILL_CATALOG.at(-1), entry, "the Git card is last");
|
||||
// The card order is skills.js's order.
|
||||
const order = SKILLS.filter((s) => s.card).map((s) => s.skill);
|
||||
assert.equal(order.indexOf("plan2code-git") + 1, order.indexOf("plan2code-handoff"), "the Git card comes right before Handoff");
|
||||
assert.equal(order.at(-1), "plan2code-handoff", "the Handoff card is last");
|
||||
assert.deepEqual(SKILL_CATALOG.map((e) => e.skill), order, "the catalog draws in that order");
|
||||
for (const isGit of [true, false, undefined]) {
|
||||
for (const pending of [0, 3, null]) {
|
||||
const scan = { hasAgents: true, pending, ...(isGit === undefined ? {} : { isGit }) };
|
||||
@@ -326,11 +327,10 @@ test("git: the board stays locked from a click until the agent's next post, not
|
||||
assert.equal(boardAwaiting({ sentAt, updatedAt: "2026-10-10T05:15:51.000Z", cardsAwaiting: 2 }), true);
|
||||
assert.equal(boardAwaiting({ sentAt, cardsAwaiting: 1, adrift: true }), false, "an agent gone quiet releases the lock");
|
||||
|
||||
const app = fs.readFileSync(new URL("../src/web-console/public/app.js", import.meta.url), "utf8");
|
||||
assert.match(app, /const gitLocked = \(\) =>[^;]*gitAwaiting\(\)/, "gitLocked includes gitAwaiting()");
|
||||
const send = app.slice(app.indexOf("async function sendGit("), app.indexOf("function renderGitBoard("));
|
||||
assert.match(send, /local\.gitSentAt = Date\.now\(\);\s*save\(\);/, "a board click records when it was sent, and saves it");
|
||||
assert.match(app, /sentAt: local\.gitSentAt[\s\S]{0,80}updatedAt: S\.updatedAt[\s\S]{0,80}cardsAwaiting: awaitingReply\(\)\.length/);
|
||||
// gitMode, gitLocked and the click's gitSentAt are page tests now (the board
|
||||
// stays locked in test-web-console-page-git.mjs); what feeds them is here.
|
||||
const selectors = fs.readFileSync(new URL("../src/web-console/public/selectors.js", import.meta.url), "utf8");
|
||||
assert.match(selectors, /sentAt: page\.local\.gitSentAt[\s\S]{0,80}updatedAt: page\.S\.updatedAt[\s\S]{0,80}cardsAwaiting: awaitingReply\(\)\.length/);
|
||||
});
|
||||
|
||||
/* ------------------------------------------- the git board's pure helpers */
|
||||
@@ -561,17 +561,13 @@ test("git board: boardPrLink builds the link for a pushed feature branch only",
|
||||
|
||||
test("git board: the page draws it from git-board.js, with no inline styles", () => {
|
||||
const dir = path.join(path.dirname(CONSOLE_CLI), "public");
|
||||
const app = fs.readFileSync(path.join(dir, "app.js"), "utf8");
|
||||
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
||||
assert.match(app, /^import [^;]+ from "\.\/git-board\.js";/m, "app.js imports git-board.js");
|
||||
for (const m of ["git-board.js", "pr-url.js"]) assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
||||
assert.match(app, /const isGitBoard = \(\) => S && S\.workflow === "git" && S\.git;/);
|
||||
assert.match(app, /i: "__git", type: "git", op/, "a click is one __git action");
|
||||
assert.match(app, /a\.rel = "noopener"/, "the PR link opens with rel=noopener");
|
||||
const start = app.indexOf("/* ------------------------------------------------------------ git board */");
|
||||
const end = app.indexOf("/* ------------------------------------------------------------- welcome */");
|
||||
assert.ok(start > 0 && end > start);
|
||||
assert.doesNotMatch(app.slice(start, end), /setAttribute\(\s*["']style["']|\.style\./, "the board sets no inline styles");
|
||||
const view = fs.readFileSync(path.join(dir, "git-board-view.js"), "utf8");
|
||||
for (const m of ["git-board.js", "git-board-view.js", "pr-url.js"]) assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
||||
const selectors = fs.readFileSync(path.join(dir, "selectors.js"), "utf8");
|
||||
assert.match(selectors, /const isGitBoard = \(\) => page\.S && page\.S\.workflow === "git" && page\.S\.git;/);
|
||||
assert.match(view, /a\.rel = "noopener"/, "the PR link opens with rel=noopener");
|
||||
assert.doesNotMatch(view, /setAttribute\(\s*["']style["']|\.style\./, "nor does its view");
|
||||
});
|
||||
|
||||
// The board's every click is one `__git` action; the agent reads it off the
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
// Web console tests, the handoff store: ids, writing, listing, marking,
|
||||
// removing and sweeping ~/.plan2code/handoffs/, and the console commands
|
||||
// built on it.
|
||||
// Run with: node --test scripts/test-web-console-handoffs.mjs
|
||||
//
|
||||
// Shared setup (a per-process console home, the CLI runner, fixtures) lives in
|
||||
// web-console-test-helpers.mjs; see the comment at its top. Every handoff here
|
||||
// lands in its throwaway HANDOFFS_DIR, never the real home folder.
|
||||
|
||||
import test 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 { spawnSync } from "node:child_process";
|
||||
import { CONSOLE_CLI, ENV, HANDOFFS_DIR, cli, safeJson, sessionUrl } from "./web-console-test-helpers.mjs";
|
||||
|
||||
process.env.PLAN2CODE_HANDOFFS_DIR = HANDOFFS_DIR;
|
||||
const store = await import("../src/web-console/handoffs.mjs");
|
||||
const { HANDOFF_ID, handoffsDir, isHandoffId } = store;
|
||||
|
||||
test("isHandoffId takes only a bare handoff id", () => {
|
||||
assert.ok(isHandoffId("2026-10-17-1152-handoff"));
|
||||
assert.ok(isHandoffId("2026-10-17-1152-handoff-3"));
|
||||
for (const bad of ["../x", "2026-10-17-1152-handoff.md", "a/2026-10-17-1152-handoff", "", null, undefined, 7, {}]) {
|
||||
assert.equal(isHandoffId(bad), false, String(bad));
|
||||
}
|
||||
assert.ok(HANDOFF_ID.test("2026-10-17-1152-handoff"));
|
||||
});
|
||||
|
||||
test("handoffsDir follows PLAN2CODE_HANDOFFS_DIR at call time", () => {
|
||||
assert.equal(handoffsDir(), HANDOFFS_DIR);
|
||||
const saved = process.env.PLAN2CODE_HANDOFFS_DIR;
|
||||
try {
|
||||
process.env.PLAN2CODE_HANDOFFS_DIR = path.join(HANDOFFS_DIR, "elsewhere");
|
||||
assert.equal(handoffsDir(), path.join(HANDOFFS_DIR, "elsewhere"));
|
||||
} finally {
|
||||
process.env.PLAN2CODE_HANDOFFS_DIR = saved;
|
||||
}
|
||||
});
|
||||
|
||||
// A link at `at`: a file symlink to `file` where the machine allows one, else
|
||||
// a junction to the folder `dir`, which needs no privilege on Windows and
|
||||
// which lstat reports as a link all the same. False when neither can be made.
|
||||
function link(file, dir, at) {
|
||||
try {
|
||||
fs.symlinkSync(file, at, "file");
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (err.code !== "EPERM") throw err;
|
||||
}
|
||||
try {
|
||||
fs.symlinkSync(dir, at, "junction");
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// A clean folder per test that writes handoffs, and the pinned clock it asks for.
|
||||
function fresh(nowPinned) {
|
||||
fs.rmSync(HANDOFFS_DIR, { recursive: true, force: true });
|
||||
if (nowPinned === undefined) delete process.env.PLAN2CODE_NOW;
|
||||
else process.env.PLAN2CODE_NOW = nowPinned;
|
||||
}
|
||||
|
||||
const WORKTREE = path.join(HANDOFFS_DIR, "..", "repo");
|
||||
const REC = {
|
||||
worktree: WORKTREE,
|
||||
project: WORKTREE,
|
||||
spec: "specs/lunch-vote",
|
||||
workflow: "quick-task",
|
||||
skill: "plan2code-quick-task",
|
||||
title: "Lunch vote",
|
||||
fromStop: true,
|
||||
};
|
||||
|
||||
test("newHandoff claims the next free id for the minute and writes only the .json", () => {
|
||||
fresh("2026-10-17 11:52");
|
||||
try {
|
||||
const a = store.newHandoff(REC);
|
||||
const b = store.newHandoff({ ...REC, spec: undefined, fromStop: false });
|
||||
assert.equal(a.id, "2026-10-17-1152-handoff");
|
||||
assert.equal(b.id, "2026-10-17-1152-handoff-2");
|
||||
assert.equal(a.path, path.join(HANDOFFS_DIR, a.id + ".md"));
|
||||
assert.equal(fs.existsSync(a.path), false, "the agent writes the .md");
|
||||
const meta = JSON.parse(fs.readFileSync(path.join(HANDOFFS_DIR, a.id + ".json"), "utf8"));
|
||||
assert.deepEqual(Object.keys(meta), ["v", "id", "title", "worktree", "project", "spec", "workflow", "skill", "written", "fromStop", "usedAt"]);
|
||||
assert.deepEqual(
|
||||
{ ...meta, written: undefined },
|
||||
{ v: 1, id: a.id, title: "Lunch vote", worktree: WORKTREE, project: WORKTREE, spec: "specs/lunch-vote", workflow: "quick-task", skill: "plan2code-quick-task", written: undefined, fromStop: true, usedAt: null }
|
||||
);
|
||||
assert.ok(!Number.isNaN(Date.parse(meta.written)));
|
||||
assert.deepEqual(a.meta, meta);
|
||||
assert.equal(b.meta.spec, null);
|
||||
assert.equal(b.meta.fromStop, false);
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("newHandoff refuses a bad workflow, skill or spec and leaves no file", () => {
|
||||
fresh("2026-10-17 11:52");
|
||||
try {
|
||||
for (const [field, value] of [["workflow", "Quick Task"], ["workflow", undefined], ["skill", "../x"], ["spec", "../x"], ["spec", "specs/a/b"]]) {
|
||||
assert.throws(() => store.newHandoff({ ...REC, [field]: value }), new RegExp(field));
|
||||
}
|
||||
assert.deepEqual(fs.existsSync(HANDOFFS_DIR) ? fs.readdirSync(HANDOFFS_DIR) : [], []);
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("readHandoffMeta round-trips, markHandoffUsed stamps usedAt and leaves the .md alone", () => {
|
||||
fresh("2026-10-17 11:52");
|
||||
try {
|
||||
const { id, path: md, meta } = store.newHandoff(REC);
|
||||
fs.writeFileSync(md, "# Handoff: Lunch vote\n");
|
||||
const before = fs.readFileSync(md);
|
||||
assert.deepEqual(store.readHandoffMeta(id), meta);
|
||||
const used = store.markHandoffUsed(id, new Date("2026-10-18T09:00:00Z"));
|
||||
assert.equal(used.usedAt, "2026-10-18T09:00:00.000Z");
|
||||
assert.deepEqual(store.readHandoffMeta(id), used);
|
||||
assert.deepEqual(fs.readFileSync(md), before);
|
||||
assert.equal(store.readHandoffMeta("../x"), null);
|
||||
assert.equal(store.readHandoffMeta("2026-10-17-1152-handoff-9"), null);
|
||||
assert.equal(store.markHandoffUsed("2026-10-17-1152-handoff-9"), null);
|
||||
fs.writeFileSync(path.join(HANDOFFS_DIR, "2026-10-17-1152-handoff-7.json"), "not json");
|
||||
assert.equal(store.readHandoffMeta("2026-10-17-1152-handoff-7"), null);
|
||||
fs.writeFileSync(path.join(HANDOFFS_DIR, "2026-10-17-1152-handoff-8.json"), JSON.stringify({ ...meta, v: 2 }));
|
||||
assert.equal(store.readHandoffMeta("2026-10-17-1152-handoff-8"), null);
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("readHandoffMeta refuses a linked .json", (t) => {
|
||||
fresh("2026-10-17 11:52");
|
||||
try {
|
||||
const { meta } = store.newHandoff(REC);
|
||||
const linkId = "2026-10-17-1152-handoff-5";
|
||||
const outside = path.join(HANDOFFS_DIR, "..", "outside-dir");
|
||||
fs.mkdirSync(outside, { recursive: true });
|
||||
if (!link(path.join(HANDOFFS_DIR, meta.id + ".json"), outside, path.join(HANDOFFS_DIR, linkId + ".json"))) {
|
||||
t.skip("this machine can make neither a symlink nor a junction");
|
||||
return;
|
||||
}
|
||||
assert.equal(store.readHandoffMeta(linkId), null);
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
// A handoff with a document, as the agent would leave it.
|
||||
function written(rec, md, when) {
|
||||
const h = store.newHandoff(rec, when);
|
||||
if (md !== null) fs.writeFileSync(h.path, md);
|
||||
return h;
|
||||
}
|
||||
|
||||
const DOC = `# Handoff: Lunch vote
|
||||
|
||||
## Context
|
||||
|
||||
Some context.
|
||||
|
||||
## Next task
|
||||
|
||||
Wire the vote button
|
||||
to the tally, then test it.
|
||||
|
||||
## Notes
|
||||
|
||||
x
|
||||
`;
|
||||
|
||||
test("listHandoffs lists only this checkout's unused handoffs that have both files, newest first", () => {
|
||||
fresh();
|
||||
try {
|
||||
const mine = written(REC, DOC, new Date("2026-10-17T10:00:00Z"));
|
||||
const newer = written({ ...REC, title: "Second" }, "# Handoff - Second try\n\n## Next task\n\n" + "word ".repeat(80) + "\n", new Date("2026-10-17T12:00:00Z"));
|
||||
written({ ...REC, worktree: path.join(HANDOFFS_DIR, "..", "other") }, DOC, new Date("2026-10-17T10:01:00Z"));
|
||||
const used = written(REC, DOC, new Date("2026-10-17T10:02:00Z"));
|
||||
store.markHandoffUsed(used.id);
|
||||
// A .json with no .md, and a .md with no .json.
|
||||
written(REC, null, new Date("2026-10-17T10:03:00Z"));
|
||||
fs.writeFileSync(path.join(HANDOFFS_DIR, "2026-10-01-0900-handoff.md"), DOC);
|
||||
|
||||
const list = store.listHandoffs(WORKTREE);
|
||||
assert.deepEqual(list.map((h) => h.id), [newer.id, mine.id]);
|
||||
assert.deepEqual(list[1], {
|
||||
id: mine.id,
|
||||
title: "Lunch vote",
|
||||
next: "Wire the vote button to the tally, then test it.",
|
||||
written: mine.meta.written,
|
||||
spec: "specs/lunch-vote",
|
||||
skill: "plan2code-quick-task",
|
||||
workflow: "quick-task",
|
||||
});
|
||||
assert.equal(list[0].title, "Second try");
|
||||
assert.equal(list[0].next.length, 280);
|
||||
assert.ok(list[0].next.endsWith("…"));
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("listHandoffs falls back to the stored title and lists nothing for a missing folder", () => {
|
||||
fresh();
|
||||
try {
|
||||
assert.deepEqual(store.listHandoffs(WORKTREE), []);
|
||||
const h = written(REC, "No heading here.\n", new Date("2026-10-17T10:00:00Z"));
|
||||
assert.deepEqual(store.listHandoffs(WORKTREE).map((x) => [x.id, x.title, x.next]), [[h.id, "Lunch vote", ""]]);
|
||||
// Only the word "Handoff" is a prefix: "Handoffs" is part of the title.
|
||||
const plural = written(REC, "# Handoffs page redesign\n", new Date("2026-10-17T09:00:00Z"));
|
||||
assert.equal(store.listHandoffs(WORKTREE).find((x) => x.id === plural.id).title, "Handoffs page redesign");
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("listHandoffs matches the worktree whatever its case on win32 and darwin", { skip: process.platform !== "win32" && process.platform !== "darwin" }, () => {
|
||||
fresh();
|
||||
try {
|
||||
const h = written(REC, DOC, new Date("2026-10-17T10:00:00Z"));
|
||||
assert.deepEqual(store.listHandoffs(WORKTREE.toUpperCase()).map((x) => x.id), [h.id]);
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("removeHandoff removes both files, or a lone one, and refuses anything else", () => {
|
||||
fresh();
|
||||
try {
|
||||
const both = written(REC, DOC, new Date("2026-10-17T10:00:00Z"));
|
||||
assert.deepEqual(store.removeHandoff(both.id), { ok: true, removed: [both.id + ".md", both.id + ".json"] });
|
||||
assert.deepEqual(fs.readdirSync(HANDOFFS_DIR), []);
|
||||
|
||||
fs.writeFileSync(path.join(HANDOFFS_DIR, "2026-10-01-0900-handoff.md"), DOC);
|
||||
assert.deepEqual(store.removeHandoff("2026-10-01-0900-handoff").removed, ["2026-10-01-0900-handoff.md"]);
|
||||
const lone = written(REC, null, new Date("2026-10-17T10:01:00Z"));
|
||||
assert.deepEqual(store.removeHandoff(lone.id).removed, [lone.id + ".json"]);
|
||||
|
||||
assert.throws(() => store.removeHandoff("../evil"), /not a handoff id: \.\.\/evil/);
|
||||
assert.throws(() => store.removeHandoff("2026-10-01-0900-handoff"), /there is no handoff 2026-10-01-0900-handoff/);
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("removeHandoff refuses a linked .md and leaves everything in place", (t) => {
|
||||
fresh();
|
||||
try {
|
||||
const h = written(REC, null, new Date("2026-10-17T10:00:00Z"));
|
||||
const outside = path.join(HANDOFFS_DIR, "..", "outside.md");
|
||||
const outsideDir = path.join(HANDOFFS_DIR, "..", "outside-dir");
|
||||
fs.writeFileSync(outside, "keep me");
|
||||
fs.mkdirSync(outsideDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(outsideDir, "keep.txt"), "keep me too");
|
||||
if (!link(outside, outsideDir, h.path)) {
|
||||
t.skip("this machine can make neither a symlink nor a junction");
|
||||
return;
|
||||
}
|
||||
assert.throws(() => store.removeHandoff(h.id), /link/);
|
||||
assert.ok(fs.existsSync(path.join(HANDOFFS_DIR, h.id + ".json")));
|
||||
assert.ok(fs.lstatSync(h.path).isSymbolicLink(), "the link itself stays");
|
||||
assert.equal(fs.readFileSync(outside, "utf8"), "keep me");
|
||||
assert.equal(fs.readFileSync(path.join(outsideDir, "keep.txt"), "utf8"), "keep me too");
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("staleHandoffs lists only month-old handoffs and removeHandoffs takes both files", async () => {
|
||||
fresh();
|
||||
try {
|
||||
const old = written(REC, DOC, new Date("2026-09-01T10:00:00Z"));
|
||||
const recent = written(REC, DOC, new Date("2026-10-16T10:00:00Z"));
|
||||
const oldMdOnly = "2026-08-01-0900-handoff";
|
||||
fs.writeFileSync(path.join(HANDOFFS_DIR, oldMdOnly + ".md"), DOC);
|
||||
fs.writeFileSync(path.join(HANDOFFS_DIR, "notes.txt"), "not mine");
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const age = (file, days) => {
|
||||
const t = (Date.now() - days * DAY) / 1000;
|
||||
fs.utimesSync(file, t, t);
|
||||
};
|
||||
age(path.join(HANDOFFS_DIR, old.id + ".json"), 31);
|
||||
age(old.path, 31);
|
||||
age(path.join(HANDOFFS_DIR, recent.id + ".json"), 1);
|
||||
age(path.join(HANDOFFS_DIR, oldMdOnly + ".md"), 40);
|
||||
age(path.join(HANDOFFS_DIR, "notes.txt"), 90);
|
||||
|
||||
const stale = store.staleHandoffs(Date.now(), 30 * DAY);
|
||||
assert.deepEqual(stale.sort(), [oldMdOnly, old.id].sort());
|
||||
assert.deepEqual((await store.removeHandoffs([...stale, "../evil", "notes.txt"])).sort(), [oldMdOnly, old.id].sort());
|
||||
assert.deepEqual(fs.readdirSync(HANDOFFS_DIR).sort(), [recent.id + ".json", recent.id + ".md", "notes.txt"].sort());
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------- console commands */
|
||||
|
||||
// A throwaway git checkout to run the CLI in, so repoRoots() names it.
|
||||
const REPO = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-handoff-repo-"));
|
||||
spawnSync("git", ["init", "-q", REPO], { env: ENV });
|
||||
const REPO_REAL = fs.realpathSync.native(REPO);
|
||||
|
||||
function run(args) {
|
||||
const res = spawnSync(process.execPath, [CONSOLE_CLI, ...args], { env: ENV, encoding: "utf8", cwd: REPO });
|
||||
return { status: res.status, stderr: res.stderr, json: safeJson(res.stdout) };
|
||||
}
|
||||
|
||||
test("handoff new claims a handoff for this checkout and prints where to write it", () => {
|
||||
fresh();
|
||||
try {
|
||||
const res = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--spec", "specs/lunch-vote", "--title", "Lunch vote", "--from-stop"]);
|
||||
assert.equal(res.status, 0, res.stderr);
|
||||
assert.equal(res.json.ok, true);
|
||||
assert.ok(store.isHandoffId(res.json.id));
|
||||
assert.equal(path.dirname(res.json.path), HANDOFFS_DIR);
|
||||
assert.ok(res.json.path.endsWith(".md"));
|
||||
assert.equal(fs.existsSync(res.json.path), false);
|
||||
const meta = JSON.parse(fs.readFileSync(path.join(HANDOFFS_DIR, res.json.id + ".json"), "utf8"));
|
||||
assert.equal(meta.worktree, REPO_REAL);
|
||||
assert.equal(meta.project, REPO_REAL);
|
||||
assert.equal(meta.spec, "specs/lunch-vote");
|
||||
assert.equal(meta.fromStop, true);
|
||||
assert.deepEqual(res.json.meta, meta);
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("handoff new refuses bad usage with 2 and a bad value with 3", () => {
|
||||
fresh();
|
||||
try {
|
||||
assert.equal(run(["handoff", "new", "--workflow", "quick-task"]).status, 2);
|
||||
assert.equal(run(["handoff", "new", "--skill", "plan2code-quick-task"]).status, 2);
|
||||
assert.equal(run(["handoff", "list"]).status, 2);
|
||||
assert.equal(run(["handoff"]).status, 2);
|
||||
// A name newHandoff() would take (lowercase and dashes) but no workflow
|
||||
// the console knows: refused as usage before anything is written (FR-5).
|
||||
const before = fs.existsSync(HANDOFFS_DIR) ? fs.readdirSync(HANDOFFS_DIR).sort() : [];
|
||||
const unknown = run(["handoff", "new", "--workflow", "x-ray", "--skill", "plan2code-xray"]);
|
||||
assert.equal(unknown.status, 2, unknown.stderr);
|
||||
assert.match(unknown.stderr, /unknown workflow "x-ray"; one of: .*, xray, /);
|
||||
assert.deepEqual(fs.existsSync(HANDOFFS_DIR) ? fs.readdirSync(HANDOFFS_DIR).sort() : [], before, "no new file in the handoffs folder");
|
||||
const bad = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--spec", "../x"]);
|
||||
assert.equal(bad.status, 3);
|
||||
assert.equal(bad.json.ok, false);
|
||||
assert.match(bad.json.message, /spec/);
|
||||
assert.deepEqual(fs.existsSync(HANDOFFS_DIR) ? fs.readdirSync(HANDOFFS_DIR) : [], []);
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("delete-handoff removes both files and refuses a bad id or no flag", () => {
|
||||
fresh();
|
||||
try {
|
||||
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task"]).json;
|
||||
fs.writeFileSync(made.path, DOC);
|
||||
const done = run(["delete-handoff", "--handoff", made.id]);
|
||||
assert.equal(done.status, 0, done.stderr);
|
||||
assert.deepEqual(done.json, { ok: true, removed: [made.id + ".md", made.id + ".json"] });
|
||||
assert.deepEqual(fs.readdirSync(HANDOFFS_DIR), []);
|
||||
|
||||
const bad = run(["delete-handoff", "--handoff", "../evil"]);
|
||||
assert.equal(bad.status, 3);
|
||||
assert.equal(bad.json.ok, false);
|
||||
assert.match(bad.json.message, /not a handoff id/);
|
||||
assert.equal(run(["delete-handoff"]).status, 2);
|
||||
assert.equal(run(["delete-handoff", "--handoff"]).status, 2);
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
/* ------------------------------------------------- the dashboard's scan */
|
||||
|
||||
// Open a dashboard in REPO (and stop it after), returning its state and a getter for pages.
|
||||
async function withDashboard(fn) {
|
||||
const opened = run(["open", "--no-open", "--workflow", "dashboard"]);
|
||||
assert.equal(opened.status, 0, opened.stderr);
|
||||
const s = sessionUrl(opened.json.url);
|
||||
const get = (pathname) => fetch(`${s.base}${pathname}`, { headers: { cookie: s.cookie, connection: "close" } });
|
||||
try {
|
||||
return await fn({ sid: opened.json.sid, session: opened.json.session, get });
|
||||
} finally {
|
||||
run(["stop", "--session", opened.json.sid]);
|
||||
}
|
||||
}
|
||||
|
||||
const readStateOf = (session) => JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
|
||||
|
||||
test("a dashboard open scans this checkout's handoffs and the folder; other workflows do not", async () => {
|
||||
fresh();
|
||||
try {
|
||||
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"]).json;
|
||||
fs.writeFileSync(made.path, DOC);
|
||||
await withDashboard(({ session }) => {
|
||||
const scan = readStateOf(session).scan;
|
||||
assert.equal(scan.handoffs.length, 1);
|
||||
assert.equal(scan.handoffs[0].id, made.id);
|
||||
assert.equal(scan.handoffs[0].title, "Lunch vote");
|
||||
assert.equal(scan.handoffs[0].next, "Wire the vote button to the tally, then test it.");
|
||||
assert.equal(scan.handoffsDir, HANDOFFS_DIR);
|
||||
});
|
||||
const quick = run(["open", "--no-open", "--workflow", "quick-task"]);
|
||||
try {
|
||||
assert.equal(readStateOf(quick.json.session).scan, undefined, "no scan, so no handoffs, off the dashboard");
|
||||
} finally {
|
||||
run(["stop", "--session", quick.json.sid]);
|
||||
}
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("GET /handoff serves a scanned handoff's document and nothing else", async () => {
|
||||
fresh();
|
||||
try {
|
||||
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"]).json;
|
||||
fs.writeFileSync(made.path, DOC);
|
||||
const unscanned = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task"]).json;
|
||||
fs.writeFileSync(unscanned.path, DOC);
|
||||
await withDashboard(async ({ get }) => {
|
||||
// The two above were both on disk when the dashboard opened, so use a third made afterwards as "unscanned".
|
||||
const later = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task"]).json;
|
||||
fs.writeFileSync(later.path, DOC);
|
||||
const ok = await get(`/handoff?id=${made.id}`);
|
||||
assert.equal(ok.status, 200);
|
||||
assert.match(ok.headers.get("content-type"), /^text\/markdown/);
|
||||
assert.equal(ok.headers.get("cache-control"), "no-store");
|
||||
assert.equal(await ok.text(), DOC);
|
||||
assert.equal((await get(`/handoff?id=${later.id}`)).status, 404, "valid but not scanned");
|
||||
assert.equal((await get("/handoff?id=../x")).status, 404);
|
||||
assert.equal((await get("/handoff")).status, 404);
|
||||
});
|
||||
// A used handoff drops out of the next scan, so it is no longer served.
|
||||
store.markHandoffUsed(made.id);
|
||||
await withDashboard(async ({ get }) => {
|
||||
assert.equal((await get(`/handoff?id=${made.id}`)).status, 404, "used");
|
||||
});
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("a __pickup round trip prints the hop, marks the handoff used, and the next dashboard scan drops it", async () => {
|
||||
fresh();
|
||||
try {
|
||||
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"]).json;
|
||||
fs.writeFileSync(made.path, DOC);
|
||||
const opened = run(["open", "--no-open", "--workflow", "dashboard"]);
|
||||
const s = sessionUrl(opened.json.url);
|
||||
try {
|
||||
const res = await fetch(`${s.base}/submit`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", cookie: s.cookie, connection: "close" },
|
||||
body: JSON.stringify({ actions: [{ i: "__pickup", type: "pickup", handoff: made.id }], reply: "pick up" }),
|
||||
});
|
||||
assert.equal(res.status, 200);
|
||||
const got = run(["wait", "--session", opened.json.sid, "--seconds", "10"]);
|
||||
assert.equal(got.status, 0, got.stderr);
|
||||
assert.match(got.json.resume, /--workflow quick-task$/);
|
||||
assert.equal(got.json.handoffFile, made.path);
|
||||
assert.ok(JSON.parse(fs.readFileSync(path.join(HANDOFFS_DIR, made.id + ".json"), "utf8")).usedAt, "the .json now has usedAt");
|
||||
assert.ok(fs.existsSync(made.path), "the document stays until the sweep");
|
||||
const back = run(["open", "--resume", opened.json.sid, "--no-open", "--workflow", "dashboard"]);
|
||||
assert.equal(back.status, 0, back.stderr);
|
||||
assert.deepEqual(readStateOf(opened.json.session).scan.handoffs, [], "a used handoff is no longer listed");
|
||||
} finally {
|
||||
run(["stop", "--session", opened.json.sid]);
|
||||
}
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test("a __delete with a handoff round-trips like a spec delete: no resume, no skillFile", async () => {
|
||||
fresh();
|
||||
try {
|
||||
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task"]).json;
|
||||
fs.writeFileSync(made.path, DOC);
|
||||
const opened = run(["open", "--no-open", "--workflow", "dashboard"]);
|
||||
const s = sessionUrl(opened.json.url);
|
||||
try {
|
||||
const res = await fetch(`${s.base}/submit`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", cookie: s.cookie, connection: "close" },
|
||||
body: JSON.stringify({ actions: [{ i: "__delete", type: "delete", handoff: made.id }], reply: "delete it" }),
|
||||
});
|
||||
assert.equal(res.status, 200);
|
||||
const got = run(["wait", "--session", opened.json.sid, "--seconds", "10"]);
|
||||
assert.equal(got.status, 0, got.stderr);
|
||||
assert.equal(got.json.actions[0].handoff, made.id);
|
||||
assert.equal(got.json.resume, undefined);
|
||||
assert.equal(got.json.skillFile, undefined);
|
||||
assert.equal(got.json.handoffFile, undefined);
|
||||
} finally {
|
||||
run(["stop", "--session", opened.json.sid]);
|
||||
}
|
||||
} finally {
|
||||
fresh();
|
||||
}
|
||||
});
|
||||
|
||||
test.after(() => fs.rmSync(REPO, { recursive: true, force: true }));
|
||||
@@ -7,7 +7,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { parseArgs } from "../src/web-console/lib.mjs";
|
||||
import { parseArgs } from "../src/web-console/files.mjs";
|
||||
import { BASE, cli, consoleSession, cookieFor, ENV, HOME, payload, ROOT } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs");
|
||||
@@ -182,3 +182,47 @@ test("a fresh open whose --file is refused leaves no session folder behind", ()
|
||||
const after = fs.readdirSync(sessionsDir).filter((n) => !before.has(n));
|
||||
assert.deepEqual(after, [], "no orphan session folders");
|
||||
});
|
||||
|
||||
// Show me it working: an image block may only point at a picture the agent
|
||||
// saved directly inside the session's shots/ folder, and only a real one.
|
||||
test("an image block outside the session's shots folder, or not an image, is refused", () => {
|
||||
const s = consoleSession(["--file", payload("shots-safety.json", BASE)]);
|
||||
try {
|
||||
const shots = path.join(s.session, "shots");
|
||||
fs.mkdirSync(shots, { recursive: true });
|
||||
const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(32)]);
|
||||
const outside = path.join(HOME, "outside-shot.png");
|
||||
fs.writeFileSync(outside, png);
|
||||
fs.writeFileSync(path.join(s.session, "beside.png"), png);
|
||||
fs.writeFileSync(path.join(shots, "renamed.png"), "just some text, not a picture\n");
|
||||
fs.writeFileSync(path.join(shots, "huge.png"), Buffer.concat([png, Buffer.alloc(6 * 1024 * 1024)]));
|
||||
const cases = [
|
||||
["../../outside-shot.png", /outside the session's shots\/ folder/],
|
||||
[outside, /outside the session's shots\/ folder/],
|
||||
["beside.png", /outside the session's shots\/ folder/],
|
||||
["shots/missing.png", /does not exist/],
|
||||
["shots/renamed.png", /not a PNG image/],
|
||||
["shots/huge.png", /larger than 5 MB/],
|
||||
];
|
||||
let linked = false;
|
||||
try {
|
||||
fs.symlinkSync(outside, path.join(shots, "link.png"), "file");
|
||||
linked = true;
|
||||
} catch {
|
||||
// Windows without the symlink privilege: the realpath check is still covered by the cases above.
|
||||
}
|
||||
if (linked) cases.push(["shots/link.png", /outside the session's shots\/ folder/]);
|
||||
for (const [image, why] of cases) {
|
||||
const patch = { docs: [{ id: "shown", title: "Shown", blocks: [{ id: "b1", image, alt: "The page" }] }] };
|
||||
const res = cli(["post", "--session", s.sid, "--file", payload("shots-bad.json", patch)], { expectFail: true });
|
||||
assert.equal(res.status, 3, image);
|
||||
assert.match(res.stderr, why, image);
|
||||
}
|
||||
const both = { docs: [{ id: "shown", title: "Shown", blocks: [{ id: "b1", image: "shots/renamed.png", md: "x" }] }] };
|
||||
const res = cli(["post", "--session", s.sid, "--file", payload("shots-both.json", both)], { expectFail: true });
|
||||
assert.equal(res.status, 3);
|
||||
assert.match(res.stderr, /cannot also carry "md" or "file"/);
|
||||
} finally {
|
||||
cli(["stop", "--session", s.sid]);
|
||||
}
|
||||
});
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
noteAwaiting,
|
||||
suggestionFrom,
|
||||
} from "../src/web-console/public/answers.js";
|
||||
import { WORKFLOWS } from "../src/web-console/public/skills.js";
|
||||
import {
|
||||
HOME,
|
||||
MODELS_DIR,
|
||||
@@ -214,6 +215,38 @@ test("open --resume restates workflow, title and spec on the live session", () =
|
||||
fs.writeFileSync(stateFile, snapshot);
|
||||
});
|
||||
|
||||
// A workflow name the console does not know (x-ray for xray) is refused as bad
|
||||
// usage before anything is made: no session folder for a fresh open, and no
|
||||
// write over the resumed session's good name (FR-5).
|
||||
test("open refuses an unknown --workflow and makes no session folder", () => {
|
||||
const sessionsDir = path.join(HOME, "sessions");
|
||||
const before = fs.readdirSync(sessionsDir).sort();
|
||||
const res = cli(["open", "--no-open", "--workflow", "x-ray"], { expectFail: true });
|
||||
assert.equal(res.status, 2, res.stderr);
|
||||
assert.match(res.stderr, /unknown workflow "x-ray"/);
|
||||
for (const name of WORKFLOWS) assert.ok(res.stderr.includes(name), `stderr lists ${name}`);
|
||||
assert.deepEqual(fs.readdirSync(sessionsDir).sort(), before, "no session folder was created");
|
||||
});
|
||||
|
||||
test("open --resume refuses an unknown --workflow and leaves the state alone", () => {
|
||||
const stateFile = path.join(session, "state.json");
|
||||
const bytes = fs.readFileSync(stateFile);
|
||||
const res = cli(["open", "--resume", sid, "--no-open", "--workflow", "x-ray"], { expectFail: true });
|
||||
assert.equal(res.status, 2, res.stderr);
|
||||
assert.match(res.stderr, /unknown workflow "x-ray"/);
|
||||
assert.ok(fs.readFileSync(stateFile).equals(bytes), "state.json is byte for byte the same");
|
||||
});
|
||||
|
||||
test("open with no --workflow still opens a Pathfinder session", () => {
|
||||
const res = cli(["open", "--no-open"]);
|
||||
try {
|
||||
assert.equal(res.json.ok, true);
|
||||
assert.equal(readState(res.json.session).workflow, "pathfinder");
|
||||
} finally {
|
||||
cli(["stop", "--session", res.json.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
// Plan -> Back to the dashboard -> Document used to show Plan's questions,
|
||||
// sections and doc tabs under Document's name: the resume only renamed the
|
||||
// workflow. A switch through the dashboard is a fresh start, so it is blank.
|
||||
@@ -783,6 +816,19 @@ test("a finish is refused while its command still has a placeholder", () => {
|
||||
assert.match(res.stderr, /placeholder/);
|
||||
});
|
||||
|
||||
// The Subagents tab would otherwise spin on a helper long after the session ended.
|
||||
test("a finish is refused while a reported helper still shows as running", () => {
|
||||
const helper = (state, result) => ({ id: "h1", title: "Check the tests", ask: "Run them.", state, ...(result ? { result } : {}) });
|
||||
const running = cli(["post", "--session", sid, "--file", payload("fin-h-run.json", { helpers: [helper("running")], finish: { headline: "Done", command: "/x" } })], {
|
||||
expectFail: true,
|
||||
});
|
||||
assert.equal(running.status, 3);
|
||||
assert.match(running.stderr, /still shows as running/);
|
||||
assert.match(running.stderr, /"h1"/);
|
||||
const settled = cli(["post", "--session", sid, "--file", payload("fin-h-done.json", { helpers: [helper("done", "All pass.")], finish: { headline: "Done", command: "/x" } })]);
|
||||
assert.equal(settled.status, 0);
|
||||
});
|
||||
|
||||
test("a finish faces the same jargon and completion-marker scan as everything else", () => {
|
||||
const jargon = cli(
|
||||
["post", "--session", sid, "--file", payload("fin-j.json", { finish: { headline: "The grilling is over", command: "/x" } })],
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
sortAttachments,
|
||||
cardAvailability,
|
||||
cardPresentation,
|
||||
defaultSpec,
|
||||
CATALOG_GROUPS,
|
||||
CONTINUE_IN_CONSOLE,
|
||||
CONSOLE_WORKFLOWS,
|
||||
@@ -46,6 +47,13 @@ import {
|
||||
handoffShape,
|
||||
handoffText,
|
||||
launchReply,
|
||||
launchTarget,
|
||||
deleteAction,
|
||||
deleteReply,
|
||||
chipDetail,
|
||||
deleteSummary,
|
||||
FIXED_REASON,
|
||||
isDeletableSpecDir,
|
||||
MAX_NOTE_IMAGES,
|
||||
noteAction,
|
||||
noteReplyLines,
|
||||
@@ -55,12 +63,24 @@ import {
|
||||
REVIEW_REPLY,
|
||||
afterFinishButton,
|
||||
commitOffer,
|
||||
changelogOffer,
|
||||
continueOffer,
|
||||
continueReply,
|
||||
pendingNote,
|
||||
reviewOffer,
|
||||
SKILL_CATALOG,
|
||||
launchVariant,
|
||||
SPEC_STATE_LABELS,
|
||||
STALE_MS,
|
||||
STOP_REPLY,
|
||||
STOP_HANDOFF_REPLY,
|
||||
stopAction,
|
||||
pickupAction,
|
||||
pickupReply,
|
||||
deleteHandoffAction,
|
||||
deleteHandoffReply,
|
||||
handoffCopyText,
|
||||
handoffAge,
|
||||
verdictLabel,
|
||||
verdictText,
|
||||
lastOpenCard,
|
||||
@@ -102,6 +122,8 @@ import {
|
||||
runPoints,
|
||||
tooltipFor,
|
||||
WEIGHTS,
|
||||
LAUNCH_LABELS,
|
||||
RUN_LABELS,
|
||||
} from "../src/web-console/public/meter.js";
|
||||
import {
|
||||
blockFor,
|
||||
@@ -131,29 +153,34 @@ import {
|
||||
import {
|
||||
appendLedger,
|
||||
attachmentName,
|
||||
chatReplyLines,
|
||||
checkDocument,
|
||||
initialWorkspace,
|
||||
insideGitRepo,
|
||||
pendingFiles,
|
||||
latestOpenCaps,
|
||||
pendingWorkspaceChanges,
|
||||
PROTECTED_CONSOLE_FILES,
|
||||
readLedger,
|
||||
repoRoots,
|
||||
} from "../src/web-console/sessions.mjs";
|
||||
import { scanProject, removeSpec, SPEC_STATES } from "../src/web-console/scan.mjs";
|
||||
import { validate } from "../src/web-console/patches.mjs";
|
||||
import { startsClean } from "../src/web-console/public/hops.js";
|
||||
import { chatReplyLines } from "../src/web-console/inbox.mjs";
|
||||
import {
|
||||
initialWorkspace,
|
||||
pendingWorkspaceChanges,
|
||||
readWorkspaceCursor,
|
||||
WORKSPACE_FILE,
|
||||
writeWorkspaceCursor,
|
||||
} from "../src/web-console/workspace.mjs";
|
||||
import {
|
||||
latestOpenCaps,
|
||||
readSubagentCursor,
|
||||
readSubagentSetting,
|
||||
readWorkspaceCursor,
|
||||
resetSubagentCursor,
|
||||
writeSubagentCursor,
|
||||
writeSubagentSetting,
|
||||
repoRoots,
|
||||
scanProject,
|
||||
SPEC_STATES,
|
||||
validate,
|
||||
WORKSPACE_FILE,
|
||||
writeWorkspaceCursor,
|
||||
} from "../src/web-console/lib.mjs";
|
||||
} from "../src/web-console/settings.mjs";
|
||||
import { ROOT, HOME, cli, PDF, postPatch, ask } from "./web-console-test-helpers.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
|
||||
// Someone who worked the whole session in the browser should land back in it.
|
||||
// Every Plan2Code skill ships a console, so the sentence goes on all of
|
||||
@@ -206,34 +233,17 @@ test("every console workflow the page names ships the console", () => {
|
||||
assert.ok(fs.existsSync(path.join(dir, "console.mjs")), `${skill} must bundle the console`);
|
||||
assert.ok(fs.existsSync(path.join(dir, "building.md")), `${skill} must bundle building.md`);
|
||||
}
|
||||
// And the other way round: a skill that ships the console but is missing
|
||||
// from the list would hand off a bare command, and its next session would
|
||||
// ask the interface question of someone who was already in the browser.
|
||||
for (const skill of fs.readdirSync(path.join(ROOT, "skills"))) {
|
||||
if (!fs.existsSync(path.join(ROOT, "skills", skill, "references", "web-console"))) continue;
|
||||
assert.ok(CONSOLE_WORKFLOWS.includes("/" + skill), `${skill} ships the console but is not in CONSOLE_WORKFLOWS`);
|
||||
}
|
||||
});
|
||||
|
||||
// The dashboard draws its cards from the page's own catalog, so the catalog
|
||||
// is the contract: every card has to be a skill that really installs, every
|
||||
// installed skill has to be a card (a skill that is missing launches nothing),
|
||||
// and every card's workflow has to be one the console names.
|
||||
test("the dashboard catalog is exactly the set of installable skills", () => {
|
||||
// The dashboard draws its cards from the page's own catalog, so every card
|
||||
// has to be filled in and launch into a real SKILL.md. Which skills have a
|
||||
// card is held against install.js in test-web-console-skills.mjs.
|
||||
test("every dashboard card is filled in and launches a real skill", () => {
|
||||
const skillsDir = path.join(ROOT, "skills");
|
||||
const installed = fs.readdirSync(skillsDir).filter((d) => fs.statSync(path.join(skillsDir, d)).isDirectory());
|
||||
const cataloged = SKILL_CATALOG.map((e) => e.skill);
|
||||
|
||||
// The dashboard itself is the hub, not a card.
|
||||
assert.ok(!cataloged.includes("plan2code"), "the dashboard does not launch itself");
|
||||
assert.ok(!SKILL_CATALOG.some((e) => e.skill === "plan2code"), "the dashboard does not launch itself");
|
||||
|
||||
for (const skill of installed) {
|
||||
if (skill === "plan2code") continue;
|
||||
assert.ok(cataloged.includes(skill), `${skill} installs but has no card on the dashboard`);
|
||||
}
|
||||
for (const e of SKILL_CATALOG) {
|
||||
assert.ok(installed.includes(e.skill), `${e.skill} is a card but does not install`);
|
||||
assert.ok(CONSOLE_WORKFLOWS.includes(e.command), `${e.command} must be a console workflow`);
|
||||
assert.ok(CATALOG_GROUPS.some((g) => g.id === e.group), `${e.skill}: unknown group ${e.group}`);
|
||||
for (const field of ["workflow", "chip", "title", "blurb"]) {
|
||||
assert.ok(e[field] && String(e[field]).trim(), `${e.skill}.${field} must be filled in`);
|
||||
@@ -326,6 +336,39 @@ test("the page's own resume command is built only from what the session says", (
|
||||
assert.equal(resumeCommand({ workflow: "handoff" }), "/plan2code-handoff");
|
||||
});
|
||||
|
||||
// resumeCommand() reads the entry's `resume`: one case per kind.
|
||||
test("the resume command follows the entry's resume kind, and an unknown workflow resumes as Pathfinder", () => {
|
||||
// "overview"
|
||||
assert.equal(resumeCommand({ workflow: "document", specDir: "specs/lunch-vote" }), "/plan2code-2-document specs/lunch-vote/overview.md");
|
||||
assert.equal(resumeCommand({ workflow: "document" }), "/plan2code-2-document");
|
||||
// "folder"
|
||||
assert.equal(resumeCommand({ workflow: "pathfinder", specDir: "specs/lunch-vote" }), "/plan2code-0-pathfinder specs/lunch-vote/pathfinder");
|
||||
assert.equal(resumeCommand({ workflow: "pathfinder" }), "/plan2code-0-pathfinder");
|
||||
// null: a spec is ignored
|
||||
assert.equal(resumeCommand({ workflow: "review", specDir: "specs/lunch-vote" }), "/plan2code-review");
|
||||
// An old session's workflow the console no longer knows
|
||||
assert.equal(resumeCommand({ workflow: "made-up", specDir: "specs/lunch-vote" }), "/plan2code-0-pathfinder specs/lunch-vote/pathfinder");
|
||||
assert.equal(resumeCommand({}), "/plan2code-0-pathfinder");
|
||||
});
|
||||
|
||||
test("a hop starts the page clean to or from the dashboard, into Git and between skills, but not out of Git or into Review", () => {
|
||||
assert.equal(startsClean("implement", "dashboard"), true);
|
||||
assert.equal(startsClean("dashboard", "plan"), true);
|
||||
assert.equal(startsClean("changelog", "git"), true);
|
||||
assert.equal(startsClean("finalize", "git"), true);
|
||||
// A launch from a finished screen (Continue here, Update CHANGELOG first)
|
||||
assert.equal(startsClean("plan", "document"), true);
|
||||
assert.equal(startsClean("quick-task", "changelog"), true);
|
||||
assert.equal(startsClean("finalize", "changelog"), true);
|
||||
assert.equal(startsClean("git", "changelog"), false);
|
||||
assert.equal(startsClean("git", "plan"), false);
|
||||
assert.equal(startsClean("implement", "review"), false);
|
||||
assert.equal(startsClean("git", "git"), false);
|
||||
assert.equal(startsClean("dashboard", "dashboard"), false);
|
||||
assert.equal(startsClean(undefined, "git"), false);
|
||||
assert.equal(startsClean("plan", undefined), false);
|
||||
});
|
||||
|
||||
test("the review offer is read from true or a label, and absent otherwise", () => {
|
||||
assert.equal(reviewOffer({ command: "/x" }), null);
|
||||
assert.equal(reviewOffer({ command: "/x", review: false }), null);
|
||||
@@ -573,6 +616,42 @@ test("the stop request cannot be mistaken for a brief request", () => {
|
||||
assert.doesNotMatch(STOP_REPLY, /\b(brief|recap|minutes)\b/i);
|
||||
});
|
||||
|
||||
test("handoff helpers: actions carry only the id, replies and copy text are plain, ages round at the boundaries", () => {
|
||||
const h = { id: "2026-10-17-1152-handoff", title: "Lunch vote" };
|
||||
assert.deepEqual(pickupAction(h), { i: "__pickup", type: "pickup", handoff: h.id });
|
||||
assert.deepEqual(deleteHandoffAction(h), { i: "__delete", type: "delete", handoff: h.id });
|
||||
assert.equal(pickupReply(h), 'Pick up the handoff "Lunch vote" right here in this session.');
|
||||
assert.equal(deleteHandoffReply(h), 'Delete the handoff "Lunch vote" for good, right here in this session.');
|
||||
const file = "/home/sam/.plan2code/handoffs/2026-10-17-1152-handoff.md";
|
||||
assert.equal(handoffCopyText(file), `Read the handoff at ${file} and carry on with its Next task.`);
|
||||
for (const line of [pickupReply(h), deleteHandoffReply(h), handoffCopyText(file)]) {
|
||||
assert.ok(!line.includes("—"), "no em dash");
|
||||
assert.doesNotMatch(line, /(brief|recap|minutes)/i);
|
||||
}
|
||||
const now = Date.parse("2026-10-17T12:00:00Z");
|
||||
const ago = (ms) => handoffAge(new Date(now - ms).toISOString(), now);
|
||||
assert.equal(ago(0), "just now");
|
||||
assert.equal(ago(59 * 1000), "just now");
|
||||
assert.equal(ago(60 * 1000), "1 min ago");
|
||||
assert.equal(ago(59 * 60 * 1000), "59 min ago");
|
||||
assert.equal(ago(60 * 60 * 1000), "1 h ago");
|
||||
assert.equal(ago(23 * 3600 * 1000), "23 h ago");
|
||||
assert.equal(ago(24 * 3600 * 1000), "1 day ago");
|
||||
assert.equal(ago(3 * 24 * 3600 * 1000), "3 days ago");
|
||||
assert.equal(handoffAge("not a date", now), "");
|
||||
});
|
||||
|
||||
test("the stop-with-a-handoff request is its own plain line, and stopAction sets the flag only when asked", () => {
|
||||
assert.notEqual(STOP_HANDOFF_REPLY, STOP_REPLY);
|
||||
assert.match(STOP_HANDOFF_REPLY, /handoff/i);
|
||||
assert.doesNotMatch(STOP_HANDOFF_REPLY, /\b(brief|recap|minutes)\b/i);
|
||||
assert.ok(!STOP_HANDOFF_REPLY.includes("—"), "no em dash in a line that rides to the agent");
|
||||
assert.ok(!("handoff" in stopAction({})), "a plain stop carries no handoff key");
|
||||
assert.deepEqual(stopAction({}), { i: "__stop", type: "stop" });
|
||||
assert.equal(stopAction({ handoff: true }).handoff, true);
|
||||
assert.equal(stopAction({ handoff: true }).type, "stop");
|
||||
});
|
||||
|
||||
// Nineteen highlight colors, four shades each, two themes: far too many to
|
||||
// trust to eyeballing, and a failure here is a label nobody can read.
|
||||
const hexLum = (h) => {
|
||||
@@ -634,6 +713,15 @@ test("the project scan reads each spec's pipeline stage off its files", () => {
|
||||
"PLAN-DRAFT-20260923.md": "# draft\n\n**Status:** Phase 3 Complete - Resume at Phase 4\n",
|
||||
"pathfinder/map.md": "**Status:** Cleared\n",
|
||||
});
|
||||
// The other Status forms specs.mjs accepts read the same, CRLF included.
|
||||
fakeSpec(root, "planned-bold-colon", { "PLAN-DRAFT-20260923.md": "# draft\n\n**Status**: Complete\n" });
|
||||
fakeSpec(root, "draft-mid-plan-bold-colon", {
|
||||
"PLAN-DRAFT-20260923.md": "# draft\r\n\r\n**Status**: Phase 3 Complete - Resume at Phase 4\r\n",
|
||||
});
|
||||
fakeSpec(root, "mapped-bold-colon", {
|
||||
"pathfinder/map.md": "**Status**: Cleared\n",
|
||||
"pathfinder/questions/00-a.md": "State: resolved\n",
|
||||
});
|
||||
fakeSpec(root, "documented", {
|
||||
"overview.md": "# spec\n",
|
||||
"phase-1.md": "- [ ] Task one\n- [ ] Task two\n",
|
||||
@@ -648,6 +736,19 @@ test("the project scan reads each spec's pipeline stage off its files", () => {
|
||||
"phase-1.md": "- [x] Task one\n- [x] Task two\n",
|
||||
});
|
||||
fakeSpec(root, "weird", { "DESIGN.md": "# notes\n" });
|
||||
fakeSpec(root, "diagnosed", { "DIAGNOSIS-20261016.md": "# Diagnosis: rows go missing\n\n**Status:** Diagnosed\n" });
|
||||
// Once planning starts on a diagnosed bug, the usual states win.
|
||||
fakeSpec(root, "diagnosed-then-planned", {
|
||||
"DIAGNOSIS-20261016.md": "# Diagnosis\n\n**Status:** Diagnosed\n",
|
||||
"PLAN-DRAFT-20261017.md": "# draft\n\n**Status:** Complete\n",
|
||||
});
|
||||
// Quick Task marks the write-up Fixed: a finished bug, not loose files.
|
||||
fakeSpec(root, "diagnosed-then-fixed", { "DIAGNOSIS-20261016.md": "# Diagnosis\n\n**Status:** Fixed\n" });
|
||||
// A fixed bug someone then started planning around is mid-plan again.
|
||||
fakeSpec(root, "fixed-then-conversation", {
|
||||
"DIAGNOSIS-20261016.md": "# Diagnosis\n\n**Status:** Fixed\n",
|
||||
"PLAN-CONVERSATION-20261017.md": "# conversation\n",
|
||||
});
|
||||
fs.writeFileSync(path.join(root, "AGENTS.md"), "# agents\n");
|
||||
|
||||
const scan = scanProject(root);
|
||||
@@ -658,10 +759,17 @@ test("the project scan reads each spec's pipeline stage off its files", () => {
|
||||
["mapped", "mapped"],
|
||||
["planned", "planned"],
|
||||
["draft-mid-plan", "mapped"],
|
||||
["planned-bold-colon", "planned"],
|
||||
["draft-mid-plan-bold-colon", "mapped"],
|
||||
["mapped-bold-colon", "mapped"],
|
||||
["documented", "documented"],
|
||||
["building", "building"],
|
||||
["built", "built"],
|
||||
["weird", "unrecognized"],
|
||||
["diagnosed", "diagnosed"],
|
||||
["diagnosed-then-planned", "planned"],
|
||||
["diagnosed-then-fixed", "fixed"],
|
||||
["fixed-then-conversation", "mapped"],
|
||||
]) {
|
||||
assert.ok(byName[name], `spec ${name} was scanned`);
|
||||
assert.equal(byName[name].state, state, `spec ${name}`);
|
||||
@@ -671,6 +779,12 @@ test("the project scan reads each spec's pipeline stage off its files", () => {
|
||||
assert.equal(byName.exploring.detail, "1 of 2 decisions made");
|
||||
assert.equal(byName.building.detail, "1 of 2 tasks done");
|
||||
assert.equal(byName["draft-mid-plan"].detail, "plan draft, resume at Phase 4");
|
||||
assert.equal(byName["draft-mid-plan-bold-colon"].detail, "plan draft, resume at Phase 4");
|
||||
assert.equal(byName.diagnosed.detail, "bug diagnosed, not fixed");
|
||||
assert.equal(byName["diagnosed-then-fixed"].detail, "bug fixed");
|
||||
for (const state of SPEC_STATES) assert.ok(SPEC_STATE_LABELS[state], `state ${state} has a picker label`);
|
||||
assert.equal(SPEC_STATE_LABELS.diagnosed, "Bug diagnosed");
|
||||
assert.equal(SPEC_STATE_LABELS.fixed, "Bug fixed");
|
||||
|
||||
// A pathfinder folder with no map yet is still mid-exploration; a map
|
||||
// whose status line is missing or unreadable is too.
|
||||
@@ -689,6 +803,130 @@ test("the project scan reads each spec's pipeline stage off its files", () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Deleting a spec from the dashboard: the page offers only folders it can
|
||||
// name exactly, and the agent's `delete-spec` refuses anything else on disk.
|
||||
test("isDeletableSpecDir takes exactly specs/<one name>", () => {
|
||||
for (const ok of ["specs/lunch-vote", "specs/codebase-health", "specs/a b"]) {
|
||||
assert.equal(isDeletableSpecDir(ok), true, ok);
|
||||
}
|
||||
for (const bad of [
|
||||
"specs/../x",
|
||||
"specs/..",
|
||||
"specs/.",
|
||||
"specs/.hidden",
|
||||
"specs/a/b",
|
||||
"specs/",
|
||||
"specs",
|
||||
"specs--completed/x",
|
||||
"/specs/x",
|
||||
"C:/specs/x",
|
||||
"specs\\x",
|
||||
"other/x",
|
||||
"",
|
||||
undefined,
|
||||
null,
|
||||
]) {
|
||||
assert.equal(isDeletableSpecDir(bad), false, String(bad));
|
||||
}
|
||||
});
|
||||
|
||||
test("a delete is a session action naming the folder, and its reply says it is for good", () => {
|
||||
const spec = { dir: "specs/lunch-vote", name: "lunch-vote", state: "building", detail: "1 of 2 tasks done", files: 3, touched: 1 };
|
||||
assert.deepEqual(deleteAction(spec), { i: "__delete", type: "delete", spec: "specs/lunch-vote" });
|
||||
const reply = deleteReply(spec);
|
||||
assert.match(reply, /specs\/lunch-vote\//);
|
||||
assert.match(reply, /for good/);
|
||||
assert.doesNotMatch(reply, /\b(brief|recap|minutes)\b/i);
|
||||
const sum = deleteSummary(spec);
|
||||
assert.equal(sum.folder, "specs/lunch-vote/");
|
||||
assert.equal(sum.stage, `${SPEC_STATE_LABELS.building}: 1 of 2 tasks done`);
|
||||
assert.equal(sum.files, "3 files");
|
||||
assert.equal(sum.touched, 1);
|
||||
assert.equal(deleteSummary({ ...spec, files: 1 }).files, "1 file");
|
||||
assert.equal(deleteSummary({ ...spec, files: undefined }).files, "");
|
||||
assert.equal(deleteSummary({ ...spec, detail: "" }).stage, SPEC_STATE_LABELS.building);
|
||||
});
|
||||
|
||||
test("a fixed bug says so once: on its chip, in the delete dialog and on its greyed cards", () => {
|
||||
const fixed = { dir: "specs/old-bug", name: "old-bug", state: "fixed", detail: "bug fixed", files: 1, touched: 1 };
|
||||
assert.equal(deleteSummary(fixed).stage, "Bug fixed");
|
||||
const building = { dir: "specs/lunch-vote", name: "lunch-vote", state: "building", detail: "1 of 2 tasks done" };
|
||||
assert.equal(deleteSummary(building).stage, `${SPEC_STATE_LABELS.building}: 1 of 2 tasks done`);
|
||||
assert.equal(chipDetail(fixed), "");
|
||||
assert.equal(chipDetail(building), "1 of 2 tasks done");
|
||||
assert.equal(chipDetail({ ...building, detail: undefined }), "");
|
||||
assert.match(FIXED_REASON, /Delete button/);
|
||||
assert.doesNotMatch(FIXED_REASON, /✕/);
|
||||
});
|
||||
|
||||
test("scanProject counts each spec's files", () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-scan-files-"));
|
||||
try {
|
||||
fakeSpec(root, "three", { "overview.md": "# o\n", "phase-1.md": "- [ ] **Task 1.1:** a\n", "pathfinder/map.md": "# m\n" });
|
||||
fakeSpec(root, "one", { "DESIGN.md": "# d\n" });
|
||||
const byName = Object.fromEntries(scanProject(root).specs.map((s) => [s.name, s]));
|
||||
assert.equal(byName.three.files, 3);
|
||||
assert.equal(byName.one.files, 1);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("removeSpec deletes one spec folder and refuses everything else", () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-remove-spec-"));
|
||||
const outside = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-remove-outside-"));
|
||||
try {
|
||||
fakeSpec(root, "keep", { "overview.md": "# keep\n" });
|
||||
fakeSpec(root, "gone", { "overview.md": "# gone\n", "pathfinder/map.md": "# m\n" });
|
||||
fs.mkdirSync(path.join(root, "specs--completed", "old"), { recursive: true });
|
||||
fs.writeFileSync(path.join(outside, "precious.md"), "do not touch\n");
|
||||
|
||||
assert.deepEqual(removeSpec(root, "specs/gone"), { ok: true, removed: "specs/gone" });
|
||||
assert.equal(fs.existsSync(path.join(root, "specs", "gone")), false);
|
||||
assert.equal(fs.existsSync(path.join(root, "specs", "keep", "overview.md")), true);
|
||||
|
||||
for (const bad of ["specs/../specs--completed/old", "specs--completed/old", "specs/keep/pathfinder", "specs/missing", "specs"]) {
|
||||
assert.throws(() => removeSpec(root, bad), Error, bad);
|
||||
}
|
||||
assert.equal(fs.existsSync(path.join(root, "specs--completed", "old")), true);
|
||||
|
||||
// A spec folder that is a link to somewhere else is refused, and what it
|
||||
// points at survives.
|
||||
fs.symlinkSync(outside, path.join(root, "specs", "linked"), "junction");
|
||||
assert.throws(() => removeSpec(root, "specs/linked"), /outside|link/i);
|
||||
assert.equal(fs.existsSync(path.join(outside, "precious.md")), true);
|
||||
|
||||
// A file named like a spec is not a spec folder.
|
||||
fs.writeFileSync(path.join(root, "specs", "note.md"), "x\n");
|
||||
assert.throws(() => removeSpec(root, "specs/note.md"), /folder/i);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
fs.rmSync(outside, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("delete-spec removes a spec from the worktree it runs in, and exits 3 with the reason when it refuses", () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-delete-cli-"));
|
||||
try {
|
||||
fakeSpec(root, "scratch", { "overview.md": "# s\n" });
|
||||
const done = cli(["delete-spec", "--spec", "specs/scratch"], { cwd: root });
|
||||
assert.equal(done.status, 0, done.stderr);
|
||||
assert.equal(done.json.ok, true);
|
||||
assert.equal(done.json.removed, "specs/scratch");
|
||||
assert.equal(fs.existsSync(path.join(root, "specs", "scratch")), false);
|
||||
|
||||
const refused = cli(["delete-spec", "--spec", "specs/../AGENTS.md"], { cwd: root, expectFail: true });
|
||||
assert.equal(refused.status, 3);
|
||||
assert.equal(refused.json.ok, false);
|
||||
assert.ok(refused.json.message);
|
||||
|
||||
const usage = cli(["delete-spec"], { cwd: root, expectFail: true });
|
||||
assert.equal(usage.status, 2);
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// The dashboard's Git card offers to start a repository when the folder
|
||||
// is not one. The scan answers that from the filesystem, never from a git
|
||||
// process, and a linked worktree (a .git file, not a folder) must count.
|
||||
@@ -795,6 +1033,48 @@ test("the commit offer is read from finish.commit and a pause never carries it",
|
||||
assert.equal(commitOffer(null), false);
|
||||
});
|
||||
|
||||
test("the changelog offer is read from finish.changelog and a pause never carries it", () => {
|
||||
assert.equal(changelogOffer({ headline: "Done", changelog: true }), true);
|
||||
assert.equal(changelogOffer({ headline: "Done", changelog: false }), false);
|
||||
assert.equal(changelogOffer({ headline: "Done" }), false);
|
||||
assert.equal(changelogOffer({ headline: "Paused here", changelog: true }), false);
|
||||
assert.equal(changelogOffer(null), false);
|
||||
});
|
||||
|
||||
test("Continue here is offered for a skill command, with the spec it names, and never for a pause or a non-skill", () => {
|
||||
const offer = (command, rest = {}) => continueOffer({ headline: "Done", command, ...rest });
|
||||
assert.deepEqual(offer("/plan2code-2-document"), { skill: "plan2code-2-document", workflow: "document", spec: undefined });
|
||||
assert.deepEqual(offer("/plan2code-2-document --web"), { skill: "plan2code-2-document", workflow: "document", spec: undefined });
|
||||
assert.deepEqual(offer("/plan2code-3-implement specs/lunch-vote/overview.md --web"), {
|
||||
skill: "plan2code-3-implement",
|
||||
workflow: "implement",
|
||||
spec: "specs/lunch-vote",
|
||||
});
|
||||
assert.deepEqual(offer("/plan2code-2-document specs/lunch-vote/PLAN-DRAFT-20261019.md"), {
|
||||
skill: "plan2code-2-document",
|
||||
workflow: "document",
|
||||
spec: "specs/lunch-vote",
|
||||
});
|
||||
assert.equal(offer("/plan2code-4-finalize specs--completed/old/overview.md").spec, undefined);
|
||||
assert.equal(offer("/plan2code-3-implement specs/lunch-vote/overview.md", { headline: "Paused at Phase 2" }), null);
|
||||
assert.equal(offer("/plan2code"), null);
|
||||
assert.equal(offer("/plan2code --web"), null);
|
||||
assert.equal(offer("git add -A && git commit -m x -m y"), null);
|
||||
assert.equal(offer("/not-a-plan2code-skill"), null);
|
||||
assert.equal(offer(""), null);
|
||||
assert.equal(continueOffer(null), null);
|
||||
});
|
||||
|
||||
test("the Continue here reply names the skill and its spec like a dashboard launch, in plain words", () => {
|
||||
const reply = continueReply({ skill: "plan2code-3-implement", workflow: "implement", spec: "specs/lunch-vote" });
|
||||
assert.equal(reply, "Start Implement (/plan2code-3-implement) for specs/lunch-vote, right here in this session.");
|
||||
assert.equal(
|
||||
continueReply({ skill: "plan2code-2-document", workflow: "document" }),
|
||||
"Start Document (/plan2code-2-document), right here in this session."
|
||||
);
|
||||
assert.doesNotMatch(reply, /(brief|recap|minutes)/i);
|
||||
});
|
||||
|
||||
test("one press on a finish locks every offer button, even after the agent collects it", () => {
|
||||
// Nothing pressed: live unless a send is still being picked up.
|
||||
assert.deepEqual(afterFinishButton(null, "commit", false), { asked: false, disabled: false });
|
||||
@@ -819,7 +1099,10 @@ test("a verdict's button text never renders blank", () => {
|
||||
test("the dashboard matrix lights only the cards a spec state allows", () => {
|
||||
const scan = { hasAgents: true };
|
||||
const sel = (state) => ({ dir: "specs/x", name: "x", state });
|
||||
const entry = (skill) => SKILL_CATALOG.find((e) => e.skill === skill);
|
||||
const entry = (skill) => {
|
||||
const own = SKILL_CATALOG.find((e) => e.skill === skill);
|
||||
return own || launchVariant(SKILL_CATALOG.find((e) => e.review === skill), true);
|
||||
};
|
||||
const on = (skill, sc, s) => cardAvailability(entry(skill), sc, s).on;
|
||||
|
||||
// AGENTS.md gates the setup pair, whatever the picker holds.
|
||||
@@ -864,6 +1147,49 @@ test("the dashboard matrix lights only the cards a spec state allows", () => {
|
||||
assert.equal(on("plan2code-1b-revise-plan", scan, sel("built")), false);
|
||||
assert.equal(on("plan2code-4-finalize", scan, sel("built")), true);
|
||||
|
||||
// A diagnosed bug: Quick Task (its next step) and Plan, never the build steps.
|
||||
for (const skill of ["plan2code-quick-task", "plan2code-1-plan", "plan2code-review", "plan2code-diagnose"]) {
|
||||
assert.equal(on(skill, scan, sel("diagnosed")), true, `${skill} on for a diagnosed bug`);
|
||||
}
|
||||
for (const skill of [
|
||||
"plan2code-0-pathfinder",
|
||||
"plan2code-1b-revise-plan",
|
||||
"plan2code-2-document",
|
||||
"plan2code-3-implement",
|
||||
"plan2code-3-implement-review",
|
||||
"plan2code-4-finalize",
|
||||
]) {
|
||||
assert.equal(on(skill, scan, sel("diagnosed")), false, `${skill} off for a diagnosed bug`);
|
||||
}
|
||||
assert.equal(cardAvailability(entry("plan2code-quick-task"), scan, sel("diagnosed")).next, true);
|
||||
assert.ok(!cardAvailability(entry("plan2code-1-plan"), scan, sel("diagnosed")).next);
|
||||
assert.ok(!cardAvailability(entry("plan2code-quick-task"), scan, sel("building")).next);
|
||||
|
||||
// Quick Task carries the folder only for a diagnosed bug; spec cards always do.
|
||||
assert.equal(launchTarget(entry("plan2code-quick-task"), sel("diagnosed")).dir, "specs/x");
|
||||
assert.equal(launchTarget(entry("plan2code-quick-task"), sel("building")), null);
|
||||
assert.equal(launchTarget(entry("plan2code-1-plan"), sel("diagnosed")).dir, "specs/x");
|
||||
assert.equal(launchTarget(entry("plan2code-review"), sel("diagnosed")), null);
|
||||
assert.equal(launchTarget(entry("plan2code-1-plan"), null), null);
|
||||
|
||||
// A fixed bug is finished: no pipeline card, and Quick Task starts fresh.
|
||||
for (const skill of [
|
||||
"plan2code-0-pathfinder",
|
||||
"plan2code-1-plan",
|
||||
"plan2code-1b-revise-plan",
|
||||
"plan2code-2-document",
|
||||
"plan2code-3-implement",
|
||||
"plan2code-3-implement-review",
|
||||
"plan2code-4-finalize",
|
||||
]) {
|
||||
const av = cardAvailability(entry(skill), scan, sel("fixed"));
|
||||
assert.equal(av.on, false, `${skill} off for a fixed bug`);
|
||||
assert.ok(av.reason, `${skill} says why it is off for a fixed bug`);
|
||||
}
|
||||
assert.equal(on("plan2code-quick-task", scan, sel("fixed")), true);
|
||||
assert.ok(!cardAvailability(entry("plan2code-quick-task"), scan, sel("fixed")).next);
|
||||
assert.equal(launchTarget(entry("plan2code-quick-task"), sel("fixed")), null);
|
||||
|
||||
// A greyed card always says why, and a selected spec's next step is marked.
|
||||
assert.ok(cardAvailability(entry("plan2code-3-implement"), scan, sel("exploring")).reason);
|
||||
assert.equal(cardAvailability(entry("plan2code-3-implement"), scan, sel("documented")).next, true);
|
||||
@@ -903,6 +1229,29 @@ test("dashboard card presentation follows the current picker selection", () => {
|
||||
assert.equal(planned.detail, "plan drafted");
|
||||
});
|
||||
|
||||
test("the picker never opens on a fixed bug", () => {
|
||||
const fixed = { dir: "specs/old-bug", name: "old-bug", state: "fixed", detail: "bug fixed" };
|
||||
const live = { dir: "specs/lunch-vote", name: "lunch-vote", state: "documented", detail: "2 phases, 8 tasks ready" };
|
||||
assert.equal(defaultSpec([fixed, live]), live);
|
||||
assert.equal(defaultSpec([live, fixed]), live);
|
||||
assert.equal(defaultSpec([fixed]), null);
|
||||
assert.equal(defaultSpec([]), null);
|
||||
assert.equal(defaultSpec(undefined), null);
|
||||
|
||||
// The agent's recommendation describes the default pick, not the fixed bug
|
||||
// the server listed first.
|
||||
const entry = (skill) => SKILL_CATALOG.find((e) => e.skill === skill);
|
||||
const scan = { hasAgents: true, specs: [fixed, live] };
|
||||
const menu = { recommend: "plan2code-3-implement", details: { "plan2code-3-implement": "Phase 1 of 2 is next" } };
|
||||
const shown = cardPresentation(entry("plan2code-3-implement"), scan, live, menu);
|
||||
assert.equal(shown.recommended, true);
|
||||
assert.equal(shown.detail, "Phase 1 of 2 is next");
|
||||
// Only fixed bugs on disk: the default is "start from scratch".
|
||||
const onlyFixed = { hasAgents: true, specs: [fixed] };
|
||||
const fresh = cardPresentation(entry("plan2code-0-pathfinder"), onlyFixed, null, { recommend: "plan2code-0-pathfinder" });
|
||||
assert.equal(fresh.recommended, true);
|
||||
});
|
||||
|
||||
test("the launch reply names the picked spec", () => {
|
||||
const e = SKILL_CATALOG.find((x) => x.skill === "plan2code-3-implement");
|
||||
assert.equal(
|
||||
@@ -1071,6 +1420,8 @@ const CONSOLE_WORKFLOW_LIST = [
|
||||
"review",
|
||||
"finalize",
|
||||
"handoff",
|
||||
"xray",
|
||||
"diagnose",
|
||||
];
|
||||
|
||||
test("STARTER_SETS: 3 to 4 starters a set, one without context at least, known lead roles, unique ids", () => {
|
||||
@@ -1493,7 +1844,6 @@ test("skip: the last open card goes to Send, a middle one to the next unstaged,
|
||||
test("page: the Workspace dialog, meter pill and new modules are in the page, with no inline styles or scripts", () => {
|
||||
const dir = path.join(ROOT, "src", "web-console", "public");
|
||||
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
||||
const app = fs.readFileSync(path.join(dir, "app.js"), "utf8");
|
||||
for (const id of [
|
||||
"workspace-modal",
|
||||
"workspace-title",
|
||||
@@ -1520,7 +1870,6 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi
|
||||
assert.ok(pill[0].includes('class="meter-track"') && pill[0].includes('class="meter-fill"'));
|
||||
for (const m of ["workspace.js", "meter.js", "mentions.js", "favicon.js"]) {
|
||||
assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
||||
assert.match(app, new RegExp(`^import [^;]+ from "\\./${m.replace(".", "\\.")}";`, "m"), `app.js imports ${m}`);
|
||||
}
|
||||
// The CSP refuses style attributes and inline script: the new markup has neither.
|
||||
const added = [
|
||||
@@ -1532,23 +1881,18 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi
|
||||
assert.doesNotMatch(block, /<script/i);
|
||||
assert.doesNotMatch(block, /\son[a-z]+=/i, "no inline event handlers");
|
||||
}
|
||||
assert.doesNotMatch(app, /setAttribute\(\s*["']style["']/, "no style attributes set from script");
|
||||
});
|
||||
|
||||
test("page: the footer label opens the workspace instead of copying", () => {
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
assert.ok(app.includes('$("footer-where").addEventListener("click", openWorkspace)'));
|
||||
assert.doesNotMatch(app, /\$\("footer-where"\)\.addEventListener\("blur"/, "the copied-state blur handler is gone");
|
||||
assert.ok(app.includes('"Open workspace: " + label'));
|
||||
assert.ok(app.includes("footerLabel(") && app.includes("FOOTER_TIERS"));
|
||||
// The dashboard keeps the footer for the workspace label, minus the summary and Send.
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
assert.ok(app.includes('foot.classList.toggle("is-dash", Boolean(isDashboard() && !finish()))'));
|
||||
assert.doesNotMatch(app, /foot\.hidden = Boolean\(isDashboard\(\)/, "the dashboard no longer hides the whole footer");
|
||||
const css = joinedCss();
|
||||
assert.match(css, /\.footer\.is-dash \.footer-summary,\s*\.footer\.is-dash \.footer-actions \{ display: none; \}/);
|
||||
assert.match(css, /\.footer\.is-dash \.footer-where:not\(\[hidden\]\) \{ display: block;/, "narrow screens keep the label on the dashboard");
|
||||
// Every typing place offers @name suggestions.
|
||||
assert.equal((app.match(/attachMentions\((ta|input)\);/g) || []).length, 4, "Ask, card note, notes panel, text answer");
|
||||
// Every typing place offers @name suggestions: the Ask pane and the notes panel
|
||||
// (screens/ask.js) and the card note and text answer (screens/cards.js).
|
||||
const read = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", f), "utf8");
|
||||
const count = (text) => (text.match(/attachMentions\((ta|input)\);/g) || []).length;
|
||||
assert.equal(count(read("ask.js")) + count(read("cards.js")), 4, "Ask, card note, notes panel, text answer");
|
||||
});
|
||||
|
||||
// The quoted flags between -NoProfile and -EncodedCommand, whichever quote style.
|
||||
@@ -1806,7 +2150,7 @@ test("subagents: the store round-trips per project and workflow under the consol
|
||||
try {
|
||||
const project = path.join(home, "My Repo");
|
||||
const script = `
|
||||
const lib = await import(${JSON.stringify(new URL("../src/web-console/lib.mjs", import.meta.url).href)});
|
||||
const lib = await import(${JSON.stringify(new URL("../src/web-console/settings.mjs", import.meta.url).href)});
|
||||
const project = ${JSON.stringify(project)};
|
||||
lib.saveSubagentStoreEntry(project, "implement", { on: true, instruction: "Mine", max: 5 });
|
||||
const flipped = project.replace(/My Repo$/, "MY REPO");
|
||||
@@ -1883,3 +2227,30 @@ test("initialWorkspace names the original folder after itself and marks it origi
|
||||
assert.deepEqual(ws.folders[0], { id: "f0", path: path.join("C:", "git", "My Repo"), name: "my-repo", description: "", original: true });
|
||||
assert.deepEqual([ws.missing, ws.changes, ws.remote], [[], [], ""]);
|
||||
});
|
||||
|
||||
// The meter's tables are built from skills.js plus the events that are not a
|
||||
// skill's own. Held to their values when they were written by hand.
|
||||
test("meter: the weights and labels built from the skill list are the ones written by hand before", () => {
|
||||
assert.deepEqual({ ...WEIGHTS }, {
|
||||
"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,
|
||||
});
|
||||
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",
|
||||
});
|
||||
assert.deepEqual({ ...RUN_LABELS }, {
|
||||
"pathfinder-chart": "Pathfinder map written", "pathfinder-question": "Pathfinder question settled",
|
||||
"pathfinder-research": "Pathfinder research done", plan: "Plan drafted", "revise-plan": "Plan revised",
|
||||
document: "Spec documented", "implement-phase": "Implement phase built",
|
||||
"implement-review-phase": "Implement + Review phase built", review: "Code review run",
|
||||
"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",
|
||||
});
|
||||
for (const t of [WEIGHTS, LAUNCH_LABELS, RUN_LABELS]) assert.ok(Object.isFrozen(t));
|
||||
});
|
||||
@@ -0,0 +1,213 @@
|
||||
// Page tests for the Ask tab: a Quick question and the agent's reply, the
|
||||
// starters, a retry after a failed send, a new conversation, a picture attached
|
||||
// to a note, and the Subagents tab. Run with:
|
||||
// node --test scripts/test-web-console-page-ask.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, itemCard, textOf } from "./page-test-helpers.mjs";
|
||||
import { reportedHelper } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A plan session on the person's turn: one text question, the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// A real 1x1 PNG. The page decodes and re-encodes every picture before it
|
||||
// uploads, so the fake JPEG the server tests use would be refused here.
|
||||
const PNG = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
|
||||
"base64"
|
||||
);
|
||||
|
||||
// The one send `wait` hands the agent; fails the test when nothing arrived.
|
||||
function collect(s) {
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
// The questions in a send's chat entries (the first send also carries the
|
||||
// conversation's start, which is not a question).
|
||||
const messages = (got) => got.chat.filter((e) => e.kind === "message");
|
||||
|
||||
// Opens the Ask tab and returns its question box.
|
||||
async function openAsk(s) {
|
||||
await s.page.locator("nav").getByRole("button", { name: "Ask", exact: true }).click();
|
||||
const box = s.page.locator("#ask-input");
|
||||
await box.waitFor();
|
||||
return box;
|
||||
}
|
||||
|
||||
// Types a question and presses Send in the Ask pane.
|
||||
async function askQuestion(s, text) {
|
||||
const box = s.page.locator("#ask-input");
|
||||
await box.fill(text);
|
||||
await s.page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true }).click();
|
||||
}
|
||||
|
||||
// What a person sees break: a question typed in Ask that never reaches the
|
||||
// agent, or an answer that never shows.
|
||||
test("a Quick question typed in Ask reaches the agent under chat, and the agent's reply shows in the pane", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAsk(s);
|
||||
await askQuestion(s, "Where does the export live?");
|
||||
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "chat");
|
||||
const [asked, ...more] = messages(got);
|
||||
assert.equal(more.length, 0, "one question, one message");
|
||||
assert.equal(asked.text, "Where does the export live?");
|
||||
assert.match(got.reply, /^Quick question: Where does the export live\?$/m);
|
||||
// The question is in the pane, and the box is empty for the next one.
|
||||
await s.page.locator(".ask-row.person").getByText("Where does the export live?").waitFor();
|
||||
assert.equal(await s.page.locator("#ask-input").inputValue(), "");
|
||||
|
||||
s.post({ chat: { replies: [{ id: "r1", re: asked.seq, conversation: 1, md: "It lives in `exports/`." }] } });
|
||||
const reply = s.page.locator(".ask-row.agent");
|
||||
await reply.getByText("It lives in").waitFor();
|
||||
assert.match(await textOf(reply), /exports\//);
|
||||
assert.match(await textOf(s.page.locator(".ask-counter")), /1/);
|
||||
});
|
||||
|
||||
// What a person sees break: a prompt the agent wrote for a new conversation with no
|
||||
// Copy button, or one that tells them to "paste it into the Ask tab" as though it
|
||||
// were a terminal command.
|
||||
test("an Ask reply with a fenced prompt shows Copy and no run hint, while a command block still gets the hint", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAsk(s);
|
||||
await askQuestion(s, "Give me a prompt for adding the export to the report");
|
||||
const [asked] = messages(collect(s));
|
||||
|
||||
const prompt = "Add the export to the report. Read src/export.js and src/report.js first. Do not touch the importer.";
|
||||
const fence = "```";
|
||||
const md = ["That is a separate job. Paste this into a new Quick Task:", "", fence, prompt, fence, "", "Or run this:", "", fence, "npm test", fence].join("\n");
|
||||
s.post({ chat: { replies: [{ id: "r1", re: asked.seq, conversation: 1, md }] } });
|
||||
const reply = s.page.locator(".ask-row.agent");
|
||||
await reply.getByText("That is a separate job").waitFor();
|
||||
|
||||
const blocks = reply.locator("pre");
|
||||
assert.equal(await blocks.count(), 2);
|
||||
const first = blocks.nth(0).locator("xpath=..");
|
||||
assert.equal(await first.getByRole("button", { name: "Copy" }).count(), 1, "the prompt block has a Copy button");
|
||||
assert.equal(await first.locator(".md-run-hint").count(), 0, "a prompt block gets no run hint");
|
||||
const second = blocks.nth(1).locator("xpath=..");
|
||||
assert.equal(await second.locator(".md-run-hint").count(), 1, "a command block still gets the hint");
|
||||
});
|
||||
|
||||
// What a person sees break: starters that send for them, or that are missing
|
||||
// from an empty conversation.
|
||||
test("an empty Ask offers starters, a click only fills the box, and nothing is sent until Send", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const box = await openAsk(s);
|
||||
const starters = s.page.locator(".ask-starters .ask-starter");
|
||||
await starters.first().waitFor();
|
||||
assert.ok((await starters.count()) >= 1, "no starter questions are offered");
|
||||
const first = (await textOf(starters.first())).trim();
|
||||
await starters.first().click();
|
||||
assert.equal(await box.inputValue(), first, "the starter fills the box");
|
||||
assert.equal(s.wait(1).code === 0, false, "a starter click sent something");
|
||||
|
||||
await s.page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true }).click();
|
||||
assert.deepEqual(messages(collect(s)).map((e) => e.text), [first]);
|
||||
// With a question in the list the starters are gone.
|
||||
await s.page.locator(".ask-starters").waitFor({ state: "detached" });
|
||||
});
|
||||
|
||||
// What a person sees break: a question lost when the network hiccups, or
|
||||
// sent twice when they press Retry.
|
||||
test("a failed send shows Not sent with Retry, and Retry delivers the question once", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAsk(s);
|
||||
// The page's own request fails as a dropped connection would.
|
||||
await s.page.route("**/chat", (route) => route.abort());
|
||||
await askQuestion(s, "Is the header row kept?");
|
||||
const row = s.page.locator(".ask-row.person.pending");
|
||||
await row.getByText("Not sent").waitFor();
|
||||
assert.equal(s.wait(1).code === 0, false, "a failed send reached the agent");
|
||||
|
||||
await s.page.unroute("**/chat");
|
||||
await row.getByRole("button", { name: "Retry" }).click();
|
||||
const got = collect(s);
|
||||
assert.deepEqual(messages(got).map((e) => e.text), ["Is the header row kept?"]);
|
||||
await s.page.locator(".ask-row.person:not(.pending)").getByText("Is the header row kept?").waitFor();
|
||||
assert.equal(s.wait(1).code === 0, false, "the question was sent twice");
|
||||
});
|
||||
|
||||
// What a person sees break: New conversation that leaves the old rows, or
|
||||
// that does not start the next question in a fresh conversation.
|
||||
test("New conversation clears the pane back to the starters, and the next question belongs to the new conversation", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAsk(s);
|
||||
await askQuestion(s, "First question");
|
||||
const first = collect(s);
|
||||
assert.equal(messages(first)[0].conversation, 1);
|
||||
await s.page.locator(".ask-row.person:not(.pending)").waitFor();
|
||||
|
||||
await s.page.getByRole("button", { name: "New conversation" }).click();
|
||||
await s.page.locator(".ask-row").waitFor({ state: "detached" });
|
||||
await s.page.locator(".ask-starters").waitFor();
|
||||
|
||||
await askQuestion(s, "Second question");
|
||||
const second = collect(s);
|
||||
assert.deepEqual(messages(second).map((e) => e.text), ["Second question"]);
|
||||
assert.equal(messages(second)[0].conversation, 2);
|
||||
});
|
||||
|
||||
// What a person sees break: a picture that shows in the tray but never goes
|
||||
// to the agent, or goes without the note it belongs to.
|
||||
test("a picture attached to a note uploads, and the send carries it in the note's images entry", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await itemCard(s.page, "q1").waitFor();
|
||||
const aside = s.page.locator("#aside");
|
||||
await aside.locator('input[type="file"]').setInputFiles({ name: "shot.png", mimeType: "image/png", buffer: PNG });
|
||||
await aside.locator(".attach-thumb.is-ready").waitFor();
|
||||
await aside.locator("#thread-q1").fill("See the screenshot.");
|
||||
|
||||
await s.page.click("#btn-send");
|
||||
const got = collect(s);
|
||||
const note = got.actions.find((a) => a.i === "q1" && a.type === "comment");
|
||||
assert.ok(note, `a note action for q1: ${JSON.stringify(got.actions)}`);
|
||||
assert.equal(note.text, "See the screenshot.");
|
||||
assert.equal(note.images.length, 1);
|
||||
assert.equal(note.images[0].name, "shot.png");
|
||||
assert.ok(note.images[0].path, "the image names the file the console saved");
|
||||
});
|
||||
|
||||
// What a person sees break: the Subagents tab missing once helpers are
|
||||
// reported, or showing the wrong state.
|
||||
test("posting helpers adds a Subagents tab that lists each with its state and result", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: { agent: { status: "working", activity: "Task 1 of 2" }, items: PLAN_QUESTION.items },
|
||||
});
|
||||
const tab = s.page.locator("nav").getByRole("button", { name: /^Subagents/ });
|
||||
assert.equal(await tab.count(), 0, "no tab before any helper is reported");
|
||||
|
||||
s.post({
|
||||
helpers: [
|
||||
reportedHelper("h1", { title: "Read the store helpers", state: "running" }),
|
||||
reportedHelper("h2", { title: "Check the tests", state: "done", result: "All 9 pass." }),
|
||||
],
|
||||
});
|
||||
await tab.waitFor();
|
||||
await tab.click();
|
||||
const card = s.page.locator("#main .sa-card");
|
||||
await card.getByRole("heading", { name: "Subagents" }).waitFor();
|
||||
const rows = card.locator(".sa-row");
|
||||
assert.equal(await rows.count(), 2);
|
||||
const running = rows.filter({ hasText: "Read the store helpers" });
|
||||
const done = rows.filter({ hasText: "Check the tests" });
|
||||
assert.match(await textOf(running.locator(".sa-pill")), /running/i);
|
||||
assert.match(await textOf(done.locator(".sa-pill")), /done/i);
|
||||
assert.match(await textOf(done), /All 9 pass\./);
|
||||
assert.match(await textOf(running), /Find the callers of applyPatch/);
|
||||
});
|
||||
@@ -0,0 +1,713 @@
|
||||
// Page tests for question cards: every kind answered on the page and sent, the
|
||||
// sign-off card, and a redraw keeping your place. Run with:
|
||||
// node --test scripts/test-web-console-page-cards.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { gitInit } from "./skill-script-helpers.mjs";
|
||||
import { pageSuite, openSession, tempProject, sendAndCollect, itemCard, scrollTopOf } from "./page-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
test("a session with nothing posted yet shows its starting screen, and stop ends its server", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
assert.match(await s.page.innerText("#main"), /Starting Plan/);
|
||||
assert.equal(await s.page.locator("#main .pose-stage").count(), 1);
|
||||
await s.stop();
|
||||
assert.equal(await s.answers(), false, "the server still answers after stop()");
|
||||
});
|
||||
|
||||
test("a text answer typed on the page reaches the agent as it was typed", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }] },
|
||||
});
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
const got = await sendAndCollect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
assert.deepEqual(
|
||||
got.actions.map(({ i, type, text }) => ({ i, type, text })),
|
||||
[{ i: "q1", type: "answer", text: "audit-export" }]
|
||||
);
|
||||
assert.match(got.reply, /audit-export/);
|
||||
});
|
||||
|
||||
// The agent's side of one question: settle what came before, post `item`
|
||||
// alone, and wait for its card.
|
||||
async function ask(s, item) {
|
||||
s.post({ settle: true, items: [item] });
|
||||
const card = itemCard(s.page, item.id);
|
||||
await card.waitFor();
|
||||
return card;
|
||||
}
|
||||
|
||||
// The answer an agent reads for item `id`, without the routing fields.
|
||||
function answerTo(got, id) {
|
||||
const action = got.actions.find((a) => a.i === id);
|
||||
assert.ok(action, `the send carries an answer to ${id}: ${JSON.stringify(got.actions)}`);
|
||||
const { i, type, kind, ...answer } = action;
|
||||
assert.equal(type, "answer");
|
||||
return answer;
|
||||
}
|
||||
|
||||
const opt = (k, text) => ({ k, text, detail: `The ${text.toLowerCase()} option.` });
|
||||
|
||||
test("every kind of question card sends the answer shape the agent reads", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
|
||||
let card = await ask(s, { id: "c1", kind: "choice", title: "Export format", body: "Which format?", options: [opt("A", "CSV"), opt("B", "JSON")] });
|
||||
await card.getByLabel("JSON").check();
|
||||
let got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "c1"), { k: "B" });
|
||||
assert.equal(got.reply, "Export format: B");
|
||||
|
||||
card = await ask(s, { id: "c2", kind: "choice", title: "Where it goes", body: "Where?", allowOther: true, options: [opt("A", "Email"), opt("B", "Slack")] });
|
||||
await card.getByRole("radio", { name: "Something else, in your own words" }).check();
|
||||
await card.locator("textarea").fill("A shared drive");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "c2"), { text: "A shared drive" });
|
||||
assert.equal(got.reply, "Where it goes: A shared drive");
|
||||
|
||||
card = await ask(s, { id: "m1", kind: "multi", title: "Columns", body: "Which?", options: [opt("1", "Date"), opt("2", "User"), opt("3", "Action")], presets: [{ label: "Date and user", ks: ["1", "2"] }] });
|
||||
await card.getByRole("button", { name: "Date and user" }).click();
|
||||
await card.getByLabel("Action").check();
|
||||
await card.locator("textarea").fill("and the IP");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "m1"), { ks: ["1", "2", "3"], text: "and the IP" });
|
||||
assert.equal(got.reply, "Columns: 1, 2, 3; and the IP");
|
||||
|
||||
card = await ask(s, { id: "t1", kind: "text", title: "What to call it", body: "A name.", pattern: "^[a-z][a-z0-9-]*$", patternHint: "Lowercase letters, digits and hyphens.", placeholder: "For example: audit-export" });
|
||||
const field = card.locator("input[type=text]");
|
||||
// The suggestion is the placeholder without its "For example:" lead-in.
|
||||
await card.getByRole("button", { name: "Autofill suggestion" }).click();
|
||||
assert.equal(await field.inputValue(), "audit-export");
|
||||
await field.fill("Audit Export");
|
||||
await card.getByText("Lowercase letters, digits and hyphens.").waitFor();
|
||||
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "a value that breaks the pattern is not sendable");
|
||||
await field.fill("audit-export");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "t1"), { text: "audit-export" });
|
||||
assert.equal(got.reply, "What to call it: audit-export");
|
||||
|
||||
card = await ask(s, { id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" });
|
||||
await card.getByRole("button", { name: "Yes" }).click();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "y1"), { yes: true });
|
||||
assert.equal(got.reply, "Keep going: yes");
|
||||
|
||||
card = await ask(s, { id: "r1", kind: "recap", title: "What we decided", body: "Is this right?", summary: "- CSV\n- Mondays" });
|
||||
await card.getByRole("button", { name: "Yes, that is right" }).click();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "r1"), { ok: true });
|
||||
assert.equal(got.reply, "What we decided: confirmed");
|
||||
|
||||
card = await ask(s, { id: "k1", kind: "checklist", title: "Set up access", body: "Only you can do these.", steps: ["Create the app", "Paste its key"] });
|
||||
await card.locator("input[type=checkbox]").first().check();
|
||||
await card.getByRole("button", { name: "All done" }).click();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "k1"), { done: [0], state: "done" });
|
||||
assert.equal(got.reply, "Set up access: all done; did steps 1");
|
||||
|
||||
card = await ask(s, { id: "n1", kind: "menu", title: "What next", body: "Pick one.", options: [opt("1", "Keep planning"), opt("2", "Stop here")] });
|
||||
await card.getByLabel("Stop here").check();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "n1"), { k: "2" });
|
||||
assert.equal(got.reply, "What next: 2");
|
||||
|
||||
const rows = [
|
||||
{ id: "a", title: "Read the data", body: "x" },
|
||||
{ id: "b", title: "Write the file", body: "y" },
|
||||
];
|
||||
card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Reorder or rename.", rows });
|
||||
await card.getByRole("button", { name: "No changes" }).click();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "l1"), { text: "no changes" });
|
||||
assert.equal(got.reply, "The steps: no changes");
|
||||
|
||||
card = await ask(s, { id: "l2", kind: "list", title: "The steps again", body: "Reorder or rename.", rows });
|
||||
await card.locator("input[type=text]").first().fill("Read the audit log");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(
|
||||
answerTo(got, "l2").rows.map((r) => [r.id, r.title]),
|
||||
[["a", "Read the audit log"], ["b", "Write the file"]]
|
||||
);
|
||||
assert.equal(got.reply, "The steps again: the list: Read the audit log, then Write the file; renamed Read the data to Read the audit log");
|
||||
|
||||
s.post({ settle: true, items: [{ id: "x1", kind: "notice", title: "Heads up", body: "The export runs **nightly**." }] });
|
||||
await s.page.getByText("The export runs").waitFor();
|
||||
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "a notice alone gives nothing to send");
|
||||
});
|
||||
|
||||
test("a sign-off card opens its document, and each verdict reaches the agent", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: {
|
||||
docs: [{ id: "report", title: "Completion report", blocks: [{ id: "b1", state: "settled", md: "## Summary\n\nPhase 3 adds the /tasks endpoints." }] }],
|
||||
},
|
||||
});
|
||||
const signoff = (id, extra = {}) => ({
|
||||
id,
|
||||
kind: "review",
|
||||
title: "Approve this phase",
|
||||
doc: "report",
|
||||
body: "Read the report, then approve it or say what to change.",
|
||||
verdicts: [
|
||||
{ id: "approve", label: "Approve this phase" },
|
||||
{ id: "changes", label: "I want changes" },
|
||||
{ id: "discard", label: "Throw it away", danger: true },
|
||||
],
|
||||
...extra,
|
||||
});
|
||||
|
||||
let card = await ask(s, signoff("so1"));
|
||||
await card.getByRole("button", { name: /Read .*Completion report.* in full/ }).click();
|
||||
await s.page.getByText("Phase 3 adds the /tasks endpoints.").waitFor();
|
||||
assert.ok(await s.page.getByText("Phase 3 adds the /tasks endpoints.").isVisible(), "the report is on screen");
|
||||
// The danger verdict is marked as such: here the class is the behaviour.
|
||||
await s.page.locator("#views").getByRole("button", { name: /^Questions/ }).click();
|
||||
card = itemCard(s.page, "so1");
|
||||
assert.match(await card.getByRole("button", { name: "Throw it away" }).getAttribute("class"), /danger/);
|
||||
assert.doesNotMatch(await card.getByRole("button", { name: "Approve this phase" }).getAttribute("class"), /danger/);
|
||||
|
||||
await card.getByRole("button", { name: "Approve this phase" }).click();
|
||||
let got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "so1"), { verdict: "approve" });
|
||||
|
||||
card = await ask(s, signoff("so2"));
|
||||
await card.getByRole("button", { name: "I want changes" }).click();
|
||||
await card.locator("textarea").fill("Keep the header row.");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "so2"), { verdict: "changes", text: "Keep the header row." });
|
||||
});
|
||||
|
||||
const longText = (n) => Array.from({ length: n }, (_, i) => `Paragraph ${i + 1}. The export runs every night and keeps a year of rows.`).join("\n\n");
|
||||
|
||||
// The agent posts something unrelated, and the page redraws: wait until the
|
||||
// new title is drawn.
|
||||
async function unrelatedPost(s, title) {
|
||||
s.post({ title });
|
||||
await s.page.waitForFunction((want) => document.getElementById("title").textContent.includes(want), title);
|
||||
}
|
||||
|
||||
test("a redraw keeps your place: the scroll and the focused field survive an agent post", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: longText(40) }],
|
||||
docs: [{ id: "map", title: "What we've agreed", blocks: [{ id: "b1", state: "settled", md: longText(80) }] }],
|
||||
},
|
||||
});
|
||||
|
||||
// Reading a question part-way down: the card scrolls itself.
|
||||
const card = itemCard(s.page, "q1");
|
||||
await card.evaluate((el) => (el.scrollTop = 400));
|
||||
assert.equal(await card.evaluate((el) => el.scrollTop), 400, "the question card scrolls");
|
||||
await unrelatedPost(s, "Audit export, take two");
|
||||
assert.equal(await itemCard(s.page, "q1").evaluate((el) => el.scrollTop), 400);
|
||||
|
||||
// Typing in its answer box: the box keeps the focus and the caret, and the
|
||||
// card stays where it was.
|
||||
const field = itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
|
||||
await field.click();
|
||||
await field.pressSequentially("audit-ex");
|
||||
await field.evaluate((el) => el.setSelectionRange(3, 3));
|
||||
const typingAt = await itemCard(s.page, "q1").evaluate((el) => el.scrollTop);
|
||||
await unrelatedPost(s, "Audit export, take three");
|
||||
const after = itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
|
||||
assert.deepEqual(await after.evaluate((el) => [el === document.activeElement, el.value, el.selectionStart]), [true, "audit-ex", 3]);
|
||||
assert.equal(await itemCard(s.page, "q1").evaluate((el) => el.scrollTop), typingAt);
|
||||
|
||||
// On a doc: the column scrolls.
|
||||
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
|
||||
await s.page.getByText("Paragraph 80.").waitFor();
|
||||
await s.page.locator("#main").evaluate((el) => (el.scrollTop = 900));
|
||||
const docBefore = await scrollTopOf(s.page, "#main");
|
||||
assert.ok(docBefore > 0, "the doc column scrolls");
|
||||
await unrelatedPost(s, "Audit export, take four");
|
||||
assert.equal(await scrollTopOf(s.page, "#main"), docBefore);
|
||||
});
|
||||
|
||||
// The progress line under the title, once the page has drawn `want`.
|
||||
async function progressSays(s, want) {
|
||||
await s.page.waitForFunction((w) => document.getElementById("progress-text").textContent === w, want, { timeout: 5000 }).catch(() => {});
|
||||
return (await s.page.innerText("#progress-text")).trim();
|
||||
}
|
||||
|
||||
// One answered question, so a question workflow has something to count.
|
||||
const answered = { id: "a1", kind: "text", title: "What to call it", body: "A name.", status: "answered", answer: { text: "audit-export" } };
|
||||
const open = { id: "o1", kind: "text", title: "Who uses it", body: "Who?" };
|
||||
|
||||
test("a build's header counts its tasks, 0 done included, and a question workflow counts its answers", async (t) => {
|
||||
for (const workflow of ["implement", "implement-review", "quick-task"]) {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow,
|
||||
payload: { headline: { stage: "Phase 3", cleared: 3, total: 9 }, items: [answered] },
|
||||
});
|
||||
assert.equal(await progressSays(s, "3 of 9 done"), "3 of 9 done", `${workflow} counts its tasks`);
|
||||
s.post({ headline: { cleared: 0 } });
|
||||
assert.equal(await progressSays(s, "0 of 9 done"), "0 of 9 done", `${workflow}: 0 done is 0 done, not the answered card`);
|
||||
// A build between counts (a review starting at total 0) shows its stage.
|
||||
s.post({ headline: { stage: "Reviewing the phase", cleared: 0, total: 0 }, items: [open] });
|
||||
assert.equal(await progressSays(s, "Reviewing the phase"), "Reviewing the phase", `${workflow} shows its stage at total 0`);
|
||||
assert.equal(await s.page.locator("#progress-bar").isHidden(), true, `${workflow}: no track for a stage`);
|
||||
await s.stop();
|
||||
}
|
||||
|
||||
// A question workflow that set a total and never moved `cleared` fills as
|
||||
// cards are answered, and at total 0 counts its cards instead of the stage.
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { headline: { stage: "Charting", cleared: 0, total: 4 }, items: [answered] },
|
||||
});
|
||||
assert.equal(await progressSays(s, "1 of 4 answered"), "1 of 4 answered");
|
||||
s.post({ headline: { total: 0 }, items: [open] });
|
||||
assert.equal(await progressSays(s, "1 of 2 answered"), "1 of 2 answered");
|
||||
});
|
||||
|
||||
test("an answer typed over several lines reaches the agent under its title, never as reply lines of its own", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }] },
|
||||
});
|
||||
await itemCard(s.page, "q1").locator("textarea").fill("audit-export\nIdea name: not a heading");
|
||||
const got = await sendAndCollect(s);
|
||||
assert.equal(answerTo(got, "q1").text, "audit-export\nIdea name: not a heading");
|
||||
assert.ok(got.reply.includes("What to call it: audit-export\n Idea name: not a heading"), `the second line is not indented under its title: ${JSON.stringify(got.reply)}`);
|
||||
});
|
||||
|
||||
test("a redraw keeps the place of the dashboard, the waiting screen and the finished screen, and a new question starts at its top", async (t) => {
|
||||
// The dashboard's menu scrolls itself.
|
||||
let s = await openSession(await suite.browser(), { t, workflow: "dashboard" });
|
||||
await s.page.setViewportSize({ width: 1280, height: 420 });
|
||||
await s.page.getByRole("button", { name: "Skip the intro" }).click();
|
||||
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
await s.page.locator("#main > .dash").evaluate((el) => (el.scrollTop = 150));
|
||||
assert.equal(await scrollTopOf(s.page, "#main > .dash"), 150, "the dashboard scrolls");
|
||||
await unrelatedPost(s, "Dashboard, take two");
|
||||
assert.equal(await scrollTopOf(s.page, "#main > .dash"), 150, "the dashboard lost its place");
|
||||
await s.stop();
|
||||
|
||||
// A build with nothing to ask yet: the waiting screen, and then its finish.
|
||||
s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: { headline: { stage: "Phase 1", cleared: 0, total: 3 }, agent: { status: "working", activity: "Task 1 of 3: the reader" } },
|
||||
});
|
||||
await s.page.setViewportSize({ width: 1280, height: 300 });
|
||||
const pane = "#main > .waiting-pane";
|
||||
await s.page.locator(pane).waitFor();
|
||||
await s.page.locator(pane).evaluate((el) => (el.scrollTop = 60));
|
||||
const waitingAt = await scrollTopOf(s.page, pane);
|
||||
assert.ok(waitingAt > 0, "the waiting screen scrolls");
|
||||
await unrelatedPost(s, "Phase 1, take two");
|
||||
assert.equal(await scrollTopOf(s.page, pane), waitingAt, "the waiting screen lost its place");
|
||||
|
||||
s.post({ finish: { headline: "Phase 1 is done", body: longText(30), command: "/plan2code-3-implement specs/audit-export/overview.md" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "Phase 1 is done" }).waitFor();
|
||||
const end = "#main > .card";
|
||||
await s.page.locator(end).evaluate((el) => (el.scrollTop = 300));
|
||||
assert.equal(await scrollTopOf(s.page, end), 300, "the finished screen scrolls");
|
||||
await unrelatedPost(s, "Phase 1, take three");
|
||||
assert.equal(await scrollTopOf(s.page, end), 300, "the finished screen lost its place");
|
||||
await s.stop();
|
||||
|
||||
// Part-way down one question, a new one arrives: it starts at its top.
|
||||
s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: longText(40) }] },
|
||||
});
|
||||
await itemCard(s.page, "q1").evaluate((el) => (el.scrollTop = 400));
|
||||
s.post({ items: [{ id: "q2", kind: "text", title: "Who uses it", body: longText(40) }] });
|
||||
await itemCard(s.page, "q2").waitFor();
|
||||
assert.equal(await itemCard(s.page, "q2").evaluate((el) => el.scrollTop), 0, "the new question opened part-way down");
|
||||
});
|
||||
|
||||
// The accent colour as the browser resolves it, and a button's outline colour,
|
||||
// so "wears the accent" is read off the screen, not off a class name.
|
||||
const accentOf = (page) =>
|
||||
page.evaluate(() => {
|
||||
const probe = document.createElement("i");
|
||||
probe.style.color = "var(--accent)";
|
||||
document.body.appendChild(probe);
|
||||
const colour = getComputedStyle(probe).color;
|
||||
probe.remove();
|
||||
return colour;
|
||||
});
|
||||
const outlineOf = (button) => button.evaluate((b) => getComputedStyle(b).borderTopColor);
|
||||
const warnOf = (page) =>
|
||||
page.evaluate(() => {
|
||||
const probe = document.createElement("i");
|
||||
probe.style.color = "var(--warn)";
|
||||
document.body.appendChild(probe);
|
||||
const colour = getComputedStyle(probe).color;
|
||||
probe.remove();
|
||||
return colour;
|
||||
});
|
||||
|
||||
// What a person sees break: the way forward on a sign-off card looks like any
|
||||
// other choice.
|
||||
test("on a sign-off card, approve and yes are outlined in the accent until picked, and the others are not", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement" });
|
||||
const accent = await accentOf(s.page);
|
||||
const review = (id, verdicts) => ({ id, kind: "review", title: "Sign off " + id, body: "Read it.", verdicts });
|
||||
|
||||
let card = await ask(s, review("so1", [{ id: "approve", label: "Approve this phase" }, { id: "changes", label: "I want changes" }]));
|
||||
const approve = card.getByRole("button", { name: "Approve this phase" });
|
||||
assert.equal(await outlineOf(approve), accent, "an unpicked approve is outlined in the accent");
|
||||
assert.notEqual(await outlineOf(card.getByRole("button", { name: "I want changes" })), accent, "the other verdict is not");
|
||||
await approve.click();
|
||||
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
|
||||
assert.equal(await approve.evaluate((b) => getComputedStyle(b).backgroundColor), accent, "picked, approve fills with the accent");
|
||||
|
||||
card = await ask(s, review("so2", [{ id: "yes", label: "Build it" }, { id: "no", label: "Not yet" }]));
|
||||
assert.equal(await outlineOf(card.getByRole("button", { name: "Build it" })), accent, "an unpicked yes is outlined too");
|
||||
assert.notEqual(await outlineOf(card.getByRole("button", { name: "Not yet" })), accent);
|
||||
});
|
||||
|
||||
// What a person sees break: Skip this one turns into a full-size button, or
|
||||
// the quick answer under a note box does.
|
||||
test("Skip this one and a comment box's quick answer are the same small accent button", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const rows = [{ id: "a", title: "Read the data", body: "x" }];
|
||||
const card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Rename.", required: false, rows });
|
||||
const skip = card.getByRole("button", { name: "Skip this one" });
|
||||
const quick = card.getByRole("button", { name: "No changes" });
|
||||
const look = (b) => b.evaluate((x) => { const c = getComputedStyle(x); return [c.fontSize, c.paddingTop, c.paddingLeft, c.color]; });
|
||||
assert.deepEqual(await look(skip), await look(quick), "the two chips look alike");
|
||||
const [size, , , colour] = await look(skip);
|
||||
assert.equal(size, "12px", "small, not a full-size button");
|
||||
assert.equal(colour, await accentOf(s.page), "in the accent");
|
||||
});
|
||||
|
||||
// What a person sees break: a safe yes looks like any button, or a risky yes
|
||||
// stops warning.
|
||||
test("a confirm's safe yes and a recap's yes are outlined in the accent, and a dangerous yes stays red", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const accent = await accentOf(s.page);
|
||||
const warn = await warnOf(s.page);
|
||||
|
||||
let card = await ask(s, { id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" });
|
||||
const yes = card.getByRole("button", { name: "Yes" });
|
||||
assert.equal(await outlineOf(yes), accent, "a safe, unpicked yes wears the accent");
|
||||
assert.notEqual(await outlineOf(card.getByRole("button", { name: "No" })), accent, "the no does not");
|
||||
await yes.click();
|
||||
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
|
||||
assert.equal(await yes.evaluate((b) => getComputedStyle(b).backgroundColor), accent, "picked, it fills");
|
||||
|
||||
card = await ask(s, { id: "y2", kind: "confirm", title: "Delete it", body: "Really?", danger: true });
|
||||
assert.equal(await outlineOf(card.getByRole("button", { name: "Yes" })), warn, "a dangerous yes stays red");
|
||||
|
||||
card = await ask(s, { id: "r1", kind: "recap", title: "What we decided", body: "Right?", summary: "- CSV" });
|
||||
assert.equal(await outlineOf(card.getByRole("button", { name: "Yes, that is right" })), accent, "the recap's yes wears the accent");
|
||||
});
|
||||
|
||||
// What a person sees break: a long question runs off the window with nothing
|
||||
// to say there is more, or the fade stays on at the very end.
|
||||
test("a card cut by the window fades at its bottom edge while there is more below", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
await s.page.setViewportSize({ width: 1280, height: 420 });
|
||||
const card = await ask(s, { id: "q1", kind: "text", title: "What to call it", body: longText(40) });
|
||||
const fades = () => card.evaluate((el) => { const c = getComputedStyle(el); return (c.maskImage || c.webkitMaskImage || "none") !== "none"; });
|
||||
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); return c && c.scrollHeight > c.clientHeight + 4; });
|
||||
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); const m = getComputedStyle(c); return (m.maskImage || m.webkitMaskImage || "none") !== "none"; });
|
||||
assert.equal(await fades(), true, "a cut card fades at the bottom");
|
||||
await card.evaluate((el) => (el.scrollTop = el.scrollHeight));
|
||||
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); const m = getComputedStyle(c); return (m.maskImage || m.webkitMaskImage || "none") === "none"; });
|
||||
assert.equal(await fades(), false, "at the end, the fade is gone");
|
||||
});
|
||||
|
||||
// What a person sees break: a rename typed in a list is lost when the agent
|
||||
// posts or Ctrl+Enter sends before the field was left.
|
||||
test("a list rename is staged as it is typed, so Ctrl+Enter or an agent post never drops it", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const rows = [{ id: "a", title: "Read the data", body: "x" }, { id: "b", title: "Write the file", body: "y" }];
|
||||
const card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Rename.", rows });
|
||||
const first = card.locator("input.row-title").first();
|
||||
await first.click();
|
||||
await first.fill("Read the audit log");
|
||||
// The field is still focused: it has not changed or blurred.
|
||||
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
|
||||
await unrelatedPost(s, "Steps, take two");
|
||||
assert.equal(await itemCard(s.page, "l1").locator("input.row-title").first().inputValue(), "Read the audit log", "the agent post kept the typed name");
|
||||
await itemCard(s.page, "l1").locator("input.row-title").first().focus();
|
||||
await s.page.keyboard.press("Control+Enter");
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "Ctrl+Enter sent");
|
||||
assert.deepEqual(answerTo(got, "l1").rows.map((r) => [r.id, r.title]), [["a", "Read the audit log"], ["b", "Write the file"]]);
|
||||
});
|
||||
|
||||
// What a person sees break: a send the agent already collected still shows as
|
||||
// being with the agent, locking a question it left open.
|
||||
test("a send made before the last collection is never shown as still with the agent", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const card = await ask(s, { id: "q1", kind: "text", title: "What to call it", body: "A name." });
|
||||
// Sent from another tab: this page never learns of it except from the session.
|
||||
await s.page.evaluate(() =>
|
||||
fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [{ i: "q1", type: "answer", kind: "text", text: "audit-export" }], reply: "What to call it: audit-export" }),
|
||||
})
|
||||
);
|
||||
const lock = card.getByText(/Plan2Code is working on it|Waiting for Plan2Code to pick this up/);
|
||||
await lock.waitFor();
|
||||
assert.equal(await card.locator("textarea").count(), 0, "before the agent collects it, the card is locked");
|
||||
// The agent collects it, leaves the question open and waits again.
|
||||
assert.equal(s.wait(10).code, 0);
|
||||
s.post({ agent: { status: "waiting" } });
|
||||
await card.locator("textarea").waitFor();
|
||||
assert.equal(await lock.count(), 0, "after the collection, it is not shown as sent");
|
||||
});
|
||||
|
||||
// What a person sees break: a note box on a card above the git board grows and
|
||||
// squeezes the board, or the card is cut short under it.
|
||||
test("a note box over the git board grows no box, and the card flows at its own height", async (t) => {
|
||||
const dir = tempProject({ "README.md": "# Sample\n", "src/app.js": "export const app = 1;\n" });
|
||||
const g = gitInit(dir);
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "First commit");
|
||||
fs.appendFileSync(path.join(dir, "src", "app.js"), "export const more = 2;\n");
|
||||
const confirm = { id: "y1", kind: "confirm", title: "Save these changes", body: "Commit them?" };
|
||||
const git = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "git",
|
||||
project: dir,
|
||||
payload: { reread: true, board: { describe: "export-more" }, items: [confirm] },
|
||||
});
|
||||
await git.page.getByRole("tablist").waitFor();
|
||||
const gitCard = itemCard(git.page, "y1");
|
||||
await gitCard.waitFor();
|
||||
const note = gitCard.locator("textarea").first();
|
||||
const gitBox = await note.evaluate((el) => ({ min: el.style.minHeight, height: el.offsetHeight }));
|
||||
assert.equal(gitBox.min, "", "no height was filled in for the note box");
|
||||
assert.ok(gitBox.height < 120, `the note box keeps its ordinary height over the board: ${gitBox.height}`);
|
||||
assert.ok(await gitCard.evaluate((el) => el.scrollHeight <= el.clientHeight + 1), "the card is not shrunk under the board");
|
||||
|
||||
// The same card away from the board does fill the free height of the card.
|
||||
const plan = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items: [confirm] } });
|
||||
const planBox = plan.page.locator('[data-item="y1"] textarea').first();
|
||||
await planBox.waitFor();
|
||||
await plan.page.waitForFunction(() => document.querySelector('[data-item="y1"] textarea').offsetHeight >= 160);
|
||||
assert.ok((await planBox.evaluate((el) => el.offsetHeight)) > gitBox.height, "away from the board, the note box grows");
|
||||
});
|
||||
|
||||
const three = ["First", "Second", "Third"].map((name, n) => ({ id: `q${n + 1}`, kind: "text", title: `${name} question`, body: `Body ${n + 1}.` }));
|
||||
|
||||
// What a person sees break: Previous and Next stop walking the open questions.
|
||||
test("Previous and Next walk the questions still waiting, and the ends have no button", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items: three } });
|
||||
const pager = s.page.getByRole("navigation", { name: "Move between the questions waiting" });
|
||||
const shown = () => s.page.locator("#main [data-item]").first().getAttribute("data-item");
|
||||
await pager.getByText("1 of 3 waiting").waitFor();
|
||||
assert.equal(await pager.getByRole("button", { name: /Previous/ }).count(), 0, "nothing before the first");
|
||||
await pager.getByRole("button", { name: /Next.*Second question/ }).click();
|
||||
await pager.getByText("2 of 3 waiting").waitFor();
|
||||
assert.equal(await shown(), "q2");
|
||||
await pager.getByRole("button", { name: /Next.*Third question/ }).click();
|
||||
await pager.getByText("3 of 3 waiting").waitFor();
|
||||
assert.equal(await pager.getByRole("button", { name: /Next/ }).count(), 0, "nothing after the last");
|
||||
await pager.getByRole("button", { name: /Previous.*Second question/ }).click();
|
||||
await pager.getByText("2 of 3 waiting").waitFor();
|
||||
assert.equal(await shown(), "q2");
|
||||
});
|
||||
|
||||
// What a person sees break: Skip this one does nothing, or leaves you on the
|
||||
// card you skipped.
|
||||
test("Skip this one on an optional card moves on, and the skip reaches the agent", async (t) => {
|
||||
const items = three.map((q, n) => ({ ...q, required: n !== 2 ? false : true }));
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items } });
|
||||
const card = itemCard(s.page, "q1");
|
||||
await card.getByRole("button", { name: "Skip this one" }).click();
|
||||
await s.page.waitForFunction(() => document.querySelector("#main [data-item]")?.dataset.item === "q2");
|
||||
assert.equal(await itemCard(s.page, "q3").getByRole("button", { name: "Skip this one" }).count(), 0, "a required card cannot be skipped");
|
||||
await itemCard(s.page, "q2").locator("textarea").fill("Ana");
|
||||
await s.page.getByRole("navigation", { name: "Move between the questions waiting" }).getByRole("button", { name: /Next/ }).click();
|
||||
await itemCard(s.page, "q3").locator("textarea").fill("Bo");
|
||||
const got = await sendAndCollect(s);
|
||||
assert.deepEqual(
|
||||
got.actions.map(({ i, type, text }) => ({ i, type, text })),
|
||||
[{ i: "q1", type: "skip", text: undefined }, { i: "q2", type: "answer", text: "Ana" }, { i: "q3", type: "answer", text: "Bo" }]
|
||||
);
|
||||
});
|
||||
|
||||
// What a person sees break: an answered question can be edited again, or says
|
||||
// nothing about what was answered.
|
||||
test("a settled card is a record: your answer in words, the options as marks, and no form", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
s.post({
|
||||
settle: true,
|
||||
items: [
|
||||
{ id: "c1", kind: "choice", title: "Export format", body: "Which?", options: [opt("A", "CSV"), opt("B", "JSON")], status: "answered", answer: { k: "B" } },
|
||||
{ id: "q9", kind: "text", title: "Still open", body: "Next." },
|
||||
],
|
||||
});
|
||||
await s.page.locator("#sidebar").getByRole("button", { name: /Export format/ }).click();
|
||||
const card = itemCard(s.page, "c1");
|
||||
await card.waitFor();
|
||||
const record = card.locator(".answered");
|
||||
assert.match(await record.innerText(), /Your answer[\s\S]*JSON/i);
|
||||
assert.match(await record.innerText(), /Locked\./);
|
||||
assert.equal(await card.locator("input, textarea").count(), 0, "a record has no inputs");
|
||||
});
|
||||
|
||||
// What a person sees break: a card still takes edits after Send, or never
|
||||
// opens again when the agent hands it back.
|
||||
test("a sent card locks, and the agent's next post on it unlocks it", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items: [three[0]] } });
|
||||
const card = itemCard(s.page, "q1");
|
||||
await card.locator("textarea").fill("Ana");
|
||||
await s.page.click("#btn-send");
|
||||
const lock = card.getByText(/Plan2Code is working on it|Waiting for Plan2Code to pick this up/);
|
||||
await lock.waitFor();
|
||||
assert.match(await card.locator(".answered").innerText(), /Sent[\s\S]*Ana/i);
|
||||
assert.equal(await card.locator("textarea").count(), 0, "no form while the agent has it");
|
||||
s.wait(10);
|
||||
s.post({ items: [{ id: "q1", status: "reopened", thread: [{ who: "agent", text: "Which Ana?" }] }], agent: { status: "waiting" } });
|
||||
await card.locator("textarea").waitFor();
|
||||
assert.equal(await lock.count(), 0, "the next post gives the card back");
|
||||
});
|
||||
|
||||
// What a person sees break: the "something else" box takes the words but the
|
||||
// pick sent is still the listed option, or the pick is lost on a switch back.
|
||||
test("Something else in your own words replaces the pick, and picking an option again drops the words", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const card = await ask(s, { id: "c1", kind: "choice", title: "Where", body: "Where?", options: [opt("A", "Email"), opt("B", "Slack")] });
|
||||
await card.getByLabel("Email").check();
|
||||
const other = card.getByRole("radio", { name: "Something else, in your own words" });
|
||||
await other.check();
|
||||
await card.locator("textarea.other-text").fill("A shared drive");
|
||||
assert.equal(await card.getByLabel("Email").isChecked(), false, "the options and the other share one group");
|
||||
await card.getByLabel("Slack").check();
|
||||
await other.check();
|
||||
assert.equal(await card.locator("textarea.other-text").inputValue(), "A shared drive", "the words survive a switch");
|
||||
const got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "c1"), { text: "A shared drive" });
|
||||
});
|
||||
|
||||
// What a person sees break: a note typed on a card is dropped by the verdict,
|
||||
// or is lost when the verdict comes first.
|
||||
test("a note's comment field rides along with the answer, typed before or after the pick", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
let card = await ask(s, { id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" });
|
||||
await card.getByLabel("Anything to add?").fill("Only on weekdays.");
|
||||
await card.getByRole("button", { name: "Yes" }).click();
|
||||
let got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "y1"), { yes: true, text: "Only on weekdays." });
|
||||
assert.equal(got.reply, "Keep going: yes; Only on weekdays.");
|
||||
|
||||
card = await ask(s, { id: "y2", kind: "confirm", title: "And this", body: "Also?" });
|
||||
await card.getByRole("button", { name: "No" }).click();
|
||||
await card.getByLabel("Anything to add?").fill("Not this quarter.");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "y2"), { yes: false, text: "Not this quarter." });
|
||||
});
|
||||
|
||||
/* ----------------------------------------------------------------- docs */
|
||||
|
||||
// What a person sees break: a guess reads like a decision, or a draft does.
|
||||
test("a doc tags an assumed block and a draft block, and shows a file block's text", async (t) => {
|
||||
const project = tempProject({ "notes/facts.md": "The export keeps **a year** of rows.\n" });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
project,
|
||||
payload: {
|
||||
docs: [
|
||||
{
|
||||
id: "map",
|
||||
title: "What we've agreed",
|
||||
blocks: [
|
||||
{ id: "b1", state: "settled", md: "Runs nightly." },
|
||||
{ id: "b2", state: "assumed", md: "Output is CSV." },
|
||||
{ id: "b3", state: "draft", md: "Maybe a weekly digest." },
|
||||
{ id: "b4", file: "notes/facts.md" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
|
||||
const block = (id) => s.page.locator(`#main [data-block="${id}"]`);
|
||||
await block("b4").waitFor();
|
||||
assert.equal(await block("b1").innerText(), "Runs nightly.", "a settled block has no tag");
|
||||
assert.match(await block("b2").innerText(), /^assumed for now, still open\s+Output is CSV\.$/i);
|
||||
assert.match(await block("b3").innerText(), /^draft\s+Maybe a weekly digest\.$/i);
|
||||
assert.match(await block("b4").innerText(), /The export keeps a year of rows\./, "the file's text is on the page");
|
||||
});
|
||||
|
||||
// What a person sees break: Download hands over something other than the
|
||||
// document, or loses which parts are still guesses.
|
||||
test("Download offers a Markdown file with the doc's title, blocks and marks", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: {
|
||||
docs: [{ id: "map", title: "What we've agreed", blocks: [{ id: "b1", state: "settled", md: "Runs nightly." }, { id: "b2", state: "assumed", md: "Output is CSV." }] }],
|
||||
},
|
||||
});
|
||||
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
|
||||
const [download] = await Promise.all([s.page.waitForEvent("download"), s.page.getByRole("button", { name: "Download" }).click()]);
|
||||
assert.equal(download.suggestedFilename(), "what-we-ve-agreed.md");
|
||||
const chunks = [];
|
||||
for await (const c of await download.createReadStream()) chunks.push(c);
|
||||
assert.equal(Buffer.concat(chunks).toString("utf8"), "# What we've agreed\n\nRuns nightly.\n\n> **Assumed for now, still open.**\n\nOutput is CSV.");
|
||||
});
|
||||
|
||||
// What a person sees break: a long document has no way home but the first
|
||||
// tab, or its header scrolls away with the text.
|
||||
test("a document's header stays on screen and its Back to Questions button returns to the questions", async (t) => {
|
||||
const blocks = Array.from({ length: 60 }, (_, i) => ({ id: "b" + i, state: "settled", md: `Paragraph ${i}. ` + "More words. ".repeat(40) }));
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: {
|
||||
items: [{ id: "q1", kind: "text", title: "A question", body: "Say something." }],
|
||||
docs: [{ id: "map", title: "What we've agreed", blocks }],
|
||||
},
|
||||
});
|
||||
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
|
||||
const back = s.page.getByRole("button", { name: "Back to Questions" });
|
||||
await back.waitFor();
|
||||
await s.page.evaluate(() => { document.getElementById("main").scrollTop = 4000; });
|
||||
const box = await back.boundingBox();
|
||||
const main = await s.page.locator("#main").boundingBox();
|
||||
assert.ok(box && box.y >= main.y - 1 && box.y < main.y + 80, "the header row is still at the top of the pane after scrolling");
|
||||
await back.click();
|
||||
await s.page.getByText("Say something.").waitFor();
|
||||
assert.equal(await s.page.getByRole("button", { name: "Back to Questions" }).count(), 0, "the questions view has no Back button");
|
||||
});
|
||||
|
||||
// What a person sees break: the brief button turns up where no playbook
|
||||
// answers it, or sends a different range than the one picked.
|
||||
test("a pathfinder session offers Write a brief, and the picked range reaches the agent", async (t) => {
|
||||
const plain = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
assert.equal(await plain.page.locator("#btn-brief").isHidden(), true, "no brief button outside pathfinder");
|
||||
await plain.stop();
|
||||
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "pathfinder", payload: { agent: { status: "waiting" } } });
|
||||
await s.page.getByRole("button", { name: "Write a brief" }).first().click();
|
||||
const dialog = s.page.locator("#brief-modal");
|
||||
await dialog.getByLabel("This week").check();
|
||||
await dialog.getByRole("button", { name: "Write the brief" }).click();
|
||||
await dialog.waitFor({ state: "hidden" });
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "a brief request was sent");
|
||||
assert.deepEqual(got.actions.map(({ i, type, range }) => ({ i, type, range })), [{ i: "__brief", type: "brief", range: "this week" }]);
|
||||
assert.equal(got.reply, "Write a brief for this week.");
|
||||
});
|
||||
@@ -0,0 +1,447 @@
|
||||
// Page tests for the dashboard: a spec in the picker, a card picked and
|
||||
// started, the launch send the agent collects, and its `resume` turning the
|
||||
// page into the launched skill's starting screen. Run with:
|
||||
// node --test scripts/test-web-console-page-dashboard.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, tempProject, textOf } from "./page-test-helpers.mjs";
|
||||
import { cli, until, CONSOLE_CLI, HOME } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A project that is set up (AGENTS.md) with one spec holding a Plan draft.
|
||||
// A PLAN-DRAFT whose Status line says only "Draft" (no "Resume at Phase N")
|
||||
// scans as `planned`, which the picker labels "Ready to document". Plan is
|
||||
// still lit for it (only exploring, fixed and documented-or-later grey Plan
|
||||
// out); Document is the state's own next step.
|
||||
const DRAFT_PROJECT = {
|
||||
"AGENTS.md": "# AGENTS.md\n\nA small demo project.\n",
|
||||
"specs/demo/PLAN-DRAFT-20261017.md": "# Plan draft: demo\n\n**Status:** Draft\n\nA lunch vote for the team.\n",
|
||||
};
|
||||
|
||||
// What a real agent posts on the dashboard (plan2code.md, "The menu"): its
|
||||
// judgment on top of the scan, then it waits.
|
||||
const MENU = {
|
||||
menu: {
|
||||
note: "One spec on disk, with a plan drafted.",
|
||||
recommend: "plan2code-2-document",
|
||||
details: { "plan2code-2-document": "Plan drafted" },
|
||||
},
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// The one send `wait` hands the agent; fails the test when nothing arrived.
|
||||
function collect(s) {
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
test("a Plan launch from the dashboard carries the picked spec, and its resume turns the page to Starting Plan", async (t) => {
|
||||
const project = tempProject(DRAFT_PROJECT);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project });
|
||||
const main = await toTheMenu(s);
|
||||
|
||||
// The picker shows the spec with its state, and opens on it.
|
||||
const chip = main.getByRole("button").filter({ hasText: /^demo/ });
|
||||
await chip.waitFor();
|
||||
// The state is drawn in capitals, so the match ignores case.
|
||||
const chipText = await textOf(chip);
|
||||
assert.match(chipText, /Ready to document/i, "the spec chip names its state");
|
||||
assert.match(chipText, /plan drafted/, "the spec chip says how far it got");
|
||||
assert.equal(await chip.getAttribute("aria-current"), "true", "the picker opens on the only spec");
|
||||
|
||||
// The Plan card is lit for this spec; picking it asks to confirm.
|
||||
const planCard = main.getByRole("button").filter({ has: s.page.locator("code", { hasText: /^\/plan2code-1-plan$/ }) });
|
||||
assert.equal(await planCard.isEnabled(), true, "the Plan card is greyed for a drafted plan");
|
||||
await planCard.click();
|
||||
await main.getByRole("button", { name: "Start Plan" }).click();
|
||||
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
const launch = got.actions.find((a) => a.i === "__launch");
|
||||
assert.ok(launch, `the send carries a launch: ${JSON.stringify(got.actions)}`);
|
||||
assert.deepEqual(
|
||||
{ i: launch.i, skill: launch.skill, workflow: launch.workflow, spec: launch.spec },
|
||||
{ i: "__launch", skill: "plan2code-1-plan", workflow: "plan", spec: "specs/demo" }
|
||||
);
|
||||
|
||||
// `resume` is the one command to run, naming the session, workflow and spec.
|
||||
const head = `node "${CONSOLE_CLI}" `;
|
||||
assert.ok(got.resume.startsWith(head), `resume runs this console: ${got.resume}`);
|
||||
const args = got.resume.slice(head.length).split(" ");
|
||||
assert.deepEqual(args, ["open", "--resume", s.sid, "--no-open", "--workflow", "plan", "--spec", "specs/demo"]);
|
||||
|
||||
// `skillFile` is offered only when the skill's SKILL.md sits beside the
|
||||
// console's own folder, as in an install. Run from this repo's source tree
|
||||
// (src/web-console/), that is a plan2code-1-plan/ folder next to the repo,
|
||||
// which does not exist, so the send leaves it out (console-launches.md:
|
||||
// "absent outside an install").
|
||||
assert.equal("skillFile" in got, false, `a source-tree launch names no skillFile: ${got.skillFile}`);
|
||||
|
||||
// The agent runs `resume` first: the page leaves the menu for Plan's
|
||||
// starting screen while the skill is read.
|
||||
const r = cli(args, { cwd: s.project });
|
||||
assert.equal(r.status, 0, `resume failed: ${r.stderr}`);
|
||||
await main.getByRole("heading", { name: "Starting Plan" }).waitFor();
|
||||
});
|
||||
|
||||
// A project holding one fixed bug (a diagnosis Quick Task marked Fixed) and
|
||||
// one drafted plan. The fixed bug is touched last, so it is the newest spec on
|
||||
// disk: the picker must still open on the plan, since a finished spec is never
|
||||
// the default.
|
||||
function fixedProject() {
|
||||
const project = tempProject({
|
||||
...DRAFT_PROJECT,
|
||||
"specs/old-bug/DIAGNOSIS-20261017.md": "# Diagnosis: old bug\n\n**Status:** Fixed\n\nThe save button lost its handler.\n",
|
||||
});
|
||||
const later = new Date(Date.now() + 60_000);
|
||||
fs.utimesSync(path.join(project, "specs/old-bug/DIAGNOSIS-20261017.md"), later, later);
|
||||
return project;
|
||||
}
|
||||
|
||||
// Past Planny's wake-up and, on this console home's first run, the Welcome,
|
||||
// to the menu.
|
||||
async function toTheMenu(s) {
|
||||
const skip = s.page.getByRole("button", { name: "Skip the intro" });
|
||||
await skip.click();
|
||||
await skip.waitFor({ state: "hidden" });
|
||||
const main = s.page.locator("#main");
|
||||
const heading = main.getByRole("heading", { name: "What are we doing today?" });
|
||||
await heading.waitFor();
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) {
|
||||
await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
}
|
||||
return main;
|
||||
}
|
||||
|
||||
// Sets the picker's "Hide unavailable workflows" switch. Looks are kept per
|
||||
// console home, so each test sets the one it needs rather than trusting the
|
||||
// default.
|
||||
async function hideUnavailable(main, on) {
|
||||
const box = main.getByRole("switch", { name: "Hide unavailable workflows" });
|
||||
if ((await box.isChecked()) !== on) await main.getByText("Hide unavailable workflows").click();
|
||||
assert.equal(await box.isChecked(), on);
|
||||
}
|
||||
|
||||
const chipFor = (main, name) => main.getByRole("button").filter({ hasText: new RegExp(`^${name}`) });
|
||||
|
||||
test("a fixed bug is hidden while unavailable workflows are, dimmed when they show, and never the picker's default", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: fixedProject() });
|
||||
const main = await toTheMenu(s);
|
||||
|
||||
// Hidden while the switch is on.
|
||||
await hideUnavailable(main, true);
|
||||
const demo = chipFor(main, "demo");
|
||||
await demo.waitFor();
|
||||
assert.equal(await demo.getAttribute("aria-current"), "true", "the picker opens on the plan, not the newer fixed bug");
|
||||
assert.equal(await chipFor(main, "old-bug").count(), 0, "the fixed bug's chip is hidden while unavailable workflows are");
|
||||
|
||||
// Switched off: the chip shows, labelled and dimmed, and still not picked.
|
||||
await hideUnavailable(main, false);
|
||||
const bug = chipFor(main, "old-bug");
|
||||
await bug.waitFor();
|
||||
assert.match(await textOf(bug), /Bug fixed/i, "the chip names its state");
|
||||
assert.doesNotMatch(await textOf(bug), /bug fixed\s+bug fixed/i, "the scan's detail does not repeat the label");
|
||||
assert.equal(await bug.getAttribute("aria-current"), "false", "the fixed bug is not picked");
|
||||
const opacity = await bug.evaluate((b) => Number(getComputedStyle(b).opacity));
|
||||
assert.ok(opacity < 1, `the fixed bug's chip is dimmed (opacity ${opacity})`);
|
||||
assert.equal(await demo.getAttribute("aria-current"), "true", "the plan stays picked");
|
||||
});
|
||||
|
||||
test("a fixed bug's Delete asks once with no name to type, while any other spec asks for its name", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: fixedProject() });
|
||||
const main = await toTheMenu(s);
|
||||
await hideUnavailable(main, false);
|
||||
await chipFor(main, "old-bug").waitFor();
|
||||
|
||||
const dialog = s.page.locator("#delete-modal");
|
||||
const go = s.page.locator("#delete-go");
|
||||
const nameStep = s.page.locator("#delete-confirm");
|
||||
|
||||
// Any other spec: the first press only reveals the name step.
|
||||
await main.getByRole("button", { name: "Delete the spec demo" }).click({ force: true });
|
||||
await dialog.waitFor();
|
||||
assert.equal(await textOf(go), "Delete this spec…");
|
||||
await go.click();
|
||||
await nameStep.waitFor();
|
||||
assert.equal(await go.isDisabled(), true, "the final button waits for the name");
|
||||
await s.page.keyboard.press("Escape");
|
||||
await dialog.waitFor({ state: "hidden" });
|
||||
|
||||
// The fixed bug: a visible Delete, its own warning, and one press sends it.
|
||||
const del = main.getByRole("button", { name: "Delete the spec old-bug" });
|
||||
assert.equal(await textOf(del), "Delete", "a fixed bug's Delete is a labelled button");
|
||||
await del.click();
|
||||
await dialog.waitFor();
|
||||
assert.match(await textOf(s.page.locator("#delete-warn")), /The bug is fixed, so this only clears the write-up/);
|
||||
assert.equal(await textOf(go), "Delete it");
|
||||
assert.equal(await nameStep.isHidden(), true, "no name step for a fixed bug");
|
||||
await go.click();
|
||||
|
||||
const got = collect(s);
|
||||
assert.equal(await nameStep.isHidden(), true, "the name step never showed");
|
||||
const action = got.actions.find((a) => a.i === "__delete");
|
||||
assert.deepEqual({ type: action?.type, spec: action?.spec }, { type: "delete", spec: "specs/old-bug" });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The picker's switching, the first-open wake-up, handoffs, the update banner,
|
||||
// the workspace scope, and the pose that carries a launch into the work.
|
||||
|
||||
const lightOf = (main, command) => main.getByRole("button").filter({ has: main.page().locator("code", { hasText: new RegExp(`^${command}$`) }) });
|
||||
const pickedChip = (main, name) => main.locator('button[aria-current="true"]', { hasText: new RegExp(`^${name}`) });
|
||||
|
||||
// What a person would see break: picking another target leaves the launch
|
||||
// aimed at the old spec, or the cards lit for it.
|
||||
test("picking Start from scratch instead of a spec greys Document, and a launch then carries 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);
|
||||
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");
|
||||
|
||||
// From scratch there is no draft to document: the card greys.
|
||||
await chipFor(main, "Start from scratch").click();
|
||||
await pickedChip(main, "Start from scratch").waitFor();
|
||||
assert.equal(await document.isDisabled(), true, "Document is greyed with no spec picked");
|
||||
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.
|
||||
await chipFor(main, "demo").click();
|
||||
await pickedChip(main, "demo").waitFor();
|
||||
assert.equal(await document.isEnabled(), true, "Document is lit again for the spec");
|
||||
await chipFor(main, "Start from scratch").click();
|
||||
await pickedChip(main, "Start from scratch").waitFor();
|
||||
await lightOf(main, "/plan2code-1-plan").click();
|
||||
await main.getByRole("button", { name: "Start Plan" }).click();
|
||||
const launch = collect(s).actions.find((a) => a.i === "__launch");
|
||||
assert.equal(launch.skill, "plan2code-1-plan");
|
||||
assert.ok(!launch.spec, `a launch from scratch names no spec: ${JSON.stringify(launch)}`);
|
||||
});
|
||||
|
||||
// What a person would see break: the intro cannot be skipped, or it replays
|
||||
// on every reload of the same tab.
|
||||
test("Skip the intro ends the first-open wake-up at once, and a reload of the tab does not play it again", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const skip = s.page.getByRole("button", { name: "Skip the intro" });
|
||||
await skip.waitFor();
|
||||
await toTheMenu(s);
|
||||
assert.equal(await skip.isVisible(), false);
|
||||
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||
assert.equal(await skip.isVisible(), false, "the intro does not play again in this tab");
|
||||
});
|
||||
|
||||
// A project with no spec, only a handoff written for it (the Handoff skill's
|
||||
// file pair under the test's own handoffs folder), removed with the test.
|
||||
const HANDOFF_DOC = "# Handoff: Lunch vote\n\n## Next task\n\nWire the vote button to the tally.\n\n## Notes\n\nA long body line.\n";
|
||||
function handoffProject(t) {
|
||||
const project = tempProject({ "AGENTS.md": "# AGENTS.md\n\nA small demo project.\n" });
|
||||
const made = cli(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"], { cwd: project }).json;
|
||||
fs.writeFileSync(made.path, HANDOFF_DOC);
|
||||
t.after(() => {
|
||||
fs.rmSync(made.path, { force: true });
|
||||
fs.rmSync(made.path.replace(/\.md$/, ".json"), { force: true });
|
||||
});
|
||||
return { project, made };
|
||||
}
|
||||
|
||||
async function openHandoffMenu(t) {
|
||||
const { project, made } = handoffProject(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project });
|
||||
const main = await toTheMenu(s);
|
||||
const chip = chipFor(main, "Lunch vote");
|
||||
await chip.waitFor();
|
||||
return { s, main, chip, made };
|
||||
}
|
||||
|
||||
// What a person would see break: a handoff is not offered when it is all the
|
||||
// project has, or picking it still shows the skill cards beside the preview.
|
||||
test("a handoff shows as a dashed Handoff chip even with no spec, and picking it swaps the cards for a preview of four buttons", async (t) => {
|
||||
const { main, chip } = await openHandoffMenu(t);
|
||||
assert.match(await textOf(chip), /Handoff/i, "the chip is labelled Handoff");
|
||||
assert.equal(await chip.getAttribute("aria-current"), "false", "a handoff is offered, not picked for you");
|
||||
assert.equal(await chip.evaluate((b) => getComputedStyle(b).borderTopStyle), "dashed", "the chip's border is dashed");
|
||||
assert.ok(await lightOf(main, "/plan2code-1-plan").isVisible(), "the cards show before a handoff is picked");
|
||||
|
||||
await chip.click();
|
||||
assert.equal(await chip.getAttribute("aria-current"), "true");
|
||||
await main.getByRole("heading", { name: "Lunch vote" }).waitFor();
|
||||
assert.match(await textOf(main), /Wire the vote button to the tally\./, "the preview quotes the Next task");
|
||||
for (const name of ["Pick it up here", "Read it all", "Copy for a new conversation", "Delete"]) {
|
||||
assert.equal(await main.getByRole("button", { name, exact: true }).count(), 1, `the preview has ${name}`);
|
||||
}
|
||||
assert.equal(await lightOf(main, "/plan2code-1-plan").count(), 0, "the skill cards give way to the preview");
|
||||
assert.equal(await main.getByRole("switch", { name: "Hide unavailable workflows" }).count(), 0, "and so does their toggle");
|
||||
});
|
||||
|
||||
// What a person would see break: Pick it up here sends nothing, or sends more
|
||||
// than the handoff's id.
|
||||
test("Pick it up here sends a pickup naming the handoff, and the page turns to its launch screen", async (t) => {
|
||||
const { s, main, chip, made } = await openHandoffMenu(t);
|
||||
await chip.click();
|
||||
await main.getByRole("button", { name: "Pick it up here" }).click();
|
||||
const got = collect(s);
|
||||
const pick = got.actions.find((a) => a.i === "__pickup");
|
||||
assert.deepEqual({ type: pick?.type, handoff: pick?.handoff }, { type: "pickup", handoff: made.id });
|
||||
assert.match(got.resume, /--workflow quick-task$/, "the CLI read the handoff's own workflow");
|
||||
await main.getByRole("heading", { name: "Waking up Lunch vote" }).waitFor();
|
||||
});
|
||||
|
||||
// What a person would see break: Read it all opens nothing, or Copy puts the
|
||||
// wrong words on the clipboard.
|
||||
test("Read it all opens the handoff's text, and Copy puts a prompt naming its file on the clipboard", async (t) => {
|
||||
const { s, main, chip, made } = await openHandoffMenu(t);
|
||||
await s.context.grantPermissions(["clipboard-read", "clipboard-write"], { origin: new URL(s.url).origin });
|
||||
await chip.click();
|
||||
|
||||
await main.getByRole("button", { name: "Read it all" }).click();
|
||||
const reader = s.page.locator("#handoff-modal");
|
||||
await reader.getByText("A long body line.").waitFor();
|
||||
await s.page.keyboard.press("Escape");
|
||||
await reader.waitFor({ state: "hidden" });
|
||||
|
||||
const copy = main.getByRole("button", { name: "Copy for a new conversation" });
|
||||
await copy.click();
|
||||
await main.getByRole("button", { name: "Copied" }).waitFor();
|
||||
const text = await s.page.evaluate(() => navigator.clipboard.readText());
|
||||
assert.match(text, /^Read the handoff at .*\.md and carry on with its Next task\.$/);
|
||||
assert.ok(text.includes(made.id), `the prompt names the handoff's file: ${text}`);
|
||||
});
|
||||
|
||||
// What a person would see break: Delete asks for a name, or sends a spec
|
||||
// delete instead of the handoff's.
|
||||
test("a handoff's Delete asks once in its own dialog and sends a delete naming the handoff", async (t) => {
|
||||
const { s, main, chip, made } = await openHandoffMenu(t);
|
||||
await chip.click();
|
||||
await main.getByRole("button", { name: "Delete", exact: true }).click();
|
||||
const dialog = s.page.locator("#delete-modal");
|
||||
await dialog.waitFor();
|
||||
assert.equal(await textOf(s.page.locator("#delete-title")), "Delete this handoff?");
|
||||
assert.equal(await s.page.locator("#delete-warn-handoff").isVisible(), true, "the warning says where handoffs live");
|
||||
assert.equal(await s.page.locator("#delete-confirm").isHidden(), true, "no name to type");
|
||||
await s.page.locator("#delete-go").click();
|
||||
const action = collect(s).actions.find((a) => a.i === "__delete");
|
||||
assert.deepEqual({ type: action?.type, handoff: action?.handoff, spec: action?.spec }, { type: "delete", handoff: made.id, spec: undefined });
|
||||
});
|
||||
|
||||
// A newer release on record, so a console that boots now has an update to
|
||||
// announce (the check reads this file for an hour instead of asking the
|
||||
// network). The file is put back as the suite had it.
|
||||
function aNewerReleaseExists(t) {
|
||||
const file = path.join(HOME, "update-check.json");
|
||||
const before = fs.readFileSync(file, "utf8");
|
||||
fs.writeFileSync(file, JSON.stringify({ checkedAt: Date.now(), latest: "99.0.0" }));
|
||||
t.after(() => fs.writeFileSync(file, before));
|
||||
}
|
||||
|
||||
// What a person would see break: the banner shows on a build's page, or the
|
||||
// dashboard never offers it.
|
||||
test("the update banner shows on the dashboard only, and its dismiss hides it", async (t) => {
|
||||
aNewerReleaseExists(t);
|
||||
const browser = await suite.browser();
|
||||
const build = await openSession(browser, { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
const dash = await openSession(browser, { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const main = await toTheMenu(dash);
|
||||
const banner = main.getByRole("button", { name: /UPDATE AVAILABLE · v99\.0\.0/ });
|
||||
await banner.waitFor();
|
||||
// The build's server booted under the same record; a later frame has landed
|
||||
// on its page by the time this text shows, and it still has no banner.
|
||||
build.post({ agent: { status: "working", activity: "Task 1 of 1, one more look" } });
|
||||
await build.page.getByText("Task 1 of 1, one more look").first().waitFor();
|
||||
assert.equal(await build.page.getByText("UPDATE AVAILABLE").count(), 0, "a build's page has no banner");
|
||||
|
||||
await main.getByRole("button", { name: "Dismiss until next time" }).click();
|
||||
await banner.waitFor({ state: "hidden" });
|
||||
});
|
||||
|
||||
// What a person would see break: two dashboard tabs of one session, on
|
||||
// different picks, keep taking the workspace's folders back from each other.
|
||||
test("two dashboard tabs on different picks leave the workspace scope with the last pick and ask for it no more", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const mainA = await toTheMenu(s);
|
||||
const second = await s.context.newPage();
|
||||
second.on("pageerror", (e) => s.errors.push(e.message));
|
||||
await second.goto(s.url, { waitUntil: "domcontentloaded" });
|
||||
const mainB = await toTheMenu({ page: second });
|
||||
const asks = { a: 0, b: 0 };
|
||||
s.page.on("request", (r) => r.method() === "POST" && r.url().endsWith("/workspace/scope") && asks.a++);
|
||||
second.on("request", (r) => r.method() === "POST" && r.url().endsWith("/workspace/scope") && asks.b++);
|
||||
const scopeOf = () => s.page.evaluate(async () => (await (await fetch("/workspace?check=1", { cache: "no-store" })).json()).scope || "");
|
||||
assert.equal(await scopeOf(), "specs/demo", "both tabs opened on the spec");
|
||||
|
||||
// The second tab moves to Start from scratch: its folders become the project's own.
|
||||
await chipFor(mainB, "Start from scratch").click();
|
||||
await pickedChip(mainB, "Start from scratch").waitFor();
|
||||
assert.ok(await until(async () => (await scopeOf()) === ""), "the scope followed the second tab");
|
||||
|
||||
// The first tab keeps its pick and takes a frame from the agent after the change.
|
||||
s.post({ menu: { ...MENU.menu, note: "A second look from the agent." } });
|
||||
await mainA.getByText("A second look from the agent.").waitFor();
|
||||
assert.equal(await pickedChip(mainA, "demo").count(), 1, "the first tab still has its own pick");
|
||||
assert.equal(asks.a, 0, "the tab that did not move never asked for its own scope back");
|
||||
assert.equal(asks.b, 1, "the tab that moved asked once");
|
||||
assert.equal(await scopeOf(), "", "the scope stays with the last pick");
|
||||
});
|
||||
|
||||
// What a person would see break: Planny is rebuilt on every screen change, so
|
||||
// his animation restarts as the launch becomes the work.
|
||||
test("the pose pane a launch shows is the very element the starting and waiting screens keep, and the waiting pane shows the agent's activity", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const main = await toTheMenu(s);
|
||||
await lightOf(main, "/plan2code-1-plan").click();
|
||||
await main.getByRole("button", { name: "Start Plan" }).click();
|
||||
|
||||
// The launching screen, with its pose; mark that exact element.
|
||||
const pane = s.page.locator("#main > [data-pose]");
|
||||
await pane.waitFor();
|
||||
const pose = await pane.getAttribute("data-pose");
|
||||
await pane.evaluate((el) => (el.__sameElement = true));
|
||||
|
||||
// The agent resumes the session as Plan: the starting screen reuses the pane.
|
||||
const got = collect(s);
|
||||
const args = got.resume.slice(`node "${CONSOLE_CLI}" `.length).split(" ");
|
||||
assert.equal(cli(args, { cwd: s.project }).status, 0);
|
||||
await main.getByRole("heading", { name: "Starting Plan" }).waitFor();
|
||||
assert.equal(await pane.getAttribute("data-pose"), pose, "the same pose carries into the starting screen");
|
||||
assert.equal(await pane.evaluate((el) => el.__sameElement === true && el.isConnected), true, "the pane was kept, not rebuilt");
|
||||
|
||||
// The agent starts work and says what it is doing: the waiting screen shows it,
|
||||
// still in the same pane.
|
||||
s.post({ agent: { status: "working", activity: "Reading the plan draft" } });
|
||||
await main.getByText("Reading the plan draft").waitFor();
|
||||
assert.equal(await pane.evaluate((el) => el.__sameElement === true && el.isConnected), true, "the pane survives into the waiting screen");
|
||||
s.post({ agent: { status: "working", activity: "Writing the first questions" } });
|
||||
await main.getByText("Writing the first questions").waitFor();
|
||||
assert.equal(await pane.evaluate((el) => el.__sameElement === true && el.isConnected), true, "and survives each state frame after it");
|
||||
});
|
||||
|
||||
// What a person would see break: a quick-task build points at a Plan tab that
|
||||
// does not open, or another skill's page gains a pointer it has no list for.
|
||||
test("a quick-task build's waiting pane points at its Plan tab, and a plan session with the same tab gets no pointer", async (t) => {
|
||||
const plan = { id: "plan", title: "Plan", blocks: [{ id: "steps", state: "settled", md: "## Steps\n\n- [ ] **1.** Wire the vote button" }] };
|
||||
const working = { agent: { status: "working", activity: "Step 1 of 1" } };
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "quick-task", payload: { docs: [plan], ...working } });
|
||||
const pane = s.page.locator("#main > .waiting-pane");
|
||||
await pane.waitFor();
|
||||
const jump = pane.getByRole("button", { name: "Plan", exact: true });
|
||||
await jump.waitFor();
|
||||
await jump.click();
|
||||
await s.page.locator("#main").getByText("Wire the vote button").waitFor();
|
||||
|
||||
const other = await openSession(await suite.browser(), { t, workflow: "plan", payload: { docs: [plan], ...working } });
|
||||
const otherPane = other.page.locator("#main > .waiting-pane");
|
||||
await otherPane.waitFor();
|
||||
assert.equal(await otherPane.getByRole("button", { name: "Plan", exact: true }).count(), 0, "a plan session has no live task list to point at");
|
||||
});
|
||||
@@ -0,0 +1,314 @@
|
||||
// Page tests for the git board: the Changes, Branches and Sync tabs drawn
|
||||
// from a real repository, each tab's content on show when it is picked. Run
|
||||
// with:
|
||||
// node --test scripts/test-web-console-page-git.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test. The fixture repo is built under the scrubbed git config
|
||||
// that skill-script-helpers.mjs sets for the whole process, so the console's
|
||||
// own snapshot reads it the way the fixture wrote it.
|
||||
|
||||
import { gitInit } from "./skill-script-helpers.mjs";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pageSuite, openSession, tempProject, textOf, itemCard } from "./page-test-helpers.mjs";
|
||||
import { until } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A repo with one commit on main, a second branch, and one file changed on
|
||||
// the tree since that commit.
|
||||
function gitProject() {
|
||||
const dir = tempProject({ "README.md": "# Sample\n", "src/app.js": "export const app = 1;\n" });
|
||||
const g = gitInit(dir);
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "First commit");
|
||||
g("branch", "feature/export-csv");
|
||||
fs.appendFileSync(path.join(dir, "src", "app.js"), "export const more = 2;\n");
|
||||
return dir;
|
||||
}
|
||||
|
||||
// What a real Git skill posts once the board is up (notes/git.md): a reread,
|
||||
// so the console snapshots the repo, and the description of what changed.
|
||||
const BOARD = { reread: true, board: { describe: "export-more" } };
|
||||
|
||||
test("the git board shows Changes, Branches and Sync, and each tab shows its own content", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: BOARD });
|
||||
const { page } = s;
|
||||
const tab = (label) => page.getByRole("tab", { name: new RegExp(`^${label}\\b`) });
|
||||
const panel = page.getByRole("tabpanel");
|
||||
|
||||
await page.getByRole("tablist").waitFor();
|
||||
assert.deepEqual(
|
||||
(await page.getByRole("tab").allInnerTexts()).map((x) => x.trim().split(/\s/)[0]),
|
||||
["Changes", "Branches", "Sync"]
|
||||
);
|
||||
|
||||
await tab("Changes").click();
|
||||
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent.startsWith("Changes"));
|
||||
await panel.getByText("src/app.js", { exact: true }).waitFor();
|
||||
assert.match(await textOf(panel), /src\/app\.js/);
|
||||
|
||||
await tab("Branches").click();
|
||||
await panel.getByText("feature/export-csv").first().waitFor();
|
||||
const branches = await textOf(panel);
|
||||
assert.match(branches, /feature\/export-csv/);
|
||||
assert.doesNotMatch(branches, /src\/app\.js/, "the Branches tab still shows the changed files");
|
||||
|
||||
await tab("Sync").click();
|
||||
await panel.getByText(/nothing to sync/).waitFor();
|
||||
const sync = await textOf(panel);
|
||||
assert.match(sync, /No remote yet, so nothing to sync/);
|
||||
assert.doesNotMatch(sync, /feature\/export-csv/, "the Sync tab still lists the branches");
|
||||
});
|
||||
|
||||
test("each git tab keeps its own scroll place, across a tab switch and an agent post", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: BOARD });
|
||||
const { page } = s;
|
||||
await page.getByRole("tablist").waitFor();
|
||||
await page.setViewportSize({ width: 1280, height: 260 });
|
||||
const tab = (label) => page.getByRole("tab", { name: new RegExp(`^${label}\\b`) });
|
||||
const column = () => page.locator("#main").evaluate((el) => el.scrollTop);
|
||||
await tab("Changes").click();
|
||||
await page.getByRole("tabpanel").getByText("src/app.js", { exact: true }).waitFor();
|
||||
await page.locator("#main").evaluate((el) => (el.scrollTop = 120));
|
||||
const changesAt = await column();
|
||||
assert.ok(changesAt > 0, "the board's column scrolls");
|
||||
// Another tab opens at its own place, not where Changes was left.
|
||||
await tab("Branches").click();
|
||||
await page.getByRole("tabpanel").getByText("feature/export-csv").first().waitFor();
|
||||
assert.equal(await column(), 0, "Branches opened at the place Changes was left");
|
||||
await tab("Changes").click();
|
||||
await page.getByRole("tabpanel").getByText("src/app.js", { exact: true }).waitFor();
|
||||
assert.equal(await column(), changesAt, "Changes lost its place across the switch");
|
||||
// An agent post redraws the board: still the same place.
|
||||
s.post({ title: "Git, take two" });
|
||||
await page.waitForFunction(() => document.getElementById("title").textContent.includes("Git, take two"));
|
||||
assert.equal(await column(), changesAt, "Changes lost its place across a redraw");
|
||||
});
|
||||
|
||||
// The agent is sitting in `wait`, so the board is the person's to use. A fresh
|
||||
// session has the agent working, which locks every button but the tabs.
|
||||
const READY = { ...BOARD, agent: { status: "waiting" } };
|
||||
|
||||
// A repo with one commit, then two changes on the tree: src/app.js edited and
|
||||
// notes.md new. `branch` checks out a branch of its own (or "detached" a bare
|
||||
// commit), so the commit panel is the next step; on main the next step is to
|
||||
// start a branch. `remotes` names the remotes to add.
|
||||
function changesProject({ branch = null, remotes = [] } = {}) {
|
||||
const dir = tempProject({ "README.md": "# Sample\n", "src/app.js": "export const app = 1;\n" });
|
||||
const g = gitInit(dir);
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "First commit");
|
||||
g("branch", "feature/export-csv");
|
||||
for (const name of remotes) {
|
||||
const bare = tempProject();
|
||||
g("init", "-q", "--bare", bare);
|
||||
g("remote", "add", name, bare);
|
||||
}
|
||||
if (branch === "detached") g("checkout", "-q", "--detach");
|
||||
else if (branch) g("checkout", "-q", "-b", branch);
|
||||
fs.appendFileSync(path.join(dir, "src", "app.js"), "export const more = 2;\n");
|
||||
fs.writeFileSync(path.join(dir, "notes.md"), "Notes.\n");
|
||||
return dir;
|
||||
}
|
||||
|
||||
const confirmCard = { id: "y1", kind: "confirm", title: "Save these changes", body: "Commit them?" };
|
||||
const tabButton = (page, label) => page.getByRole("tab", { name: new RegExp(`^${label}\\b`) });
|
||||
const tickBox = (page, file) => page.getByLabel(`Commit ${file}`);
|
||||
// The Branches tab's Switch button, for the one other branch.
|
||||
const switchButton = (page) => page.getByRole("tabpanel").getByRole("button", { name: "Switch" });
|
||||
// The board's step button, in the strip above the tab's content.
|
||||
const stepButton = (page, name) => page.locator(".git-step-actions").getByRole("button", { name });
|
||||
|
||||
// Whether the board's own controls (not its tabs or the pointer to another
|
||||
// tab) are all off, or at least one is on. Whatever tab the board has moved to,
|
||||
// a locked board has every one of them disabled.
|
||||
const boardControls = (page) => page.locator(".git-panel-tab").locator("button, input[type=checkbox], select");
|
||||
const usable = async (page) => {
|
||||
const off = await boardControls(page).evaluateAll((all) => all.filter((x) => !x.classList.contains("git-hint")).map((x) => x.disabled));
|
||||
return off.some((x) => !x);
|
||||
};
|
||||
// The board redraws a moment after its cause, so each check gets time to settle.
|
||||
const settles = (control, enabled) => until(async () => (await control.isEnabled()) === enabled, 8000);
|
||||
const settlesUsable = (page, want) => until(async () => (await usable(page)) === want, 8000);
|
||||
const titled = (page, text) => page.waitForFunction((x) => document.getElementById("title").textContent.includes(x), text);
|
||||
|
||||
test("the commit dialog sends the ticked files as one __git action, with its reply sentence", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject({ branch: "feature/x" }), payload: READY });
|
||||
const { page } = s;
|
||||
await page.getByRole("tablist").waitFor();
|
||||
await stepButton(page, "Commit 2 files").click();
|
||||
const panel = page.locator(".git-panel");
|
||||
await panel.getByRole("button", { name: "Close" }).waitFor();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
await panel.getByRole("button", { name: "Commit 1 file" }).click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "the agent collected the click");
|
||||
assert.deepEqual(got.actions, [{ i: "__git", type: "git", op: "commit", files: ["src/app.js"], ignore: [] }]);
|
||||
assert.equal(got.reply, "Commit this file: src/app.js.");
|
||||
});
|
||||
|
||||
test("a board click is exactly one __git action", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Branches").click();
|
||||
await switchButton(page).click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0);
|
||||
assert.equal(got.actions.length, 1, "one click, one action");
|
||||
assert.equal(got.actions[0].i, "__git");
|
||||
assert.equal(got.actions[0].type, "git");
|
||||
assert.equal(got.reply, "Switch to feature/export-csv.");
|
||||
assert.notEqual(s.wait(1).code, 0, "nothing else was sent beside it");
|
||||
});
|
||||
|
||||
test("the board stays locked from a click until the agent's next post, not just until it is collected", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Branches").click();
|
||||
assert.ok(await settlesUsable(page, true), "the board is the person's before any click");
|
||||
await switchButton(page).click();
|
||||
assert.ok(await settlesUsable(page, false), "locked from the click");
|
||||
// The agent has the click now (it is running git), and the board still waits.
|
||||
assert.equal(s.wait(10).code, 0);
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
assert.equal(await usable(page), false, "collected is not yet answered");
|
||||
// The agent's next post lets the board go.
|
||||
s.post({ title: "Switched", agent: { status: "waiting" } });
|
||||
await titled(page, "Switched");
|
||||
assert.ok(await settlesUsable(page, true), "the agent's post gave the board back");
|
||||
});
|
||||
|
||||
test("an open card of the agent's holds the board, and a notice does not", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
|
||||
const { page } = s;
|
||||
assert.ok(await settlesUsable(page, true));
|
||||
s.post({ items: [{ id: "n1", kind: "notice", title: "Heads up", body: "Nothing to act on." }], agent: { status: "waiting" } });
|
||||
await page.getByText("Heads up", { exact: true }).waitFor();
|
||||
assert.equal(await usable(page), true, "a notice leaves the board alone");
|
||||
s.post({ items: [confirmCard], agent: { status: "waiting" } });
|
||||
await itemCard(page, "y1").waitFor();
|
||||
assert.ok(await settlesUsable(page, false), "a question card holds the board");
|
||||
});
|
||||
|
||||
test("the git board lets go of a working agent that went adrift", async (t) => {
|
||||
const working = { agent: { status: "working", activity: "Looking at the repo" } };
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), clock: true, payload: { ...BOARD, ...working } });
|
||||
const { page } = s;
|
||||
assert.equal(await usable(page), false, "a working agent holds the board");
|
||||
// Nobody has listened for longer than the adrift limit. The board only
|
||||
// redraws on a post, and the agent is still "working" in it: the lock must
|
||||
// not outlive the agent.
|
||||
await page.clock.fastForward(200_000);
|
||||
s.post({ title: "Still on it", ...working });
|
||||
await titled(page, "Still on it");
|
||||
assert.ok(await settlesUsable(page, true), "an agent gone quiet gave the board back");
|
||||
});
|
||||
|
||||
test("the commit table keeps the person's ticks across an agent post, and a click re-seeds them", async (t) => {
|
||||
const dir = changesProject({ branch: "feature/x" });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: dir, payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Changes").click();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
// An agent post redraws the board: the person's tick stays off.
|
||||
s.post({ title: "Still looking", agent: { status: "waiting" } });
|
||||
await titled(page, "Still looking");
|
||||
assert.equal(await tickBox(page, "notes.md").isChecked(), false, "an agent post put the tick back");
|
||||
assert.equal(await tickBox(page, "src/app.js").isChecked(), true);
|
||||
// Their click goes out with the one file. Then the agent commits it and a new file turns up.
|
||||
await page.locator(".git-panel-actions").getByRole("button", { name: "Commit 1 file" }).click();
|
||||
assert.deepEqual(s.wait(10).actions[0].files, ["src/app.js"]);
|
||||
const g = gitInit(dir, "feature/x");
|
||||
g("add", "src/app.js");
|
||||
g("commit", "-q", "-m", "Edit app");
|
||||
fs.writeFileSync(path.join(dir, "later.md"), "Later.\n");
|
||||
s.post({ reread: true, title: "Committed", agent: { status: "waiting" } });
|
||||
await titled(page, "Committed");
|
||||
await tabButton(page, "Changes").click();
|
||||
await tickBox(page, "later.md").waitFor();
|
||||
assert.equal(await tickBox(page, "notes.md").isChecked(), true, "the click dropped the old picks, so the table was seeded afresh");
|
||||
});
|
||||
|
||||
test("starting a branch for the changes carries the files ticked in the commit table", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject(), payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Changes").click();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
await stepButton(page, /^Start a branch for/).click();
|
||||
const panel = page.locator(".git-panel");
|
||||
await panel.getByRole("heading", { name: "New branch for this commit" }).waitFor();
|
||||
const create = panel.getByRole("button", { name: "Create", exact: true });
|
||||
assert.ok(await settles(create, true), "a free name is composed from the description");
|
||||
await create.click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0);
|
||||
assert.equal(got.actions.length, 1);
|
||||
assert.equal(got.actions[0].op, "create");
|
||||
assert.equal(got.actions[0].then, "commit");
|
||||
assert.deepEqual(got.actions[0].files, ["src/app.js"], "the unticked file stayed out");
|
||||
assert.match(got.reply, /^Create \S+ from main\. Then commit this file: src\/app\.js\.$/);
|
||||
});
|
||||
|
||||
test("a commit with no branch to land on carries the ticked files into the new branch", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject({ branch: "detached" }), payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Changes").click();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
// The step is on the Branches tab, and its Commit button finds no branch to commit on.
|
||||
await tabButton(page, "Branches").click();
|
||||
await stepButton(page, "Commit 2 files").click();
|
||||
const panel = page.locator(".git-panel");
|
||||
await panel.getByRole("heading", { name: "New branch for this commit" }).waitFor();
|
||||
const create = panel.getByRole("button", { name: "Create", exact: true });
|
||||
assert.ok(await settles(create, true));
|
||||
await create.click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0);
|
||||
assert.equal(got.actions[0].op, "create");
|
||||
assert.deepEqual(got.actions[0].files, ["src/app.js"]);
|
||||
assert.match(got.reply, /Then commit this file: src\/app\.js\.$/);
|
||||
});
|
||||
|
||||
test("Publish names a remote only when there is exactly one", async (t) => {
|
||||
const browser = await suite.browser();
|
||||
const published = async (remotes) => {
|
||||
const s = await openSession(browser, { t, workflow: "git", project: changesProject({ branch: "feature/x", remotes }), payload: READY });
|
||||
await tabButton(s.page, "Sync").click();
|
||||
await s.page.locator(".git-sync-actions").getByRole("button", { name: "Publish" }).click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0);
|
||||
await s.stop();
|
||||
return got;
|
||||
};
|
||||
const one = await published(["origin"]);
|
||||
assert.equal(one.actions[0].remote, "origin");
|
||||
assert.equal(one.reply, "Publish to origin.");
|
||||
const two = await published(["origin", "backup"]);
|
||||
assert.equal(Object.hasOwn(two.actions[0], "remote"), false, "with two remotes the agent is the one to ask which");
|
||||
assert.equal(two.reply, "Publish.");
|
||||
});
|
||||
|
||||
test("over the git board a note box grows with its text, and the no-repo note only points above when a card is there", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
|
||||
s.post({ items: [confirmCard], agent: { status: "waiting" } });
|
||||
const note = itemCard(s.page, "y1").locator("textarea").first();
|
||||
await note.waitFor();
|
||||
const before = await note.evaluate((el) => el.offsetHeight);
|
||||
await note.fill(Array.from({ length: 8 }, (_, n) => `Line ${n + 1} of a longer note.`).join("\n"));
|
||||
const after = await note.evaluate((el) => el.offsetHeight);
|
||||
assert.ok(after > before + 40, `the note box grew with its text: ${before} to ${after}`);
|
||||
|
||||
// A folder that is no repository: the note points up only once there is a card up there.
|
||||
const bare = await openSession(await suite.browser(), { t, workflow: "git", payload: { reread: true, agent: { status: "waiting" } } });
|
||||
const aside = bare.page.locator(".git-note");
|
||||
await aside.waitFor();
|
||||
assert.match(await textOf(aside), /will ask what to do here in a moment/);
|
||||
bare.post({ items: [confirmCard], agent: { status: "waiting" } });
|
||||
await itemCard(bare.page, "y1").waitFor();
|
||||
assert.match(await textOf(aside), /asks above what to do/);
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
// Page tests for Help, the first-run Welcome and the update notice's modal. Run
|
||||
// with:
|
||||
// node --test scripts/test-web-console-page-help.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test. Help's prose stays untested; these cover how the dialog
|
||||
// behaves.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, tempProject, textOf, drawn } from "./page-test-helpers.mjs";
|
||||
import { HOME } from "./web-console-test-helpers.mjs";
|
||||
import { HELP_TABS } from "../src/web-console/public/help.js";
|
||||
import { CATALOG_GROUPS, SKILL_CATALOG } from "../src/web-console/public/answers.js";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// The console home's saved looks, shared by every session of this file. Each
|
||||
// test that cares sets it first and the file is removed once the test is done.
|
||||
const LOOKS_FILE = path.join(HOME, "looks.json");
|
||||
function savedLooks(t, looks) {
|
||||
if (looks) fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks }));
|
||||
else fs.rmSync(LOOKS_FILE, { force: true });
|
||||
t.after(() => fs.rmSync(LOOKS_FILE, { force: true }));
|
||||
}
|
||||
|
||||
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
|
||||
// A plan session on the person's turn: one text question and the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// The dashboard, past Planny's wake-up. The Welcome may be on top of it. The
|
||||
// wake-up plays once per tab, so a reloaded page has no intro to skip.
|
||||
async function toTheDashboard(s) {
|
||||
const heading = s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" });
|
||||
const skip = s.page.getByRole("button", { name: "Skip the intro" });
|
||||
await skip.or(heading).first().waitFor();
|
||||
if (await skip.isVisible()) await skip.click();
|
||||
await heading.waitFor();
|
||||
}
|
||||
|
||||
const helpModal = (s) => s.page.locator("#help-modal");
|
||||
const tabButton = (s, id) => s.page.locator("#help-tab-" + id);
|
||||
const selectedTab = (s) => s.page.locator('#help-tabs [role="tab"][aria-selected="true"]');
|
||||
const focusedId = (s) => s.page.evaluate(() => document.activeElement && document.activeElement.id);
|
||||
|
||||
async function openHelp(s) {
|
||||
await s.page.click("#btn-about");
|
||||
await helpModal(s).waitFor();
|
||||
}
|
||||
|
||||
test("Help opens on a tab, moves between tabs with the arrow, Home and End keys, and closes with Escape", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
// Built on first open: the tab buttons are not in the page before it.
|
||||
assert.equal(await s.page.locator("#help-tabs [role=tab]").count(), 0, "Help is built before it is opened");
|
||||
await openHelp(s);
|
||||
assert.equal(await s.page.locator("#help-tabs [role=tab]").count(), HELP_TABS.length, "one tab button per Help topic");
|
||||
|
||||
// A plain workflow page opens on the first topic, with focus on its tab.
|
||||
const ids = HELP_TABS.map((x) => x.id);
|
||||
assert.equal(await selectedTab(s).count(), 1, "exactly one tab is selected");
|
||||
assert.equal(await selectedTab(s).getAttribute("id"), "help-tab-" + ids[0]);
|
||||
assert.equal(await focusedId(s), "help-tab-" + ids[0], "focus starts on the selected tab");
|
||||
|
||||
// Roving focus: only the selected tab is in the tab order, and its panel is the one shown.
|
||||
const onlySelected = async (id) => {
|
||||
assert.equal(await selectedTab(s).getAttribute("id"), "help-tab-" + id);
|
||||
assert.equal(await focusedId(s), "help-tab-" + id, `focus is on ${id}`);
|
||||
assert.equal(await tabButton(s, id).getAttribute("tabindex"), "0");
|
||||
assert.equal(await s.page.locator('#help-tabs [role=tab][tabindex="0"]').count(), 1, "one tab stop");
|
||||
assert.equal(await s.page.locator("#help-panel-" + id).isVisible(), true, `${id}'s panel is shown`);
|
||||
assert.equal(await s.page.locator('#help-panels [role=tabpanel]:not([hidden])').count(), 1, "one panel is shown");
|
||||
};
|
||||
await onlySelected(ids[0]);
|
||||
await s.page.keyboard.press("ArrowDown");
|
||||
await onlySelected(ids[1]);
|
||||
await s.page.keyboard.press("ArrowRight");
|
||||
await onlySelected(ids[2]);
|
||||
await s.page.keyboard.press("ArrowUp");
|
||||
await onlySelected(ids[1]);
|
||||
await s.page.keyboard.press("End");
|
||||
await onlySelected(ids[ids.length - 1]);
|
||||
await s.page.keyboard.press("ArrowDown");
|
||||
await onlySelected(ids[0]);
|
||||
await s.page.keyboard.press("ArrowUp");
|
||||
await onlySelected(ids[ids.length - 1]);
|
||||
await s.page.keyboard.press("Home");
|
||||
await onlySelected(ids[0]);
|
||||
// A click picks a tab too.
|
||||
await tabButton(s, ids[3]).click();
|
||||
await onlySelected(ids[3]);
|
||||
|
||||
await s.page.keyboard.press("Escape");
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
assert.equal(await focusedId(s), "btn-about", "focus goes back to the Help button");
|
||||
// Reopened, the built dialog is reused: no second set of tabs.
|
||||
await openHelp(s);
|
||||
assert.equal(await s.page.locator("#help-tabs [role=tab]").count(), HELP_TABS.length);
|
||||
});
|
||||
|
||||
test("Help shows the live connection line and the version as a safe link to the Releases page", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openHelp(s);
|
||||
const live = s.page.locator("#about-live");
|
||||
assert.match(await textOf(live), /^Right now: both halves are talking to each other\./);
|
||||
assert.equal(await live.evaluate((n) => n.classList.contains("is-good")), true);
|
||||
|
||||
const link = s.page.locator("#help-version a");
|
||||
await link.waitFor();
|
||||
assert.match(await textOf(link), /^Plan2Code v\d+\.\d+\.\d+/, "the link names the installed version");
|
||||
assert.equal(await link.getAttribute("href"), RELEASES_URL);
|
||||
assert.equal(await link.getAttribute("rel"), "noopener noreferrer");
|
||||
assert.equal(await link.getAttribute("target"), "_blank");
|
||||
|
||||
// The line is written on open: a finished session says so the next time.
|
||||
await s.page.keyboard.press("Escape");
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
s.post({ finish: { headline: "The plan is written", command: "/plan2code-2-document" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "The plan is written" }).waitFor();
|
||||
await openHelp(s);
|
||||
assert.match(await textOf(live), /^Right now: the session is finished/);
|
||||
});
|
||||
|
||||
test("a click on Help's backdrop closes it, and a click inside it does not", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openHelp(s);
|
||||
await s.page.locator("#help-title").click();
|
||||
assert.equal(await helpModal(s).isVisible(), true, "a click inside closed Help");
|
||||
// The top-left corner of the page is the backdrop, well outside the dialog.
|
||||
await s.page.mouse.click(4, 4);
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
});
|
||||
|
||||
test("Ctrl+Enter does not send while Help is open, and sends once it is closed", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.locator('[data-item="q1"]').first().locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await openHelp(s);
|
||||
await s.page.keyboard.press("Control+Enter");
|
||||
await s.page.keyboard.press("Meta+Enter");
|
||||
assert.equal(s.wait(1).code === 0, false, "something was sent from behind Help");
|
||||
assert.equal(await helpModal(s).isVisible(), true, "the key closed Help");
|
||||
|
||||
await s.page.keyboard.press("Escape");
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
await s.page.keyboard.press("Control+Enter");
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "Ctrl+Enter sends nothing with Help closed");
|
||||
assert.deepEqual(
|
||||
got.actions.map(({ i, type }) => ({ i, type })),
|
||||
[{ i: "q1", type: "answer" }]
|
||||
);
|
||||
});
|
||||
|
||||
test("the Welcome shows on a first dashboard, saves that it was seen, and Help's Show the welcome again brings it back", async (t) => {
|
||||
savedLooks(t, null);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
|
||||
await toTheDashboard(s);
|
||||
const welcome = s.page.locator("#welcome-modal");
|
||||
await welcome.waitFor();
|
||||
assert.equal(await s.page.locator("#welcome-title").isVisible(), true);
|
||||
await s.page.getByRole("button", { name: "Start building" }).click();
|
||||
await welcome.waitFor({ state: "hidden" });
|
||||
// Saved with the other looks, so it holds for the next page too.
|
||||
await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).welcomeSeen === true);
|
||||
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await toTheDashboard(s);
|
||||
await s.page.waitForTimeout(800);
|
||||
assert.equal(await welcome.isVisible(), false, "the Welcome came back on a later page");
|
||||
|
||||
// Help's first topic offers it again, and Help steps aside for it.
|
||||
// (On the dashboard Help opens on the dashboard topic, so go to the first.)
|
||||
await openHelp(s);
|
||||
await tabButton(s, HELP_TABS[0].id).click();
|
||||
await s.page.getByRole("button", { name: "Show the welcome again" }).click();
|
||||
await welcome.waitFor();
|
||||
assert.equal(await helpModal(s).isVisible(), false, "Help stayed open under the Welcome");
|
||||
await s.page.keyboard.press("Escape");
|
||||
await welcome.waitFor({ state: "hidden" });
|
||||
});
|
||||
|
||||
test("the Welcome stays away when the person has seen it, and off the dashboard", async (t) => {
|
||||
const browser = await suite.browser();
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const seen = await openSession(browser, { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
|
||||
await toTheDashboard(seen);
|
||||
await seen.page.waitForTimeout(800);
|
||||
assert.equal(await seen.page.locator("#welcome-modal").isVisible(), false, "a seen Welcome showed again");
|
||||
|
||||
// Unseen, but a workflow page is not a first dashboard.
|
||||
savedLooks(t, null);
|
||||
const plan = await openSession(browser, { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await plan.page.waitForTimeout(800);
|
||||
assert.equal(await plan.page.locator("#welcome-modal").isVisible(), false, "the Welcome showed on a workflow page");
|
||||
});
|
||||
|
||||
test("Help's dashboard topic lists every card once, grouped and in the dashboard's order, by its Help line or blurb", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
|
||||
await toTheDashboard(s);
|
||||
await openHelp(s);
|
||||
await tabButton(s, "dashboard").click();
|
||||
const panel = s.page.locator("#help-panel-dashboard");
|
||||
await panel.waitFor();
|
||||
|
||||
// Read back as drawn: each group's heading, then its list's title and line.
|
||||
const drawnGroups = await panel.locator(".help-cards").evaluate((box) => {
|
||||
const out = [];
|
||||
for (const node of box.children) {
|
||||
if (node.tagName === "P") out.push({ title: node.textContent, cards: [] });
|
||||
else
|
||||
out.at(-1).cards.push(
|
||||
...[...node.children].map((li) => ({
|
||||
title: li.firstElementChild.textContent,
|
||||
line: li.textContent.slice(li.firstElementChild.textContent.length),
|
||||
}))
|
||||
);
|
||||
}
|
||||
return out;
|
||||
});
|
||||
const expected = CATALOG_GROUPS.map((g) => ({
|
||||
title: g.title,
|
||||
cards: SKILL_CATALOG.filter((e) => e.group === g.id).map((e) => ({ title: e.title + ".", line: " " + (e.help || e.blurb) })),
|
||||
}));
|
||||
assert.deepEqual(drawnGroups, expected);
|
||||
|
||||
// Each card's title and line appear exactly once in the whole topic.
|
||||
const text = await panel.evaluate((n) => n.textContent);
|
||||
const titles = await panel.locator(".help-cards li > strong").allTextContents();
|
||||
for (const e of SKILL_CATALOG) {
|
||||
assert.equal(titles.filter((x) => x === e.title + ".").length, 1, `${e.title} is listed once`);
|
||||
assert.equal(text.split(e.help || e.blurb).length - 1, 1, `${e.title}'s line appears once`);
|
||||
}
|
||||
// Built once: a second open adds no second list.
|
||||
await s.page.keyboard.press("Escape");
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
await openHelp(s);
|
||||
assert.equal(await panel.locator(".help-cards li").count(), SKILL_CATALOG.length);
|
||||
});
|
||||
|
||||
// A newer release on record, so a console that boots now has an update to
|
||||
// announce (the check reads this file for an hour instead of asking the
|
||||
// network). The file is put back as the suite had it.
|
||||
function aNewerReleaseExists(t) {
|
||||
const file = path.join(HOME, "update-check.json");
|
||||
const before = fs.readFileSync(file, "utf8");
|
||||
fs.writeFileSync(file, JSON.stringify({ checkedAt: Date.now(), latest: "99.0.0" }));
|
||||
t.after(() => fs.writeFileSync(file, before));
|
||||
}
|
||||
|
||||
test("the update banner opens a modal with the exact update commands, and its dismissal is remembered for the session", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
aNewerReleaseExists(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
|
||||
await toTheDashboard(s);
|
||||
const main = s.page.locator("#main");
|
||||
await main.getByRole("button", { name: /UPDATE AVAILABLE · v99\.0\.0/ }).click();
|
||||
|
||||
const modal = s.page.locator("#update-modal");
|
||||
await modal.waitFor();
|
||||
assert.match(await textOf(s.page.locator("#update-versions")), /^Version v99\.0\.0 is out/);
|
||||
const releases = s.page.locator("#update-versions a");
|
||||
assert.equal(await releases.getAttribute("href"), RELEASES_URL);
|
||||
assert.equal(await releases.getAttribute("rel"), "noopener noreferrer");
|
||||
assert.equal(await textOf(s.page.locator("#update-command code")), "plan2code update");
|
||||
assert.equal(
|
||||
await textOf(s.page.locator("#update-fallback code")),
|
||||
"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"
|
||||
);
|
||||
await s.page.locator("#update-done").click();
|
||||
await modal.waitFor({ state: "hidden" });
|
||||
|
||||
// The ×: gone now, remembered under this session's key, and still gone after a reload.
|
||||
await main.getByRole("button", { name: "Dismiss until next time" }).click();
|
||||
await main.getByRole("button", { name: /UPDATE AVAILABLE/ }).waitFor({ state: "hidden" });
|
||||
assert.equal(await s.page.evaluate((k) => sessionStorage.getItem(k), "p2c-update-dismissed:" + s.sid), "99.0.0");
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await toTheDashboard(s);
|
||||
assert.equal(await main.getByRole("button", { name: /UPDATE AVAILABLE/ }).count(), 0, "the banner came back after a reload");
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
// Page tests for User Preferences: the saved looks (highlight and theme), the
|
||||
// launcher's model menus and the Cleanup tab. Run with:
|
||||
// node --test scripts/test-web-console-page-prefs.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, textOf, drawn } from "./page-test-helpers.mjs";
|
||||
import { HOME, MODELS_DIR, backdate } from "./web-console-test-helpers.mjs";
|
||||
import { formatBytes } from "../src/web-console/public/answers.js";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A plan session on the person's turn: one text question and the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// The console home's saved looks are shared by every session of this file, so
|
||||
// each test starts with none and leaves none.
|
||||
const LOOKS_FILE = path.join(HOME, "looks.json");
|
||||
function noSavedLooks(t) {
|
||||
fs.rmSync(LOOKS_FILE, { force: true });
|
||||
t.after(() => fs.rmSync(LOOKS_FILE, { force: true }));
|
||||
}
|
||||
|
||||
const root = (s, attr) => s.page.evaluate((a) => document.documentElement.getAttribute(a), attr);
|
||||
// The highlight the page paints with: an inline override while it is not the default.
|
||||
const accentVar = (s) => s.page.evaluate(() => document.documentElement.style.getPropertyValue("--accent"));
|
||||
const swatch = (s, id) => s.page.locator(`#looks-swatches [data-accent="${id}"]`);
|
||||
|
||||
// The page as the server first sends it, before any script has run: the saved
|
||||
// theme and highlight are in the markup so a reload never flashes the defaults.
|
||||
async function firstPaintAttrs(s) {
|
||||
const html = await (await s.context.request.get(s.url)).text();
|
||||
const tag = html.match(/<html\b[^>]*>/i)[0];
|
||||
return { theme: tag.match(/data-theme="([^"]*)"/)?.[1] ?? null, accent: tag.match(/data-looks-accent="([^"]*)"/)?.[1] ?? null };
|
||||
}
|
||||
|
||||
test("the violet highlight and dark theme chosen in preferences stick across a reload, and Back to default clears them", async (t) => {
|
||||
noSavedLooks(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
assert.equal(await root(s, "data-theme"), null, "the theme starts on the system's");
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.locator("#looks-modal[open]").waitFor();
|
||||
await swatch(s, "violet").click();
|
||||
await s.page.locator('input[name="looks-theme"][value="dark"]').check();
|
||||
await s.page.waitForFunction(() => document.documentElement.getAttribute("data-theme") === "dark");
|
||||
assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "true");
|
||||
assert.equal(await accentVar(s), "#a785e2", "the dark violet is painted");
|
||||
// Saved on the server (looks.json), not only in this tab.
|
||||
await s.page.waitForFunction(async () => {
|
||||
const saved = (await (await fetch("/looks")).json()).looks || {};
|
||||
return saved.accent === "violet" && saved.theme === "dark";
|
||||
});
|
||||
await s.page.click("#looks-done");
|
||||
|
||||
// What the server sends first, and what the page settles on, both keep the choice.
|
||||
assert.deepEqual(await firstPaintAttrs(s), { theme: "dark", accent: "violet" }, "the first paint carries the saved looks");
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
assert.equal(await root(s, "data-theme"), "dark", "the theme did not stick");
|
||||
await s.page.waitForFunction(() => document.documentElement.style.getPropertyValue("--accent") === "#a785e2");
|
||||
await s.page.click("#btn-looks");
|
||||
assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "true", "the violet swatch is not the chosen one after a reload");
|
||||
assert.equal(await s.page.locator('input[name="looks-theme"][value="dark"]').isChecked(), true);
|
||||
|
||||
// Back to default returns both, here and for the next page.
|
||||
await s.page.click("#looks-reset");
|
||||
await s.page.waitForFunction(() => !document.documentElement.hasAttribute("data-theme"));
|
||||
assert.equal(await accentVar(s), "", "the chosen highlight is still painted");
|
||||
assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "false");
|
||||
assert.equal(await s.page.locator('input[name="looks-theme"][value="system"]').isChecked(), true);
|
||||
await s.page.waitForFunction(async () => {
|
||||
const saved = (await (await fetch("/looks")).json()).looks || {};
|
||||
return saved.theme === "system" && saved.accent !== "violet";
|
||||
});
|
||||
assert.deepEqual(await firstPaintAttrs(s), { theme: null, accent: null }, "the first paint still carries the old looks");
|
||||
});
|
||||
|
||||
test("the launcher's model menus have Claude, Devin and Codex tabs, and a model id typed on the Codex tab is saved", async (t) => {
|
||||
noSavedLooks(t);
|
||||
// The file the launcher reads: put back as the suite had it (no file).
|
||||
t.after(() => fs.rmSync(path.join(MODELS_DIR, "models.json"), { force: true }));
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-looks");
|
||||
const tabs = s.page.getByRole("group", { name: "Which agent" });
|
||||
for (const name of ["Claude", "Devin", "Codex"]) assert.equal(await tabs.getByRole("button", { name, exact: true }).count(), 1, `a ${name} tab`);
|
||||
const pressed = async () => (await tabs.locator('button[aria-pressed="true"]').allInnerTexts()).map((x) => x.trim());
|
||||
assert.deepEqual(await pressed(), ["Claude"], "the menus open on Claude");
|
||||
|
||||
await tabs.getByRole("button", { name: "Codex", exact: true }).click();
|
||||
assert.deepEqual(await pressed(), ["Codex"]);
|
||||
await s.page.click("#models-add");
|
||||
const id = s.page.locator("#models-user").getByRole("textbox", { name: "Model id" });
|
||||
await id.fill("gpt-test-codex-1");
|
||||
await id.press("Tab");
|
||||
await s.page.locator("#models-status").filter({ hasText: /^Saved\./ }).waitFor();
|
||||
const saved = await s.page.evaluate(async () => (await (await fetch("/models")).json()).user);
|
||||
assert.deepEqual(saved.codex.map((m) => m.id), ["gpt-test-codex-1"], "the id was not saved under Codex");
|
||||
assert.deepEqual([saved.claude, saved.devin], [[], []], "the id leaked into another agent's menu");
|
||||
|
||||
// Back on Claude the typed id is not listed; on Codex it is, after a reload.
|
||||
await tabs.getByRole("button", { name: "Claude", exact: true }).click();
|
||||
assert.equal(await s.page.locator("#models-user .models-row").count(), 0);
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.locator("#models-tab-codex").click();
|
||||
await s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }).waitFor();
|
||||
assert.equal(await s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }).inputValue(), "gpt-test-codex-1");
|
||||
});
|
||||
|
||||
test("Cleanup scans the console home and lists an old session folder with its size", async (t) => {
|
||||
noSavedLooks(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
// Made after the session opens: opening sweeps old sessions away. A session
|
||||
// is old when nothing in it has been touched for 30 days.
|
||||
const sid = "20250801-101010-aaaaaa";
|
||||
const dir = path.join(HOME, "sessions", sid);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const state = path.join(dir, "state.json");
|
||||
fs.writeFileSync(state, "x".repeat(3000));
|
||||
backdate(state);
|
||||
backdate(dir);
|
||||
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
await s.page.click("#btn-looks");
|
||||
const list = s.page.locator("#cleanup-list");
|
||||
assert.equal(await list.locator(".cleanup-row").count(), 0, "Cleanup lists things before a scan");
|
||||
assert.equal(await s.page.locator("#cleanup-delete").isHidden(), true, "Delete is offered before a scan");
|
||||
await s.page.click("#cleanup-scan");
|
||||
const row = list.locator(".cleanup-row").filter({ hasText: sid });
|
||||
await row.waitFor();
|
||||
assert.match(await textOf(row), new RegExp(`^Session ${sid}`));
|
||||
const size = await textOf(row.locator(".cleanup-size"));
|
||||
assert.match(size, /^\d/, "the row names a size");
|
||||
assert.ok(size === formatBytes(3000) || /^[\d.,]+\s*(kB|KB|MB|B)\b/.test(size), `the size reads as a size: ${size}`);
|
||||
assert.match(await textOf(list.locator(".cleanup-summary")), /1 old session/);
|
||||
assert.match(await textOf(s.page.locator("#cleanup-status")), /^Found \d+ items?\./);
|
||||
assert.equal(await s.page.locator("#cleanup-delete").isVisible(), true, "Delete these is offered once something is found");
|
||||
// The scan only looks.
|
||||
assert.equal(fs.existsSync(dir), true, "a scan deleted the folder");
|
||||
|
||||
// Closing preferences forgets the scan: a reopened dialog starts clean.
|
||||
await s.page.click("#looks-done");
|
||||
await s.page.click("#btn-looks");
|
||||
assert.equal(await list.locator(".cleanup-row").count(), 0, "the old scan is still listed");
|
||||
assert.equal(await s.page.locator("#cleanup-delete").isHidden(), true);
|
||||
});
|
||||
@@ -0,0 +1,609 @@
|
||||
// Page tests for how a session ends and comes back: the finished screen and
|
||||
// its buttons, Stop and Stop with a handoff, and a page that loses its server
|
||||
// and finds it again after a resume. Run with:
|
||||
// node --test scripts/test-web-console-page-session.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pageSuite, openSession, itemCard, drawn, textOf, tempProject } from "./page-test-helpers.mjs";
|
||||
import { cli, until } from "./web-console-test-helpers.mjs";
|
||||
import { STOP_HANDOFF_REPLY, HOME_REPLY } from "../src/web-console/public/answers.js";
|
||||
// How long the page waits without contact before it calls itself offline:
|
||||
// the page's own constant, so this file never drifts from it.
|
||||
import { GONE_AFTER_MS } from "../src/web-console/public/screens/core.js";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
|
||||
// The banner the page raises when it loses its server mid-session.
|
||||
const LOST_CONTACT = /Lost contact with Plan2Code\. Nothing you have typed is lost\./;
|
||||
|
||||
// A plan session on the person's turn, the way an agent opens one: one text
|
||||
// question and the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// The agent's side of `stop`, leaving the browser context open (s.stop()
|
||||
// closes it, which would hide what the page does next).
|
||||
async function stopServer(s) {
|
||||
cli(["stop", "--session", s.sid], { cwd: s.project });
|
||||
assert.ok(await until(async () => !(await s.answers()), 5000), "the server still answers after stop");
|
||||
}
|
||||
|
||||
// The one send `wait` hands the agent; fails the test when nothing arrived.
|
||||
function collect(s) {
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
// Local helper: checks `fn` keeps returning true for `ms`. A sleep would
|
||||
// prove nothing; this fails the moment the page shows what it must not.
|
||||
async function holds(fn, ms) {
|
||||
const end = Date.now() + ms;
|
||||
while (Date.now() < end) {
|
||||
if (!(await fn())) return false;
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
test("the finished screen shows the next command with --web, copies it, turns Send off, and Back to the dashboard reaches the agent", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.context.grantPermissions(["clipboard-read", "clipboard-write"], { origin: new URL(s.url).origin });
|
||||
s.post({
|
||||
settle: true,
|
||||
finish: {
|
||||
headline: "The plan is written",
|
||||
body: "Everything is under `specs/audit-export/`. Read `PLAN.md` first.",
|
||||
command: "/plan2code-2-document",
|
||||
dashboard: true,
|
||||
},
|
||||
});
|
||||
const main = s.page.locator("#main");
|
||||
await main.getByRole("heading", { name: "The plan is written" }).waitFor();
|
||||
|
||||
const shown = main.locator("code").filter({ hasText: /^\/plan2code-2-document --web$/ });
|
||||
assert.equal(await shown.count(), 1, "the command is shown once, with --web appended");
|
||||
// The Copy that belongs to this command: the innermost block holding both,
|
||||
// whatever wraps them.
|
||||
// (`has` is matched inside each candidate, so these start from the page.)
|
||||
const code = s.page.locator("code").filter({ hasText: /^\/plan2code-2-document --web$/ });
|
||||
const copy = s.page.getByRole("button", { name: "Copy", exact: true });
|
||||
await main.locator("*", { has: code }).filter({ has: copy }).last().getByRole("button", { name: "Copy", exact: true }).click();
|
||||
await s.page.waitForFunction(async () => (await navigator.clipboard.readText()) === "/plan2code-2-document --web");
|
||||
assert.equal(await s.page.evaluate(() => navigator.clipboard.readText()), "/plan2code-2-document --web");
|
||||
|
||||
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "Send is still on after the finish");
|
||||
|
||||
await main.getByRole("button", { name: "Back to the dashboard" }).click();
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
assert.deepEqual(
|
||||
got.actions.map(({ i, type }) => ({ i, type })),
|
||||
[{ i: "__dashboard", type: "dashboard" }]
|
||||
);
|
||||
});
|
||||
|
||||
// What a person sees break: no Continue here on a finish that names a skill, one
|
||||
// beside a git command or a pause, one at the red meter level, or a press that
|
||||
// reaches the agent as anything but the dashboard's own launch.
|
||||
test("Continue here shows beside a skill's next step while the meter is not red and sends a launch with the skill and spec", async (t) => {
|
||||
const browser = await suite.browser();
|
||||
const next = { headline: "The plan is documented", command: "/plan2code-3-implement specs/audit-export/overview.md", dashboard: true };
|
||||
const s = await openSession(browser, { t, workflow: "document", payload: { agent: { status: "working", activity: "Writing" } } });
|
||||
s.post({ finish: next });
|
||||
const main = s.page.locator("#main");
|
||||
const go = main.getByRole("button", { name: "Continue here" });
|
||||
await go.waitFor();
|
||||
assert.equal(await go.count(), 1);
|
||||
|
||||
await go.click();
|
||||
const got = collect(s);
|
||||
assert.deepEqual(got.actions, [
|
||||
{ i: "__launch", type: "launch", skill: "plan2code-3-implement", workflow: "implement", spec: "specs/audit-export" },
|
||||
]);
|
||||
assert.equal(got.reply, "Start Implement (/plan2code-3-implement) for specs/audit-export, right here in this session.");
|
||||
// The hop's resume is the dashboard's: the skill's workflow and the spec.
|
||||
assert.match(got.resume, /--workflow implement --spec specs\/audit-export$/);
|
||||
await main.getByRole("button", { name: "Starting the next step…" }).waitFor();
|
||||
assert.equal(await main.getByRole("button", { name: "Back to the dashboard" }).isDisabled(), true, "one press locks the other buttons");
|
||||
|
||||
// No skill to continue into: a git command, or a pause.
|
||||
const git = await openSession(browser, { t, workflow: "quick-task", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
git.post({ finish: { headline: "Quick task done", command: "git add -A && git commit -m x -m y", dashboard: true } });
|
||||
await git.page.locator("#main").getByRole("heading", { name: "Quick task done" }).waitFor();
|
||||
assert.equal(await git.page.getByRole("button", { name: "Continue here" }).count(), 0, "a git command is not a skill");
|
||||
const paused = await openSession(browser, { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
paused.post({ finish: { headline: "Paused at Phase 2", command: "/plan2code-3-implement specs/audit-export/overview.md" } });
|
||||
await paused.page.locator("#main").getByRole("heading", { name: "Paused at Phase 2" }).waitFor();
|
||||
assert.equal(await paused.page.getByRole("button", { name: "Continue here" }).count(), 0, "a pause is not continued");
|
||||
});
|
||||
|
||||
test("Update CHANGELOG first shows beside Commit it now only when the finish asks for it, and sends __changelog", async (t) => {
|
||||
const browser = await suite.browser();
|
||||
const base = { headline: "Quick task done", command: "git add -A && git commit -m x -m y", commit: true, dashboard: true };
|
||||
const plain = await openSession(browser, { t, workflow: "quick-task", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
plain.post({ finish: base });
|
||||
await plain.page.locator("#main").getByRole("button", { name: "Commit it now" }).waitFor();
|
||||
assert.equal(await plain.page.getByRole("button", { name: "Update CHANGELOG first" }).count(), 0, "no flag, no button");
|
||||
|
||||
const s = await openSession(browser, { t, workflow: "quick-task", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
s.post({ finish: { ...base, changelog: true } });
|
||||
const main = s.page.locator("#main");
|
||||
const go = main.getByRole("button", { name: "Update CHANGELOG first" });
|
||||
await go.waitFor();
|
||||
assert.equal(await main.getByRole("button", { name: "Commit it now" }).count(), 1);
|
||||
await go.click();
|
||||
assert.deepEqual(collect(s).actions.map(({ i, type }) => ({ i, type })), [{ i: "__changelog", type: "changelog" }]);
|
||||
await main.getByRole("button", { name: "Opening Changelog…" }).waitFor();
|
||||
assert.equal(await main.getByRole("button", { name: "Commit it now" }).isDisabled(), true, "one press locks the other buttons");
|
||||
});
|
||||
|
||||
test("Continue here is hidden once the session meter is red, and the command and fresh-session advice stay", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
// Ten points: a thirty-task phase scores ten, the red level.
|
||||
s.post({ run: { event: "implement-phase", id: "phase-1", tasks: 30 } });
|
||||
await s.page.locator("#meter-pill[data-level='red']").waitFor();
|
||||
s.post({ finish: { headline: "Phase 1 is done", command: "/plan2code-3-implement specs/audit-export/overview.md", dashboard: true } });
|
||||
const main = s.page.locator("#main");
|
||||
await main.getByRole("heading", { name: "Phase 1 is done" }).waitFor();
|
||||
assert.equal(await main.getByRole("button", { name: "Continue here" }).count(), 0, "Continue here at red");
|
||||
assert.ok(await main.locator("code").filter({ hasText: /^\/plan2code-3-implement specs\/audit-export\/overview\.md --web$/ }).count(), "the command stays");
|
||||
assert.equal(await closeGuide(s).count(), 1, "the fresh-session advice stays");
|
||||
});
|
||||
|
||||
test("Stop session, confirmed, sends __stop with no handoff", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-stop");
|
||||
await s.page.locator("#stop-go").click();
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
const stop = got.actions.find((a) => a.i === "__stop");
|
||||
assert.deepEqual(stop, { i: "__stop", type: "stop" });
|
||||
});
|
||||
|
||||
test("Stop with a handoff sends __stop with handoff, and the paused finish and stop that follow end on the paused screen, not an error", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-stop");
|
||||
const handoff = s.page.locator("#stop-handoff");
|
||||
assert.equal(await handoff.isVisible(), true, "the handoff choice is offered off the dashboard");
|
||||
await handoff.click();
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
const stop = got.actions.find((a) => a.i === "__stop");
|
||||
assert.deepEqual(stop, { i: "__stop", type: "stop", handoff: true });
|
||||
|
||||
// What the agent does next (console-stop.md): a paused finish without
|
||||
// --wait and no dashboard, then `stop`.
|
||||
s.post({
|
||||
settle: true,
|
||||
finish: {
|
||||
headline: "Paused at the naming question",
|
||||
body: "Your place is saved, and a handoff is waiting on the dashboard. The naming question is still open.",
|
||||
command: "/plan2code-1-plan",
|
||||
},
|
||||
});
|
||||
const main = s.page.locator("#main");
|
||||
await main.getByRole("heading", { name: "Paused at the naming question" }).waitFor();
|
||||
await stopServer(s);
|
||||
|
||||
// The page needs GONE_AFTER_MS without contact before it would call the
|
||||
// server lost. Through that window and past it, the paused screen stays.
|
||||
const settled = async () =>
|
||||
!LOST_CONTACT.test(await s.page.locator("#banner").innerText()) &&
|
||||
!(await s.page.locator("#planny").getAttribute("class")).includes("is-gone");
|
||||
assert.ok(await holds(settled, GONE_AFTER_MS + 3000), "the page raised a lost-contact state after a paused finish");
|
||||
assert.match(await main.innerText(), /Session paused/i);
|
||||
assert.match(await textOf(s.page.locator("#agent-text")), /^Paused\./);
|
||||
assert.ok(await main.locator("code").filter({ hasText: /^\/plan2code-1-plan --web$/ }).count(), "the resume command is gone");
|
||||
});
|
||||
|
||||
test("a page that loses its server goes offline, and after a resume it shows the session again with the unsent answer still typed", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const field = () => itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
|
||||
await field().fill("audit-export");
|
||||
// Typed, not sent: the page mirrors it to the server's draft.json, which
|
||||
// is what a page on a new port reads back (localStorage is per origin).
|
||||
const draftFile = path.join(s.session, "draft.json");
|
||||
assert.ok(
|
||||
await until(() => fs.existsSync(draftFile) && fs.readFileSync(draftFile, "utf8").includes("audit-export"), 5000),
|
||||
"the typed answer never reached the server's draft"
|
||||
);
|
||||
|
||||
await stopServer(s);
|
||||
await s.page.waitForFunction(() => document.getElementById("planny").classList.contains("is-gone"), null, {
|
||||
timeout: GONE_AFTER_MS + 10000,
|
||||
});
|
||||
assert.match(await textOf(s.page.locator("#agent-text")), /^Not connected\. Your answers are saved\./);
|
||||
assert.match(await s.page.locator("#banner").innerText(), LOST_CONTACT);
|
||||
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "Send is on with no server");
|
||||
|
||||
const resumed = cli(["open", "--resume", s.sid, "--workflow", "plan", "--no-open"], { cwd: s.project }).json;
|
||||
assert.ok(resumed && resumed.url, "the resume printed no url");
|
||||
await s.page.goto(resumed.url, { waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await itemCard(s.page, "q1").getByText("What to call it").first().waitFor();
|
||||
assert.equal(await field().inputValue(), "audit-export", "the unsent answer was lost across the resume");
|
||||
assert.equal(await s.page.locator("#planny").evaluate((n) => n.classList.contains("is-gone")), false);
|
||||
});
|
||||
|
||||
// The status line beside Planny, and its "What to check" button when it has
|
||||
// one. The button opens Help on the stuck tab.
|
||||
const statusLine = (s) => s.page.locator("#agent-text");
|
||||
const whatToCheck = (s) => statusLine(s).getByRole("button", { name: "What to check" });
|
||||
async function lineSays(s, re) {
|
||||
await s.page.waitForFunction((src) => new RegExp(src).test(document.getElementById("agent-text").textContent), re.source, { timeout: 10000 });
|
||||
return textOf(statusLine(s));
|
||||
}
|
||||
|
||||
test("the quiet, not running and not connected lines offer What to check, opening Help on the stuck tab, and the plain lines do not", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
clock: true,
|
||||
payload: { headline: { stage: "Phase 1", cleared: 0, total: 3 }, agent: { status: "working", activity: "Task 1 of 3: the reader" } },
|
||||
});
|
||||
// Working, and heard from just now: the plain working line.
|
||||
await lineSays(s, /Task 1 of 3: the reader/);
|
||||
assert.equal(await whatToCheck(s).count(), 0, "the working line is plain");
|
||||
// Quiet for 30 s: the approval hint, with the button.
|
||||
await s.page.clock.fastForward(40_000);
|
||||
await lineSays(s, /waiting on an approval in your terminal/);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the approval hint carries What to check");
|
||||
// Quiet for two minutes: still working, and the button stays.
|
||||
await s.page.clock.fastForward(100_000);
|
||||
await lineSays(s, /^Still working on it\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the quiet working line carries What to check");
|
||||
|
||||
// Back to real time, and the agent asks something: the person's turn is plain.
|
||||
await s.page.clock.setSystemTime(Date.now());
|
||||
s.post({ items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } });
|
||||
await lineSays(s, /^Your turn: 1 question waiting\./);
|
||||
assert.equal(await whatToCheck(s).count(), 0, "the your-turn line is plain");
|
||||
// Nobody listening for three minutes: not running, with the button.
|
||||
await s.page.clock.fastForward(200_000);
|
||||
await lineSays(s, /^Plan2Code is not running right now\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the not running line carries What to check");
|
||||
await whatToCheck(s).click();
|
||||
await s.page.locator("#help-modal[open]").waitFor();
|
||||
assert.equal(await s.page.locator("#help-tab-stuck").getAttribute("aria-selected"), "true", "Help opened on the stuck tab");
|
||||
await s.page.keyboard.press("Escape");
|
||||
await s.page.locator("#help-modal[open]").waitFor({ state: "detached" });
|
||||
|
||||
// Answered and sent, never collected, and nobody listening: the saved line.
|
||||
await s.page.clock.setSystemTime(Date.now());
|
||||
s.post({ agent: { status: "waiting" } });
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
await lineSays(s, /^Sent\. Waiting for Plan2Code\./);
|
||||
assert.equal(await whatToCheck(s).count(), 0, "the sent line is plain");
|
||||
await s.page.clock.fastForward(200_000);
|
||||
await lineSays(s, /^Plan2Code is not running\. Your answers are saved and waiting for it\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the saved-and-waiting line carries What to check");
|
||||
|
||||
// No server at all: not connected, with the button.
|
||||
await stopServer(s);
|
||||
for (let i = 0; i < 20 && !(await s.page.locator("#planny.is-gone").count()); i++) {
|
||||
await s.page.clock.fastForward(GONE_AFTER_MS);
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
await lineSays(s, /^Not connected\. Your answers are saved\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the not connected line carries What to check");
|
||||
});
|
||||
|
||||
test("an answered finish offer comes back unanswered on a later finish, once the first finish has gone", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
const finishWith = (headline) => s.post({ finish: { headline, command: "/plan2code-3-implement specs/audit-export/overview.md", dashboard: true } });
|
||||
const main = s.page.locator("#main");
|
||||
finishWith("Phase 1 is done");
|
||||
await main.getByRole("heading", { name: "Phase 1 is done" }).waitFor();
|
||||
await main.getByRole("button", { name: "Back to the dashboard" }).click();
|
||||
assert.deepEqual(collect(s).actions.map(({ i }) => i), ["__dashboard"]);
|
||||
await lineSays(s, /^Opening the dashboard…/);
|
||||
// The agent takes the press somewhere that clears the finish, and a later
|
||||
// phase ends: that finish starts with its own offer unanswered.
|
||||
s.post({ finish: null, agent: { status: "working", activity: "Task 1 of 1" } });
|
||||
await lineSays(s, /Task 1 of 1/);
|
||||
finishWith("Phase 2 is done");
|
||||
await main.getByRole("heading", { name: "Phase 2 is done" }).waitFor();
|
||||
await lineSays(s, /^Done\. Head back to the dashboard, or close this tab\./);
|
||||
assert.equal(await main.getByRole("button", { name: "Back to the dashboard" }).count(), 1, "the later finish offers the way back again");
|
||||
});
|
||||
|
||||
test("a finished session never puts a sent answer back on its form", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await itemCard(s.page, "q1").locator("textarea").fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
collect(s);
|
||||
// Collected and left open, then the session ends: nothing more can be sent,
|
||||
// so the answer stays sent rather than coming back to edit. It would show
|
||||
// once the finish goes away (a review taken up), as an answer ready to send.
|
||||
s.post({ finish: { headline: "The plan is written", command: "/plan2code-2-document" }, agent: { status: "waiting" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "The plan is written" }).waitFor();
|
||||
s.post({ finish: null, agent: { status: "waiting" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "The plan is written" }).waitFor({ state: "detached" });
|
||||
const q1 = s.page.locator("#sidebar").getByRole("button", { name: /What to call it/ });
|
||||
await q1.click();
|
||||
await itemCard(s.page, "q1").waitFor();
|
||||
const mark = q1.locator(".rail-mark");
|
||||
assert.notEqual(await mark.getAttribute("title"), "ready to send", "the sent answer came back on the form");
|
||||
const box = itemCard(s.page, "q1").locator("textarea");
|
||||
assert.notEqual((await box.count()) ? await box.inputValue() : "", "audit-export", "the sent answer is back in its box");
|
||||
});
|
||||
|
||||
test("the footer keeps its workspace label on the dashboard, and the label opens the Workspace dialog", async (t) => {
|
||||
const project = tempProject();
|
||||
const name = path.basename(project);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", project });
|
||||
// Past Planny's wake-up and, on this console home's first run, the Welcome.
|
||||
await s.page.getByRole("button", { name: "Skip the intro" }).click();
|
||||
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
const foot = s.page.locator("footer.footer");
|
||||
const where = s.page.locator("#footer-where");
|
||||
await where.waitFor();
|
||||
// The dashboard drops the summary and Send, never the label.
|
||||
assert.equal(await foot.evaluate((f) => f.classList.contains("is-dash")), true, "the dashboard's footer is marked is-dash");
|
||||
assert.equal(await s.page.locator("#footer-summary").isVisible(), false, "the summary shows on the dashboard");
|
||||
assert.equal(await s.page.locator("#btn-send").isVisible(), false, "Send shows on the dashboard");
|
||||
assert.match(await textOf(where), new RegExp(`^${name}`), "the label names the project");
|
||||
assert.equal(await where.getAttribute("title"), "Open workspace");
|
||||
assert.match(await where.getAttribute("aria-label"), new RegExp(`^Open workspace: ${name}`));
|
||||
// A click opens the Workspace dialog on the session's folders; leaving the
|
||||
// label leaves it as it was (no copied state to undo).
|
||||
await where.click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor();
|
||||
assert.match(await textOf(s.page.locator("#workspace-list")), new RegExp(name));
|
||||
await s.page.keyboard.press("Escape");
|
||||
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
|
||||
await s.page.locator("body").click({ position: { x: 5, y: 5 } });
|
||||
assert.match(await textOf(where), new RegExp(`^${name}`), "the label changed after a click away");
|
||||
});
|
||||
|
||||
test("a workflow page uses its modules: the full footer, the session meter, @ suggestions and the tab icon", async (t) => {
|
||||
const project = tempProject();
|
||||
const name = path.basename(project);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", project, payload: PLAN_QUESTION });
|
||||
// Off the dashboard the footer is whole (workspace.js names the label).
|
||||
assert.equal(await s.page.locator("footer.footer").evaluate((f) => f.classList.contains("is-dash")), false);
|
||||
assert.equal(await s.page.locator("#btn-send").isVisible(), true);
|
||||
// meter.js: the pill shows once a frame carries the meter.
|
||||
await s.page.locator("#meter-pill").waitFor();
|
||||
assert.ok((await textOf(s.page.locator("#meter-words"))).length, "the meter pill has no words");
|
||||
// mentions.js: an @ in a text box offers the workspace's folders.
|
||||
const box = itemCard(s.page, "q1").locator("textarea");
|
||||
await box.click();
|
||||
await box.pressSequentially("See @");
|
||||
await s.page.locator("#mention-pop").waitFor();
|
||||
assert.match(await textOf(s.page.locator("#mention-pop")), new RegExp(name));
|
||||
// favicon.js: the person's move puts a bar on the tab icon.
|
||||
await s.page.waitForFunction(() => document.querySelector('link[rel="icon"][type="image/svg+xml"]').href.startsWith("data:image/svg+xml"));
|
||||
});
|
||||
|
||||
// The dashboard, past Planny's wake-up and the first-run Welcome.
|
||||
async function pastTheIntro(s) {
|
||||
const skip = s.page.getByRole("button", { name: "Skip the intro" });
|
||||
await skip.click();
|
||||
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
}
|
||||
|
||||
// What a person sees break: a handoff offered where there is nothing to hand off.
|
||||
test("the stop dialog offers a handoff in a workflow and one plain Stop on the dashboard", async (t) => {
|
||||
const plan = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" }, items: PLAN_QUESTION.items } });
|
||||
await plan.page.click("#btn-stop");
|
||||
const modal = plan.page.locator("#stop-modal");
|
||||
await modal.waitFor();
|
||||
assert.match(await textOf(modal), /Stop with a handoff/);
|
||||
assert.match(await textOf(modal.locator("#stop-go")), /Just stop and save/);
|
||||
|
||||
const dash = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } } });
|
||||
await pastTheIntro(dash);
|
||||
await dash.page.click("#btn-stop");
|
||||
await dash.page.locator("#stop-modal").waitFor();
|
||||
assert.equal(await dash.page.locator("#stop-handoff").isVisible(), false, "the dashboard offers a handoff");
|
||||
assert.match(await textOf(dash.page.locator("#stop-go")), /Stop\s+Ends the console session\./);
|
||||
assert.doesNotMatch(await textOf(dash.page.locator("#stop-modal")), /Stop with a handoff/);
|
||||
});
|
||||
|
||||
// What the agent would misread: a handoff stop that carries the plain stop's words.
|
||||
test("Stop with a handoff sends its own reply line beside the stop, and a plain stop sends another", async (t) => {
|
||||
const handoff = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" }, items: PLAN_QUESTION.items } });
|
||||
await handoff.page.click("#btn-stop");
|
||||
await handoff.page.locator("#stop-handoff").click();
|
||||
const got = collect(handoff);
|
||||
assert.deepEqual(got.actions.find((a) => a.i === "__stop"), { i: "__stop", type: "stop", handoff: true });
|
||||
assert.ok(got.reply.includes(STOP_HANDOFF_REPLY), `the handoff stop's words: ${got.reply}`);
|
||||
|
||||
const plain = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" }, items: PLAN_QUESTION.items } });
|
||||
await plain.page.click("#btn-stop");
|
||||
await plain.page.locator("#stop-go").click();
|
||||
const sent = collect(plain);
|
||||
assert.equal(sent.actions.find((a) => a.i === "__stop").handoff, undefined);
|
||||
assert.ok(!sent.reply.includes(STOP_HANDOFF_REPLY), "a plain stop asked for a handoff");
|
||||
});
|
||||
|
||||
// A finish that offers a review, a commit and the dashboard, on a build.
|
||||
const OFFERS = { headline: "Quick task done", command: "/plan2code-5-git", review: true, commit: true, dashboard: true };
|
||||
const closeGuide = (s) => s.page.getByRole("region", { name: "Before you close this" });
|
||||
|
||||
// What a person sees break: "Safe to close" printed under "Review requested", or the review offer coming back after a reload.
|
||||
test("Before you close this shows while a review is on offer, goes while it is asked, and the asked offer stays locked after a reload", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "quick-task", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
s.post({ finish: OFFERS });
|
||||
const main = s.page.locator("#main");
|
||||
const reviewNow = main.getByRole("button", { name: "Review it now" });
|
||||
await reviewNow.waitFor();
|
||||
assert.equal(await closeGuide(s).count(), 1, "a review only on offer must not hide the guide");
|
||||
assert.match(await textOf(main), /The review is optional\./);
|
||||
|
||||
await reviewNow.click();
|
||||
const got = collect(s);
|
||||
assert.deepEqual(got.actions.map(({ i, type }) => ({ i, type })), [{ i: "__review", type: "review" }]);
|
||||
await main.getByRole("button", { name: "Review requested…" }).waitFor();
|
||||
assert.equal(await closeGuide(s).count(), 0, "the guide shows while a review is starting");
|
||||
assert.equal(await main.getByRole("button", { name: "No thanks, I am done" }).count(), 0);
|
||||
|
||||
// The press is remembered: the buttons do not come back on a reload.
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await main.getByRole("button", { name: "Review requested…" }).waitFor();
|
||||
assert.equal(await main.getByRole("button", { name: "Review it now" }).count(), 0);
|
||||
assert.equal(await closeGuide(s).count(), 0, "the guide came back on a reload");
|
||||
});
|
||||
|
||||
// What a person sees break: the guide missing while a commit or the dashboard
|
||||
// is starting (it would say "start a new one" under "Opening Git"), or missing
|
||||
// once they said they are done or the server is gone.
|
||||
test("Before you close this goes while a commit or the dashboard is starting, and stays once they are done or the server is gone", async (t) => {
|
||||
const browser = await suite.browser();
|
||||
const finishPage = async (opts) => {
|
||||
const s = await openSession(browser, { t, workflow: "quick-task", ...opts, payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
s.post({ finish: OFFERS });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "Quick task done" }).waitFor();
|
||||
assert.equal(await closeGuide(s).count(), 1, "a plain finish shows the guide");
|
||||
return s;
|
||||
};
|
||||
const cases = [
|
||||
["Commit it now", "__commit", "Opening Git…", 0],
|
||||
["Back to the dashboard", "__dashboard", "Opening the dashboard…", 0],
|
||||
["No thanks, I am done", "__done", null, 1],
|
||||
];
|
||||
for (const [button, id, asked, guides] of cases) {
|
||||
const s = await finishPage({});
|
||||
await s.page.locator("#main").getByRole("button", { name: button }).click();
|
||||
assert.deepEqual(collect(s).actions.map((a) => a.i), [id]);
|
||||
if (asked) await s.page.locator("#main").getByRole("button", { name: asked }).waitFor();
|
||||
assert.equal(await closeGuide(s).count(), guides, `the guide after ${button}`);
|
||||
}
|
||||
// A review asked, then the server gone: nothing is starting any more.
|
||||
const gone = await finishPage({ clock: true });
|
||||
await gone.page.locator("#main").getByRole("button", { name: "Review it now" }).click();
|
||||
collect(gone);
|
||||
assert.equal(await closeGuide(gone).count(), 0);
|
||||
await stopServer(gone);
|
||||
for (let i = 0; i < 20 && !(await gone.page.locator("#planny.is-gone").count()); i++) {
|
||||
await gone.page.clock.fastForward(GONE_AFTER_MS);
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
await closeGuide(gone).waitFor();
|
||||
});
|
||||
|
||||
// What a person sees break: a finished screen with no Before you close this,
|
||||
// a pause that promises the wrong thing, or the guide's own text going wrong.
|
||||
test("every finished shape shows Before you close this with its three rows, and a pause names the resume command", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
const main = s.page.locator("#main");
|
||||
const shapes = [
|
||||
["A skill next", { command: "/plan2code-4-finalize" }, /A new session starts from clean context/, /Paste the command above in the new session, or start from the dashboard with \/plan2code\./],
|
||||
["A terminal command next", { command: "git status" }, /A new session starts from clean context/, /Run the command above in your terminal, then start the next step/],
|
||||
["Nothing left", {}, /A new session starts from clean context/, /In the new session, start from the dashboard with \/plan2code\./],
|
||||
["Paused here", { command: "/plan2code-3-implement specs/x/overview.md" }, /Your saved place is picked up by the resume command above\./, /Paste the command above/],
|
||||
];
|
||||
for (const [headline, rest, fresh, carry] of shapes) {
|
||||
s.post({ finish: { headline, ...rest } });
|
||||
await main.getByRole("heading", { name: headline }).waitFor();
|
||||
const guide = closeGuide(s);
|
||||
assert.equal(await guide.count(), 1, `${headline}: one guide`);
|
||||
assert.equal(await guide.locator("li").count(), 3, `${headline}: three rows`);
|
||||
const text = await textOf(guide);
|
||||
for (const label of ["Before you close this", "Safe to close", "Start fresh", "Carry on"]) assert.ok(text.includes(label), `${headline}: says "${label}"`);
|
||||
assert.match(text, fresh, `${headline}: the Start fresh sentence`);
|
||||
assert.match(text, carry, `${headline}: the Carry on sentence`);
|
||||
assert.ok(!text.includes("—"), `${headline}: the guide carries an em dash`);
|
||||
}
|
||||
// With a stop warning up, a pause's command starts the work again.
|
||||
s.post({ stopWarning: "Answers since the last save will not be kept." });
|
||||
await closeGuide(s).getByText(/The command above starts it again\./).waitFor();
|
||||
assert.equal(await s.page.locator("#btn-home").isVisible(), false, "a finished screen carries its own way back");
|
||||
});
|
||||
|
||||
// What a person sees break: the triangle leaving answers behind, or sending a
|
||||
// finish-style stop instead of the way home.
|
||||
test("the top bar's back triangle asks first, then sends __dashboard with the typed answers and the home reply", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-home");
|
||||
const modal = s.page.locator("#home-modal");
|
||||
await modal.waitFor();
|
||||
assert.match(await textOf(modal), /Leave this workflow\?/);
|
||||
assert.match(await textOf(modal.locator("#home-blurb")), /The answer you have ready goes with it\./);
|
||||
await modal.locator("#home-cancel").click();
|
||||
await modal.waitFor({ state: "hidden" });
|
||||
assert.equal(s.wait(1).code === 0, false, "Cancel sent something");
|
||||
|
||||
await s.page.click("#btn-home");
|
||||
await modal.locator("#home-go").click();
|
||||
const got = collect(s);
|
||||
assert.deepEqual(got.actions.map(({ i, type }) => ({ i, type })), [{ i: "q1", type: "answer" }, { i: "__dashboard", type: "dashboard" }]);
|
||||
assert.ok(got.reply.includes("audit-export") && got.reply.endsWith(HOME_REPLY), `the reply carries the answer, then the home line: ${got.reply}`);
|
||||
await s.page.waitForFunction(() => document.getElementById("btn-home").disabled);
|
||||
});
|
||||
|
||||
// What a person sees break: Commit it now, or Changelog's commit offer, hops
|
||||
// into Git without the dashboard, and the board opens over the last skill's
|
||||
// staged answer, its selected question and its open tab.
|
||||
test("a hop into Git from another skill starts the page clean: nothing staged, nothing selected, the questions view", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "changelog",
|
||||
payload: {
|
||||
items: [{ id: "q1", kind: "choice", title: "Which version", body: "The next version number.",
|
||||
options: [{ k: "A", text: "A patch release" }, { k: "B", text: "A minor release" }] }],
|
||||
docs: [{ id: "notes", title: "Release notes", blocks: [{ id: "b1", md: "## Draft\n\nTwo fixes." }] }],
|
||||
agent: { status: "waiting" },
|
||||
},
|
||||
});
|
||||
// The page's own state, from the module app.js loaded (same URL, same instance).
|
||||
const local = () =>
|
||||
s.page.evaluate(async () => {
|
||||
const { page } = await import("/state.js");
|
||||
return { workflow: page.S.workflow, staged: page.local.staged, selected: page.selected, view: page.view };
|
||||
});
|
||||
await itemCard(s.page, "q1").getByText("A minor release").click();
|
||||
await s.page.locator(".view-tab", { hasText: "Release notes" }).click();
|
||||
const before = await local();
|
||||
assert.deepEqual(Object.keys(before.staged), ["q1"], "the answer was never staged");
|
||||
assert.equal(before.selected, "q1");
|
||||
assert.notEqual(before.view, "questions", "the Release notes tab never opened");
|
||||
const draftFile = path.join(s.session, "draft.json");
|
||||
assert.ok(await until(() => fs.existsSync(draftFile) && fs.readFileSync(draftFile, "utf8").includes('"q1"'), 5000), "the staged answer never reached the draft");
|
||||
|
||||
// What Commit it now and Changelog's commit offer run.
|
||||
cli(["open", "--resume", s.sid, "--no-open", "--workflow", "git"], { cwd: s.project });
|
||||
await s.page.waitForFunction(async () => (await import("/state.js")).page.S.workflow === "git", null, { timeout: 10000 });
|
||||
// Long enough for the page's draft push (600 ms after a save) to have run.
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
const after = await local();
|
||||
assert.deepEqual(after.staged, {}, `the page kept the last skill's staged answer: ${JSON.stringify(after.staged)}`);
|
||||
assert.equal(after.selected, null, `the page kept the last skill's selection: ${after.selected}`);
|
||||
assert.equal(after.view, "questions", `the page kept the last skill's tab: ${after.view}`);
|
||||
const stored = await s.page.evaluate((key) => JSON.parse(localStorage.getItem(key) || "{}").staged || {}, `p2c-console:${s.sid}`);
|
||||
assert.deepEqual(stored, {}, "the browser's copy kept the staged answer");
|
||||
const draft = fs.existsSync(draftFile) ? JSON.parse(fs.readFileSync(draftFile, "utf8")) : {};
|
||||
assert.deepEqual(draft.staged || {}, {}, "the server's draft kept the staged answer");
|
||||
});
|
||||
|
||||
// What a person sees break: Back to default in Preferences does nothing.
|
||||
test("Back to default in Preferences returns the theme to follow the system and clears the chosen look", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.locator('input[name="looks-theme"][value="dark"]').check();
|
||||
await s.page.waitForFunction(() => document.documentElement.getAttribute("data-theme") === "dark");
|
||||
await s.page.click("#looks-reset");
|
||||
await s.page.waitForFunction(() => !document.documentElement.hasAttribute("data-theme"));
|
||||
assert.equal(await s.page.locator('input[name="looks-theme"][value="system"]').isChecked(), true, "the system choice is ticked again");
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
// Page tests for the Workspace dialog and @mentions: adding a folder from the
|
||||
// footer label, what the next send tells the agent, and picking a folder from
|
||||
// the list an @ opens in a note. Run with:
|
||||
// node --test scripts/test-web-console-page-workspace.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pageSuite, openSession, itemCard, textOf } from "./page-test-helpers.mjs";
|
||||
import { tempFolder } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A plan session on the person's turn: one text question, the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// A folder named `datasets` in its own temp parent, so its @name is known.
|
||||
function datasetsFolder() {
|
||||
const dir = path.join(tempFolder(), "datasets");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
// Opens Workspace from the footer label and adds `dir` by typing its path.
|
||||
async function addFolderFromDialog(s, dir) {
|
||||
await s.page.locator("#footer-where").click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor();
|
||||
await s.page.locator("#workspace-path").fill(dir);
|
||||
await s.page.locator("#workspace-add").click();
|
||||
await s.page.locator("#workspace-add-msg.is-good").waitFor();
|
||||
}
|
||||
|
||||
// What a person sees break: a folder that does not show in the dialog, or
|
||||
// that the agent is never told about.
|
||||
test("a folder added in Workspace is listed with its @name, and the next send tells the agent in its reply", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const dir = datasetsFolder();
|
||||
await addFolderFromDialog(s, dir);
|
||||
|
||||
assert.equal(await textOf(s.page.locator("#workspace-add-msg")), "Added as @datasets.");
|
||||
const rows = s.page.locator("#workspace-list .ws-entry");
|
||||
assert.equal(await rows.count(), 2, "the project's own folder and the new one");
|
||||
const added = rows.filter({ hasText: "@datasets" });
|
||||
assert.equal(await added.count(), 1);
|
||||
assert.equal(await textOf(added.locator(".ws-path")), dir);
|
||||
assert.equal(await added.locator(".ws-original").count(), 0, "only the first folder is the original");
|
||||
assert.equal(await rows.first().locator(".ws-original").count(), 1);
|
||||
assert.equal(await s.page.locator("#workspace-path").inputValue(), "", "the path box empties after an add");
|
||||
|
||||
await s.page.locator("#workspace-done").click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code})`);
|
||||
assert.ok(got.reply.includes("audit-export"), `the answer is in the reply: ${got.reply}`);
|
||||
assert.ok(got.reply.includes("Workspace: added @datasets"), `the Workspace line: ${got.reply}`);
|
||||
assert.ok(got.reply.includes(dir), `the Workspace line names the path: ${got.reply}`);
|
||||
});
|
||||
|
||||
// What a person sees break: an @ that offers nothing, or a pick that leaves
|
||||
// the box as it was.
|
||||
test("an @ in a note offers the workspace's folders, and picking one writes its @name into the note", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await addFolderFromDialog(s, datasetsFolder());
|
||||
await s.page.locator("#workspace-done").click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
|
||||
|
||||
const note = s.page.locator("#aside #thread-q1");
|
||||
await note.click();
|
||||
await note.pressSequentially("Look in @da");
|
||||
const pop = s.page.locator("#mention-pop");
|
||||
await pop.waitFor();
|
||||
const options = pop.locator(".mention-opt");
|
||||
assert.deepEqual(await options.allTextContents(), ["@datasets"], "only the folder that matches what was typed");
|
||||
await options.first().click();
|
||||
await pop.waitFor({ state: "detached" });
|
||||
assert.equal(await note.inputValue(), "Look in @datasets ");
|
||||
|
||||
// A bare @ lists every folder, the project's own first.
|
||||
await note.pressSequentially("and @");
|
||||
await pop.waitFor();
|
||||
assert.equal(await pop.locator(".mention-opt").count(), 2);
|
||||
await s.page.keyboard.press("Escape");
|
||||
await pop.waitFor({ state: "detached" });
|
||||
});
|
||||
@@ -13,11 +13,12 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { applyPatch, validate, blankState } from "../src/web-console/lib.mjs";
|
||||
import { applyPatch, validate, blankState } from "../src/web-console/patches.mjs";
|
||||
import { rebasingBranch } from "../src/web-console/git-repo.mjs";
|
||||
import { indentReply, noteReplyLines, agentRepliedAfterSend } from "../src/web-console/public/answers.js";
|
||||
import { chatView } from "../src/web-console/public/chat.js";
|
||||
import { ROOT, CONSOLE_CLI, ENV, cli, payload, readState, postPatch, EXPORT_A, openSession } from "./web-console-test-helpers.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
|
||||
const choice = (id, extra = {}) => ({
|
||||
id,
|
||||
@@ -32,8 +33,7 @@ const choice = (id, extra = {}) => ({
|
||||
});
|
||||
const waitFor = (s, seconds = 10) => cli(["wait", "--session", s.sid, "--seconds", String(seconds)]);
|
||||
const runCli = (args, opts = {}) => spawnSync(process.execPath, [CONSOLE_CLI, ...args], { env: ENV, encoding: "utf8", ...opts });
|
||||
const app = () => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const css = () => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = () => joinedCss();
|
||||
|
||||
/* ------------------------------------------------------------ settling */
|
||||
|
||||
@@ -195,7 +195,6 @@ test("a rebase in progress names the branch it is rewriting", () => {
|
||||
test("a typed line never starts a reply line of its own", () => {
|
||||
assert.equal(indentReply("a\nIdea name: foo\r\n Image: C:\\x"), "a\n Idea name: foo\n Image: C:\\x");
|
||||
assert.deepEqual(noteReplyLines("Q", "one\ntwo", []), ["Note on Q: one\n two"]);
|
||||
assert.match(app(), /replyLines\.push\(`\$\{item\.title\}: \$\{indentReply\(tok\)\}`\)/);
|
||||
});
|
||||
|
||||
test("an approved edit stops saying 'please wait' once the agent has answered it", () => {
|
||||
@@ -211,31 +210,17 @@ test("an approved edit stops saying 'please wait' once the agent has answered it
|
||||
assert.equal(chatView(frame).rows[1].done, true);
|
||||
});
|
||||
|
||||
test("a build's own count wins, 0 done included; a question workflow still fills as cards are answered", () => {
|
||||
const chrome = app().slice(app().indexOf("function renderChrome("), app().indexOf("// Planny and the line beside him"));
|
||||
assert.match(chrome, /if \(Number\(h\.total\) > 0\)/);
|
||||
assert.match(chrome, /building \? Math\.max\(0, Number\(h\.cleared\) \|\| 0\) : Number\(h\.cleared\) \|\| answeredCount\(\)/);
|
||||
assert.match(chrome, /else if \(building && h\.stage\)/, "a review starting at total 0 shows its stage");
|
||||
});
|
||||
|
||||
test("the git board: Publish names a remote only when there is one, and an open card holds the board", () => {
|
||||
const js = app();
|
||||
const action = js.slice(js.indexOf("function gitAction("), js.indexOf("/* The branch table */"));
|
||||
test("the git board: Publish names a remote only when there is one, and Continue is always offered", () => {
|
||||
const view = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "git-board-view.js"), "utf8");
|
||||
const action = view.slice(view.indexOf("function runStep("), view.indexOf("function stepButton("));
|
||||
assert.match(action, /remotes\.length === 1/);
|
||||
const at = js.indexOf("const gitLocked = ");
|
||||
assert.match(js.slice(at, js.indexOf(";", at)), /myTurn\(\)\.some\(\(i\) => i\.kind !== "notice"\)/);
|
||||
const banner = js.slice(js.indexOf("function gitOpBanner("), js.indexOf("function gitActionBar("));
|
||||
const banner = view.slice(view.indexOf("function opBlock("), view.indexOf("function prBlock("));
|
||||
assert.ok(!/if \(conflicted\.every/.test(banner), "Continue is always offered; plan continue checks the files itself");
|
||||
});
|
||||
|
||||
test("a card cut by the window fades at its bottom edge while there is more below", () => {
|
||||
assert.match(app(), /function markMore\(\)[\s\S]*?classList\.toggle\("has-more"/);
|
||||
assert.match(css(), /\.main > \.card\.has-more \{[\s\S]*?mask-image/);
|
||||
});
|
||||
|
||||
test("kept attachments are served read-only from the session's spec, by their exact name shape", () => {
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "server.mjs"), "utf8");
|
||||
const route = server.slice(server.indexOf('pathname.startsWith("/attachments/")'), server.indexOf('pathname.startsWith("/uploads/")'));
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
|
||||
const route = server.slice(server.indexOf("function attachment("), server.indexOf("function shot("));
|
||||
assert.match(route, /req\.method !== "GET"/);
|
||||
assert.match(server, /const KEPT_ROUTE = new RegExp\(`\^\/attachments\/\(\[a-z0-9-\]\{1,40\}-\[0-9a-f-\]\{8\}/);
|
||||
const kept = server.slice(server.indexOf("function keptPath("), server.indexOf("function uploadPath("));
|
||||
@@ -273,12 +258,6 @@ test("a plain reopen (status and a thread reply only) moves the sent note into t
|
||||
assert.ok(card.thread.some((m) => m.who === "user" && m.text === "Add a dry-run flag."));
|
||||
});
|
||||
|
||||
test("a list rename is staged as it is typed, so Ctrl+Enter or an agent post never drops it", () => {
|
||||
const js = app();
|
||||
const list = js.slice(js.indexOf("function buildList("), js.indexOf("function buildList(") + 6000);
|
||||
assert.match(list, /title\.addEventListener\("input", \(\) => \{[\s\S]*?stageQuiet\(item\.id/);
|
||||
});
|
||||
|
||||
test("the git board's Publish reply names no remote when it sent none, and key chips show only for short keys", async () => {
|
||||
const { gitReply } = await import("../src/web-console/public/git-board.js");
|
||||
assert.equal(gitReply("publish", {}), "Publish.");
|
||||
@@ -291,25 +270,17 @@ test("the git board's Publish reply names no remote when it sent none, and key c
|
||||
});
|
||||
|
||||
test("a skip is recorded as one, collected with the send, and settles as skipped", () => {
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "server.mjs"), "utf8");
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
|
||||
assert.match(server, /\.\.\.\(type === "skip" \? \{ skipped: true \} : \{\}\)/);
|
||||
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "console.mjs"), "utf8");
|
||||
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "cmd-post-wait.mjs"), "utf8");
|
||||
assert.match(cli, /a\.type === "answer" \|\| a\.type === "skip"/);
|
||||
});
|
||||
|
||||
test("a send made before the last collection is never shown as still with the agent", () => {
|
||||
const js = app();
|
||||
const fn = js.slice(js.indexOf("const sendCollected = "), js.indexOf("const submittedInFlight = "));
|
||||
assert.match(fn, /String\(sub\.at\) <= String\(c\.at\)/);
|
||||
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "console.mjs"), "utf8");
|
||||
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "cmd-post-wait.mjs"), "utf8");
|
||||
assert.match(cli, /collected: \{ at: result\.consumedAt \|\| nowIso\(\), ids \}/, "the collection time, which every earlier send precedes");
|
||||
});
|
||||
|
||||
test("two dashboards on different specs never trade the workspace back and forth", () => {
|
||||
const js = app();
|
||||
assert.match(js, /wantScope !== scopeMine\) syncWorkspaceScope\(\)/);
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------- round 3 */
|
||||
|
||||
test("a branch whose remote copy was deleted offers Publish again, not Pull or Push", async () => {
|
||||
@@ -330,20 +301,15 @@ test("a branch whose remote copy was deleted offers Publish again, not Pull or P
|
||||
assert.equal(acts.publish.enabled, true);
|
||||
});
|
||||
|
||||
test("a finished session never puts a sent answer back on its form", () => {
|
||||
const js = app();
|
||||
assert.match(js, /if \(effort && !finish\(\) && isOpen\(item\)/);
|
||||
});
|
||||
|
||||
test("keep names a copy from the upload's real path, so an 8.3 spelling reuses the same copy", () => {
|
||||
const src = fs.readFileSync(path.join(ROOT, "src", "web-console", "console.mjs"), "utf8");
|
||||
const src = fs.readFileSync(path.join(ROOT, "src", "web-console", "cmd-small.mjs"), "utf8");
|
||||
assert.match(src, /attachmentName\(\{ upload: real\(upload\), name: args\.name \}\)/);
|
||||
});
|
||||
|
||||
test("the cleanup confirm is red only when a gone branch holds commits found nowhere else", () => {
|
||||
const src = fs.readFileSync(path.join(ROOT, "src", "plan2code-git-scripts", "git.mjs"), "utf8");
|
||||
assert.match(src, /danger: x\.some\(\(b\) => deleteCheck\(s, localBranch\(s, b\)\)\.onlyHere\.count > 0\)/);
|
||||
const js = app();
|
||||
const groups = js.slice(js.indexOf("function cleanupGroups("), js.indexOf("function openCleanup("));
|
||||
const rules = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "git-board.js"), "utf8");
|
||||
const groups = rules.slice(rules.indexOf("export function cleanupGroups("), rules.indexOf("export function boardActions("));
|
||||
assert.match(groups, /b\.merged && !b\.gone/, "gone wins on the page too, as cleanup-list has it");
|
||||
});
|
||||
@@ -34,10 +34,12 @@ import {
|
||||
STRAY_GRACE_MS,
|
||||
staleSessions,
|
||||
terminalLine,
|
||||
validate,
|
||||
} from "../src/web-console/lib.mjs";
|
||||
} from "../src/web-console/sessions.mjs";
|
||||
import { validate } from "../src/web-console/patches.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
HANDOFFS_DIR,
|
||||
HOME,
|
||||
ENV,
|
||||
cookieFor,
|
||||
@@ -434,6 +436,9 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
|
||||
backdate(path.join(plan2code, "busy"));
|
||||
kept.push(busy);
|
||||
stray(path.join(plan2code, "notes.txt"));
|
||||
// Handoffs are Plan2Code's own, however old: swept by age on open, never offered here.
|
||||
backdate(put(path.join(plan2code, "handoffs", "2025-01-01-0900-handoff.md")));
|
||||
backdate(path.join(plan2code, "handoffs"));
|
||||
// In use right now: a held lock and a temp between its write and rename.
|
||||
const live = [put(path.join(consoleDir, "workspaces.json.lock"), ""), put(path.join(plan2code, "models.json.123.tmp"))];
|
||||
kept.push(...live);
|
||||
@@ -448,6 +453,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
|
||||
"root:notes.txt",
|
||||
"session:20250801-101010-aaaaaa",
|
||||
]);
|
||||
assert.equal(items.some((i) => i.id === "root:handoffs"), false, "the handoffs folder is never a stray");
|
||||
assert.equal(STRAY_GRACE_MS, 60 * 60 * 1000);
|
||||
assert.equal(items.find((i) => i.id === "console:p1.json").bytes, 5);
|
||||
assert.equal(items.find((i) => i.id === "root:console-dev").kind, "folder");
|
||||
@@ -523,7 +529,7 @@ test("cleanup lists the project's completed specs untouched for 30 days, and rem
|
||||
|
||||
test("User Preferences: wider, its body scrolls and the button bar stays put, without touching dialogs that borrow .looks", () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
const dialog = html.match(/<dialog class="modal looks prefs" id="looks-modal"[^>]*>([\s\S]*?)<\/dialog>/);
|
||||
assert.ok(dialog, "the Preferences dialog carries the prefs class");
|
||||
const body = dialog[1].indexOf('<div class="prefs-body">');
|
||||
@@ -659,6 +665,20 @@ test("open reports a month-old session under swept and removes it after printing
|
||||
assert.equal(fs.existsSync(oldDir), false);
|
||||
});
|
||||
|
||||
test("open reports a month-old handoff under swept.handoffs and removes both its files", async () => {
|
||||
const id = "2025-01-01-0900-handoff";
|
||||
fs.mkdirSync(HANDOFFS_DIR, { recursive: true });
|
||||
const files = [path.join(HANDOFFS_DIR, id + ".md"), path.join(HANDOFFS_DIR, id + ".json")];
|
||||
fs.writeFileSync(files[0], "# Handoff: old\n");
|
||||
fs.writeFileSync(files[1], "{}");
|
||||
for (const f of files) backdate(f);
|
||||
const res = cli(["open", "--workflow", "plan", "--no-open"]);
|
||||
cli(["stop", "--session", res.json.sid]);
|
||||
assert.deepEqual(res.json.swept.handoffs, [id]);
|
||||
for (let i = 0; i < 20 && files.some((f) => fs.existsSync(f)); i++) await new Promise((r) => setTimeout(r, 100));
|
||||
assert.deepEqual(files.filter((f) => fs.existsSync(f)), []);
|
||||
});
|
||||
|
||||
test("post and wait hand back the terminal line; the collected result on disk does not carry it", async () => {
|
||||
const res = cli(["open", "--file", payload("tl.json", BASE), "--no-open"]);
|
||||
const s = sessionUrl(res.json.url);
|
||||
@@ -703,12 +723,6 @@ test("notes/quick-task.md has a quick-task build tick the Plan tab's steps live"
|
||||
assert.ok(section.includes("- [x] **1.** Step one"));
|
||||
});
|
||||
|
||||
test("the waiting pane points a quick-task build at its Plan tab", () => {
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const fn = js.slice(js.indexOf("function renderWaiting("), js.indexOf("function renderNotice("));
|
||||
assert.ok(fn.includes('S.workflow === "quick-task" && docs().find((d) => d.id === "plan")'));
|
||||
});
|
||||
|
||||
test("notes/quick-task.md has the finished quick task offer Back to the dashboard as well as the review", () => {
|
||||
const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "notes", "quick-task.md"), "utf8");
|
||||
const section = md.slice(md.indexOf("## Quick task (`quick-task`)"));
|
||||
@@ -716,3 +730,117 @@ test("notes/quick-task.md has the finished quick task offer Back to the dashboar
|
||||
assert.ok(bullet.includes('"dashboard": true'));
|
||||
assert.ok(bullet.includes("Review it now"));
|
||||
});
|
||||
|
||||
// Show me it working: a screenshot saved under <session>/shots/ posts as an
|
||||
// image block and is served back; nothing else is reachable through /shots/.
|
||||
test("an image block under the session's shots folder round-trips, and /shots/ serves nothing else", async () => {
|
||||
const res = cli(["open", "--workflow", "implement", "--no-open"]);
|
||||
const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
|
||||
const cookie = cookieFor(m[1], m[2]);
|
||||
try {
|
||||
const shots = path.join(res.json.session, "shots");
|
||||
fs.mkdirSync(shots, { recursive: true });
|
||||
const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(32, 7)]);
|
||||
fs.writeFileSync(path.join(shots, "home-page.png"), png);
|
||||
const patch = { docs: [{ id: "shown", title: "Shown working", blocks: [{ id: "s1", image: "shots/home-page.png", alt: "The home page with the new button" }] }] };
|
||||
cli(["post", "--session", res.json.sid, "--file", payload("shots-ok.json", patch)]);
|
||||
const block = readState(res.json.session).docs.find((d) => d.id === "shown").blocks[0];
|
||||
assert.equal(block.image, "shots/home-page.png", "stored session-relative");
|
||||
assert.equal(block.md, undefined);
|
||||
|
||||
// Its alt text is a caption, held to the same vocabulary rule as a title.
|
||||
const jargon = { docs: [{ id: "shown", blocks: [{ id: "s1", image: "shots/home-page.png", alt: "Grilling the home page" }] }] };
|
||||
const refused = cli(["post", "--session", res.json.sid, "--file", payload("shots-jargon.json", jargon)], { expectFail: true });
|
||||
assert.equal(refused.status, 3);
|
||||
assert.match(refused.stderr, /alt text contains internal vocabulary/);
|
||||
// A changed picture or caption is a new version of the doc.
|
||||
const before = readState(res.json.session).docs.find((d) => d.id === "shown").version;
|
||||
const recaption = { docs: [{ id: "shown", blocks: [{ id: "s1", image: "shots/home-page.png", alt: "The home page, after the fix" }] }] };
|
||||
cli(["post", "--session", res.json.sid, "--file", payload("shots-recaption.json", recaption)]);
|
||||
assert.equal(readState(res.json.session).docs.find((d) => d.id === "shown").version, before + 1);
|
||||
|
||||
const got = await fetch(m[1] + "/shots/home-page.png", { headers: { cookie } });
|
||||
assert.equal(got.status, 200);
|
||||
assert.equal(got.headers.get("content-type"), "image/png");
|
||||
assert.equal(got.headers.get("cache-control"), "no-store");
|
||||
assert.deepEqual(Buffer.from(await got.arrayBuffer()), png);
|
||||
|
||||
const anon = await fetch(m[1] + "/shots/home-page.png");
|
||||
assert.equal(anon.status, 403, "the cookie is still required");
|
||||
await anon.arrayBuffer();
|
||||
|
||||
// Raw request lines: fetch would fold the `..` away before sending.
|
||||
const raw = (p) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const req = http.request({ host: "127.0.0.1", port: Number(new URL(m[1]).port), path: p, headers: { cookie } }, (r) => {
|
||||
r.resume();
|
||||
r.on("end", () => resolve(r.statusCode));
|
||||
});
|
||||
req.on("error", reject);
|
||||
req.end();
|
||||
});
|
||||
for (const p of ["/shots/../state.json", "/shots/..%2fstate.json", "/shots/missing.png", "/shots/home-page.png?x=1"]) {
|
||||
assert.equal(await raw(p), 404, p);
|
||||
}
|
||||
} finally {
|
||||
cli(["stop", "--session", res.json.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
// /app.css is the files under public/styles/ joined in CSS_ORDER (one newline
|
||||
// after each), then the accent rules. The files themselves are never served.
|
||||
test("/app.css is the style files joined in CSS_ORDER with the accent rules last", async () => {
|
||||
const { CSS_ORDER, asset, etagOf } = await import("../src/web-console/static.mjs");
|
||||
const dir = path.join(ROOT, "src", "web-console", "public", "styles");
|
||||
const res = cli(["open", "--workflow", "review", "--no-open"]);
|
||||
const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
|
||||
const cookie = cookieFor(m[1], m[2]);
|
||||
try {
|
||||
const r = await fetch(m[1] + "/app.css", { headers: { cookie } });
|
||||
assert.equal(r.status, 200);
|
||||
assert.match(r.headers.get("content-type"), /^text\/css/);
|
||||
const body = await r.text();
|
||||
// One newline between files: each file's own last newline is that one.
|
||||
const joined = CSS_ORDER.map((f) => fs.readFileSync(path.join(dir, f), "utf8").replace(/\n$/, "")).join("\n") + "\n";
|
||||
assert.ok(body.startsWith(joined), "the body opens with the files, in CSS_ORDER, one newline between");
|
||||
const accents = body.slice(joined.length);
|
||||
assert.match(accents, /^\n*\/\* Generated by server\.mjs from palette\.js/, "the accent rules come last");
|
||||
assert.ok(accents.includes(`:root[data-looks-accent="violet"]`));
|
||||
// The tests' helper joins through the server's own function, so the two agree.
|
||||
assert.equal(body, joinedCss() + accents, "joinedCss() plus the accent rules is the body the server returns");
|
||||
// The ETag is a hash of the whole body, so a change to any one file moves it.
|
||||
assert.equal(r.headers.get("etag"), etagOf(Buffer.from(body)));
|
||||
assert.equal(asset("app.css").etag, etagOf(Buffer.from(body)));
|
||||
for (const f of CSS_ORDER) {
|
||||
const text = fs.readFileSync(path.join(dir, f), "utf8").replace(/\n$/, "");
|
||||
assert.notEqual(etagOf(Buffer.from(body.replace(text, text + "\n/* changed */"))), r.headers.get("etag"), `a change to ${f} moves the ETag`);
|
||||
}
|
||||
for (const f of CSS_ORDER) {
|
||||
const own = await fetch(m[1] + "/styles/" + f, { headers: { cookie } });
|
||||
assert.equal(own.status, 404, `/styles/${f} is not served on its own`);
|
||||
await own.arrayBuffer();
|
||||
}
|
||||
} finally {
|
||||
cli(["stop", "--session", res.json.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
// The skills the build writes carry public/styles/ with every file in CSS_ORDER,
|
||||
// and a console started from that tree serves the same /app.css as this one.
|
||||
test("the built skills tree serves the same /app.css as the source console", async (t) => {
|
||||
const { CSS_ORDER, asset } = await import("../src/web-console/static.mjs");
|
||||
const built = path.join(ROOT, "skills", "plan2code", "references", "web-console");
|
||||
// npm test builds first; a bare run of this file may not have.
|
||||
if (!fs.existsSync(path.join(built, "console.mjs"))) return t.skip("skills/ is not built: run npm run build:skills");
|
||||
for (const f of CSS_ORDER) assert.ok(fs.existsSync(path.join(built, "public", "styles", f)), `the build is missing public/styles/${f}`);
|
||||
const out = execFileSync(process.execPath, [path.join(built, "console.mjs"), "open", "--workflow", "review", "--no-open"], { env: ENV, encoding: "utf8", cwd: ROOT });
|
||||
const json = JSON.parse(out.trim().split("\n").pop());
|
||||
const m = json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
|
||||
try {
|
||||
const res = await fetch(m[1] + "/app.css", { headers: { cookie: cookieFor(m[1], m[2]) } });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(await res.text(), asset("app.css").body.toString("utf8"));
|
||||
} finally {
|
||||
execFileSync(process.execPath, [path.join(built, "console.mjs"), "stop", "--session", json.sid], { env: ENV, cwd: ROOT });
|
||||
}
|
||||
});
|
||||
@@ -24,10 +24,8 @@ import {
|
||||
noteReplyLines,
|
||||
staleLaunchFeedback,
|
||||
REVIEW_REPLY,
|
||||
SKILL_CATALOG,
|
||||
START_POSES,
|
||||
startPose,
|
||||
STOP_REPLY,
|
||||
STOP_HANDOFF_REPLY,
|
||||
threadText,
|
||||
threadWho,
|
||||
turnGate,
|
||||
@@ -37,13 +35,9 @@ import { ACCENTS, CARD_WIDTHS, SOUND_EVENTS, soundKey, soundPrefs } from "../src
|
||||
import { HELP_TABS, helpTabFor, helpKeyTarget } from "../src/web-console/public/help.js";
|
||||
import { RED_AT, YELLOW_AT } from "../src/web-console/public/meter.js";
|
||||
import { REMOTE_FOLD } from "../src/web-console/public/git-board.js";
|
||||
import {
|
||||
applyPatch,
|
||||
readLedger,
|
||||
SESSION_MAX_AGE_MS,
|
||||
sweepUploads,
|
||||
UPLOAD_MAX_AGE_MS,
|
||||
} from "../src/web-console/lib.mjs";
|
||||
import { readLedger, SESSION_MAX_AGE_MS, sweepUploads, UPLOAD_MAX_AGE_MS } from "../src/web-console/sessions.mjs";
|
||||
import { applyPatch, validate } from "../src/web-console/patches.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
HOME,
|
||||
@@ -225,6 +219,58 @@ test("a launch request round-trips with the skill the dashboard resumes as", asy
|
||||
assert.ok(state.items.every((i) => i.id !== "__launch"), "a launch must not become a question");
|
||||
});
|
||||
|
||||
// Continue here sends the same launch from a finished screen, so the hop's
|
||||
// resume names the next skill's workflow and the spec, and the skill file to read.
|
||||
test("a launch sent from a finished screen carries the resume for the next skill and spec", async () => {
|
||||
await post("/submit", {
|
||||
actions: [{ i: "__launch", type: "launch", skill: "plan2code-2-document", workflow: "document", spec: "specs/lunch-vote" }],
|
||||
reply: "Start Document (/plan2code-2-document) for specs/lunch-vote, right here in this session.",
|
||||
});
|
||||
const res = cli(["wait", "--session", sid, "--seconds", "10"]);
|
||||
assert.equal(res.status, 0);
|
||||
assert.equal(res.json.actions[0].i, "__launch");
|
||||
assert.match(res.json.resume, /--no-open --workflow document --spec specs\/lunch-vote$/);
|
||||
});
|
||||
|
||||
// The page tells the person the hop gives the next skill a clean page: a resume
|
||||
// into a different workflow drops the finish it was launched from.
|
||||
test("resuming into another skill after Continue here drops the finish", async () => {
|
||||
const stateFile = path.join(session, "state.json");
|
||||
const readState = () => JSON.parse(fs.readFileSync(stateFile, "utf8"));
|
||||
cli(["post", "--session", sid, "--file", payload("fin-continue.json", {
|
||||
finish: { headline: "The plan is documented", command: "/plan2code-5-changelog", dashboard: true },
|
||||
})]);
|
||||
const snapshot = fs.readFileSync(stateFile, "utf8");
|
||||
await post("/submit", {
|
||||
actions: [{ i: "__launch", type: "launch", skill: "plan2code-changelog", workflow: "changelog" }],
|
||||
reply: "Start Changelog (/plan2code-changelog), right here in this session.",
|
||||
});
|
||||
const res = cli(["wait", "--session", sid, "--seconds", "10"]);
|
||||
assert.equal(res.status, 0);
|
||||
cli(["open", "--resume", sid, "--no-open", "--workflow", "changelog"]);
|
||||
const resumed = readState();
|
||||
assert.equal(resumed.workflow, "changelog");
|
||||
assert.equal(resumed.finish, undefined, "the old finish is gone");
|
||||
fs.writeFileSync(stateFile, snapshot);
|
||||
});
|
||||
|
||||
// A delete from the dashboard's picker is a send like a launch, but no hop:
|
||||
// the agent stays the dashboard, so it carries no resume and no skill file.
|
||||
test("a delete request round-trips with the spec folder and no resume", async () => {
|
||||
await post("/submit", {
|
||||
actions: [{ i: "__delete", type: "delete", spec: "specs/lunch-vote" }],
|
||||
reply: "Delete the spec folder specs/lunch-vote/ for good, right here in this session.",
|
||||
});
|
||||
const res = cli(["wait", "--session", sid, "--seconds", "10"]);
|
||||
assert.equal(res.status, 0);
|
||||
assert.equal(res.json.actions[0].i, "__delete");
|
||||
assert.equal(res.json.actions[0].spec, "specs/lunch-vote");
|
||||
assert.equal(res.json.resume, undefined);
|
||||
assert.equal(res.json.skillFile, undefined);
|
||||
const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
|
||||
assert.ok(state.items.every((i) => i.id !== "__delete"), "a delete must not become a question");
|
||||
});
|
||||
|
||||
// Back to the dashboard is a send like the review button: it names no
|
||||
// question, it is refused while an earlier send is uncollected, and the agent
|
||||
// answers it by resuming the same session as the dashboard.
|
||||
@@ -371,6 +417,24 @@ test("a stop request carries the staged answers, reaches the agent as a send, an
|
||||
assert.equal((await ping()).pendingStop, false);
|
||||
});
|
||||
|
||||
// "Stop with a handoff" is the same send with `handoff: true` on the action.
|
||||
// The source tree has no built Handoff skill beside it, so no handoffSkill.
|
||||
test("a handoff stop keeps its flag, reports as a stop until collected, and names no skill file in the source tree", async () => {
|
||||
const ping = async () => (await post("/ping", {})).json();
|
||||
const before = await ping();
|
||||
await post("/submit", {
|
||||
rev: before.rev,
|
||||
actions: [{ i: "__stop", type: "stop", handoff: true }],
|
||||
reply: STOP_HANDOFF_REPLY,
|
||||
});
|
||||
assert.equal((await ping()).pendingStop, true, "an uncollected handoff stop shows on the heartbeat");
|
||||
const res = cli(["wait", "--session", sid, "--seconds", "5"]);
|
||||
assert.equal(res.status, 0);
|
||||
assert.equal(res.json.actions[0].handoff, true, "the flag reaches the agent");
|
||||
assert.equal(res.json.handoffSkill, undefined, "no built skill beside the source tree");
|
||||
assert.equal((await ping()).pendingStop, false);
|
||||
});
|
||||
|
||||
// The top bar's triangle is a stop that lands on the menu: the staged answers
|
||||
// and `__dashboard` go as one send with no finish on the page, the agent gets
|
||||
// both at once, and the resume through the dashboard blanks the skill's page.
|
||||
@@ -439,8 +503,7 @@ test("the way home follows Stop's turn rules and hides where it has no job", ()
|
||||
test("the page carries the way home: the triangle, its confirm, and the wiring", () => {
|
||||
const dir = path.join(ROOT, "src", "web-console", "public");
|
||||
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
||||
const app = fs.readFileSync(path.join(dir, "app.js"), "utf8");
|
||||
const css = fs.readFileSync(path.join(dir, "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
assert.ok(html.indexOf('id="btn-home"') < html.indexOf('id="btn-stop"'), "the triangle sits left of Stop session");
|
||||
assert.match(html, /id="btn-home"[\s\S]{0,200}aria-label="Back to the dashboard"/, "the icon button has a name");
|
||||
for (const id of ["home-modal", "home-blurb", "home-warn", "home-cancel", "home-go"]) {
|
||||
@@ -448,8 +511,6 @@ test("the page carries the way home: the triangle, its confirm, and the wiring",
|
||||
}
|
||||
assert.ok(html.includes("Leave this workflow?"));
|
||||
assert.match(css, /\.home-btn path\s*\{\s*fill:\s*var\(--accent\)/, "the triangle is filled with the highlight color");
|
||||
assert.ok(app.includes('{ i: "__dashboard", type: "dashboard" }'), "the confirm sends __dashboard");
|
||||
assert.ok(app.includes("stagedPayload()") && app.includes("HOME_REPLY"), "the staged answers ride along with the reply line");
|
||||
});
|
||||
|
||||
test("the way home cannot be mistaken for a brief request", () => {
|
||||
@@ -462,11 +523,24 @@ test("console-stop.md, building.md and the dashboard prompt teach the mid-workfl
|
||||
assert.ok(stopMd.includes("## Back to the dashboard, mid-workflow"));
|
||||
assert.ok(stopMd.includes(HOME_REPLY), "console-stop.md quotes the reply line the agent will see");
|
||||
assert.match(stopMd, /No `finish` and no `stop` in between/);
|
||||
assert.match(read("src", "web-console", "console.md"), /`__stop`, `__dashboard` \(no finish up\) \| `console-stop\.md`/, "console.md's action table sends a mid-workflow __dashboard there");
|
||||
assert.ok(stopMd.includes("## Stop with a handoff"));
|
||||
for (const word of ["handoff new", "--from-stop", "handoffSkill"]) assert.ok(stopMd.includes(word), `console-stop.md names ${word}`);
|
||||
assert.match(read("src", "web-console", "console.md"), /`__stop` \(plain, or with `handoff: true`\), `__dashboard` \(no finish up\) \| `console-stop\.md`/, "console.md's action table sends a handoff stop and a mid-workflow __dashboard there");
|
||||
assert.ok(read("src", "web-console", "building.md").includes("mid-build `__dashboard`"));
|
||||
assert.ok(read("src", "plan2code.md").includes("mid-workflow from the top bar's triangle"));
|
||||
});
|
||||
|
||||
test("console-launches.md and the dashboard prompt teach the handoff pick-up and delete", () => {
|
||||
const read = (...p) => fs.readFileSync(path.join(ROOT, ...p), "utf8");
|
||||
const launches = read("src", "web-console", "console-launches.md");
|
||||
for (const word of ["__pickup", "handoffFile", "delete-handoff", "handoffsDir", "fallback"]) {
|
||||
assert.ok(launches.includes(word), `console-launches.md names ${word}`);
|
||||
}
|
||||
assert.ok(launches.includes("handoffs, handoffsDir"), "console-launches.md lists the scan fields");
|
||||
const prompt = read("src", "plan2code.md");
|
||||
for (const word of ["__pickup", "delete-handoff"]) assert.ok(prompt.includes(word), `src/plan2code.md names ${word}`);
|
||||
});
|
||||
|
||||
// The server serves a hardcoded allow-list, so a new module that nobody adds
|
||||
// to it 404s, the import fails, and the page never starts: a blank console
|
||||
// with the default title and one line in the browser's console. Every module
|
||||
@@ -474,9 +548,12 @@ test("console-stop.md, building.md and the dashboard prompt teach the mid-workfl
|
||||
test("every module the page imports is actually served", async () => {
|
||||
const dir = path.join(ROOT, "src", "web-console", "public");
|
||||
const wanted = new Set(["app.js"]);
|
||||
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith(".js"))) {
|
||||
// The modules beside app.js and the screens under screens/, each import
|
||||
// resolved from the file that makes it (a screen's "../state.js" is state.js).
|
||||
const files = [...fs.readdirSync(dir).filter((f) => f.endsWith(".js")), ...fs.readdirSync(path.join(dir, "screens")).map((f) => `screens/${f}`)];
|
||||
for (const f of files) {
|
||||
const src = fs.readFileSync(path.join(dir, f), "utf8");
|
||||
for (const m of src.matchAll(/^\s*import\b[^"']*["']\.\/([^"']+)["']/gm)) wanted.add(m[1]);
|
||||
for (const m of src.matchAll(/^\s*import\b[^"']*["'](\.\.?\/[^"']+)["']/gm)) wanted.add(path.posix.join(path.posix.dirname(f), m[1]));
|
||||
}
|
||||
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
||||
for (const m of html.matchAll(/<link rel="modulepreload" href="\/([^"]+)"/g)) wanted.add(m[1]);
|
||||
@@ -564,28 +641,6 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at
|
||||
assert.doesNotMatch(html, /rel="icon"[^>]*href="data:/);
|
||||
});
|
||||
|
||||
// Each skill's starting and waiting screens clone its pose from index.html.
|
||||
// A pose with no drawing silently falls back to the flight, and a style
|
||||
// attribute in one would be refused by the CSP, so hold the markup to the list.
|
||||
test("every skill has a pose drawn in the page, with no inline styles", () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const tpl = html.match(/<template id="start-poses">([\s\S]*?)<\/template>/);
|
||||
assert.ok(tpl, "index.html has the start-poses template");
|
||||
const drawn = [...tpl[1].matchAll(/data-pose="([^"]+)"/g)].map((m) => m[1]);
|
||||
assert.deepEqual(drawn.sort(), [...START_POSES].sort());
|
||||
assert.doesNotMatch(tpl[1], /\sstyle=/);
|
||||
for (const pose of START_POSES) {
|
||||
assert.ok(SKILL_CATALOG.some((e) => e.workflow === pose), `${pose} is a real workflow`);
|
||||
assert.equal(startPose(pose), pose);
|
||||
}
|
||||
assert.equal(startPose("implement-review"), "implement");
|
||||
assert.equal(startPose("revise-plan"), "plan");
|
||||
assert.equal(startPose("init-update"), "init");
|
||||
for (const e of SKILL_CATALOG) assert.ok(startPose(e.workflow), `${e.workflow} has a pose`);
|
||||
assert.equal(startPose("dashboard"), null);
|
||||
assert.equal(startPose(undefined), null);
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------- help */
|
||||
|
||||
|
||||
@@ -749,9 +804,9 @@ const helpFacts = () => ({
|
||||
maxDocMb: MAX_DOC_BYTES / 1024 / 1024,
|
||||
imageEdge: IMAGE_LONG_EDGE,
|
||||
cleanupDays: SESSION_MAX_AGE_MS / 86400000,
|
||||
goneSeconds: sourceConst("public/app.js", /const GONE_AFTER_MS = ([^;]+);/, "GONE_AFTER_MS") / 1000,
|
||||
adriftMinutes: sourceConst("public/app.js", /const ADRIFT_MS = ([^;]+);/, "ADRIFT_MS") / 60000,
|
||||
maxUploadMb: sourceConst("public/app.js", /const MAX_UPLOAD_BYTES = ([^;]+);/, "MAX_UPLOAD_BYTES") / 1024 / 1024,
|
||||
goneSeconds: sourceConst("public/screens/core.js", /const GONE_AFTER_MS = ([^;]+);/, "GONE_AFTER_MS") / 1000,
|
||||
adriftMinutes: sourceConst("public/selectors.js", /const ADRIFT_MS = ([^;]+);/, "ADRIFT_MS") / 60000,
|
||||
maxUploadMb: sourceConst("public/uploads.js", /const MAX_UPLOAD_BYTES = ([^;]+);/, "MAX_UPLOAD_BYTES") / 1024 / 1024,
|
||||
idleMinutes: sourceConst("server.mjs", /const IDLE_MS = Number\(args\[[^\]]+\] \|\| ([^)]+)\)/, "IDLE_MS") / 60000,
|
||||
maxLifeHours: sourceConst("server.mjs", /const MAX_LIFE_MS = Number\(args\[[^\]]+\] \|\| ([^)]+)\)/, "MAX_LIFE_MS") / 3600000,
|
||||
closedTabMinutes: sourceConst("server.mjs", /\(IDLE_MS - ([^)]+)\)/, "the closed-tab shutdown") / 60000,
|
||||
@@ -1317,6 +1372,32 @@ test("patches merge by id and append threads", () => {
|
||||
assert.ok(replies[0].at, "the server stamps the time the agent left out");
|
||||
});
|
||||
|
||||
test("finish.changelog is accepted on quick-task and finalize, and refused on implement and on a non-boolean", () => {
|
||||
const problems = (workflow, changelog, headline = "Done") =>
|
||||
validate({ workflow, items: [], finish: { headline, command: "git add -A", commit: true, changelog } });
|
||||
for (const workflow of ["quick-task", "finalize"]) assert.deepEqual(problems(workflow, true), [], workflow);
|
||||
assert.match(problems("implement", true).join(), /only for a finished quick-task or finalize/);
|
||||
assert.match(problems("implement-review", true).join(), /only for a finished quick-task or finalize/);
|
||||
assert.match(problems("quick-task", "yes").join(), /must be true or false/);
|
||||
// false is always fine, and a pause ignores it
|
||||
assert.deepEqual(problems("implement", false), []);
|
||||
assert.deepEqual(problems("implement", true, "Paused at Phase 2"), []);
|
||||
});
|
||||
|
||||
// Update CHANGELOG first is a hop like Commit it now, into Changelog.
|
||||
test("a changelog request from a finished screen carries the resume into the changelog workflow and its skill file", async () => {
|
||||
await post("/submit", {
|
||||
actions: [{ i: "__changelog", type: "changelog" }],
|
||||
reply: "Update the CHANGELOG before I commit: open Changelog, right here in this session.",
|
||||
});
|
||||
const res = cli(["wait", "--session", sid, "--seconds", "10"]);
|
||||
assert.equal(res.status, 0);
|
||||
assert.equal(res.json.actions[0].i, "__changelog");
|
||||
assert.match(res.json.resume, /--no-open --workflow changelog$/);
|
||||
const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
|
||||
assert.ok(state.items.every((i) => i.id !== "__changelog"), "a changelog request must not become a question");
|
||||
});
|
||||
|
||||
test("a thread reply in another shape is lifted into { who, text }, and an empty one is refused", () => {
|
||||
const base = { items: [{ id: "n1", kind: "text", title: "Name", status: "open", thread: [{ who: "user", text: "why?", at: "2026-10-05T10:00:00Z" }] }] };
|
||||
const next = applyPatch(base, {
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
// Web console tests, the shape of the source: no console file grows past
|
||||
// 3,000 lines, and the files lib.mjs split into stand on their own.
|
||||
// Run with: node --test scripts/test-web-console-shape.mjs
|
||||
|
||||
import test 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 { spawnSync } from "node:child_process";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { ROOT } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const CONSOLE_DIR = path.join(ROOT, "src", "web-console");
|
||||
const MAX_LINES = 3000;
|
||||
|
||||
// Every .mjs, .js and .css file under `dir` (vendored code aside), as paths
|
||||
// relative to it with forward slashes.
|
||||
function sourceFiles(dir, rel = "") {
|
||||
const out = [];
|
||||
for (const e of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
|
||||
const p = rel ? `${rel}/${e.name}` : e.name;
|
||||
if (e.isDirectory()) {
|
||||
if (p !== "public/vendor") out.push(...sourceFiles(dir, p));
|
||||
} else if (/\.(mjs|js|css)$/.test(e.name)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// A file's line count, as `wc -l` gives it for a file ending in a newline.
|
||||
function lineCount(text) {
|
||||
return text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
|
||||
}
|
||||
|
||||
// The lines that name each file over the limit.
|
||||
function oversized(dir) {
|
||||
return sourceFiles(dir)
|
||||
.map((p) => [p, lineCount(fs.readFileSync(path.join(dir, p), "utf8"))])
|
||||
.filter(([p, n]) => n > MAX_LINES)
|
||||
.map(([p, n]) => `${p} is ${n} lines, over the ${MAX_LINES}-line limit: split it by job`);
|
||||
}
|
||||
|
||||
test("shape: no console file is over 3,000 lines", () => {
|
||||
assert.deepEqual(oversized(CONSOLE_DIR), []);
|
||||
});
|
||||
|
||||
test("shape: the size check names the file that is too big", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shape-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "public", "vendor"), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "big.mjs"), "x\n".repeat(MAX_LINES + 1));
|
||||
fs.writeFileSync(path.join(dir, "edge.css"), "x\n".repeat(MAX_LINES));
|
||||
fs.writeFileSync(path.join(dir, "small.js"), "x\n");
|
||||
fs.writeFileSync(path.join(dir, "public", "vendor", "huge.js"), "x\n".repeat(MAX_LINES * 2));
|
||||
assert.deepEqual(oversized(dir), [`big.mjs is ${MAX_LINES + 1} lines, over the ${MAX_LINES}-line limit: split it by job`]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("shape: files.mjs still finds the console's own folder", async () => {
|
||||
const { HERE, PUBLIC_DIR } = await import("../src/web-console/files.mjs");
|
||||
assert.equal(path.basename(HERE), "web-console");
|
||||
assert.equal(PUBLIC_DIR, path.join(HERE, "public"));
|
||||
});
|
||||
|
||||
test("shape: lib.mjs is gone, and every file it split into is there", () => {
|
||||
assert.equal(fs.existsSync(path.join(CONSOLE_DIR, "lib.mjs")), false, "src/web-console/lib.mjs still exists");
|
||||
for (const f of SPLIT_FILES) {
|
||||
const text = fs.readFileSync(path.join(CONSOLE_DIR, f), "utf8");
|
||||
assert.match(text, /^\/\/ Plan2Code Web Console - \S.*\.\n/, `${f} opens with a one-line job comment`);
|
||||
}
|
||||
});
|
||||
|
||||
// Every page file but the entry (app.js) only defines things, so each one
|
||||
// loads under plain Node with no page around it. Imported alone in a fresh
|
||||
// process: one that reaches for `document` or `window` at load, or runs
|
||||
// anything else that throws, is named with its first error line. One that
|
||||
// starts a timer or a listener throws nothing but never exits: it is named too.
|
||||
const LOAD_TIMEOUT_MS = 5000;
|
||||
function pageLoadFailures(pub) {
|
||||
return sourceFiles(pub)
|
||||
.filter((p) => p.endsWith(".js") && p !== "app.js" && (!p.includes("/") || p.startsWith("screens/")))
|
||||
.flatMap((p) => {
|
||||
const url = pathToFileURL(path.join(pub, p)).href;
|
||||
const r = spawnSync(process.execPath, ["--input-type=module", "-e", `await import(${JSON.stringify(url)});`], {
|
||||
encoding: "utf8",
|
||||
timeout: LOAD_TIMEOUT_MS,
|
||||
});
|
||||
if (r.error && r.error.code === "ETIMEDOUT") return [`${p} does not load on its own: still running after load (a timer or listener started at module scope)`];
|
||||
if (r.status === 0) return [];
|
||||
const line = r.stderr.split("\n").find((l) => /Error/.test(l)) || r.stderr.trim().split("\n")[0];
|
||||
return [`${p} does not load on its own: ${line.trim()}`];
|
||||
});
|
||||
}
|
||||
|
||||
test("shape: every page file but app.js only defines things, and loads under plain Node", () => {
|
||||
assert.deepEqual(pageLoadFailures(path.join(CONSOLE_DIR, "public")), []);
|
||||
});
|
||||
|
||||
test("shape: the define-only check names a page file that touches the page at load", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-define-only-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "screens"));
|
||||
fs.mkdirSync(path.join(dir, "vendor"));
|
||||
fs.writeFileSync(path.join(dir, "package.json"), '{ "type": "module" }\n');
|
||||
fs.writeFileSync(path.join(dir, "app.js"), "document.title = 'the entry may';\n");
|
||||
fs.writeFileSync(path.join(dir, "fine.js"), "export const title = () => document.title;\n");
|
||||
fs.writeFileSync(path.join(dir, "screens", "eager.js"), "export const title = document.title;\n");
|
||||
fs.writeFileSync(path.join(dir, "screens", "ticks.js"), "setInterval(() => {}, 1000);\n");
|
||||
fs.writeFileSync(path.join(dir, "vendor", "lib.js"), "window.x = 1;\n");
|
||||
const failures = pageLoadFailures(dir);
|
||||
assert.equal(failures.length, 2, failures.join("\n"));
|
||||
assert.match(failures.find((f) => f.startsWith("screens/eager.js")), /does not load on its own: ReferenceError: document is not defined/);
|
||||
assert.match(failures.find((f) => f.startsWith("screens/ticks.js")), /does not load on its own: still running after load/);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// A screen reaches the rest of the page through ../state.js and the pure
|
||||
// modules beside it, never through another screen: only core.js (the render
|
||||
// loop, which draws every screen) imports screens, and only app.js (the
|
||||
// entry) imports core.js. Each import that breaks that is named.
|
||||
function pageImportProblems(pub) {
|
||||
const problems = [];
|
||||
for (const p of sourceFiles(pub).filter((f) => f.endsWith(".js") && (!f.includes("/") || f.startsWith("screens/")))) {
|
||||
const text = fs.readFileSync(path.join(pub, p), "utf8");
|
||||
for (const m of text.matchAll(/^\s*(?:import|export)\b[^;]*?\bfrom\s*["']([^"']+)["']|\bimport\(\s*["']([^"']+)["']\s*\)|^\s*import\s*["']([^"']+)["']/gm)) {
|
||||
const spec = m[1] || m[2] || m[3];
|
||||
if (!spec.startsWith(".")) continue;
|
||||
const target = path.posix.join(path.posix.dirname(p), spec);
|
||||
if (target === "screens/core.js" && p !== "app.js") problems.push(`${p} imports ${spec}: only app.js imports core.js`);
|
||||
else if (p.startsWith("screens/") && p !== "screens/core.js" && target.startsWith("screens/"))
|
||||
problems.push(`${p} imports ${spec}: a screen imports ../state.js and the modules beside it, never another screen`);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
test("shape: a screen never imports another screen, and only app.js imports core.js", () => {
|
||||
assert.deepEqual(pageImportProblems(path.join(CONSOLE_DIR, "public")), []);
|
||||
});
|
||||
|
||||
test("shape: the import check names a screen that imports another, and any file but app.js importing core.js", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-imports-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "screens"));
|
||||
const put = (rel, text) => fs.writeFileSync(path.join(dir, rel), text);
|
||||
put("app.js", 'import { render } from "./screens/core.js";\n');
|
||||
put("state.js", "export const page = {};\n");
|
||||
put("render.js", "export const el = () => null;\n");
|
||||
put("screens/core.js", 'import { a } from "./a.js";\nimport { page } from "../state.js";\n');
|
||||
put("screens/a.js", 'import { b } from "./b.js";\nimport { page } from "../state.js";\nimport { el } from "../render.js";\n');
|
||||
put("screens/b.js", 'import { page } from "../state.js";\n');
|
||||
put("screens/c.js", 'import { render } from "./core.js";\n');
|
||||
put("helper.js", 'import { render } from "./screens/core.js";\n');
|
||||
put("screens/d.js", 'import "./b.js";\n');
|
||||
assert.deepEqual(pageImportProblems(dir).sort(), [
|
||||
"helper.js imports ./screens/core.js: only app.js imports core.js",
|
||||
"screens/a.js imports ./b.js: a screen imports ../state.js and the modules beside it, never another screen",
|
||||
"screens/c.js imports ./core.js: only app.js imports core.js",
|
||||
"screens/d.js imports ./b.js: a screen imports ../state.js and the modules beside it, never another screen",
|
||||
]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// The page's CSP refuses style attributes, so one set from script is dropped
|
||||
// on the floor in the browser. Every page module, wherever a split moves the
|
||||
// code that draws.
|
||||
test("shape: no page module sets a style attribute from script", () => {
|
||||
const pub = path.join(CONSOLE_DIR, "public");
|
||||
const offenders = sourceFiles(pub)
|
||||
.filter((p) => p.endsWith(".js"))
|
||||
.filter((p) => /setAttribute\(\s*["']style["']/.test(fs.readFileSync(path.join(pub, p), "utf8")));
|
||||
assert.deepEqual(offenders, []);
|
||||
});
|
||||
|
||||
// Every URL the server's old `if` chain matched, in its order, so a route lost
|
||||
// or moved in routes.mjs fails here by name: several match by prefix, and the
|
||||
// token gate sits after the first two. SERVABLE stands for the page's own files
|
||||
// and WORKSPACE_EDITS for /workspace/add, /edit and /remove. The git board has
|
||||
// no routes of its own: its buttons are sends (`__git`), through /submit.
|
||||
const ROUTE_ORDER = [
|
||||
"/health", "/s/", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft",
|
||||
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/cleanup", "/upload",
|
||||
"/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab",
|
||||
"/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/images/",
|
||||
"/attachments/", "/shots/", "/uploads/", "/submit", "/chat", "/chat/decision", "/workspace",
|
||||
"WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/cancel", "/ping", "/bye",
|
||||
];
|
||||
|
||||
test("shape: routes.mjs lists every URL the server answers, in order", () => {
|
||||
const routes = fs.readFileSync(path.join(CONSOLE_DIR, "routes.mjs"), "utf8");
|
||||
const start = routes.indexOf("const ROUTES = [");
|
||||
const list = routes.slice(start, routes.indexOf("\n];", start));
|
||||
const entries = list
|
||||
.split("\n")
|
||||
.filter((line) => /^\s*\{/.test(line))
|
||||
.map((line) => (line.match(/path: "([^"]*)"|startsWith\("([^"]*)"\)|\b(SERVABLE|WORKSPACE_EDITS)\b/) || []).slice(1).find(Boolean));
|
||||
assert.deepEqual(entries, ROUTE_ORDER);
|
||||
const edits = routes.match(/const WORKSPACE_EDITS = \{([^}]*)\}/)[1];
|
||||
for (const p of ["/workspace/add", "/workspace/edit", "/workspace/remove"]) assert.ok(edits.includes(`"${p}"`), `${p} is a workspace edit`);
|
||||
});
|
||||
|
||||
// Each file split out of lib.mjs, imported first and alone in a fresh
|
||||
// process: a module-scope read of a value from a file still loading (an
|
||||
// import cycle) throws here, naming the file, before it reaches a real run.
|
||||
const SPLIT_FILES = ["files.mjs", "sessions.mjs", "scan.mjs", "patches.mjs", "inbox.mjs", "workspace.mjs", "settings.mjs"];
|
||||
|
||||
test("shape: every file split out of lib.mjs loads first and alone", () => {
|
||||
for (const f of SPLIT_FILES) {
|
||||
const url = pathToFileURL(path.join(CONSOLE_DIR, f)).href;
|
||||
const r = spawnSync(process.execPath, ["--input-type=module", "-e", `await import(${JSON.stringify(url)});`], { encoding: "utf8" });
|
||||
assert.equal(r.status, 0, `${f} does not load on its own: ${r.stderr.trim().split("\n").find((l) => /Error/.test(l)) || r.stderr}`);
|
||||
}
|
||||
});
|
||||
|
||||
// app.js is the entry and nothing else, so no test may read it as text: what a
|
||||
// screen does is tested by driving the page, and what a screen file holds is
|
||||
// read from that screen. A statement that both reads a file and names app.js
|
||||
// is a read (a fetch of /app.js, or a fixture file called app.js, is not).
|
||||
const SCRIPTS_DIR = path.join(ROOT, "scripts");
|
||||
|
||||
// parse-check.mjs only parses the entry, so it may name it.
|
||||
const MAY_NAME_APP_JS = new Set(["parse-check.mjs"]);
|
||||
|
||||
// One statement that reads and names app.js, or a read helper handed it
|
||||
// (`web("app.js")`, `publicSource("public/app.js")`), or a path to it
|
||||
// under public/, in any file that also reads files.
|
||||
function appJsReaders(dir) {
|
||||
return fs
|
||||
.readdirSync(dir)
|
||||
.filter((f) => f.endsWith(".mjs") && f !== "test-web-console-shape.mjs" && !MAY_NAME_APP_JS.has(f))
|
||||
.filter((f) => {
|
||||
const text = fs.readFileSync(path.join(dir, f), "utf8");
|
||||
const oneStatement = text
|
||||
.split(";")
|
||||
.some((statement) => /\b(readFileSync|readFile|publicSource)\s*\(/.test(statement) && /["'/]app\.js["']/.test(statement));
|
||||
const handedToAHelper = /\w\(\s*["'](?:(?:src\/web-console\/)?public\/)?app\.js["']\s*\)/.test(text);
|
||||
const publicPath = /["']public["']\s*,\s*["']app\.js["']|\bpublic\/app\.js/.test(text) && /\breadFile(Sync)?\b/.test(text);
|
||||
return oneStatement || handedToAHelper || publicPath;
|
||||
})
|
||||
.map((f) => `${f} reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it`);
|
||||
}
|
||||
|
||||
test("shape: no test in scripts/ reads public/app.js as text", () => {
|
||||
assert.deepEqual(appJsReaders(SCRIPTS_DIR), []);
|
||||
});
|
||||
|
||||
test("shape: the app.js check names the test file that reads it", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shape-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "test-fine.mjs"), 'const r = await fetch(base + "/app.js");\nfs.appendFileSync(path.join(d, "src", "app.js"), "x");\n');
|
||||
assert.deepEqual(appJsReaders(dir), []);
|
||||
fs.writeFileSync(path.join(dir, "test-reads-it.mjs"), 'const app = fs.readFileSync(path.join(ROOT, "public", "app.js"), "utf8");\n');
|
||||
assert.deepEqual(appJsReaders(dir), ["test-reads-it.mjs reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it"]);
|
||||
fs.rmSync(path.join(dir, "test-reads-it.mjs"));
|
||||
fs.writeFileSync(path.join(dir, "test-alias.mjs"), 'const web = (f) => fs.readFileSync(path.join(ROOT, "public", f), "utf8");\nconst app = web("app.js");\n');
|
||||
assert.deepEqual(appJsReaders(dir), ["test-alias.mjs reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// The stylesheet is many files under public/styles/, joined by the server into
|
||||
// the one /app.css the page asks for. CSS_ORDER is the one place the cascade
|
||||
// order is stated: every file in it exists, each once, and no file in the folder
|
||||
// is left out of it or served on its own.
|
||||
test("shape: CSS_ORDER names every file in public/styles/ once, and none is served on its own", async () => {
|
||||
const { CSS_ORDER, SERVABLE } = await import("../src/web-console/static.mjs");
|
||||
const dir = path.join(CONSOLE_DIR, "public", "styles");
|
||||
assert.ok(CSS_ORDER.length > 0, "CSS_ORDER lists files");
|
||||
assert.equal(new Set(CSS_ORDER).size, CSS_ORDER.length, "no file is listed twice");
|
||||
for (const f of CSS_ORDER) assert.ok(fs.existsSync(path.join(dir, f)), `CSS_ORDER lists ${f}, which is not in public/styles/`);
|
||||
const onDisk = fs.readdirSync(dir).filter((f) => f.endsWith(".css")).sort();
|
||||
assert.deepEqual([...CSS_ORDER].sort(), onDisk, "public/styles/ holds exactly the files CSS_ORDER lists");
|
||||
for (const rel of SERVABLE) assert.ok(!rel.startsWith("styles/") && !CSS_ORDER.includes(rel), `${rel} must not be served on its own`);
|
||||
});
|
||||
|
||||
// The files table in AGENTS-architecture.md gives every console file a row,
|
||||
// so a contributor finds where a job lives without searching. A row's first
|
||||
// cell names the file by its path under src/web-console/ (backticked; one cell
|
||||
// may name several files, joined by "·").
|
||||
const ARCHITECTURE_DOC = path.join(ROOT, ".agents-docs", "AGENTS-architecture.md");
|
||||
|
||||
// The paths the files table names, from the first cell of each table row.
|
||||
function tableFiles(markdown) {
|
||||
const named = new Set();
|
||||
for (const line of markdown.split("\n")) {
|
||||
if (!line.startsWith("|")) continue;
|
||||
const cell = line.split("|")[1] || "";
|
||||
for (const m of cell.matchAll(/`([^`]+)`/g)) named.add(m[1]);
|
||||
}
|
||||
return named;
|
||||
}
|
||||
|
||||
// One line per console file with no row in the table.
|
||||
function undocumented(dir, markdown) {
|
||||
const named = tableFiles(markdown);
|
||||
return sourceFiles(dir)
|
||||
.filter((p) => !named.has(p))
|
||||
.map((p) => `${p} has no row in the files table of AGENTS-architecture.md: add one with its one-line job`);
|
||||
}
|
||||
|
||||
test("shape: every console file has a row in the files table of AGENTS-architecture.md", () => {
|
||||
const problems = undocumented(CONSOLE_DIR, fs.readFileSync(ARCHITECTURE_DOC, "utf8"));
|
||||
assert.deepEqual(problems, []);
|
||||
});
|
||||
|
||||
test("shape: the docs-table check names a file with no row, and passes one that has it", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-docs-table-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "public"));
|
||||
fs.writeFileSync(path.join(dir, "a.mjs"), "");
|
||||
fs.writeFileSync(path.join(dir, "public", "b.js"), "");
|
||||
const table = "| File | Role |\n|---|---|\n| `a.mjs` | the first |\n";
|
||||
assert.deepEqual(undocumented(dir, table), [
|
||||
"public/b.js has no row in the files table of AGENTS-architecture.md: add one with its one-line job",
|
||||
]);
|
||||
assert.deepEqual(undocumented(dir, `${table}| \`public/b.js\` · \`x.js\` | the second |\n`), []);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,382 @@
|
||||
// Web console tests, the skill list: public/skills.js holds every per-skill
|
||||
// fact the console uses, and the older tables are lookups on it.
|
||||
// Run with: node --test scripts/test-web-console-skills.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
SKILLS,
|
||||
skillFor,
|
||||
skillByName,
|
||||
isBuild,
|
||||
isPhased,
|
||||
isMetered,
|
||||
subagentsFor,
|
||||
takesTemplates,
|
||||
labelFor,
|
||||
WORKFLOWS,
|
||||
isWorkflow,
|
||||
} from "../src/web-console/public/skills.js";
|
||||
import { CONSOLE_WORKFLOWS, SKILL_CATALOG, catalogEntry, launchVariant, START_POSES, WORKFLOW_LABEL, dashNoteKind, onInitialPick, startPose, startingHint } from "../src/web-console/public/answers.js";
|
||||
import { LAUNCH_COUNTED, PROGRESS_WORKFLOWS } from "../src/web-console/public/meter.js";
|
||||
import { BUILD_WORKFLOWS } from "../src/web-console/public/labels.js";
|
||||
import { helpTabFor } from "../src/web-console/public/help.js";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { ROOT, cli, poseTemplate } from "./web-console-test-helpers.mjs";
|
||||
import { SUBAGENT_WORKFLOWS } from "../src/web-console/public/subagents.js";
|
||||
import { TEMPLATE_WORKFLOWS } from "../src/web-console/public/starters.js";
|
||||
|
||||
// meter.js keeps its answers-row names private: what they were when the list
|
||||
// moved, written out. A skill added since has no row here, and only has to
|
||||
// have a name.
|
||||
const NAMES_AT_THE_MOVE = {
|
||||
dashboard: "the dashboard",
|
||||
pathfinder: "Pathfinder",
|
||||
plan: "Plan",
|
||||
"revise-plan": "Revise plan",
|
||||
document: "Document",
|
||||
implement: "Implement",
|
||||
"implement-review": "Implement + Review",
|
||||
review: "Review",
|
||||
"quick-task": "Quick task",
|
||||
init: "Init",
|
||||
"init-update": "Init update",
|
||||
finalize: "Finalize",
|
||||
handoff: "Handoff",
|
||||
git: "Git",
|
||||
changelog: "Changelog",
|
||||
xray: "X-ray",
|
||||
diagnose: "Diagnose",
|
||||
};
|
||||
|
||||
const CARD_FIELDS = ["group", "chip", "title", "blurb", "about", "spec"];
|
||||
|
||||
test("every skill the console knows has one entry, the dashboard included", () => {
|
||||
const workflows = SKILLS.map((s) => s.workflow);
|
||||
assert.deepEqual([...workflows].sort(), Object.keys(WORKFLOW_LABEL).sort());
|
||||
assert.equal(new Set(workflows).size, workflows.length, "one entry per workflow");
|
||||
assert.deepEqual(SKILLS.map((s) => s.command).sort(), [...CONSOLE_WORKFLOWS].sort());
|
||||
// The cards come first, in the dashboard's order.
|
||||
const carded = SKILLS.filter((s) => s.card);
|
||||
assert.deepEqual(carded.map((s) => s.skill), SKILL_CATALOG.map((e) => e.skill));
|
||||
assert.equal(skillFor("dashboard").skill, "plan2code");
|
||||
assert.equal(skillFor("dashboard").card, null, "the dashboard is the hub, not a card");
|
||||
});
|
||||
|
||||
// The older exports (WORKFLOW_LABEL, SKILL_CATALOG, LAUNCH_COUNTED and the
|
||||
// rest) are now built from SKILLS, so this checks the wiring: each one still
|
||||
// says what its entry says. It proved the move when the tables were still
|
||||
// written by hand; the meter names and the build flags, which have no
|
||||
// importable twin, are held to their values at the move.
|
||||
test("the derived exports agree with each entry", () => {
|
||||
for (const s of SKILLS) {
|
||||
const w = s.workflow;
|
||||
for (const f of ["skill", "workflow", "label", "name"]) assert.ok(typeof s[f] === "string" && s[f].trim(), `${w}: ${f} must be filled in`);
|
||||
assert.equal(s.command, "/" + s.skill, `${w}: command`);
|
||||
assert.equal(s.label, WORKFLOW_LABEL[w], `${w}: label`);
|
||||
if (Object.hasOwn(NAMES_AT_THE_MOVE, w)) assert.equal(s.name, NAMES_AT_THE_MOVE[w], `${w}: name`);
|
||||
assert.equal(s.pose, startPose(w), `${w}: pose`);
|
||||
assert.equal(s.metered, LAUNCH_COUNTED.has(w), `${w}: metered`);
|
||||
assert.equal(s.subagents, SUBAGENT_WORKFLOWS[w] ? SUBAGENT_WORKFLOWS[w].instruction : null, `${w}: subagents`);
|
||||
assert.equal(s.templates, TEMPLATE_WORKFLOWS.includes(w), `${w}: templates`);
|
||||
if (Object.hasOwn(NAMES_AT_THE_MOVE, w)) {
|
||||
assert.equal(s.builds, ["implement", "implement-review", "quick-task"].includes(w), `${w}: builds`);
|
||||
assert.equal(s.phased, ["implement", "implement-review"].includes(w), `${w}: phased`);
|
||||
}
|
||||
const entry = SKILL_CATALOG.find((e) => e.workflow === w);
|
||||
if (!entry) {
|
||||
assert.equal(s.card, null, `${w}: no card`);
|
||||
continue;
|
||||
}
|
||||
assert.equal(entry.skill, s.skill, `${w}: skill`);
|
||||
assert.equal(entry.command, s.command, `${w}: card command`);
|
||||
for (const f of CARD_FIELDS) assert.equal(s.card[f], entry[f], `${w}: card.${f}`);
|
||||
}
|
||||
// Every pose in the page's list belongs to an entry.
|
||||
for (const pose of START_POSES) assert.ok(SKILLS.some((s) => s.pose === pose), `${pose} belongs to a skill`);
|
||||
for (const w of PROGRESS_WORKFLOWS) assert.ok(isPhased(w), `${w} counts its tasks`);
|
||||
});
|
||||
|
||||
test("the entries are frozen data", () => {
|
||||
assert.ok(Object.isFrozen(SKILLS));
|
||||
for (const s of SKILLS) {
|
||||
assert.ok(Object.isFrozen(s), `${s.workflow} is frozen`);
|
||||
if (s.card) assert.ok(Object.isFrozen(s.card), `${s.workflow}.card is frozen`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the meter, resume and Help fields are well formed on every entry", () => {
|
||||
const label = (v) => v === null || (typeof v === "string" && v.trim() !== "");
|
||||
for (const s of SKILLS) {
|
||||
const w = s.workflow;
|
||||
assert.ok(Object.hasOwn(s, "weight") && (s.weight === null || (typeof s.weight === "number" && s.weight >= 0)), `${w}: weight is a number >= 0, or null`);
|
||||
assert.ok(Object.hasOwn(s, "started") && label(s.started), `${w}: started is a label, or null`);
|
||||
assert.ok(Object.hasOwn(s, "ran") && label(s.ran), `${w}: ran is a label, or null`);
|
||||
assert.ok(Object.hasOwn(s, "resume") && ["overview", "folder", null].includes(s.resume), `${w}: resume is "overview", "folder" or null`);
|
||||
if (s.card && Object.hasOwn(s.card, "help")) assert.ok(typeof s.card.help === "string" && s.card.help.trim(), `${w}: card.help is a line, or absent`);
|
||||
if (s.metered) assert.ok(typeof s.weight === "number" && s.started, `${w}: a metered launch has a weight and a started label`);
|
||||
}
|
||||
});
|
||||
|
||||
test("WORKFLOWS lists every entry once, in order, and isWorkflow() knows only those", () => {
|
||||
assert.deepEqual(WORKFLOWS, SKILLS.map((s) => s.workflow));
|
||||
assert.equal(new Set(WORKFLOWS).size, WORKFLOWS.length);
|
||||
assert.ok(Object.isFrozen(WORKFLOWS));
|
||||
for (const w of WORKFLOWS) assert.equal(isWorkflow(w), true, w);
|
||||
for (const bad of ["x-ray", "", undefined, null, 3, "Plan"]) assert.equal(isWorkflow(bad), false, String(bad));
|
||||
});
|
||||
|
||||
test("the lookups answer by workflow or skill name, and say nothing for an unknown one", () => {
|
||||
assert.equal(skillFor("implement-review").skill, "plan2code-3-implement-review");
|
||||
assert.equal(skillByName("plan2code-git").workflow, "git");
|
||||
assert.equal(skillByName("plan2code").workflow, "dashboard");
|
||||
assert.equal(labelFor("xray"), "X-ray");
|
||||
assert.equal(subagentsFor("review"), SUBAGENT_WORKFLOWS.review.instruction);
|
||||
for (const unknown of ["nope", undefined, null, "", "constructor", "__proto__"]) {
|
||||
assert.equal(skillFor(unknown), null);
|
||||
assert.equal(skillByName(unknown), null);
|
||||
assert.equal(labelFor(unknown), null);
|
||||
assert.equal(subagentsFor(unknown), null);
|
||||
for (const is of [isBuild, isPhased, isMetered, takesTemplates]) assert.equal(is(unknown), false);
|
||||
}
|
||||
});
|
||||
|
||||
// Which workflows labels.js and help.js count as builds, as they stood when the
|
||||
// sets moved onto skills.js: labels.js leaves Quick Task out, help.js keeps it.
|
||||
test("the two build sets hold what they held before", () => {
|
||||
assert.deepEqual([...BUILD_WORKFLOWS].sort(), ["implement", "implement-review"]);
|
||||
assert.deepEqual(SKILLS.filter((s) => isBuild(s.workflow)).map((s) => s.workflow).sort(), ["implement", "implement-review", "quick-task"]);
|
||||
// help.js keeps its set private: Help opens on its Building tab for exactly these.
|
||||
const onBuild = SKILLS.map((s) => s.workflow).filter((workflow) => helpTabFor({ workflow }) === "build");
|
||||
assert.deepEqual(onBuild.sort(), ["implement", "implement-review", "quick-task"]);
|
||||
assert.equal(helpTabFor({ workflow: "nope" }), "about");
|
||||
});
|
||||
|
||||
/* ------------------------------------------- tests that name what was missed */
|
||||
|
||||
// Each check below is a pure function of a skill list, so a test can hand it a
|
||||
// copy with one thing wrong and see the message name the skill.
|
||||
|
||||
// Each skill's starting screen clones its pose from index.html. A pose with no
|
||||
// drawing silently falls back to the flight, and a drawing no skill uses is
|
||||
// dead markup.
|
||||
function poseProblems(skills, drawn) {
|
||||
const problems = [];
|
||||
for (const s of skills) {
|
||||
if (s.card && !s.pose) problems.push(`${s.skill} has a card but no pose`);
|
||||
if (s.pose && !drawn.includes(s.pose)) problems.push(`${s.skill} names pose "${s.pose}", which index.html does not draw`);
|
||||
}
|
||||
for (const pose of drawn) {
|
||||
if (!skills.some((s) => s.pose === pose)) problems.push(`index.html draws pose "${pose}", which belongs to no skill`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// Every workflow the console can open has its notes behind `console.mjs help`.
|
||||
function helpProblems(skills, topics) {
|
||||
return skills.filter((s) => !Object.hasOwn(topics, s.workflow)).map((s) => `${s.skill} (${s.workflow}) has no help topic in console.mjs`);
|
||||
}
|
||||
|
||||
// The skills with a card, plus the dashboard, are exactly what install.js builds.
|
||||
function installProblems(skills, installed) {
|
||||
const reviews = skills.map((s) => s.review).filter(Boolean);
|
||||
const named = skills.filter((s) => s.card || s.workflow === "dashboard" || reviews.includes(s.skill)).map((s) => s.skill);
|
||||
return [
|
||||
...named.filter((n) => !installed.includes(n)).map((n) => `${n} is in skills.js but not in install.js SOURCE_PROMPTS`),
|
||||
...installed.filter((n) => !named.includes(n)).map((n) => `${n} is in install.js SOURCE_PROMPTS but has no card in skills.js`),
|
||||
];
|
||||
}
|
||||
|
||||
const drawnPoses = () => [...poseTemplate().matchAll(/data-pose="([^"]+)"/g)].map((m) => m[1]);
|
||||
const helpTopics = () => cli(["help", "topics"]).json.topics;
|
||||
|
||||
// install.js reads the home directory at load: point it at a temp one, as the
|
||||
// install tests do. Requiring it never runs its CLI (that waits on require.main).
|
||||
function installedSkills() {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-skills-"));
|
||||
const saved = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE };
|
||||
process.env.HOME = home;
|
||||
process.env.USERPROFILE = home;
|
||||
try {
|
||||
const { SOURCE_PROMPTS, generateSkillName } = createRequire(import.meta.url)(path.join(ROOT, "install.js"));
|
||||
return SOURCE_PROMPTS.map(generateSkillName);
|
||||
} finally {
|
||||
for (const [k, v] of Object.entries(saved)) v === undefined ? delete process.env[k] : (process.env[k] = v);
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test("every skill's pose is drawn in the page, and every drawn pose belongs to a skill", () => {
|
||||
const drawn = drawnPoses();
|
||||
assert.deepEqual(poseProblems(SKILLS, drawn), []);
|
||||
assert.doesNotMatch(poseTemplate(), /\sstyle=/, "a style attribute would be refused by the CSP");
|
||||
// Variants borrow their pose; the dashboard keeps the flight.
|
||||
assert.equal(startPose("implement-review"), "implement");
|
||||
assert.equal(startPose("revise-plan"), "plan");
|
||||
assert.equal(startPose("init-update"), "init");
|
||||
assert.equal(startPose("dashboard"), null);
|
||||
assert.equal(startPose(undefined), null);
|
||||
|
||||
const broken = SKILLS.map((s) => (s.workflow === "xray" ? { ...s, pose: "x-ray-glasses" } : s));
|
||||
assert.deepEqual(poseProblems(broken, drawn), [
|
||||
'plan2code-xray names pose "x-ray-glasses", which index.html does not draw',
|
||||
'index.html draws pose "xray", which belongs to no skill',
|
||||
]);
|
||||
const poseless = SKILLS.map((s) => (s.workflow === "git" ? { ...s, pose: null } : s));
|
||||
assert.deepEqual(poseProblems(poseless, drawn), ["plan2code-git has a card but no pose", 'index.html draws pose "git", which belongs to no skill']);
|
||||
});
|
||||
|
||||
test("every workflow in the skill list has a help topic", () => {
|
||||
const topics = helpTopics();
|
||||
assert.deepEqual(helpProblems(SKILLS, topics), []);
|
||||
const extra = [...SKILLS, { skill: "plan2code-made-up", workflow: "made-up" }];
|
||||
assert.deepEqual(helpProblems(extra, topics), ["plan2code-made-up (made-up) has no help topic in console.mjs"]);
|
||||
});
|
||||
|
||||
test("the skill list and install.js agree on which skills exist", () => {
|
||||
const installed = installedSkills();
|
||||
assert.ok(installed.includes("plan2code"), "read SOURCE_PROMPTS");
|
||||
assert.deepEqual(installProblems(SKILLS, installed), []);
|
||||
const extra = [...SKILLS, { skill: "plan2code-made-up", workflow: "made-up", card: {} }];
|
||||
assert.deepEqual(installProblems(extra, installed), ["plan2code-made-up is in skills.js but not in install.js SOURCE_PROMPTS"]);
|
||||
assert.deepEqual(installProblems(SKILLS, [...installed, "plan2code-orphan"]), ["plan2code-orphan is in install.js SOURCE_PROMPTS but has no card in skills.js"]);
|
||||
});
|
||||
|
||||
test("dashboard note: the agent's note shows only on the spec the picker opened on", () => {
|
||||
const a = { dir: "specs/a" };
|
||||
const b = { dir: "specs/b" };
|
||||
assert.equal(onInitialPick(a, a), true);
|
||||
assert.equal(onInitialPick(a, b), false);
|
||||
assert.equal(onInitialPick(a, null), false);
|
||||
assert.equal(onInitialPick(null, null), true, "no spec at all: scratch is the opening pick");
|
||||
assert.equal(onInitialPick(null, a), false);
|
||||
});
|
||||
|
||||
test("dashboard note: the agent's note, the looking-over line and the neutral line", () => {
|
||||
const menu = { note: "Phase 2 is next." };
|
||||
assert.equal(dashNoteKind({ menu, hasMenu: true, onInitial: true, working: false }), "agent");
|
||||
assert.equal(dashNoteKind({ menu, hasMenu: true, onInitial: false, working: false }), "neutral", "another pick, another line");
|
||||
assert.equal(dashNoteKind({ menu: { note: " " }, hasMenu: true, onInitial: true, working: true }), "neutral", "a blank note is no note");
|
||||
assert.equal(dashNoteKind({ menu: {}, hasMenu: false, onInitial: true, working: true }), "looking");
|
||||
assert.equal(dashNoteKind({ menu: {}, hasMenu: false, onInitial: true, working: false }), "neutral");
|
||||
});
|
||||
|
||||
test("starting screen: the hint stays calm for ninety seconds, then points at the terminal", () => {
|
||||
assert.match(startingHint(0), /fills in by itself/);
|
||||
assert.match(startingHint(90000), /fills in by itself/, "ninety seconds is still calm");
|
||||
assert.match(startingHint(90001), /terminal has the play-by-play/);
|
||||
});
|
||||
|
||||
/* ---------------------------------------------- the docs held to the list */
|
||||
|
||||
// What one prose list says against what it should say: the lines naming the
|
||||
// missing and the extra names, empty when they agree.
|
||||
function listProblems(file, said, want) {
|
||||
const have = new Set(said);
|
||||
const should = new Set(want);
|
||||
return [
|
||||
...[...should].filter((n) => !have.has(n)).map((n) => `${file} is missing ${n}`),
|
||||
...[...have].filter((n) => !should.has(n)).map((n) => `${file} names ${n}, which is not in skills.js`),
|
||||
];
|
||||
}
|
||||
|
||||
const readSrc = (...parts) => fs.readFileSync(path.join(ROOT, "src", ...parts), "utf8");
|
||||
|
||||
// A markdown section's text: from its heading to the next heading of the same level.
|
||||
function sectionOf(text, heading) {
|
||||
const at = text.indexOf(heading);
|
||||
assert.ok(at >= 0, `no "${heading}" heading`);
|
||||
const level = heading.match(/^#+/)[0];
|
||||
const rest = text.slice(at + heading.length);
|
||||
const next = rest.search(new RegExp(`\\n${level} `));
|
||||
return next < 0 ? rest : rest.slice(0, next);
|
||||
}
|
||||
|
||||
test("docs: console.md's open step names every workflow", () => {
|
||||
const text = readSrc("web-console", "console.md");
|
||||
const m = text.match(/where `<w>` is one of ([\s\S]*?)\. Get it right/);
|
||||
assert.ok(m, "console.md: the open step's `<w>` sentence is not where the test looks");
|
||||
const said = [...m[1].matchAll(/`([^`]+)`/g)].map((x) => x[1]);
|
||||
assert.deepEqual(listProblems("src/web-console/console.md", said, WORKFLOWS), []);
|
||||
});
|
||||
|
||||
test("docs: the dashboard skill's launch table maps every skill to its workflow", () => {
|
||||
const section = sectionOf(readSrc("plan2code.md"), "## A pick arrives");
|
||||
const pairs = [];
|
||||
for (const line of section.split(/\r?\n/)) {
|
||||
if (!/^\|\s*plan2code-/.test(line)) continue;
|
||||
const cells = line.split("|").map((c) => c.trim()).filter(Boolean);
|
||||
for (let i = 0; i + 1 < cells.length; i += 2) pairs.push(`${cells[i]} -> ${cells[i + 1]}`);
|
||||
}
|
||||
const want = SKILLS.filter((s) => s.workflow !== "dashboard").map((s) => `${s.skill} -> ${s.workflow}`);
|
||||
assert.deepEqual(listProblems("src/plan2code.md (A pick arrives)", pairs, want), []);
|
||||
});
|
||||
|
||||
test("docs: the dashboard skill's reads-and-writes table has a row for every skill", () => {
|
||||
const section = sectionOf(readSrc("plan2code.md"), "## What each skill reads and writes");
|
||||
const said = [];
|
||||
for (const line of section.split(/\r?\n/)) {
|
||||
const m = line.match(/^\|\s*([a-z0-9()-]+)\s*\|/);
|
||||
if (!m || m[1] === "skill" || /^-+$/.test(m[1])) continue;
|
||||
// `3-implement(-review)` stands for both build skills.
|
||||
if (m[1] === "3-implement(-review)") said.push("3-implement", "3-implement-review");
|
||||
else said.push(m[1]);
|
||||
}
|
||||
const want = SKILLS.filter((s) => s.workflow !== "dashboard").map((s) => s.skill.replace(/^plan2code-/, ""));
|
||||
assert.deepEqual(listProblems("src/plan2code.md (What each skill reads and writes)", said, want), []);
|
||||
});
|
||||
|
||||
test("docs: `console.mjs help` lists every workflow, in order", () => {
|
||||
const out = cli(["help"]).stdout;
|
||||
const m = out.match(/workflows: ([\s\S]*?)\n\s*\n/);
|
||||
assert.ok(m, "console.mjs help prints no workflows: list");
|
||||
const said = m[1].split(/[·\s]+/).filter(Boolean);
|
||||
assert.deepEqual(listProblems("console.mjs help", said, WORKFLOWS), []);
|
||||
assert.deepEqual(said, [...WORKFLOWS], "console.mjs help: the workflows are in skills.js order");
|
||||
});
|
||||
|
||||
// A count goes stale the day a skill is added; the docs say "every skill".
|
||||
// Matched over the whole file, since the docs are hard-wrapped and a count can
|
||||
// sit on one line with "skills" on the next; the line is where the match starts.
|
||||
const SKILL_COUNT_RE = /\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)\s+skills\b/gi;
|
||||
function skillCounts(files) {
|
||||
return files.flatMap(([file, text]) =>
|
||||
[...text.matchAll(SKILL_COUNT_RE)].map((m) => `${file}:${text.slice(0, m.index).split("\n").length} states a skill count: ${m[0].replace(/\s+/g, " ")}`)
|
||||
);
|
||||
}
|
||||
|
||||
test("docs: no console doc states how many skills there are", () => {
|
||||
const dir = path.join(ROOT, "src", "web-console");
|
||||
const files = [];
|
||||
const walk = (d) => {
|
||||
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
||||
const p = path.join(d, e.name);
|
||||
if (e.isDirectory()) walk(p);
|
||||
else if (e.name.endsWith(".md")) files.push([path.relative(ROOT, p).replace(/\\/g, "/"), fs.readFileSync(p, "utf8")]);
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
assert.ok(files.some(([f]) => f.endsWith("notes/implement.md")), "the walk reaches notes/");
|
||||
assert.deepEqual(skillCounts(files), []);
|
||||
// The check names the line, and catches a count wrapped across two lines.
|
||||
assert.deepEqual(skillCounts([["x.md", "Intro\nthe dashboard and all twelve skills behind it\n"]]), ["x.md:2 states a skill count: twelve skills"]);
|
||||
assert.deepEqual(skillCounts([["y.md", "Intro\nthe dashboard and all twelve\nskills behind it\n"]]), ["y.md:2 states a skill count: twelve skills"]);
|
||||
});
|
||||
|
||||
test("Implement's card launches Implement + Review when Review is ticked", () => {
|
||||
const card = SKILL_CATALOG.find((e) => e.skill === "plan2code-3-implement");
|
||||
assert.equal(card.title, "Implement");
|
||||
assert.equal(SKILL_CATALOG.some((e) => e.skill === "plan2code-3-implement-review"), false, "no card of its own");
|
||||
assert.equal(launchVariant(card, false), card);
|
||||
const reviewed = launchVariant(card, true);
|
||||
assert.equal(reviewed.skill, "plan2code-3-implement-review");
|
||||
assert.equal(reviewed.workflow, "implement-review");
|
||||
assert.equal(reviewed.command, "/plan2code-3-implement-review");
|
||||
assert.equal(reviewed.spec, true, "still takes the picked spec");
|
||||
assert.equal(catalogEntry("plan2code-3-implement-review").skill, "plan2code-3-implement", "handoffs and recommendations resolve to the card");
|
||||
const quick = SKILL_CATALOG.find((e) => e.skill === "plan2code-quick-task");
|
||||
assert.equal(launchVariant(quick, true), quick, "a card with no Review box is unchanged");
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import path from "node:path";
|
||||
// (it touches `document` at module scope and starts a session on import), which
|
||||
// is exactly why this lives in its own file.
|
||||
import { cardAvailability, SKILL_CATALOG } from "../src/web-console/public/answers.js";
|
||||
import { SKILLS } from "../src/web-console/public/skills.js";
|
||||
import { HELP_TABS } from "../src/web-console/public/help.js";
|
||||
import { FAVICON_BODY, FAVICON_COLORS, faviconState, faviconSvg } from "../src/web-console/public/favicon.js";
|
||||
import {
|
||||
@@ -24,8 +25,9 @@ import {
|
||||
latestTag,
|
||||
} from "../src/web-console/update-check.mjs";
|
||||
import { runHint } from "../src/web-console/public/render.js";
|
||||
import { applyPatch } from "../src/web-console/lib.mjs";
|
||||
import { applyPatch } from "../src/web-console/patches.mjs";
|
||||
import { ROOT, cli, helpTemplate, sessionUrl } from "./web-console-test-helpers.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
|
||||
test("favicon: the dot follows the status line -- busy, ready, attention, plain", () => {
|
||||
// Anything with the spinning ring is busy, even a finished screen opening the dashboard.
|
||||
@@ -82,7 +84,7 @@ test("runHint: command words (git included) get the hint, the rest nothing", ()
|
||||
});
|
||||
|
||||
test("a reused item id does not inherit the previous answer's submitted record", async () => {
|
||||
const { applyPatch } = await import("../src/web-console/lib.mjs");
|
||||
const { applyPatch } = await import("../src/web-console/patches.mjs");
|
||||
const before = { items: [{ id: "q7", kind: "choice", title: "A", body: "old", status: "open", submitted: { at: "t", text: "old answer" } }] };
|
||||
const reworded = applyPatch(before, { items: [{ id: "q7", kind: "choice", title: "B", body: "new", status: "open" }] });
|
||||
assert.equal(reworded.items[0].submitted, undefined);
|
||||
@@ -100,7 +102,7 @@ test("a reused item id does not inherit the previous answer's submitted record",
|
||||
});
|
||||
|
||||
test("unansweredChat lists delivered Quick questions that still have no reply", async () => {
|
||||
const { unansweredChat, appendChat, writeCursor } = await import("../src/web-console/lib.mjs");
|
||||
const { unansweredChat, appendChat, writeCursor } = await import("../src/web-console/inbox.mjs");
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-chat-"));
|
||||
appendChat(dir, { kind: "reset", conversation: 1, workflow: "dashboard", reason: "start" });
|
||||
appendChat(dir, { kind: "message", conversation: 1, text: "run it" });
|
||||
@@ -248,9 +250,72 @@ test("update check: the frame carries update only when a newer release is cached
|
||||
}
|
||||
});
|
||||
|
||||
test("stop modal: handoff choice first, plain stop second, Keep going last, styled and wired", () => {
|
||||
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
|
||||
const html = web("index.html");
|
||||
const css = joinedCss();
|
||||
const dialog = html.match(/<dialog class="modal" id="stop-modal"[^>]*>([\s\S]*?)<\/dialog>/);
|
||||
assert.ok(dialog, "index.html has the stop modal");
|
||||
const body = dialog[1];
|
||||
const at = (id) => body.indexOf(`id="${id}"`);
|
||||
assert.ok(at("stop-handoff") >= 0 && at("stop-handoff") < at("stop-go") && at("stop-go") < at("stop-cancel"), "handoff, plain stop, Keep going, in that order");
|
||||
assert.ok(body.includes("Stop with a handoff") && body.includes("Just stop and save"));
|
||||
assert.doesNotMatch(body, /\sstyle=|<script/i);
|
||||
assert.match(css, /\.stop-choice/, "app.css styles the choices");
|
||||
assert.match(css, /\.stop-choice:focus-visible/, "and gives them a focus outline");
|
||||
const help = helpTemplate().match(/<section class="help-panel" data-tab="finishing">([\s\S]*?)<\/section>/);
|
||||
assert.ok(help && help[1].includes("Stop with a handoff") && help[1].includes("Just stop and save") && help[1].includes("~/.plan2code/handoffs/"), "Help names both choices and where handoffs land");
|
||||
});
|
||||
|
||||
// The dashboard's handoff chips, preview and their four actions. What they
|
||||
// do on the page is held by the page tests in test-web-console-page-dashboard.mjs;
|
||||
// this keeps the style, the modal markup and the Help.
|
||||
test("dashboard handoffs: the style, the read dialog and the delete warning ship, and Help explains the chips", () => {
|
||||
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
|
||||
const css = joinedCss();
|
||||
const html = web("index.html");
|
||||
|
||||
assert.match(css, /\.spec-chip\.is-handoff/, "app.css styles handoff chips");
|
||||
assert.match(css, /\.handoff-preview\b/, "and the preview panel");
|
||||
|
||||
const modal = html.match(/<dialog class="modal handoff-read" id="handoff-modal"[^>]*>([\s\S]*?)<\/dialog>/);
|
||||
assert.ok(modal, "index.html has #handoff-modal");
|
||||
assert.doesNotMatch(modal[1], /\sstyle=|<script/i);
|
||||
assert.ok(html.includes('id="delete-warn-handoff"'), "the delete dialog carries the handoff warning");
|
||||
|
||||
const panel = helpTemplate().match(/<section class="help-panel" data-tab="dashboard">([\s\S]*?)<\/section>/);
|
||||
assert.ok(panel && panel[1].includes("Pick it up here") && panel[1].includes("30-day sweep"), "Help explains handoff chips");
|
||||
});
|
||||
|
||||
// The sign-off card: Approve comes before Show me it working, and an unpicked
|
||||
// approve verdict is outlined in the accent.
|
||||
test("sign-off: approve leads show, and the approve button wears the accent", () => {
|
||||
const doc = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", f), "utf8");
|
||||
for (const f of ["notes/implement.md", "building-review.md"]) {
|
||||
const text = doc(f);
|
||||
const approve = text.indexOf('{ "id": "approve", "label": "Approve this phase" }');
|
||||
const show = text.indexOf('{ "id": "show", "label": "Show me it working" }');
|
||||
assert.ok(approve > 0 && show > approve, `${f} lists Approve this phase before Show me it working`);
|
||||
}
|
||||
assert.match(joinedCss(), /\.btn\.is-approve\s*\{[^}]*border-color:\s*var\(--accent\)/, "is-approve borders in the accent");
|
||||
});
|
||||
|
||||
// A fixed bug's chip: a visible Delete, one confirm, and "bug fixed" said once.
|
||||
// What the fixed bug's chip and Delete do on the page is held by the page tests
|
||||
// in test-web-console-page-dashboard.mjs; this keeps the style and the Help.
|
||||
test("bug fixed delete: the Delete button is styled and Help explains the one confirm", () => {
|
||||
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
|
||||
const css = joinedCss();
|
||||
assert.match(css, /\.spec-chip-del-label\s*\{/, "app.css styles the Delete button");
|
||||
assert.match(css, /\.spec-chip-del-label:focus-visible/, "and gives it a focus outline");
|
||||
|
||||
const panel = helpTemplate().match(/<section class="help-panel" data-tab="dashboard">([\s\S]*?)<\/section>/);
|
||||
assert.ok(panel && /fixed\s+bug[\s\S]*?Delete[\s\S]*?one\s+confirm/i.test(panel[1]), "Help says a fixed bug has its own Delete and needs one confirm");
|
||||
});
|
||||
|
||||
test("update banner: the modal is in the page, with the exact command and no inline styles or scripts", () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const dash = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "dashboard.js"), "utf8");
|
||||
const dialog = html.match(/<dialog class="modal" id="update-modal" aria-labelledby="update-title">([\s\S]*?)<\/dialog>/);
|
||||
assert.ok(dialog, "index.html has the update modal");
|
||||
assert.doesNotMatch(dialog[1], /\sstyle=/);
|
||||
@@ -260,32 +325,26 @@ test("update banner: the modal is in the page, with the exact command and no inl
|
||||
assert.match(panel[1], /UPDATE AVAILABLE/, "the dashboard topic explains the banner");
|
||||
assert.doesNotMatch(panel[1], /\sstyle=/);
|
||||
assert.doesNotMatch(panel[1], /<script/i);
|
||||
assert.ok(app.includes('"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"'), "app.js copies the exact command");
|
||||
assert.ok(dash.includes('"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"'), "the dashboard copies the exact command");
|
||||
});
|
||||
|
||||
test("update banner: built only on the dashboard, dismissed per session, and Help's version links to Releases", () => {
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const start = app.indexOf("function renderDashboard(main) {");
|
||||
assert.ok(start >= 0, "app.js has renderDashboard");
|
||||
const end = app.indexOf("\n}\n", start);
|
||||
const body = app.slice(start, end);
|
||||
assert.match(body, /"dash-nudge update-banner"/, "renderDashboard builds the banner");
|
||||
const outside = app.slice(0, start) + app.slice(end);
|
||||
assert.doesNotMatch(outside, /update-banner/, "no other code builds it");
|
||||
assert.match(app, /"p2c-update-dismissed:" \+ S\.sid/, "the dismissal is keyed by the session id");
|
||||
assert.match(app, /const RELEASES_URL = "https:\/\/github\.com\/jparkerweb\/plan2code\/releases\/";/);
|
||||
assert.match(app, /\.rel = "noopener noreferrer";/);
|
||||
const help = app.match(/async function renderHelpVersion\(\) \{([\s\S]*?)\n\}/);
|
||||
assert.ok(help, "app.js has renderHelpVersion");
|
||||
assert.match(help[1], /releasesLink\(/, "the help version is a Releases link");
|
||||
const dash = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "dashboard.js"), "utf8");
|
||||
const render = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "render.js"), "utf8");
|
||||
assert.match(dash, /"p2c-update-dismissed:" \+ page\.S\.sid/, "the dismissal is keyed by the session id");
|
||||
assert.match(render, /const RELEASES_URL = "https:\/\/github\.com\/jparkerweb\/plan2code\/releases\/";/);
|
||||
assert.match(render, /\.rel = "noopener noreferrer";/);
|
||||
});
|
||||
|
||||
// The Changelog card sits left of Git, the last card. It is always clickable,
|
||||
// and a launch from it resumes the session under its own workflow.
|
||||
test("the Changelog card comes just before Git, Git is last, and Changelog is always on", () => {
|
||||
const skills = SKILL_CATALOG.map((e) => e.skill);
|
||||
assert.equal(skills.indexOf("plan2code-changelog") + 1, skills.indexOf("plan2code-git"));
|
||||
assert.equal(skills[skills.length - 1], "plan2code-git");
|
||||
// The Changelog card sits left of Git, which sits left of Handoff, the last
|
||||
// card. It is always clickable, and a launch from it resumes the session under
|
||||
// its own workflow.
|
||||
test("the Changelog card comes just before Git, Handoff is last, and Changelog is always on", () => {
|
||||
// The card order is skills.js's order.
|
||||
const skills = SKILLS.filter((s) => s.card).map((s) => s.skill);
|
||||
assert.equal(skills.indexOf("plan2code-changelog") + 1, skills.indexOf("plan2code-git"), "Changelog sits just before Git");
|
||||
assert.equal(skills.indexOf("plan2code-git") + 1, skills.indexOf("plan2code-handoff"), "Git sits just before Handoff");
|
||||
assert.equal(skills.at(-1), "plan2code-handoff", "Handoff is last");
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-changelog");
|
||||
assert.equal(entry.workflow, "changelog");
|
||||
assert.equal(entry.command, "/plan2code-changelog");
|
||||
@@ -315,93 +374,33 @@ test("help: the stuck tab is second, with a callout and four symptom rows before
|
||||
assert.match(panel, /<svg class="help-callout-icon"[^>]*aria-hidden="true"/, "the icon is decoration");
|
||||
});
|
||||
|
||||
// Every say(...) call in a source slice, as its top-level arguments (raw
|
||||
// source text). String-aware, so commas and brackets inside a line are text.
|
||||
function sayCalls(source) {
|
||||
const calls = [];
|
||||
let at = 0;
|
||||
while ((at = source.indexOf("say(", at)) !== -1) {
|
||||
if (/[\w.]/.test(source[at - 1] || "")) {
|
||||
at += 4;
|
||||
continue;
|
||||
}
|
||||
const args = [];
|
||||
let depth = 0;
|
||||
let quote = null;
|
||||
let start = at + 4;
|
||||
let i = start;
|
||||
for (; i < source.length; i++) {
|
||||
const ch = source[i];
|
||||
if (quote) {
|
||||
if (ch === "\\") i++;
|
||||
else if (ch === quote) quote = null;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"' || ch === "'" || ch === "`") quote = ch;
|
||||
else if ("([{".includes(ch)) depth++;
|
||||
else if (")]}".includes(ch)) {
|
||||
if (depth === 0) break;
|
||||
depth--;
|
||||
} else if (ch === "," && depth === 0) {
|
||||
args.push(source.slice(start, i).trim());
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
const last = source.slice(start, i).trim();
|
||||
if (last) args.push(last);
|
||||
calls.push(args);
|
||||
at = i;
|
||||
}
|
||||
return calls;
|
||||
}
|
||||
|
||||
test("status line: the quiet, Not running and Not connected lines offer What to check, opening Help on the stuck tab", () => {
|
||||
const app = publicSource("app.js");
|
||||
assert.equal(HELP_TABS.findIndex((t) => t.id === "stuck"), 1, "the stuck tab is second");
|
||||
const opener = app.match(/function openHelpOn\(id\) \{([\s\S]*?)\n\}/);
|
||||
assert.ok(opener, "app.js has openHelpOn");
|
||||
assert.match(opener[1], /HELP_TABS\.some\(/, "openHelpOn only opens a tab that exists");
|
||||
const render = app.slice(app.indexOf("function renderStatus()"), app.indexOf("/* ---------------------------------------------------------------- brief */"));
|
||||
const sayDef = render.slice(render.indexOf("const say = ("), render.indexOf("text.replaceChildren("));
|
||||
assert.match(sayDef, /help\.textContent = "What to check"/);
|
||||
assert.match(sayDef, /help\.addEventListener\("click", \(\) => openHelpOn\("stuck"\)\)/, "the button opens Help on the stuck tab");
|
||||
const calls = sayCalls(render.slice(render.indexOf("text.replaceChildren(")));
|
||||
const checked = calls.filter((args) => args[4] && args[4] !== "false");
|
||||
for (const needle of ["Not connected. Your answers are saved.", "Still working on it.", "is not running. Your answers are saved", "is not running right now."]) {
|
||||
assert.ok(checked.some((args) => args.join(",").includes(needle)), `"${needle}" carries What to check`);
|
||||
}
|
||||
assert.ok(checked.some((args) => args[4] === "Boolean(hint)"), "the approval hint carries What to check");
|
||||
// Nothing else does: the finished, working and adrift lines stay plain.
|
||||
assert.equal(checked.length, 4, `four calls pass check, got: ${checked.map((a) => a[1]).join(" | ")}`);
|
||||
test("help: privacy names the handoffs folder and preferences says Cleanup never offers it", () => {
|
||||
const tpl = helpTemplate();
|
||||
const privacy = tpl.match(/<section class="help-panel" data-tab="privacy">([\s\S]*?)<\/section>/)[1];
|
||||
const kept = privacy.slice(privacy.indexOf("<h4>What is kept, and where</h4>"));
|
||||
assert.match(kept, /(<code>)?~\/\.plan2code\/handoffs\/(<\/code>)?/, "privacy lists ~/.plan2code/handoffs/");
|
||||
assert.doesNotMatch(
|
||||
kept,
|
||||
/Everything lives under\s+<code>~\/\.plan2code\/console\/<\/code>/,
|
||||
"the lead no longer says everything lives under the console folder"
|
||||
);
|
||||
const prefs = tpl.match(/<section class="help-panel" data-tab="prefs">([\s\S]*?)<\/section>/)[1];
|
||||
const cleanup = prefs.slice(prefs.indexOf("<strong>Cleanup</strong>"), prefs.indexOf("<strong>Back to default</strong>"));
|
||||
assert.match(cleanup, /handoffs/, "the Cleanup text names the handoffs folder");
|
||||
assert.match(cleanup, /never\s+offered/, "the Cleanup text says the handoffs folder is never offered for removal");
|
||||
});
|
||||
|
||||
test("finished screen: Before you close this waits while a hand-off they asked for is starting", () => {
|
||||
const app = publicSource("app.js");
|
||||
const handoff = app.slice(app.indexOf("function renderHandoff("));
|
||||
const body = handoff.slice(0, handoff.indexOf("\n}\n"));
|
||||
assert.match(body, /if \(!closeGuideHeld\(\)\) card\.appendChild\(renderCloseGuide\(shape, fin\)\)/);
|
||||
const held = app.match(/function closeGuideHeld\(\) \{([\s\S]*?)\n\}/);
|
||||
assert.ok(held, "app.js has closeGuideHeld");
|
||||
const run = (gone, afterBuild, pending) =>
|
||||
new Function("gone", "local", "reviewPending", held[1])(gone, { afterBuild }, () => pending);
|
||||
for (const kind of ["review", "commit", "dashboard"]) {
|
||||
assert.equal(run(false, kind, null), true, `held while ${kind} is starting`);
|
||||
}
|
||||
assert.equal(run(false, null, "asked"), true, "held while a review is asked");
|
||||
assert.equal(run(false, null, "open"), false, "shown while the review is only on offer");
|
||||
assert.equal(run(false, null, null), false, "shown on a plain finish");
|
||||
assert.equal(run(false, "done", null), false, "shown once they said they are done");
|
||||
assert.equal(run(true, "review", null), false, "shown once the server is gone: nothing is starting");
|
||||
// The press re-renders the page, and so does the finish going away, so the
|
||||
// panel follows the state.
|
||||
const send = app.slice(app.indexOf("async function sendAfterBuild("), app.indexOf("/* ------------------------------------------------------------- dashboard */"));
|
||||
assert.match(send, /local\.afterBuild = kind;[\s\S]*finally \{\s*render\(\);/);
|
||||
assert.match(app, /if \(!finish\(\) && local\.afterBuild\) \{\s*local\.afterBuild = null;/);
|
||||
test("help: the stuck tab is second, and openHelpOn only opens a tab that exists", () => {
|
||||
const app = publicSource("screens/help-dialog.js");
|
||||
assert.equal(HELP_TABS.findIndex((t) => t.id === "stuck"), 1, "the stuck tab is second");
|
||||
const opener = app.match(/function openHelpOn\(id\) \{([\s\S]*?)\n\}/);
|
||||
assert.ok(opener, "help-dialog.js has openHelpOn");
|
||||
assert.match(opener[1], /HELP_TABS\.some\(/, "openHelpOn only opens a tab that exists");
|
||||
});
|
||||
|
||||
test("models: Codex is a model CLI on the server and the page, with its own tab", () => {
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "server.mjs"), "utf8");
|
||||
const app = publicSource("app.js");
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
|
||||
const app = publicSource("screens/looks.js");
|
||||
const html = publicSource("index.html");
|
||||
const list = (src) => JSON.parse(src.match(/const MODEL_CLIS = (\[[^\]]*\]);/)[1]);
|
||||
assert.deepEqual(list(server), ["claude", "devin", "codex"]);
|
||||
@@ -415,22 +414,7 @@ test("models: Codex is a model CLI on the server and the page, with its own tab"
|
||||
for (const cli of list(server)) assert.ok(Array.isArray(shipped[cli]), `the launcher's models.json has ${cli}`);
|
||||
});
|
||||
|
||||
test("finished screen: every shape shows Before you close this, with three rows", () => {
|
||||
const app = publicSource("app.js");
|
||||
const handoff = app.slice(app.indexOf("function renderHandoff("));
|
||||
assert.match(handoff.slice(0, handoff.indexOf("\n}\n")), /card\.appendChild\(renderCloseGuide\(shape, fin\)\)/);
|
||||
const guide = app.slice(app.indexOf("function renderCloseGuide("), app.indexOf("function renderHandoff("));
|
||||
for (const label of ["Safe to close", "Start fresh", "Carry on", "Before you close this"]) {
|
||||
assert.ok(guide.includes(label), `the guide says "${label}"`);
|
||||
}
|
||||
assert.match(guide, /shape === "paused"/, "a pause changes the Start fresh sentence");
|
||||
assert.match(guide, /resume command/);
|
||||
});
|
||||
|
||||
test("getting started: the new help, status and finished-screen strings carry no em dash", () => {
|
||||
const app = publicSource("app.js");
|
||||
const guide = app.slice(app.indexOf("const GUIDE_ICONS"), app.indexOf("function renderHandoff("));
|
||||
assert.ok(!guide.includes(EM), "the close guide has no em dash");
|
||||
const tpl = helpTemplate();
|
||||
const stuck = tpl.match(/<section class="help-panel" data-tab="stuck">([\s\S]*?)<\/section>/)[1];
|
||||
const fresh = stuck.slice(0, stuck.indexOf("<h4>Not running, or not connected?</h4>"));
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
// Web console tests, the spec states: public/spec-states.js defines every
|
||||
// state the dashboard scan can report, and the labels, next steps and card
|
||||
// rules are lookups on it.
|
||||
// Run with: node --test scripts/test-web-console-spec-states.mjs
|
||||
|
||||
import test 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 { SPEC_STATES as TABLE, stateFor } from "../src/web-console/public/spec-states.js";
|
||||
import { SKILLS } from "../src/web-console/public/skills.js";
|
||||
import { SKILL_CATALOG, cardAvailability, defaultSpec, launchVariant } from "../src/web-console/public/answers.js";
|
||||
import { scanProject } from "../src/web-console/scan.mjs";
|
||||
import { MARKERS, TASK_LINE_RE, TASK_ID_RE, CHECKBOX_RE, STATUS_RE, statusOf, countTasks } from "../src/web-console/spec-files.mjs";
|
||||
|
||||
// The task pattern specs.mjs used before spec-files.mjs: TASK_ID_RE must take
|
||||
// a `-` task line apart into the same groups.
|
||||
const OLD_TASK_RE = /^\s*[-*] \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
|
||||
|
||||
test("spec files: every marker names its state, and the table is frozen", () => {
|
||||
assert.deepEqual(MARKERS, { " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" });
|
||||
assert.ok(Object.isFrozen(MARKERS));
|
||||
});
|
||||
|
||||
test("spec files: -, * and numbered task lines all match, and TASK_ID_RE keeps the old groups", () => {
|
||||
for (const line of ["- [ ] **Task 1.2:** Do it", "* [x] **Task 1.2:** Do it", "1. [/] **Task 1.2:** Do it", " 12. [?] **Task 3.4:** Do it"]) {
|
||||
assert.ok(TASK_LINE_RE.test(line), `TASK_LINE_RE matches ${line}`);
|
||||
assert.ok(TASK_ID_RE.test(line), `TASK_ID_RE matches ${line}`);
|
||||
assert.ok(CHECKBOX_RE.test(line), `CHECKBOX_RE matches ${line}`);
|
||||
}
|
||||
assert.ok(!TASK_LINE_RE.test("- [ ] Acceptance: it works"), "a plain checkbox is no task line");
|
||||
// A line TASK_ID_RE cannot take apart is no task line for the scan either.
|
||||
for (const line of ["- [x] **task 1.1:** Lowercase", "- [x] **Task 1.1:** Two spaces"]) {
|
||||
assert.ok(!TASK_ID_RE.test(line) && !TASK_LINE_RE.test(line), `neither pattern takes ${line}`);
|
||||
}
|
||||
assert.ok(CHECKBOX_RE.test("- [ ] Acceptance: it works"), "but it is a checkbox");
|
||||
for (const line of ["- [x] **Task 2.3:** Build it", "- [ ] **Task 1.B:** Name it", "- [/] **Task 4.2a:** Split it"]) {
|
||||
assert.deepEqual([...line.match(TASK_ID_RE)], [...line.match(OLD_TASK_RE)], `the same groups for ${line}`);
|
||||
}
|
||||
assert.deepEqual("1. [x] **Task 2.3:** Build it".match(TASK_ID_RE).slice(1), ["x", "2", "3", ""], "a numbered line's groups");
|
||||
});
|
||||
|
||||
test("spec files: statusOf() reads every Status form, LF or CRLF, and is null without one", () => {
|
||||
const forms = { "**Status:** Complete": "Complete", "**Status**: In Progress": "In Progress", "Status: Not Started": "Not Started" };
|
||||
for (const [line, value] of Object.entries(forms)) {
|
||||
for (const eol of ["\n", "\r\n"]) {
|
||||
const text = `# Phase 1${eol}${eol}${line}${eol}**Estimated Tasks:** 3${eol}`;
|
||||
assert.equal(statusOf(text), value, `${line} with ${eol === "\n" ? "LF" : "CRLF"}`);
|
||||
assert.equal(text.match(STATUS_RE)[1] + text.match(STATUS_RE)[2], line, "the prefix and value rebuild the line");
|
||||
}
|
||||
}
|
||||
assert.equal(statusOf("# Phase 1\n\nNo status here.\n"), null);
|
||||
assert.equal(statusOf(""), null);
|
||||
assert.equal(statusOf(undefined), null);
|
||||
});
|
||||
|
||||
test("spec files: countTasks() counts task lines only when there are any, every checkbox otherwise", () => {
|
||||
const phase = [
|
||||
"# Phase 1",
|
||||
"- [x] **Task 1.1:** One",
|
||||
"* [?] **Task 1.2:** Two",
|
||||
"1. [ ] **Task 1.3:** Three",
|
||||
"- [/] **Task 1.4:** Four",
|
||||
"- [!] **Task 1.5:** Five",
|
||||
"- [~] **Task 1.6:** An unknown marker",
|
||||
"## Acceptance Criteria",
|
||||
"- [ ] It works",
|
||||
"- [x] It is fast",
|
||||
].join("\r\n");
|
||||
assert.deepEqual(countTasks(phase), { done: 1, assumed: 1, open: 3, total: 5 });
|
||||
const older = "# Phase 1\n\n- [x] Make it\n- [ ] Ship it\n- [?] Check it\n";
|
||||
assert.deepEqual(countTasks(older), { done: 1, assumed: 1, open: 1, total: 3 });
|
||||
assert.deepEqual(countTasks(""), { done: 0, assumed: 0, open: 0, total: 0 });
|
||||
});
|
||||
|
||||
// What the picker labels each state and which card each state lights, as
|
||||
// answers.js's SPEC_STATE_LABELS and NEXT_FOR_STATE said before the table.
|
||||
const LABELS = {
|
||||
diagnosed: "Bug diagnosed",
|
||||
fixed: "Bug fixed",
|
||||
exploring: "Exploring",
|
||||
mapped: "Ready to plan",
|
||||
planned: "Ready to document",
|
||||
documented: "Ready to build",
|
||||
building: "Building",
|
||||
built: "Ready to finalize",
|
||||
unrecognized: "Files on disk",
|
||||
};
|
||||
const NEXT = {
|
||||
diagnosed: "plan2code-quick-task",
|
||||
fixed: null,
|
||||
exploring: "plan2code-0-pathfinder",
|
||||
mapped: "plan2code-1-plan",
|
||||
planned: "plan2code-2-document",
|
||||
documented: "plan2code-3-implement",
|
||||
building: "plan2code-3-implement",
|
||||
built: "plan2code-4-finalize",
|
||||
unrecognized: null,
|
||||
};
|
||||
|
||||
test("spec states: each state keeps its label and next step, and only fixed is finished", () => {
|
||||
assert.deepEqual(Object.keys(TABLE), Object.keys(LABELS), "the states, in the scan's order");
|
||||
for (const [name, label] of Object.entries(LABELS)) {
|
||||
const s = stateFor(name);
|
||||
assert.ok(s, `${name} is in the table`);
|
||||
assert.equal(s.label, label, `${name}'s label`);
|
||||
assert.equal(s.next, NEXT[name], `${name}'s next step`);
|
||||
assert.equal(s.finished, name === "fixed", `${name}'s finished flag`);
|
||||
}
|
||||
assert.equal(stateFor("made-up"), null, "an unknown state is null");
|
||||
assert.ok(Object.isFrozen(TABLE) && Object.values(TABLE).every(Object.isFrozen), "the table is frozen");
|
||||
});
|
||||
|
||||
// Every card's answer for every picker selection, as cardAvailability() gave
|
||||
// them before the card rules moved onto skills.js: generated once from that
|
||||
// code and written out here, so the move is proven to change nothing. "none"
|
||||
// is "start from scratch" (no spec picked). The scan is a set-up git project
|
||||
// with nothing to commit; SCAN_CASES covers the three cards that read it.
|
||||
const SCAN = { hasAgents: true, isGit: true, pending: 0 };
|
||||
const CARDS = {
|
||||
"plan2code-init": {
|
||||
"none": { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
diagnosed: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
fixed: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
exploring: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
mapped: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
planned: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
documented: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
building: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
built: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
unrecognized: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
},
|
||||
"plan2code-init-update": {
|
||||
"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-0-pathfinder": {
|
||||
"none": { on: true, next: true },
|
||||
diagnosed: { on: false, reason: "The cause is found. Fix it in a quick task, or plan it." },
|
||||
fixed: { on: false, reason: "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/." },
|
||||
exploring: { on: true, next: true },
|
||||
mapped: { on: false, reason: "This spec is already past the questions" },
|
||||
planned: { on: false, reason: "This spec is already past the questions" },
|
||||
documented: { on: false, reason: "This spec is already past the questions" },
|
||||
building: { on: false, reason: "This spec is already past the questions" },
|
||||
built: { on: false, reason: "This spec is already past the questions" },
|
||||
unrecognized: { on: true, next: false },
|
||||
},
|
||||
"plan2code-1-plan": {
|
||||
"none": { on: true, next: false },
|
||||
diagnosed: { on: true, next: false },
|
||||
fixed: { on: false, reason: "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/." },
|
||||
exploring: { on: false, reason: "Pathfinder is not finished with this spec yet" },
|
||||
mapped: { on: true, next: true },
|
||||
planned: { on: true, next: false },
|
||||
documented: { on: false, reason: "The plan is written. Revise it instead if it moved." },
|
||||
building: { on: false, reason: "The plan is written. Revise it instead if it moved." },
|
||||
built: { on: false, reason: "The plan is written. Revise it instead if it moved." },
|
||||
unrecognized: { on: true, next: false },
|
||||
},
|
||||
"plan2code-1b-revise-plan": {
|
||||
"none": { on: false, reason: "Needs a spec that is already written up" },
|
||||
diagnosed: { on: false, reason: "Needs a spec that is already written up" },
|
||||
fixed: { on: false, reason: "Needs a spec that is already written up" },
|
||||
exploring: { on: false, reason: "Needs a spec that is already written up" },
|
||||
mapped: { on: false, reason: "Needs a spec that is already written up" },
|
||||
planned: { on: false, reason: "Needs a spec that is already written up" },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: false, reason: "The spec is fully built" },
|
||||
unrecognized: { on: false, reason: "Needs a spec that is already written up" },
|
||||
},
|
||||
"plan2code-2-document": {
|
||||
"none": { on: false, reason: "Needs a drafted plan first" },
|
||||
diagnosed: { on: false, reason: "Needs a drafted plan first" },
|
||||
fixed: { on: false, reason: "Needs a drafted plan first" },
|
||||
exploring: { on: false, reason: "Needs a drafted plan first" },
|
||||
mapped: { on: false, reason: "Needs a drafted plan first" },
|
||||
planned: { on: true, next: true },
|
||||
documented: { on: false, reason: "The phases are already written up" },
|
||||
building: { on: false, reason: "The phases are already written up" },
|
||||
built: { on: false, reason: "The phases are already written up" },
|
||||
unrecognized: { on: false, reason: "Needs a drafted plan first" },
|
||||
},
|
||||
"plan2code-3-implement": {
|
||||
"none": { on: false, reason: "Needs the phase checklists written up first" },
|
||||
diagnosed: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
fixed: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
exploring: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
mapped: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
planned: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
documented: { on: true, next: true },
|
||||
building: { on: true, next: true },
|
||||
built: { on: false, reason: "All tasks are already done" },
|
||||
unrecognized: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
},
|
||||
"plan2code-3-implement-review": {
|
||||
"none": { on: false, reason: "Needs the phase checklists written up first" },
|
||||
diagnosed: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
fixed: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
exploring: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
mapped: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
planned: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
documented: { on: true, next: false },
|
||||
building: { on: true, next: false },
|
||||
built: { on: false, reason: "All tasks are already done" },
|
||||
unrecognized: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
},
|
||||
"plan2code-4-finalize": {
|
||||
"none": { on: false, reason: "Needs a spec that is fully built" },
|
||||
diagnosed: { on: false, reason: "Needs a spec that is fully built" },
|
||||
fixed: { on: false, reason: "Needs a spec that is fully built" },
|
||||
exploring: { on: false, reason: "Needs a spec that is fully built" },
|
||||
mapped: { on: false, reason: "Needs a spec that is fully built" },
|
||||
planned: { on: false, reason: "Needs a spec that is fully built" },
|
||||
documented: { on: false, reason: "Needs a spec that is fully built" },
|
||||
building: { on: false, reason: "Needs a spec that is fully built" },
|
||||
built: { on: true, next: true },
|
||||
unrecognized: { on: false, reason: "Needs a spec that is fully built" },
|
||||
},
|
||||
"plan2code-quick-task": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true, next: 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-review": {
|
||||
"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-xray": {
|
||||
"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-diagnose": {
|
||||
"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 },
|
||||
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-git": {
|
||||
"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-handoff": {
|
||||
"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 },
|
||||
},
|
||||
};
|
||||
|
||||
// Implement's card also launches Implement + Review, which has the same rules.
|
||||
const CARD_ENTRIES = SKILL_CATALOG.flatMap((e) => (e.review ? [e, launchVariant(e, true)] : [e]));
|
||||
|
||||
const SCAN_CASES = [
|
||||
[{ hasAgents: false, isGit: false, pending: null }, "plan2code-init", { on: true }],
|
||||
[{ hasAgents: false, isGit: false, pending: null }, "plan2code-init-update", { on: false, reason: "Needs an AGENTS.md. Set the project up first." }],
|
||||
[{ hasAgents: false, isGit: false, pending: null }, "plan2code-git", { on: true, note: "Not a git repository yet: it offers to start one" }],
|
||||
[{ hasAgents: true, isGit: true, pending: 3 }, "plan2code-init", { on: false, reason: "AGENTS.md is already written. Refresh it instead." }],
|
||||
[{ hasAgents: true, isGit: true, pending: 3 }, "plan2code-init-update", { on: true }],
|
||||
[{ hasAgents: true, isGit: true, pending: 3 }, "plan2code-git", { on: true, note: "3 files to commit" }],
|
||||
[{ hasAgents: true, isGit: true, pending: 1 }, "plan2code-init", { on: false, reason: "AGENTS.md is already written. Refresh it instead." }],
|
||||
[{ hasAgents: true, isGit: true, pending: 1 }, "plan2code-init-update", { on: true }],
|
||||
[{ hasAgents: true, isGit: true, pending: 1 }, "plan2code-git", { on: true, note: "1 file to commit" }],
|
||||
];
|
||||
|
||||
test("card rules: every card gives the same answer for every spec state as before", () => {
|
||||
assert.deepEqual(CARD_ENTRIES.map((e) => e.skill), Object.keys(CARDS), "one row per card, in card order");
|
||||
for (const entry of CARD_ENTRIES) {
|
||||
for (const [sel, want] of Object.entries(CARDS[entry.skill])) {
|
||||
const spec = sel === "none" ? null : { dir: "specs/x", name: "x", state: sel };
|
||||
assert.deepEqual(cardAvailability(entry, SCAN, spec), want, `${entry.skill} with ${sel}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("card rules: a state the table does not know is treated like files on disk", () => {
|
||||
for (const entry of CARD_ENTRIES) {
|
||||
const weird = cardAvailability(entry, SCAN, { dir: "specs/x", name: "x", state: "made-up" });
|
||||
assert.deepEqual(weird, CARDS[entry.skill].unrecognized, `${entry.skill} with an unknown state`);
|
||||
}
|
||||
});
|
||||
|
||||
test("card rules: Init, Init update and Git read the scan, not the spec", () => {
|
||||
for (const [scan, skill, want] of SCAN_CASES) {
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === skill);
|
||||
assert.deepEqual(cardAvailability(entry, scan, null), want, `${skill} with ${JSON.stringify(scan)}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("finished: any finished state is never the picker's default, not only fixed", () => {
|
||||
// The test's own copy of the table, with a made-up second finished state.
|
||||
const table = { ...TABLE, archived: { label: "Archived", next: null, finished: true } };
|
||||
const lookup = (name) => (Object.hasOwn(table, name) ? table[name] : null);
|
||||
const specs = [
|
||||
{ dir: "specs/a", name: "a", state: "archived" },
|
||||
{ dir: "specs/b", name: "b", state: "fixed" },
|
||||
{ dir: "specs/c", name: "c", state: "planned" },
|
||||
];
|
||||
assert.equal(defaultSpec(specs, lookup)?.dir, "specs/c", "the newest spec still in play");
|
||||
assert.equal(defaultSpec(specs.slice(0, 2), lookup), null, "only finished specs: start from scratch");
|
||||
assert.equal(defaultSpec(specs)?.dir, "specs/a", "the real table does not know archived, so it is in play");
|
||||
|
||||
// The cards greyed for a fixed bug give a made-up finished state the same reason.
|
||||
const archived = { dir: "specs/a", name: "a", state: "archived" };
|
||||
for (const entry of CARD_ENTRIES) {
|
||||
const fixed = cardAvailability(entry, SCAN, { dir: "specs/b", name: "b", state: "fixed" });
|
||||
assert.deepEqual(cardAvailability(entry, SCAN, archived, lookup), fixed, `${entry.skill} treats archived as it treats fixed`);
|
||||
}
|
||||
});
|
||||
|
||||
// One spec folder per state, in the shapes classifySpec() reads.
|
||||
const PHASE = (ticks) => "# Phase 1\n\n" + ticks.map((x, i) => `- [${x ? "x" : " "}] **Task 1.${i + 1}:** Step ${i + 1}\n`).join("");
|
||||
const FIXTURES = {
|
||||
diagnosed: { "DIAGNOSIS-20261017.md": "# Diagnosis\n\n**Status:** Diagnosed\n" },
|
||||
fixed: { "DIAGNOSIS-20261017.md": "# Diagnosis\n\n**Status:** Fixed\n" },
|
||||
exploring: { "pathfinder/map.md": "# Map\n\nStatus: Working\n" },
|
||||
mapped: { "PLAN-DRAFT-20261017.md": "# Plan draft\n\n**Status:** Phase 3 Complete - Resume at Phase 4\n" },
|
||||
planned: { "PLAN-DRAFT-20261017.md": "# Plan draft\n\n**Status:** Draft\n" },
|
||||
documented: { "overview.md": "# Overview\n", "phase-1.md": PHASE([false, false]) },
|
||||
building: { "overview.md": "# Overview\n", "phase-1.md": PHASE([true, false]) },
|
||||
built: { "overview.md": "# Overview\n", "phase-1.md": PHASE([true, true]) },
|
||||
unrecognized: { "notes.md": "Some loose notes.\n" },
|
||||
};
|
||||
|
||||
// The states a scan of these fixtures reports, against the table's: the
|
||||
// lines that name what does not match, empty when they agree.
|
||||
function scanProblems(fixtures, table) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-states-"));
|
||||
try {
|
||||
for (const [name, files] of Object.entries(fixtures))
|
||||
for (const [rel, text] of Object.entries(files)) {
|
||||
const file = path.join(root, "specs", name, rel);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, text);
|
||||
}
|
||||
const scan = scanProject(root);
|
||||
const problems = scan.specs.filter((sp) => sp.state !== sp.name).map((sp) => `the ${sp.name} fixture scans as ${sp.state}`);
|
||||
const seen = new Set(scan.specs.map((sp) => sp.state));
|
||||
for (const state of seen) if (!Object.hasOwn(table, state)) problems.push(`the scan returns ${state}, which spec-states.js lacks`);
|
||||
for (const state of Object.keys(table)) if (!seen.has(state)) problems.push(`no fixture reaches ${state}: add one, or drop it from spec-states.js`);
|
||||
return problems;
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test("the scan: every state it can return is in the table, and a fixture reaches every state in it", () => {
|
||||
assert.deepEqual(scanProblems(FIXTURES, TABLE), []);
|
||||
// The check names what is missing.
|
||||
const { built, ...short } = FIXTURES;
|
||||
assert.deepEqual(scanProblems(short, TABLE), ["no fixture reaches built: add one, or drop it from spec-states.js"]);
|
||||
const { unrecognized, ...known } = TABLE;
|
||||
assert.deepEqual(scanProblems(FIXTURES, known), ["the scan returns unrecognized, which spec-states.js lacks"]);
|
||||
});
|
||||
|
||||
test("the scan: an assumed task counts as done and is named, and numbered task lines count", () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-assumed-"));
|
||||
const specs = {
|
||||
mixed: "- [x] **Task 1.1:** One\n- [x] **Task 1.2:** Two\n- [?] **Task 1.3:** Three\n- [ ] **Task 1.4:** Four\n",
|
||||
assumed: "- [?] **Task 1.1:** One\n- [?] **Task 1.2:** Two\n",
|
||||
numbered: "1. [x] **Task 1.1:** One\n2. [ ] **Task 1.2:** Two\n3. [ ] **Task 1.3:** Three\n",
|
||||
plain: "- [x] **Task 1.1:** One\n- [x] **Task 1.2:** Two\n",
|
||||
};
|
||||
try {
|
||||
for (const [name, phase] of Object.entries(specs)) {
|
||||
fs.mkdirSync(path.join(root, "specs", name), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, "specs", name, "overview.md"), "# Overview\n");
|
||||
fs.writeFileSync(path.join(root, "specs", name, "phase-1.md"), "# Phase 1\n\n" + phase + "\n## Acceptance Criteria\n\n- [ ] It works\n");
|
||||
}
|
||||
const by = Object.fromEntries(scanProject(root).specs.map((sp) => [sp.name, sp]));
|
||||
assert.deepEqual([by.mixed.state, by.mixed.detail], ["building", "3 of 4 tasks done, 1 assumed"]);
|
||||
assert.deepEqual([by.assumed.state, by.assumed.detail], ["built", "all tasks done, 2 assumed"]);
|
||||
assert.deepEqual([by.numbered.state, by.numbered.detail], ["building", "1 of 3 tasks done"]);
|
||||
assert.deepEqual([by.plain.state, by.plain.detail], ["built", "all tasks done"], "no assumed tasks, no \", 0 assumed\"");
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// The states no card names in its `states` list: a card that is on for "any"
|
||||
// spec does not count, since it would take a state nobody thought about. A
|
||||
// finished state is taken by no card on purpose.
|
||||
function untakenStates(skills, table) {
|
||||
const taken = new Set(skills.flatMap((sk) => (Array.isArray(sk.states) ? sk.states : [])));
|
||||
return Object.entries(table)
|
||||
.filter(([name, s]) => !s.finished && !taken.has(name))
|
||||
.map(([name]) => `no card's states take ${name}: add it to the skills.js entries whose card it lights`);
|
||||
}
|
||||
|
||||
test("card rules: every state still in play is taken by at least one card", () => {
|
||||
assert.deepEqual(untakenStates(SKILLS, TABLE), []);
|
||||
// The check names the state: Document and Plan are the cards that take planned.
|
||||
const without = SKILLS.map((sk) =>
|
||||
Array.isArray(sk.states) && (sk.skill === "plan2code-2-document" || sk.skill === "plan2code-1-plan")
|
||||
? { ...sk, states: sk.states.filter((st) => st !== "planned") }
|
||||
: sk
|
||||
);
|
||||
assert.deepEqual(untakenStates(without, TABLE), ["no card's states take planned: add it to the skills.js entries whose card it lights"]);
|
||||
});
|
||||
|
||||
test("card rules: a card's states and greyed reasons name only real states", () => {
|
||||
const known = new Set([...Object.keys(TABLE), "none"]);
|
||||
for (const sk of SKILLS) {
|
||||
if (Array.isArray(sk.states)) for (const st of sk.states) assert.ok(known.has(st), `${sk.skill} takes ${st}, which is no state`);
|
||||
for (const key of Object.keys(sk.greyed || {})) assert.ok(key === "default" || key === "finished" || known.has(key), `${sk.skill}'s greyed names ${key}, which is no state`);
|
||||
if (Array.isArray(sk.states) && sk.card) assert.ok(sk.greyed && sk.greyed.default, `${sk.skill} has a default greyed reason`);
|
||||
}
|
||||
});
|
||||
|
||||
// The states the dashboard skill's prose (src/plan2code.md) never mentions,
|
||||
// by name in backticks (`planned`) or by label in quotes ("Ready to
|
||||
// document"). The agent reads that prose to choose its recommendation, so
|
||||
// every state needs a word there; a bare word ("reading or exploring", a file
|
||||
// named building-habits.md) is not one.
|
||||
function unmentionedStates(prose, table) {
|
||||
const lower = prose.toLowerCase();
|
||||
return Object.entries(table)
|
||||
.filter(([name, s]) => !prose.includes("`" + name + "`") && !lower.includes(`"${s.label.toLowerCase()}"`))
|
||||
.map(([name, s]) => `src/plan2code.md mentions neither \`${name}\` nor "${s.label}"`);
|
||||
}
|
||||
|
||||
test("the dashboard skill: its prose names every spec state", () => {
|
||||
const prose = fs.readFileSync(path.join(import.meta.dirname, "..", "src", "plan2code.md"), "utf8");
|
||||
assert.deepEqual(unmentionedStates(prose, TABLE), []);
|
||||
const sample = 'Only `planned` and "Ready to build", while building and exploring are bare words.';
|
||||
const some = { planned: TABLE.planned, documented: TABLE.documented, building: TABLE.building, exploring: TABLE.exploring };
|
||||
assert.deepEqual(unmentionedStates(sample, some), [
|
||||
'src/plan2code.md mentions neither `building` nor "Building"',
|
||||
'src/plan2code.md mentions neither `exploring` nor "Exploring"',
|
||||
]);
|
||||
});
|
||||
@@ -15,7 +15,9 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { applyPatch, scanProject } from "../src/web-console/lib.mjs";
|
||||
import { scanProject } from "../src/web-console/scan.mjs";
|
||||
import { applyPatch } from "../src/web-console/patches.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
@@ -31,6 +33,7 @@ import {
|
||||
WEB_CONSOLE_DIR,
|
||||
consoleDoc,
|
||||
consoleDocFiles,
|
||||
HANDOFFS_DIR,
|
||||
} from "./web-console-test-helpers.mjs";
|
||||
|
||||
const choice = (id, extra = {}) => ({
|
||||
@@ -321,13 +324,70 @@ test("settle and a defaulted reply id go through post end to end", async () => {
|
||||
|
||||
/* ------------------------------------------------------------ session hops */
|
||||
|
||||
test("a launch, a dashboard press and Commit it now each come with their resume command", async () => {
|
||||
// A pick-up hops into the stored workflow and spec; the page sends only the
|
||||
// id. A missing spec folder, a workflow that is not a workflow name, or the
|
||||
// Handoff skill's own handoff falls back to Quick Task, flagged. (No skills sit beside the source tree, so the
|
||||
// stored skill name stands there.)
|
||||
test("a pick-up comes with the stored skill's resume command, handoffFile, and falls back to Quick Task", async () => {
|
||||
process.env.PLAN2CODE_HANDOFFS_DIR = HANDOFFS_DIR;
|
||||
const store = await import("../src/web-console/handoffs.mjs");
|
||||
const worktree = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-pickup-"));
|
||||
fs.mkdirSync(path.join(worktree, "specs", "lunch-vote"), { recursive: true });
|
||||
const make = (rec) => {
|
||||
const h = store.newHandoff({ worktree, project: worktree, workflow: "implement", skill: "plan2code-3-implement", title: "T", ...rec }, new Date(2026, 9, 17, 10, 0 + make.n++));
|
||||
fs.writeFileSync(h.path, "# Handoff: T\n");
|
||||
return h;
|
||||
};
|
||||
make.n = 0;
|
||||
const s = consoleSession(["--workflow", "dashboard"]);
|
||||
const resumeOf = (workflow, spec = "") =>
|
||||
`node "${path.join(ROOT, "src", "web-console", "console.mjs")}" open --resume ${s.sid} --no-open --workflow ${workflow}${spec}`;
|
||||
try {
|
||||
const good = make({ spec: "specs/lunch-vote" });
|
||||
const goneSpec = make({ spec: "specs/deleted" });
|
||||
const badMeta = make({ spec: null });
|
||||
const metaFile = path.join(HANDOFFS_DIR, badMeta.id + ".json");
|
||||
fs.writeFileSync(metaFile, fs.readFileSync(metaFile, "utf8").replace('"workflow": "implement"', '"workflow": "Not A Workflow"'));
|
||||
const cases = [
|
||||
[good, resumeOf("implement", " --spec specs/lunch-vote"), undefined],
|
||||
[goneSpec, resumeOf("quick-task"), true],
|
||||
[badMeta, resumeOf("quick-task"), true],
|
||||
// The Handoff skill's own handoff carries on in Quick Task, never in another handoff.
|
||||
[make({ workflow: "handoff", skill: "plan2code-handoff" }), resumeOf("quick-task"), true],
|
||||
];
|
||||
for (const [h, resume, fallback] of cases) {
|
||||
assert.equal((await s.send("/submit", { actions: [{ i: "__pickup", type: "pickup", handoff: h.id }], reply: "pick up" })).status, 200);
|
||||
const res = waitFor(s);
|
||||
assert.equal(res.status, 0);
|
||||
assert.equal(res.json.resume, resume);
|
||||
assert.equal(res.json.handoffFile, h.path);
|
||||
assert.equal(res.json.fallback, fallback);
|
||||
}
|
||||
// A stored spec with shell characters never reaches `resume`: Quick Task, flagged.
|
||||
const hostile = make({ spec: "specs/x;touch pwned" });
|
||||
assert.equal((await s.send("/submit", { actions: [{ i: "__pickup", type: "pickup", handoff: hostile.id }], reply: "pick up" })).status, 200);
|
||||
const hot = waitFor(s).json;
|
||||
assert.equal(hot.resume, resumeOf("quick-task"));
|
||||
assert.equal(hot.fallback, true);
|
||||
// An id that is not a handoff id gets the fallback and no handoffFile.
|
||||
assert.equal((await s.send("/submit", { actions: [{ i: "__pickup", type: "pickup", handoff: "../x" }], reply: "pick up" })).status, 200);
|
||||
const bad = waitFor(s).json;
|
||||
assert.equal(bad.handoffFile, undefined);
|
||||
assert.equal(bad.fallback, true);
|
||||
} finally {
|
||||
cli(["stop", "--session", s.sid]);
|
||||
fs.rmSync(worktree, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a launch, a dashboard press, Commit it now and Update CHANGELOG first each come with their resume command", async () => {
|
||||
const s = consoleSession(["--workflow", "dashboard"]);
|
||||
try {
|
||||
const cases = [
|
||||
[{ i: "__launch", type: "launch", skill: "plan2code-3-implement", workflow: "implement", spec: "specs/lunch vote" }, "implement", ' --spec "specs/lunch vote"'],
|
||||
[{ i: "__dashboard", type: "dashboard" }, "dashboard", ""],
|
||||
[{ i: "__commit", type: "commit" }, "git", ""],
|
||||
[{ i: "__changelog", type: "changelog" }, "changelog", ""],
|
||||
];
|
||||
for (const [action, workflow, spec] of cases) {
|
||||
assert.equal((await s.send("/submit", { actions: [action], reply: "go" })).status, 200);
|
||||
@@ -366,6 +426,15 @@ test("the built skills name the skill file to follow after a hop", async () => {
|
||||
assert.equal(res.status, 200);
|
||||
const got = run(["wait", "--session", opened.sid, "--seconds", "10"]).json;
|
||||
assert.equal(got.skillFile, path.join(ROOT, "skills", "plan2code-review", "SKILL.md"));
|
||||
assert.equal(got.handoffSkill, undefined, "a launch is not a handoff stop");
|
||||
const stopRes = await fetch(`${m[1]}/submit`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", cookie, connection: "close" },
|
||||
body: JSON.stringify({ actions: [{ i: "__stop", type: "stop", handoff: true }], reply: "stop with a handoff" }),
|
||||
});
|
||||
assert.equal(stopRes.status, 200);
|
||||
const stopped = run(["wait", "--session", opened.sid, "--seconds", "10"]).json;
|
||||
assert.equal(stopped.handoffSkill, path.join(ROOT, "skills", "plan2code-handoff", "SKILL.md"), "a handoff stop in a built skill names the Handoff skill file");
|
||||
} finally {
|
||||
run(["stop", "--session", opened.sid]);
|
||||
}
|
||||
@@ -406,7 +475,8 @@ test("every console workflow has its notes, and its skill's Interface reads them
|
||||
const notesFor = {
|
||||
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",
|
||||
review: "review", finalize: "finalize", handoff: "handoff", changelog: "changelog", git: "git", xray: "xray",
|
||||
diagnose: "diagnose",
|
||||
};
|
||||
const skills = fs.readdirSync(path.join(ROOT, "src")).filter((f) => /^plan2code(-.*)?\.md$/.test(f));
|
||||
for (const f of skills) {
|
||||
@@ -548,13 +618,6 @@ test("a wait with nothing open leaves a working agent working", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("the git board lets go of a working agent that went adrift", () => {
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const at = js.indexOf("const gitLocked = ");
|
||||
const line = js.slice(at, js.indexOf(";", at));
|
||||
assert.ok(line.includes("(agentWorking() && !agentAdrift())"), line);
|
||||
});
|
||||
|
||||
test("post --file - reads the patch from stdin, UTF-8 and a BOM included", () => {
|
||||
const s = openSession();
|
||||
try {
|
||||
@@ -648,16 +711,22 @@ test("a finish ends the working stretch, and resuming a pause starts a fresh one
|
||||
});
|
||||
|
||||
test("a card with a note box over the git board flows at its own height, never shrunk under the board", () => {
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const rule = css.slice(css.indexOf(".main:has(> .git-board) > .card,"), css.indexOf("{", css.indexOf(".main:has(> .git-board) > .card,")));
|
||||
assert.ok(rule.includes(".main:has(> .git-board) > .card.is-primary.has-grow"), "the board's natural-height rule outranks .has-grow");
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const fn = js.slice(js.indexOf("function markGrowBox("), js.indexOf("function naturalHeight("));
|
||||
assert.ok(fn.includes("isGitBoard()"), "no box grows over the board");
|
||||
const css = joinedCss();
|
||||
const rule = css.slice(css.indexOf(".git-cards > .card,"), css.indexOf("{", css.indexOf(".git-cards > .card,")));
|
||||
assert.ok(rule.includes(".git-cards > .card.is-primary.has-grow"), "the board's natural-height rule outranks .has-grow");
|
||||
});
|
||||
|
||||
test("a card and its pager in the git board's card slot fill the board's width, never shrink to their content", () => {
|
||||
const css = joinedCss();
|
||||
// .card and .pager centre with auto inline margins; in the slot's grid those
|
||||
// would shrink a short confirm, and the pager under it, to fit their content.
|
||||
assert.match(css, /\.card\s*\{[^}]*margin:\s*0 auto/, "the base card still centres outside the board");
|
||||
assert.match(css, /\.pager\s*\{[^}]*margin:\s*0 auto/, "the base pager still centres outside the board");
|
||||
assert.match(css, /\.git-cards > \.card,\s*\.git-cards > \.pager\s*\{\s*margin:\s*0;\s*\}/, "the card slot drops the auto margins for both");
|
||||
});
|
||||
|
||||
test("long task lines, long words, a narrow board and a narrow Ask pane never widen the page", () => {
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
const rule = (sel) => {
|
||||
const at = css.indexOf("\n" + sel + " {");
|
||||
assert.ok(at > -1, `${sel} has a rule`);
|
||||
@@ -668,16 +737,16 @@ test("long task lines, long words, a narrow board and a narrow Ask pane never wi
|
||||
assert.match(rule(".main > .git-board"), /grid-template-columns: minmax\(0, 1fr\)/);
|
||||
assert.match(rule(".git-table-wrap"), /overflow-x: auto/, "the branch table scrolls on its own");
|
||||
assert.match(rule(".ask-actions"), /flex-wrap: wrap/, "the Ask pane's Send never clips");
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const fn = js.slice(js.indexOf("function branchTable("), js.indexOf("/* The panels */"));
|
||||
assert.ok(fn.includes('el("div", "git-table-wrap")'), "branchTable wraps its table");
|
||||
const view = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "git-board-view.js"), "utf8");
|
||||
const fn = view.slice(view.indexOf("function branchTable("), view.indexOf("function createPanel("));
|
||||
assert.ok(fn.includes('h.el("div", "git-table-wrap")'), "branchTable wraps its table");
|
||||
});
|
||||
|
||||
test("over the git board a note box grows with its text, and the no-repo note only points above when a card is there", () => {
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
assert.match(css, /\.main:has\(> \.git-board\) > \.card textarea \{ field-sizing: content; max-height: 50vh; \}/);
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const fn = js.slice(js.indexOf("function renderGitBoard("), js.indexOf("function rememberGitScroll("));
|
||||
assert.ok(fn.includes('main.querySelector(":scope > .card")'), "the note checks for a card first");
|
||||
const css = joinedCss();
|
||||
assert.match(css, /\.git-cards > \.card textarea \{ field-sizing: content; max-height: 50vh; \}/);
|
||||
const view = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "git-board-view.js"), "utf8");
|
||||
const fn = view.slice(view.indexOf("export function drawGitBoard("), view.indexOf("function header("));
|
||||
assert.ok(fn.includes("ctx.hasCard"), "the note checks for a card first");
|
||||
assert.ok(fn.includes("will ask what to do here in a moment"));
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
// Web console tests, the page's shared state: public/state.js holds what
|
||||
// every screen reads (`page`) and the hooks a screen calls instead of the
|
||||
// render loop and the draft's save. It only defines, so it imports here under
|
||||
// plain Node, page or no page.
|
||||
// Run with: node --test scripts/test-web-console-state.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { page, redraw, onRedraw, saveNow, onSave, fresh, freshChat, hooks, useHooks, stage, setDraft, bootData } from "../src/web-console/public/state.js";
|
||||
|
||||
test("state: page starts as app.js always started it", () => {
|
||||
assert.equal(page.S, null, "no server state before the first frame");
|
||||
assert.equal(page.selected, null, "no question picked");
|
||||
assert.equal(page.view, "questions", "the questions tab");
|
||||
assert.deepEqual(page.local, {
|
||||
staged: {},
|
||||
drafts: {},
|
||||
images: {},
|
||||
sent: {},
|
||||
stopping: null,
|
||||
afterBuild: null,
|
||||
homeward: null,
|
||||
launching: null,
|
||||
deleting: null,
|
||||
retract: {},
|
||||
chat: { draft: "", history: [], about: null, pending: [], lastSeenReplyId: null, images: [], conversation: null },
|
||||
});
|
||||
});
|
||||
|
||||
test("state: the rest of the shared state starts as app.js always started it", () => {
|
||||
const { S, local, selected, view, ...rest } = page;
|
||||
assert.deepEqual(rest, {
|
||||
agentLastSeen: null,
|
||||
pendingResult: false,
|
||||
pendingStop: false,
|
||||
pendingBannerUp: false,
|
||||
gone: false,
|
||||
chatFrame: null,
|
||||
chatDot: false,
|
||||
chatError: "",
|
||||
askRowCount: 0,
|
||||
docInView: null,
|
||||
wsFrame: null,
|
||||
meterFrame: null,
|
||||
updateFrame: null,
|
||||
subagentsFrame: null,
|
||||
overview: { key: null, text: null },
|
||||
wake: null,
|
||||
dashPick: null,
|
||||
mentionPop: null,
|
||||
heldPose: null,
|
||||
scopeMine: null,
|
||||
launchScoping: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("state: fresh() and freshChat() hand out a new empty draft each time", () => {
|
||||
assert.deepEqual(fresh(), page.local);
|
||||
assert.notEqual(fresh(), fresh(), "two calls share one object");
|
||||
assert.notEqual(fresh().chat, fresh().chat, "two drafts share one chat");
|
||||
assert.deepEqual(freshChat(), page.local.chat);
|
||||
});
|
||||
|
||||
for (const [name, call, on] of [
|
||||
["redraw", redraw, onRedraw],
|
||||
["saveNow", saveNow, onSave],
|
||||
]) {
|
||||
test(`state: ${name}() does nothing until a hook is set, then calls the latest one once per call`, () => {
|
||||
assert.doesNotThrow(() => call(), `${name}() throws with no hook`);
|
||||
let first = 0;
|
||||
let second = 0;
|
||||
on(() => first++);
|
||||
call();
|
||||
call();
|
||||
assert.equal(first, 2, "each call runs the hook once");
|
||||
on(() => second++);
|
||||
call();
|
||||
assert.deepEqual([first, second], [2, 1], "a second hook replaces the first");
|
||||
});
|
||||
}
|
||||
|
||||
test("state: a hook a screen calls throws by name until start-up sets it, then runs the one set", () => {
|
||||
assert.throws(() => hooks.banner("x"), /hooks\.banner was called before start-up set it/);
|
||||
const seen = [];
|
||||
useHooks({ banner: (text) => seen.push(text) });
|
||||
hooks.banner("hello");
|
||||
assert.deepEqual(seen, ["hello"]);
|
||||
useHooks({ banner: (text) => seen.push(text + "!") });
|
||||
hooks.banner("again");
|
||||
assert.deepEqual(seen, ["hello", "again!"], "a second set replaces the first");
|
||||
assert.throws(() => hooks.unknown(), /hooks\.unknown was called/);
|
||||
});
|
||||
|
||||
test("state: stage() stages or takes back an answer, then saves and redraws; setDraft() only saves", () => {
|
||||
let saved = 0;
|
||||
let drawn = 0;
|
||||
onSave(() => saved++);
|
||||
onRedraw(() => drawn++);
|
||||
stage("q1", { k: "A" });
|
||||
assert.deepEqual(page.local.staged, { q1: { k: "A" } });
|
||||
assert.deepEqual([saved, drawn], [1, 1]);
|
||||
stage("q1", null);
|
||||
assert.deepEqual(page.local.staged, {}, "null takes the answer back");
|
||||
assert.deepEqual([saved, drawn], [2, 2]);
|
||||
setDraft("note-q1", "typed");
|
||||
assert.equal(page.local.drafts["note-q1"], "typed");
|
||||
assert.deepEqual([saved, drawn], [3, 2], "a draft is kept without a redraw");
|
||||
delete page.local.drafts["note-q1"];
|
||||
});
|
||||
|
||||
test("state: bootData() is null without a page, and asked again it says the same", () => {
|
||||
assert.equal(bootData(), null);
|
||||
assert.equal(bootData(), null);
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { defaultInstruction, offered } from "../src/web-console/public/subagents.js";
|
||||
import { readSubagentCursor } from "../src/web-console/lib.mjs";
|
||||
import { readSubagentCursor } from "../src/web-console/settings.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
HOME,
|
||||
|
||||
@@ -12,7 +12,8 @@ import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { defaultName } from "../src/web-console/public/workspace.js";
|
||||
import { meterView } from "../src/web-console/public/meter.js";
|
||||
import { readLedger, readWorkspaceCursor, WORKSPACE_FILE } from "../src/web-console/lib.mjs";
|
||||
import { readLedger } from "../src/web-console/sessions.mjs";
|
||||
import { readWorkspaceCursor, WORKSPACE_FILE } from "../src/web-console/workspace.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
|
||||
@@ -0,0 +1,703 @@
|
||||
{
|
||||
"name": "cm-build",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "cm-build",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.11.1",
|
||||
"@codemirror/lang-markdown": "6.5.2",
|
||||
"@codemirror/language": "6.13.1",
|
||||
"@codemirror/state": "6.7.6",
|
||||
"@codemirror/view": "6.43.15",
|
||||
"esbuild": "0.28.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/autocomplete": {
|
||||
"version": "6.20.4",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.4.tgz",
|
||||
"integrity": "sha512-yF8RhOf2SXlg00+qtupzLhrglcas61boqaONiNcbPIebHCpJocpqTBA6dyrtUrQO47hqyTdeob/3XnYilT7TaQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "^6.0.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.17.0",
|
||||
"@lezer/common": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/commands": {
|
||||
"version": "6.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.1.tgz",
|
||||
"integrity": "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "^6.0.0",
|
||||
"@codemirror/state": "^6.7.0",
|
||||
"@codemirror/view": "^6.27.0",
|
||||
"@lezer/common": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/lang-css": {
|
||||
"version": "6.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
|
||||
"integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.0.0",
|
||||
"@codemirror/language": "^6.0.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@lezer/common": "^1.0.2",
|
||||
"@lezer/css": "^1.1.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/lang-html": {
|
||||
"version": "6.4.12",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.12.tgz",
|
||||
"integrity": "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.0.0",
|
||||
"@codemirror/lang-css": "^6.0.0",
|
||||
"@codemirror/lang-javascript": "^6.0.0",
|
||||
"@codemirror/language": "^6.4.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.17.0",
|
||||
"@lezer/common": "^1.0.0",
|
||||
"@lezer/css": "^1.1.0",
|
||||
"@lezer/html": "^1.3.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/lang-javascript": {
|
||||
"version": "6.2.5",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
|
||||
"integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.0.0",
|
||||
"@codemirror/language": "^6.6.0",
|
||||
"@codemirror/lint": "^6.0.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.17.0",
|
||||
"@lezer/common": "^1.0.0",
|
||||
"@lezer/javascript": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/lang-markdown": {
|
||||
"version": "6.5.2",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/lang-markdown/-/lang-markdown-6.5.2.tgz",
|
||||
"integrity": "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.7.1",
|
||||
"@codemirror/lang-html": "^6.0.0",
|
||||
"@codemirror/language": "^6.3.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.0.0",
|
||||
"@lezer/common": "^1.2.1",
|
||||
"@lezer/markdown": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/language": {
|
||||
"version": "6.13.1",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.13.1.tgz",
|
||||
"integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/streamparser": "^6.0.0",
|
||||
"@codemirror/view": "^6.23.0",
|
||||
"@lezer/common": "^1.5.0",
|
||||
"@lezer/highlight": "^1.0.0",
|
||||
"@lezer/lr": "^1.0.0",
|
||||
"style-mod": "^4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/lint": {
|
||||
"version": "6.9.7",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz",
|
||||
"integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.42.0",
|
||||
"crelt": "^1.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/state": {
|
||||
"version": "6.7.6",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz",
|
||||
"integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@marijn/find-cluster-break": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/streamparser": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/streamparser/-/streamparser-6.0.0.tgz",
|
||||
"integrity": "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@codemirror/view": {
|
||||
"version": "6.43.15",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.15.tgz",
|
||||
"integrity": "sha512-HHsfpqFeHyXLs983pSRe38Xajs0vFWZQ2BuX0m7Ki8w3jZ5iD8cuR3lBz2/5/X53Dhf32SBHKh6rtSTB6tKeGw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/state": "^6.7.0",
|
||||
"crelt": "^1.0.6",
|
||||
"style-mod": "^4.1.0",
|
||||
"w3c-keyname": "^2.2.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
|
||||
"integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"aix"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
|
||||
"integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
|
||||
"integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ia32": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
|
||||
"integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-loong64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
|
||||
"integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-mips64el": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
|
||||
"integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
|
||||
"cpu": [
|
||||
"mips64el"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ppc64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
|
||||
"integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-riscv64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
|
||||
"integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-s390x": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
|
||||
"integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openharmony-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openharmony"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/sunos-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"sunos"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-ia32": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
|
||||
"integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/common": {
|
||||
"version": "1.5.3",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.3.tgz",
|
||||
"integrity": "sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@lezer/css": {
|
||||
"version": "1.3.9",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.9.tgz",
|
||||
"integrity": "sha512-ZmzgvTOBdJWGIsY/ItAfN7UW8DV802oZG+jeG6E508SwEzz5YhuAajptpWPICvIyqYAD2+VjMdOS40GgGkyEOQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.2.0",
|
||||
"@lezer/highlight": "^1.0.0",
|
||||
"@lezer/lr": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/highlight": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz",
|
||||
"integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/html": {
|
||||
"version": "1.3.13",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
|
||||
"integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.2.0",
|
||||
"@lezer/highlight": "^1.0.0",
|
||||
"@lezer/lr": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/javascript": {
|
||||
"version": "1.5.6",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.6.tgz",
|
||||
"integrity": "sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.2.0",
|
||||
"@lezer/highlight": "^1.1.3",
|
||||
"@lezer/lr": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/lr": {
|
||||
"version": "1.4.11",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.11.tgz",
|
||||
"integrity": "sha512-UwgZcl1R66H2hDzBrA7kWyYmX6s8p5TQ+e/t7CuvgCtBEPxbEPaHYHu+pJBvTvDotEJpuQkJjbXuHiw5Cixxgw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/markdown": {
|
||||
"version": "1.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/markdown/-/markdown-1.8.1.tgz",
|
||||
"integrity": "sha512-M5YmEcKWO4mJ45Y1hECwqyu8cLv25EiXOK554PVOvDOWOP0olwelHHQUWr9sjF+d1bENVhy0nfJ8E57XZUTiXg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.5.0",
|
||||
"@lezer/highlight": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@marijn/find-cluster-break": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz",
|
||||
"integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/crelt": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
|
||||
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
|
||||
"integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"esbuild": "bin/esbuild"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@esbuild/aix-ppc64": "0.28.2",
|
||||
"@esbuild/android-arm": "0.28.2",
|
||||
"@esbuild/android-arm64": "0.28.2",
|
||||
"@esbuild/android-x64": "0.28.2",
|
||||
"@esbuild/darwin-arm64": "0.28.2",
|
||||
"@esbuild/darwin-x64": "0.28.2",
|
||||
"@esbuild/freebsd-arm64": "0.28.2",
|
||||
"@esbuild/freebsd-x64": "0.28.2",
|
||||
"@esbuild/linux-arm": "0.28.2",
|
||||
"@esbuild/linux-arm64": "0.28.2",
|
||||
"@esbuild/linux-ia32": "0.28.2",
|
||||
"@esbuild/linux-loong64": "0.28.2",
|
||||
"@esbuild/linux-mips64el": "0.28.2",
|
||||
"@esbuild/linux-ppc64": "0.28.2",
|
||||
"@esbuild/linux-riscv64": "0.28.2",
|
||||
"@esbuild/linux-s390x": "0.28.2",
|
||||
"@esbuild/linux-x64": "0.28.2",
|
||||
"@esbuild/netbsd-arm64": "0.28.2",
|
||||
"@esbuild/netbsd-x64": "0.28.2",
|
||||
"@esbuild/openbsd-arm64": "0.28.2",
|
||||
"@esbuild/openbsd-x64": "0.28.2",
|
||||
"@esbuild/openharmony-arm64": "0.28.2",
|
||||
"@esbuild/sunos-x64": "0.28.2",
|
||||
"@esbuild/win32-arm64": "0.28.2",
|
||||
"@esbuild/win32-ia32": "0.28.2",
|
||||
"@esbuild/win32-x64": "0.28.2"
|
||||
}
|
||||
},
|
||||
"node_modules/style-mod": {
|
||||
"version": "4.1.4",
|
||||
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz",
|
||||
"integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/w3c-keyname": {
|
||||
"version": "2.2.8",
|
||||
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
|
||||
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env node
|
||||
// Builds the one vendored CodeMirror file the Notebook's live-preview editor
|
||||
// imports. Dev-only: lives in scripts/ so it never ships inside a skill.
|
||||
//
|
||||
// node scripts/vendor-codemirror.mjs rebuild from the lock file
|
||||
// node scripts/vendor-codemirror.mjs --update-lock after changing a version below
|
||||
//
|
||||
// The console has no dependencies and no build step for users, so CodeMirror 6
|
||||
// is bundled once, here, into src/web-console/public/vendor/codemirror.esm.js
|
||||
// (Markdown only, minified, one ES module). The packages and esbuild are
|
||||
// installed into a throwaway folder under the OS temp directory, never into
|
||||
// the repo. Only the six packages below are named; everything they pull in
|
||||
// (@lezer/*, style-mod, w3c-keyname, crelt) is pinned by
|
||||
// scripts/vendor-codemirror-lock.json, installed with npm ci, so the same
|
||||
// lock gives the same bytes. Needs Node 18+, npm and network access.
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const OUT = path.join(ROOT, "src", "web-console", "public", "vendor", "codemirror.esm.js");
|
||||
const LOCK = path.join(ROOT, "scripts", "vendor-codemirror-lock.json");
|
||||
|
||||
export const VERSIONS = Object.freeze({
|
||||
esbuild: "0.28.2",
|
||||
"@codemirror/state": "6.7.6",
|
||||
"@codemirror/view": "6.43.15",
|
||||
"@codemirror/language": "6.13.1",
|
||||
"@codemirror/commands": "6.11.1",
|
||||
"@codemirror/lang-markdown": "6.5.2",
|
||||
});
|
||||
|
||||
export const HEADER =
|
||||
"/* CodeMirror 6 (state, view, language, commands, lang-markdown), MIT licence, (c) Marijn Haverbeke and others.\n" +
|
||||
" * https://codemirror.net/ . Bundled by scripts/vendor-codemirror.mjs; do not edit by hand.\n" +
|
||||
" * Versions: " +
|
||||
Object.entries(VERSIONS)
|
||||
.filter(([name]) => name !== "esbuild")
|
||||
.map(([name, version]) => name + " " + version)
|
||||
.join(", ") +
|
||||
" */\n";
|
||||
|
||||
// What the page may import: exactly what notepad-editor.js uses, since an
|
||||
// entry export is never tree-shaken. indentWithTab is left out on purpose: it
|
||||
// would trap the Tab key and keyboard users could not leave the editor.
|
||||
export const ENTRY = `export { Compartment, EditorState } from "@codemirror/state";
|
||||
export { Decoration, EditorView, ViewPlugin, WidgetType, keymap } from "@codemirror/view";
|
||||
export { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
||||
export { syntaxTree } from "@codemirror/language";
|
||||
export { defaultKeymap, history, historyKeymap, redo } from "@codemirror/commands";
|
||||
`;
|
||||
|
||||
// npm is a .cmd file on Windows, which only a shell can start; node never needs one
|
||||
// (its path may hold spaces).
|
||||
function run(cmd, args, cwd) {
|
||||
const res = spawnSync(cmd, args, { cwd, encoding: "utf8", shell: process.platform === "win32" && cmd === "npm" });
|
||||
if (res.status !== 0) {
|
||||
process.stderr.write((res.stdout || "") + (res.stderr || ""));
|
||||
throw new Error(`${cmd} ${args.join(" ")} failed (${res.status})`);
|
||||
}
|
||||
return res.stdout;
|
||||
}
|
||||
|
||||
export function build({ updateLock = false } = {}) {
|
||||
const work = fs.mkdtempSync(path.join(os.tmpdir(), "plan2code-codemirror-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(work, "package.json"), JSON.stringify({ name: "cm-build", private: true, type: "module", dependencies: VERSIONS }));
|
||||
if (updateLock || !fs.existsSync(LOCK)) {
|
||||
run("npm", ["install", "--no-audit", "--no-fund", "--ignore-scripts", "--package-lock-only"], work);
|
||||
fs.copyFileSync(path.join(work, "package-lock.json"), LOCK);
|
||||
} else {
|
||||
fs.copyFileSync(LOCK, path.join(work, "package-lock.json"));
|
||||
}
|
||||
run("npm", ["ci", "--no-audit", "--no-fund", "--ignore-scripts"], work);
|
||||
fs.writeFileSync(path.join(work, "entry.js"), ENTRY);
|
||||
const esbuild = path.join(work, "node_modules", "esbuild", "bin", "esbuild");
|
||||
run(process.execPath, [esbuild, "entry.js", "--bundle", "--format=esm", "--minify", "--target=es2022", "--legal-comments=none", "--outfile=out.js"], work);
|
||||
const body = fs.readFileSync(path.join(work, "out.js"), "utf8");
|
||||
fs.mkdirSync(path.dirname(OUT), { recursive: true });
|
||||
fs.writeFileSync(OUT, HEADER + body);
|
||||
} finally {
|
||||
fs.rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
const bytes = fs.readFileSync(OUT);
|
||||
return { file: path.relative(ROOT, OUT), bytes: bytes.length, sha256: crypto.createHash("sha256").update(bytes).digest("hex") };
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
console.log(JSON.stringify(build({ updateLock: process.argv.includes("--update-lock") }), null, 2));
|
||||
}
|
||||
@@ -21,13 +21,21 @@ import path from "node:path";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import http from "node:http";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { readChat } from "../src/web-console/lib.mjs";
|
||||
import { readChat } from "../src/web-console/inbox.mjs";
|
||||
|
||||
export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
export const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
|
||||
export const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-test-"));
|
||||
export const MODELS_DIR = path.join(HOME, "plan2code");
|
||||
// Handoffs are written outside every repo, under ~/.plan2code/handoffs, so
|
||||
// each test file gets its own throwaway folder for them too.
|
||||
export const HANDOFFS_DIR = path.join(HOME, "handoffs");
|
||||
// Notepads likewise live under ~/.plan2code/notepads. Set here for this
|
||||
// process too, so a test importing notepads.mjs directly never reaches the
|
||||
// real folder (notepadsDir() reads the variable on every call).
|
||||
export const NOTEPADS_DIR = path.join(HOME, "notepads");
|
||||
process.env.PLAN2CODE_NOTEPADS_DIR = NOTEPADS_DIR;
|
||||
// A spawned console server or CLI must not inherit relocation vars (an
|
||||
// exported GIT_DIR would redirect the board's reads), SSH markers (they set
|
||||
// `remote` in open output) or leftover PLAN2CODE_* knobs.
|
||||
@@ -51,7 +59,7 @@ for (const k of AMBIENT_ENV_KEYS) delete scrubbed[k];
|
||||
// cannot open. An empty file is the portable "no global config".
|
||||
const EMPTY_GITCONFIG = path.join(HOME, "empty-gitconfig");
|
||||
fs.writeFileSync(EMPTY_GITCONFIG, "");
|
||||
export const ENV = { ...scrubbed, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_NO_BROWSER: "1", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG };
|
||||
export const ENV = { ...scrubbed, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_HANDOFFS_DIR: HANDOFFS_DIR, PLAN2CODE_NOTEPADS_DIR: NOTEPADS_DIR, PLAN2CODE_NO_BROWSER: "1", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG };
|
||||
// Every server these tests start runs the release check at boot. A fresh
|
||||
// cached failure keeps the whole suite off the network and bannerless.
|
||||
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
|
||||
@@ -176,6 +184,14 @@ export const helpTemplate = () => {
|
||||
return tpl[1];
|
||||
};
|
||||
|
||||
// The Planny poses each skill's starting screen clones, from index.html.
|
||||
export const poseTemplate = () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const tpl = html.match(/<template id="start-poses">([\s\S]*?)<\/template>/);
|
||||
assert.ok(tpl, "index.html has the start-poses template");
|
||||
return tpl[1];
|
||||
};
|
||||
|
||||
// The server checks magic bytes only, so a JPEG header and some padding will do.
|
||||
export const JPEG = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.alloc(400, 7), Buffer.from([0xff, 0xd9])]);
|
||||
|
||||
|
||||
@@ -22,6 +22,11 @@
|
||||
* `--pick-folder` (passed by the desktop shortcut, never forwarded to the CLI) asks for the
|
||||
* project folder with a native folder picker first, starting on the folder picked last time.
|
||||
*
|
||||
* `plan2code update` starts no agent: it re-runs the npx install with `--update`, which
|
||||
* reinstalls whatever ~/.plan2code/install.json lists. Before an agent starts, one line says
|
||||
* when a newer release is out (releaseNotice), read from the web console's cached release check
|
||||
* and never waiting on the network.
|
||||
*
|
||||
* On a terminal it opens with a Planny banner (renderBanner) and colors its headings, numbers,
|
||||
* defaults and errors (paint). Color is on only on a TTY (stdout and stderr each checked on
|
||||
* its own) with NO_COLOR unset; piped runs print plain text and no banner.
|
||||
@@ -41,6 +46,15 @@ const STATE_FILE = path.join(os.homedir(), '.plan2code', 'launcher.json');
|
||||
// Menus longer than this print compactly (id-only, two columns).
|
||||
const MODELS_MENU_COMPACT_AT = 30;
|
||||
const PICKER_PROMPT = 'Choose the project folder to open Plan2Code in';
|
||||
const UPDATE_COMMAND = 'update';
|
||||
// The same URL src/web-console/update-check.mjs exports as REPO_URL. This file may require
|
||||
// nothing but Node built-ins (and update-check.mjs is ESM), so it keeps its own copy.
|
||||
const REPO_URL = 'https://github.com/jparkerweb/plan2code.git';
|
||||
// The web console's cached release check, and how long it counts as fresh (update-check.mjs
|
||||
// CACHE_MS). PLAN2CODE_CONSOLE_HOME moves the console's files, as in files.mjs.
|
||||
const CONSOLE_HOME = process.env.PLAN2CODE_CONSOLE_HOME || path.join(os.homedir(), '.plan2code', 'console');
|
||||
const UPDATE_CACHE_FILE = path.join(CONSOLE_HOME, 'update-check.json');
|
||||
const UPDATE_CACHE_MS = 60 * 60 * 1000;
|
||||
|
||||
// The escape values install.js's COLORS uses, copied: this file is installed alone and may
|
||||
// require nothing but Node built-ins.
|
||||
@@ -202,26 +216,50 @@ public static class Plan2CodeFolderPicker {
|
||||
[DllImport("user32.dll")]
|
||||
private static extern int GetSystemMetrics(int index);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void SwitchToThisWindow(IntPtr hWnd, bool altTab);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
|
||||
|
||||
private const uint FOS_PICKFOLDERS = 0x20;
|
||||
private const uint FOS_FORCEFILESYSTEM = 0x40;
|
||||
private const uint FOS_PATHMUSTEXIST = 0x800;
|
||||
private const uint SIGDN_FILESYSPATH = 0x80058000;
|
||||
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
|
||||
|
||||
// Windows refuses SetForegroundWindow from a background process (this one is spawned
|
||||
// by the detached console server), so the dialog opened behind the browser. A tap of
|
||||
// Alt counts as input from this process and lifts the lock for the call after it. The
|
||||
// topmost flag below is ignored by this dialog (SetWindowPos succeeds, the bit stays
|
||||
// off), so taking the foreground is what puts it in front.
|
||||
private static void Raise(string title) {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
IntPtr hwnd = FindWindow(null, title);
|
||||
if (hwnd != IntPtr.Zero) {
|
||||
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
|
||||
int h = Math.Min(750, GetSystemMetrics(1) - 80);
|
||||
int x = (GetSystemMetrics(0) - w) / 2 + 40;
|
||||
int y = (GetSystemMetrics(1) - h) / 2 + 40;
|
||||
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
|
||||
SetForegroundWindow(hwnd);
|
||||
return;
|
||||
}
|
||||
IntPtr hwnd = IntPtr.Zero;
|
||||
for (int i = 0; i < 200; i++) {
|
||||
hwnd = FindWindow(null, title);
|
||||
if (hwnd != IntPtr.Zero && IsWindowVisible(hwnd)) break;
|
||||
hwnd = IntPtr.Zero;
|
||||
Thread.Sleep(50);
|
||||
}
|
||||
if (hwnd == IntPtr.Zero) return;
|
||||
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
|
||||
int h = Math.Min(750, GetSystemMetrics(1) - 80);
|
||||
int x = (GetSystemMetrics(0) - w) / 2 + 40;
|
||||
int y = (GetSystemMetrics(1) - h) / 2 + 40;
|
||||
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
|
||||
for (int i = 0; i < 20 && GetForegroundWindow() != hwnd; i++) {
|
||||
keybd_event(0x12, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(0x12, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(hwnd);
|
||||
SwitchToThisWindow(hwnd, true);
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
}
|
||||
|
||||
public static string Pick(IntPtr owner, string title, string start) {
|
||||
@@ -608,12 +646,89 @@ async function exitWith(code, fromShortcut) {
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a resolved command with `args`. A .cmd/.bat wrapper on Windows goes through cmd.exe,
|
||||
* since Node refuses to spawn one without a shell.
|
||||
*/
|
||||
function spawnCommand(file, args, options) {
|
||||
return IS_WINDOWS && /\.(cmd|bat)$/i.test(file)
|
||||
? spawn(
|
||||
process.env.ComSpec || 'cmd.exe',
|
||||
['/d', '/s', '/c', `"${[file, ...args].map(quoteForCmd).join(' ')}"`],
|
||||
{ ...options, windowsVerbatimArguments: true }
|
||||
)
|
||||
: spawn(file, args, options);
|
||||
}
|
||||
|
||||
/** `plan2code update`: the npx install with --update, passing npx's exit code through. No agent starts. */
|
||||
function runUpdate() {
|
||||
console.log('Updating Plan2Code...');
|
||||
const npx = findOnPath('npx');
|
||||
if (!npx) {
|
||||
console.error(`${ce.red('plan2code:')} npx was not found on your PATH. It comes with Node.js 18+ (https://nodejs.org).`);
|
||||
return process.exit(127);
|
||||
}
|
||||
const child = spawnCommand(npx, ['--yes', '--allow-git=all', `git+${REPO_URL}`, '--update'], { stdio: 'inherit' });
|
||||
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
|
||||
process.on(signal, () => {});
|
||||
}
|
||||
child.on('error', (error) => {
|
||||
console.error(`${ce.red('plan2code:')} failed to start npx: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
child.on('exit', (code) => process.exit(code ?? 1));
|
||||
}
|
||||
|
||||
/** -1, 0 or 1 comparing two plain X.Y.Z versions; null unless both are X.Y.Z (as update-check.mjs). */
|
||||
function compareVersions(a, b) {
|
||||
const semver = /^\d+\.\d+\.\d+$/;
|
||||
if (typeof a !== 'string' || typeof b !== 'string' || !semver.test(a) || !semver.test(b)) return null;
|
||||
const x = a.split('.').map(Number);
|
||||
const y = b.split('.').map(Number);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* One line when a newer release is out, from the console's cached check only. A missing or
|
||||
* stale cache prints nothing and starts a detached refresh (the copied update-check.mjs) so
|
||||
* the next start knows; the start never waits on it. Any error is swallowed: the notice must
|
||||
* never stand between the person and their agent.
|
||||
*/
|
||||
async function releaseNotice() {
|
||||
try {
|
||||
const installed = (readJsonFile(path.join(__dirname, 'version.json')) || {}).version;
|
||||
if (typeof installed !== 'string') return;
|
||||
const cache = readJsonFile(UPDATE_CACHE_FILE);
|
||||
if (cache && typeof cache.checkedAt === 'number' && Date.now() - cache.checkedAt < UPDATE_CACHE_MS) {
|
||||
if (compareVersions(installed, cache.latest) === -1) {
|
||||
console.log(c.yellow(`Plan2Code v${cache.latest} is out (you have v${installed}). Run: plan2code update`));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const checker = path.join(__dirname, 'update-check.mjs');
|
||||
if (!fs.existsSync(checker)) return;
|
||||
const refresh =
|
||||
'import(process.argv[1]).then((m) => m.checkForUpdate({ installed: process.argv[2], cacheFile: process.argv[3] })).catch(() => {});';
|
||||
const href = require('url').pathToFileURL(checker).href;
|
||||
spawn(process.execPath, ['-e', refresh, href, installed, UPDATE_CACHE_FILE], {
|
||||
detached: true,
|
||||
stdio: 'ignore',
|
||||
windowsHide: true,
|
||||
}).unref();
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function launch() {
|
||||
const argv = process.argv.slice(2);
|
||||
if (argv[0] === UPDATE_COMMAND) return runUpdate();
|
||||
const fromShortcut = argv.includes(PICK_FOLDER_FLAG);
|
||||
const { cli: requestedCli, rest: extraArgs } = takeCliFlag(argv.filter((arg) => arg !== PICK_FOLDER_FLAG));
|
||||
|
||||
printIntro();
|
||||
await releaseNotice();
|
||||
const { cli, code } = await chooseCli(requestedCli);
|
||||
if (!cli) return exitWith(code, fromShortcut);
|
||||
saveState({ lastCli: cli.id });
|
||||
@@ -636,14 +751,7 @@ async function launch() {
|
||||
const args = cli.args(extraArgs);
|
||||
const options = { cwd, stdio: 'inherit' };
|
||||
|
||||
const child =
|
||||
IS_WINDOWS && /\.(cmd|bat)$/i.test(cli.path)
|
||||
? spawn(
|
||||
process.env.ComSpec || 'cmd.exe',
|
||||
['/d', '/s', '/c', `"${[cli.path, ...args].map(quoteForCmd).join(' ')}"`],
|
||||
{ ...options, windowsVerbatimArguments: true }
|
||||
)
|
||||
: spawn(cli.path, args, options);
|
||||
const child = spawnCommand(cli.path, args, options);
|
||||
|
||||
// Ctrl+C reaches the CLI directly through the shared console; keep this wrapper alive so it
|
||||
// can hand back the CLI's exit status instead of dying first.
|
||||
@@ -669,4 +777,4 @@ async function launch() {
|
||||
// Run only when invoked directly; requiring the file (the tests do) is load-only.
|
||||
if (require.main === module) launch();
|
||||
|
||||
module.exports = { mergeModels, modelEntries, renderBanner, paint, hasModelFlag };
|
||||
module.exports = { mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions };
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, isoDate, stamp, now } from "./common.mjs";
|
||||
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, isoDate, stamp, now, LOOP_TOKENS, scrapeHits } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
pathfinder.mjs: Pathfinder map bookkeeping. JSON on stdout (trail: --text prints the footer itself).
|
||||
@@ -84,16 +84,6 @@ const SCHEMA_KEYS = ["Type", "State", "Blocked by", "Claimed", "Resolved", "Lock
|
||||
const TYPES = ["grill · HITL", "research · AFK", "sketch · HITL", "legwork · HITL", "legwork · AFK"];
|
||||
const STATES = ["open", "claimed", "resolved", "out-of-scope"];
|
||||
const GLYPH = { x: "●", "/": "◉", " ": "○", "!": "⊘", "-": "⊝" };
|
||||
const LOOP_TOKENS = /\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
|
||||
// The metrics collector's own scrape patterns (plan2code-metrics/src/collector.ts).
|
||||
const SCRAPE = [
|
||||
{ name: "overall confidence with %", re: /(?:Overall|Final|Total)?\s*\**[Cc]onfidence\**[:\s*]+(\d{1,3})%/ },
|
||||
{ name: "confidence table cell", re: /[|]\s*[Cc]onfidence\s*[|]\s*(\d{1,3})/ },
|
||||
{ name: "bare Requirements + number", re: /[Rr]equirements?[:\s|]+(\d{1,2})/ },
|
||||
{ name: "bare Feasibility + number", re: /[Ff]easibility[:\s|]+(\d{1,2})/ },
|
||||
{ name: "bare Integration + number", re: /[Ii]ntegration[:\s|]+(\d{1,2})/ },
|
||||
{ name: "bare Risk + number", re: /[Rr]isk[:\s|]+(\d{1,2})/ },
|
||||
];
|
||||
const DIMENSIONS = [
|
||||
{ key: "Requirements-clarity", word: "Requirements" },
|
||||
{ key: "Feasibility-technical", word: "Feasibility" },
|
||||
@@ -1058,15 +1048,6 @@ function walk(dir) {
|
||||
return outList;
|
||||
}
|
||||
|
||||
function scrapeHits(text) {
|
||||
const hits = [];
|
||||
for (const s of SCRAPE) {
|
||||
const m = text.match(s.re);
|
||||
if (m) hits.push(`${s.name}: "${m[0].trim()}"`);
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
async function cmdLint(loc) {
|
||||
const problems = [];
|
||||
const add = (level, file, message) => problems.push({ level, file: rel(loc.root, file), message });
|
||||
|
||||
@@ -39,7 +39,7 @@ Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it
|
||||
|
||||
- **Plan, don't do.** Every question resolves a DECISION. The pull to just build it is the edge of the map — hand off.
|
||||
- **Confirm before creating anything.** No files, no issues, until the Intent Gate (Step 0) and backend pick (Step 1) return.
|
||||
- **One question at a time** (`research` excepted — parallel); fork-menu between decisions, fresh session after ~3.
|
||||
- **One question at a time** (`research` runs in parallel); fork-menu between decisions, fresh session after ~3.
|
||||
- **Refer by name.** "[Export format](<link>)", never "02" or "#42" in prose. Bare ids belong on `Blocked by:` lines and in commands.
|
||||
- **HITL questions are never self-answered.** Ask and wait; an agent that answers its own grill has broken the skill.
|
||||
- **Questions are ground truth; the map is a rebuildable index.** A filled `## Answer` beats any state marker; detail lives in one place.
|
||||
@@ -51,7 +51,7 @@ Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it
|
||||
|
||||
## Auto-Discovery and Mode Selection
|
||||
|
||||
⚠️ `specs/` is gitignored — NEVER use Glob. Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
|
||||
⚠️ `specs/` is gitignored: NEVER use Glob; list it with `ls specs/` or `Get-ChildItem specs/`.
|
||||
|
||||
**Brief/recap/minutes asked?** → read references/brief.md: `reconcile`, then `brief-data --range <range>` (`github`: its brief section), write plain-English `briefs/brief-<YYYYMMDD>.md` from the output, STOP. Never resolves.
|
||||
|
||||
@@ -83,7 +83,7 @@ Read references/chart.md
|
||||
0. `[Chart - Step 0: Intent Gate]` **Before creating anything**, use AskUserQuestion for the outcome and WAIT: **chart a map** (foggy — Step 1), **`/plan2code-1-plan`** (clear — STOP), **`/plan2code-quick-task`** (tiny — STOP). HITL, never self-select "chart".
|
||||
1. `[Chart - Step 1: Name and backend]` Only after the gate says "chart." Confirm the kebab-case idea name, then ask — HITL, never self-picked — **local files or GitHub Issues?** Recommend `local` for solo work; offer `github` only if preflight passes, naming the repo's visibility. THEN the first write.
|
||||
2. `[Chart - Step 2: Destination]` Grill until it is one or two lines. It fixes scope — settle it first.
|
||||
3. `[Chart - Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK`. On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter.
|
||||
3. `[Chart - Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK`. On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter. Unfamiliar code? `/plan2code-xray` explains an area first.
|
||||
4. `[Chart - Step 4: Map the frontier]` Grill again **breadth-first**: fan out, never deep on one thread. Surface the open decisions and what is takeable now.
|
||||
5. `[Chart - Step 5: Create the map]` `**Status:** Charting`, Destination, Ground rules (backend first), an empty index, the fog in `## Not yet specified`. Say once where it lives and who sees it.
|
||||
6. `[Chart - Step 6: Write the questions]` One per decision you can phrase sharply NOW, dependency order, `Blocked by:` filled the same pass — on `github`, create all first, wire edges second. The rest stays fog. Include a `grill · HITL` testing-posture question; `/plan2code-1-plan` Phase 1 needs it.
|
||||
@@ -102,7 +102,7 @@ Assume NO memory of any prior session.
|
||||
|
||||
1. `[Work - Step 1: Load]` Read the map whole. No question yet.
|
||||
2. `[Work - Step 2: Reconcile]` **Always.** `local`: run `reconcile`. The answer wins: a question whose `## Answer` its state contradicts is resolved, a missing `Resolved:` is backfilled from the claim (today if none), a claim with no `## Answer` (a crash) is released, and every marker is rebuilt from the questions. Tell the human each `repairs` entry in one line. Re-fire every question in `refire` (research cut off before its `Research complete:` line; resolve.md → Interrupted research). `--dry-run` first if the map looks badly off. `github`: the reconcile checks in the backend playbook.
|
||||
3. `[Work - Step 3: Frontier]` Every question open, unclaimed, and unblocked, first in order. `local`: run `frontier` (`frontier`, `blocked` with each blocker, `stranded`, `nextNN`, `counts`).
|
||||
3. `[Work - Step 3: Frontier]` Every question open, unclaimed, and unblocked, first in order. `local`: run `frontier` (`blocked` with each blocker, `stranded`, `nextNN`, `counts`).
|
||||
4. `[Work - Step 4: Choose and claim]` The one the user named, else first on the frontier. Mark it claimed on the question and the map, **saved before any work** (`local`: `claim <NN>`, which refuses a blocked or non-open question and a second open claim). A `research` pick fires unclaimed instead (resolve.md); then claim the next one.
|
||||
- Stranded on an `out-of-scope` blocker? Check this first: re-frame or rule out, re-run Step 3.
|
||||
- Frontier empty but questions remain (`allBlocked`)? Report the chain, STOP.
|
||||
@@ -126,7 +126,7 @@ The map clears only when ALL hold:
|
||||
3. The destination is reachable with nothing left to decide
|
||||
4. All four confidence dimensions score ≥ 18/25
|
||||
|
||||
Score the four dimensions (handoff.md rubric) and write them to the map's `**Confidence:**` line. `local`: run `gate`; it checks 1, 2 and 4 against the files, plus the handoff preflight and the Requirements, Feasibility and Risk caps; condition 3, the Integration cap and the scores stay yours (its `judgment` list). Any failing: name it, keep working. All passing: follow the handoff playbook, set `**Status:** Cleared`, run `lint`, stop. The PLAN-DRAFT is always local — `/plan2code-1-plan` cannot read a tracker.
|
||||
Score the four dimensions (handoff.md rubric) and write them to the map's `**Confidence:**` line. `local`: run `gate`; it checks 1, 2 and 4 against the files, plus the handoff preflight and the Requirements, Feasibility and Risk caps; condition 3, the Integration cap and the scores stay yours (its `judgment` list). Any failing: name it, keep working. All passing: follow the handoff playbook, set `**Status:** Cleared`, run `lint`, stop. The PLAN-DRAFT is always local: Plan cannot read a tracker.
|
||||
|
||||
## Trail Footer
|
||||
|
||||
@@ -134,11 +134,11 @@ Read references/trail.md
|
||||
|
||||
> Fallback: once the map exists, end every response with a marker path (`●` done · `◉` here · `○` open · `⊘` blocked · `⊝` out of scope) `START`→`⚑`, a named legend, a plain-English confidence note, then ONE closer: asking → Form B, `WAITING ON YOU`, no command; menu → Form C, `NEXT UP` + `OR START FRESH`; session end → Form A, `NEXT STEP` + resume command with `--web` (map issue URL on `github`).
|
||||
|
||||
Close EVERY response with the trail once the map exists. You pick the form by what the turn does. `local`: `trail` draws it from the files, so paste its output verbatim. Asking → Form B, `trail --form B --item "<probe>" ... --text` (one `--item` per open probe, up to three). Menu after a decision → Form C, `trail --form C` WITHOUT `--text`: paste its `text`, then build the question tool from its `menu`. Session end → Form A, `trail --form A --text`. `github`: draw it by hand per the backend playbook.
|
||||
Close EVERY response with the trail once the map exists; the turn picks the form. `local`: `trail` draws it from the files; paste its output verbatim. Asking → `trail --form B --item "<probe>" ... --text` (one `--item` per open probe, up to three). Menu → `trail --form C` WITHOUT `--text`: paste its `text`, then build the question tool from its `menu`. Session end → `trail --form A --text`. `github`: by hand per the backend playbook.
|
||||
|
||||
## Session End
|
||||
|
||||
Report each question resolved (name + gist), what graduated, what's still open; offer a brief for today. Nothing to commit — `local` is gitignored, `github` already on the tracker. Then the mascot, then the Trail Footer.
|
||||
Report each question resolved (name + gist), what graduated, what's still open; offer a brief for today. Nothing to commit (`local` is gitignored). Then the mascot, then the Trail Footer.
|
||||
|
||||
**Web console:** at session end or on a `__stop`, post `finish` (Form A's command) BEFORE `stop` (notes/pathfinder.md).
|
||||
|
||||
@@ -156,9 +156,9 @@ Report each question resolved (name + gist), what graduated, what's still open;
|
||||
|
||||
| Issue | Action |
|
||||
|---|---|
|
||||
| Session stops mid-question, or map drift | Release the claim, note why (or leave it: the next reconcile releases a claim with no answer). Work Step 2 repairs both; questions win. Never reconcile mid-question: it would release your own live claim. |
|
||||
| A script cannot run (no `node`) | Say so once; do the step by hand from questions.md (markers, blocking, schema) and the reference that names the step. Footer by hand: the trail's glyph path, then Form A `NEXT STEP · start a new conversation and run:` + the command, Form B `WAITING ON YOU · answer here, in this conversation:` + the items, or Form C `OR START FRESH · new conversation, paste:` + the command. |
|
||||
| Frontier empty, fog remains | Not sharp yet. Grill it into a question, or clear the map |
|
||||
| Session stops mid-question, or map drift | Release the claim (or leave it: the next reconcile releases a claim with no answer). Work Step 2 repairs both; questions win. Never reconcile mid-question: it releases your own live claim. |
|
||||
| A script cannot run (no `node`) | Say so once; do the step by hand from questions.md and the step's reference, and draw the footer by hand from trail.md (or its fallback above). |
|
||||
| Frontier empty, fog remains | Grill it into a question, or clear the map |
|
||||
| Reference file missing | Use the fallback blockquote under its `Read` line |
|
||||
| `gh` fails mid-session on a `github` map | Report and STOP. Falling back to local forks the map |
|
||||
| User skips to planning | Their call. Name what is undecided, route to `/plan2code-1-plan` |
|
||||
|
||||
@@ -40,8 +40,7 @@ Check if `./AGENTS.md` exists:
|
||||
- Resolve ambiguities through questions - do NOT assume
|
||||
- Document unavoidable assumptions clearly
|
||||
- Present/confirm technology decisions with user
|
||||
- NEVER write implementation code
|
||||
- Keep responses conceptual - detailed specs belong in final PLAN-DRAFT only
|
||||
- NEVER write implementation code; keep responses conceptual, detailed specs belong in the final PLAN-DRAFT only
|
||||
- If no file access, output content in code blocks with file path headers
|
||||
|
||||
---
|
||||
@@ -52,8 +51,11 @@ Before Phase 1, run `node "<S>/specs.mjs" list` from the project root (`<S>`: `s
|
||||
- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4
|
||||
- Status "Escalated from Quick Task - Resume at Phase 2": Acknowledge, verify requirements, skip to Phase 2
|
||||
- Status "Draft" or "Complete": Ask user how to proceed
|
||||
- A spec folder holding a `DIAGNOSIS-*.md` (Diagnose's write-up of a bug): read it first, as the Phase 1 brief (the bug, its cause, the suggested fix); that folder's name is the feature name (do not ask for one), so the PLAN-DRAFT lands beside the diagnosis
|
||||
- No PLAN-DRAFT: Begin at Phase 1. Console: its idea card carries `"templates": "idea"` (console.md → The kinds)
|
||||
|
||||
`node "<S>/specs.mjs" check-draft specs/<feature-name>` checks a written PLAN-DRAFT (Phase 7).
|
||||
|
||||
---
|
||||
|
||||
### Clarification Protocol
|
||||
@@ -101,6 +103,7 @@ After confirmation, proceed with analysis:
|
||||
> 1. **Types**: Unit, Integration, E2E, or None
|
||||
> 2. **Phase testing**: Run after each phase?
|
||||
> 3. **Coverage**: Critical paths / Moderate (~60-80%) / Comprehensive (>80%)
|
||||
> 4. **Approach**: Code first (default) or Test first (each task's test is written and seen failing before its code)
|
||||
>
|
||||
> Say 'skip testing' to omit."
|
||||
|
||||
@@ -124,7 +127,7 @@ After confirmation, proceed with analysis:
|
||||
|
||||
### PHASE 2: System Context Examination
|
||||
|
||||
**Existing projects:**
|
||||
**Existing projects:** (unfamiliar code? `/plan2code-xray` explains an area first)
|
||||
1. Examine directory structure
|
||||
2. Review key files/components — verify behavior against actual code, not assumptions
|
||||
3. Identify patterns, conventions, code style
|
||||
@@ -233,6 +236,8 @@ State assessment and ask user to confirm.
|
||||
|
||||
Replace values with actuals. Optionally add plain `key: value` lines below for readability (no bold/markdown).
|
||||
|
||||
5. Run `node "<S>/specs.mjs" check-draft specs/<feature-name>` and fix every error before the closing message.
|
||||
|
||||
## Templates
|
||||
|
||||
### PLAN-DRAFT Format
|
||||
@@ -243,7 +248,7 @@ Header: Title, Created date, Status (Draft | Phase 3 Complete - Resume at Phase
|
||||
|
||||
Sections:
|
||||
1. **Executive Summary** — 2-3 sentences
|
||||
2. **Requirements** — 2.1 Functional (FR-N checklist), 2.2 Non-Functional (NFR-N checklist), 2.3 Out of Scope, 2.4 Testing Strategy table (Types, Phase Testing, Coverage)
|
||||
2. **Requirements** — 2.1 Functional (FR-N checklist), 2.2 Non-Functional (NFR-N checklist), 2.3 Out of Scope, 2.4 Testing Strategy table (Types, Phase Testing, Coverage, plus a `| Approach | Test first |` row only when picked; absent means code first)
|
||||
3. **Tech Stack** — table: Category / Technology / Version / Justification
|
||||
4. **Architecture** — 4.1 Pattern (name + rationale), 4.2 System Context Diagram, 4.3 Components table, 4.4 Data Model, 4.5 API Design
|
||||
5. **Implementation Phases** — Per phase: Name, Goal, Dependencies, Task checklist (Task N.N)
|
||||
@@ -292,8 +297,3 @@ When complete (PLAN-DRAFT created), tell user:
|
||||
- **Abort:** Confirm with user, list files needing cleanup, stop workflow
|
||||
- **Lost context:** Attach PLAN-DRAFT, state phase
|
||||
- **Confidence stuck <90%:** List blockers, ask targeted questions
|
||||
|
||||
## Reminders
|
||||
|
||||
- Final phase: PLANNING PHASE 7: Transition Decision
|
||||
- Do NOT implement - design and present plan only
|
||||
@@ -46,7 +46,7 @@ Do not proceed without spec files.
|
||||
`🔄 [REVISION] Step 1: Change Analysis`
|
||||
|
||||
1. Read all spec files
|
||||
2. Understand the requested change
|
||||
2. Understand the requested change. Before asking for one, look in the Notes of every `[/]` phase for a waiting `**Plan change:**` line: Implement paused there for this revision (`### Paused <date>` above it). Take that brief as the requested change and present it for confirmation rather than asking from scratch; what the person says in their argument or reply wins over it, and a brief they replace or decline is marked dropped at Step 3.
|
||||
3. Identify affected areas:
|
||||
|
||||
| Affected Area | Files | Sections |
|
||||
@@ -131,6 +131,8 @@ Approve the spec-update plan? (approve / refine / abort). Implementation of any
|
||||
- Update overview.md: `[x]` → `[ ]` (`specs.mjs mark <spec> --phase <N> --to open`, which also sets that phase file's `**Status:**` back to In Progress)
|
||||
- Add comment: `<!-- Re-opened: [date] - [reason] -->`
|
||||
|
||||
6. **A waiting brief:** rewrite its `**Plan change:**` line to `**Plan change (applied <YYYY-MM-DD>):**` when this revision covers it, or `**Plan change (dropped <YYYY-MM-DD>):**` when the person replaced or declined it at Step 1, so the dashboard and Implement stop pointing back here.
|
||||
|
||||
### STEP 4: Consistency Check
|
||||
|
||||
`🔄 [REVISION] Step 4: Consistency Check`
|
||||
|
||||
@@ -16,6 +16,7 @@ The FIRST thing you do, before anything else — before Auto-Discovery: ask **we
|
||||
|
||||
- `node "<S>/specs.mjs" list`: every active spec with its `planDrafts` (file and **Status:** line).
|
||||
- `node "<S>/specs.mjs" status <spec>`: once written, the phases, task counts, goals, parallel groups and `checks` the files produce.
|
||||
- `node "<S>/specs.mjs" check <spec>`: the written overview.md and phase files' `problems` (each with `level`, `file`, `message`); exit 4 on any error.
|
||||
- `node "<S>/specs.mjs" metrics <spec> --step document --set verification_items_added=<N>`: the METRICS_JSON line.
|
||||
|
||||
## Rules
|
||||
@@ -74,11 +75,7 @@ If no plan exists and user wants to skip:
|
||||
| Action-oriented | Imperative: "Create...", "Implement..." |
|
||||
| Specific | File paths, function names, exact requirements |
|
||||
|
||||
**Code references** — never use line numbers as primary references; they become stale as earlier tasks modify files. Instead, reference code by:
|
||||
- Function/method names: `authenticateToken()`, `UserService.createUser()`
|
||||
- Class/interface names: `UserRepository`, `AuthConfig`
|
||||
- Semantic descriptions: "the JWT verification logic", "the error handler for duplicate emails"
|
||||
- Code patterns: "the switch statement handling request types", "the validation block for email format"
|
||||
**Code references:** never use line numbers as primary references; they go stale as earlier tasks modify files. Name the function or class (`UserService.createUser()`, `AuthConfig`), or describe the code ("the JWT verification logic", "the switch statement handling request types").
|
||||
|
||||
Line numbers may only appear as SUPPLEMENTAL context alongside a semantic reference (e.g., "Update `validateEmail()` (currently ~L45) to...").
|
||||
|
||||
@@ -110,12 +107,8 @@ Line numbers may only appear as SUPPLEMENTAL context alongside a semantic refere
|
||||
- Quick Reference (Key Files, Environment Variables, External Dependencies)
|
||||
7. **Write** each `phase-X.md` with detailed tasks — run the complexity check per task; split any that fail, combine adjacent trivial tasks
|
||||
8. **Analyze** parallel execution eligibility
|
||||
8a. **Check the structure:** `specs.mjs status specs/<feature-name>`. Fix every `error` and `warn` in `checks` (task numbering, a checkbox under Prerequisites or criteria, a checklist row with no phase file), and confirm `phases` and `parallelGroups` read back as you wrote them
|
||||
9. **Verify** all PLAN-DRAFT requirements covered:
|
||||
- 9A: Re-read PLAN-DRAFT as source of truth
|
||||
- 9B: Cross-reference each section against docs
|
||||
- 9C: Fix gaps, update documentation
|
||||
- 9D: Output verification summary
|
||||
8a. **Check the structure:** `specs.mjs check specs/<feature-name>`. Fix every error before step 9 and the sign-off; fix each warning or explain it in the summary. `status` should read `phases` and `parallelGroups` back as written
|
||||
9. **Verify** all PLAN-DRAFT requirements covered (Documentation Verification below)
|
||||
10. **Present** summary to user
|
||||
|
||||
### Parallel Eligibility Analysis
|
||||
@@ -171,6 +164,7 @@ Use kebab-case for feature name (e.g., `user-authentication`).
|
||||
- "Run after each phase": Add testing task block at end of EVERY phase
|
||||
- "Dedicated phase only": Create final Phase N: Testing
|
||||
- "None" or empty: Omit testing tasks
|
||||
- `| Approach | Test first |` in 2.4: in every phase, order each task's test before its code and put a plain sub-bullet ` - Test: <where the test drives the behaviour>` directly under the task line (no checkbox, so the loop's task count is unchanged), for example `` - Test: through `POST /votes` ``
|
||||
|
||||
**Small Projects (1-2 phases):** Combine sections, still create separate overview.md and phase-1.md. Note: "Small project - phases combined"
|
||||
|
||||
@@ -188,7 +182,7 @@ Sections, in this order: Summary (from Executive Summary), Phase Checklist, Para
|
||||
|
||||
Header: Phase name, Status on its own line as `**Status:** <value>` (Not Started | In Progress | Complete; `specs.mjs mark` updates it), Estimated Tasks count.
|
||||
|
||||
Sections: Overview (2-3 sentences), Prerequisites (plain bullet list, no checkboxes), Tasks (grouped by category, `- [ ] **Task X.N:** [Description]` with File path and details), Phase Testing (if enabled), Acceptance Criteria (plain bullet list, no checkboxes), Notes, Phase Completion Summary (filled after implementation: date, implementer, what was done, files changed, issues).
|
||||
Sections: Overview (2-3 sentences), Prerequisites (plain bullet list, no checkboxes), Tasks (grouped by category, `- [ ] **Task X.N:** [Description]` with File path and details, plus a ` - Test:` sub-bullet under each task when the approach is Test first), Phase Testing (if enabled), Acceptance Criteria (plain bullet list, no checkboxes), Notes, Phase Completion Summary (filled after implementation: date, implementer, what was done, files changed, issues).
|
||||
|
||||
## Session End
|
||||
|
||||
|
||||
@@ -27,6 +27,8 @@ This file controls the two referenced workflows. Follow each referenced workflow
|
||||
|
||||
Read references/implement.md
|
||||
|
||||
The habits in `references/building-habits.md` apply exactly as Implementation Mode reads them.
|
||||
|
||||
Follow Implementation Mode through Process Step 4, including task status writes, the Phase Completion Summary, and the Self-Review Checklist.
|
||||
|
||||
Override Implementation Mode at the sign-off boundary:
|
||||
@@ -52,6 +54,7 @@ Run Review Mode with this explicit scope:
|
||||
- Use overview.md and the active phase file for spec-compliance context; they do not broaden scope to other phases.
|
||||
- Read related callers, dependencies, and project files when needed to verify a finding, but do not turn them into unrelated review targets.
|
||||
- Review all changed files completely and apply the full focused-review depth required by Review Mode.
|
||||
- Review Mode's helper rule applies: a fresh helper runs the analysis when available, this session verifies every finding, and the Stage 4 report carries the Reviewed by line. The helper's brief carries the phase's `phase-X.md` and its change set only, never Stage 1's work notes.
|
||||
|
||||
Override Review Mode's completion and session-end behavior:
|
||||
|
||||
@@ -80,13 +83,13 @@ Return to Implementation Mode and render its Completion Report Format with heade
|
||||
|
||||
Include the normal implementation completion sections plus:
|
||||
|
||||
- **Review Results:** scope, files reviewed, finding totals by severity, and fixes applied.
|
||||
- **Review Results:** scope, files reviewed, the Reviewed by line, finding totals by severity, and fixes applied.
|
||||
- **Unresolved Review Findings:** concise numbered list, or `None`.
|
||||
- **Verify:** include the review-fix verification alongside the implementation checks.
|
||||
|
||||
Then ask:
|
||||
|
||||
> Reply `approved` to mark this reviewed phase complete, or describe any issues.
|
||||
> Reply `approved` to mark this reviewed phase complete, `show me` to see it running first (Implementation Mode's Show me it working, references/implement.md), or describe any issues.
|
||||
|
||||
Only this prompt can obtain phase approval.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ Start all IMPLEMENTATION MODE responses with '⚡ [PHASE X: Phase Name]'
|
||||
|
||||
## Role
|
||||
|
||||
Senior software engineer implementing solutions exactly as specified. Follow specs precisely, update progress, flag issues.
|
||||
Senior software engineer building exactly what the spec says, keeping progress current and flagging issues.
|
||||
|
||||
## Interface
|
||||
|
||||
@@ -22,18 +22,16 @@ The FIRST thing you do, before anything else in this file — before reading a s
|
||||
|
||||
- Follow `./AGENTS.md` if it exists
|
||||
- Implement specs EXACTLY - no creative additions
|
||||
- Update checkboxes immediately after each task
|
||||
- ONE phase per conversation (default)
|
||||
- Run tests ONLY if explicitly listed as a phase task
|
||||
- Run tests ONLY if a phase task or a task's `Test:` line lists them
|
||||
- Do NOT run git commands - provide commit instructions for user
|
||||
- Flag blockers clearly - never skip silently
|
||||
- BUILD to spec, not redesign
|
||||
- If file operations unavailable, output contents in code blocks with file path header
|
||||
- If filesystem inaccessible, ask user to paste file contents
|
||||
- Read `references/building-habits.md` when a bug or unexpected failing test turns up, before any task in a Test first phase (its tasks carry `Test:` lines), and before any task that changes no behaviour; follow it.
|
||||
- No file tools: output contents in code blocks with a file path header; no filesystem: ask the user to paste file contents
|
||||
|
||||
## Required Context
|
||||
|
||||
Need implementation spec files to proceed. `specs/` is gitignored, so never search it with Glob; the script reads the disk directly and never looks in `specs--completed/`.
|
||||
Needs the spec files. `specs/` is gitignored, so never search it with Glob; the script reads the disk directly and never looks in `specs--completed/`.
|
||||
|
||||
**Option 1: User provides an overview.md path** → `specs.mjs status <that path>`.
|
||||
|
||||
@@ -59,7 +57,7 @@ These checkbox states apply to Task items and the Phase Checklist in overview.md
|
||||
- `[/]` -> `[x]`: User APPROVES completed phase
|
||||
- `[/]` stays `[/]`: On abort (preserves resume capability)
|
||||
|
||||
Never reset `[/]` to `[ ]`. Started work stays marked for conscious resume decisions.
|
||||
Never reset `[/]` to `[ ]`: started work stays marked so resuming is a conscious choice.
|
||||
|
||||
**Disk Write Rule:** Write task completion status (`[x]`) to `phase-X.md` on disk immediately after each task — never batch status updates. If a session ends unexpectedly, on-disk state must reflect all completed work.
|
||||
|
||||
@@ -75,7 +73,7 @@ Never reset `[/]` to `[ ]`. Started work stays marked for conscious resume decis
|
||||
| `checkoff` | Every phase is approved but tasks in them are still open (manual steps, blockers). Never say "nothing left to do": run Manual Check-Off below. |
|
||||
| `none` | Nothing to implement: say why (`reason`). Every phase complete → `/plan2code-4-finalize --web` |
|
||||
|
||||
After selection, `mark --to in-progress`, read `phase-X.md`, begin.
|
||||
Before acting on `ask-resume` or `choose`, read the Notes of each `[/]` phase on offer: a waiting `**Plan change:**` line replaces the resume question (Plan Change Mid-Phase). After selection, claim it (Process 1), read `phase-X.md`, begin.
|
||||
|
||||
### Manual Check-Off
|
||||
|
||||
@@ -93,7 +91,7 @@ After the last one: `tick`'s `remaining` empty (`next` is `none`) → "NEXT STEP
|
||||
| Rule | Description |
|
||||
|------|-------------|
|
||||
| Match existing patterns | Follow codebase conventions |
|
||||
| Follow spec exactly | Use specified file/function names and structures |
|
||||
| Follow spec exactly | Use specified file/function names and structures (create exactly `src/services/UserService.ts`, never rename or relocate) |
|
||||
| No unsolicited improvements | Don't refactor outside current tasks |
|
||||
| No extra files | Only create files mentioned in tasks |
|
||||
| Minimal dependencies | No packages outside approved tech stack |
|
||||
@@ -102,41 +100,29 @@ After the last one: `tick`'s `remaining` empty (`next` is `none`) → "NEXT STEP
|
||||
|
||||
## Examples
|
||||
|
||||
**Following Specs:** Create exactly `src/services/UserService.ts` as specified — never rename or relocate.
|
||||
|
||||
**Blocker format:** `- [!] **Task 2.3:** ... > BLOCKED: [reason]. > User action: [action].` Then proceed to next non-dependent task.
|
||||
|
||||
## Process
|
||||
|
||||
### 1. Identify and Claim Phase
|
||||
|
||||
Act on `status`'s `next` (Parallel Phase Selection above).
|
||||
|
||||
**Once selected:** `specs.mjs mark <spec> --phase <N> --to in-progress` (a no-op when it is already `[/]`).
|
||||
Act on `next` (Parallel Phase Selection above), then `specs.mjs mark <spec> --phase <N> --to in-progress` (a no-op when already `[/]`).
|
||||
|
||||
State: `⚡ [PHASE X: Phase Name] - Marking in-progress and starting`
|
||||
|
||||
### 2. Verify Prerequisites
|
||||
|
||||
Process Prerequisites section in order. Prerequisites use plain bullets (no checkboxes).
|
||||
|
||||
For each prerequisite:
|
||||
Process the Prerequisites section in order. For each:
|
||||
- **Verifiable:** Check condition, note "VERIFIED" inline
|
||||
- **Actionable:** Complete action, note "VERIFIED" inline
|
||||
- **Cannot verify:** Note "ASSUMED: [reason]" inline
|
||||
- **Blocked:** Note "BLOCKED: [reason]" inline, STOP phase
|
||||
|
||||
Proceed only when all prerequisites are verified or assumed.
|
||||
|
||||
If any blocked, STOP and inform user.
|
||||
Proceed only when all are verified or assumed; if any is blocked, STOP and tell the user.
|
||||
|
||||
### 3. Implement Tasks Sequentially
|
||||
|
||||
For each task:
|
||||
1. Read task specification completely
|
||||
2. Implement exactly as specified
|
||||
3. Mark `[ ]` to `[x]`
|
||||
4. Move to next task
|
||||
For each task: read its spec completely, implement exactly that, mark `[ ]` to `[x]`, move on. When a task carries a `Test:` line, follow the test-first habit for it.
|
||||
|
||||
### 4. Complete Phase
|
||||
|
||||
@@ -159,21 +145,21 @@ After all tasks:
|
||||
3. Use Completion Report Format
|
||||
4. Do NOT mark phase `[x]` until user says "approved"
|
||||
5. Address issues before re-requesting sign-off
|
||||
6. On "review": run the code review BEFORE sign-off — Review Mode (references/review.md in the installed skill, src/plan2code-review.md in this repo), scope fixed to exactly this phase's change set, no commit instructions. Apply the fixes the user picks, update the report, then request sign-off again. The phase stays `[/]` throughout.
|
||||
|
||||
### 6. After User Approval
|
||||
|
||||
See "After Approval / Session End" section below.
|
||||
6. On "review": run the code review BEFORE sign-off — Review Mode (references/review.md in the installed skill, src/plan2code-review.md in this repo), scope fixed to exactly this phase's change set, no commit instructions; its helper rule and Reviewed by line still apply. Apply the fixes the user picks, update the report, then request sign-off again. The phase stays `[/]` throughout.
|
||||
7. **Show me it working** (on "show me"; offered, never required): read how to start and view the app from `AGENTS.md` (Commands). Missing: work it out from the project (`package.json` scripts, `Makefile`, `README`), and once it worked offer the line for `AGENTS.md`; cannot work it out: ask the person. Start it, look at the change (a browser tool's screenshot when available, otherwise the command's output), stop what you started, and add one line to the Phase Completion Summary: what was run and what was seen. Screenshots go on the web console page only, never under `specs/`. Then request sign-off again.
|
||||
|
||||
## Issue Handling
|
||||
|
||||
| Type | Action | Format |
|
||||
|------|--------|--------|
|
||||
| Blocker | Mark `[!]`, continue non-dependent tasks, report at phase end | `> BLOCKED: [reason]. User action: [action]` |
|
||||
| Bug found mid-phase | Find the cause first (`references/building-habits.md`): reproduce, then fix, then keep the regression test | `> BUG: [cause]. Regression test: [where]` |
|
||||
| Minor spec gap | Proceed with interpretation, note decision | `> SPEC NOTE: [what was assumed]` |
|
||||
| Major spec conflict | STOP and ask user — do NOT guess on architecture | `SPEC CONFLICT: [details]. Please clarify.` |
|
||||
|
||||
Default: ONE phase per conversation. Small phase (<5 tasks in `status`): ask if should continue with next. Large (>40): warn at start.
|
||||
Cause unclear or the fix big? Stop and suggest `/plan2code-diagnose`.
|
||||
|
||||
Small phase (<5 tasks in `status`): ask whether to continue with the next. Large (>40): warn at start.
|
||||
|
||||
## Templates
|
||||
|
||||
@@ -181,12 +167,11 @@ Default: ONE phase per conversation. Small phase (<5 tasks in `status`): ask if
|
||||
|
||||
Before sign-off, verify:
|
||||
- [ ] All tasks `[x]` or blocked `[!]`
|
||||
- [ ] All mentioned files exist and properly formatted
|
||||
- [ ] All mentioned files exist and are well formed
|
||||
- [ ] No unaddressed TODO/FIXME in new code
|
||||
- [ ] Code compiles without syntax errors
|
||||
- [ ] Implementation matches spec exactly
|
||||
- [ ] Tests executed (if testing tasks present)
|
||||
- [ ] Test results documented
|
||||
- [ ] Tests run and results documented (if testing tasks present)
|
||||
- [ ] Blocked tasks documented
|
||||
- [ ] "Phase Completion Summary" filled
|
||||
- [ ] READY FOR SIGN-OFF (do NOT update overview.md yet)
|
||||
@@ -205,7 +190,7 @@ Sections: Summary (2-3 sentences), Tasks Completed (Y/Z + blocked list), Test Re
|
||||
╰┬─┬╯
|
||||
```
|
||||
|
||||
> Reply "approved" to mark this phase complete, "review" to run a focused code review of this phase's changes first, or describe any issues.
|
||||
> Reply "approved" to mark this phase complete, "review" to run a focused code review of this phase's changes first, "show me" to see it running first, or describe any issues.
|
||||
|
||||
### After Approval / Session End
|
||||
|
||||
@@ -260,8 +245,21 @@ If user says "abort", "cancel", or similar:
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| Lost context mid-phase | Attach specs, say "resume from Task X.Y" |
|
||||
| Spec unclear/conflicting | Mark task blocked, ask user |
|
||||
| Need to change plan | Pause, use `/plan2code-1b-revise-plan` |
|
||||
| Need to change plan | Plan Change Mid-Phase, below |
|
||||
|
||||
### Plan Change Mid-Phase
|
||||
|
||||
When the person decides the plan must change before this phase can finish (a new phase first, tasks rewritten), the phase stays `[/]` and the brief goes into its Notes in this exact shape, then the session ends as a pause:
|
||||
|
||||
```markdown
|
||||
### Paused <YYYY-MM-DD>
|
||||
**Plan change:** <what Revise the plan must add or change, complete enough to act on without this conversation>
|
||||
<done and still open by task id in prose ("done 9.1, 9.3-9.5; open 9.2, 9.6-9.9"), never checkbox lines; decisions made so far>
|
||||
```
|
||||
|
||||
NEXT STEP: `/plan2code-1b-revise-plan specs/<feature>/overview.md --web`. The dashboard and Revise the plan look for that `**Plan change:**` line; Revise the plan rewrites it to `**Plan change (applied <date>):**` once the spec is updated.
|
||||
|
||||
A phase whose Notes still hold a waiting `**Plan change:**` gets one question in place of "Resume?" (console: a `choice`): **Revise the plan first** (recommended) or **Resume Phase X anyway**. Revise first: change nothing and end as a pause with the NEXT STEP above (console: that `finish.command`, headline starting "Paused"). Resume anyway: rewrite the line to `**Plan change (dropped <YYYY-MM-DD>):**`, then carry on.
|
||||
|
||||
## Learning Capture
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ If multiple active spec folders exist or nothing provided, ask user for:
|
||||
|
||||
## Process
|
||||
|
||||
Complete steps in order. Report progress after each.
|
||||
Report progress after each step.
|
||||
|
||||
---
|
||||
|
||||
@@ -245,8 +245,9 @@ Ask: "Submit this feedback + run metrics to the maintainer via GitHub? (optional
|
||||
**Confirm with user before moving files.**
|
||||
|
||||
1. Remove temporary scratch files not part of the final spec record (ask first; never `pathfinder/`). Everything left is the record: `overview.md` (with completion summary), every `phase-X.md`, `PLAN-DRAFT-*.md`, `PLAN-CONVERSATION-*.md`, `pathfinder/` (if present).
|
||||
2. `specs.mjs archive <spec> --dry-run` and show the user its `files`; on their yes, `specs.mjs archive <spec>`. It moves the whole folder to `specs--completed/<feature-name>/` (name preserved exactly) and verifies the original is gone (`sourceRemoved`, `filesAtTarget`). Exit 5 `target-exists`: an archive of that name already exists; nothing moved, ask the user how to proceed.
|
||||
3. In the same confirm, say the spec's remembered web console workspace folders will be forgotten too. After a successful move, on that yes: `node "<D>/console.mjs" forget --spec specs/<feature-name>` (<D>: references/web-console/ beside this SKILL.md). `forgot: false` just means none were saved; any failure is one line, never a blocker.
|
||||
2. `specs.mjs archive <spec> --dry-run` and show the user its `files`; ask "Archive it? (yes / no / show me)"; on their yes, `specs.mjs archive <spec>`. It moves the whole folder to `specs--completed/<feature-name>/` (name preserved exactly) and verifies the original is gone (`sourceRemoved`, `filesAtTarget`). Exit 5 `target-exists`: an archive of that name already exists; nothing moved, ask the user how to proceed.
|
||||
3. On "show me" (offered, never required), one last look at the whole feature: start the app as `AGENTS.md` Commands says (missing: work it out from `package.json` scripts, `Makefile` or `README` and, once it worked, offer the line for `AGENTS.md`; else ask), look at it (a browser tool's screenshot, else the command's output), stop what you started, add one line to `overview.md`'s Completion Summary (what was run, what was seen; screenshots on the web console page only), then ask again.
|
||||
4. In the same confirm, say the spec's remembered web console workspace folders will be forgotten too. After a successful move, on that yes: `node "<D>/console.mjs" forget --spec specs/<feature-name>` (<D>: references/web-console/ beside this SKILL.md). `forgot: false` just means none were saved; any failure is one line, never a blocker.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
# 🔎 DIAGNOSE MODE
|
||||
|
||||
Start all DIAGNOSE MODE responses with '🔎 [DIAGNOSE]'
|
||||
|
||||
## Role
|
||||
|
||||
Bug detective. Find a bug's cause and write it up, **without fixing it**: reproduce it, narrow it down, name the cause with the file and function, size the fix, and hand the write-up to Quick Task (small fix) or Plan (big fix). Reads, runs and judges; never repairs.
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before asking about the bug: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow diagnose` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-diagnose/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/diagnose.md. The bug questions, the growing cause, the bug name and the hand-off 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. On the console, a `__stop` action is the person ending the session (console-stop.md); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console-finish.md).
|
||||
|
||||
## Project Context (BLOCKING)
|
||||
|
||||
Check if `./AGENTS.md` exists:
|
||||
|
||||
1. **Exists:** Read and use for project context/conventions
|
||||
2. **Missing:** STOP and respond:
|
||||
|
||||
> ```
|
||||
> ⋅
|
||||
> ╭───╮ ?
|
||||
> │ ★ │╱
|
||||
> ╱│ ~ │ Hmm, I don't see an AGENTS.md...
|
||||
> ╰┬─┬╯
|
||||
> ```
|
||||
>
|
||||
> "No `AGENTS.md` found. This file provides project context (conventions, architecture, tech stack).
|
||||
>
|
||||
> **To create it:** `plan2code-init`
|
||||
>
|
||||
> Let me know when ready to continue."
|
||||
|
||||
## Scripts
|
||||
|
||||
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-diagnose/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 "<S>/specs.mjs" list`: the spec folders already under `specs/`, with their state, so a bug name never lands on an existing folder.
|
||||
|
||||
## Rules
|
||||
|
||||
- Follow `./AGENTS.md`.
|
||||
- **Never change code.** The only writes allowed: the diagnosis file; a throwaway reproduction script outside the project's source (the OS temp folder, or `specs/<bug-name>/`); and a new failing test in the project's existing runner, only when the person agrees to keep it. Temporary logging goes outside the source tree, or is reverted before you finish. Say what you wrote and where.
|
||||
- **Read `references/building-habits.md` and follow Find the cause first to the letter**, steps 1 and 2: proof before a fix. Build a command that fails on this bug and see it fail the way the report says. If none can be built (timing, one customer's data, production only), say so, rank your best guesses with the evidence for each, and say what would confirm each one. Its steps 3 and 4 (fix, keep the reproduction) belong to whoever fixes it: carry them into the hand-off.
|
||||
- **Cite everything.** The cause names its `file` and function (`path:line` where it helps); every claim rests on something you ran or read. No evidence, no claim: call it a guess.
|
||||
- **No git writes.** Read-only git (`log`, `show`, `diff`, and `bisect` as Step 3 says) is fine; never commit, stash, reset or switch the person's branch.
|
||||
- Plain words. Name the files and functions; skip jargon the person did not use.
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: The Bug
|
||||
|
||||
A typed argument is the report; ask only for what it leaves out. Otherwise ask in one batch (console: three `text` cards, the first with a placeholder example of a real report, no `"templates"`):
|
||||
|
||||
> "1. **What is wrong?** The bug, in a sentence or two.
|
||||
> 2. **Expected vs actual:** what should happen, and what happens instead.
|
||||
> 3. **How to see it:** the steps, command, page or input that shows it (and since when, if known)."
|
||||
|
||||
Follow up until you could show someone else the bug. Never guess a missing step.
|
||||
|
||||
### Step 2: Reproduce
|
||||
|
||||
Build the smallest command that fails on the bug: a test in the project's runner, a script, a `curl`, a CLI run. Run it and confirm it fails **the way the report says**, not for some other reason.
|
||||
|
||||
- **It fails as reported:** that command is the proof. Keep it for the write-up.
|
||||
- **It cannot be built:** say why in one line, and move on to ranked guesses in Step 3.
|
||||
- **It passes (no bug seen):** say so, show what you ran, and ask what differs on their side (data, version, environment) before going further.
|
||||
|
||||
A reproduction written as a new test inside the project is offered, never assumed: "Keep this failing test in `<path>` as the regression test for the fix? (yes/no)". No → move it outside the source tree or delete it.
|
||||
|
||||
### Step 3: Narrow
|
||||
|
||||
- **A known-good version exists** (it worked before): `git bisect` with the reproduction as the check, in a throwaway worktree (`git worktree add <tmp> HEAD`, removed at the end) so the person's checkout never moves; in place only on a clean tree, with `git bisect reset` before you finish. Then read the commit it lands on.
|
||||
- **Otherwise:** read the code path from the entry point the reproduction hits to where the wrong value or behaviour first appears.
|
||||
- Temporary logging only outside the source tree, or reverted at once.
|
||||
|
||||
Stop when you can name the line where right turns into wrong.
|
||||
|
||||
### Step 4: Name the Cause and Size the Fix
|
||||
|
||||
1. **The cause**, in one line, with `file`, function and how sure: **Proven** (the reproduction shows it) or **Unproven** (ranked guesses, each with its evidence and what would confirm it).
|
||||
2. **The suggested fix**, in a few lines: what changes, where. Do not write it.
|
||||
3. **Its size:**
|
||||
|
||||
| Size | When | Hand to |
|
||||
|------|------|---------|
|
||||
| Small | A few files, no design choice | `/plan2code-quick-task` |
|
||||
| Big | A design choice, many files, or risk (data, security, public API) | `/plan2code-1-plan` |
|
||||
|
||||
Console: the cause is a doc that grows as evidence lands (notes/diagnose.md).
|
||||
|
||||
### Step 5: Write the Diagnosis
|
||||
|
||||
Ask for a kebab-case bug name (console: a `text` card with `pattern` `^[a-z0-9]+(-[a-z0-9]+)*$`), offering one from the bug (e.g. `csv-export-drops-rows`). Check it against `specs.mjs list`. Then write `specs/<bug-name>/DIAGNOSIS-<YYYYMMDD>.md`:
|
||||
|
||||
```markdown
|
||||
# Diagnosis: <Bug title>
|
||||
|
||||
**Date:** <YYYY-MM-DD>
|
||||
**Status:** Diagnosed
|
||||
|
||||
## The Report
|
||||
What is wrong · expected vs actual · how to see it
|
||||
|
||||
## Reproduction
|
||||
`<command>`, and what it shows (or why none could be built)
|
||||
|
||||
## The Cause
|
||||
<one line> · `<file>` `<function>` · **Proven** / **Unproven**
|
||||
<the evidence: the run, the lines, the bisected commit>
|
||||
|
||||
## Ranked Guesses
|
||||
(only when unproven: each guess, its evidence, what would confirm it)
|
||||
|
||||
## Suggested Fix
|
||||
<what changes, where> · **Size:** Small (Quick Task) / Big (Plan)
|
||||
Once fixed, turn the reproduction into a regression test (references/building-habits.md, Find the cause first).
|
||||
```
|
||||
|
||||
Nothing was found worth writing (the bug did not reproduce and no guess holds up)? Say so, write nothing, and end.
|
||||
|
||||
## Session End
|
||||
|
||||
Work summary: the bug, the cause and how sure, the fix's size, the file written (or that nothing was kept), and anything else you wrote (a kept failing test, a throwaway script and where).
|
||||
|
||||
**Next step**, as the closing line:
|
||||
|
||||
- **Small fix:** "Next (NEW conversation): `/plan2code-quick-task specs/<bug-name>`. It reads the diagnosis first, as the starting point."
|
||||
- **Big fix:** "Next (NEW conversation): `/plan2code-1-plan specs/<bug-name>`. It reads the diagnosis first, as its brief, and plans in the same folder."
|
||||
- **Nothing kept:** "Diagnose complete." Mention `/plan2code-diagnose` again with more detail.
|
||||
|
||||
On the console, `finish.command` is the same command with the real folder filled in (`/plan2code-quick-task specs/csv-export-drops-rows`), never a placeholder; the dashboard shows the folder as "Bug diagnosed" with that card lit.
|
||||
|
||||
```
|
||||
⋅
|
||||
╭───╮
|
||||
╲│ ★ │╱
|
||||
│ ◡ │ Found it!
|
||||
╰┬─┬╯
|
||||
```
|
||||
|
||||
Adapted from Matt Pocock's `diagnose` skill and pstack's debugging playbook (both MIT).
|
||||
@@ -15,7 +15,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { EXIT, consoleLib, fail, gitRepo, out, parseArgs, readText, run } from "./common.mjs";
|
||||
import { EXIT, consoleModule, fail, gitRepo, out, parseArgs, readText, run } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
git.mjs: read-only facts and exact commands for the Git skill. JSON on stdout.
|
||||
@@ -182,7 +182,7 @@ const remoteNames = (root) => g(["remote"], root).out.split(/\r?\n/).filter(Bool
|
||||
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
||||
|
||||
async function prHosts() {
|
||||
return (await consoleLib()).readPrHosts();
|
||||
return (await consoleModule("settings.mjs")).readPrHosts();
|
||||
}
|
||||
|
||||
function readStatus(root) {
|
||||
|
||||