mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
Add Stop with a handoff, handoff chips on the dashboard, and a one-step delete for fixed bugs
AI Assisted
This commit is contained in:
1 parent
33a0dbd34a
commit
36843e4bc9
34 files changed
+1926
-267
No files matched your search
@@ -155,7 +155,6 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
|
||||
| `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 |
|
||||
@@ -181,7 +180,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
|
||||
| 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`, `git-board-view.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 |
|
||||
@@ -195,6 +194,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `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 |
|
||||
| `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 |
|
||||
| `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. 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 |
|
||||
@@ -214,13 +214,13 @@ Key design points:
|
||||
- **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.
|
||||
- **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 `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`, `__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 `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, 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.
|
||||
- **`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`, `install.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 }], 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`, `install.json`, `models.json`, `handoffs`) 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.
|
||||
@@ -255,6 +255,8 @@ Key design points:
|
||||
- **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.
|
||||
- **`__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.
|
||||
- **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`).
|
||||
- **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 `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.
|
||||
- **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".
|
||||
|
||||
@@ -138,7 +138,7 @@ See the `skills/` build-artifact gotcha in [Code Style & Gotchas](./AGENTS-code-
|
||||
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, every one of these (the tests fail on a miss, but not all at once):
|
||||
- `src/plan2code.md`: the skill/workflow table and "What each skill reads and writes" (checked by `scripts/check-skill-table.mjs`: every backticked token must appear in the skill's prompt).
|
||||
- `src/web-console/public/answers.js`: `WORKFLOW_LABEL`, `CONSOLE_WORKFLOWS`, `resumeCommand()`, a `SKILL_CATALOG` card (utilities go in group `"extra"` before Changelog: tests pin Changelog then Git last), `START_POSES` and `cardAvailability()`.
|
||||
- `src/web-console/public/answers.js`: `WORKFLOW_LABEL`, `CONSOLE_WORKFLOWS`, `resumeCommand()`, a `SKILL_CATALOG` card (utilities go in group `"extra"` before Changelog: tests pin Changelog, Git, then Handoff last), `START_POSES` and `cardAvailability()`.
|
||||
- `src/web-console/public/meter.js`: `WEIGHTS`, `LAUNCH_COUNTED` (if its launch scores), `WORKFLOW_NAMES`, `LAUNCH_LABELS`, `RUN_LABELS`; and in `src/web-console/console-meter.md` the event list, plus the sentence near its top naming the skills that score on launch (when it joins `LAUNCH_COUNTED`).
|
||||
- `src/web-console/public/index.html`: a start-pose `<svg class="pose pose-<workflow>" data-pose="<workflow>">` in `<template id="start-poses">` (pose CSS in `app.css`), and a line in Help's About list.
|
||||
- `src/web-console/notes/<workflow>.md`, named in the skill's Interface line.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+34
-5
@@ -199,18 +199,34 @@ 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. **Diagnose a bug** sits beside it, also always
|
||||
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. Click a card and Planny
|
||||
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,
|
||||
then about five seconds of him powering on to a boot-up sound (arms lifting
|
||||
@@ -465,6 +481,15 @@ 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.
|
||||
|
||||
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
|
||||
@@ -681,6 +706,7 @@ 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/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 |
|
||||
@@ -700,7 +726,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.
|
||||
@@ -711,7 +738,8 @@ 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`, `install.json` (what you installed, which
|
||||
`plan2code update` reads) and `models.json`. It also lists each
|
||||
`plan2code update` reads), `models.json` and `handoffs/` (old handoffs go by
|
||||
age, above). 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
|
||||
@@ -750,7 +778,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, and the workspace. 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.
|
||||
|
||||
@@ -763,6 +791,7 @@ 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`. |
|
||||
|
||||
@@ -42,7 +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 (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`), 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 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.
|
||||
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
|
||||
|
||||
## Skill Scripts
|
||||
@@ -102,3 +102,4 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
- 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 you move a dashboard card, update every test that pins `SKILL_CATALOG` order (`scripts/test-web-console-source.mjs` and `scripts/test-web-console-git.mjs`): the Handoff move once updated only one and left `npm test` red.
|
||||
@@ -16,6 +16,8 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **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
|
||||
|
||||
@@ -23,10 +25,18 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **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.
|
||||
|
||||
### 🗑️ 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
|
||||
|
||||
|
||||
@@ -192,7 +192,7 @@ The dashboard's cards, and when each one lights up for the spec you pick:
|
||||
| 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 (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 |
|
||||
@@ -362,7 +362,7 @@ 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 |
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
"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-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-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-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.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-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-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"husky": "^9.0.0"
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,503 @@
|
||||
// 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);
|
||||
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 }));
|
||||
@@ -50,7 +50,9 @@ import {
|
||||
launchTarget,
|
||||
deleteAction,
|
||||
deleteReply,
|
||||
chipDetail,
|
||||
deleteSummary,
|
||||
FIXED_REASON,
|
||||
isDeletableSpecDir,
|
||||
MAX_NOTE_IMAGES,
|
||||
noteAction,
|
||||
@@ -67,6 +69,14 @@ import {
|
||||
SPEC_STATE_LABELS,
|
||||
STALE_MS,
|
||||
STOP_REPLY,
|
||||
STOP_HANDOFF_REPLY,
|
||||
stopAction,
|
||||
pickupAction,
|
||||
pickupReply,
|
||||
deleteHandoffAction,
|
||||
deleteHandoffReply,
|
||||
handoffCopyText,
|
||||
handoffAge,
|
||||
verdictLabel,
|
||||
verdictText,
|
||||
lastOpenCard,
|
||||
@@ -580,6 +590,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) => {
|
||||
@@ -775,6 +821,18 @@ test("a delete is a session action naming the folder, and its reply says it is f
|
||||
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 {
|
||||
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
} from "../src/web-console/lib.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
HANDOFFS_DIR,
|
||||
HOME,
|
||||
ENV,
|
||||
cookieFor,
|
||||
@@ -434,6 +435,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 +452,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");
|
||||
@@ -659,6 +664,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);
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
START_POSES,
|
||||
startPose,
|
||||
STOP_REPLY,
|
||||
STOP_HANDOFF_REPLY,
|
||||
threadText,
|
||||
threadWho,
|
||||
turnGate,
|
||||
@@ -388,6 +389,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.
|
||||
@@ -479,11 +498,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
|
||||
|
||||
@@ -248,6 +248,107 @@ 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 app = web("app.js");
|
||||
const css = web("app.css");
|
||||
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 open = app.slice(app.indexOf("function openStopConfirm()"), app.indexOf("async function stopSession("));
|
||||
assert.ok(open.includes("stop-handoff") && open.includes("isDashboard()"), "openStopConfirm hides the handoff on the dashboard");
|
||||
assert.ok(app.includes("stopSession(true)") && app.includes("STOP_HANDOFF_REPLY") && app.includes("stopAction"), "app.js wires the handoff stop");
|
||||
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.
|
||||
test("dashboard handoffs: dashed chips, a preview with four buttons, and the cards give way", () => {
|
||||
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
|
||||
const app = web("app.js");
|
||||
const css = web("app.css");
|
||||
const html = web("index.html");
|
||||
const fn = (name, next) => app.slice(app.indexOf(`function ${name}(`), app.indexOf(next, app.indexOf(`function ${name}(`)));
|
||||
|
||||
const picker = fn("renderSpecPicker", "\nfunction ");
|
||||
assert.ok(picker.includes("is-handoff") && picker.includes('"Handoff"'), "renderSpecPicker builds handoff chips");
|
||||
assert.ok(picker.includes('"handoff:"'), "a handoff is picked as handoff:<id>");
|
||||
const dash = fn("renderDashboard", "\n/* -----");
|
||||
assert.ok(dash.includes("handoffList()"), "renderDashboard shows the picker for handoffs alone");
|
||||
const early = dash.indexOf("renderHandoffPreview(");
|
||||
assert.ok(early > 0 && early < dash.indexOf("hideUnavailableToggle()"), "the preview returns before the toggle and the card groups");
|
||||
assert.match(app, /const selHandoff = \(\) =>/);
|
||||
assert.match(app, /startsWith\("handoff:"\)/);
|
||||
|
||||
const preview = fn("renderHandoffPreview", "\nasync function ");
|
||||
for (const label of ["Pick it up here", "Read it all", "Copy for a new conversation", "Delete"]) {
|
||||
assert.ok(preview.includes(`"${label}"`), `the preview names ${label}`);
|
||||
}
|
||||
assert.ok(app.includes("pickupAction(") && app.includes('"/submit"'), "Pick it up here posts a __pickup to /submit");
|
||||
assert.ok(app.includes('"/handoff?id="'), "Read it all fetches /handoff?id=");
|
||||
assert.ok(app.includes("handoffCopyText("), "Copy puts the ready prompt on the clipboard");
|
||||
assert.ok(app.includes("deleteHandoffAction(") && app.includes("function openHandoffDelete("), "Delete reuses the confirm dialog");
|
||||
|
||||
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`);
|
||||
}
|
||||
const app = doc("public/app.js");
|
||||
assert.match(app, /v\.id === "approve" \? " is-approve"/, "an unpicked approve verdict gets is-approve");
|
||||
assert.match(doc("public/app.css"), /\.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.
|
||||
test("bug fixed delete: a promoted Delete on the chip and a one-step confirm", () => {
|
||||
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
|
||||
const app = web("app.js");
|
||||
const fn = (name, next) => app.slice(app.indexOf(`function ${name}(`), app.indexOf(next, app.indexOf(`function ${name}(`)));
|
||||
|
||||
const picker = fn("renderSpecPicker", "\nfunction ");
|
||||
assert.ok(picker.includes('"spec-chip-del-label"') && picker.includes('"Delete"'), "renderSpecPicker builds a Delete button for a fixed bug");
|
||||
assert.ok(picker.includes("chipDetail("), "the chip's detail line comes from chipDetail");
|
||||
assert.doesNotMatch(picker, /spec\.detail\b/, "never the scan's detail directly");
|
||||
|
||||
const css = web("app.css");
|
||||
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 step = fn("deleteStep", "\nasync function ");
|
||||
const fixedAt = step.indexOf('state === "fixed"');
|
||||
const revealAt = step.indexOf('$("delete-confirm").hidden = false');
|
||||
assert.ok(fixedAt > 0 && revealAt > 0 && fixedAt < revealAt, "deleteStep sends a fixed bug's delete before it would reveal the name step");
|
||||
const open = fn("openDeleteConfirm", "\nfunction ");
|
||||
assert.ok(open.includes('state === "fixed"') && open.includes("so this only clears the write-up"), "openDeleteConfirm sets up one step and the fixed warning");
|
||||
|
||||
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");
|
||||
@@ -280,12 +381,13 @@ test("update banner: built only on the dashboard, dismissed per session, and Hel
|
||||
assert.match(help[1], /releasesLink\(/, "the help version is a Releases link");
|
||||
});
|
||||
|
||||
// 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", () => {
|
||||
// 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", () => {
|
||||
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");
|
||||
assert.deepEqual(skills.slice(-3), ["plan2code-changelog", "plan2code-git", "plan2code-handoff"]);
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-changelog");
|
||||
assert.equal(entry.workflow, "changelog");
|
||||
assert.equal(entry.command, "/plan2code-changelog");
|
||||
@@ -315,6 +417,22 @@ 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");
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
|
||||
// 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) {
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
WEB_CONSOLE_DIR,
|
||||
consoleDoc,
|
||||
consoleDocFiles,
|
||||
HANDOFFS_DIR,
|
||||
} from "./web-console-test-helpers.mjs";
|
||||
|
||||
const choice = (id, extra = {}) => ({
|
||||
@@ -321,6 +322,62 @@ test("settle and a defaulted reply id go through post end to end", async () => {
|
||||
|
||||
/* ------------------------------------------------------------ session hops */
|
||||
|
||||
// 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 and Commit it now each come with their resume command", async () => {
|
||||
const s = consoleSession(["--workflow", "dashboard"]);
|
||||
try {
|
||||
@@ -366,6 +423,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]);
|
||||
}
|
||||
|
||||
@@ -28,6 +28,9 @@ 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");
|
||||
// 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 +54,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_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 }));
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
// handoff-path.mjs: where the handoff document goes, and whether git would pick it up.
|
||||
//
|
||||
// The handoff skill names its file <dir>/<YYYY-MM-DD-HHmm>-handoff.md, takes the
|
||||
// timestamp from the clock rather than a guess, creates the folder, and checks
|
||||
// whether the file would be tracked by git (is this a repo, is the path
|
||||
// ignored). That is a fixed sequence with one right answer per machine, so it
|
||||
// lives here. Whether to add an ignore line is the user's call.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { EXIT, fail, out, parseArgs, run, isoDate, now } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
handoff-path.mjs: pick the handoff file path and check it against git. JSON on stdout.
|
||||
|
||||
node handoff-path.mjs [--dir temp|<path>] [--root <dir>] [--dry-run]
|
||||
|
||||
--dir temp (the default): the OS temporary directory. Anything else is a
|
||||
folder, relative to --root (default: the current directory), e.g.
|
||||
handoffs (a project folder literally named temp: ./temp).
|
||||
Created if missing (not with --dry-run).
|
||||
|
||||
Prints { path, dir, created, timestamp, git: { repo, inRepo, ignored,
|
||||
ignoreLine }, warning? }. The file name is <YYYY-MM-DD-HHmm>-handoff.md; if one
|
||||
already exists for this minute, -2, -3... is appended so earlier handoffs are
|
||||
never overwritten. git.ignored is null when the file is outside a repo (nothing
|
||||
to ignore); false means it would show up in git status, and then git.ignoreLine
|
||||
is the .gitignore line to offer and the top-level warning says so.
|
||||
|
||||
Exit: 0 ok · 2 bad arguments · 5 the folder cannot be created, or --dir names
|
||||
an existing file (not-a-folder).
|
||||
`;
|
||||
|
||||
function git(cwd, args) {
|
||||
try {
|
||||
return { ok: true, out: execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim() };
|
||||
} catch (err) {
|
||||
return { ok: false, status: err.status };
|
||||
}
|
||||
}
|
||||
|
||||
run(USAGE, async (argv) => {
|
||||
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["dir", "root"] });
|
||||
const root = path.resolve(args.root || ".");
|
||||
const choice = args.dir || "temp";
|
||||
const dir = choice === "temp" ? os.tmpdir() : path.resolve(root, choice);
|
||||
let created = false;
|
||||
if (fs.existsSync(dir) && !fs.statSync(dir).isDirectory()) {
|
||||
fail(EXIT.REFUSED, "not-a-folder", `${dir} exists and is a file, not a folder.`, "Pass a folder for --dir (a new one is created), or use --dir temp.");
|
||||
}
|
||||
if (!fs.existsSync(dir)) {
|
||||
if (!args["dry-run"]) {
|
||||
try {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
created = true;
|
||||
} catch (err) {
|
||||
fail(EXIT.REFUSED, "mkdir-failed", `Could not create ${dir}: ${err.message}`, "Pick another folder, or use --dir temp.");
|
||||
}
|
||||
}
|
||||
}
|
||||
const d = now();
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
const timestamp = `${isoDate(d)}-${pad(d.getHours())}${pad(d.getMinutes())}`;
|
||||
let file = path.join(dir, `${timestamp}-handoff.md`);
|
||||
for (let n = 2; fs.existsSync(file); n++) file = path.join(dir, `${timestamp}-${n}-handoff.md`);
|
||||
|
||||
// Compare real paths: git prints the repo's real top level, while the folder
|
||||
// may arrive as an 8.3 short name (C:\Users\JOHN~1\...) or through a symlink
|
||||
// (macOS /tmp -> /private/tmp). A folder not created yet (--dry-run) resolves
|
||||
// through its nearest existing ancestor. Git runs from that ancestor too, so
|
||||
// the file is checked against the repo it would actually land in.
|
||||
const existing = (() => {
|
||||
let p = dir;
|
||||
while (!fs.existsSync(p) && path.dirname(p) !== p) p = path.dirname(p);
|
||||
return p;
|
||||
})();
|
||||
const realDir = path.join(fs.realpathSync.native(existing), path.relative(existing, dir));
|
||||
const realFile = path.join(realDir, path.basename(file));
|
||||
const top = git(existing, ["rev-parse", "--show-toplevel"]);
|
||||
const gitInfo = { repo: top.ok || git(root, ["rev-parse", "--show-toplevel"]).ok, inRepo: false, ignored: null };
|
||||
if (top.ok) {
|
||||
const repoRoot = fs.realpathSync.native(path.resolve(top.out));
|
||||
const relToRepo = path.relative(repoRoot, realFile);
|
||||
gitInfo.inRepo = !!relToRepo && !relToRepo.startsWith("..") && !path.isAbsolute(relToRepo);
|
||||
if (gitInfo.inRepo) {
|
||||
// check-ignore exits 0 when ignored, 1 when not; it honours global and nested ignore files.
|
||||
const ci = git(repoRoot, ["check-ignore", "-q", relToRepo.split(path.sep).join("/")]);
|
||||
gitInfo.ignored = ci.ok;
|
||||
const relDir = path.relative(repoRoot, realDir).split(path.sep).join("/");
|
||||
// The repo root itself is never the line to ignore: offer the handoff files instead.
|
||||
gitInfo.ignoreLine = relDir ? `${relDir}/` : "*-handoff.md";
|
||||
}
|
||||
}
|
||||
out({
|
||||
ok: true,
|
||||
path: file,
|
||||
dir,
|
||||
created,
|
||||
dryRun: !!args["dry-run"],
|
||||
timestamp,
|
||||
git: gitInfo,
|
||||
...(gitInfo.inRepo && gitInfo.ignored === false ? { warning: `This file would be tracked by git. Offer to add "${gitInfo.ignoreLine}" to .gitignore; do not add it without asking.` } : {}),
|
||||
});
|
||||
});
|
||||
@@ -38,28 +38,15 @@ the next task (and shape the whole document around it), but still confirm.
|
||||
|
||||
## Where to write it
|
||||
|
||||
Ask the user if they would like to save the file to the temporary directory of the user's OS (this should be the default) or to some other location like `./handoffs/` at the repo root. Then let the script pick the exact path, from the project root:
|
||||
No question to ask: every handoff lives in `~/.plan2code/handoffs/`, outside every repo. From the project root, let the console name the file:
|
||||
|
||||
```
|
||||
node "<S>/handoff-path.mjs" --dir temp # or: --dir handoffs
|
||||
node "<D>/console.mjs" handoff new --workflow handoff --skill plan2code-handoff --spec specs/<feature> --title "<short title>"
|
||||
```
|
||||
|
||||
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-handoff/scripts/` globally). It prints one JSON object: `path` is `<dir>/<YYYY-MM-DD-HHmm>-handoff.md` from the clock (suffixed `-2`, `-3`... rather than overwrite an earlier handoff), and the folder is created if missing. Write the document to exactly that `path`. Exit 5 means the folder could not be created (or `--dir` names a file): ask for another location.
|
||||
`<D>` is `references/web-console/` beside this SKILL.md, as in Interface. Pass `--spec` only when the work was inside a spec; the title is a few words naming the work. It prints one JSON object: write the document to exactly its `path`, and tell the person that path. Exit 3 means it could not write there: say so and stop.
|
||||
|
||||
### Make sure you aren't leaking the file into version control
|
||||
|
||||
The handoff is working state for the next session, not a project artifact, so it
|
||||
should stay out of commits and PRs. Don't assume it will — this skill may run in
|
||||
any repo. The same output's `git` block says:
|
||||
|
||||
- `repo: false`, or `inRepo: false` (the OS temp dir): nothing to ignore; just tell the user where the file is.
|
||||
- `ignored: true`: git already ignores it (via any `.gitignore`, global or nested; `git check-ignore` is the check).
|
||||
- `ignored: false`: it would be tracked; `git.ignoreLine` is the line to offer, and the top-level `warning` says so.
|
||||
|
||||
If it is **not** ignored, do not silently modify the user's `.gitignore`. Tell
|
||||
them the file would be tracked by git and offer to add the `ignoreLine` (e.g.
|
||||
`handoffs/`) to `.gitignore` — let them decide. Some users may want handoffs committed so
|
||||
teammates get them; that's a legitimate choice, so present it, don't force it.
|
||||
The dashboard lists the handoff for this checkout until it is picked up, and old ones go after 30 days.
|
||||
|
||||
## If this touched a plan2code spec
|
||||
|
||||
@@ -142,10 +129,3 @@ lives (env var name, secret manager entry) rather than its value.
|
||||
Tell the user the path you wrote to and give a one-line summary of the confirmed
|
||||
next task, so they know what the incoming agent will start on. Mention that a
|
||||
fresh session can be pointed at the file to resume the work.
|
||||
|
||||
If your ignore check above found the file is in a repo and **not** gitignored
|
||||
(`git.ignored: false`, which includes a repo with no `.gitignore`), say so plainly
|
||||
here, e.g. "note: `handoffs/` isn't gitignored in this repo, so this file will
|
||||
show up in `git status` and could be committed", and offer to add the
|
||||
`ignoreLine`. Outside a repo there is nothing to ignore. Never leave
|
||||
the user unaware that the handoff might ride along into a commit.
|
||||
+10
-1
@@ -37,6 +37,7 @@ The page draws the cards itself — you never send the list. It also knows the r
|
||||
- A `diagnosed` spec ("Bug diagnosed") is a bug Diagnose wrote up: recommend Quick Task, or Plan when its `DIAGNOSIS-<date>.md` sizes the fix as big; its folder rides along on either launch.
|
||||
- A `fixed` spec ("Bug fixed") is a diagnosed bug Quick Task fixed but did not archive: finished, so never recommend for it or name it in the note; the picker never pre-selects one and hides it while unavailable workflows are hidden. The person archives it (Quick Task offers that once the bug is fixed) or deletes it with the picker's ✕.
|
||||
- Nothing on disk, or only `fixed` specs → `recommend: "plan2code-0-pathfinder"`; the note invites the first idea.
|
||||
- A handoff in `state.scan.handoffs` newer than the most recently touched spec is usually the place to start: say so in `note` (the page has no card to `recommend` for it).
|
||||
- Recommend only what you would tell a person who asked "where do I start?". When in doubt, no flag and a neutral note — the page falls back to flagging the selected spec's own next step.
|
||||
- `recommend` must name a lit card for the initial selection. If the person switches specs or starts fresh, the page derives the suggestion and detail from its scan instead.
|
||||
|
||||
@@ -58,7 +59,7 @@ Ground truth for menu notes and Ask-tab answers. For anything beyond this table,
|
||||
| 3-implement(-review) | `overview.md`, `phase-X.md` | code; `[x]` marks + completion summary in `phase-X.md` |
|
||||
| review | spec, diff | the fixes picked; no spec writes |
|
||||
| 4-finalize | spec + code | summary in `overview.md`; moves the spec to `specs--completed/` |
|
||||
| handoff | conversation, spec, git | `<timestamp>-handoff.md` (OS temp or `handoffs/`) |
|
||||
| handoff | conversation, spec, git | `~/.plan2code/handoffs/<id>.md`, listed on the dashboard |
|
||||
| changelog | `CHANGELOG.md`, `package.json`, git history | `CHANGELOG.md` entries, `package.json` version; no commits |
|
||||
| git | git status, branches, diffs, `AGENTS.md` | commits, branches; optional `.gitignore`, push, publish; no spec writes |
|
||||
| xray | the codebase, `git` history, `gh` when present | an answer; `ARCHITECTURE-BRIEF-<date>.md` or `XRAY-<area>-<date>.md` when asked |
|
||||
@@ -107,6 +108,10 @@ If `skill` is not in the table below, say so on the page and stay the dashboard.
|
||||
| plan2code-git | git | | plan2code-changelog | changelog |
|
||||
| plan2code-xray | xray | | plan2code-diagnose | diagnose |
|
||||
|
||||
## A pick-up arrives
|
||||
|
||||
A handoff chip's **Pick it up here** sends `__pickup` with `resume`, `skillFile` and `handoffFile` (and `fallback` when the named skill or spec is gone, or the Handoff skill wrote it). Read `console-launches.md` → A pick-up, then do as a pick does: `resume` first, then the skill's file, then the handoff.
|
||||
|
||||
## A delete arrives
|
||||
|
||||
The ✕ on a picker chip asks for that spec to go, after a two-step confirm on the page: `{ "i": "__delete", "type": "delete", "spec": "specs/<name>" }`. The page never deletes; you do, through the console's checked command, never your own `rm`:
|
||||
@@ -115,6 +120,10 @@ The ✕ on a picker chip asks for that spec to go, after a two-step confirm on t
|
||||
2. `node "<D>/console.mjs" open --resume <sid> --no-open --workflow dashboard`, which rescans `specs/`.
|
||||
3. Post the menu again with `--wait`; the note says what was deleted, or why it was not. Stay the dashboard.
|
||||
|
||||
A `fixed` spec is deleted after one confirm on the page (its own Delete button, no name to type); your steps are the same.
|
||||
|
||||
A handoff's Delete is the same `__delete` with `handoff` (an id) instead of `spec`: run `node "<D>/console.mjs" delete-handoff --handoff <action.handoff>`, then steps 2 and 3.
|
||||
|
||||
## Coming back from another skill
|
||||
|
||||
You arrive here mid-conversation after a `__dashboard` press — from a finished screen, or mid-workflow from the top bar's triangle once that skill saved its place — having already run `open --resume <sid> --no-open --workflow dashboard` (the send's `resume`; it cleared the last skill's page, its finish included — console-finish.md, console-stop.md). Skip Interface steps 1–2; your first job is the menu judgment, then post the menu with `--wait`: re-read `state.scan`, which the resume refreshed — the spec you just worked on is usually the most recently touched. Then the usual wait loop and launches.
|
||||
|
||||
@@ -119,8 +119,8 @@ review set it to its own stage):
|
||||
"items": [{ "id": "signoff", "status": "reopened",
|
||||
"body": "Reviewed and ready for sign-off. The review found 3 issues: 2 fixed, 1 still open in the Review findings tab. The report is updated.",
|
||||
"verdicts": [
|
||||
{ "id": "show", "label": "Show me it working" },
|
||||
{ "id": "approve", "label": "Approve this phase" },
|
||||
{ "id": "show", "label": "Show me it working" },
|
||||
{ "id": "changes", "label": "I want changes" }
|
||||
],
|
||||
"token": { "approve": "approved", "changes": "needs changes", "show": "show me" },
|
||||
|
||||
@@ -47,7 +47,7 @@ first, and post before anything slow.
|
||||
|
||||
## What the page already knows
|
||||
|
||||
`state.scan` is `{ hasAgents, isGit, pending, specs: [{ dir, name, state, detail, touched }] }`,
|
||||
`state.scan` is `{ hasAgents, isGit, pending, specs: [{ dir, name, state, detail, touched }], handoffs, handoffsDir }`,
|
||||
a snapshot of the last `open` (a spec created mid-session appears the next time
|
||||
the session resumes as a dashboard). `pending` is how many files a commit would
|
||||
take (`null` when git cannot say): the Git card never greys out, shows the count
|
||||
@@ -64,6 +64,34 @@ person's turn by itself.
|
||||
A `__stop` before a pick ends the session the usual way: `finish` (paused
|
||||
headline, `"command": "/plan2code"`) then `stop` (`console-stop.md`).
|
||||
|
||||
`handoffs` is this checkout's unused handoffs, newest first (`[{ id, title,
|
||||
next, written, spec, skill, workflow }]`, read from `~/.plan2code/handoffs/`
|
||||
by `open`, a dashboard only), and `handoffsDir` is that folder. The picker shows
|
||||
them as dashed **Handoff** chips after the specs.
|
||||
|
||||
## A pick-up
|
||||
|
||||
Selecting a handoff chip shows a preview and hides the skill cards. **Pick it up
|
||||
here** sends a hop like a launch, naming only the id:
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [{ "i": "__pickup", "type": "pickup", "handoff": "2026-10-17-1152-handoff" }],
|
||||
"reply": "Pick up the handoff \"Lunch vote\" right here in this session.",
|
||||
"resume": "node \"…/console.mjs\" open --resume <sid> --no-open --workflow quick-task --spec specs/lunch-vote",
|
||||
"skillFile": "…/plan2code-quick-task/SKILL.md",
|
||||
"handoffFile": "~/.plan2code/handoffs/2026-10-17-1152-handoff.md" }
|
||||
```
|
||||
|
||||
`wait` has already read the handoff's stored skill and spec, marked the handoff
|
||||
used (the next scan no longer lists it) and put the command in `resume`. Run
|
||||
`resume`, read `skillFile` with your file-read tool, then read `handoffFile`,
|
||||
follow the skill from where its real work starts, and carry on from the
|
||||
handoff's **Next task**. When the send carries `"fallback": true` the named
|
||||
skill or spec was gone, or the Handoff skill wrote it: say so in one line,
|
||||
since Quick Task is picking it up.
|
||||
The handoff's document stays on disk until the 30-day sweep.
|
||||
|
||||
## A delete
|
||||
|
||||
The ✕ on a picker chip, after the page's two-step confirm (what goes, then
|
||||
@@ -78,3 +106,8 @@ having touched nothing, and drops the workspace remembered for that spec.
|
||||
Then `open --resume <sid> --no-open --workflow dashboard` to rescan, and post
|
||||
the menu again with `--wait`, its note saying what went or why it did not.
|
||||
The page shows the chip as "Deleting…" until that rescan lands.
|
||||
|
||||
A handoff's **Delete** sends the same `__delete`, with `handoff` (its id) where a
|
||||
spec has `spec`. Delete it through
|
||||
`node "<CONSOLE>" delete-handoff --handoff <id>` (exit 3 with `message` when it
|
||||
refuses, nothing touched), then rescan and post the menu as for a spec.
|
||||
@@ -43,6 +43,41 @@ you are halfway through writing their last answers. The one exception is an
|
||||
agent that has stopped checking in: then Stop comes back, and the request waits
|
||||
on disk for whichever session collects it next.
|
||||
|
||||
## Stop with a handoff
|
||||
|
||||
Off the dashboard, the Stop dialog offers **Stop with a handoff** first and
|
||||
**Just stop and save** second. The handoff choice sends the same `__stop`, with
|
||||
`handoff: true`, and `wait` adds `handoffSkill` (the Handoff skill's `SKILL.md`,
|
||||
present in a built skill):
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [ /* staged answers and notes, as usual */,
|
||||
{ "i": "__stop", "type": "stop", "handoff": true } ],
|
||||
"reply": "...the answer lines...\nStop here, save my place and write a handoff, so the dashboard can pick this up later.",
|
||||
"handoffSkill": "…/plan2code-handoff/SKILL.md" }
|
||||
```
|
||||
|
||||
Act on it in this turn, in this order:
|
||||
|
||||
1. **Handle the answers** exactly as in "Stop requests" step 1.
|
||||
2. **Save your place** exactly as step 2 there.
|
||||
3. **Make the handoff file:**
|
||||
`node "<CONSOLE>" handoff new --workflow <yours> --skill <your skill> [--spec <spec>] --title "<short title>" --from-stop`
|
||||
It prints the `path` to write.
|
||||
4. **Write the handoff.** Open `handoffSkill` with your file-read tool (never a
|
||||
skill-invocation tool) and write the document it describes to that `path`.
|
||||
Skip its questions and its "Where to write it" step: infer the Next task
|
||||
from where the work stands, and say in the document that it was inferred.
|
||||
5. **Post `finish`** (`console-finish.md`) with a headline starting "Paused", a
|
||||
`body` that names the handoff path and says the dashboard will offer it, and
|
||||
the resume command, without `--wait`.
|
||||
6. **`stop`** the server.
|
||||
|
||||
With no `handoffSkill` (a source checkout), use the structure in
|
||||
`~/.agents/skills/plan2code-handoff/SKILL.md`. Do not ask whether they are
|
||||
sure: the page already asked.
|
||||
|
||||
## Back to the dashboard, mid-workflow
|
||||
|
||||
On every workflow but the dashboard, a triangle left of Stop session takes the
|
||||
|
||||
@@ -161,7 +161,7 @@ An action whose `i` starts with `__` is about the session, not a question:
|
||||
|
||||
| Action | Read |
|
||||
| --- | --- |
|
||||
| `__stop`, `__dashboard` (no finish up) | `console-stop.md` |
|
||||
| `__stop` (plain, or with `handoff: true`), `__dashboard` (no finish up) | `console-stop.md` |
|
||||
| `__commit`, `__dashboard` (from a finished screen) | `console-finish.md` |
|
||||
| `__launch` | `console-launches.md` |
|
||||
| `__delete` | `console-launches.md` (the dashboard only) |
|
||||
|
||||
+132
-10
@@ -99,6 +99,7 @@ import {
|
||||
writeWorkspaceCursor,
|
||||
} from "./lib.mjs";
|
||||
import { snapshot } from "./git-repo.mjs";
|
||||
import { handoffsDir, isHandoffId, listHandoffs, markHandoffUsed, newHandoff, readHandoffMeta, removeHandoff, removeHandoffs, staleHandoffs } from "./handoffs.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_COMMITS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { blockFor, offered } from "./public/subagents.js";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
@@ -321,6 +322,13 @@ async function cmdOpen() {
|
||||
// own top level: `project` is the common-dir key so linked worktrees share
|
||||
// sessions, but each shows the specs on its own disk.
|
||||
const scan = state.workflow === "dashboard" ? scanProject(worktree) : null;
|
||||
// This checkout's unused handoffs live outside every repo (handoffs.mjs), so
|
||||
// they join the scan here and not in scanProject(), which also serves
|
||||
// `specs.mjs list`. handoffsDir rides along so the page never guesses it.
|
||||
if (scan) {
|
||||
scan.handoffs = listHandoffs(worktree);
|
||||
scan.handoffsDir = handoffsDir();
|
||||
}
|
||||
// The git board's data, the same way: the console's own read-only snapshot
|
||||
// (git-repo.mjs), taken before the lock so no git process runs under it.
|
||||
const gitSnap = state.workflow === "git" ? snapshot(worktree, { prHosts: readPrHosts() }) : null;
|
||||
@@ -384,14 +392,16 @@ async function cmdOpen() {
|
||||
// Nothing about this reaches the page.
|
||||
const sweptSessions = staleSessions(SESSIONS_DIR, Date.now(), SESSION_MAX_AGE_MS, sid);
|
||||
const sweptScratch = staleScratch(HOME_DIR, Date.now(), SESSION_MAX_AGE_MS);
|
||||
const sweptHandoffs = staleHandoffs(Date.now(), SESSION_MAX_AGE_MS);
|
||||
const swept =
|
||||
sweptSessions.length || sweptScratch.length
|
||||
? { swept: { sessions: sweptSessions, scratch: sweptScratch } }
|
||||
sweptSessions.length || sweptScratch.length || sweptHandoffs.length
|
||||
? { swept: { sessions: sweptSessions, scratch: sweptScratch, handoffs: sweptHandoffs } }
|
||||
: {};
|
||||
const sweep = () => {
|
||||
sweepUploads(SESSIONS_DIR, Date.now(), UPLOAD_MAX_AGE_MS, sid).catch(() => {});
|
||||
removeSessions(SESSIONS_DIR, sweptSessions).catch(() => {});
|
||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||
removeHandoffs(sweptHandoffs).catch(() => {});
|
||||
};
|
||||
|
||||
// A standing instruction the new agent is owed, as `subagents` and a
|
||||
@@ -1107,7 +1117,8 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
const hop = hopFor(path.basename(dir), result);
|
||||
print({ ...out, ...hop, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
markPickedUp(result);
|
||||
print({ ...out, ...hop, ...handoffFor(result), ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
try {
|
||||
writeJsonAtomic(resultPath, collected);
|
||||
} catch {}
|
||||
@@ -1166,21 +1177,78 @@ const HOP_ACTIONS = {
|
||||
launch: (a) => ({ workflow: a.workflow, spec: a.spec, skill: a.skill }),
|
||||
dashboard: () => ({ workflow: "dashboard", skill: "plan2code" }),
|
||||
commit: () => ({ workflow: "git", skill: "plan2code-git" }),
|
||||
pickup: pickupHop,
|
||||
};
|
||||
|
||||
// A pick-up hops into the skill and spec the handoff's `.json` names (the page
|
||||
// sends only the id). When the skill is no longer installed, the spec folder
|
||||
// is gone, or the Handoff skill wrote it, Quick Task picks it up instead,
|
||||
// flagged so the agent says so. In a
|
||||
// source tree no skill sits beside the console, so nothing can be told to be
|
||||
// missing and the stored skill stands.
|
||||
function skillPath(skill) {
|
||||
return path.resolve(HERE, "..", "..", "..", skill, "SKILL.md");
|
||||
}
|
||||
|
||||
function pickupHop(action) {
|
||||
const id = action.handoff;
|
||||
const meta = isHandoffId(id) ? readHandoffMeta(id) : null;
|
||||
const handoffFile = isHandoffId(id) ? path.join(handoffsDir(), id + ".md") : undefined;
|
||||
const quick = { workflow: "quick-task", spec: undefined, skill: "plan2code-quick-task", handoffFile, fallback: true };
|
||||
if (!meta) return quick;
|
||||
if (typeof meta.workflow !== "string" || !/^[a-z-]+$/.test(meta.workflow)) return quick;
|
||||
// The Handoff skill's own handoff: resuming it would only write another one.
|
||||
if (meta.workflow === "handoff") return quick;
|
||||
if (typeof meta.skill !== "string" || !/^[a-z0-9-]+$/.test(meta.skill)) return quick;
|
||||
const specGone =
|
||||
typeof meta.spec === "string" && meta.spec && (!SAFE_SPEC.test(meta.spec) || !fs.existsSync(path.join(meta.worktree || "", meta.spec)));
|
||||
const skillGone = !fs.existsSync(skillPath(meta.skill)) && fs.existsSync(skillPath("plan2code-quick-task"));
|
||||
if (specGone || skillGone) return quick;
|
||||
return { workflow: meta.workflow, spec: meta.spec || undefined, skill: meta.skill, handoffFile };
|
||||
}
|
||||
|
||||
// A stop that asked for a handoff gets the Handoff skill's file beside it, so
|
||||
// the agent opens it instead of locating it. Only a built skill has one.
|
||||
function handoffFor(result) {
|
||||
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
|
||||
if (!actions.some((a) => a && a.type === "stop" && a.i === "__stop" && a.handoff === true)) return {};
|
||||
const file = path.resolve(HERE, "..", "..", "..", "plan2code-handoff", "SKILL.md");
|
||||
return fs.existsSync(file) ? { handoffSkill: file } : {};
|
||||
}
|
||||
|
||||
// A pick-up uses its handoff up as its hop is printed, so the next dashboard
|
||||
// scan no longer lists it. Never fatal; a repeat delivery marks it again.
|
||||
function markPickedUp(result) {
|
||||
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
|
||||
for (const a of actions) {
|
||||
if (a && a.type === "pickup" && typeof a.i === "string" && a.i.startsWith("__") && isHandoffId(a.handoff)) {
|
||||
try {
|
||||
markHandoffUsed(a.handoff);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A spec name that is safe to put in the `resume` command: `specs/<name>` with
|
||||
// nothing a shell would act on. A handoff's `.json` and a page's send are both
|
||||
// data off disk or the wire, so the name is checked here and not trusted.
|
||||
const SAFE_SPEC = /^specs\/[^/\\"'`$;&|<>(){}*?!#~\r\n]+$/;
|
||||
|
||||
function hopFor(sid, result) {
|
||||
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
|
||||
const action = actions.find((a) => a && Object.hasOwn(HOP_ACTIONS, a.type) && typeof a.i === "string" && a.i.startsWith("__"));
|
||||
if (!action) return {};
|
||||
const { workflow, spec, skill } = HOP_ACTIONS[action.type](action);
|
||||
const { workflow, spec, skill, handoffFile, fallback } = HOP_ACTIONS[action.type](action);
|
||||
if (typeof workflow !== "string" || !/^[a-z-]+$/.test(workflow)) return {};
|
||||
const quote = (v) => (/[\s"]/.test(v) ? `"${v.replace(/"/g, '\\"')}"` : v);
|
||||
const specArg = typeof spec === "string" && spec ? ` --spec ${quote(spec)}` : "";
|
||||
const specArg = typeof spec === "string" && SAFE_SPEC.test(spec) ? ` --spec ${quote(spec)}` : "";
|
||||
const out = { resume: `node "${path.join(HERE, "console.mjs")}" open --resume ${sid} --no-open --workflow ${workflow}${specArg}` };
|
||||
if (typeof skill === "string" && /^[a-z0-9-]+$/.test(skill)) {
|
||||
const file = path.resolve(HERE, "..", "..", "..", skill, "SKILL.md");
|
||||
const file = skillPath(skill);
|
||||
if (fs.existsSync(file)) out.skillFile = file;
|
||||
}
|
||||
if (typeof handoffFile === "string") out.handoffFile = handoffFile;
|
||||
if (fallback) out.fallback = true;
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -1323,6 +1391,47 @@ function cmdDeleteSpec() {
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- handoff */
|
||||
|
||||
// A handoff the agent is about to write, claimed in ~/.plan2code/handoffs/
|
||||
// (handoffs.mjs) for this checkout: the Stop flow's "Stop with a handoff" and
|
||||
// the Handoff skill both start here. Only the .json is written; the agent
|
||||
// writes the document at the printed path.
|
||||
function cmdHandoff() {
|
||||
const usage = "handoff needs: handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]";
|
||||
if (args._[0] !== "new" || args._.length > 1) die(usage, 2);
|
||||
if (typeof args.workflow !== "string" || typeof args.skill !== "string") die(usage, 2);
|
||||
if ("from-stop" in args && args["from-stop"] !== true) die("--from-stop takes no value", 2);
|
||||
const { worktree, project } = repoRoots();
|
||||
try {
|
||||
const { id, path: file, meta } = newHandoff({
|
||||
worktree,
|
||||
project,
|
||||
spec: args.spec,
|
||||
workflow: args.workflow,
|
||||
skill: args.skill,
|
||||
title: args.title,
|
||||
fromStop: args["from-stop"] === true,
|
||||
});
|
||||
print({ ok: true, id, path: file, meta });
|
||||
} catch (err) {
|
||||
print({ ok: false, message: err.message });
|
||||
process.exit(3);
|
||||
}
|
||||
}
|
||||
|
||||
// The dashboard's Delete on a Handoff chip, carried out by the agent, the
|
||||
// same shape as delete-spec: removeHandoff() does every check.
|
||||
function cmdDeleteHandoff() {
|
||||
if (typeof args.handoff !== "string" || !args.handoff.trim()) die("delete-handoff needs --handoff <id>", 2);
|
||||
try {
|
||||
print(removeHandoff(args.handoff));
|
||||
} catch (err) {
|
||||
print({ ok: false, message: err.message });
|
||||
process.exit(3);
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- help */
|
||||
|
||||
function cmdHelp() {
|
||||
@@ -1334,8 +1443,8 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
open [--file <payload.json>] [--workflow <w>] [--title "<t>"] [--spec <dir>]
|
||||
[--session|--resume <sid>] [--no-open] [--idle-ms <ms>]
|
||||
Start or resume a session and its server. Prints { ok, sid, session,
|
||||
url, terminalLine }, plus swept { sessions, scratch } when old
|
||||
sessions or scratch files were removed. Run it FIRST, before
|
||||
url, terminalLine }, plus swept { sessions, scratch, handoffs } when
|
||||
old sessions, scratch files or handoffs were removed. Run it FIRST, before
|
||||
reading anything: the page shows a starting screen until your
|
||||
first post. --file is optional, and --title defaults to the
|
||||
project's folder name. Also prints workspace: { folders: [{ name,
|
||||
@@ -1398,6 +1507,17 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
worktree: never a link, never deeper, never specs--completed/.
|
||||
Prints { ok, removed }; exit 2 = bad usage, 3 = refused, with
|
||||
{ ok: false, message } saying why. Nothing is touched on a refusal.
|
||||
handoff new --workflow <w> --skill <s> [--spec specs/<name>] [--title "<t>"] [--from-stop]
|
||||
Claim a handoff for this checkout in ~/.plan2code/handoffs/ (Stop
|
||||
with a handoff, the Handoff skill). Writes only <id>.json; you write
|
||||
the document at path. Prints { ok, id, path, meta }; exit 2 = bad
|
||||
usage, 3 = a bad value, with { ok: false, message } saying why.
|
||||
delete-handoff --handoff <id>
|
||||
Delete that handoff for good (a Handoff chip's Delete, a __delete
|
||||
action): <id>.md and <id>.json, only in ~/.plan2code/handoffs/,
|
||||
never a link. Prints { ok, removed }; exit 2 = bad usage, 3 =
|
||||
refused, with { ok: false, message } saying why. Nothing is touched
|
||||
on a refusal.
|
||||
status [--session <sid>] [--all]
|
||||
One session, or (--all) every session on this machine, every project.
|
||||
stop --session <sid> | --all
|
||||
@@ -1665,6 +1785,8 @@ const COMMANDS = {
|
||||
keep: cmdKeep,
|
||||
forget: cmdForget,
|
||||
"delete-spec": cmdDeleteSpec,
|
||||
handoff: cmdHandoff,
|
||||
"delete-handoff": cmdDeleteHandoff,
|
||||
status: cmdStatus,
|
||||
stop: cmdStop,
|
||||
help: cmdHelp,
|
||||
@@ -1684,7 +1806,7 @@ if (Number.isFinite(nodeMajor) && nodeMajor < 18) {
|
||||
|
||||
if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
|
||||
process.stderr.write(
|
||||
"console: usage: console.mjs <open|post|wait|chat|keep|forget|delete-spec|status|stop|help> [--session <id>] [--file <patch.json>] [--seconds N]\n"
|
||||
"console: usage: console.mjs <open|post|wait|chat|keep|forget|delete-spec|handoff|delete-handoff|status|stop|help> [--session <id>] [--file <patch.json>] [--seconds N]\n"
|
||||
);
|
||||
process.exit(2);
|
||||
}
|
||||
@@ -1692,7 +1814,7 @@ if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
|
||||
// A flag given with no value parses as `true`, and a boolean handed on as a
|
||||
// path or a name crashes somewhere deep (path.basename(true) throws). Every
|
||||
// flag that takes a value is checked once, here, and refused as bad usage.
|
||||
const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "upload", "name", "from", "seconds", "limit", "idle-ms"];
|
||||
const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "skill", "handoff", "upload", "name", "from", "seconds", "limit", "idle-ms"];
|
||||
for (const flag of VALUE_FLAGS) {
|
||||
if (flag in args && typeof args[flag] !== "string") die(`--${flag} needs a value`, 2);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
// Plan2Code Web Console - the handoff store.
|
||||
//
|
||||
// Every handoff lives in one folder, outside every repo:
|
||||
//
|
||||
// ~/.plan2code/handoffs/<id>.md the Handoff skill's document, written by
|
||||
// the agent and never changed here
|
||||
// ~/.plan2code/handoffs/<id>.json who wrote it, for which checkout, spec
|
||||
// and skill, and whether it was picked up
|
||||
//
|
||||
// This module is the only code that names, lists, marks, deletes and sweeps
|
||||
// them. The console ships inside every skill, so the Stop flow, the Handoff
|
||||
// skill and the dashboard all reach it through console.mjs commands.
|
||||
// PLAN2CODE_HANDOFFS_DIR moves the folder, for tests.
|
||||
//
|
||||
// Node built-ins only. No build step.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
export const HANDOFFS_DIR = process.env.PLAN2CODE_HANDOFFS_DIR || path.join(os.homedir(), ".plan2code", "handoffs");
|
||||
|
||||
// Read at call time, so a test that sets the variable after import sees it.
|
||||
export function handoffsDir() {
|
||||
return process.env.PLAN2CODE_HANDOFFS_DIR || path.join(os.homedir(), ".plan2code", "handoffs");
|
||||
}
|
||||
|
||||
export const HANDOFF_ID = /^\d{4}-\d{2}-\d{2}-\d{4}-handoff(-\d+)?$/;
|
||||
|
||||
export function isHandoffId(id) {
|
||||
return typeof id === "string" && HANDOFF_ID.test(id) && id === path.basename(id);
|
||||
}
|
||||
|
||||
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
|
||||
// clock, as the skill scripts' now() does. Copied, not imported: the console
|
||||
// is copied into skills on its own and may not reach src/skill-scripts/.
|
||||
function clock() {
|
||||
const pinned = process.env.PLAN2CODE_NOW;
|
||||
if (pinned) {
|
||||
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
|
||||
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
|
||||
const d = new Date(pinned);
|
||||
if (!Number.isNaN(d.getTime())) return d;
|
||||
}
|
||||
return new Date();
|
||||
}
|
||||
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
|
||||
/* ----------------------------------------------------------------- write */
|
||||
|
||||
/**
|
||||
* Claim a new handoff for the agent to write. The id is the local minute,
|
||||
* `YYYY-MM-DD-HHmm-handoff`, with `-2`, `-3` and so on after a clash; the
|
||||
* `.json` is created exclusively, so two sessions in the same minute never
|
||||
* share one. Only the `.json` is written: the agent writes the `.md` at the
|
||||
* returned path. A bad field throws, naming it, before anything is created.
|
||||
*/
|
||||
export function newHandoff({ worktree, project, spec, workflow, skill, title, fromStop } = {}, now = clock()) {
|
||||
if (typeof workflow !== "string" || !/^[a-z-]+$/.test(workflow)) throw new Error(`workflow must be lowercase letters and dashes, got ${JSON.stringify(workflow)}`);
|
||||
if (typeof skill !== "string" || !/^[a-z0-9-]+$/.test(skill)) throw new Error(`skill must be a skill name, got ${JSON.stringify(skill)}`);
|
||||
if (spec !== undefined && spec !== null && spec !== "" && (typeof spec !== "string" || !/^specs\/[^/\\]+$/.test(spec))) {
|
||||
throw new Error(`spec must be specs/<name>, got ${JSON.stringify(spec)}`);
|
||||
}
|
||||
const dir = handoffsDir();
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const base = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}-handoff`;
|
||||
for (let n = 1; ; n++) {
|
||||
const id = n === 1 ? base : `${base}-${n}`;
|
||||
// A lone .md left by hand also holds its name.
|
||||
if (fs.existsSync(path.join(dir, id + ".md"))) continue;
|
||||
let fd;
|
||||
try {
|
||||
fd = fs.openSync(path.join(dir, id + ".json"), "wx");
|
||||
} catch (err) {
|
||||
if (err.code === "EEXIST") continue;
|
||||
throw err;
|
||||
}
|
||||
const meta = {
|
||||
v: 1,
|
||||
id,
|
||||
title: typeof title === "string" ? title : "",
|
||||
worktree,
|
||||
project,
|
||||
spec: spec || null,
|
||||
workflow,
|
||||
skill,
|
||||
written: now.toISOString(),
|
||||
fromStop: Boolean(fromStop),
|
||||
usedAt: null,
|
||||
};
|
||||
try {
|
||||
fs.writeSync(fd, JSON.stringify(meta, null, 2) + "\n");
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
return { id, path: path.join(dir, id + ".md"), meta };
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ read */
|
||||
|
||||
// A regular file in the folder, never a link: lstat, not stat.
|
||||
function regularFile(file) {
|
||||
try {
|
||||
return fs.lstatSync(file).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The handoff's `.json`, or null: an invalid id, a missing or linked file, or not a v1 record. */
|
||||
export function readHandoffMeta(id) {
|
||||
if (!isHandoffId(id)) return null;
|
||||
const file = path.join(handoffsDir(), id + ".json");
|
||||
if (!regularFile(file)) return null;
|
||||
try {
|
||||
const meta = JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
return meta && typeof meta === "object" && meta.v === 1 ? meta : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Stamp `usedAt` (a pick-up) and rewrite the `.json`; the `.md` is never touched. */
|
||||
export function markHandoffUsed(id, now = clock()) {
|
||||
const meta = readHandoffMeta(id);
|
||||
if (!meta) return null;
|
||||
const next = { ...meta, usedAt: now.toISOString() };
|
||||
const file = path.join(handoffsDir(), id + ".json");
|
||||
const tmp = `${file}.${process.pid}.tmp`;
|
||||
fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + "\n");
|
||||
fs.renameSync(tmp, file);
|
||||
return next;
|
||||
}
|
||||
|
||||
const NEXT_MAX = 280;
|
||||
|
||||
// The case-folded resolved path, as removeSpec() compares realpaths.
|
||||
function samePath(a, b) {
|
||||
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
|
||||
return typeof a === "string" && typeof b === "string" && fold(path.resolve(a)) === fold(path.resolve(b));
|
||||
}
|
||||
|
||||
// The document's first `# ` heading, without a leading "Handoff" and the
|
||||
// punctuation after it.
|
||||
function docTitle(md) {
|
||||
const m = md.match(/^# (.+)$/m);
|
||||
if (!m) return "";
|
||||
return m[1].replace(/^Handoff\b/i, "").replace(/^[\s:\-\u2013\u2014]+/, "").trim();
|
||||
}
|
||||
|
||||
// The first paragraph under `## Next task`, on one line and cut to NEXT_MAX.
|
||||
function docNext(md) {
|
||||
const lines = md.split(/\r?\n/);
|
||||
const at = lines.findIndex((l) => /^##\s+Next task\b/i.test(l));
|
||||
if (at < 0) return "";
|
||||
const para = [];
|
||||
for (const line of lines.slice(at + 1)) {
|
||||
if (/^#{1,6}\s/.test(line)) break;
|
||||
if (!line.trim()) {
|
||||
if (para.length) break;
|
||||
continue;
|
||||
}
|
||||
para.push(line.trim());
|
||||
}
|
||||
const text = para.join(" ").replace(/\s+/g, " ").trim();
|
||||
return text.length > NEXT_MAX ? text.slice(0, NEXT_MAX - 1).trimEnd() + "…" : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* This checkout's handoffs still waiting to be picked up: a readable `.json`
|
||||
* with no `usedAt`, a `.md` beside it, and the same worktree. Newest first,
|
||||
* as `[{ id, title, next, written, spec, skill, workflow }]`.
|
||||
*/
|
||||
export function listHandoffs(worktree) {
|
||||
const dir = handoffsDir();
|
||||
let names;
|
||||
try {
|
||||
names = fs.readdirSync(dir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const out = [];
|
||||
for (const name of names) {
|
||||
if (!name.endsWith(".json")) continue;
|
||||
const id = name.slice(0, -".json".length);
|
||||
const meta = readHandoffMeta(id);
|
||||
if (!meta || meta.usedAt || !samePath(meta.worktree, worktree)) continue;
|
||||
const md = path.join(dir, id + ".md");
|
||||
if (!regularFile(md)) continue;
|
||||
let text;
|
||||
try {
|
||||
text = fs.readFileSync(md, "utf8");
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
out.push({
|
||||
id,
|
||||
title: docTitle(text) || meta.title || "",
|
||||
next: docNext(text),
|
||||
written: meta.written,
|
||||
spec: meta.spec ?? null,
|
||||
skill: meta.skill,
|
||||
workflow: meta.workflow,
|
||||
});
|
||||
}
|
||||
return out.sort((a, b) => String(b.written).localeCompare(String(a.written)));
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- remove */
|
||||
|
||||
/**
|
||||
* Delete one handoff, both files (or whichever one exists), for the
|
||||
* dashboard's Delete (`delete-handoff`). Only a handoff id; each file must be
|
||||
* a regular file, never a link, whose real folder is the handoffs folder.
|
||||
* Every refusal throws with the reason, and nothing is touched.
|
||||
*/
|
||||
export function removeHandoff(id) {
|
||||
if (!isHandoffId(id)) throw new Error(`not a handoff id: ${id}`);
|
||||
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
|
||||
const dir = handoffsDir();
|
||||
const names = [id + ".md", id + ".json"];
|
||||
const present = [];
|
||||
for (const name of names) {
|
||||
let st;
|
||||
try {
|
||||
st = fs.lstatSync(path.join(dir, name));
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (st.isSymbolicLink()) throw new Error(`${name} is a link, so it is not deleted from here`);
|
||||
if (!st.isFile()) throw new Error(`${name} is not a file`);
|
||||
present.push(name);
|
||||
}
|
||||
if (!present.length) throw new Error(`there is no handoff ${id}`);
|
||||
const realDir = fold(fs.realpathSync.native(dir));
|
||||
for (const name of present) {
|
||||
if (fold(path.dirname(fs.realpathSync.native(path.join(dir, name)))) !== realDir) {
|
||||
throw new Error(`${name} resolves outside the handoffs folder, so it is not deleted`);
|
||||
}
|
||||
}
|
||||
for (const name of present) fs.rmSync(path.join(dir, name));
|
||||
return { ok: true, removed: present };
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- sweep */
|
||||
|
||||
/**
|
||||
* Handoffs untouched for `maxAgeMs`, picked up or not: the `.json`'s mtime,
|
||||
* or the `.md`'s when there is no `.json`. Regular files with a handoff id
|
||||
* only, as staleScratch() does for the console folder.
|
||||
*/
|
||||
export function staleHandoffs(now, maxAgeMs) {
|
||||
const dir = handoffsDir();
|
||||
let names;
|
||||
try {
|
||||
names = fs.readdirSync(dir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const ids = new Set();
|
||||
for (const name of names) {
|
||||
const m = name.match(/^(.+)\.(md|json)$/);
|
||||
if (m && isHandoffId(m[1])) ids.add(m[1]);
|
||||
}
|
||||
const stale = [];
|
||||
for (const id of ids) {
|
||||
for (const ext of [".json", ".md"]) {
|
||||
let st;
|
||||
try {
|
||||
st = fs.lstatSync(path.join(dir, id + ext));
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (st.isFile() && now - st.mtimeMs > maxAgeMs) stale.push(id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return stale;
|
||||
}
|
||||
|
||||
// Every id re-checked against the same rule before anything is removed.
|
||||
export async function removeHandoffs(ids) {
|
||||
const dir = handoffsDir();
|
||||
const removed = [];
|
||||
for (const id of ids) {
|
||||
if (!isHandoffId(id)) continue;
|
||||
try {
|
||||
await fs.promises.rm(path.join(dir, id + ".md"), { force: true });
|
||||
await fs.promises.rm(path.join(dir, id + ".json"), { force: true });
|
||||
removed.push(id);
|
||||
} catch {}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
@@ -580,9 +580,10 @@ export async function removeScratch(consoleDir, names) {
|
||||
// protected files, its sessions dir (old sessions go one by one, by age) and,
|
||||
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
|
||||
// console, the launcher (bin/, launcher.json), the install record that
|
||||
// `plan2code update` reads (install.json) and the models the person added.
|
||||
// `plan2code update` reads (install.json), the models the person added and
|
||||
// the handoffs (old ones go one by one, by age, on open: handoffs.mjs).
|
||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs"]);
|
||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
||||
// folders hold files that live for milliseconds -- a held
|
||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
||||
|
||||
@@ -4,7 +4,7 @@ Workflow notes for `handoff`, part of the web console contract (`console.md`).
|
||||
|
||||
One gate: the next-task confirmation, then the document itself as a doc —
|
||||
that is what the person is there to download. Give it no `saved` and paste it
|
||||
as `md`: the handoff file often sits outside the project (the OS temp folder),
|
||||
as `md`: the handoff file lives in `~/.plan2code/handoffs/`, outside the project,
|
||||
where a `file` block is refused, and the download is the point. The finish carries no
|
||||
`command`: the doc download is the point, and the dashboard button and the
|
||||
"All done" line cover what comes next. Unless it is a pause, the finish carries
|
||||
|
||||
@@ -67,8 +67,8 @@ only ever be offered once nothing could come of it:
|
||||
"body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, see it running, or say what to change.",
|
||||
"verdicts": [
|
||||
{ "id": "review", "label": "Review the code first" },
|
||||
{ "id": "show", "label": "Show me it working" },
|
||||
{ "id": "approve", "label": "Approve this phase" },
|
||||
{ "id": "show", "label": "Show me it working" },
|
||||
{ "id": "changes", "label": "I want changes" }
|
||||
],
|
||||
"token": { "approve": "approved", "changes": "needs changes", "show": "show me" },
|
||||
|
||||
@@ -371,6 +371,16 @@ export function handoffShape(fin) {
|
||||
// sentence: nothing Pathfinder would read as asking for a brief.
|
||||
export const STOP_REPLY = "Stop here and save my place, so I can pick this up later.";
|
||||
|
||||
// The same request, with a handoff note written first. Same plain voice: the
|
||||
// reply is read by the agent, and a word like "brief" would send Pathfinder
|
||||
// off to write one.
|
||||
export const STOP_HANDOFF_REPLY = "Stop here, save my place and write a handoff, so the dashboard can pick this up later.";
|
||||
|
||||
/** The `__stop` action; `handoff: true` only when the handoff choice was pressed. */
|
||||
export function stopAction({ handoff } = {}) {
|
||||
return handoff ? { i: "__stop", type: "stop", handoff: true } : { i: "__stop", type: "stop" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a session-level button (Stop session, Back to the dashboard) cannot be
|
||||
* pressed right now, or null when it can. Both wait for the person's turn:
|
||||
@@ -813,7 +823,7 @@ const ON = { on: true };
|
||||
export const GIT_INIT_NOTE = "Not a git repository yet: it offers to start one";
|
||||
export const pendingNote = (n) => `${n} file${n === 1 ? "" : "s"} to commit`;
|
||||
const off = (reason) => ({ on: false, reason });
|
||||
const FIXED_REASON = "This bug is fixed. Delete it with ✕, or move it to specs--completed/.";
|
||||
export const FIXED_REASON = "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/.";
|
||||
|
||||
/**
|
||||
* The spec the picker opens on: the most recently touched one that is still
|
||||
@@ -955,12 +965,50 @@ export function deleteReply(spec) {
|
||||
|
||||
// What the delete dialog says about the spec, from the scan alone. `touched`
|
||||
// stays a number: the page formats it in the person's own locale.
|
||||
// A handoff on the dashboard (scan.handoffs). The page sends only the id; the
|
||||
// CLI reads the rest from the stored metadata. Plain wording, no em dashes:
|
||||
// these lines are read by the agent.
|
||||
export function pickupAction(h) {
|
||||
return { i: "__pickup", type: "pickup", handoff: h.id };
|
||||
}
|
||||
export function pickupReply(h) {
|
||||
return `Pick up the handoff "${h.title}" right here in this session.`;
|
||||
}
|
||||
export function deleteHandoffAction(h) {
|
||||
return { i: "__delete", type: "delete", handoff: h.id };
|
||||
}
|
||||
export function deleteHandoffReply(h) {
|
||||
return `Delete the handoff "${h.title}" for good, right here in this session.`;
|
||||
}
|
||||
export function handoffCopyText(file) {
|
||||
return `Read the handoff at ${file} and carry on with its Next task.`;
|
||||
}
|
||||
/** "just now", "12 min ago", "6 h ago", "3 days ago" for an ISO time. */
|
||||
export function handoffAge(written, now = Date.now()) {
|
||||
const t = Date.parse(written);
|
||||
if (!Number.isFinite(t)) return "";
|
||||
const mins = Math.max(0, Math.floor((now - t) / 60000));
|
||||
if (mins < 1) return "just now";
|
||||
if (mins < 60) return `${mins} min ago`;
|
||||
const hours = Math.floor(mins / 60);
|
||||
if (hours < 24) return `${hours} h ago`;
|
||||
const days = Math.floor(hours / 24);
|
||||
return `${days} day${days === 1 ? "" : "s"} ago`;
|
||||
}
|
||||
|
||||
// The line under a spec's name on its chip. A fixed bug's label already says
|
||||
// "Bug fixed", so the scan's "bug fixed" detail would only repeat it.
|
||||
export function chipDetail(spec) {
|
||||
return spec.state === "fixed" ? "" : spec.detail || "";
|
||||
}
|
||||
|
||||
export function deleteSummary(spec) {
|
||||
const label = SPEC_STATE_LABELS[spec.state] || spec.state || "";
|
||||
const detail = chipDetail(spec);
|
||||
const n = spec.files;
|
||||
return {
|
||||
folder: `${spec.dir}/`,
|
||||
stage: spec.detail ? `${label}: ${spec.detail}` : label,
|
||||
stage: detail ? `${label}: ${detail}` : label,
|
||||
files: Number.isInteger(n) ? `${n} file${n === 1 ? "" : "s"}` : "",
|
||||
touched: Number.isFinite(spec.touched) && spec.touched > 0 ? spec.touched : null,
|
||||
};
|
||||
|
||||
@@ -1761,6 +1761,9 @@ input[type="text"].invalid { border-color: var(--warn); }
|
||||
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
||||
/* A review card's approve verdict, before it is picked: the accent outline
|
||||
marks it as the main way forward. */
|
||||
.btn.is-approve { border-color: var(--accent); }
|
||||
/* Send glows and breathes while there is something to send: the steady
|
||||
--glow, plus a soft accent ring that spreads and fades. The ring is off
|
||||
under reduced motion, below; the glow stays. */
|
||||
@@ -2773,6 +2776,47 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.modal-why { margin: 14px 0 0; font-size: 13px; color: var(--warn); min-height: 1px; }
|
||||
.modal-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px; }
|
||||
|
||||
/* The Stop dialog's two ways out, stacked: the handoff first (the suggested
|
||||
one), the plain stop second, "Keep going" alone below. */
|
||||
.stop-choices { display: grid; gap: 10px; margin-top: 16px; }
|
||||
.stop-choice {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
padding: 12px 14px;
|
||||
text-align: left;
|
||||
font: inherit;
|
||||
color: var(--ink);
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: var(--radius);
|
||||
cursor: pointer;
|
||||
}
|
||||
.stop-choice:hover, .stop-choice.suggested { border-color: var(--accent); }
|
||||
.stop-choice:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.stop-choice:disabled { opacity: 0.6; cursor: default; }
|
||||
.stop-choice[hidden] { display: none; }
|
||||
.stop-choice-icon {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
border: 1px solid var(--rule-2);
|
||||
font-size: 13px;
|
||||
color: var(--accent);
|
||||
}
|
||||
.stop-choice-text { display: grid; gap: 2px; min-width: 0; }
|
||||
.stop-choice-title { font-weight: 600; font-size: 14px; }
|
||||
.stop-choice-detail { font-size: 12.5px; color: var(--ink-2); }
|
||||
.modal-actions:has(#stop-cancel) { justify-content: center; margin-top: 14px; }
|
||||
@media (max-width: 560px) {
|
||||
.modal-actions:has(#stop-cancel) .btn { width: 100%; }
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------- doc tools */
|
||||
|
||||
.doc-tools { display: flex; gap: 8px; margin-left: auto; flex: none; align-items: center; }
|
||||
@@ -3056,6 +3100,38 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
}
|
||||
.spec-chip:not(.is-sel) .spec-chip-state { color: var(--ink-3); }
|
||||
.spec-chip-detail { font-size: 11.5px; color: var(--ink-3); }
|
||||
/* A handoff in the picker: the same lozenge, dashed, in the stage colour. */
|
||||
.spec-chip.is-handoff { border-style: dashed; }
|
||||
.spec-chip.is-handoff .spec-chip-state, .spec-chip.is-handoff:not(.is-sel) .spec-chip-state { color: var(--stage); }
|
||||
.spec-chip.is-handoff.is-sel { border-style: solid; border-color: var(--stage); }
|
||||
.spec-chip.is-handoff.is-deleting { opacity: 0.5; }
|
||||
|
||||
/* What a picked handoff shows under the picker. */
|
||||
.handoff-preview {
|
||||
margin: 0 0 30px;
|
||||
padding: 18px 20px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--stage);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
.handoff-preview-title { font: 600 20px/1.25 var(--serif); margin: 0 0 4px; }
|
||||
.handoff-preview-meta { margin: 0 0 14px; font-size: 12.5px; color: var(--ink-3); }
|
||||
.handoff-preview-label {
|
||||
margin: 0 0 3px;
|
||||
font-size: 10.5px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--stage);
|
||||
}
|
||||
.handoff-preview-next { margin: 0 0 16px; font-size: 14px; color: var(--ink); }
|
||||
.handoff-preview-actions { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.handoff-preview-actions .btn.danger { margin-left: auto; }
|
||||
.modal.handoff-read { max-width: 720px; }
|
||||
.modal.handoff-read[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
||||
.handoff-body { flex: 1; min-height: 0; overflow-y: auto; margin-top: 8px; }
|
||||
.modal.handoff-read .modal-actions { flex: none; }
|
||||
|
||||
/* A spec's Delete button sits beside its chip, not inside it: a button cannot
|
||||
hold a button. Quiet until the chip is hovered or focused. */
|
||||
.spec-chip-wrap { position: relative; display: flex; }
|
||||
@@ -3085,6 +3161,28 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.spec-chip-del:hover { color: var(--warn); border-color: var(--warn); opacity: 1; }
|
||||
.spec-chip-del:focus-visible { outline: 2px solid var(--warn); outline-offset: 1px; }
|
||||
.spec-chip-del:disabled { cursor: default; opacity: 0.3; }
|
||||
/* A fixed bug's Delete is always shown, as a pill at the chip's bottom right;
|
||||
the chip makes room below its lines so the pill never covers the name. The
|
||||
chip's is-fixed dimming targets .spec-chip, so the pill keeps full strength. */
|
||||
.spec-chip-wrap.is-fixed .spec-chip { padding-right: 14px; padding-bottom: 36px; }
|
||||
.spec-chip-del-label {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
bottom: 8px;
|
||||
padding: 2px 10px;
|
||||
border: 1px solid var(--warn);
|
||||
border-radius: 999px;
|
||||
background: var(--panel);
|
||||
color: var(--warn);
|
||||
font: inherit;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
line-height: 1.5;
|
||||
cursor: pointer;
|
||||
}
|
||||
.spec-chip-del-label:hover:not(:disabled) { background: var(--warn-soft); }
|
||||
.spec-chip-del-label:focus-visible { outline: 2px solid var(--warn); outline-offset: 1px; }
|
||||
.spec-chip-del-label:disabled { cursor: default; opacity: 0.4; }
|
||||
.spec-chip-wrap.is-deleting .spec-chip { opacity: 0.5; }
|
||||
.delete-facts { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; margin: 14px 0 0; font-size: 13.5px; }
|
||||
.delete-facts dt { color: var(--ink-3); }
|
||||
|
||||
+300
-32
@@ -9,7 +9,7 @@
|
||||
// that is local and reversible. For someone who has never used a tool like
|
||||
// this, that reversibility is the whole point.
|
||||
|
||||
import { md, el, copyButton, selectContents } from "./render.js";
|
||||
import { md, mdInto, el, copyButton, selectContents } from "./render.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, SOUND_EVENTS, cardWidth, soundKey, soundPrefs } from "./palette.js";
|
||||
import { activityLabel, workingLine } from "./labels.js";
|
||||
import { playWake } from "./boot.js";
|
||||
@@ -46,6 +46,13 @@ import {
|
||||
launchTarget,
|
||||
deleteAction,
|
||||
deleteReply,
|
||||
pickupAction,
|
||||
pickupReply,
|
||||
deleteHandoffAction,
|
||||
deleteHandoffReply,
|
||||
handoffCopyText,
|
||||
handoffAge,
|
||||
chipDetail,
|
||||
deleteSummary,
|
||||
isDeletableSpecDir,
|
||||
MAX_ATTACHMENTS,
|
||||
@@ -71,6 +78,8 @@ import {
|
||||
STALE_MS,
|
||||
startPose,
|
||||
STOP_REPLY,
|
||||
STOP_HANDOFF_REPLY,
|
||||
stopAction,
|
||||
sentAnswer,
|
||||
agentRepliedAfterSend,
|
||||
indentReply,
|
||||
@@ -831,6 +840,22 @@ const selSpec = () => {
|
||||
return specs.find((s) => s.dir === local.specSel) || null;
|
||||
};
|
||||
|
||||
// This checkout's unused handoffs (scan.handoffs, newest first). A handoff is
|
||||
// picked in the same chip row as a spec, stored as `specSel = "handoff:<id>"`;
|
||||
// selSpec() then reads as "no spec", and selHandoff() is the handoff itself,
|
||||
// or null once it is gone from the scan (which also drops the stale pick).
|
||||
const handoffList = () => {
|
||||
const sc = scan();
|
||||
return sc && Array.isArray(sc.handoffs) ? sc.handoffs : [];
|
||||
};
|
||||
const selHandoff = () => {
|
||||
if (typeof local.specSel !== "string" || !local.specSel.startsWith("handoff:")) return null;
|
||||
const id = local.specSel.slice("handoff:".length);
|
||||
const h = handoffList().find((x) => x.id === id) || null;
|
||||
if (!h) delete local.specSel;
|
||||
return h;
|
||||
};
|
||||
|
||||
// The review a finished build offers, and where it has got to:
|
||||
// "open" on offer, and a press would reach the agent
|
||||
// "asked" pressed, and the agent has not taken it up yet
|
||||
@@ -3098,6 +3123,10 @@ function openUpdateModal() {
|
||||
|
||||
function renderDashboard(main) {
|
||||
maybeWake();
|
||||
// First, so nothing below reads a pick whose handoff has left the scan, and
|
||||
// a delete the agent's rescan has finished stops holding the buttons.
|
||||
selHandoff();
|
||||
settleDeleting();
|
||||
const menu = (S && S.menu) || {};
|
||||
const wrap = el("div", "dash");
|
||||
if (needsRoleNudge(looks)) wrap.appendChild(roleNudge());
|
||||
@@ -3159,7 +3188,17 @@ function renderDashboard(main) {
|
||||
}
|
||||
|
||||
const specs = specList();
|
||||
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
|
||||
if (specs.length || handoffList().length) wrap.appendChild(renderSpecPicker(specs));
|
||||
const handoff = selHandoff();
|
||||
if (handoff) {
|
||||
// A handoff is picked up, not launched: its skill and spec come from its
|
||||
// own record, so the skill cards and their toggle have nothing to say.
|
||||
if (!local.launching && !launchScoping && scopeMine !== "") syncWorkspaceScope();
|
||||
wrap.appendChild(renderHandoffPreview(handoff));
|
||||
main.appendChild(wrap);
|
||||
queueMicrotask(maybeWelcome);
|
||||
return;
|
||||
}
|
||||
wrap.appendChild(hideUnavailableToggle());
|
||||
// Only when this tab's own pick moved: another tab changing the scope
|
||||
// sends a frame here too, and re-asserting this tab's pick on every render
|
||||
@@ -3678,13 +3717,18 @@ function hideUnavailableToggle() {
|
||||
no send — so it costs nothing to change your mind. */
|
||||
function renderSpecPicker(specs) {
|
||||
const sel = selSpec();
|
||||
const handoffs = handoffList();
|
||||
const pickedHandoff = selHandoff();
|
||||
const box = el("section", "spec-pick");
|
||||
box.appendChild(el("h3", "dash-group-title", "Pick up a spec, or start fresh"));
|
||||
box.appendChild(
|
||||
el("h3", "dash-group-title", handoffs.length ? "Pick up a spec or a handoff, or start fresh" : "Pick up a spec, or start fresh")
|
||||
);
|
||||
const row = el("div", "spec-row");
|
||||
|
||||
const scratch = el("button", "spec-chip" + (sel ? "" : " is-sel"));
|
||||
const scratchOn = !sel && !pickedHandoff;
|
||||
const scratch = el("button", "spec-chip" + (scratchOn ? " is-sel" : ""));
|
||||
scratch.type = "button";
|
||||
scratch.setAttribute("aria-current", String(!sel));
|
||||
scratch.setAttribute("aria-current", String(scratchOn));
|
||||
scratch.appendChild(el("span", "spec-chip-name", "Start from scratch"));
|
||||
scratch.appendChild(el("span", "spec-chip-state", "a new idea"));
|
||||
scratch.addEventListener("click", () => {
|
||||
@@ -3695,13 +3739,6 @@ function renderSpecPicker(specs) {
|
||||
});
|
||||
row.appendChild(scratch);
|
||||
|
||||
// A delete in flight ends when the agent's rescan lands (a new scan), gone
|
||||
// or refused: either way the picker below is the truth again.
|
||||
const sc = scan();
|
||||
if (local.deleting && sc && sc.at !== local.deleting.scanAt) {
|
||||
local.deleting = null;
|
||||
save();
|
||||
}
|
||||
for (const spec of specs) {
|
||||
const on = sel && sel.dir === spec.dir;
|
||||
// A fixed bug is finished: hidden while unavailable workflows are, dimmed
|
||||
@@ -3715,7 +3752,8 @@ function renderSpecPicker(specs) {
|
||||
b.setAttribute("aria-current", String(Boolean(on)));
|
||||
b.appendChild(el("span", "spec-chip-name", spec.name));
|
||||
b.appendChild(el("span", "spec-chip-state", deleting ? "Deleting…" : SPEC_STATE_LABELS[spec.state] || spec.state));
|
||||
if (spec.detail) b.appendChild(el("span", "spec-chip-detail", spec.detail));
|
||||
const detail = chipDetail(spec);
|
||||
if (detail) b.appendChild(el("span", "spec-chip-detail", detail));
|
||||
b.addEventListener("click", () => {
|
||||
local.specSel = spec.dir;
|
||||
save();
|
||||
@@ -3724,7 +3762,9 @@ function renderSpecPicker(specs) {
|
||||
});
|
||||
wrap.appendChild(b);
|
||||
if (isDeletableSpecDir(spec.dir)) {
|
||||
const del = el("button", "spec-chip-del", "✕");
|
||||
// A fixed bug is done with, so its Delete is a visible button rather
|
||||
// than the hover ✕ every other spec has.
|
||||
const del = fixed ? el("button", "spec-chip-del-label", "Delete") : el("button", "spec-chip-del", "✕");
|
||||
del.type = "button";
|
||||
del.title = `Delete ${spec.dir}/`;
|
||||
del.setAttribute("aria-label", `Delete the spec ${spec.name}`);
|
||||
@@ -3734,10 +3774,139 @@ function renderSpecPicker(specs) {
|
||||
}
|
||||
row.appendChild(wrap);
|
||||
}
|
||||
// Handoffs follow the specs: dashed chips, the state word is "Handoff".
|
||||
for (const h of handoffs) {
|
||||
const on = Boolean(pickedHandoff && pickedHandoff.id === h.id);
|
||||
const deleting = Boolean(local.deleting && local.deleting.dir === "handoff:" + h.id);
|
||||
const b = el("button", "spec-chip is-handoff" + (on ? " is-sel" : "") + (deleting ? " is-deleting" : ""));
|
||||
b.type = "button";
|
||||
b.setAttribute("aria-current", String(on));
|
||||
b.appendChild(el("span", "spec-chip-name", h.title || "Handoff"));
|
||||
b.appendChild(el("span", "spec-chip-state", deleting ? "Deleting…" : "Handoff"));
|
||||
b.appendChild(el("span", "spec-chip-detail", handoffAge(h.written)));
|
||||
b.addEventListener("click", () => {
|
||||
local.specSel = "handoff:" + h.id;
|
||||
save();
|
||||
render();
|
||||
});
|
||||
row.appendChild(b);
|
||||
}
|
||||
box.appendChild(row);
|
||||
return box;
|
||||
}
|
||||
|
||||
// A delete in flight ends when the agent's rescan lands (a new scan), gone
|
||||
// or refused: either way the picker is the truth again.
|
||||
function settleDeleting() {
|
||||
const sc = scan();
|
||||
if (local.deleting && sc && sc.at !== local.deleting.scanAt) {
|
||||
local.deleting = null;
|
||||
save();
|
||||
}
|
||||
}
|
||||
|
||||
// What a picked handoff shows: where it came from and its Next task, with the
|
||||
// four things to do with it.
|
||||
function renderHandoffPreview(h) {
|
||||
const box = el("section", "handoff-preview");
|
||||
box.appendChild(el("h3", "handoff-preview-title", h.title || "Handoff"));
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === h.skill);
|
||||
const meta = [
|
||||
"Written " + (h.written ? new Date(h.written).toLocaleString() : "at an unknown time"),
|
||||
h.spec ? "spec " + h.spec.replace(/^specs\//, "") : "no spec",
|
||||
"from " + (entry ? entry.title : h.skill),
|
||||
];
|
||||
box.appendChild(el("p", "handoff-preview-meta", meta.join(" · ")));
|
||||
if (h.next) {
|
||||
box.appendChild(el("p", "handoff-preview-label", "Next task"));
|
||||
box.appendChild(el("p", "handoff-preview-next", h.next));
|
||||
}
|
||||
const busy = Boolean(local.launching || local.deleting) || gone || pendingResult;
|
||||
const actions = el("div", "handoff-preview-actions");
|
||||
const go = el("button", "btn primary", "Pick it up here");
|
||||
go.type = "button";
|
||||
go.disabled = busy;
|
||||
go.addEventListener("click", () => pickUpHandoff(h));
|
||||
const read = el("button", "btn", "Read it all");
|
||||
read.type = "button";
|
||||
read.addEventListener("click", () => readHandoff(h));
|
||||
const copy = el("button", "btn", "Copy for a new conversation");
|
||||
copy.type = "button";
|
||||
copy.addEventListener("click", () => {
|
||||
const dir = (scan() && scan().handoffsDir) || "";
|
||||
const sep = dir.includes("\\") ? "\\" : "/";
|
||||
const file = dir ? dir.replace(/[\\/]+$/, "") + sep + h.id + ".md" : h.id + ".md";
|
||||
copyHandoffText(handoffCopyText(file), copy);
|
||||
});
|
||||
const del = el("button", "btn danger", "Delete");
|
||||
del.type = "button";
|
||||
del.disabled = busy;
|
||||
del.addEventListener("click", () => openHandoffDelete(h));
|
||||
actions.append(go, read, copy, del);
|
||||
box.appendChild(actions);
|
||||
return box;
|
||||
}
|
||||
|
||||
// The prompt that sends a new conversation to the handoff. A refused
|
||||
// clipboard gets a plain word on the button instead of a silent nothing.
|
||||
async function copyHandoffText(text, button) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
button.textContent = "Copied";
|
||||
} catch {
|
||||
button.textContent = "Copy was refused";
|
||||
}
|
||||
setTimeout(() => (button.textContent = "Copy for a new conversation"), 1500);
|
||||
}
|
||||
|
||||
// Pick it up here: a hop like a card launch. The page sends only the id; the
|
||||
// CLI reads the stored skill and spec, marks the handoff used and falls back
|
||||
// to Quick Task if either is gone.
|
||||
async function pickUpHandoff(h) {
|
||||
if (gone || pendingResult || local.launching || finish()) return;
|
||||
launchScoping = true;
|
||||
await syncWorkspaceScope(h.spec || "");
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [pickupAction(h)], reply: pickupReply(h) }),
|
||||
});
|
||||
if (res.status === 409) {
|
||||
launchScoping = false;
|
||||
pendingResult = true;
|
||||
banner("Your last pick is still being picked up. One moment.", "info");
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
sound("startSkill");
|
||||
local.launching = { skill: h.skill, title: h.title || "the handoff", at: Date.now() };
|
||||
launchScoping = false;
|
||||
pendingResult = true;
|
||||
save();
|
||||
render();
|
||||
} catch {
|
||||
launchScoping = false;
|
||||
banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||
}
|
||||
}
|
||||
|
||||
// Read it all: the document, in a dialog, from /handoff?id= (served only for
|
||||
// an id the dashboard's own scan listed).
|
||||
async function readHandoff(h) {
|
||||
$("handoff-title").textContent = h.title || "Handoff";
|
||||
const body = $("handoff-body");
|
||||
body.replaceChildren(el("p", "md-p", "Reading…"));
|
||||
$("handoff-modal").showModal();
|
||||
try {
|
||||
const res = await fetch("/handoff?id=" + encodeURIComponent(h.id), { cache: "no-store" });
|
||||
if (res.status !== 200) throw new Error(String(res.status));
|
||||
mdInto(body, await res.text());
|
||||
} catch {
|
||||
body.replaceChildren(el("p", "md-p", "This handoff could not be read."));
|
||||
}
|
||||
}
|
||||
|
||||
function dashCard(entry, menu) {
|
||||
const presentation = cardPresentation(entry, scan(), selSpec(), menu);
|
||||
// The agent's `recommend` and detail describe the initially selected spec.
|
||||
@@ -5248,8 +5417,13 @@ function buildReview(card, item, staged) {
|
||||
for (const v of verdicts) {
|
||||
const on = staged && staged.verdict === v.id;
|
||||
// A picked danger verdict stays red (filled), so choosing "Abort" never
|
||||
// reads like choosing the safe default.
|
||||
const b = el("button", "btn" + (on ? (v.danger ? " danger is-on" : " primary") : v.danger ? " danger" : ""), verdictText(v));
|
||||
// reads like choosing the safe default. An unpicked approve is outlined
|
||||
// in the accent, so the main way forward stands out.
|
||||
const b = el(
|
||||
"button",
|
||||
"btn" + (on ? (v.danger ? " danger is-on" : " primary") : v.danger ? " danger" : v.id === "approve" ? " is-approve" : ""),
|
||||
verdictText(v)
|
||||
);
|
||||
b.type = "button";
|
||||
b.addEventListener("click", () =>
|
||||
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "review", verdict: v.id }))
|
||||
@@ -7550,13 +7724,58 @@ function openHomeConfirm() {
|
||||
|
||||
// The picker's Delete: a dialog in two steps. The first says what goes and
|
||||
// that it is for good; "Delete this spec…" then reveals the second, which
|
||||
// enables the final button only once the spec's name is typed exactly.
|
||||
// enables the final button only once the spec's name is typed exactly. A
|
||||
// fixed bug skips the second step: its first press sends the delete.
|
||||
// Cancel, Escape or a click on Keep it at either step changes nothing.
|
||||
let deleteTarget = null;
|
||||
// The spec warning as index.html writes it, kept so a fixed bug's wording
|
||||
// never sticks for the next spec.
|
||||
let deleteWarnDefault = null;
|
||||
|
||||
// A handoff's Delete reuses the same dialog in one step: no name to type, and
|
||||
// the warning says where the file lives instead of what git does not track.
|
||||
function openHandoffDelete(h) {
|
||||
if (gone || pendingResult || local.launching || local.deleting) return;
|
||||
deleteTarget = { handoff: h };
|
||||
$("delete-title").textContent = "Delete this handoff?";
|
||||
$("delete-blurb").textContent = "This handoff will be deleted from ~/.plan2code/handoffs/.";
|
||||
$("delete-warn").hidden = true;
|
||||
$("delete-warn-handoff").hidden = false;
|
||||
const facts = $("delete-facts");
|
||||
facts.replaceChildren();
|
||||
const fact = (term, value) => {
|
||||
if (!value) return;
|
||||
facts.appendChild(el("dt", "", term));
|
||||
facts.appendChild(el("dd", "", value));
|
||||
};
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === h.skill);
|
||||
fact("Handoff", h.title || h.id);
|
||||
fact("Written", h.written ? new Date(h.written).toLocaleString() : "");
|
||||
fact("Spec", h.spec ? h.spec.replace(/^specs\//, "") : "");
|
||||
fact("From", entry ? entry.title : h.skill);
|
||||
$("delete-confirm").hidden = true;
|
||||
const go = $("delete-go");
|
||||
go.textContent = "Delete it";
|
||||
go.classList.add("is-on");
|
||||
go.disabled = false;
|
||||
$("delete-modal").showModal();
|
||||
}
|
||||
|
||||
function openDeleteConfirm(spec) {
|
||||
if (!isDeletableSpecDir(spec.dir) || gone || pendingResult || local.launching || local.deleting) return;
|
||||
deleteTarget = spec;
|
||||
// A fixed bug is finished work: one confirm, and a warning that says so.
|
||||
const fixed = spec.state === "fixed";
|
||||
$("delete-title").textContent = "Delete this spec?";
|
||||
const warn = $("delete-warn");
|
||||
if (!deleteWarnDefault) deleteWarnDefault = [...warn.childNodes].map((n) => n.cloneNode(true));
|
||||
warn.replaceChildren(
|
||||
...(fixed
|
||||
? ["The bug is fixed, so this only clears the write-up. ", el("code", "", "specs/"), " is not tracked by git, so it cannot be brought back."]
|
||||
: deleteWarnDefault.map((n) => n.cloneNode(true)))
|
||||
);
|
||||
warn.hidden = false;
|
||||
$("delete-warn-handoff").hidden = true;
|
||||
const sum = deleteSummary(spec);
|
||||
$("delete-blurb").textContent = `Everything in ${sum.folder} will be deleted from this project.`;
|
||||
const facts = $("delete-facts");
|
||||
@@ -7575,8 +7794,8 @@ function openDeleteConfirm(spec) {
|
||||
$("delete-name").value = "";
|
||||
$("delete-confirm").hidden = true;
|
||||
const go = $("delete-go");
|
||||
go.textContent = "Delete this spec…";
|
||||
go.classList.remove("is-on");
|
||||
go.textContent = fixed ? "Delete it" : "Delete this spec…";
|
||||
go.classList.toggle("is-on", fixed);
|
||||
go.disabled = false;
|
||||
$("delete-modal").showModal();
|
||||
}
|
||||
@@ -7584,6 +7803,8 @@ function openDeleteConfirm(spec) {
|
||||
function deleteStep() {
|
||||
const go = $("delete-go");
|
||||
if (!deleteTarget) return;
|
||||
if (deleteTarget.handoff) return sendDeleteHandoff(deleteTarget.handoff);
|
||||
if (deleteTarget.state === "fixed") return sendDelete(deleteTarget);
|
||||
if ($("delete-confirm").hidden) {
|
||||
$("delete-confirm").hidden = false;
|
||||
go.textContent = "Delete for good";
|
||||
@@ -7596,6 +7817,38 @@ function deleteStep() {
|
||||
sendDelete(deleteTarget);
|
||||
}
|
||||
|
||||
async function sendDeleteHandoff(h) {
|
||||
const go = $("delete-go");
|
||||
go.disabled = true;
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [deleteHandoffAction(h)], reply: deleteHandoffReply(h) }),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
const sc = scan();
|
||||
local.deleting = { dir: "handoff:" + h.id, scanAt: sc ? sc.at : null };
|
||||
if (local.specSel === "handoff:" + h.id) delete local.specSel;
|
||||
pendingResult = true;
|
||||
save();
|
||||
$("delete-modal").close();
|
||||
} catch (err) {
|
||||
$("delete-modal").close();
|
||||
if (err && err.pending) pendingResult = true;
|
||||
banner(
|
||||
err && err.pending
|
||||
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
|
||||
: "That did not go through. Nothing was deleted; try again.",
|
||||
"warn"
|
||||
);
|
||||
} finally {
|
||||
deleteTarget = null;
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
async function sendDelete(spec) {
|
||||
const go = $("delete-go");
|
||||
go.disabled = true;
|
||||
@@ -7684,29 +7937,42 @@ function openStopConfirm() {
|
||||
}
|
||||
const n = Object.keys(local.staged).length + pendingNotes().length;
|
||||
const warn = stopWarning();
|
||||
const dash = isDashboard();
|
||||
$("stop-blurb").textContent =
|
||||
(n === 1 ? "The answer you have ready goes with it. " : n ? `The ${n} answers you have ready go with it. ` : "") +
|
||||
(isDashboard()
|
||||
? "Nothing has started yet, so there is nothing to save: this just ends the console session."
|
||||
: warn
|
||||
? "Plan2Code stops here."
|
||||
: "Plan2Code will save your place and give you a command to pick this up later, in a new conversation.");
|
||||
(dash ? "Nothing has started yet, so there is nothing to save: this just ends the console session." : "");
|
||||
$("stop-blurb").hidden = !$("stop-blurb").textContent;
|
||||
$("stop-warn").hidden = !warn;
|
||||
$("stop-warn").textContent = warn;
|
||||
$("stop-go").textContent = isDashboard() ? "Stop" : warn ? "Stop anyway" : "Stop and save";
|
||||
// The dashboard has nothing to hand off: one plain Stop. Elsewhere both
|
||||
// choices show, and "Just stop and save" turns into "Stop anyway" where
|
||||
// nothing is saved yet.
|
||||
$("stop-handoff").hidden = dash;
|
||||
const title = $("stop-go").querySelector(".stop-choice-title");
|
||||
const detail = $("stop-go").querySelector(".stop-choice-detail");
|
||||
if (dash) {
|
||||
title.textContent = "Stop";
|
||||
detail.textContent = "Ends the console session.";
|
||||
} else if (warn) {
|
||||
title.textContent = "Stop anyway";
|
||||
detail.textContent = "Ends the session now. What the warning above names is not kept.";
|
||||
} else {
|
||||
title.textContent = "Just stop and save";
|
||||
detail.textContent = "Saves what this step keeps on disk and gives you a command to resume. What we talked about is not kept.";
|
||||
}
|
||||
$("stop-modal").showModal();
|
||||
}
|
||||
|
||||
async function stopSession() {
|
||||
const go = $("stop-go");
|
||||
go.disabled = true;
|
||||
async function stopSession(handoff = false) {
|
||||
const buttons = [$("stop-handoff"), $("stop-go")];
|
||||
for (const b of buttons) b.disabled = true;
|
||||
const payload = stagedPayload();
|
||||
payload.actions.push({ i: "__stop", type: "stop" });
|
||||
payload.actions.push(stopAction({ handoff }));
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, STOP_REPLY].join("\n") }),
|
||||
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, handoff ? STOP_HANDOFF_REPLY : STOP_REPLY].join("\n") }),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
@@ -7725,7 +7991,7 @@ async function stopSession() {
|
||||
"warn"
|
||||
);
|
||||
} finally {
|
||||
go.disabled = false;
|
||||
for (const b of buttons) b.disabled = false;
|
||||
render();
|
||||
}
|
||||
}
|
||||
@@ -8299,6 +8565,7 @@ function openHelpOn(id) {
|
||||
$("btn-home").addEventListener("click", openHomeConfirm);
|
||||
$("update-done").addEventListener("click", () => $("update-modal").close());
|
||||
$("delete-cancel").addEventListener("click", () => $("delete-modal").close());
|
||||
$("handoff-close").addEventListener("click", () => $("handoff-modal").close());
|
||||
$("delete-go").addEventListener("click", deleteStep);
|
||||
$("delete-name").addEventListener("input", () => {
|
||||
$("delete-go").disabled = !deleteTarget || $("delete-name").value.trim() !== deleteTarget.name;
|
||||
@@ -8316,7 +8583,8 @@ $("home-cancel").addEventListener("click", () => $("home-modal").close());
|
||||
$("home-go").addEventListener("click", goHome);
|
||||
$("btn-stop").addEventListener("click", openStopConfirm);
|
||||
$("stop-cancel").addEventListener("click", () => $("stop-modal").close());
|
||||
$("stop-go").addEventListener("click", stopSession);
|
||||
$("stop-handoff").addEventListener("click", () => stopSession(true));
|
||||
$("stop-go").addEventListener("click", () => stopSession(false));
|
||||
$("stopping-hide").addEventListener("click", () => {
|
||||
stoppingHidden = true;
|
||||
$("stopping-modal").close();
|
||||
|
||||
@@ -1661,6 +1661,23 @@
|
||||
<strong>Hide unavailable workflows</strong>, under the picker, hides
|
||||
them instead. It is on to begin with, and remembered on this machine.
|
||||
</p>
|
||||
<p>
|
||||
The <strong>✕</strong> on a spec deletes its folder, after two steps:
|
||||
one says what goes, the other wants the spec's name typed. A fixed
|
||||
bug has its own <strong>Delete</strong> button at the bottom of its
|
||||
chip instead, and needs just one confirm, since the work is done.
|
||||
</p>
|
||||
<p>
|
||||
A <strong>Handoff</strong> is a note a step left when you stopped it
|
||||
with a handoff. It shows as a dashed chip after the specs. Pick one
|
||||
and the cards give way to a preview with its Next task and four
|
||||
buttons: <strong>Pick it up here</strong> carries on in the same step
|
||||
and spec, <strong>Read it all</strong> shows the whole note,
|
||||
<strong>Copy for a new conversation</strong> puts a ready prompt on
|
||||
the clipboard, and <strong>Delete</strong> removes it. A picked-up
|
||||
handoff drops off the list, but stays in
|
||||
<code>~/.plan2code/handoffs/</code> until the 30-day sweep.
|
||||
</p>
|
||||
<h4>The Suggested flag</h4>
|
||||
<p>
|
||||
One card may carry a <strong>Suggested</strong> flag: where Plan2Code
|
||||
@@ -2092,8 +2109,16 @@
|
||||
through writing your answers down.
|
||||
</li>
|
||||
<li>
|
||||
It asks first. <strong>Keep going</strong> backs out;
|
||||
<strong>Stop and save</strong> stops.
|
||||
It asks first, and offers two ways to stop.
|
||||
<strong>Stop with a handoff</strong> saves your place and writes a
|
||||
note the dashboard can offer to pick up later;
|
||||
<strong>Just stop and save</strong> saves what the step keeps on
|
||||
disk and gives you a command to resume, without the conversation;
|
||||
<strong>Keep going</strong> backs out.
|
||||
</li>
|
||||
<li>
|
||||
A handoff lands in <code>~/.plan2code/handoffs/</code> and shows on
|
||||
the dashboard, next to your specs, until you use or delete it.
|
||||
</li>
|
||||
<li>
|
||||
At points where nothing is saved yet, such as early in a plan, the
|
||||
@@ -2245,7 +2270,9 @@
|
||||
that folder is usually gitignored and git can't restore it. It
|
||||
shows each one with its size, and <strong>Delete these</strong>
|
||||
removes exactly that list. Your preferences, saved folders, models,
|
||||
the launcher and the session you are in always stay.
|
||||
the launcher and the session you are in always stay, and the
|
||||
<code>handoffs/</code> folder is Plan2Code's own, so it is never
|
||||
offered for removal.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Back to default</strong> puts everything back as it was, and
|
||||
@@ -2296,7 +2323,10 @@
|
||||
this machine who has it can open the session.
|
||||
</p>
|
||||
<h4>What is kept, and where</h4>
|
||||
<p>Everything lives under <code>~/.plan2code/console/</code> in your home folder:</p>
|
||||
<p>
|
||||
Everything lives in your home folder, under
|
||||
<code>~/.plan2code/console/</code> unless noted:
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
each session's questions, your drafts and your answers, in
|
||||
@@ -2314,7 +2344,13 @@
|
||||
</li>
|
||||
<li>
|
||||
your Subagents switch for each project and skill, in
|
||||
<code>subagents.json</code>.
|
||||
<code>subagents.json</code>;
|
||||
</li>
|
||||
<li>
|
||||
handoffs you save when you stop or with the Handoff skill, in
|
||||
<code>~/.plan2code/handoffs/</code>, one <code>.md</code> and one
|
||||
<code>.json</code> each, removed after the same
|
||||
<span data-fact="cleanupDays">30</span> days.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
@@ -2585,20 +2621,37 @@
|
||||
<!-- Only when stopping now would lose answers. A button that says it
|
||||
saves has to be true about the times it cannot. -->
|
||||
<p class="modal-why" id="stop-warn" hidden></p>
|
||||
<div class="stop-choices">
|
||||
<button type="button" class="stop-choice suggested" id="stop-handoff">
|
||||
<span class="stop-choice-icon" aria-hidden="true">✎</span>
|
||||
<span class="stop-choice-text">
|
||||
<span class="stop-choice-title">Stop with a handoff</span>
|
||||
<span class="stop-choice-detail">Saves your place and writes a handoff note. Next time the dashboard offers to pick it up right where this left off.</span>
|
||||
</span>
|
||||
</button>
|
||||
<button type="button" class="stop-choice" id="stop-go">
|
||||
<span class="stop-choice-icon" aria-hidden="true">■</span>
|
||||
<span class="stop-choice-text">
|
||||
<span class="stop-choice-title">Just stop and save</span>
|
||||
<span class="stop-choice-detail">Saves what this step keeps on disk and gives you a command to resume. What we talked about is not kept.</span>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="stop-cancel">Keep going</button>
|
||||
<button type="button" class="btn primary" id="stop-go">Stop and save</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- Deleting a spec from the dashboard's picker. Two deliberate steps: the
|
||||
first says what goes and that it is for good, the second wants the
|
||||
spec's name typed. The page only asks; the agent deletes. -->
|
||||
spec's name typed. A fixed bug takes the first step only. The page
|
||||
only asks; the agent deletes. -->
|
||||
<dialog class="modal" id="delete-modal" aria-labelledby="delete-title">
|
||||
<h2 id="delete-title">Delete this spec?</h2>
|
||||
<p class="modal-blurb" id="delete-blurb"></p>
|
||||
<dl class="delete-facts" id="delete-facts"></dl>
|
||||
<p class="modal-why" id="delete-warn">This is permanent. <code>specs/</code> is not tracked by git, so nothing can bring these files back.</p>
|
||||
<p class="modal-why" id="delete-warn-handoff" hidden>Handoffs are not kept anywhere else.</p>
|
||||
<div class="delete-confirm" id="delete-confirm" hidden>
|
||||
<label for="delete-name">To delete it for good, type <strong id="delete-name-hint"></strong></label>
|
||||
<input type="text" id="delete-name" autocomplete="off" spellcheck="false" />
|
||||
@@ -2609,6 +2662,16 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- A handoff's whole document, from the dashboard's "Read it all". Escape
|
||||
closes it; the body is filled by the page with rendered markdown. -->
|
||||
<dialog class="modal handoff-read" id="handoff-modal" aria-labelledby="handoff-title">
|
||||
<h2 id="handoff-title">Handoff</h2>
|
||||
<div class="handoff-body md" id="handoff-body"></div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="handoff-close">Close</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<dialog class="modal" id="home-modal" aria-labelledby="home-title">
|
||||
<h2 id="home-title">Leave this workflow?</h2>
|
||||
<p class="modal-blurb" id="home-blurb"></p>
|
||||
|
||||
@@ -75,6 +75,7 @@ import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
||||
import { checkForUpdate } from "./update-check.mjs";
|
||||
import { handoffsDir, isHandoffId } from "./handoffs.mjs";
|
||||
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
@@ -1211,6 +1212,21 @@ const server = http.createServer((req, res) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// A handoff's document, read-only, for the dashboard's "Read it all". Only a
|
||||
// dashboard serves it, and only an id its own scan listed: a used or unknown
|
||||
// id, or anything that is not a bare handoff id, is a 404.
|
||||
if (pathname === "/handoff" && req.method === "GET") {
|
||||
const state = readState() || {};
|
||||
const id = url.searchParams.get("id");
|
||||
const listed = state.workflow === "dashboard" && isHandoffId(id) && (state.scan?.handoffs || []).some((h) => h && h.id === id);
|
||||
if (!listed) return send(res, 404, "", "text/plain");
|
||||
fs.readFile(path.join(handoffsDir(), id + ".md"), "utf8", (err, text) => {
|
||||
if (err) return send(res, 404, "", "text/plain");
|
||||
send(res, 200, text, "text/markdown; charset=utf-8", { "cache-control": "no-store" });
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/version" && req.method === "GET") {
|
||||
const version = installedVersion();
|
||||
if (version) return json(res, 200, { version, latest: updateLatest });
|
||||
|
||||
Reference in new issue
Block a user