From 1877ca1fa7de8600c9bc26037cdc29f5f750ec54 Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Wed, 7 Oct 2026 23:13:04 -0700 Subject: [PATCH] Stop tracking skills/ build output, rebuilt by the installer instead AI Assisted --- skills/plan2code-0-pathfinder/SKILL.md | 174 - .../references/brief.md | 102 - .../references/chart.md | 691 -- .../references/github-issues.md | 474 - .../references/grilling.md | 388 - .../references/handoff.md | 423 - .../references/questions.md | 47 - .../references/resolve.md | 566 -- .../references/trail.md | 86 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - .../plan2code-0-pathfinder/scripts/common.mjs | 247 - .../scripts/pathfinder.mjs | 1294 --- .../scripts/version.json | 22 - skills/plan2code-1-plan/SKILL.md | 305 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - skills/plan2code-1-plan/scripts/common.mjs | 247 - skills/plan2code-1-plan/scripts/specs.mjs | 676 -- skills/plan2code-1-plan/scripts/version.json | 22 - skills/plan2code-1b-revise-plan/SKILL.md | 249 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - .../scripts/common.mjs | 247 - .../scripts/specs.mjs | 676 -- .../scripts/version.json | 22 - skills/plan2code-2-document/SKILL.md | 275 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - .../plan2code-2-document/scripts/common.mjs | 247 - skills/plan2code-2-document/scripts/specs.mjs | 676 -- .../plan2code-2-document/scripts/version.json | 22 - skills/plan2code-3-implement-review/SKILL.md | 109 - .../references/dimensions.md | 191 - .../references/false-positives.md | 105 - .../references/implement.md | 256 - .../references/review.md | 205 - .../references/session-end.md | 18 - .../references/verification-protocol.md | 72 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - .../scripts/commit-msg.mjs | 120 - .../scripts/common.mjs | 247 - .../scripts/review-scope.mjs | 138 - .../scripts/specs.mjs | 676 -- .../scripts/version.json | 22 - skills/plan2code-3-implement/SKILL.md | 262 - .../references/dimensions.md | 191 - .../references/false-positives.md | 105 - .../references/review.md | 205 - .../references/session-end.md | 18 - .../references/verification-protocol.md | 72 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - .../scripts/commit-msg.mjs | 120 - .../plan2code-3-implement/scripts/common.mjs | 247 - .../scripts/review-scope.mjs | 138 - .../plan2code-3-implement/scripts/specs.mjs | 676 -- .../scripts/version.json | 22 - skills/plan2code-4-finalize/SKILL.md | 356 - .../community-feedback-submission.md | 72 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - .../scripts/commit-msg.mjs | 120 - .../plan2code-4-finalize/scripts/common.mjs | 247 - .../scripts/feedback-payload.mjs | 379 - skills/plan2code-4-finalize/scripts/specs.mjs | 676 -- .../plan2code-4-finalize/scripts/version.json | 22 - skills/plan2code-handoff/SKILL.md | 157 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - skills/plan2code-handoff/scripts/common.mjs | 247 - .../scripts/handoff-path.mjs | 107 - skills/plan2code-handoff/scripts/specs.mjs | 676 -- skills/plan2code-handoff/scripts/version.json | 22 - skills/plan2code-init-update/SKILL.md | 282 - .../references/ai-agent-file-sync.md | 64 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - .../scripts/agent-files.mjs | 224 - .../scripts/agents-md.mjs | 157 - .../scripts/commit-msg.mjs | 120 - .../plan2code-init-update/scripts/common.mjs | 247 - .../scripts/version.json | 22 - skills/plan2code-init/SKILL.md | 134 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - skills/plan2code-init/scripts/agent-files.mjs | 224 - skills/plan2code-init/scripts/agents-md.mjs | 157 - skills/plan2code-init/scripts/common.mjs | 247 - skills/plan2code-init/scripts/version.json | 22 - skills/plan2code-quick-task/SKILL.md | 167 - .../references/dimensions.md | 191 - .../references/false-positives.md | 105 - .../plan2code-quick-task/references/review.md | 205 - .../references/session-end.md | 18 - .../references/verification-protocol.md | 72 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - .../scripts/commit-msg.mjs | 120 - .../plan2code-quick-task/scripts/common.mjs | 247 - .../scripts/review-scope.mjs | 138 - skills/plan2code-quick-task/scripts/specs.mjs | 676 -- .../plan2code-quick-task/scripts/version.json | 22 - skills/plan2code-review/SKILL.md | 211 - .../plan2code-review/references/dimensions.md | 191 - .../references/false-positives.md | 105 - .../references/session-end.md | 18 - .../references/verification-protocol.md | 72 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - .../plan2code-review/scripts/commit-msg.mjs | 120 - skills/plan2code-review/scripts/common.mjs | 247 - .../plan2code-review/scripts/review-scope.mjs | 138 - skills/plan2code-review/scripts/specs.mjs | 676 -- skills/plan2code-review/scripts/version.json | 22 - skills/plan2code/SKILL.md | 117 - .../references/web-console/building.md | 498 -- .../references/web-console/console.md | 1412 --- .../references/web-console/console.mjs | 1355 --- .../plan2code/references/web-console/lib.mjs | 2160 ----- .../references/web-console/picker.mjs | 265 - .../references/web-console/public/answers.js | 1003 --- .../references/web-console/public/app.css | 3537 -------- .../references/web-console/public/app.js | 7784 ----------------- .../references/web-console/public/boot.js | 138 - .../references/web-console/public/bootup.mp3 | Bin 276942 -> 0 bytes .../references/web-console/public/chat.js | 226 - .../references/web-console/public/favicon.js | 90 - .../references/web-console/public/favicon.png | Bin 3633 -> 0 bytes .../references/web-console/public/favicon.svg | 5 - .../references/web-console/public/help.js | 67 - .../references/web-console/public/index.html | 2363 ----- .../references/web-console/public/insert.mp3 | Bin 21987 -> 0 bytes .../references/web-console/public/labels.js | 31 - .../references/web-console/public/mentions.js | 46 - .../references/web-console/public/meter.js | 306 - .../references/web-console/public/next.mp3 | Bin 35108 -> 0 bytes .../web-console/public/package.json | 3 - .../references/web-console/public/palette.js | 238 - .../references/web-console/public/render.js | 308 - .../web-console/public/sleeping.mp3 | Bin 105645 -> 0 bytes .../web-console/public/start-skill.mp3 | Bin 46605 -> 0 bytes .../web-console/public/start-stop.mp3 | Bin 49920 -> 0 bytes .../references/web-console/public/starters.js | 440 - .../web-console/public/subagents.js | 226 - .../web-console/public/vendor/marked.esm.js | 2580 ------ .../web-console/public/workspace.js | 92 - .../references/web-console/server.mjs | 2056 ----- .../references/web-console/update-check.mjs | 138 - .../references/web-console/version.json | 22 - 535 files changed, 377309 deletions(-) delete mode 100644 skills/plan2code-0-pathfinder/SKILL.md delete mode 100644 skills/plan2code-0-pathfinder/references/brief.md delete mode 100644 skills/plan2code-0-pathfinder/references/chart.md delete mode 100644 skills/plan2code-0-pathfinder/references/github-issues.md delete mode 100644 skills/plan2code-0-pathfinder/references/grilling.md delete mode 100644 skills/plan2code-0-pathfinder/references/handoff.md delete mode 100644 skills/plan2code-0-pathfinder/references/questions.md delete mode 100644 skills/plan2code-0-pathfinder/references/resolve.md delete mode 100644 skills/plan2code-0-pathfinder/references/trail.md delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/building.md delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/console.md delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/console.mjs delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/lib.mjs delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/picker.mjs delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/answers.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/app.css delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/app.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/boot.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/chat.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/favicon.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/favicon.png delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/help.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/index.html delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/labels.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/mentions.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/meter.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/package.json delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/palette.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/render.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/starters.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/subagents.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/public/workspace.js delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/server.mjs delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/update-check.mjs delete mode 100644 skills/plan2code-0-pathfinder/references/web-console/version.json delete mode 100644 skills/plan2code-0-pathfinder/scripts/common.mjs delete mode 100644 skills/plan2code-0-pathfinder/scripts/pathfinder.mjs delete mode 100644 skills/plan2code-0-pathfinder/scripts/version.json delete mode 100644 skills/plan2code-1-plan/SKILL.md delete mode 100644 skills/plan2code-1-plan/references/web-console/building.md delete mode 100644 skills/plan2code-1-plan/references/web-console/console.md delete mode 100644 skills/plan2code-1-plan/references/web-console/console.mjs delete mode 100644 skills/plan2code-1-plan/references/web-console/lib.mjs delete mode 100644 skills/plan2code-1-plan/references/web-console/picker.mjs delete mode 100644 skills/plan2code-1-plan/references/web-console/public/answers.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/app.css delete mode 100644 skills/plan2code-1-plan/references/web-console/public/app.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/boot.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code-1-plan/references/web-console/public/chat.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/favicon.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/favicon.png delete mode 100644 skills/plan2code-1-plan/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code-1-plan/references/web-console/public/help.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/index.html delete mode 100644 skills/plan2code-1-plan/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code-1-plan/references/web-console/public/labels.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/mentions.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/meter.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code-1-plan/references/web-console/public/package.json delete mode 100644 skills/plan2code-1-plan/references/web-console/public/palette.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/render.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code-1-plan/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code-1-plan/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code-1-plan/references/web-console/public/starters.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/subagents.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code-1-plan/references/web-console/public/workspace.js delete mode 100644 skills/plan2code-1-plan/references/web-console/server.mjs delete mode 100644 skills/plan2code-1-plan/references/web-console/update-check.mjs delete mode 100644 skills/plan2code-1-plan/references/web-console/version.json delete mode 100644 skills/plan2code-1-plan/scripts/common.mjs delete mode 100644 skills/plan2code-1-plan/scripts/specs.mjs delete mode 100644 skills/plan2code-1-plan/scripts/version.json delete mode 100644 skills/plan2code-1b-revise-plan/SKILL.md delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/building.md delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/console.md delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/console.mjs delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/lib.mjs delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/picker.mjs delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/answers.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/app.css delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/app.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/boot.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/chat.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/favicon.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/favicon.png delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/help.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/index.html delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/labels.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/mentions.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/meter.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/package.json delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/palette.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/render.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/starters.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/subagents.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/public/workspace.js delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/server.mjs delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/update-check.mjs delete mode 100644 skills/plan2code-1b-revise-plan/references/web-console/version.json delete mode 100644 skills/plan2code-1b-revise-plan/scripts/common.mjs delete mode 100644 skills/plan2code-1b-revise-plan/scripts/specs.mjs delete mode 100644 skills/plan2code-1b-revise-plan/scripts/version.json delete mode 100644 skills/plan2code-2-document/SKILL.md delete mode 100644 skills/plan2code-2-document/references/web-console/building.md delete mode 100644 skills/plan2code-2-document/references/web-console/console.md delete mode 100644 skills/plan2code-2-document/references/web-console/console.mjs delete mode 100644 skills/plan2code-2-document/references/web-console/lib.mjs delete mode 100644 skills/plan2code-2-document/references/web-console/picker.mjs delete mode 100644 skills/plan2code-2-document/references/web-console/public/answers.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/app.css delete mode 100644 skills/plan2code-2-document/references/web-console/public/app.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/boot.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code-2-document/references/web-console/public/chat.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/favicon.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/favicon.png delete mode 100644 skills/plan2code-2-document/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code-2-document/references/web-console/public/help.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/index.html delete mode 100644 skills/plan2code-2-document/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code-2-document/references/web-console/public/labels.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/mentions.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/meter.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code-2-document/references/web-console/public/package.json delete mode 100644 skills/plan2code-2-document/references/web-console/public/palette.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/render.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code-2-document/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code-2-document/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code-2-document/references/web-console/public/starters.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/subagents.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code-2-document/references/web-console/public/workspace.js delete mode 100644 skills/plan2code-2-document/references/web-console/server.mjs delete mode 100644 skills/plan2code-2-document/references/web-console/update-check.mjs delete mode 100644 skills/plan2code-2-document/references/web-console/version.json delete mode 100644 skills/plan2code-2-document/scripts/common.mjs delete mode 100644 skills/plan2code-2-document/scripts/specs.mjs delete mode 100644 skills/plan2code-2-document/scripts/version.json delete mode 100644 skills/plan2code-3-implement-review/SKILL.md delete mode 100644 skills/plan2code-3-implement-review/references/dimensions.md delete mode 100644 skills/plan2code-3-implement-review/references/false-positives.md delete mode 100644 skills/plan2code-3-implement-review/references/implement.md delete mode 100644 skills/plan2code-3-implement-review/references/review.md delete mode 100644 skills/plan2code-3-implement-review/references/session-end.md delete mode 100644 skills/plan2code-3-implement-review/references/verification-protocol.md delete mode 100644 skills/plan2code-3-implement-review/references/web-console/building.md delete mode 100644 skills/plan2code-3-implement-review/references/web-console/console.md delete mode 100644 skills/plan2code-3-implement-review/references/web-console/console.mjs delete mode 100644 skills/plan2code-3-implement-review/references/web-console/lib.mjs delete mode 100644 skills/plan2code-3-implement-review/references/web-console/picker.mjs delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/answers.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/app.css delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/app.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/boot.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/chat.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/favicon.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/favicon.png delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/help.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/index.html delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/labels.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/mentions.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/meter.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/package.json delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/palette.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/render.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/starters.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/subagents.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/public/workspace.js delete mode 100644 skills/plan2code-3-implement-review/references/web-console/server.mjs delete mode 100644 skills/plan2code-3-implement-review/references/web-console/update-check.mjs delete mode 100644 skills/plan2code-3-implement-review/references/web-console/version.json delete mode 100644 skills/plan2code-3-implement-review/scripts/commit-msg.mjs delete mode 100644 skills/plan2code-3-implement-review/scripts/common.mjs delete mode 100644 skills/plan2code-3-implement-review/scripts/review-scope.mjs delete mode 100644 skills/plan2code-3-implement-review/scripts/specs.mjs delete mode 100644 skills/plan2code-3-implement-review/scripts/version.json delete mode 100644 skills/plan2code-3-implement/SKILL.md delete mode 100644 skills/plan2code-3-implement/references/dimensions.md delete mode 100644 skills/plan2code-3-implement/references/false-positives.md delete mode 100644 skills/plan2code-3-implement/references/review.md delete mode 100644 skills/plan2code-3-implement/references/session-end.md delete mode 100644 skills/plan2code-3-implement/references/verification-protocol.md delete mode 100644 skills/plan2code-3-implement/references/web-console/building.md delete mode 100644 skills/plan2code-3-implement/references/web-console/console.md delete mode 100644 skills/plan2code-3-implement/references/web-console/console.mjs delete mode 100644 skills/plan2code-3-implement/references/web-console/lib.mjs delete mode 100644 skills/plan2code-3-implement/references/web-console/picker.mjs delete mode 100644 skills/plan2code-3-implement/references/web-console/public/answers.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/app.css delete mode 100644 skills/plan2code-3-implement/references/web-console/public/app.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/boot.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code-3-implement/references/web-console/public/chat.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/favicon.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/favicon.png delete mode 100644 skills/plan2code-3-implement/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code-3-implement/references/web-console/public/help.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/index.html delete mode 100644 skills/plan2code-3-implement/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code-3-implement/references/web-console/public/labels.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/mentions.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/meter.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code-3-implement/references/web-console/public/package.json delete mode 100644 skills/plan2code-3-implement/references/web-console/public/palette.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/render.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code-3-implement/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code-3-implement/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code-3-implement/references/web-console/public/starters.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/subagents.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code-3-implement/references/web-console/public/workspace.js delete mode 100644 skills/plan2code-3-implement/references/web-console/server.mjs delete mode 100644 skills/plan2code-3-implement/references/web-console/update-check.mjs delete mode 100644 skills/plan2code-3-implement/references/web-console/version.json delete mode 100644 skills/plan2code-3-implement/scripts/commit-msg.mjs delete mode 100644 skills/plan2code-3-implement/scripts/common.mjs delete mode 100644 skills/plan2code-3-implement/scripts/review-scope.mjs delete mode 100644 skills/plan2code-3-implement/scripts/specs.mjs delete mode 100644 skills/plan2code-3-implement/scripts/version.json delete mode 100644 skills/plan2code-4-finalize/SKILL.md delete mode 100644 skills/plan2code-4-finalize/references/community-feedback-submission.md delete mode 100644 skills/plan2code-4-finalize/references/web-console/building.md delete mode 100644 skills/plan2code-4-finalize/references/web-console/console.md delete mode 100644 skills/plan2code-4-finalize/references/web-console/console.mjs delete mode 100644 skills/plan2code-4-finalize/references/web-console/lib.mjs delete mode 100644 skills/plan2code-4-finalize/references/web-console/picker.mjs delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/answers.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/app.css delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/app.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/boot.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/chat.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/favicon.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/favicon.png delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/help.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/index.html delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/labels.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/mentions.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/meter.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/package.json delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/palette.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/render.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/starters.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/subagents.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/public/workspace.js delete mode 100644 skills/plan2code-4-finalize/references/web-console/server.mjs delete mode 100644 skills/plan2code-4-finalize/references/web-console/update-check.mjs delete mode 100644 skills/plan2code-4-finalize/references/web-console/version.json delete mode 100644 skills/plan2code-4-finalize/scripts/commit-msg.mjs delete mode 100644 skills/plan2code-4-finalize/scripts/common.mjs delete mode 100644 skills/plan2code-4-finalize/scripts/feedback-payload.mjs delete mode 100644 skills/plan2code-4-finalize/scripts/specs.mjs delete mode 100644 skills/plan2code-4-finalize/scripts/version.json delete mode 100644 skills/plan2code-handoff/SKILL.md delete mode 100644 skills/plan2code-handoff/references/web-console/building.md delete mode 100644 skills/plan2code-handoff/references/web-console/console.md delete mode 100644 skills/plan2code-handoff/references/web-console/console.mjs delete mode 100644 skills/plan2code-handoff/references/web-console/lib.mjs delete mode 100644 skills/plan2code-handoff/references/web-console/picker.mjs delete mode 100644 skills/plan2code-handoff/references/web-console/public/answers.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/app.css delete mode 100644 skills/plan2code-handoff/references/web-console/public/app.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/boot.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code-handoff/references/web-console/public/chat.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/favicon.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/favicon.png delete mode 100644 skills/plan2code-handoff/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code-handoff/references/web-console/public/help.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/index.html delete mode 100644 skills/plan2code-handoff/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code-handoff/references/web-console/public/labels.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/mentions.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/meter.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code-handoff/references/web-console/public/package.json delete mode 100644 skills/plan2code-handoff/references/web-console/public/palette.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/render.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code-handoff/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code-handoff/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code-handoff/references/web-console/public/starters.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/subagents.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code-handoff/references/web-console/public/workspace.js delete mode 100644 skills/plan2code-handoff/references/web-console/server.mjs delete mode 100644 skills/plan2code-handoff/references/web-console/update-check.mjs delete mode 100644 skills/plan2code-handoff/references/web-console/version.json delete mode 100644 skills/plan2code-handoff/scripts/common.mjs delete mode 100644 skills/plan2code-handoff/scripts/handoff-path.mjs delete mode 100644 skills/plan2code-handoff/scripts/specs.mjs delete mode 100644 skills/plan2code-handoff/scripts/version.json delete mode 100644 skills/plan2code-init-update/SKILL.md delete mode 100644 skills/plan2code-init-update/references/ai-agent-file-sync.md delete mode 100644 skills/plan2code-init-update/references/web-console/building.md delete mode 100644 skills/plan2code-init-update/references/web-console/console.md delete mode 100644 skills/plan2code-init-update/references/web-console/console.mjs delete mode 100644 skills/plan2code-init-update/references/web-console/lib.mjs delete mode 100644 skills/plan2code-init-update/references/web-console/picker.mjs delete mode 100644 skills/plan2code-init-update/references/web-console/public/answers.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/app.css delete mode 100644 skills/plan2code-init-update/references/web-console/public/app.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/boot.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code-init-update/references/web-console/public/chat.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/favicon.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/favicon.png delete mode 100644 skills/plan2code-init-update/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code-init-update/references/web-console/public/help.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/index.html delete mode 100644 skills/plan2code-init-update/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code-init-update/references/web-console/public/labels.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/mentions.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/meter.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code-init-update/references/web-console/public/package.json delete mode 100644 skills/plan2code-init-update/references/web-console/public/palette.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/render.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code-init-update/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code-init-update/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code-init-update/references/web-console/public/starters.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/subagents.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code-init-update/references/web-console/public/workspace.js delete mode 100644 skills/plan2code-init-update/references/web-console/server.mjs delete mode 100644 skills/plan2code-init-update/references/web-console/update-check.mjs delete mode 100644 skills/plan2code-init-update/references/web-console/version.json delete mode 100644 skills/plan2code-init-update/scripts/agent-files.mjs delete mode 100644 skills/plan2code-init-update/scripts/agents-md.mjs delete mode 100644 skills/plan2code-init-update/scripts/commit-msg.mjs delete mode 100644 skills/plan2code-init-update/scripts/common.mjs delete mode 100644 skills/plan2code-init-update/scripts/version.json delete mode 100644 skills/plan2code-init/SKILL.md delete mode 100644 skills/plan2code-init/references/web-console/building.md delete mode 100644 skills/plan2code-init/references/web-console/console.md delete mode 100644 skills/plan2code-init/references/web-console/console.mjs delete mode 100644 skills/plan2code-init/references/web-console/lib.mjs delete mode 100644 skills/plan2code-init/references/web-console/picker.mjs delete mode 100644 skills/plan2code-init/references/web-console/public/answers.js delete mode 100644 skills/plan2code-init/references/web-console/public/app.css delete mode 100644 skills/plan2code-init/references/web-console/public/app.js delete mode 100644 skills/plan2code-init/references/web-console/public/boot.js delete mode 100644 skills/plan2code-init/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code-init/references/web-console/public/chat.js delete mode 100644 skills/plan2code-init/references/web-console/public/favicon.js delete mode 100644 skills/plan2code-init/references/web-console/public/favicon.png delete mode 100644 skills/plan2code-init/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code-init/references/web-console/public/help.js delete mode 100644 skills/plan2code-init/references/web-console/public/index.html delete mode 100644 skills/plan2code-init/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code-init/references/web-console/public/labels.js delete mode 100644 skills/plan2code-init/references/web-console/public/mentions.js delete mode 100644 skills/plan2code-init/references/web-console/public/meter.js delete mode 100644 skills/plan2code-init/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code-init/references/web-console/public/package.json delete mode 100644 skills/plan2code-init/references/web-console/public/palette.js delete mode 100644 skills/plan2code-init/references/web-console/public/render.js delete mode 100644 skills/plan2code-init/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code-init/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code-init/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code-init/references/web-console/public/starters.js delete mode 100644 skills/plan2code-init/references/web-console/public/subagents.js delete mode 100644 skills/plan2code-init/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code-init/references/web-console/public/workspace.js delete mode 100644 skills/plan2code-init/references/web-console/server.mjs delete mode 100644 skills/plan2code-init/references/web-console/update-check.mjs delete mode 100644 skills/plan2code-init/references/web-console/version.json delete mode 100644 skills/plan2code-init/scripts/agent-files.mjs delete mode 100644 skills/plan2code-init/scripts/agents-md.mjs delete mode 100644 skills/plan2code-init/scripts/common.mjs delete mode 100644 skills/plan2code-init/scripts/version.json delete mode 100644 skills/plan2code-quick-task/SKILL.md delete mode 100644 skills/plan2code-quick-task/references/dimensions.md delete mode 100644 skills/plan2code-quick-task/references/false-positives.md delete mode 100644 skills/plan2code-quick-task/references/review.md delete mode 100644 skills/plan2code-quick-task/references/session-end.md delete mode 100644 skills/plan2code-quick-task/references/verification-protocol.md delete mode 100644 skills/plan2code-quick-task/references/web-console/building.md delete mode 100644 skills/plan2code-quick-task/references/web-console/console.md delete mode 100644 skills/plan2code-quick-task/references/web-console/console.mjs delete mode 100644 skills/plan2code-quick-task/references/web-console/lib.mjs delete mode 100644 skills/plan2code-quick-task/references/web-console/picker.mjs delete mode 100644 skills/plan2code-quick-task/references/web-console/public/answers.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/app.css delete mode 100644 skills/plan2code-quick-task/references/web-console/public/app.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/boot.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code-quick-task/references/web-console/public/chat.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/favicon.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/favicon.png delete mode 100644 skills/plan2code-quick-task/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code-quick-task/references/web-console/public/help.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/index.html delete mode 100644 skills/plan2code-quick-task/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code-quick-task/references/web-console/public/labels.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/mentions.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/meter.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code-quick-task/references/web-console/public/package.json delete mode 100644 skills/plan2code-quick-task/references/web-console/public/palette.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/render.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code-quick-task/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code-quick-task/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code-quick-task/references/web-console/public/starters.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/subagents.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code-quick-task/references/web-console/public/workspace.js delete mode 100644 skills/plan2code-quick-task/references/web-console/server.mjs delete mode 100644 skills/plan2code-quick-task/references/web-console/update-check.mjs delete mode 100644 skills/plan2code-quick-task/references/web-console/version.json delete mode 100644 skills/plan2code-quick-task/scripts/commit-msg.mjs delete mode 100644 skills/plan2code-quick-task/scripts/common.mjs delete mode 100644 skills/plan2code-quick-task/scripts/review-scope.mjs delete mode 100644 skills/plan2code-quick-task/scripts/specs.mjs delete mode 100644 skills/plan2code-quick-task/scripts/version.json delete mode 100644 skills/plan2code-review/SKILL.md delete mode 100644 skills/plan2code-review/references/dimensions.md delete mode 100644 skills/plan2code-review/references/false-positives.md delete mode 100644 skills/plan2code-review/references/session-end.md delete mode 100644 skills/plan2code-review/references/verification-protocol.md delete mode 100644 skills/plan2code-review/references/web-console/building.md delete mode 100644 skills/plan2code-review/references/web-console/console.md delete mode 100644 skills/plan2code-review/references/web-console/console.mjs delete mode 100644 skills/plan2code-review/references/web-console/lib.mjs delete mode 100644 skills/plan2code-review/references/web-console/picker.mjs delete mode 100644 skills/plan2code-review/references/web-console/public/answers.js delete mode 100644 skills/plan2code-review/references/web-console/public/app.css delete mode 100644 skills/plan2code-review/references/web-console/public/app.js delete mode 100644 skills/plan2code-review/references/web-console/public/boot.js delete mode 100644 skills/plan2code-review/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code-review/references/web-console/public/chat.js delete mode 100644 skills/plan2code-review/references/web-console/public/favicon.js delete mode 100644 skills/plan2code-review/references/web-console/public/favicon.png delete mode 100644 skills/plan2code-review/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code-review/references/web-console/public/help.js delete mode 100644 skills/plan2code-review/references/web-console/public/index.html delete mode 100644 skills/plan2code-review/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code-review/references/web-console/public/labels.js delete mode 100644 skills/plan2code-review/references/web-console/public/mentions.js delete mode 100644 skills/plan2code-review/references/web-console/public/meter.js delete mode 100644 skills/plan2code-review/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code-review/references/web-console/public/package.json delete mode 100644 skills/plan2code-review/references/web-console/public/palette.js delete mode 100644 skills/plan2code-review/references/web-console/public/render.js delete mode 100644 skills/plan2code-review/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code-review/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code-review/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code-review/references/web-console/public/starters.js delete mode 100644 skills/plan2code-review/references/web-console/public/subagents.js delete mode 100644 skills/plan2code-review/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code-review/references/web-console/public/workspace.js delete mode 100644 skills/plan2code-review/references/web-console/server.mjs delete mode 100644 skills/plan2code-review/references/web-console/update-check.mjs delete mode 100644 skills/plan2code-review/references/web-console/version.json delete mode 100644 skills/plan2code-review/scripts/commit-msg.mjs delete mode 100644 skills/plan2code-review/scripts/common.mjs delete mode 100644 skills/plan2code-review/scripts/review-scope.mjs delete mode 100644 skills/plan2code-review/scripts/specs.mjs delete mode 100644 skills/plan2code-review/scripts/version.json delete mode 100644 skills/plan2code/SKILL.md delete mode 100644 skills/plan2code/references/web-console/building.md delete mode 100644 skills/plan2code/references/web-console/console.md delete mode 100644 skills/plan2code/references/web-console/console.mjs delete mode 100644 skills/plan2code/references/web-console/lib.mjs delete mode 100644 skills/plan2code/references/web-console/picker.mjs delete mode 100644 skills/plan2code/references/web-console/public/answers.js delete mode 100644 skills/plan2code/references/web-console/public/app.css delete mode 100644 skills/plan2code/references/web-console/public/app.js delete mode 100644 skills/plan2code/references/web-console/public/boot.js delete mode 100644 skills/plan2code/references/web-console/public/bootup.mp3 delete mode 100644 skills/plan2code/references/web-console/public/chat.js delete mode 100644 skills/plan2code/references/web-console/public/favicon.js delete mode 100644 skills/plan2code/references/web-console/public/favicon.png delete mode 100644 skills/plan2code/references/web-console/public/favicon.svg delete mode 100644 skills/plan2code/references/web-console/public/help.js delete mode 100644 skills/plan2code/references/web-console/public/index.html delete mode 100644 skills/plan2code/references/web-console/public/insert.mp3 delete mode 100644 skills/plan2code/references/web-console/public/labels.js delete mode 100644 skills/plan2code/references/web-console/public/mentions.js delete mode 100644 skills/plan2code/references/web-console/public/meter.js delete mode 100644 skills/plan2code/references/web-console/public/next.mp3 delete mode 100644 skills/plan2code/references/web-console/public/package.json delete mode 100644 skills/plan2code/references/web-console/public/palette.js delete mode 100644 skills/plan2code/references/web-console/public/render.js delete mode 100644 skills/plan2code/references/web-console/public/sleeping.mp3 delete mode 100644 skills/plan2code/references/web-console/public/start-skill.mp3 delete mode 100644 skills/plan2code/references/web-console/public/start-stop.mp3 delete mode 100644 skills/plan2code/references/web-console/public/starters.js delete mode 100644 skills/plan2code/references/web-console/public/subagents.js delete mode 100644 skills/plan2code/references/web-console/public/vendor/marked.esm.js delete mode 100644 skills/plan2code/references/web-console/public/workspace.js delete mode 100644 skills/plan2code/references/web-console/server.mjs delete mode 100644 skills/plan2code/references/web-console/update-check.mjs delete mode 100644 skills/plan2code/references/web-console/version.json diff --git a/skills/plan2code-0-pathfinder/SKILL.md b/skills/plan2code-0-pathfinder/SKILL.md deleted file mode 100644 index f901e60..0000000 --- a/skills/plan2code-0-pathfinder/SKILL.md +++ /dev/null @@ -1,174 +0,0 @@ ---- -name: plan2code-0-pathfinder -description: "Plan2Code Step 0: Pathfinder Mode - user-initiated workflow step. Do not invoke autonomously." -disable-model-invocation: true ---- - -# 🧭 PATHFINDER MODE - -Start all PATHFINDER MODE responses with '🧭 [PATHFINDER: Chart - Step X: Name]' or '🧭 [PATHFINDER: Work - Step X: Name]'. - -## Role - -Pathfinder, not architect. An idea has arrived too big or unclear to plan. Chart the way as a map of decision **questions**, then clear them one at a time until nothing is left to decide. Hand off to `/plan2code-1-plan`. - -Read references/grilling.md - -> Fallback: ≤3 independent probes/turn, each with a recommendation, re-ask any skipped; AskUserQuestion for every question, prose only if unavailable; plain English; facts you look up, decisions are the human's. - -## Interface - -The FIRST thing you do, before anything else in this file — before Step 0: ask **web console** (suggested) or **terminal**? Console → run `node "/console.mjs" open --workflow pathfinder` before reading (: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then /console.md → Pathfinder notes. Switchable anytime. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console.md → Launches), then Step 0. - -## Backend - -The map lives in ONE of two places — the human's pick at Chart Step 1, never yours: - -- **local** (default) — files under `specs//pathfinder/`. Private, gitignored, solo. -- **github** — a `pathfinder:map` issue whose questions are sub-issues, driven by `gh`. Shared, visible in the tracker, parallel. - -Read references/github-issues.md — REQUIRED on `github`, skip on `local`. - -> Fallback: map = a `pathfinder:map` issue titled `Map: `; questions = its sub-issues, labelled `pathfinder:-`; blocking = native dependencies; claim = assign `@me`; resolve = `## Answer` comment, then close. - -Recorded as the first `## Ground rules` bullet (`**Backend:** local|github`), never re-asked or switched. Either way the PLAN-DRAFT lands in local `specs//` — downstream steps read files, not issues. - -## Scripts - -On `local`, the map's bookkeeping is a script; the decisions are yours. `node "/pathfinder.mjs" specs//pathfinder`, run from the project root, where `` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-0-pathfinder/scripts/` globally). It prints one JSON object. Exit 0 is success; anything else carries `message` and `next`, so do what `next` says. Exit 5 (refused) means a rule would break: never work around it by editing the files by hand. `--help` lists every command; they are named at the steps below. It reads local files only: on `github`, the backend playbook does each step with `gh` (except `lint`, which checks the local briefs and PLAN-DRAFT once one exists), and a `no-map` result there is expected, never a cue to chart. - -## Project Context - -Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it answers. If missing, fold it into the Step 0 gate batch: *"No `AGENTS.md`. Pathfinder can chart without it. Continue, or run `plan2code-init` first?"* Record the outcome as the first line of `## Ground rules`: ``- `AGENTS.md` exists and governs.`` or, when missing, exactly ``- `AGENTS.md` is absent.`` (the handoff reads it). - -## Rules - -- **Plan, don't do.** Every question resolves a DECISION. The pull to just build it is the edge of the map — hand off. -- **Confirm before creating anything.** No files, no issues, until the Intent Gate (Step 0) and backend pick (Step 1) return. -- **One question at a time** (`research` excepted — parallel); fork-menu between decisions, fresh session after ~3. -- **Refer by name.** "[Export format]()", never "02" or "#42" in prose. Bare ids belong on `Blocked by:` lines and in commands. -- **HITL questions are never self-answered.** Ask and wait; an agent that answers its own grill has broken the skill. -- **Questions are ground truth; the map is a rebuildable index.** A filled `## Answer` beats any state marker; detail lives in one place. -- **Never write implementation code** into the project. Sketches are throwaway, living only under `pathfinder/sketch-NN/`. -- **Reserved names — never create inside `pathfinder/`:** `overview.md`, `phase-.md`, `PLAN-DRAFT-*.md`, `PLAN-CONVERSATION-*.md`. -- **Never emit the loop's completion tokens under `specs/`** — `TASK_COMPLETE`, `PHASE_COMPLETE`, `ALL_TASKS_COMPLETE`, `IMPLEMENTATION_COMPLETE`, `SPEC_COMPLETE`, `WORK_COMPLETE`. It scans for them. -- **No `- [ ]` checkboxes inside question files**, and no `METRICS_JSON` anywhere. -- **Lint before every Session End** (on `github`, once a brief or PLAN-DRAFT is on local disk; it checks those): `lint` checks the rules above, the schema lines, `Blocked by:` targets and cycles, and metrics-scraper bait. Fix every error it lists (exit 4) before you stop. - -## Auto-Discovery and Mode Selection - -⚠️ `specs/` is gitignored — NEVER use Glob. Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS). - -**Brief/recap/minutes asked?** → read references/brief.md: `reconcile`, then `brief-data --range ` (`github`: its brief section), write plain-English `briefs/brief-.md` from the output, STOP. Never resolves. - -**Identify the idea FIRST** (from the argument, or ask), then evaluate for THAT idea — first match wins. An issue URL or number means `github`; else look for a local map, then `gh issue list --label pathfinder:map` for `Map: `. - -| Condition | Route | -|---|---| -| No map, but `specs//overview.md` exists | Documented — offer `/plan2code-3-implement`. STOP | -| No map in either backend | MODE A, Step 0 (Intent Gate) | -| Map `**Status:** Charting` | MODE A, resume at Step 6 | -| Map `**Status:** Working` | MODE B | -| Map `**Status:** Cleared` | Point at the PLAN-DRAFT and `/plan2code-1-plan`. STOP | -| Map exists, `**Status:**` unreadable | MODE B — Step 2 rebuilds and sets it | - -One idea per session, each with its own map. - -## Questions - -Read references/questions.md — the `local` format. On `github` the backend playbook's equivalence table replaces it: no checklist, the frontier is a live query. - -> Fallback (`local`): `map.md` indexes; `questions/NN-.md` hold the decisions, `00` is codebase context, six `Key: value` lines each, `Resolved:` dating it. Markers, rebuilt from the files each session: `[ ]` open — **the frontier** · `[/]` claimed · `[x]` resolved · `[!]` blocked · `[-]` out of scope. - -## MODE A: Chart - -Read references/chart.md - -> Fallback: confirm the outcome with the human FIRST; only then grill the destination, then breadth-first; write the map and one question per sharp decision. - -0. `[Chart - Step 0: Intent Gate]` **Before creating anything**, use AskUserQuestion for the outcome and WAIT: **chart a map** (foggy — Step 1), **`/plan2code-1-plan`** (clear — STOP), **`/plan2code-quick-task`** (tiny — STOP). HITL, never self-select "chart". -1. `[Chart - Step 1: Name and backend]` Only after the gate says "chart." Confirm the kebab-case idea name, then ask — HITL, never self-picked — **local files or GitHub Issues?** Recommend `local` for solo work; offer `github` only if preflight passes, naming the repo's visibility. THEN the first write. -2. `[Chart - Step 2: Destination]` Grill until it is one or two lines. It fixes scope — settle it first. -3. `[Chart - Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK`. On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter. -4. `[Chart - Step 4: Map the frontier]` Grill again **breadth-first**: fan out, never deep on one thread. Surface the open decisions and what is takeable now. -5. `[Chart - Step 5: Create the map]` `**Status:** Charting`, Destination, Ground rules (backend first), an empty index, the fog in `## Not yet specified`. Say once where it lives and who sees it. -6. `[Chart - Step 6: Write the questions]` One per decision you can phrase sharply NOW, dependency order, `Blocked by:` filled the same pass — on `github`, create all first, wire edges second. The rest stays fog. Include a `grill · HITL` testing-posture question; `/plan2code-1-plan` Phase 1 needs it. -7. `[Chart - Step 7: Index]` `local`: `reconcile` fills `## Question Checklist` from the files (every missing row, with its marker). Either backend: set `**Status:** Working`. `local`: then `lint`. -8. `[Chart - Step 8: Fire research]` One subagent per `research` question, in parallel. Each writes only its `## Evidence`, never decides. **Wait for all** (they die with the terminal), then Session End. - -**No fog at Step 4?** Small enough to plan directly: create no map, keep the recon as a local file, attach it to `/plan2code-1-plan`, STOP. Charting resolves nothing by hand — stop at Step 8. - -## MODE B: Work - -Read references/resolve.md - -> Fallback: resolve by type — research reads sources, sketch makes something concrete, grill interviews the human, legwork does the manual work. - -Assume NO memory of any prior session. - -1. `[Work - Step 1: Load]` Read the map whole. No question yet. -2. `[Work - Step 2: Reconcile]` **Always.** `local`: run `reconcile`. The answer wins: a question whose `## Answer` its state contradicts is resolved, a missing `Resolved:` is backfilled from the claim (today if none), a claim with no `## Answer` (a crash) is released, and every marker is rebuilt from the questions. Tell the human each `repairs` entry in one line. Re-fire every question in `refire` (research cut off before its `Research complete:` line; resolve.md → Interrupted research). `--dry-run` first if the map looks badly off. `github`: the reconcile checks in the backend playbook. -3. `[Work - Step 3: Frontier]` Every question open, unclaimed, and unblocked, first in order. `local`: run `frontier` (`frontier`, `blocked` with each blocker, `stranded`, `nextNN`, `counts`). -4. `[Work - Step 4: Choose and claim]` The one the user named, else first on the frontier. Mark it claimed on the question and the map, **saved before any work** (`local`: `claim `, which refuses a blocked or non-open question and a second open claim). A `research` pick fires unclaimed instead (resolve.md); then claim the next one. - - Stranded on an `out-of-scope` blocker? Check this first: re-frame or rule out, re-run Step 3. - - Frontier empty but questions remain (`allBlocked`)? Report the chain, STOP. - - Nothing open (`nothingOpen`)? The Clearing Gate. -5. `[Work - Step 5: Zoom]` Read the claimed question in full, plus any closed question it references. Obey `## Ground rules`. -6. `[Work - Step 6: Resolve]` Route by type per the resolve playbook. HITL needs the human's own words. -7. `[Work - Step 7: Record]` Write `## Answer`: the decision, what was rejected and why, consequences, a one-line `**Gist:**` last. Sources under `## Evidence`. Mark it resolved, dated today, index the gist + date on the map, bump `**Updated:**` (`local`: `resolve ` does all four; its `unblocked` list feeds the menu). -8. `[Work - Step 8: Graduate]` Fog now sharp? Write those questions (`local`: numbered from `nextNN`, then `reconcile` to index them), delete the graduated bullets. Past the destination? Rule it out of scope, one line in `## Out of scope` (`local`: `rule-out --reason ""`; handle anything it reports `stranded`). Invalidated? Re-frame or rule out. -9. `[Work - Step 9: Menu]` Run The Clearing Gate. Not cleared: fork-menu (Form C; resolve.md §Cadence) — pick → Step 4, stop → Session End. - -## The Clearing Gate - -Read references/handoff.md - -> Fallback: write `specs//PLAN-DRAFT-.md` from the map, Status `Phase 3 Complete - Resume at Phase 4`, then route to `/plan2code-1-plan`. - -The map clears only when ALL hold: - -1. Nothing open, claimed, or blocked -2. `## Not yet specified` is EMPTY -3. The destination is reachable with nothing left to decide -4. All four confidence dimensions score ≥ 18/25 - -Score the four dimensions (handoff.md rubric) and write them to the map's `**Confidence:**` line. `local`: run `gate`; it checks 1, 2 and 4 against the files, plus the handoff preflight and the Requirements, Feasibility and Risk caps; condition 3, the Integration cap and the scores stay yours (its `judgment` list). Any failing: name it, keep working. All passing: follow the handoff playbook, set `**Status:** Cleared`, run `lint`, stop. The PLAN-DRAFT is always local — `/plan2code-1-plan` cannot read a tracker. - -## Trail Footer - -Read references/trail.md - -> Fallback: once the map exists, end every response with a marker path (`●` done · `◉` here · `○` open · `⊘` blocked · `⊝` out of scope) `START`→`⚑`, a named legend, a plain-English confidence note, then ONE closer: asking → Form B, `WAITING ON YOU`, no command; menu → Form C, `NEXT UP` + `OR START FRESH`; session end → Form A, `NEXT STEP` + resume command with `--web` (map issue URL on `github`). - -Close EVERY response with the trail once the map exists. You pick the form by what the turn does. `local`: `trail` draws it from the files, so paste its output verbatim. Asking → Form B, `trail --form B --item "" ... --text` (one `--item` per open probe, up to three). Menu after a decision → Form C, `trail --form C` WITHOUT `--text`: paste its `text`, then build the question tool from its `menu`. Session end → Form A, `trail --form A --text`. `github`: draw it by hand per the backend playbook. - -## Session End - -Report each question resolved (name + gist), what graduated, what's still open; offer a brief for today. Nothing to commit — `local` is gitignored, `github` already on the tracker. Then the mascot, then the Trail Footer. - -**Web console:** at session end or on a `__stop`, post `finish` (Form A's command) BEFORE `stop` (console.md → Pathfinder). - -``` -⋅ - ╭───╮ - ╲│ ★ │╱ - │ ◡ │ One more decision down. The fog is thinner! - ╰┬─┬╯ -``` - -**When the map cleared**, the mascot says `The way is clear! Time to plan!` and the footer routes to `/plan2code-1-plan` — or `/plan2code-init` FIRST if `## Ground rules` records `AGENTS.md` absent. - -## Abort / Recovery - -| Issue | Action | -|---|---| -| Session stops mid-question, or map drift | Release the claim, note why (or leave it: the next reconcile releases a claim with no answer). Work Step 2 repairs both; questions win. Never reconcile mid-question: it would release your own live claim. | -| A script cannot run (no `node`) | Say so once; do the step by hand from questions.md (markers, blocking, schema) and the reference that names the step. Footer by hand: the trail's glyph path, then Form A `NEXT STEP · start a new conversation and run:` + the command, Form B `WAITING ON YOU · answer here, in this conversation:` + the items, or Form C `OR START FRESH · new conversation, paste:` + the command. | -| Frontier empty, fog remains | Not sharp yet. Grill it into a question, or clear the map | -| Reference file missing | Use the fallback blockquote under its `Read` line | -| `gh` fails mid-session on a `github` map | Report and STOP. Falling back to local forks the map | -| User skips to planning | Their call. Name what is undecided, route to `/plan2code-1-plan` | - -## Learning Capture - -If charting surfaced project-specific insights, suggest `/plan2code-init-update` to capture them in `AGENTS.md`. diff --git a/skills/plan2code-0-pathfinder/references/brief.md b/skills/plan2code-0-pathfinder/references/brief.md deleted file mode 100644 index bca23d8..0000000 --- a/skills/plan2code-0-pathfinder/references/brief.md +++ /dev/null @@ -1,102 +0,0 @@ -# Brief Playbook - -> Loaded when the user's argument asks for a brief. Produces one plain-English report file for a date range — the artifact a PM pastes into Slack or reads aloud in a meeting. The only mutation BRIEF mode ever performs is the Work Step 2 reconcile; it never claims, resolves, or answers a question. - -> **Backend note.** The report is IDENTICAL either way — same sections, same plain-English rules — and the brief file always lands on **local disk** under `specs//pathfinder/briefs/`, even on `**Backend:** github`. What differs is where the inputs come from: on `github` the range filter reads each question issue's close date instead of a `Resolved:` line, and the open / blocked / out-of-scope sections come from the frontier query rather than the checklist — see `github-issues.md`. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes. - -## When it fires - -The argument (or message) asks for a `brief`, `summary`, `recap`, or `minutes` for an idea, with an optional range: - -``` -/plan2code-0-pathfinder write a brief for today for specs//pathfinder -/plan2code-0-pathfinder brief since 2026-08-15 for specs//pathfinder -/plan2code-0-pathfinder full brief for specs//pathfinder -``` - -Translate the person's words into the script's range: `today` (the default when unstated) · `this-week` (Monday through today) · `since:` · `..` · `full` (everything since the map was created). Resolve a relative phrase ("since Tuesday") to a date yourself; the script takes dates only and reads today from the clock. - -No `map.md` for the idea? There is nothing to brief — say so and route to charting. `**Status:** Cleared`? A brief is still legitimate: cover the full history and point at the PLAN-DRAFT in `## Next step`. - -## Procedure - -1. **Resolve the idea** exactly as Auto-Discovery does. -2. **Reconcile first**: `node "/pathfinder.mjs" reconcile specs//pathfinder`. A brief must never disagree with the map it summarizes, which is why BRIEF mode repairs drift rather than reporting it. Keep its `repairs` for step 5. -3. **Gather**: `node "/pathfinder.mjs" brief-data specs//pathfinder --range `. It filters resolved questions by `Resolved:` date and returns every section's source (below), the file to write, and `drift` / `undatedResolved` (both empty after step 2; if not, rerun step 2). Out-of-scope rulings are never date-filtered: standing scope boundaries appear in every brief. -4. **Write** the file at its `file` path (create `briefs/` if absent). The name carries today's date regardless of range; the `**Covers:**` line disambiguates. Same-day re-runs overwrite (`exists: true`): a brief is a report, not a record; the question files remain the record. -5. **Report** in chat: the file path, the range, one line on any reconcile repairs. Then the Trail Footer, Form A (the session is over; the command routes by map status as usual). Run `lint` first: it checks the brief for percent signs and scraper bait. - -## The template - -Substitute real content; keep the section order. `` reads naturally per range: "Decided today", "Decided this week", "Decided so far" (full). - -```markdown -# Audit log export - decisions brief - -**Covers:** 2026-09-02 · **Map:** 6 of 9 decisions made - -## Where this is headed - - - -## Decided today - -- **Export format** - CSV with a UTF-8 BOM plus a SHA-256 manifest file. - Rejected: JSONL (recipients open these in Excel); XLSX (harder to verify byte-for-byte). - *Recorded as hard to reverse.* -- **Export authorization** - new tenant-scoped compliance role; self-events included but flagged. - Rejected: reusing the admin role (no tenant scoping today). - -## Ruled out - -- **SIEM push connector** - continuous streaming is a separate effort with its own owner. - -## Open - ready to decide next - -- **Delivery channel** - can now be decided; the row-count ceiling it was waiting on landed today. -- **Testing posture** - needs Product and Engineering together. - -## Open - waiting on something first - -- **Redaction rules** - waiting on Legal's answer about exporting raw payloads. - -## Still taking shape - -- How far back an export may reach - depends on a retention answer nobody has yet. - -## How solid is this? - -Solid overall, but risk handling is borderline - one limit has no decided behavior past it yet. - -## Next step - -Run: `/plan2code-0-pathfinder specs/audit-log-export/pathfinder` - ---- -*Full reasoning behind every decision: `specs/audit-log-export/pathfinder/questions/`* -``` - -**How each section is built:** - -| Section | `brief-data` field | Rendering rule | -|---|---|---| -| Heading + `**Covers:**` | `title`, `covers`, `progress` | `progress` already uses the trail's counting rule (out-of-scope excluded from the total) | -| Where this is headed | `destination` | Verbatim. Never paraphrase it | -| Decided `` | `decidedHeading`, `decided` (`name`, `gist`, `rejected`, `hardToReverse`) | Question name bold, gist as the first line, each `rejected` entry compressed to ONE line with the why in parentheses. `hardToReverse` renders as *Recorded as hard to reverse.* — never the word "locked". Empty → `note` | -| Ruled out | `ruledOut` | One line each: name + why, link markup dropped | -| Open - ready to decide next | `ready` | Flag each `justUnblockedBy`: "can now be decided; X landed " | -| Open - waiting on something first | `waiting` | Name the blocker in plain words ("waiting on the export format decision"), never `Blocked by: 02` | -| Still taking shape | `fog` | Lightly rephrase each bullet into one plain sentence | -| How solid is this? | `confidence` | Already the plain-English line. Omit the section when it is null | -| Next step | `nextStep` | `command` as given; with a `plan`, point at that PLAN-DRAFT too | - -Nothing decided in the range? Keep the file honest: "No decisions were recorded in this period." under Decided, and render the open sections as usual — a meeting that only surfaced questions still gets minutes. - -## Rules - -- **Zero pathfinder machinery in the file.** No `NN` numbers, no markers, no `Type:`/`State:` tokens, no fog/frontier/grill vocabulary, no `Locked:`. Questions are referred to by name only, no links. The audience may never open a terminal. -- **Scraper safety, same as the PLAN-DRAFT:** no `%`, no raw `NN/25` scores, and no bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number anywhere in the file. The plain-English confidence line is the only rendering permitted. -- **Standing `specs/` rules apply:** no loop tokens, no `- [ ]` checkboxes, no `METRICS_JSON`. -- **Rejections are one line each.** The brief summarizes; the question file argues. The closing pointer line covers readers who want the full reasoning. -- **BRIEF mode does not count as question work.** It does not count toward the session's decision cadence; no claim is ever taken. -- **Do not edit an old brief to "update" it.** Yesterday's brief reflects yesterday's map — write today's instead. Same-day overwrite only. diff --git a/skills/plan2code-0-pathfinder/references/chart.md b/skills/plan2code-0-pathfinder/references/chart.md deleted file mode 100644 index 3aaa8ae..0000000 --- a/skills/plan2code-0-pathfinder/references/chart.md +++ /dev/null @@ -1,691 +0,0 @@ -# Chart Playbook -> Part of plan2code-0-pathfinder — loaded at the top of MODE A (Chart). Expands the numbered Chart steps. -> -> **Backend note.** Steps 0, 2, and 4 — the gates and the grills — are identical either way, and so is every judgement call below (fog vs question, in scope vs out, the destination test). What differs is where Steps 3 and 5-7 put the bytes: on `**Backend:** github`, `github-issues.md` overrides the `map.md` and question-file templates here, the single-pass rule under *Step 6: Numbering and dependency order*, and the timing of the recon. Read it alongside this file, not instead of it. - -Charting produces a map and a set of question files. It resolves nothing by hand. Every judgement below serves one goal: put a sharp question on the map for everything you can phrase now, and leave everything else honestly in the fog. - ---- - -## Step 0: The intent gate - -Pathfinder builds an apparatus — a directory, a map, a file per decision. That apparatus earns its keep only when the way to the destination is genuinely foggy. For a small or already-clear ask it is pure overhead, and creating it before the human has agreed to it is the fastest way to make Pathfinder feel heavy and get in the way. So the gate runs **before the first byte hits disk**. - -You already have the idea name from Auto-Discovery. Do NOT create the directory yet. Say, in substance: - -> "This is Pathfinder. Nothing exists for `` yet. Pathfinder charts a map of the open decisions when an idea is big or unclear to plan — but that is overhead if this is small or already clear. Three ways to go: -> - **Chart it** — I map the open decisions, we clear them one at a time, then hand a draft to `/plan2code-1-plan`. -> - **Straight to `/plan2code-1-plan`** — the way looks clear enough to plan now. -> - **`/plan2code-quick-task`** — small enough to just do. -> -> My read: ``. Which?" - -Rules for the gate: - -- **It is HITL.** You recommend; the human chooses. Never self-select "chart" and start creating files because it is the default path — that is exactly the failure this gate exists to stop. -- **Read the request honestly.** A one-line bugfix, or a change with no open decisions, is not a charting job — recommend an off-ramp and mean it. Reserve "chart" for real fog: several unsettled decisions, unclear scope, or competing designs. A joint Product + Engineering kickoff on a fresh idea is the canonical "chart it" case — a new feature explored by two teams is fog almost by definition. -- **No disk writes.** Naming the idea and talking is free. Creating `specs//pathfinder/` is not — it waits for an explicit "chart." -- **On an off-ramp, route and STOP.** Point at `/plan2code-1-plan` or `/plan2code-quick-task`, create nothing, end the session. If `AGENTS.md` is absent, mention `/plan2code-init` first, as with any handoff. - -This gate and the Step 4 no-fog off-ramp are the same instinct at two moments: the gate is the human's call before any work; the off-ramp is your call once the breadth-first grill has proven there was no fog after all. Either one ending the session without a map is a success, not a failure. - ---- - -## Step 2: The destination grill - -The destination is settled **first** because it fixes scope. Every later judgement — is this a question or fog, is this in scope or past the edge, is this map cleared — is measured against it. A vague destination makes all three unanswerable, and you will spend the rest of the map arguing about boundaries instead of decisions. - -A destination is **one or two lines** describing what exists when the map clears. It is not a feature description. It is not a value proposition. It names the artifact and draws the edge. - -### The script - -Recommend an answer with each probe — the human corrects faster than they compose. Follow the grilling playbook for tone, cadence, and the batching rules; this is the content. - -**Six probes, two batches.** They do not all pass the independence test, so they split: - -| Batch | Probes | Why they go together | -|---|---|---| -| First | 1 (artifact), 2 (person), 6 (forcing function) | Each stands alone. None reads differently under the others' answers. | -| Second | 3 (sacrificial boundary), 4 (smallest arrival), 5 (arrival signal) | All three presuppose an artifact and an actor. Sending them before batch 1 lands asks the human to draw an edge around something unnamed. | - -Two round trips, not six. Three probes each — exactly the cap, so neither batch needs splitting. - -Batch 2 bends the independence test on purpose. The arrival signal (5) can shift under the smallest arrival (4), so strictly it should be held back — but holding it costs a third round trip to catch a conflict that is rare and cheap to spot. The trade is to send them together and reconcile at the recap: if the smallest arrival comes back materially smaller than the artifact you were told about, re-check the arrival signal against it before writing the destination. A knowing trade here, not a licence to batch dependent probes elsewhere. - -**Both batches go through the structured question tool.** Give each probe genuine candidate options with trade-offs and a recommendation; the built-in `Other` path is where the human composes the actor, a further feature to leave out, the arrival signal, or forcing-function detail in their own words. A clicked option is not written verbatim as the destination — the recap-confirmation tool call turns all six answers into the agreed one-or-two-line destination before disk write. - -**Probe 1 — the artifact** - -> "When we are done here, what exists that does not exist now: a plan you hand to `/plan2code-1-plan`, a decision recorded before anyone plans, or a change already made in the codebase? My guess: a plan." - -*Fishing for:* the shape of the destination. Push back if the answer is "the feature working" — that is past the edge of every pathfinder map. Say so plainly: "That is the build. The map ends at the plan for the build." - -**Probe 2 — the person on the other end** - -> "Who uses the result, and what do they do with it the day it lands?" - -*Fishing for:* the actor and the moment of use. Vague actors ("users", "the business") produce vague scope. Push until you get a role someone could name in an approval — compliance officer, on-call SRE, tenant admin. - -**Probe 3 — the sacrificial boundary** - -> "Which of these features are we leaving out this time?" - -Deliver it as a multi-select (`multi` on the web console) of 3–5 features a reasonable person might expect to be included. Every option names a feature ("Scheduled exports"), never a rule to keep ("Exports stay manual"). Each option's description ends "(Leaving this out = …)", naming what that leaves. Offer a recommended preset of the ones you would leave out; the free-text path lets them name another feature. - -*Fishing for:* the first `## Out of scope` bullets — the ticked features become them. This probe does more work than any other. If nothing is ticked, push once: a destination nobody has excluded anything from has not been thought about. The preset is the push. - -**Probe 4 — the smallest arrival** - -> "What is the smallest version that would still count? If only that existed, would you call it done or would you feel cheated?" - -*Fishing for:* the difference between the destination and the wish list. Everything above the smallest arrival is a candidate for out of scope or for a later effort. - -**Probe 5 — the arrival signal** - -> "How will you know it's done — what do you look at?" - -*Fishing for:* a checkable condition. "It feels right" is not one. "Every open decision has an answer and I can hand the draft to planning without re-litigating format" is one. - -**Probe 6 — the forcing function** - -> "What made this come up now? A deadline, an incident, an audit, a customer?" - -*Fishing for:* constraints that will shape half the questions and that nobody volunteers unprompted. A regulatory deadline changes the delivery question, the testing posture question, and the out-of-scope line all at once. - -**The probe names above are internal labels, not headings the human reads.** Head each Q block plainly — *What you end up with*, *Who uses it*, *Leave for later*, *Smallest version that counts*, *How you know it's done*, *Why now* — and keep the probe text itself as plain as the quotes above. "The sacrificial boundary" and "the arrival signal" mean something to this playbook and nothing to the person answering. Full rule in the grilling playbook, *Say it in plain English*. - -### Worked example — same idea, two destinations - -**Idea:** "we should let people export audit logs" - -**BAD destination** - -> Let users export audit logs so they have their data. - -Why it fails, concretely: - -| Failure | Consequence downstream | -|---|---| -| No artifact named | Nobody knows whether the map clears at a plan or at shipped code | -| "Users" is not a role | The authorization question cannot even be phrased | -| No edge | Live streaming, SIEM push, and a schema redesign all argue their way in | -| No arrival signal | The Clearing Gate has nothing to check against | -| "their data" is a rationale, not a boundary | Every fog bullet reads as in scope | - -**GOOD destination** - -> A locked implementation plan for a compliance officer to export a filtered range of audit events from the admin UI and receive them as a single downloadable file. The map ends at the plan, not at shipped code. Continuous streaming to external systems is not on the route. - -Three sentences, two lines of substance: artifact (a plan), actor (compliance officer), trigger surface (admin UI), shape of the result (one downloadable file), and an explicit edge (no streaming). Every one of those clauses will be cited later when you decide whether something is a question, fog, or out of scope. - -**Write the destination into `map.md` verbatim as agreed.** Do not improve it afterwards. If it needs changing, change it with the human present — a silently redrawn destination invalidates every scope call already made. - ---- - -## Step 3: Codebase recon - -Recon is `legwork · AFK` — you do it alone, and you write it down **already resolved**. It exists so that no later session re-reads the same directories, and so that the handoff carries the ground truth `/plan2code-1-plan` Phase 2 (System Context Examination) would otherwise have to rediscover. - -`questions/00-codebase-context.md` is always `00`. It always exists. It is created with `State: resolved` and a filled `## Answer` in the same write. - -### What to explore - -| Area | What to establish | Where to look | -|---|---|---| -| **Directory structure** | The map of the repo at the depth that matters for this destination — not every folder, the ones the work will touch | Top-level listing, then two levels into the relevant subtrees | -| **Key components** | The modules that would be read, changed, or called. Name, path, responsibility | Entry points, route/controller registries, service layers | -| **Patterns and conventions** | How this codebase does the thing you are about to plan: error handling, validation, config, module layout, naming, async style | Two or three recent files in the target area, plus `AGENTS.md` | -| **Integration points** | External systems, queues, storage, auth providers, feature-flag services the work will cross | Config files, environment variable references, client wrappers | -| **Technical debt in the blast radius** | Only debt the destination would collide with. Not a repo-wide audit | Long files in the target area, duplicated helpers, stale TODO markers with no owner | -| **System boundaries** | What this effort owns versus what it merely calls. Where the change stops | Package boundaries, ownership files, API contracts | - -Two disciplines keep this file useful: - -- **Verify behaviour against actual code, never against a filename.** A file called `auditLogger.ts` may log nothing. -- **Scope the recon to the destination.** A recon of the whole repo is unreadable and stale in a week. If a subtree cannot plausibly be touched by the destination, say so in one line and move on. - -Record what you could **not** determine as an explicit gap. Gaps at recon time are often the first real fog bullets. - -### The literal file - -```markdown -> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete. - -# Codebase context - -Type: legwork · AFK -State: resolved -Blocked by: none -Claimed: 2026-08-03 09:12 -Resolved: 2026-08-03 -Locked: no - -## Question - -What does this codebase already provide, constrain, and forbid for an operator-initiated -audit-log export? Establish structure, components, conventions, integrations, debt in the -blast radius, and boundaries — enough that no later session re-reads the same ground and -enough to hand to `/plan2code-1-plan` as its system context. - -## Answer - -### Directory structure - -- `src/api/` — Express routers, one file per resource. `src/api/admin/` is the admin surface. -- `src/services/` — business logic; the only layer allowed to touch `src/db/`. -- `src/db/` — Knex query builders and migrations. `audit_events` lives here. -- `src/jobs/` — BullMQ workers. Existing precedent for long-running work. -- `src/web/admin/` — React admin UI, TanStack Query, colocated route components. -- `test/` — Vitest, mirroring `src/` one-to-one. - -Untouched by this destination: `src/billing/`, `src/web/marketing/`. - -### Key components - -| Component | Path | Responsibility | -|---|---|---| -| `auditEvents.record()` | `src/services/auditEvents.ts` | Sole writer of `audit_events`; called from 31 sites | -| `adminRouter` | `src/api/admin/index.ts` | Mounts admin routes; applies `requireAdmin` | -| `requireAdmin` | `src/api/middleware/auth.ts` | Session check plus role check; no per-tenant scoping today | -| `reportQueue` | `src/jobs/reportQueue.ts` | BullMQ queue used by the existing billing report export | -| `signedUrl()` | `src/services/storage.ts` | S3 pre-signed URL helper, fixed 15-minute expiry | - -### Patterns and conventions - -- Errors: typed error classes thrown from services, mapped to HTTP by `errorHandler`. Never raw `res.status(500)`. -- Validation: Zod schema per route, exported next to the handler. -- Config: everything through `src/config.ts`; no direct `process.env` reads outside it. -- Async: `async`/`await` throughout. No callback style remains. -- Long-running work: enqueue to BullMQ, return `202` with a job id. Established by billing reports. -- Tests: Vitest, colocated fixtures, no shared mutable state between cases. - -### Integration points - -- **Postgres 15** via Knex. `audit_events` is ~180M rows, partitioned monthly. -- **Redis** backing BullMQ. -- **S3** for generated artifacts; the billing export already writes there. -- **SES** for transactional mail; templates in `src/mail/templates/`. -- No SIEM, log-shipping, or streaming integration exists today. - -### Technical debt in the blast radius - -- `audit_events` has an index on `(tenant_id, created_at)` but none on `actor_id`. Any - actor-filtered export will sequential-scan a partition. -- `requireAdmin` does not scope by tenant — a platform admin currently sees all tenants. - Any authorization decision here inherits that gap. -- The billing export writes CSV by hand-rolled string concatenation with no escaping. - Do not copy it. - -### System boundaries - -Owned by this effort: a read path over `audit_events`, an admin UI surface, an artifact -written to S3, and a delivery notification. Not owned: the write path (`auditEvents.record()` -is untouched), the audit event schema, tenancy semantics in `requireAdmin`. - -### Gaps - -- Retention policy for `audit_events` is not expressed anywhere in code. Someone outside - engineering owns it. -- No load figures exist for the largest tenant's monthly event count. - -**Gist:** Node/Express/Knex/React with an established BullMQ-to-S3 export precedent from -billing; `audit_events` is 180M rows partitioned monthly with no `actor_id` index, and -`requireAdmin` has no per-tenant scoping. - -## Evidence - -- `src/api/admin/index.ts`, `src/api/middleware/auth.ts` -- `src/services/auditEvents.ts`, `src/services/storage.ts` -- `src/jobs/reportQueue.ts` and the billing export job it drives -- `src/db/migrations/20240914_partition_audit_events.js` -- `AGENTS.md` (conventions section) -``` - ---- - -## Step 4: The breadth-first frontier grill - -The destination grill went **deep on one thing**. This grill goes **wide on everything**. They are different activities and mixing them is the most common way to produce a bad map. - -| | Destination grill (Step 2) | Frontier grill (Step 4) | -|---|---|---| -| Goal | One or two settled lines | An inventory of open decisions | -| Movement | Drill until it is precise | Fan out until you stop finding new areas | -| Follow-ups | Chase every hedge | One clarifier at most, then move on | -| Success | The human commits to a boundary | You can name the areas, sharp and unsharp alike | -| Failure mode | Accepting a slogan | Solving a question instead of finding the next one | - -**You are not resolving anything here.** You are taking inventory. The instant an answer feels satisfying, you are probably going deep. - -### Recognising that you have gone deep - -Watch for these. Any one of them means stop and pull back: - -- You have asked three consecutive probes about the same area. -- You are discussing an implementation detail (a column type, a library, a retry count) rather than a decision. -- You are proposing a design instead of asking what has to be decided. -- The human is enjoying it. Depth is more fun than breadth; that is exactly why it steals the session. -- You have written something down that reads like an answer. - -### Pulling back - -Say it out loud so the human tracks the move, then jump: - -> "Good — that is one for the map, not for now. Parking it as *Export format*. Different corner: who is allowed to run an export at all?" - -Two mechanics keep the fan-out honest: - -1. **Round-robin the areas.** Before you start, list the axes you intend to cross — engineering axes (data, surface, permissions, volume, delivery, failure, operations, testing) AND product axes (user value, success measurement, target user, rollout, analytics, support & docs, legal/compliance). Not every axis applies to every destination: name the ones that do before the first probe, say which you are skipping and why, then take one probe per axis before any second probe on any axis. -2. **Ask for the axis you have not touched.** Near the end: "What have I not asked about that would embarrass us to discover in week three?" - -**Breadth-first is the ideal batch.** One probe per axis means the probes are independent by construction — that is what breadth-first *means* — so this grill should run as batches of three, not as a stream of singles. If you catch yourself wanting to batch two probes on the same axis, that is depth wearing a batch's clothes; pull back. - -**With Product in the room, the product axes are not optional.** A joint Product + Engineering session that only fans out across engineering axes produces a map Product cannot answer for — and vice versa. Alternate: an engineering batch, then a product batch, so neither team spectates for three turns straight. - -### Sample breadth probes - -Each opens a different axis. Batch three at a time in list order (skipping axes you ruled inapplicable), with probe 7 riding alongside the "what have I not asked about" closer above; note each answer and move. - -**Every batch goes through the structured question tool.** The output is a *sort* into sharp question or fog, so the option descriptions carry the framing and the built-in `Other` path captures elaboration the named choices miss. Never ask these probes as a prose list when the tool exists. - -1. **Data** — "What is the smallest and largest thing an operator could reasonably ask for in one export? Give me both ends." -2. **Surface** — "Where does this start: a button in the admin UI, a scheduled thing, an API call someone scripts?" -3. **Permissions** — "Who is allowed to run one, and can they export events about people other than themselves?" -4. **Volume and time** — "If an export takes four minutes, is that fine, bad, or a redesign?" -5. **Delivery and failure** — "The export succeeds but the download link expires before they click it. What should have happened?" -6. **Operations** — "Six months from now someone asks who exported what. Does this feature audit itself?" -7. **Testing** — "What would you need to see pass before you would let this near a customer's compliance data?" *(This one always runs — see the mandatory testing-posture question below.)* - -The product axes, same style — one sample probe each: - -8. **User value** — "A compliance officer gets this feature Monday morning. What stops being painful for them that day?" -9. **Success measurement** — "Three months after ship, what number or behavior tells you this was worth building?" -10. **Target user** — "Who is this for first — every tenant, one segment, one named customer who asked?" -11. **Rollout** — "Does this land for everyone at once, behind a flag, or piloted with one tenant first?" -12. **Analytics** — "What do you want to know about how people actually use it — and is any of that instrumented today?" -13. **Support & docs** — "A support ticket about this lands in week one. What does the agent need to see to answer it without escalating?" -14. **Legal / compliance** — "Does anything here touch data retention, privacy, or a regulator's definition of a record?" - -Record each answer as one line in your working notes with an area label. At the end of the grill you will have two piles: lines you can turn into a sharp question, and lines you cannot. The second pile is the fog. - ---- - -## The fog-vs-question test - -This is the single most important judgement in the skill. Get it wrong toward questions and the map fills with unanswerable stubs that block the frontier. Get it wrong toward fog and the map has nothing takeable on it. - -> **The test is whether you can STATE the question precisely now — not whether you can ANSWER it now.** - -- **Write a question file** when the question is already sharp — *even if it is blocked and nobody can act on it yet*. Blocked questions are real questions; they get `Blocked by:` and a `[!]` row and they wait. Blocked is not the same as unformed. -- **Leave it in `## Not yet specified`** when you cannot yet phrase it that sharply. You can see there is something there; you cannot say what is being asked. - -**Do not pre-slice the fog.** A fog patch is deliberately coarser than a question. One patch may graduate into three questions, or one, or none once the frontier reaches it. Splitting fog into question-shaped fragments before it is sharp invents a structure that the answers will contradict, and it costs a later session the work of deleting your guesses. Write the patch as loosely as the view allows. - -A useful forcing check: **could a different person, reading only this line, know what a good answer looks like?** If yes, it is a question. If they would have to ask you what you meant, it is fog. - -### Worked examples - -| Candidate | Verdict | Reasoning | -|---|---|---| -| "CSV or JSONL for the export file?" | **Question** | Two named options, one decision, one sitting. A reader knows what an answer looks like. `grill · HITL`. | -| "Which roles may export events about other users?" | **Question**, blocked | Sharp today, but it depends on the tenant-scoping decision. Write it, set `Blocked by:`, mark the row `[!]`. Blockedness never demotes a sharp question to fog. | -| "Something about how big exports behave" | **Fog** | "Big" has no meaning until the volume ceiling lands. You cannot say whether the question is about pagination, streaming, timeouts, or refusal. One line in `## Not yet specified`. | -| "There is probably something about PII redaction" | **Fog** | The area is visible, the question is not. Once Legal answers, this may graduate into *which fields are redacted*, *who configures it*, and *does redaction apply to the actor or the subject* — or into nothing, if the answer is "export raw." Slicing it now guesses all three. | -| "How should we architect the export pipeline?" | **Neither — split it** | No single answer closes it; it bundles at least four decisions (sync vs queued, storage target, artifact lifetime, notification). Ask what the parts are. The sharp parts become questions, the rest becomes fog. A candidate no single answer closes is not a question. | - -**What never belongs in `## Not yet specified`:** anything already decided (it is a resolved question with a gist on its row), anything that already has a question file, and anything past the destination (that is out of scope). - ---- - -## Out of scope versus fog - -Fog gathers **only toward the destination**. The destination fixes the scope, so work beyond it is not dim — it is *excluded*. It is not fog, and it must never sit in `## Not yet specified`, where a later session would try to graduate it. - -**The distinction is SCOPE, not sharpness.** This is the part people get wrong. An out-of-scope item can be perfectly sharp — "should the export push to Splunk on a schedule?" is a crisp question with a crisp answer. It is still out of scope, because the destination said the map ends at an operator-initiated export. Sharpness decides *fog versus question*. Position relative to the destination decides *in scope versus out*. - -| | Fog (`## Not yet specified`) | Out of scope (`## Out of scope`) | -|---|---|---| -| Position | Before the destination | Past the destination | -| Why it is not a question | Cannot be phrased sharply yet | Could be phrased perfectly — it just is not ours | -| Future | Graduates into questions as the frontier advances | Never graduates | -| Reopening | Automatic, as answers land | Only if the destination is redrawn — and then as a fresh effort, not a resumption | -| The act | An admission of ignorance | A scoping decision | - -Ruling something out of scope is a **scoping act, not a step on the route**. When a question you already created turns out to sit past the destination — mis-scoped in during charting, or exposed by a later answer — run `rule-out --reason ""` (resolve.md, Ruling a question out of scope mid-work): it sets `State: out-of-scope`, marks its row `[-]` and leaves one linked line in `## Out of scope` with the reason. Then handle anything it reports `stranded`. It does not get an `## Answer` and it is not a decision the route walked. - -Watch for **stranded** questions: a live question whose `Blocked by:` names something now out of scope will never unblock. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting. - ---- - -## Step 6: Numbering and dependency order - -Upstream wayfinder creates every unit first and wires the blocking edges in a **second pass**, because a server-side tracker assigns ids and nothing can reference a sibling until it has one. On `**Backend:** local` that constraint does not exist — **you choose `NN` yourself**, so charting is a **single pass**: decide the order, then write each file complete, `Blocked by:` filled at the moment of writing. - -(On `**Backend:** github` the constraint comes back, and so does the two-pass shape. Rules 1, 6, 7, and 8 below still hold — they are about dependency reasoning, not about ids. Rules 2-5, which are about `NN`, are replaced by sub-issue order; see `github-issues.md`.) - -The rules: - -1. **Sort by dependency before you write anything.** Sketch the edges on paper first: which decisions must land before which others can even be discussed. -2. **Blockers get lower numbers.** If *Row-count ceiling* blocks *Delivery channel*, the ceiling is `02` and delivery is `05`. This makes `Blocked by: 02` readable at a glance and makes "lowest `NN` first" on the frontier a sane traversal order. -3. **`00` is always the codebase context.** Never anything else. -4. **`NN` is never reused and never renumbered.** Not when a question is ruled out of scope, not when one is deleted, not to close a gap in the sequence. Links and `Blocked by:` lines would rot silently. Gaps in the numbering are normal and harmless. -5. **The next number is max + 1**, and `frontier` reports it as `nextNN`: one past the highest `NN` in the directory listing, on any `Blocked by:` line, or in any `questions/NN-` link in the map or a question file, and never below the map's `**Next NN:**` line. That line is a high-water mark the script keeps (every write command updates it, and it only rises), so even a deleted question that nothing links to any more never has its number handed out again. Never edit it by hand. -6. **Only depend on what genuinely gates the question.** A `Blocked by:` chain that is really a preference for reading order strangles the frontier. Ask: could this question be answered — badly but honestly — without the blocker? If yes, it is not blocked. -7. **Cycles are a phrasing bug.** If A blocks B and B blocks A, the two are one decision. Merge them or re-frame one to drop the edge. -8. **Refer by name in prose.** Bare numbers appear only on `Blocked by:` lines. - -A worked ordering for the audit-log export map: - -| `NN` | Name | Type | Blocked by | Why here | -|---|---|---|---|---| -| `00` | Codebase context | `legwork · AFK` | none | Always first, always resolved | -| `01` | Export format | `grill · HITL` | none | Nothing gates it; it gates the artifact shape | -| `02` | Row-count ceiling | `research · AFK` | none | A fact about the data, independent of every preference | -| `03` | Export authorization | `grill · HITL` | none | Independent axis; can be argued today | -| `04` | Testing posture | `grill · HITL` | none | Mandatory; independent of everything else | -| `05` | Delivery channel | `grill · HITL` | `02` | Synchronous download versus queued link turns entirely on volume | -| `06` | SIEM push connector | `grill · HITL` | none | Created, then immediately ruled out of scope during charting — `State: out-of-scope`, no `## Answer` | - ---- - -## The `map.md` template - -Below is a complete, realistic map for the audit-log export effort **partway through MODE B**, after two questions have resolved — it shows every marker in use. At Chart Step 5 the same file carries `**Status:** Charting`, an empty `## Question Checklist`, and no `[x]` row except `00`. Copy the structure exactly, including the HTML comments — they are written **for the next session**, which has no memory of this one. - -`**Status:**` is `Charting` while Step 5 and Step 6 run, becomes `Working` at Step 7, and becomes `Cleared` only at handoff. It is how the orchestrator routes a fresh session, so it must be accurate before you stop. - -Set `**Confidence:**` honestly at Step 5 and re-score it every time a question resolves. Charting scores are low by construction — that is the point. The Clearing Gate needs every dimension at 18/25 or better. Never inflate to make the gate pass. - -Write the four dimension labels **hyphenated exactly as shown** — `Requirements-clarity`, `Feasibility-technical`, `Integration-points`, `Risk-assessment` — in the `NN/25` form, with no percent symbol anywhere in the file. The metrics collector scrapes planning documents by regex for a bare dimension word followed by whitespace, a colon, or a pipe and then digits; the hyphen breaks that match. A percent sign or a bare `Requirements 18` would be ingested as a completed planning step's confidence score that no planning step ever produced. - -Say once, at Step 5: *"This map lives in gitignored `specs/` — local to you, not shared. `git add -f` it to track it."* - -```markdown -> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete. - -# Map: audit-log-export - -*Decisions live in `questions/` — one file each. This file is just the index.* - -**Status:** Working -**Updated:** 2026-08-03 -**Confidence:** Requirements-clarity 18/25 · Feasibility-technical 14/25 · Integration-points 16/25 · Risk-assessment 14/25 -**Next NN:** 07 - - - - - - - -## Destination - -A locked implementation plan for a compliance officer to export a filtered range of audit -events from the admin UI and receive them as a single downloadable file. The map ends at the -plan, not at shipped code. Continuous streaming to external systems is not on the route. - - - -## Ground rules - - - -- `AGENTS.md` exists and governs. Its conventions are not re-litigated by any question here. -- One question _file_ at a time; the fork-menu between decisions; a fresh session recommended after ~3. `research` questions may run as parallel subagents. -- Every user-facing question uses the structured question tool when available; probes batch at most three. Prose Q blocks are fallback only when the tool is unavailable. -- Questions are put to the human in plain English. Technical terms only where the term is the decision. -- HITL questions are answered by the human in their own words. Never self-answered. -- No new runtime dependency is assumed without a `research` question backing it. -- Compliance language is reviewed by Dana before anything user-facing is finalised. -- Sketches are throwaway and live only under `pathfinder/sketch-NN/`. - -## Glossary - - - -| Term | Meaning here | Avoid | -|---|---|---| -| Audit event | One row in `audit_events`: actor, tenant, action, target, timestamp, payload | log line, activity record | -| Compliance officer | Tenant-scoped role that reviews activity; not a platform admin | admin, auditor | -| Export | One operator-initiated request producing one artifact for one filtered range | download, dump, extract | -| Retention window | How far back `audit_events` is queryable; owned outside engineering | archive period | -| Signed artifact | The generated file plus a checksum a recipient can verify independently | signed file, bundle | - -## Question Checklist - - - -- [x] [Codebase context](./questions/00-codebase-context.md) — Node/Express/Knex/React with a BullMQ-to-S3 export precedent; `audit_events` is 180M rows partitioned monthly, no `actor_id` index, `requireAdmin` has no tenant scoping. *(2026-08-03)* -- [x] [Export format](./questions/01-export-format.md) — CSV with a UTF-8 BOM and RFC 4180 quoting, plus a sidecar SHA-256 manifest; JSONL rejected because recipients open these in Excel. *(2026-08-03)* -- [/] [Row-count ceiling](./questions/02-row-count-ceiling.md) -- [ ] [Export authorization](./questions/03-export-authorization.md) -- [ ] [Testing posture](./questions/04-testing-posture.md) -- [!] [Delivery channel](./questions/05-delivery-channel.md) — Blocked by 02 -- [-] [SIEM push connector](./questions/06-siem-push-connector.md) — out of scope, see below - -## Not yet specified - - - -- How far back an export may reach. There is a retention answer somewhere outside engineering - and nobody has it yet; until then we cannot say whether the question is about a hard limit, - a warning, or a per-tenant setting. -- Redaction of event payloads. Legal may say "export raw", in which case this evaporates — - or it may become several decisions about which fields, who configures them, and whether the - rule follows the actor or the subject. Revisit after Export authorization. -- What happens when an export range straddles a monthly partition that was migrated mid-range. - Cannot phrase this sharply until Export format is applied to a real query plan. -- Whether the export feature audits itself, and if so at what granularity. Suspect this is one - small question but it may turn on the authorization model. - -## Out of scope - - - -- [SIEM push connector](./questions/06-siem-push-connector.md) — scheduled push to Splunk or - similar. The destination ends at an operator-initiated export; anything continuous is a - different effort with a different owner. -- Redesign of the `audit_events` schema. The write path is untouched by this destination; - changing it would pull in all 31 call sites of `auditEvents.record()`. -- Adding the missing `actor_id` index. Real, and it will hurt, but it is a database change - with its own review path. Recorded here so the plan can reference it as a dependency - rather than absorb it. -``` - ---- - -## The question-file template - -Six contiguous `Key: value` lines after the H1. Not YAML. No frontmatter delimiters. No `- [ ]` checkboxes anywhere inside a question file — use plain bullets, including for legwork checklists. - -`## Question` is written at charting. `## Answer` is appended only when the question resolves. `## Evidence` holds sources, links, and artifacts, and a `research` subagent writes into it during Chart Step 8 without deciding anything. - -### An open question - -```markdown -> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete. - -# Export authorization - -Type: grill · HITL -State: open -Blocked by: none -Claimed: none -Resolved: none -Locked: yes - -## Question - -Who may run an audit-log export, and over whose events? - -Three sub-decisions, all of which must land together because any two of them constrain the third: - -- Which role gates the export action — the existing `admin` role, a new `compliance` role, or - a per-tenant grant? -- May an exporter include events where they are the actor, or must self-events be excluded to - keep the export usable as evidence? -- `requireAdmin` currently does not scope by tenant, so a platform admin sees every tenant's - events. Does the export inherit that, or does it enforce a tenant scope the rest of the - admin surface does not? - -Recommended answer to react to: a new tenant-scoped `compliance` role; self-events included -but flagged in a column; the export enforces tenant scope even though the surrounding admin -surface does not. - -Marked `Locked: yes` — the third sub-decision creates a precedent that later admin features -will follow, and reversing it later means re-auditing every export already delivered. - -## Evidence - -- `src/api/middleware/auth.ts` — `requireAdmin` checks session and role, no tenant predicate. -- Codebase context records the same gap under technical debt. -``` - -### A resolved question - -```markdown -> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete. - -# Export format - -Type: grill · HITL -State: resolved -Blocked by: none -Claimed: 2026-08-03 10:41 -Resolved: 2026-08-03 -Locked: yes - -## Question - -What file format does an export produce, and what does a recipient need in order to trust the -file has not been altered? - -## Answer - -**Decision.** CSV, UTF-8 with a byte-order mark, RFC 4180 quoting, one header row, timestamps -in ISO 8601 UTC. Alongside it a sidecar `.sha256` manifest listing the artifact filename and -its digest. - -**Rejected.** - -- *JSONL* — better for nested payloads and trivially streamable, but every named recipient - opens these in Excel and would need a conversion step during an audit. The people who - prefer JSONL are not the people receiving the file. -- *XLSX* — solves the Excel encoding problems outright, but adds a generation library and - makes byte-level verification of the artifact meaningfully harder. -- *Detached signature instead of a checksum* — real integrity guarantees, but requires key - management nobody has scoped, and no recipient has asked to verify a signature. - -**Consequences.** - -- Nested `payload` is flattened to one JSON string column. Anyone needing structure parses - that column. -- The BOM is required or Excel mangles non-ASCII actor names. This must be an explicit test. -- Do not reuse the billing export's CSV writer — it concatenates strings with no escaping. - A quoting-correct writer is now in scope for the plan. -- The checksum makes the artifact self-verifying, which lets Delivery channel consider a - short-lived link without weakening the integrity story. - -**Gist:** CSV with a UTF-8 BOM and RFC 4180 quoting, plus a sidecar SHA-256 manifest; JSONL -rejected because recipients open these in Excel. - -## Evidence - -- RFC 4180, sections 2.5-2.7 (quoting and embedded delimiters). -- `src/jobs/billingExport.ts` — the hand-rolled writer that must not be copied. -- Dana confirmed on 2026-08-03 that external auditors accept a published checksum. -``` - ---- - -## Step 4: The no-fog off-ramp - -If the breadth-first grill surfaces **no fog** — every area you opened produced either a settled answer or a question you could phrase immediately, and `## Not yet specified` would be empty — then the way to the destination is already visible. The journey is small enough to plan directly and a map would be pure overhead. - -Do this, in order: - -1. **Keep `questions/00-codebase-context.md`.** This is the important part. It is exactly what `/plan2code-1-plan` Phase 2 (System Context Examination) has to produce anyway, and you have already produced it. Throwing the recon away to "clean up" wastes the most valuable artifact of the session. -2. **Do not create `map.md`.** The off-ramp fires at Step 4 and the map is not written until Step 5, so in the normal flow there is nothing to delete — just stop before writing it. (If you reached Step 4 with a `map.md` already on disk, delete it: a map with empty fog and no open questions will confuse the next session into resuming something that does not exist.) -3. **Tell the user plainly what happened and what to do:** - - > "No fog surfaced — the way to the destination is already visible, so this does not need a map. I kept the codebase recon at `specs/audit-log-export/pathfinder/questions/00-codebase-context.md`; attach that file to a `/plan2code-1-plan` session and it covers Phase 2 outright." - -4. **Stop.** Do not chart anyway "just in case", do not create questions, do not start planning in this session. - -Be honest about the trigger. If two areas are genuinely unformed, that is fog and the map earns its keep. The off-ramp is for the case where you fanned out across every axis and kept landing on solid ground. - ---- - -## Step 6: The mandatory testing-posture question - -**Every map includes a `grill · HITL` question on testing posture.** No exceptions, including maps where testing feels obvious. - -The reason is mechanical: `/plan2code-1-plan` Phase 1 asks for three things — testing types, whether tests run after each implementation phase, and a coverage target — and `/plan2code-2-document` **string-matches** that answer, either appending a testing block to every phase, creating a dedicated final testing phase, or omitting testing entirely. A map that clears without this answer hands the human a planning session that stalls on its first question. Ask it while there is still someone in the room. - -Record the answer in the literals downstream matches on, not in paraphrase. ("Phase" here names `/plan2code-1-plan`'s implementation phases and is a downstream contract string — it is never a pathfinder unit of work.) - -It is almost never blocked. Give it whatever number the dependency ordering leaves free, and expect it to sit on the frontier from day one. - -```markdown -> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete. - -# Testing posture - -Type: grill · HITL -State: open -Blocked by: none -Claimed: none -Resolved: none -Locked: no - -## Question - -What testing does this work carry, so `/plan2code-1-plan` Phase 1 can be answered without -stalling? Three parts, all needed: - -- **Types** — unit, integration, end-to-end, some combination, or none. -- **Phase testing** — record one of the two literals `/plan2code-2-document` matches: - `Run after each phase` (a testing block closes every implementation phase) or - `Dedicated phase only` (one final testing phase). -- **Coverage target** — record one of Phase 1's three literals: `Critical paths`, - `Moderate (~60-80%)`, or `Comprehensive (>80%)`. - -Recommended answer to react to: unit plus integration; `Run after each phase`; -`Critical paths`. Rationale — this touches compliance data, so the correctness of the -CSV writer and the authorization predicate must be pinned by tests, but the admin UI is thin -enough that end-to-end coverage would cost more than it catches. - -Two specific cases worth naming in the answer regardless of the general posture, because -Codebase context shows both are easy to get wrong here: - -- The UTF-8 BOM survives Excel round-tripping for non-ASCII actor names. -- The tenant-scope predicate actually excludes other tenants' events, asserted against seeded - cross-tenant data rather than a mock. - -Note for whoever resolves this: the coverage target is a number the human owns. Do not infer -it from the codebase's current coverage, and do not soften it to whatever the repo already -achieves. - -## Evidence - -- `AGENTS.md` records Vitest as the runner with fixtures colocated under `test/`. -- Codebase context: no end-to-end harness exists today; adding one is a real cost, not a flag. -``` \ No newline at end of file diff --git a/skills/plan2code-0-pathfinder/references/github-issues.md b/skills/plan2code-0-pathfinder/references/github-issues.md deleted file mode 100644 index 2a5bc3f..0000000 --- a/skills/plan2code-0-pathfinder/references/github-issues.md +++ /dev/null @@ -1,474 +0,0 @@ -# GitHub Issues Backend - -> Part of plan2code-0-pathfinder — loaded at the top of EVERY session whose map lives on GitHub Issues. It re-expresses the local-file model in issue terms: where the map lives, where a question lives, how blocking, claiming, and resolving are done, and what stays on local disk regardless. -> -> **Local-file maps never load this file.** If `## Ground rules` says `**Backend:** local`, close it and use `questions.md`. - -Everything the skill says about *judgement* is unchanged by the backend: the fog-vs-question test, the destination grill, one question at a time, the decide-menu-checkpoint cadence, HITL is never self-answered, the Clearing Gate rubric. This file changes only *where the bytes go*. - ---- - -## Why a second backend exists - -Local files are private scratch — `specs/` is gitignored, so the map is yours alone and nobody else can see it, comment on it, or resolve a question in parallel. That is the right default for a solo effort. - -A map on GitHub Issues buys three things local files cannot: - -| | Local files | GitHub Issues | -|---|---|---| -| Visibility | One machine, one person | Anyone with repo access, in a UI they already have open | -| Blocking | A `Blocked by:` line only an agent reads | Native issue dependencies — GitHub greys out blocked issues in its own UI | -| Concurrency | One session at a time by construction | Several people can work unblocked questions at once; the assignee is a real lock | - -It costs three things too, and the human must know all three before they pick it: - -1. **Issues on a public repo are public.** The destination, the rejected alternatives, the codebase recon, the technical debt in the blast radius — all of it is world-readable the moment it is written. Never chart to a public repo's tracker anything that would embarrass the project or leak a customer. -2. **It writes to shared state.** A local map costs nothing to abandon. Twelve stale issues labelled `pathfinder:grill-hitl` on a team's tracker is litter someone has to clean. -3. **It needs `gh`, auth, and issues enabled.** More that can break, in a step whose whole job is to remove friction. - ---- - -## Preflight — before the first write - -Run these once, at Chart Step 1, **before** offering GitHub as an option. Any failure means GitHub is not offered at all; say why in one line and continue with local files. - -| # | Check | Command | On failure | -|---|---|---|---| -| 1 | `gh` is installed | `gh --version` | Not offered — "no `gh` on this machine" | -| 2 | Authenticated | `gh auth status` | Not offered — "`gh` is not logged in" | -| 3 | Inside a repo with a GitHub remote | `gh repo view --json nameWithOwner,visibility,hasIssuesEnabled` | Not offered — "no GitHub remote here" | -| 4 | Issues are enabled | same call, `hasIssuesEnabled` | Not offered — "issues are disabled on this repo" | -| 5 | Write access | `gh api repos// --jq .permissions.push` | Not offered — read-only access cannot chart | - -Record `nameWithOwner` and `visibility` from check 3 — **`visibility` is not optional detail.** If it is `PUBLIC`, the offer must say so in the same breath, e.g. *"GitHub Issues — note `jparkerweb/plan2code` is public, so the whole map is world-readable."* - -Once a map exists, preflight shrinks to checks 1 and 2. A session that cannot reach `gh` cannot work a GitHub map: say so and stop, rather than silently starting a local one. - -### Labels - -Create the label set at **Chart Step 5**, with the map issue — never during preflight, which must stay read-only until the human has actually picked `github`. `--force` makes it idempotent, so it is safe to re-run every session: - -```bash -gh label create "pathfinder:map" --color 5319E7 --description "Pathfinder map" --force -gh label create "pathfinder:grill-hitl" --color 1D76DB --description "Decision only the human can make" --force -gh label create "pathfinder:research-afk" --color 0E8A16 --description "Fact-finding, agent alone" --force -gh label create "pathfinder:sketch-hitl" --color FBCA04 --description "Human reacts to something concrete" --force -gh label create "pathfinder:legwork-hitl" --color D93F0B --description "Manual work needing a human" --force -gh label create "pathfinder:legwork-afk" --color D93F0B --description "Manual work the agent can do" --force -gh label create "pathfinder:locked" --color B60205 --description "Hard to reverse; consequences recorded" --force -gh label create "pathfinder:out-of-scope" --color CFD3D7 --description "Ruled past the destination" --force -``` - -**Type and mode share one label** — `grill-hitl`, not `grill` plus `hitl` — for the same reason the local `Type:` line is one token: two labels can drift apart, and a `research` question that has quietly become HITL is a question nobody is driving. - ---- - -## The equivalence table - -This is the whole mapping. Everything below expands a row. - -| Local file model | GitHub Issues model | -|---|---| -| `specs//pathfinder/map.md` | One issue, labelled `pathfinder:map`, titled `Map: ` | -| `questions/NN-.md` | A **sub-issue** of the map, titled with the question name | -| `NN` ordering | The map's sub-issue order — the order they were created, which is dependency order | -| `## Question` in the file | The issue body | -| `## Answer` appended | A comment on the issue, opening `## Answer` | -| `## Evidence` | A comment opening `## Evidence` (a research subagent writes its own) | -| `Type:` line | The `pathfinder:-` label | -| `State: open` | Issue open, **no assignee** | -| `State: claimed` | Issue open, **assigned** | -| `State: resolved` | Issue **closed as completed**, with an `## Answer` comment | -| `State: out-of-scope` | Issue **closed as not planned**, labelled `pathfinder:out-of-scope`, no `## Answer` | -| `Blocked by: 02, 04` | Native issue dependencies (`dependencies/blocked_by`) | -| `Locked: yes` | The `pathfinder:locked` label | -| `Claimed: ` | GitHub's own assignment event in the timeline | -| `Resolved: ` | The issue's own close timestamp (`closedAt`) — nothing to write, nothing to backfill | -| `## Question Checklist` in `map.md` | **Nothing** — the frontier is a live query, not a written list | -| `## Not yet specified`, `## Out of scope`, `## Ground rules`, `## Destination`, `## Glossary` | The same sections, in the map issue body | -| `sketch-NN/` | Still local disk — see *What stays on local disk* | -| `PLAN-DRAFT-.md` | Still local disk — see *Handoff* | - -### The checklist is deleted, not ported - -In local mode `map.md` carries a `## Question Checklist` because a directory of files has no queryable state. GitHub has queryable state, so **the map issue body carries no checklist at all.** Closed questions get one line each under `## Decisions so far`; open questions are not listed anywhere. - -This kills the single largest source of drift in the local backend — a checklist that disagrees with the files — and it is why Work Step 2's reconcile pass is much shorter here. - ---- - -## Refer by name - -Unchanged, and harder to get right here because GitHub hands you a number for everything. In prose the human reads, write `[Export format](https://github.com/o/r/issues/42)` — never `#42`, never "issue 42", never a bare number. A wall of `#42, #43, #44` is illegible; names read at a glance. - -Bare `#` appears in exactly two places: inside a fallback `Blocked by:` body line when native dependencies are unavailable, and inside a `gh` command. - ---- - -## Chart Steps 3-4 — hold the recon, protect the off-ramp - -In `local` mode Step 3 writes `questions/00-codebase-context.md` the moment the recon is done, because a file in gitignored scratch costs nothing if the session then takes the Step 4 off-ramp. **On a shared tracker it costs something**: a stray issue nobody asked for, on a repo other people are watching. - -So on `github`, Step 3 does the recon and **holds it in the session**. It becomes an issue at Step 6, alongside the other questions. - -If the Step 4 breadth-first grill surfaces **no fog**, the off-ramp fires before anything has been created: - -1. Write the recon to `specs//pathfinder/questions/00-codebase-context.md` — a **local file**, exactly as the local backend would. It is what `/plan2code-1-plan` Phase 2 needs, and it is too valuable to throw away. -2. Create **nothing** on the tracker. No map issue, no question issues, no labels. -3. Tell the user plainly and STOP. - -The tracker only ever sees an effort that earned a map. - ---- - -## Creating the map (Chart Step 5) - -Title is `Map: ` — the kebab-case idea name, verbatim, so `gh issue list --label pathfinder:map` reads as an index of efforts. - -```bash -gh issue create --label "pathfinder:map" --title "Map: audit-log-export" --body-file - <<'EOF' -> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete. - -**Status:** Charting -**Updated:** 2026-08-08 -**Confidence:** Requirements-clarity 8/25 · Feasibility-technical 6/25 · Integration-points 6/25 · Risk-assessment 5/25 - - - -## Destination - -A locked implementation plan for a compliance officer to export a filtered range of audit -events from the admin UI and receive them as a single downloadable file. The map ends at the -plan, not at shipped code. Continuous streaming to external systems is not on the route. - -## Ground rules - -- **Backend:** github — this issue is the map; questions are its sub-issues. -- `AGENTS.md` exists and governs. Its conventions are not re-litigated by any question here. -- One question _issue_ at a time; the fork-menu between decisions; a fresh session recommended after ~3. `research` questions may run as parallel subagents. -- Every user-facing question uses the structured question tool when available; probes batch at most three. Prose Q blocks are fallback only when the tool is unavailable. -- HITL questions are answered by the human in their own words. Never self-answered. -- Sketches are throwaway and live on local disk only, under `specs/audit-log-export/pathfinder/sketch-/`. - -## Glossary - -| Term | Meaning here | Avoid | -|---|---|---| -| Audit event | One row in `audit_events`: actor, tenant, action, target, timestamp, payload | log line | - -## Decisions so far - - - -## Not yet specified - - - -## Out of scope - - -EOF -``` - -Two things that must be exact: - -- **`**Status:**` is still a literal line in the body.** It is how a fresh session routes, exactly as in local mode. `Charting` → `Working` → `Cleared`. -- **`**Backend:** github` is the first `## Ground rules` bullet.** It is how a fresh session knows to load this file at all. Without it, a session that opens the map issue has no way to know which playbook it is in. - -Confidence keeps the hyphenated `Requirements-clarity 8/25` form for the same reason it does in local mode — the metrics collector scrapes bare dimension words followed by digits, and would ingest a planning confidence nobody scored. - -**Say once, at Step 5:** *"The map lives on `/`'s issue tracker — ``, so ``. Everything charted here is visible there."* - ---- - -## Creating the questions (Chart Step 6) — two passes, not one - -The local backend charts in a **single pass** because you choose `NN` yourself and can write `Blocked by: 02` into a file before `02` exists. **On GitHub that is impossible** — an issue has no id until the server assigns one, and a dependency edge needs the blocker's id. So charting here reverts to upstream's shape: - -**Pass 1 — create every question issue, in dependency order.** Blockers first. The creation order becomes the sub-issue order, which becomes the reading order for the frontier and the trail, so it is doing the job `NN` does locally. Capture each new issue's number *and* database id as you go. - -```bash -# Create, capturing the URL; the number is its last path segment. -gh issue create --label "pathfinder:grill-hitl" --title "Export format" --body-file - <<'EOF' -> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete. - -## Question - -What file format does an export produce, and what does a recipient need in order to trust -the file has not been altered? - -Recommended answer to react to: CSV with a UTF-8 BOM plus a sidecar SHA-256 manifest. -EOF - -# The database id — needed for BOTH wiring steps below. Not the #number, not the node_id. -gh api repos///issues/ --jq .id -``` - -**Pass 2 — wire the structure.** Two edges per question, both keyed on **database ids**: - -```bash -# a) Attach as a sub-issue of the map. sub_issue_id is the CHILD's database id. -gh api --method POST repos///issues//sub_issues \ - -F sub_issue_id= - -# b) Add each blocking edge. issue_id is the BLOCKER's database id. -gh api --method POST repos///issues//dependencies/blocked_by \ - -F issue_id= -``` - -**The database id is the single most common failure in this backend.** `gh api repos/o/r/issues/42 --jq .id` returns something like `2716143027`. The `42` is the *number*; `I_kwDO...` is the *node id*. The node id is rejected outright. The *number* is worse: a small integer like `42` is itself a perfectly valid database id — of some unrelated issue created years ago — so the call can succeed and silently attach the wrong thing. Fetch `.id` for every issue you are about to reference, and never hand-assemble one. - -Charting still writes `00-codebase-context`'s equivalent — the Step 3 recon you held. Create it **first**, labelled `pathfinder:legwork-afk`, post the recon as an `## Answer` comment, and close it as completed in the same pass. It is resolved on arrival, exactly as in local mode, and it is what the handoff's `## System Context` is built from. - -### If the endpoints are unavailable - -Sub-issues and dependencies are recent GitHub features. On an instance that rejects either endpoint, fall back in the body — and say plainly, once, that the frontier will not render in GitHub's UI: - -| Missing | Fallback | -|---|---| -| Sub-issues | Put `Part of #` on the first line of each question body, and a task list of the questions in the map body | -| Dependencies | Put `Blocked by: #12, #14` on its own line at the top of the question body | - -Prefer the native mechanisms every time they work. The whole reason to pay GitHub's costs is that the human sees the frontier in the UI without opening the map. - ---- - -## The frontier query (Work Step 3) - -The frontier is every question that is **open, unblocked, and unassigned**. Lowest position in sub-issue order wins — the same traversal `lowest NN first` gives locally. - -```bash -# 1. The map's children, in order, with the state you need to filter on. -gh api repos///issues//sub_issues \ - --jq '.[] | {number, title, state, assignee: .assignee.login, - blocked: .issue_dependencies_summary.blocked_by, - labels: [.labels[].name]}' -``` - -Then, in order: - -1. Drop anything `state: closed` — that is resolved or out of scope. -2. Drop anything with an `assignee` — claimed by another session. -3. Drop anything still blocked. -4. The first survivor is the next question. - -For step 3, `issue_dependencies_summary.blocked_by` counts **open** blockers, which is exactly the live gate — a blocker that closes drops the count without anyone editing anything. **Treat it as a fast pre-filter, not the authority.** If it comes back `null` or absent from the list response, or you need to *name* the blockers for the trail footer or a fully-blocked report, ask the endpoint that owns the answer: - -```bash -gh api repos///issues//dependencies/blocked_by --jq '.[] | {number, title, state, reason: .state_reason}' -``` - -A question is unblocked when every blocker listed there is closed. That call is also the only way to see the next trap: - -**A blocker closed as `not planned` is out of scope and will never resolve.** Its dependent is not merely blocked, it is *stranded* — the same trap as locally. Re-frame the dependent's body to drop the dependency, cut the edge, or rule it out too. Never leave it sitting: the summary count cannot tell you the difference, so this check is on you. - -```bash -# Cut a dependency edge. The blocker's database id goes in the PATH here, not the body. -gh api --method DELETE \ - repos///issues//dependencies/blocked_by/ -``` - ---- - -## Claim (Work Step 4) - -```bash -gh issue edit --add-assignee "@me" -``` - -**The session's first write, before any work.** The assignee *is* the claim — GitHub timestamps it for you, so there is no `Claimed:` line to maintain. An open, unassigned question is unclaimed; that is the whole protocol. - -Unlike the local backend, other people may genuinely be working this map at the same time. Re-read the issue immediately after assigning; if someone else's login is on it, you lost the race — release yours and take the next frontier item. - ---- - -## Resolve (Work Step 7) - -Three writes, in this order. The order matters: the answer must exist before the issue closes, or a crash between them leaves a closed question with no decision in it. - -```bash -# 1. The answer, as a comment. Same anatomy as a local ## Answer: -# decision, rejected alternatives with reasons, consequences, one-line **Gist:**. -gh issue comment --body-file - <<'EOF' -## Answer - -**Decision.** CSV, UTF-8 with a byte-order mark, RFC 4180 quoting, one header row. -Alongside it a sidecar `.sha256` manifest. - -**Rejected.** - -- *JSONL* — trivially streamable, but every named recipient opens these in Excel. -- *XLSX* — fixes Excel encoding, but adds a library and makes byte-level verification harder. - -**Consequences.** - -- Do not reuse the billing export's CSV writer; it concatenates strings with no escaping. -- Makes [Delivery channel](https://github.com/o/r/issues/45) sharper — the artifact is - self-verifying, so a short-lived link no longer weakens the integrity story. - -**Gist:** CSV with a UTF-8 BOM and RFC 4180 quoting, plus a sidecar SHA-256 manifest; -JSONL rejected because recipients open these in Excel. -EOF - -# 2. Close as completed. -gh issue close --reason completed - -# 3. Append the gist to the map's Decisions so far (read body, edit, write back). -gh issue view --json body --jq .body > /tmp/map.md -# ...append: - [Export format]() — *(YYYY-MM-DD)* -gh issue edit --body-file /tmp/map.md -``` - -Then bump `**Updated:**` and re-score `**Confidence:**` in the same map edit. - -**The close date IS the `Resolved:` date.** There is no line to set and none to backfill — `closedAt` is written by GitHub the moment step 2 runs, and a brief filters on it. Stamp the same date in italics on the `## Decisions so far` line so the map reads as a dated record on its own. - -**Never edit the question body to hold the answer.** The body is the question as asked; the comment is the answer. Editing the body rewrites history and destroys the record of what was actually put to the human — which is half of why the answer is defensible three weeks later. - -### Editing the map body safely - -Every map mutation is read-modify-write on a body other sessions may be editing concurrently. Read it fresh immediately before the edit, apply your change to *that* text, and write it straight back. Never edit from a copy you read at the top of the session — you will silently revert whatever landed in between. - ---- - -## Ruling a question out of scope (Work Step 8) - -```bash -gh issue edit --add-label "pathfinder:out-of-scope" -gh issue close --reason "not planned" -``` - -Then one line under the map's `## Out of scope`, giving the name as a link plus the reason. **No `## Answer` comment** — there is no decision here, only a scope boundary. Add one comment saying why it is out, so the closed issue explains itself. - -`not planned` versus `completed` is the load-bearing distinction: it is how a later session tells a decision that was made from a question that was ruled off the route, and it is what GitHub's UI shows at a glance. Getting it backwards puts a scope boundary into the Provenance table of the plan. - ---- - -## Reconcile (Work Step 2) - -Much shorter here — the tracker holds the state, so there is no checklist to rebuild. Four checks: - -| Check | Symptom | Repair | -|---|---|---| -| Crashed mid-answer | Open, assigned, and an `## Answer` comment already exists | The comment wins. Close as completed, add the gist to Decisions so far, say so. | -| Stale claim | Open, assigned, no `## Answer`, and the assignee is you from a dead session | Unassign, say so, put it back on the frontier. **If it is someone else's login, leave it** — that is a live session, not a crash. | -| Interrupted research | An open `research` question with no `## Evidence` comment ending in `**Research complete:**` | Re-fire its subagent (`resolve.md` → Interrupted research), say so in one line. | -| Index drift | A closed, completed question with no line under `## Decisions so far` | Read its `## Answer` comment, append the gist. | - -Then re-read `## Not yet specified` in full — that part is identical to local mode, and the bullet left behind after its question exists is just as corrosive here. - -Local mode's `Resolved:` backfill has no counterpart here: `closedAt` cannot be absent on a closed issue. If a `## Decisions so far` line is missing its date, take the date from `closedAt` during the index-drift repair above. - ---- - -## What stays on local disk - -Three things never move to the tracker, whatever the backend: - -| Artifact | Where | Why | -|---|---|---| -| Runnable sketches | `specs//pathfinder/sketch-/` | Throwaway code has no business in an issue, and the quarantine rule (never in the project's own source tree) is unchanged. Link the path from the issue and note the reader needs the repo checked out. | -| `PLAN-DRAFT-.md` | `specs//` | `/plan2code-1-plan` reads a **file**. This is a hard downstream contract — see Handoff. | -| Anything secret | Nowhere | Credentials, tokens, customer data. A `legwork` checklist says *where* a credential lives, never what it is — and on a public tracker that rule stops being a convention and starts being an incident. | - -Sketch directories are named for the issue number rather than a local `NN`, so `sketch-42` belongs to the question at `#42`. Same rules otherwise: throwaway, one command to run, never merged. - -Research subagents work the same way with one substitution: the brief carries the **issue URL** instead of a file path, and the instruction is to post findings as a comment opening `## Evidence` via `gh issue comment` — and to decide nothing. The comment ends with the `**Research complete:** ` line, and the firing session waits for every subagent before Session End, exactly as on local disk. `## Answer` and the close are still written by the session that fired it. - ---- - -## The trail footer - -Identical in shape; the inputs come from the query instead of the checklist. - -- **Heading** — `🧭 · · / cleared`, where `` excludes anything labelled `pathfinder:out-of-scope`. -- **Glyph order** — sub-issue order, the same order Chart Step 6 created them in. -- **Glyphs** — `●` closed as completed · `◉` open and assigned to you · `○` open, unassigned, unblocked · `⊘` open with `blocked_by > 0` · `⊝` closed as not planned. -- **Named legend** — names, never `#numbers`. `(blocked:)` names the blocker rather than numbering it, since there is no stable `NN` to point at. -- **Confidence** — the plain-English line, from the map body's `**Confidence:**`. - -Form A's resume command changes, because there is no local path to resume from: - -``` -NEXT STEP · start a new conversation and run: -`/plan2code-0-pathfinder https://github.com///issues/` -``` - -Form B is unchanged — a turn that asks the human something still says `WAITING ON YOU`, still names the outstanding probes, and still emits no resume command. - -Form C — the fork-menu after a recorded decision — is unchanged in shape, with two substitutions: the takeable options come from the frontier query rather than the checklist rows, and the `OR START FRESH` command carries the map issue URL. The `RECOMMENDED` marker and the ~3-decision checkpoint work exactly as `trail.md` describes. - -With no script to draw them, the labels are exact: Form A `NEXT STEP · start a new conversation and run:`, Form B `WAITING ON YOU · answer here, in this conversation:`, Form C `OR START FRESH · new conversation, paste:`. The Form C question tool uses the header `Next step` and the question "Continue here, or start fresh? Everything is saved." (add "I recommend starting fresh, to keep me sharp." at the ~3-decision checkpoint). Its options are up to three takeable question names plus `Start fresh`, one marked `RECOMMENDED`. - ---- - -## BRIEF mode - -The report is identical either way, and the file still lands on **local disk** at `specs//pathfinder/briefs/brief-.md` — a brief is a plain-English artifact for people, not tracker state, and writing it as an issue comment would bury it. Three substitutions against `brief.md`: - -| `brief.md` says | Here | -|---|---| -| Filter resolved questions by `Resolved:` in range | Filter the map's sub-issues closed as completed by `closedAt` in range | -| Reconcile backfills absent `Resolved:` dates | Nothing to backfill; run the four reconcile checks above instead | -| Open / blocked / out-of-scope sections read the checklist | They read the frontier query — unassigned-unblocked, `blocked_by > 0`, and `pathfinder:out-of-scope` respectively | - -`## Not yet specified`, `## Destination`, and `**Confidence:**` come from the map issue body, same as always. The no-machinery rule tightens rather than relaxes: no `#numbers`, no label names, no `gh` commands in the file. The reader may never have opened the tracker either. - ---- - -## Handoff (The Clearing Gate) - -The gate's four dimensions, the 18/25 bar, the hard caps, and the honesty rules are unchanged. Only the preflight and the plumbing differ. - -**Preflight, GitHub form:** - -| # | Check | -|---|---| -| 1 | Reconcile pass run (above) | -| 2 | Zero open sub-issues — `gh api .../sub_issues --jq '[.[] \| select(.state=="open")] \| length'` returns `0` | -| 3 | `## Not yet specified` in the map body is empty | -| 4 | Every completed question has an `## Answer` comment carrying a `**Gist:**` | -| 5 | `ls specs//` shows no existing `PLAN-DRAFT-*.md` | -| 6 | No `## Answer` defers a choice to "whoever implements this" | - -**The draft is written to local disk**, at `specs//PLAN-DRAFT-.md`, with the byte-exact status line `**Status:** Phase 3 Complete - Resume at Phase 4`. This is not a preference. `/plan2code-1-plan` discovers its input with `ls specs/`; it has no notion of an issue tracker, and a draft that exists only as an issue is a draft the rest of plan2code cannot see. Create `specs//` if charting never needed it. - -Three substitutions inside the template: - -| Local | GitHub | -|---|---| -| `**Planning record:** specs//pathfinder/map.md` | `**Planning record:** ` | -| `[Export format](./pathfinder/questions/01-export-format.md)` | `[Export format](https://github.com/o/r/issues/42)` | -| `## Out of scope` copied line for line, only the link prefix changing | Copied line for line, links already absolute — **nothing changes at all** | - -Everything else — the mapping table, Section 5 left empty, the two load-bearing `**Next:**` bullets, no scrapable confidence numbers — is unchanged. - -**Freeze the map:** - -1. Set `**Status:** Cleared` in the map issue body. -2. Bump `**Updated:**`. -3. Add `**Plan:** specs//PLAN-DRAFT-.md` under the status line. -4. `gh issue close --reason completed`. -5. **Close nothing else, delete nothing, edit no answers.** Every question issue stays exactly as it is — it is the rationale record behind the plan. - -Closing the map is the one addition over local mode, and it earns its place: `gh issue list --label pathfinder:map --state open` then reads as *the efforts still being charted*, which is the question a person scanning the tracker actually has. - -A later session that opens a map issue reading `Status: Cleared` must not resume it. Point at the PLAN-DRAFT and `/plan2code-1-plan`, and stop. A redrawn destination is a fresh effort with a fresh map issue. - ---- - -## Failure modes - -| Symptom | Cause | Fix | -|---|---|---| -| `Not Found` from a `sub_issues` or `dependencies` POST | An issue *number* was passed where a database *id* is required | `gh api repos/o/r/issues/ --jq .id`, retry with that | -| The wrong issue got attached | A number from another repo happened to be a valid id | Detach, re-fetch `.id` from the right repo, re-attach | -| Frontier is empty but open questions remain | Every one is blocked, or every one is assigned | Name the chain and stop — or, if the assignees are stale claims from your own dead sessions, reconcile first | -| A blocked question never unblocks | Its blocker was closed as `not planned` | Stranded. Re-frame to drop the dependency and cut the edge, or rule it out too | -| Two sessions resolved the same question | The claim was written after the work, not before | Claim is the *first* write. Merge the two answers into one comment, keep one close | -| A map edit lost someone's line | The body was edited from a stale copy read earlier in the session | Re-read the body immediately before every map write | -| `/plan2code-1-plan` finds nothing to resume | The PLAN-DRAFT was posted as an issue instead of written to `specs//` | Write the file. The draft is always local | -| Secrets in the tracker | A `legwork` answer pasted a credential | Rotate the credential first, then delete the comment. Editing it is not enough — GitHub keeps the edit history | diff --git a/skills/plan2code-0-pathfinder/references/grilling.md b/skills/plan2code-0-pathfinder/references/grilling.md deleted file mode 100644 index c409067..0000000 --- a/skills/plan2code-0-pathfinder/references/grilling.md +++ /dev/null @@ -1,388 +0,0 @@ -# Grilling Playbook -> Part of plan2code-0-pathfinder — loaded once per session, used by Chart and Work alike. - -Grilling is how a `grill · HITL` question resolves, how Chart Step 2 names the destination, and how Chart Step 4 maps the frontier. It is also the fallback for any question whose type gives you no better route. The output of a grill is a decision in the human's own words — never a decision you made on their behalf. - -**Probe ≠ question file.** A *probe* is one turn of the interrogation; a *question file* is one `questions/NN-.md` on the map. Batching applies to probes only. **One question file at a time still holds** — a batch of three probes resolves ONE file; a session moves to the next file only through the fork-menu between decisions (resolve.md §Cadence), never by interleaving two grills. - -**Grilling a room.** When several people answer — a Product + Engineering session — the mechanics are unchanged, plus three rules: address probes to the room, not a person, unless one person owns the call; the recap must capture the decision in the room's words, and whose call broke any tie is worth a clause in the `## Answer`; and a contested pick is NOT a decision — when Product and Engineering disagree, record both positions under `## Evidence`, leave the question `open`, and move on (or offer a `sketch` — reacting to something concrete resolves more standoffs than argument). Never average two positions into an answer nobody actually gave. - -## The interview protocol - -**Grilling is batched.** Put up to **three independent probes** to the human per turn, then wait. Never more than three, and never two probes where one's wording depends on the other's answer. - -The old rule here was one probe per turn. It was safe and it was unusably slow: a charted map carries a dozen open questions, and a decision that costs one round trip per probe is a decision the human abandons half-finished. Batching is the default now; the discipline moved from *ask one* to *prove they are independent, then send three*. - -| Rule | Why | -|---|---| -| Up to 3 probes per turn, never more | Past three the human skims, and a skimmed answer is worse than none. Three is a ceiling, not a quota — send two if only two are independent. | -| Only batch mutually independent probes | The independence test below. A probe whose wording or recommendation shifts based on another probe's answer waits for the next turn. | -| Use the structured question tool for every question when available | The built-in UI is the primary experience: selectable answers, visible skips, and `Other` for composition. Prose provides context, never the answer control. | -| Keep detail in descriptions, context, and `Other` | Batching buys round trips; it must never buy them by shrinking a decision to fit a picker. | -| Wait for the whole batch before sending the next | Their answers reshape what comes next. Pre-writing turn 2 wastes it. | -| Recommend an answer with every probe | A bare question makes the human do all the work. A recommendation gives them something to push against, which is faster and sharper. | -| Write it in plain English; keep the technical word only where that word IS the decision | A probe the human has to decode is a probe they answer approximately. See *Say it in plain English*. | -| Track the batch; re-ask what came back unanswered | This is what buys the batch. Dropped probes going unnoticed was the entire case for asking one at a time. | -| Walk one branch of the decision tree at a time | Batch across the branch's width, never down its depth. Do not ask about export scheduling before you know whether exports exist. | -| Do not act until they confirm shared understanding | Recap, get the confirmation, then write. No `## Answer` before the confirmation. | -| Never write implementation code during a grill | Grilling produces decisions. If you feel the pull to build, you have reached the edge of the map — say so and hand off. | - -Shape of a single probe, batched or not: - -``` -Question — one decision, stated so it can be answered in a sentence. -Why it — one line: what it blocks, what breaks if it goes the other way. -matters -Recommend — your pick, with the reason. One line. -Options — the genuine alternatives, if there are more than two. -``` - -Worked probe, from a grill on `[Export format](./questions/04-export-format.md)`: - -> **Q:** When a custodian exports a conversation that includes a 40 MB video attachment, does the export bundle the file or link to it? -> **Why it matters:** Bundling sets the size ceiling on an export job and decides whether exports can stream; linking makes the export useless once retention expires the blob. -> **Recommendation:** Bundle, with a per-job size cap of 2 GB and an automatic split into part files above that — reviewers open exports offline in tools that cannot follow links. -> **Alternatives:** Link-only (smaller, breaks offline); hybrid by MIME type (two code paths, two failure modes). - -Batching does not shrink a probe. Three probes means three of these, each with its own why-it-matters and its own recommendation. Three bare questions in a list is not a batch, it is a form to fill in. - -### Say it in plain English - -Every probe gets read once, by a busy human, in a terminal. Write it the way you would say it out loud to a colleague who knows the product but has never read this skill. Plain is not vague — the two failures are opposite and both cost you the decision: woolly wording gets a woolly answer, dense wording gets a guessed one. - -**Default to everyday words.** Short sentences, concrete nouns. "What should happen when the export is too big to email?" beats "what are the failure semantics of the artifact delivery path under a size-limit violation?" Same decision, one of them answerable on the first read. - -**Keep the technical term where that term IS the decision.** A format name, a real file path, a column name, a version number, a limit, a `## Glossary` term the map already settled — those are load-bearing, and softening them makes the probe unanswerable. `.eml`-in-a-ZIP versus NDJSON *is* the choice; "normal email files versus one big machine-readable stream" is the gloss you put beside it, never the replacement for it. - -> The test: would swapping the term for a plain phrase lose information the human needs in order to choose? Lose information — keep the term and gloss it. Lose nothing — cut it. - -**Gloss an unavoidable term once, inline, then use it freely:** "…stored under Object Lock (S3's write-once mode — once it is set, even we cannot delete early)." Once per session, not once per probe. Re-explaining a term to the person who owns the system is its own insult. - -**Never put Pathfinder's machinery in front of the human.** They are deciding something about their product; the vocabulary below is internal bookkeeping and buys them nothing: - -| Do not say | Say | -|---|---| -| "this is a `grill · HITL`" | "this one is yours to call" | -| "the frontier holds two takeable questions" | "two things we can decide right now" | -| "graduating this out of the fog" | "this is sharp enough to write down as a real question now" | -| "the sacrificial boundary" | "which of these features are we leaving out this time?" | -| "shall I set `Locked: yes`?" | "worth recording why we picked this, so nobody re-opens it in six months?" | -| "Q3 is blocked by 02" | "the export format question has to land before this one" | -| "the UI cannot handle this question" | nothing — put context before the tool and preserve `Other` | - -**Refer to questions by name, never by number** — "[Export format](./questions/04-export-format.md)", not "04". The number means something to the file system and to nobody else. - -**No metaphor where a fact fits.** Maps, fog, and trails belong in the footer and the mascot. Inside a probe they cost a translation step: "three things here are still undecided" beats "the fog is thick in this quarter of the map." - -**On a what-to-drop question, name the thing dropped.** Whenever a question asks what gets dropped, left out or cut, every option names the thing being dropped, never a rule to keep. Otherwise ticking an option reads as a double negative, and the person has to work out whether a tick means yes or no. Bad: "☐ Exports stay manual" · Good: "☐ Scheduled exports (Leaving this out = someone runs each export by hand)" - -The same discipline covers everything else the human reads — the recap turn in *Landing the grill*, the option labels and descriptions in the structured tool, the sketch probes, and the HITL checklists in the resolution playbook. Plain in the question, precise in the term that carries the decision. - -### The independence test - -A probe may join the current batch only if **all three** hold: - -| Test | Fails when | -|---|---| -| Its wording would not change under any answer to another probe in the batch | "How do we name the part files?" reads differently if the format turns out to be a single stream | -| Its recommendation would not change either | You would recommend a 2 GB cap under ZIP parts and no cap under NDJSON | -| It does not presuppose another probe's answer | "How often do scheduled exports run?" assumes scheduled exports exist | - -In doubt, hold it back. A held probe costs one extra round trip. A dependent probe sent early costs a wrong answer recorded as a decision, and you will not find out until the plan contradicts itself. - -Independent probes are usually the ones that came from **different areas** — data, interface, security, operations, testing. Dependent probes are usually consecutive steps down one thread. - -### Delivering a batch: structured UI first - -**Use the environment's structured question tool for every user-facing question when it is available.** This includes destination probes, frontier probes, claimed-question grills, recap confirmations, lock offers, sketch reactions, intent gates, and fork-menus. The built-in UI is faster to scan, preserves visible skips, and always provides an `Other` path for composed answers. Numbered prose Q blocks exist only as the fallback when the tool is unavailable. - -One question object per probe, up to three per call. Never split a batch between a tool popup and prose — the prose half gets lost when the human answers in the UI. - -**Composed answers still use the tool.** Do not invent a false-complete option set merely to make a picker. Offer the genuine candidates you know; the automatic `Other` option is where the human composes a boundary, rationale, hybrid, old-incident detail, or alternative you could not know. When no genuine candidate exists, offer useful control choices such as `Use recommendation` and `Defer for now`; the human writes the real answer through `Other`. A click is still followed by the normal recap-confirmation turn, which captures reasoning in the human's words. - -**Artifacts do not force prose questions.** Show the state table, fake request/response, ASCII UI, or worked example in the response, then immediately invoke the structured tool for the pointed reaction probes. The artifact is prose; the questions are UI controls. Never ask "thoughts?" outside the tool. - -**Never reshape the decision to fit the tool.** Descriptions carry trade-offs; `Other` carries composition. Split bundled decisions into separate probes and rename colliding short headers. Do not cut a real alternative or hide complexity. If the UI cannot represent the question faithfully even with descriptions + `Other`, state the full context immediately before the tool and keep the actual answer control in the tool. - -The turn closes with the waiting footer (Form B in `trail.md`): it names outstanding probes and carries no resume command. The recap confirmation is also asked through the tool and remains Form B. - -#### The structured tool - -The primary channel. One question object per probe, up to three in a single call: - -- **Header** — the decision in two or three plain words (`Export format`, `Size cap`). Not a type, not a marker, not a number. -- **Question** — the probe, with its why-it-matters. This is prose and it is not rationed; the same sentences you would have written in a Q block go here. -- **Options** — the genuine alternatives, each described by its trade-off, with the recommended one named as such in its description. Two to four; the free-text escape hatch covers the rest. Label plainly, then let the description carry the precise term: `One file per message` labelling the `.eml`-in-a-ZIP option, with `.eml` named in the description. - -A short *label* is not a short *decision*. The label is a handle — `Fixed tick count` — and the description carries the trade-off that makes it choosable. A label bundling several independent answers is a probe that wants splitting. - -**A click is a decision, not a sentence.** The HITL rule wants an `## Answer` traceable to something the human actually said, and a selected option label is thin evidence on its own. What makes tool-delivered answers legitimate is the recap turn in *Landing the grill* — you play the choices back in the tool's question text and they confirm or correct in their own words. Never skip the recap on the grounds that the tool already captured the answer; the tool captured the *pick*, and the recap captures the *agreement*. - -**If a reply comes back thinner than the decision** — a bare click on something you now realise carries weight — do not paper over it. Fold the why into the recap turn as one more probe before writing the `## Answer`. - -#### Numbered Q blocks - -Fallback ONLY when the structured question tool does not exist or its call fails. Never choose prose merely because the answer is detailed, composed, architectural, `Locked: yes`, or attached to an artifact — descriptions + `Other` + context immediately before the tool cover those cases. - -**Copy this shape exactly.** The blank lines are load-bearing, not decoration: - -````markdown -Three independent decisions are open. Answer in any order, skip any you want to punt — "Q2: a, c; Q3: the hybrid" is a perfectly good reply. - ---- - -**Q1 — Export format** - -When a custodian exports a year of a channel, what do they get back? - -*Why it matters:* fixes the size ceiling, decides whether exports can stream, and determines whether the review vendors can ingest without a conversion step. - -*Recommendation:* **(a)** — both vendors named in Codebase context read `.eml` natively. - -- **a)** ZIP of one `.eml` per message, plus `manifest.csv` -- **b)** A single NDJSON stream — compact and streamable, but nobody downstream parses it -- **c)** PST — what Legal asked for by name, but single-writer with a ~50 GB ceiling - ---- - -**Q2 — Leave for later** - -Which of these features are we leaving out this time? Tick any number. - -*Why it matters:* the ones you tick become the first things written down as out of scope, and every later "is that in or out?" call is measured against them. A destination nobody has excluded anything from has not been thought about. - -*Recommendation:* **(a)** and **(c)** — neither is needed for the first review hand-off. - -- **a)** Scheduled exports (Leaving this out = someone runs each export by hand) -- **b)** Exports of deleted messages (Leaving this out = anything already purged stays out of the file) -- **c)** Export to a cloud bucket (Leaving this out = the file downloads to the custodian's machine only) -- **d)** Redaction inside the export (Leaving this out = the review vendor redacts after ingest) -```` - -Number them, keep the numbers stable across turns and sessions, and say out loud that partial answers are welcome — the invitation is what makes the skip visible instead of silent. - -#### Formatting rules for a Q block - -A batch is only worth sending if the human can read it. These are mechanical, and getting them wrong turns three careful probes into one unreadable paragraph: - -| Rule | Why | -|---|---| -| **A blank line between every element** — the `**Qn — Name**` line, the question, *Why it matters*, *Recommendation*, and the option list | Markdown joins consecutive non-blank lines into a single paragraph. Without blank lines the entire batch renders as a wall of text and the human skims it, which is the failure the three-probe cap exists to prevent. | -| **Never hard-wrap a sentence across source lines** | The wrap is invisible to the renderer, so it buys nothing and costs you the paragraph break. Write each sentence as one logical line however long it is; the terminal wraps it. | -| **Options are a bullet list, one option per bullet** — `- **a)** …` | Indented continuation lines are the specific thing that collapses: under four spaces the indent is stripped, at four or more it becomes a code block. A bullet list survives every renderer and keeps the options scannable. | -| **`---` between probes** | Three probes run together is one block of text. The rule gives the eye a stop and makes "answer Q2 and Q3" easy to aim at. | -| **The question itself gets its own line, not a run-on with the heading** | `**Q1 — Export format.** When a custodian…` buries the decision inside a paragraph. Name it, break, then ask it. | -| **Never use spaces to convey structure** | Whatever hierarchy you indent by hand disappears on render. Structure comes from blank lines, bullets, and bold — nothing else. | - -For the recap in *Landing the grill*, summarize each decision in the structured tool's question text and ask the human to confirm or correct it; use `Other` for corrections. - -### When answers come back partial - -Assume they will. The human answers two and drops one, and the dropped one is often the hardest and most valuable. - -1. **Diff what came back against what you sent.** Skipped, answered with "Other: skip", or silently omitted all count as unanswered. -2. **Lead the next tool call with the unanswered probes**, using their original headers and full wording. Not "you missed Export scope" — the whole probe again, with its recommendation, because they have lost the context by now. Unanswered probes come *before* any new probe, and they count against the cap of three. -3. **Skipped twice, stop pushing.** Record it under `## Evidence` as an open probe with your recommendation verbatim, then either narrow it into something answerable or spin it out — a fresh question file if you can phrase it sharply, a `## Not yet specified` line if you cannot. -4. **Never promote your own recommendation into `## Answer`.** A probe the human declined twice is unanswered, not decided. Writing it up as decided is self-answering a HITL question, which breaks the skill. - -Never let a dropped probe fall off the end of the session unrecorded. - -## Facts you look up, decisions you ask - -This is the single rule that keeps a grill from feeling like an interrogation. If a **fact** can be found by exploring the environment — filesystem, codebase, tools, docs, config, git history, the map's own resolved questions — go find it. The **decisions** are the human's; put each one to them and wait. - -| You look it up | You ask | -|---|---| -| Which Postgres version the app runs against | Whether the export index is allowed to add a new table | -| Whether `ExportJob` already has a `status` column | What states that column is allowed to hold | -| How the current retention sweep is scheduled | Whether exports must survive a retention sweep | -| Whether the repo uses Vitest or Jest | Whether these paths get unit tests, integration tests, or neither | -| What the S3 bucket lifecycle rule is today | Whether we are allowed to change it | -| What `AGENTS.md` says about naming conventions | Anything `AGENTS.md` does not already answer | - -Look first, then ask. A question that opens with "I checked `src/export/job.ts` — it already has a `status` enum with `queued | running | failed`. Does a partial success need a fourth state?" is worth three of "how should export status work?" - -**Never ask what `AGENTS.md`, the map's `## Ground rules`, or a resolved question already answers.** Re-asking a settled decision reopens it by accident and costs you the human's trust for the rest of the session. - -**When the lookup is expensive**, that is not a grill — it is a `research · AFK` or `legwork` question. Say so, note it, and keep grilling the decisions you can still put to the human. - -## The HITL rule, stated hard - -An agent that answers its own grill has broken the skill. - -A `grill · HITL` question resolves **only** through live exchange with the human. Not from the codebase, not from a plausible default, not from "the obvious industry standard," not from what you would have picked. The whole value of the question is that a human with context you do not have chose one branch over another. - -Signs you are about to break it: - -- You wrote a recommendation and then wrote the `## Answer` without a reply in between. -- You wrote "assuming the user would want X" anywhere. -- You resolved a question in a session where the human said nothing but "go". -- The `## Answer` contains no sentence traceable to something the human actually said. - -**When the human goes unreachable mid-grill:** - -1. The claim **stays**. `State: claimed` and `Claimed:` are left exactly as they are. -2. Append to `## Evidence` — never `## Answer` — the exchange so far: the probes already answered, **every probe of the last batch still outstanding**, and your recommendation for each, verbatim. -3. End the session. Report the question by name and say it is mid-grill and waiting on the human. This one IS a session end, so the Trail Footer takes **Form A** — the pathed resume command, not `WAITING ON YOU`. -4. Invent nothing. No provisional answer, no "pending confirmation" answer, no default recorded as a decision. - -The next session picks the claim back up and re-sends the outstanding batch. If the session was truly abandoned rather than paused, Work Step 2 reconciliation resets it to `open` on its own — that is its job, not yours. - -## The four disciplines - -Run all four continuously during any grill. They are not stages; they fire whenever the trigger appears in what the human just said. - -### Challenge against the glossary - -When a term conflicts with the map's `## Glossary`, call it out immediately, mid-sentence if necessary. - -> "The glossary defines **Export** as a completed archive file delivered to a custodian. You just used it for the background job that builds one. Which do you mean — or do we need a second term?" - -### Sharpen fuzzy or overloaded language - -When a term is vague or carries two meanings, propose a precise canonical term and get a ruling. - -> "You keep saying 'account.' Sometimes you mean the organization paying us, sometimes the individual login. Those are a **Customer** and a **User** and they have different retention rules. Which one owns the export quota?" - -### Stress-test relationships with concrete invented scenarios - -Do not ask abstractly whether a relationship holds. Invent a specific scenario that probes the edge and force a precise boundary. - -> "A custodian leaves the company on the 3rd. Their retention policy expires their messages on the 5th. Legal opens a hold on the 4th. On the 6th, does the export still contain those messages?" - -Invent the numbers, names, and dates. Vague scenarios get vague answers. - -### Cross-reference claims against the actual code - -When the human states how something works, check whether the code agrees, and surface contradictions instead of quietly picking a side. - -> "You said retention deletes rows. `RetentionSweep.run()` sets `deleted_at` and leaves the row in place — a soft delete. Which is the behavior we are designing against?" - -A contradiction is a finding, not an embarrassment. Surface it in the same turn you found it. - -## The glossary - -Domain modeling would write a `CONTEXT.md`. Pathfinder does **not** — plan2code owns `AGENTS.md`, and a competing root glossary file would collide with it. The map's `## Glossary` section is the one place resolved terms live. - -Entry format — one row in the map's `## Glossary` table: the term, a one-or-two-sentence definition, and the rejected synonyms in the Avoid column: - -``` -| Term | Meaning here | Avoid | -|---|---|---| -| Export | A completed, immutable archive file delivered to a custodian. Always the artifact, never the process that produces it. | download, extract, dump | -| Export Job | The background unit of work that produces an Export. Has states; an Export does not. | export run | -| Custodian | The person whose communications an Export contains. Not necessarily the person who requested it. | user, owner, subject | -``` - -Rules: - -| Rule | Detail | -|---|---| -| Update inline, never defer | The moment a term is resolved, write it into `## Glossary` and save. A term you meant to add at the end of the session is a term you lost. | -| Be opinionated | When several words compete, pick one and put the rest in the Avoid column. A glossary that lists synonyms as equals has decided nothing. | -| Keep definitions tight | One or two sentences. Define what it **is**, not what it does. | -| Only project-specific terms | "Retention Policy" belongs. "Timeout", "retry", "DTO" do not, however heavily the project uses them. | -| It is a glossary and nothing else | No implementation details, no open questions, no scratch notes, no decisions. Decisions live in question files. | -| Group under sub-bullets only when clusters emerge | A flat list is fine for one cohesive area. | - -Every term you resolve is a term no later session re-litigates. That is the whole return on the discipline. - -## The Lock test - -Domain modeling would offer an ADR here. Pathfinder sets `Locked: yes` on the question instead — the decision record and the question are the same file. - -Offer `Locked: yes` **only** when all three hold: - -| Test | Meaning | Fails when | -|---|---|---| -| Hard to reverse | Changing your mind later costs real time or migration | You could flip it in an afternoon | -| Surprising without context | A future reader will ask "why did they do it this way?" | It is the obvious choice anyone would make | -| A real trade-off | There were genuine alternatives and one was picked for specific reasons | There was only ever one option | - -If any one is missing, skip it. An easy-to-reverse decision will just get reversed. An unsurprising one raises no questions to answer. One with no alternative records nothing beyond "we did the obvious thing." - -**What earns a lock:** architectural shape ("the export index is a materialized view, not a table"); integration patterns between components ("retention and export communicate by event, never by direct call"); technology choices carrying lock-in (database, message bus, auth provider — not every library, just the ones that would take a quarter to swap); boundary and scope decisions, including the explicit no-s; deliberate deviations from the obvious path ("hand-written SQL here, not the ORM, because the ORM cannot express the retention join"); constraints invisible in the code ("no cross-region replication — the data residency contract forbids it"); and non-obvious rejections ("we considered and rejected GraphQL, for reasons someone will otherwise re-propose in six months"). - -**What `Locked: yes` obliges the `## Answer` to contain:** - -1. The decision itself, in one or two sentences. -2. **Every alternative genuinely considered, and why each was rejected.** This is the part that makes a lock worth having. "We rejected X" with no reason is not a lock. -3. The consequences a later reader would not guess. -4. The one-line `**Gist:**` that Work Step 7 requires, same as any answer. - -Offer it, do not impose it: *"This one looks hard to reverse and the reasoning will not be obvious in six months. Lock it?"* The human decides. - -**Where locks go at handoff:** the handoff playbook lifts every `Locked: yes` question into the PLAN-DRAFT's **Architecture** section, and their rejected alternatives and standing constraints into **Assumptions**. Unlocked answers still inform the draft, but locks are the ones that survive verbatim into planning. Grill them harder for that reason. - -## The one grill every map must resolve, and the lens applied to all of them - -### 1. Testing posture — `grill · HITL` - -Chart Step 6 requires this question. It exists because `/plan2code-1-plan` Phase 1 asks for exactly three things and stalls without them: testing types, whether tests run after each phase, and the coverage target. A map that clears without answering them hands the human a plan session that immediately re-asks. - -The first three probes below pass the independence test against each other — none reads differently under another's answer — so **send all three as one structured-tool batch**. Every probe has named alternatives and fixed literals; `Other` remains available. - -| Probe | Recommend by default | -|---|---| -| Which types are in scope — unit, integration, E2E, or none? | Unit plus integration; E2E only where a real browser or real broker is the only honest test | -| Does the suite run after each implementation phase, or once at the end? | `Run after each phase` — work that cannot be verified when it lands cannot be signed off | -| Coverage target: critical paths, moderate (~60-80%), or comprehensive (>80%)? | Critical paths, named explicitly, rather than a percentage nobody defends | -| What is deliberately not tested, and why? | **Fourth probe, and it does not ride in the batch.** It has no option set — the explicit no-s have to be composed — and it reads differently once the types are settled. Fold it into the recap turn, where you are already waiting on them. | -| What is already there — runner, fixtures, CI wiring? | **Not a probe.** Look it up before you send the batch, and cite it in the probes above | - -Record the answer in the exact literals `/plan2code-2-document` string-matches: the types; `Run after each phase` or `Dedicated phase only`; and `Critical paths`, `Moderate (~60-80%)`, or `Comprehensive (>80%)`. Not prose — a paraphrase matches no branch downstream. - -### 2. Test seams and verifiability — a lens, not a question file - -For each major decision on the map, ask the same question: **how will anyone know it works?** A decision nobody can verify is a decision that silently rots. - -This is not a question of its own and never gets a file or an `NN`. Run it inside whatever grill is claimed; anything it surfaces that needs deciding separately becomes a new question at Work Step 8. - -These six all interrogate one decision from different sides, so they batch cleanly — but they ride along inside the claimed grill rather than owning a turn. Fold the two or three that bite into the batch you were already sending; never spend a whole turn on all six. - -| Probe | What it flushes out | -|---|---| -| What observable behavior changes if this decision is implemented correctly? | Decisions with no observable effect — usually a sign the question was about implementation, not design | -| What is the cheapest thing that fails when it breaks? | The seam. If the answer is "a customer complains," there is no seam yet | -| Can this be tested without a live third-party account, a real S3 bucket, a wall-clock sleep? | Untestable-by-construction designs, while they are still cheap to change | -| Where does the boundary go so a test can stand at it — an interface, a queue, an HTTP edge, a pure function? | The seam the plan will need to name | -| What does the failure look like in production — log line, metric, alert, dead-letter queue? | Verifiability after ship, not just in CI | -| If we get this wrong, how long before we find out? | Decisions that need a canary or a feature flag rather than a test | - -If a decision survives all six with no answer, it is not ready to leave the map. Either re-frame the question, or add the seam as a constraint in the `## Answer` so the plan inherits it. - -## Anti-patterns - -| Failure mode | What it looks like | Fix | -|---|---|---| -| Batching **dependent** probes | "What format, what do we name the part files, and how big is a part?" | Only the first is independent. Send it; hold the other two — they are unanswerable until format lands. | -| Drip-feeding one probe at a time | Twelve open questions on the map, one probe per response, the human gives up on session four | Batch up to three independent probes. On a charted map the human's round trips are the scarce resource, not your token budget. | -| Losing a probe the human skipped | Sent three, got two back, moved on and never mentioned the third | Diff the batch. Lead the next turn with what came back empty, restated in full. | -| A batch of naked questions | Three one-liners with no recommendations and no why-it-matters | Every probe in a batch carries its own recommendation and its own stake. Otherwise you have offloaded the thinking, not the round trips. | -| Asking in prose when the tool exists | Numbered Q blocks or a loose "which one?" despite AskUserQuestion being available | Put every answer control in the structured UI. Use descriptions for trade-offs and `Other` for composition. Prose may provide context or an artifact immediately before the tool, never the question itself. | -| Flattening a gnarly probe into labels | An architectural decision reduced to three option labels with no useful descriptions | Keep the tool, not the flattening: put the real trade-off in each description, preserve `Other`, and recap the reasoning before recording. | -| Treating an artifact as an excuse for prose | An ASCII UI followed by "thoughts?" | Show the artifact, then invoke the structured tool with pointed reaction probes naming the rows/elements. | -| Retreating to prose over a fixable batch | Two probes collide on the short header, or one label bundles three answers | Rename the headers; split the bundled probe. Reshape the batch, never the decision. | -| Sending four probes because the tool accepts four | A fourth probe added to a clean batch of three because there was room in the call | The cap is three regardless of what the environment allows. The ceiling is the human's attention, not the tool's schema. | -| Grilling in Pathfinder's own vocabulary | "The frontier has one takeable `grill · HITL` — shall we graduate 02 out of the fog and lock it?" | Plain English. Markers, types, `NN` numbers, and fog are your bookkeeping; the human is deciding about their product. | -| Plain-washing the load-bearing term | "Do you want the friendly file or the compact one?" where the real choice is `.eml`-in-a-ZIP versus NDJSON | Plain wording, precise nouns. Name the formats and gloss them; a decision made on a euphemism cannot be written into `## Answer`. | -| Asking what the codebase already answers | "Do you use Postgres or MySQL?" | Look. Every avoidable question spends trust you need for the hard ones. | -| Accepting a vague answer and moving on | "Handle it sensibly" → recorded as the decision | Push once more, concretely: "Sensibly meaning we drop the attachment, or fail the whole job?" A vague answer is not an answer. | -| Leading the human to your preferred answer | "You'd want Postgres here, right?" | Recommend openly, then present the real alternatives with their real merits. A recommendation invites a fight; a leading question suppresses one. | -| Grilling past the decision into implementation | "Should the retry helper take a callback or return a promise?" | That is the plan's job, or the implementer's. Stop at the decision. The pull to keep going is the edge of the map. | -| Drifting off the claimed question | Claimed `[Export format](./questions/04-export-format.md)`, forty minutes later deep in auth | Name the drift out loud, capture the new thread as a fresh question or as a line in `## Not yet specified`, and return. One question _file_ at a time — switching happens at the menu, not mid-grill. | -| Self-answering a HITL question | An `## Answer` with no words the human said | Delete it. Reopen the question. See the HITL rule. | -| Recording the decision but not the rejections | "We chose event-driven." | Rejections are half the record — and mandatory when `Locked: yes`. Ask what else was on the table before you close. | -| Grilling a fact | "How long does the retention sweep take?" | If it is measurable, measure it — or make it a `research · AFK` question. Do not make the human guess at their own system. | -| Letting the glossary go stale | Three terms resolved, none written down | Write each one the moment it lands. Deferring loses them. | -| Closing without confirmation | Answer written straight after the last reply | Recap the whole chain of decisions, get the explicit confirm, then write. | - -## Landing the grill - -When the branch is walked out. **Steps 1-3 are ONE turn, not three** — recap, confirmation request, and lock offer go out together, because a lock offer sent after a separate confirmation costs a round trip to ask a yes/no the human could have answered alongside the recap. - -1. Recap the decisions in order, in the human's own terms, using glossary vocabulary. Include anything a structured-tool reply left implicit, so the confirmation covers the reasoning and not just the picks. -2. Ask for confirmation through the structured question tool (`Confirm` / `Correct via Other`). Do not skip this — the recap is where the human catches the one thing you misheard, and where a clicked option becomes words they said. -3. Apply the Lock test as another question in the same tool call. Offer, do not impose. -4. Write `## Answer` per Work Step 7: the decision, what was rejected and why, consequences, and a one-line `**Gist:**`. Evidence, links, and transcript fragments go under `## Evidence`. -5. Anything the grill surfaced that belongs to a different question goes to the map — a fresh question if you can phrase it sharply, `## Not yet specified` if you cannot, `## Out of scope` if it sits past the destination. \ No newline at end of file diff --git a/skills/plan2code-0-pathfinder/references/handoff.md b/skills/plan2code-0-pathfinder/references/handoff.md deleted file mode 100644 index e76fbd3..0000000 --- a/skills/plan2code-0-pathfinder/references/handoff.md +++ /dev/null @@ -1,423 +0,0 @@ -# Handoff Playbook — Clearing the Map into a PLAN-DRAFT - -Loaded at The Clearing Gate. Turns a cleared map into `specs//PLAN-DRAFT-.md` that `/plan2code-1-plan` resumes from at Phase 4, then freezes `pathfinder/` as the rationale record. - -**Backend note.** The scoring rubric, the hard caps, the honesty rules, the template, and the mapping table are the same either way — and the draft is written to local disk either way, because `/plan2code-1-plan` reads a file, not a tracker. On `**Backend:** github`, `github-issues.md` replaces only the preflight table, the question links (issue URLs, already absolute), and the freeze steps. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes. - -Nothing here is creative. The gate is scored, the mapping is fixed, the template is literal. Follow it exactly or the resuming plan session silently loses work. - -## Preflight — before scoring anything - -Run `reconcile`, then `node "/pathfinder.mjs" gate specs//pathfinder`. Its `checks` cover the mechanical preflight, read from the files: - -| `checks` id | Means | If it fails | -|---|---|---| -| `markers-match-files` | The map's markers are the files' (reconcile ran) | Run `reconcile`. Markers are derived, never authored. | -| `no-open-claimed-blocked` | Zero `[ ]`, `[/]`, `[!]` | Not cleared. Return to the frontier. | -| `fog-empty` | `## Not yet specified` is empty | Not cleared. Graduate the fog into questions, or admit it is out of scope. | -| `every-resolved-has-gist` | Every resolved file has a real `## Answer` with a `**Gist:**` | The file wins over the marker. Repair, then re-check. | -| `hard-caps` | None of the Requirements, Feasibility or Risk caps below holds (the Integration cap is yours to check) | That dimension cannot exceed 17: fix the record first. | -| `scores-at-least-18` | The map's `**Confidence:**` line has all four at 18 or better | Not cleared. Keep working the weak dimension. | - -`existingPlanDraft` lists a `PLAN-DRAFT-*.md` already in `specs//`: read it and update it in place, never add a second dated draft. `planDraftPath` is the file to write either way. - -One preflight item stays yours: **the destination is reachable with nothing left to decide**: no `## Answer` defers a choice to "whoever implements this". If one does, the map is not cleared: name the open decision and graduate it into a question. - -Score the four dimensions (below), write them to the map's `**Confidence:**` line, and rerun `gate` until `mechanicalPass` is true. - -## The clearing-gate scoring rubric - -Four dimensions, 0-25 each, scored against **written evidence in `questions/`** — never against your recollection of the conversation. The gate needs **every dimension at 18/25 or better**. There is no averaging: 25/25/25/14 fails. - -### Band scale (applies to all four) - -| Band | Meaning | -|---|---| -| 23-25 | Decided, written down, and consequences recorded. A developer could act on it without asking a question. | -| 18-22 | Decided and written down. Residual detail remains, but it is *specification* detail that Phase 5/6 settles — not a decision anyone still has to make. | -| 12-17 | A real decision is still open, or an answer exists with no evidence behind it. **Gate fails.** | -| 0-11 | The area was never charted. **Gate fails**, and the map was cleared prematurely. | - -The 18-boundary is the honest line between *"needs designing"* and *"needs deciding"*. Pathfinder owns deciding. If someone still has to decide, you are not done. - -### What each dimension scores - -| Dimension | Scores | Raises it | Lowers it | -|---|---|---|---| -| **Requirements Clarity** | Are the requirements unambiguous? | Every resolved `grill` answer states the decision AND what was rejected; the testing-posture answer names types, cadence, and coverage | Answers phrased as preferences ("probably NDJSON") instead of decisions; a requirement that only exists in the map gist and not in a question file | -| **Technical Feasibility** | Do we know HOW to build each component? | Resolved `sketch` questions with a real artifact under `sketch-NN/`; `research` answers citing primary sources under `## Evidence`; `00-codebase-context.md` naming the actual files that change | A mechanism nobody has exercised in this codebase; a research answer whose `## Evidence` is empty or cites only a blog post | -| **Integration Points** | Are all external dependencies identified? | Every system named in `## Destination` has a resolved question touching it; auth, quota, and failure behavior named per integration | An integration mentioned in an answer but never questioned; a config store that was read but never written to during a sketch | -| **Risk Assessment** | Are blockers documented with mitigations? | Answers that record consequences; `Locked: yes` answers that say what breaks if reversed; ceilings with a stated behavior at the ceiling | A recorded limit with no decided behavior past it; a `Locked: yes` answer with no consequences section | - -### Hard caps - -A cap overrides your judgment. While a cap condition holds, the dimension **cannot** exceed 17, so the gate cannot pass. `gate` reports the Requirements, Feasibility and Risk caps from the files (`caps`); the Integration cap needs you to match the destination's systems to questions. - -| Cap | Condition | -|---|---| -| Requirements ≤ 17 | The testing-posture question is not `resolved`, or its answer omits any of types / cadence / coverage | -| Feasibility ≤ 17 | Any `research` question is `resolved` with an empty `## Evidence` | -| Integration ≤ 17 | A system named in `## Destination` has no resolved question touching it | -| Risk ≤ 17 | Any `Locked: yes` answer records no consequences | - -### Honesty rules - -- Score the **written record**, not the conversation. If the human agreed to something in a session and nobody wrote it into a `## Answer`, it does not exist and it does not earn points. -- A filled `## Answer` is not automatically 25. An answer that decides but records no consequences tops out around 20. -- Never round up to clear the gate. A 17 that "feels like an 18" is the exact case the gate exists to catch. -- Never move a decision to `## Out of scope` to raise a score. Out-of-scope is a scoping act with a reason; scope-cutting to pass a gate is score inflation with extra steps. -- If two dimensions are borderline, write the one-line justification for each score into the Session End report. Justifications that cannot be written are scores that cannot be defended. - -### Worked example — idea `audit-log-s3-export` - -Destination: *"A spec a developer can implement: nightly export of tenant audit logs to customer-owned S3 buckets, with a signed manifest per run."* - -Resolved questions: [Codebase context](./questions/00-codebase-context.md), [Export format](./questions/01-export-format.md), [Scheduling model](./questions/02-scheduling-model.md), [Destination auth](./questions/03-destination-auth.md), [Retention and replay](./questions/04-retention-and-replay.md), [Testing posture](./questions/05-testing-posture.md), [Throughput ceiling](./questions/06-throughput-ceiling.md). Ruled out: [Failure notification](./questions/07-failure-notification.md). - -**First scoring pass:** - -| Dimension | Score | Justification against evidence | -|---|---|---| -| Requirements Clarity | 22/25 | Four `grill` answers state decisions and rejections (NDJSON chosen, CSV rejected for nested actor payloads). Testing posture settled: integration + unit, run after each phase, moderate coverage. Minus 3: the manifest's exact field list is unspecified — a Phase 5 spec detail, not an open decision. | -| Technical Feasibility | 21/25 | `sketch-02` uploaded a 400 MB multipart object to a real bucket end to end. `00-codebase-context.md` names `AuditExportJob` and the existing Hangfire registration as the extension points. Minus 4: no component in this codebase has ever assumed a cross-account IAM role; the pattern is documented in AWS docs cited under `## Evidence` but unexercised here. | -| Integration Points | 23/25 | Three integrations, each with a resolved question: S3 (Destination auth), Hangfire (Scheduling model), tenant config store (Codebase context). Auth and quota named per integration. Minus 2: the tenant config store's write path was read but never exercised by a sketch. | -| Risk Assessment | **16/25** | Consequences recorded on Export format and Destination auth. But Throughput ceiling establishes 200 MB per tenant per day at p95 and **records no decided behavior above it** — truncate, spill to the next run, or fail the run is still undecided. | - -**Gate result: FAIL** on Risk Assessment (16 < 18), and the orchestrator third clearing condition — the destination reachable with nothing left to decide — fails with it: a decision is genuinely still open. Do not write a PLAN-DRAFT. Name the failure, graduate `questions/08-overflow-behavior.md` (`grill · HITL`, `Blocked by: none`) from the gap, and end the session on the frontier. - -**Second scoring pass, one session later**, with [Overflow behavior](./questions/08-overflow-behavior.md) resolved (spill to the next run, alarm at three consecutive spills): - -| Dimension | Score | -|---|---| -| Requirements Clarity | 22/25 | -| Technical Feasibility | 21/25 | -| Integration Points | 23/25 | -| Risk Assessment | 20/25 | - -All four at 18 or better. Gate passes. Proceed to the mechanism. - -## The mechanism, stated plainly - -Pathfinder writes `specs//PLAN-DRAFT-.md` with the header line: - -`**Status:** Phase 3 Complete - Resume at Phase 4` - -`/plan2code-1-plan` **already recognises that exact string.** Its "Check for Existing Progress" block, which runs before Phase 1, reads: - -`- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4` - -That is the whole handoff. The string is the contract, and it needs **zero changes to the planning skill** — pathfinder is impersonating the Large-project Context Checkpoint that 1-plan's own Phase 3 performs, which writes the same status for the same reason. - -Consequences of that being a literal string match: - -- Copy it byte for byte. Plain ASCII hyphen-minus surrounded by single spaces. An en dash, a colon, or "Phase 3 complete" in lower case breaks the match and 1-plan starts over at Phase 1 — throwing away every decision the map holds. -- It goes on its own `**Status:**` line in the header block, not buried in prose. -- The file must be named `PLAN-DRAFT-.md` and live directly in `specs//`. `PLAN-DRAFT-*.md` is a reserved name inside `pathfinder/` — never write it there. -- Use the date in `gate`'s `planDraftPath` (it reads the clock). Do not guess it. On `github` (no `gate`), take today's date from the shell and check `ls specs//` for an existing draft. - -**Discovery is shell-only.** `specs/` is gitignored, so Glob silently returns nothing and every downstream skill would report "no PLAN-DRAFT found". Use `ls specs/` and `ls specs//` (Bash) or `Get-ChildItem specs/` (PowerShell) — the same rule 1-plan and `/plan2code-2-document` follow when they look for the file you are about to write. - -**Do not append `## Planning Metrics` or any metrics comment.** Pathfinder is not a metered step. 1-plan's Phase 7 owns that block and will add it when it finishes the plan. Do not emit any of the loop's completion tokens listed in the skill's Rules anywhere under `specs/`. - -## Map to PLAN-DRAFT mapping - -Everything in the draft traces to something on the map. Nothing is invented at handoff time — if a section has no source, that is a gate failure you missed, not a paragraph to write from imagination. - -| Source on the cleared map | Becomes | -|---|---| -| `## Destination` | Section 1 Executive Summary (2-3 sentences, present tense) and Section 7 Success Criteria (the destination restated as checkable outcomes) | -| Resolved `grill` answers describing behavior | Section 2.1 Functional Requirements, one `FR-N` per decided behavior | -| Resolved `grill` answers describing performance, security, scale, operability | Section 2.2 Non-Functional Requirements, one `NFR-N` each | -| `## Out of scope` | Section 2.3 Out of Scope — copied line for line, wording and order intact. The ONLY permitted change is the link prefix: `./questions/` becomes `./pathfinder/questions/`, because the draft sits one level above the map. Do not re-word, re-order, or summarise; a re-worded scope boundary is a re-litigated one. | -| The testing-posture question's answer | Section 2.4 Testing Strategy table (Types / Phase Testing / Coverage) | -| Resolved `research` answers and their `## Evidence` | Section 3 Tech Stack — the cited source becomes the Justification cell | -| `questions/00-codebase-context.md` | The `## System Context` section, and the components table in 4.3 | -| Answers with `Locked: yes` | Section 4 Architecture (4.1 Pattern rationale, 4.4 Data Model, 4.5 API Design) **and** Section 9 Assumptions — a locked decision is an assumption downstream work is allowed to rely on | -| Consequences recorded across all `## Answer` sections | Section 6 Risks and Mitigations — the consequence is the Risk, the decision that bounds it is the Mitigation | -| `## Ground rules` | The `AGENTS.md` line in `## System Context`; conventions the plan must not violate | -| The shape of the map (question count, integrations touched, components named) | The `## Scope Assessment` section | -| Resolved `sketch` questions and their artifacts | Section 3 Justification cells and Section 6 Mitigation cells ("proven by `pathfinder/sketch-02/`") | -| Every resolved question, by name | `## Pathfinder Provenance` | -| — | **Section 5 Implementation Phases stays empty.** 1-plan Phase 6 breaks the work into phases. Pathfinder decides; it does not slice. Leave the placeholder note in place and do not put implementation checkboxes there. | - -Questions ruled `out-of-scope` never appear in Provenance and never become requirements. Their one line in `## Out of scope` is their only trace — that is the point of the marker. - -## The PLAN-DRAFT template - -Write this literally, substituting real content. Keep the section numbering exactly as shown — 1-plan and `/plan2code-2-document` both address sections by number. - -````markdown -> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete. - -# Audit Log Export - Implementation Plan - -**Created:** 2026-08-03 -**Status:** Phase 3 Complete - Resume at Phase 4 -**Charted by:** `/plan2code-0-pathfinder` over 9 sessions -**Planning record:** `specs/audit-log-s3-export/pathfinder/map.md` (no PLAN-CONVERSATION - this plan was charted, not conversed) -**Confidence (pathfinder):** Requirements-clarity 22/25 · Feasibility-technical 21/25 · Integration-points 23/25 · Risk-assessment 20/25 - ---- - -## 1. Executive Summary - -Tenants can have their audit logs exported nightly to an S3 bucket they own, with a -signed manifest per run so they can prove completeness. Export runs on the existing -Hangfire schedule, writes NDJSON, and assumes a customer-provided cross-account IAM -role with an external ID. Runs that exceed the per-tenant daily ceiling spill into the -next run rather than truncating. - -## 2. Requirements - -### 2.1 Functional Requirements - -- [ ] **FR-1:** Export each tenant's prior-day audit events as newline-delimited JSON, one object per event, UTF-8, no BOM -- [ ] **FR-2:** Write a per-run manifest listing object keys, event counts, byte counts, and a SHA-256 per object -- [ ] **FR-3:** Sign the manifest with the platform export key; publish the public key at a stable URL -- [ ] **FR-4:** Assume the tenant-configured IAM role with the tenant's external ID; never use platform-owned credentials against a customer bucket -- [ ] **FR-5:** Allow an operator to replay any run within a 7-day window without duplicating manifest sequence numbers -- [ ] **FR-6:** Spill events above the per-tenant daily ceiling into the next scheduled run, oldest first -- [ ] **FR-7:** Raise an alarm after three consecutive spilling runs for the same tenant - -### 2.2 Non-Functional Requirements - -- [ ] **NFR-1:** Sustain 200 MB per tenant per day at p95 without extending the nightly window past 04:00 UTC -- [ ] **NFR-2:** Never log tenant event bodies, bucket names, or assumed-role ARNs above debug level -- [ ] **NFR-3:** A failed run must leave no partial objects visible in the customer bucket -- [ ] **NFR-4:** Export must add no schema changes to the audit event write path - -### 2.3 Out of Scope - - - -- [Failure notification](./pathfinder/questions/07-failure-notification.md) — email/webhook delivery of run failures belongs to the platform alerting effort, not this export. The alarm in FR-7 is raised, not delivered. -- **On-demand export from the tenant UI** — the destination is the scheduled export. A user-triggered export is a separate effort with its own map. -- **Log formats other than NDJSON** — Parquet was raised and ruled past the destination. - -### 2.4 Testing Strategy - -| Aspect | Decision | -|---|---| -| Types | Unit + Integration | -| Phase Testing | Run after each phase | -| Coverage | Moderate (~60-80%) | - -## System Context - -**Project type:** Existing codebase — .NET 8 service, `src/Platform.Audit/` - -| Aspect | Finding | Source | -|---|---|---| -| Entry points to change | `AuditExportJob`, registered in `HangfireStartup.ConfigureRecurringJobs()` | [Codebase context](./pathfinder/questions/00-codebase-context.md) | -| Existing patterns to follow | Jobs resolve tenant scope via `ITenantScopeFactory`; no job reads config directly | [Codebase context](./pathfinder/questions/00-codebase-context.md) | -| Integration surfaces | S3 (customer-owned), Hangfire scheduler, `TenantConfigStore` | [Destination auth](./pathfinder/questions/03-destination-auth.md), [Scheduling model](./pathfinder/questions/02-scheduling-model.md) | -| Technical debt in the path | `AuditQuery` materialises full result sets; streaming reader needed before FR-1 | [Codebase context](./pathfinder/questions/00-codebase-context.md) | -| System boundaries | Read-only against the audit store; writes only to customer buckets and the run-log table | [Retention and replay](./pathfinder/questions/04-retention-and-replay.md) | -| Conventions in force | `AGENTS.md` present and read; its logging and DI conventions govern | `pathfinder/map.md` ## Ground rules | - -## Scope Assessment - -**Assessment: Medium** — 11 requirements across 3 integrations, 5 components touched. No Large threshold is met. - -| Indicator | Value | -|---|---| -| Requirements decided | 11 (7 FR + 4 NFR) | -| Components | 5 (`AuditExportJob`, `NdjsonWriter`, `ManifestSigner`, `S3RoleAssumer`, `ExportRunLog`) | -| Integrations | 3 (S3, Hangfire, `TenantConfigStore`) | -| Decisions charted | 8 resolved, 1 ruled out of scope | - -## 3. Tech Stack - - - -| Category | Technology | Version | Justification | -|---|---|---|---| -| Serialization | `System.Text.Json` NDJSON writer | .NET 8 | [Export format](./pathfinder/questions/01-export-format.md) — no new dependency; CSV rejected for nested actor payloads | -| Object storage | `AWSSDK.S3` multipart upload | 3.7.x | [Throughput ceiling](./pathfinder/questions/06-throughput-ceiling.md) — proven in `pathfinder/sketch-02/` against a real bucket at 400 MB | -| Cross-account auth | STS `AssumeRole` + external ID | — | [Destination auth](./pathfinder/questions/03-destination-auth.md) — AWS confused-deputy guidance cited in that file's `## Evidence` | -| Scheduling | Existing Hangfire recurring job | in-repo | [Scheduling model](./pathfinder/questions/02-scheduling-model.md) — a new scheduler was rejected | - -## 4. Architecture - -### 4.1 Pattern - -Pipeline inside the existing job host: query → stream → chunk → upload → manifest → sign. -Chosen because the audit store is the only source and the export is strictly one-way. -[Locked] A separate export microservice was rejected — see [Scheduling model](./pathfinder/questions/02-scheduling-model.md). - -### 4.2 System Context Diagram - - - -### 4.3 Components - -| Component | Responsibility | Inputs | Outputs | Depends on | -|---|---|---|---|---| -| `AuditExportJob` | Orchestrates one tenant-run | Tenant id, run date | Run result | `TenantConfigStore` | -| `NdjsonWriter` | Streams events to chunked NDJSON | Event stream | Byte stream, counts | — | -| `S3RoleAssumer` | Assumes the tenant role, returns a scoped client | Role ARN, external ID | `IAmazonS3` | STS | -| `ManifestSigner` | Builds and signs the run manifest | Object metadata | Signed manifest | Platform export key | -| `ExportRunLog` | Records runs for replay and spill detection | Run result | Run rows | Platform DB | - -### 4.4 Data Model - -Manifest sequence numbers are per tenant, monotonic, and reused on replay. -[Locked] See [Retention and replay](./pathfinder/questions/04-retention-and-replay.md). - -### 4.5 API Design - - - -## 5. Implementation Phases - - - -## 6. Risks and Mitigations - -| Risk | Likelihood | Impact | Mitigation | -|---|---|---|---| -| Cross-account role assumption is unexercised in this codebase | Medium | High | Spike `S3RoleAssumer` against a second AWS account before any other component | -| A tenant exceeds the daily ceiling indefinitely | Medium | Medium | Spill oldest-first plus a three-run alarm — [Overflow behavior](./pathfinder/questions/08-overflow-behavior.md) | -| Partial objects visible after a failed run | Low | High | Upload to a run-scoped prefix, publish the manifest last — the manifest is the commit point | -| `AuditQuery` materialises full result sets | High | High | Streaming reader is a prerequisite, not an optimisation | -| Customer revokes the role mid-run | Low | Medium | Fail the run whole; replay window covers recovery | - -## 7. Success Criteria - -- [ ] A tenant with a configured role receives NDJSON and a signed manifest for the prior day, nightly -- [ ] The published public key verifies the manifest signature -- [ ] A 250 MB tenant-day completes without extending the window past 04:00 UTC -- [ ] A replay inside 7 days reproduces the run without a new sequence number -- [ ] A failed run leaves nothing visible in the customer bucket - -## 8. Open Questions - - - -None. The map cleared with zero open questions. - -## 9. Assumptions - -- Tenants can create an IAM role in their own account — [Destination auth](./pathfinder/questions/03-destination-auth.md) [Locked] -- The nightly Hangfire window remains available and is not contended by other jobs — [Scheduling model](./pathfinder/questions/02-scheduling-model.md) [Locked] -- Manifest sequence reuse on replay is acceptable to tenant compliance teams — [Retention and replay](./pathfinder/questions/04-retention-and-replay.md) [Locked] -- Audit events are immutable once written, so a replay reproduces byte-identical output - -## Pathfinder Provenance - -Charted over 9 sessions. Each requirement above traces to a decision below; open the -question for what was rejected, why, and what it costs. - -| Question | Gist | -|---|---| -| [Codebase context](./pathfinder/questions/00-codebase-context.md) | `AuditExportJob` and `HangfireStartup` are the extension points; `AuditQuery` needs a streaming reader first | -| [Export format](./pathfinder/questions/01-export-format.md) | NDJSON with a per-run signed manifest; CSV rejected for nested actor payloads | -| [Scheduling model](./pathfinder/questions/02-scheduling-model.md) | Reuse the existing Hangfire recurring job; a dedicated export service was rejected | -| [Destination auth](./pathfinder/questions/03-destination-auth.md) | Customer-owned bucket via assumed role plus external ID; no platform-held customer credentials | -| [Retention and replay](./pathfinder/questions/04-retention-and-replay.md) | 7-day replay window, sequence numbers reused on replay | -| [Testing posture](./pathfinder/questions/05-testing-posture.md) | Unit + integration, run after each phase, moderate coverage | -| [Throughput ceiling](./pathfinder/questions/06-throughput-ceiling.md) | 200 MB per tenant per day at p95; multipart upload proven in `pathfinder/sketch-02/` | -| [Overflow behavior](./pathfinder/questions/08-overflow-behavior.md) | Spill oldest-first into the next run; alarm after three consecutive spills | - -Ruled out of scope: [Failure notification](./pathfinder/questions/07-failure-notification.md) — recorded in 2.3. - ---- - -**Next:** Resume with `/plan2code-1-plan` at Phase 4 (Tech Stack). - -- **Phase 7 verification:** sections 1, 2, System Context and Scope Assessment are already settled — their source of truth is `specs/audit-log-s3-export/pathfinder/map.md`, not this conversation. Verify sections 3-7 only. -- **Phase 7:** replace THIS file in place. Do not create a second PLAN-DRAFT in this folder. -```` - -### Two things in that template that are not optional - -**No scrapable confidence numbers anywhere in the file.** Write the confidence as `Requirements-clarity 22/25 · Feasibility-technical 21/25 · Integration-points 23/25 · Risk-assessment 20/25` — hyphenated dimension labels, sub-scores over 25, no total, no percent sign. - -The reason is exact. When a PLAN-DRAFT carries no `METRICS_JSON` comment, the metrics collector falls back to scraping it by regex: an overall-confidence pattern that requires a literal `%`, and four breakdown patterns that match a bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed directly by whitespace, a colon, or a pipe and then digits. **The breakdown patterns do not require a percent sign.** A pathfinder-written draft always lacks that comment until `/plan2code-1-plan` Phase 7 appends one, so both the percent sign *and* the bare dimension words have to be kept off the page — otherwise the pipeline records a planning-step confidence that no planning step ever produced. The hyphen in `Requirements-clarity` breaks the match; a table row reading `| Requirements | 11 |` does not, which is why the Scope Assessment row is labelled `Requirements decided`. - -**The `**Next:**` footer must ship with both bullets.** Pathfinder cannot edit the planning skill, so those two instructions travel inside the artifact: - -- *Without the verification bullet*, 1-plan's Phase 7 does exactly what it is told to do — "re-read conversation as source of truth" — finds a fresh conversation that starts at Phase 4 and contains no requirements discussion at all, concludes sections 1 and 2 are unsupported, and silently drops the requirements that N pathfinder sessions produced. The bullet redirects the source of truth for the settled sections to `map.md`. -- *Without the replace-in-place bullet*, 1-plan's Phase 7 creates `PLAN-DRAFT-.md` alongside yours. `/plan2code-2-document` then finds two drafts in the folder, hits its "Multiple found: List all, ask which to document" branch, and asks the user to disambiguate between a pathfinder draft and a plan draft that partially supersedes it. - -Never drop the footer to make the file tidier. It is load-bearing. - -After writing the draft, run `lint`: it scans a pathfinder-written PLAN-DRAFT with the metrics collector's own patterns and names any bait that reached the page. - -## System Context and Scope Assessment — why they buy you Phase 4 - -These two named, unnumbered sections are what make "Resume at Phase 4" legitimate rather than a shortcut. They stand in for the phases pathfinder already did the work of: - -| Draft section | Satisfies | Because pathfinder already | -|---|---|---| -| Sections 1 and 2 (including 2.4 Testing Strategy) | 1-plan **Phase 1: Requirements Analysis** | Grilled every functional and non-functional decision, and always charted a testing-posture question — that question exists specifically so Phase 1's testing prompt is already answered | -| `## System Context` | 1-plan **Phase 2: System Context Examination** | Wrote `questions/00-codebase-context.md` at Chart Step 3: directory structure, key components verified against actual code, patterns and conventions, integration points, technical debt, boundaries — Phase 2's own checklist, item for item | -| `## Scope Assessment` | 1-plan **Phase 3: Scope Assessment** | Produced the counts Phase 3 measures — requirements, components, integrations — as a byproduct of charting. Map the totals onto Phase 3's Small / Medium / Large table and state the verdict | - -Populate `## System Context` from `00-codebase-context.md` and nothing else. It is the one question guaranteed to exist on every map, it was resolved on the spot with the codebase open, and it is a `legwork · AFK` answer — factual, not preferential. Cite it in the Source column so a skeptical reader can check the finding against the file. - -Populate `## Scope Assessment` from the shape of the map. Count resolved questions that produced requirements (not `00-codebase-context.md`, not out-of-scope ones), count distinct components named across the answers, count distinct external systems. Apply Phase 3's thresholds honestly: Large if **any** threshold is met. Score the counts, never the session count — a map can take nine sessions to clear and still be Medium, and the `Phase 3 Complete - Resume at Phase 4` status string works regardless of the verdict, so there is nothing to gain by inflating it. Pathfinder cannot count implementation phases (Section 5 is deliberately left empty), so assess on requirements, components, and integrations only. - -If the charting session found `AGENTS.md` absent, say so in the `Conventions in force` row rather than leaving it blank. The plan session needs to know the conventions were never available, not guess that they were checked. - -## Freeze the map - -Once the PLAN-DRAFT is written and saved: - -1. Set `**Status:** Cleared` in `map.md`. -2. Bump `**Updated:**` to today. -3. Add a plan pointer line under the status: `**Plan:** ../PLAN-DRAFT-20260803.md`. -4. Leave **everything** under `pathfinder/` exactly where it is — `map.md`, every file in `questions/`, every `sketch-NN/` directory. - -**Never delete `pathfinder/`.** It is the rationale record behind the plan: what was decided, what was rejected, why, and what it costs. It sits in the same class as `PLAN-CONVERSATION-*.md` — the transcript a plan is defensible against — and `/plan2code-4-finalize` archives it alongside `PLAN-DRAFT.md` and `PLAN-CONVERSATION-*.md` into `specs--completed//`. Deleting it turns every locked decision in the plan into an unexplained constraint six months from now. - -Do not tidy it either. Do not collapse resolved questions into the map, do not prune `## Evidence`, do not remove sketch directories because the code is throwaway. The sketch is the proof behind a feasibility score. - -**A later session that finds `Status: Cleared` must not resume work on it.** The map is finished; there is nothing left to decide inside it. Point at the PLAN-DRAFT and `/plan2code-1-plan`, and stop. If the destination has been redrawn — the scope grew, an out-of-scope item came back, the goal changed — that is a **fresh effort with a fresh map**, not a resumption: a new kebab-case idea name, a new `specs//pathfinder/`, charting from Step 1. The frontier stops at the destination, so a new destination gets a new frontier. Reopening a cleared map silently invalidates the PLAN-DRAFT that was built from it, and nothing downstream would notice. - -## What to tell the user - -Session End for the cleared case reports six things, in this order: - -| # | Report | -|---|---| -| 1 | The destination, restated — what the map was finding its way to, now reached | -| 2 | How many decisions were made, and the headline ones **by name** | -| 3 | What was ruled out of scope, and why (one line each) | -| 4 | The four confidence scores, with a one-line justification for any below 21 | -| 5 | The PLAN-DRAFT path | -| 6 | The next command — carried by the Trail Footer, which at `Cleared` routes to `/plan2code-1-plan` | - -Example: - -> **Destination reached:** a spec a developer can implement for nightly audit-log export to customer-owned S3 buckets with a signed manifest. -> -> **8 decisions made** across 9 sessions. The load-bearing ones: [Export format](./questions/01-export-format.md) settled on NDJSON with a signed manifest; [Destination auth](./questions/03-destination-auth.md) settled on assumed roles with an external ID so we never hold customer credentials; [Overflow behavior](./questions/08-overflow-behavior.md) settled on spilling rather than truncating. -> -> **Ruled out of scope:** failure-notification delivery (belongs to the platform alerting effort), on-demand export from the tenant UI (its own effort), Parquet output (past the destination). -> -> **Confidence:** Requirements-clarity 22/25 · Feasibility-technical 21/25 · Integration-points 23/25 · Risk-assessment 20/25. Feasibility is held at 21 because cross-account role assumption is unexercised in this codebase — it is a documented pattern, not a proven one here, and it is the first thing to spike. -> -> **Written:** `specs/audit-log-s3-export/PLAN-DRAFT-20260803.md`. It resumes planning at Phase 4 — sections 1, 2, System Context and Scope Assessment are already settled. The reasoning behind every one of them stays in `specs/audit-log-s3-export/pathfinder/`; do not delete it. - -Then the closing block from the skill's Session End — the mascot with the message *The way is clear! Time to plan!* followed by the Trail Footer, whose trail shows every stop walked to the `⚑` destination and whose command is `/plan2code-1-plan`. - -**One branch.** If `## Ground rules` records `AGENTS.md` as **absent**, recommend `/plan2code-init` FIRST, and offer `questions/00-codebase-context.md` as its input: - -> Before planning: this project has no `AGENTS.md`, and `/plan2code-1-plan` blocks on that. Run `/plan2code-init` first and attach `specs/audit-log-s3-export/pathfinder/questions/00-codebase-context.md` — the recon pass already established the structure, conventions, and integration points it asks for. Then `/plan2code-1-plan`. - -Nothing to commit — `specs/` is gitignored. Say so once, then stop. - -## Failure modes - -| Symptom | Cause | Fix | -|---|---|---| -| 1-plan starts at Phase 1 and re-asks for requirements | The status string does not match byte for byte | Compare against the quoted line above; watch for en dashes and casing | -| 1-plan cannot find the draft at all | Glob was used to discover `specs/` | Shell only: `ls specs/` | -| `/plan2code-2-document` asks which of two drafts to use | The replace-in-place bullet was dropped from the footer | Merge the two drafts into the pathfinder-dated one, delete the other, restore the footer | -| The finished plan is missing requirements the map decided | The verification bullet was dropped from the footer | Re-derive 2.1 and 2.2 from the resolved answers, restore the footer | -| Metrics report a planning confidence nobody scored | A percent sign, or a bare dimension word followed by a number, reached the file | Hyphenate the dimension labels and drop the percent sign | -| A locked decision in the plan has no visible reason | `pathfinder/` was deleted or pruned | Unrecoverable. This is why the freeze step exists | -| Gate passes but the first implementation session immediately hits an undecided question | A dimension was rounded up | The gate was the check. Score the written record, not the feeling | \ No newline at end of file diff --git a/skills/plan2code-0-pathfinder/references/questions.md b/skills/plan2code-0-pathfinder/references/questions.md deleted file mode 100644 index ea7bf10..0000000 --- a/skills/plan2code-0-pathfinder/references/questions.md +++ /dev/null @@ -1,47 +0,0 @@ -# Questions & Map Format -> Part of plan2code-0-pathfinder — the on-disk format both modes share: directory layout, `NN` numbering, the question-file schema, `Type:` vocabulary, and the marker / blocking rules. The main file keeps only the marker legend and a layout gist; the authority is here. -> -> **This file describes the `local` backend only.** If `## Ground rules` says `**Backend:** github`, the equivalence table in `github-issues.md` replaces every rule below — there are no files, no `NN`, no schema lines, and no checklist. - -## Layout - -``` -specs// -├── pathfinder/ -│ ├── map.md <- the index -│ ├── questions/NN-.md <- 00-codebase-context.md always exists -│ ├── briefs/brief-.md <- plain-English reports, written by BRIEF mode only -│ └── sketch-NN/ <- optional runnable sketch, throwaway -└── PLAN-DRAFT-.md <- written ONLY when the map clears -``` - -`questions/` is ground truth; `map.md` is a rebuildable index that gists and links. A filled `## Answer` beats any `State:` line. Detail lives in exactly one place — the question file. - -## Numbering - -`NN` is zero-padded from `00`, assigned in dependency order (blockers lower), **never reused or renumbered** — links and `Blocked by:` would rot silently. Next = max + 1 (`frontier`'s `nextNN`), never below the map's `**Next NN:**` high-water line, which the script keeps so a deleted question's number stays retired (chart.md, Step 6 rule 5). A one-digit file name (`1-export.md`) still reads as `01`, but `lint` asks for the rename. `00` is always `00-codebase-context.md`, never anything else. Gaps in the sequence are normal and harmless. - -## The six schema lines - -Each question file carries six contiguous `Key: value` lines after its H1 — NOT YAML frontmatter, no `---` delimiters: - -| Line | Values | -|---|---| -| `Type:` | `grill · HITL` \| `research · AFK` \| `sketch · HITL` \| `legwork · HITL` \| `legwork · AFK` — one token, so type and mode cannot drift | -| `State:` | `open` \| `claimed` \| `resolved` \| `out-of-scope` | -| `Blocked by:` | `none` \| `02, 04` | -| `Claimed:` | `none` \| `` — a work-in-progress lock, not a completion record | -| `Resolved:` | `none` \| `` — set in the same write as `State: resolved` (Work Step 7). The date the decision landed; briefs filter on it | -| `Locked:` | `yes` only when hard to reverse AND surprising without context AND a real trade-off | - -**Backfill (older maps):** a file with a filled `## Answer` but `Resolved: none` (or no `Resolved:` line at all) gets the line backfilled at reconcile — from the `Claimed:` date, or today if `Claimed: none`. Say so once in the session report. - -**Type meanings.** **grill** (default) — a decision only the human can make. **research** — a fact outside this directory gates it. **sketch** — the human needs something concrete to react to. **legwork** — manual work that must happen before a decision is possible. - -## Markers and blocking - -**Map markers**, rebuilt from the files every session: `[ ]` open — **these rows ARE the frontier** · `[/]` claimed · `[x]` resolved · `[!]` open but blocked · `[-]` out of scope. Resolved rows carry the gist plus the `Resolved:` date in italics: `— *(YYYY-MM-DD)*`. - -`scripts/pathfinder.mjs` implements exactly these rules (`reconcile` rebuilds the markers, `frontier` computes blocking, `lint` checks the schema), so this file is the reference for reading its output and for writing a question file. Apply the rules by hand only when the script cannot run. - -**Unblocked** ⟺ every `NN` in `Blocked by:` is `resolved`. **Stranded:** a blocker gone `out-of-scope` never resolves — the question is not merely blocked. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting. diff --git a/skills/plan2code-0-pathfinder/references/resolve.md b/skills/plan2code-0-pathfinder/references/resolve.md deleted file mode 100644 index 3a4b37a..0000000 --- a/skills/plan2code-0-pathfinder/references/resolve.md +++ /dev/null @@ -1,566 +0,0 @@ -# Resolution Playbook - -> Loaded at the top of MODE B. Work Step 6 routes here by `Type:`; Work Step 8 uses the fog procedure at the end. -> -> **Backend note.** Every resolution technique here is backend-independent — the type table, the primary-source rule, the sketch tiers, the checklist discipline, the `## Answer` anatomy. On `**Backend:** github`, `Type:` is a `pathfinder:-` label, `## Answer` and `## Evidence` are comments rather than file sections, and a research subagent gets an issue URL instead of a path; see `github-issues.md`. Sketches stay on local disk regardless. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes. - -Every question resolves into the SAME shape — a filled `## Answer` plus whatever `## Evidence` backs it. The type only decides how you get there. - -| `Type:` | Who drives | Parallel? | What "resolved" means | -|---|---|---|---| -| `research · AFK` | Subagent, alone | **Yes** — many at once | Facts found and cited; no decision made | -| `sketch · HITL` | Agent builds, human reacts | No | The human reacted and chose | -| `legwork · AFK` | Agent, alone | No | The work is done; resulting facts recorded | -| `legwork · HITL` | Human does, agent waits | No | The human confirmed it is done | -| `grill · HITL` | Human decides, agent interrogates | No — but probes batch, up to 3 per turn | The human said it in their own words | - -**One question _file_ at a time** holds for every row except `research` — several may resolve in one session, but strictly in sequence, per the Cadence below. `research` is also the one type that is **never claimed**: its subagents fire unclaimed (the file stays `State: open`), so `claim` and its one-claim rule govern grill, sketch and legwork only, and a grill can be claimed while research runs. A research question is finished with `## Answer` plus `resolve` once its subagent is back, or re-fired from `reconcile`'s `refire` if it was cut off. HITL rows are never self-answered — an agent that writes its own `## Answer` on a `grill` has broken the skill. - -Every file you create along the way — question files, sketch READMEs — opens with the banner: - -`> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.` - ---- - -## Cadence: decide → menu → checkpoint - -The Work loop no longer ends after one decision. It ends when the human stops it, or when the checkpoint recommends stopping — whichever comes first. This holds for a solo developer and for a Product + Engineering room alike; a meeting is just a session with more people answering, and needs no special invocation. - -``` -claim ONE → resolve → recap → confirm → record → mark map [x] - → MENU (trail.md Form C): takeable frontier + resume command, human picks or stops - → claim the next … repeat … -``` - -**The menu turn.** After every recorded decision, use the structured question tool per trail.md §Form C: offer up to three takeable questions (from the map's checklist rows — name + gist, no file re-reads) plus `Start fresh`; `Other` covers another frontier name. Flag anything just unblocked, mark exactly one description `RECOMMENDED`, and print the resume command under `OR START FRESH` before the tool. Lowest `NN` stays the *recommendation* default, never the selection — the human picks. - -**The checkpoint is the menu with the recommendation flipped.** The old one-per-session rule had two jobs: crash-safety and context hygiene — a fresh window per decision keeps the model sharp. Sequential claims preserve the first. The checkpoint preserves the second: after **~3 questions resolved this session** (soft cap), or earlier after a heavy, contested, or `Locked: yes` decision that would benefit from settling overnight, mark the tool's `Start fresh` option RECOMMENDED and say why in the question text — "to keep me sharp." The human can override in either direction; a recommendation is something to push against, not a gate. - -The restart costs one paste and loses nothing: every claim, answer, and map update hits disk before anything else happens, and the next session assumes no memory anyway. The fresh session reconciles, renders the trail, and presents the menu again. - -**In-loop hygiene** — what keeps each cycle lean between checkpoints: - -- Read only what the cycle needs: the claimed question file plus resolved neighbors' *gists* (Work Step 5). Never re-read the whole `questions/` directory between cycles — reconcile ran once at session start, and this session is the only writer. -- The menu renders from the map's checklist rows, never from re-reading question files. -- Strictly one claim open at any moment. Claim → record → release, then the menu. Never two. (Research subagents run unclaimed beside it; see the top of this file.) - -**Group sessions.** When Product and Engineering (or any room) work the map together, the grilling playbook's group-session rules apply: probes address the room, the recap captures the decision in the room's words, and a contested pick is never recorded as decided — both positions go under `## Evidence`, the question stays `open`, and the menu moves on (or offer to convert it to `sketch`; reacting to something concrete resolves more standoffs than argument). At Session End, offer `write a brief for today` — the brief doubles as the meeting minutes. - -**Stopping is always legitimate.** Ending after one decision is fine. The skill no longer forces deliberation time between decisions; it *advises* it, via the checkpoint, where a decision was heavy enough to deserve settling overnight. - ---- - -## `research · AFK` - -The only type an agent resolves alone, and the only type that may run several at once. Charting fires them in a batch at Chart Step 8; MODE B fires any that appear later the same way, unclaimed: never run `claim` on a research question. When one tops the frontier at Work Step 4, fire it, then claim the first non-research question. - -### Spin up a subagent - -One subagent per research question. Do not read the docs yourself in the main session — the point is that the main session's context stays clean for the decision work. - -The subagent's brief must carry, verbatim: - -1. The absolute path of the question file it owns. -2. The `## Question` text. -3. The instruction to write into `## Evidence` of THAT file and nothing else — `## Answer` and `State:` are written by the session that fired it, at Work Step 7. -4. The primary-source rule below. -5. The no-deciding rule below. -6. The instruction to end `## Evidence` with `**Research complete:** ` as its last line, written only once every claim is in. Without that line, the next session cannot tell finished research from research that was cut off. - -### Wait for every subagent - -Subagents run inside this session's process, even when the harness runs them in the background. Close the terminal, or end the session, and they die mid-write, leaving `## Evidence` half-filled. So: - -- **Do not reach Session End, or post a web console `finish`, while any research subagent is still running.** Wait for each one to report back. The main session does not read the sources while it waits; it only collects completions. -- While waiting in the web console, post `{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}` and update the count as each returns, so the page never says "done" while work is still in flight. -- Never tell the human the research "will finish on its own" or is "running in the background, ready for next time". It is not: it lives in this terminal. -- Once all are back, Session End reports each research question with a one-line summary of what was found (not decided). - -### Interrupted research - -At Work Step 2, `reconcile` lists in `refire` every research question that is not resolved and whose `## Evidence` lacks the `**Research complete:**` line (with its path and `## Question` text for the brief): it was never finished, by a closed terminal, a crash, a rate limit. Re-fire its subagent with the same brief, plus one instruction: keep what is already in `## Evidence`, verify it, fill the gaps, then write the line. Say so in one line to the human. A map written before this line existed shows the same symptom; re-firing it costs a little time and nothing else. - -### Primary sources only - -Investigate against **primary sources** — official documentation, the library's own source code, the RFC or spec text, the first-party API reference, the vendor's own pricing page, the actual response from a live endpoint. Never a secondary write-up of them. A blog post, a Stack Overflow answer, or a model's recollection is a *lead*, not a source: follow every claim back to the source that owns it, and cite that. - -| Claim about | Source that owns it | -|---|---| -| A library's behavior | That library's source or its own docs for the installed version | -| An HTTP API's shape | The vendor's API reference, or a real captured request/response | -| A file format | The format specification | -| A limit or quota | The vendor's own limits page, dated | -| This project's behavior | The code in this repo, by path | - -If no primary source can be found, say so explicitly in `## Evidence` and mark the claim UNVERIFIED. An honest gap is worth more than a confident secondhand sentence — the gap becomes a `legwork` question (go run it and see) or a `grill` (the human decides under uncertainty). - -**Version-pin everything.** "Node supports it" is not a finding. "Node 20.11 supports it; the project's `.nvmrc` pins 18.19, which does not" is. - -### It does not decide - -A research question's `## Answer` states the FACTS FOUND and what they imply. It never picks. The moment the findings enable a choice, that choice becomes a **separate `grill`** question, written at Work Step 8. - -This split is the whole reason research is safe to run AFK. An agent that reads three storage options and then declares a winner has quietly made an architectural decision the human never saw. - -### The dropped git branch - -Upstream captures each prototype and research run on a throwaway git branch. **Pathfinder deliberately drops that.** `specs/` is already untracked scratch space, and plan2code never touches git during pathfinder. The question file IS the durable capture. Do not create branches, do not commit, do not mention branches in the `## Answer`. - -### Worked example - -`questions/04-object-lock-retention.md` after Work Step 7 recorded its subagent findings: - -```markdown -> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete. - -# Object Lock retention semantics for the archive bucket - -Type: research · AFK -State: resolved -Blocked by: none -Claimed: 2026-08-03 14:02 -Resolved: 2026-08-03 -Locked: no - -## Question - -If archived messages land in S3 under Object Lock, what retention modes exist, -which of them can be shortened or lifted after the fact, and what does each -require of the bucket at creation time? We need the facts before deciding -whether a 7-year hold can coexist with a customer's right-to-delete request. - -## Answer - -**Facts found** - -1. Object Lock supports two retention modes: GOVERNANCE and COMPLIANCE. -2. Under GOVERNANCE, a principal holding `s3:BypassGovernanceRetention` can - shorten or remove a retention period on an object version. -3. Under COMPLIANCE, no principal — including the account root — can shorten - or remove it until the retain-until date passes. -4. Object Lock can only be enabled at bucket creation, and enabling it forces - versioning on permanently. -5. A legal hold is independent of retention mode, has no expiry, and is - toggled by any principal with `s3:PutObjectLegalHold`. - -**What this implies** - -- A right-to-delete request is satisfiable under GOVERNANCE and is NOT - satisfiable under COMPLIANCE before the retain-until date. These two - obligations cannot both be met on the same object version. -- Retrofitting Object Lock onto the existing `archive-prod` bucket is not - possible; it would require a new bucket and a full copy. - -**Decision this enables (not made here)** - -Which mode the archive uses, and how right-to-delete is honored under it, -is now a sharp question — see Work Step 8, spun off as a grill. - -**Gist:** COMPLIANCE mode is irreversible even for root; GOVERNANCE is -bypassable — and Object Lock cannot be added to the existing bucket. - -## Evidence - -- Two modes, and the governance-bypass permission — - AWS S3 User Guide, "Object Lock overview", section "Retention modes". - https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock-overview.html - (retrieved 2026-08-03) -- COMPLIANCE cannot be shortened by any user including the root user — - same page, "Compliance mode" paragraph, verbatim: "no user can overwrite or - delete the object version during the retention period." -- Enable-at-creation-only, and forced versioning — - AWS S3 User Guide, "Enabling Object Lock", first note block. - https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock-configure.html -- Legal hold independence and no expiry — - same guide, "Legal holds" section. -- Existing bucket has Object Lock disabled — verified against this account: - `aws s3api get-object-lock-configuration --bucket archive-prod` - returns `ObjectLockConfigurationNotFoundError`. (run 2026-08-03) -- UNVERIFIED: whether our compliance counsel treats GOVERNANCE as sufficient - for the SEC 17a-4 attestation. No primary source exists for this — it is a - human judgment, not a fact. Belongs in a grill. - -**Research complete:** 2026-08-03 -``` - -Note what the example does: every claim carries its own citation, a live command counts as a primary source, the one thing that cannot be sourced is flagged rather than smoothed over, and the closing `**Research complete:**` line marks the subagent's work as whole. - ---- - -## `sketch · HITL` - -Raise the fidelity of the discussion by making something cheap and concrete for the human to react to. "How should this behave?" and "what should this look like?" produce vague answers in the abstract and sharp ones in front of an artifact. - -Two tiers. **Start at Tier 1 every time.** - -### Tier 1 — paper sketch (the default) - -No executable code. You write a concrete thing into the question's `## Evidence`, show it to the human, and they react. Most sketch questions never need more than this. - -Shapes that work: - -| Shape | Use when the question is | -|---|---| -| Outline | "What are the steps, and in what order?" | -| State table | "What states exist and which transitions are legal?" | -| Worked example with real numbers | "Does this rule produce sane results?" | -| Fake request/response pair | "What should this API actually look like?" | -| ASCII UI | "What goes on this screen and what is primary?" | -| Decision table | "Under which conditions do we do which thing?" | - -Rules for a paper sketch: use REAL-looking content, never placeholders. Real customer names, real message counts, real timestamps, real error strings. A table full of `foo` and `item 1` gets nodded at; a table with `retention_expired` in it gets argued with, and the argument is the point. - -Present it, then ask the pointed questions the sketch actually opens — up to three, batched, in the same turn as the artifact. A sketch is the one place where several probes come free: the human has the whole picture in front of them, so a second and third question cost them almost nothing, and a state table with three questionable rows should not take three sessions. - -Pointed is the discipline that survives batching. Never "thoughts?" — every probe names its row or element: "row 5 says a flagged message still archives when retention expires. Right, or does the hold pin it in place?" Show the artifact inline, then immediately invoke the structured question tool for up to three pointed reaction probes. The artifact stays in prose; every answer control stays in the UI, with `Other` available for hybrids and corrections. - -Follow the structured-tool rules in `grilling.md`: short distinct headers, the pointed question plus why-it-matters in the question field, genuine alternatives with trade-offs in descriptions, and one recommendation per probe. - -Putting up a sketch is a **Form B turn** in `trail.md`: close it with `WAITING ON YOU` naming the probes, never a resume command. The human is meant to react to the artifact in this conversation, and a footer telling them to start a new one throws the sketch away. - -#### Paper sketch example A — state table - -For `questions/06-review-lifecycle.md`: - -```markdown -| From | Event | To | Legal? | -|--------------|----------------------|--------------|-------------| -| ingested | policy match | flagged | yes | -| ingested | no match, 24h passes | archived | yes | -| flagged | reviewer clears | archived | yes | -| flagged | reviewer escalates | escalated | yes | -| flagged | retention expires | archived | ← QUESTION | -| escalated | case closed | archived | yes | -| escalated | retention expires | escalated | stays put | -| archived | legal hold applied | held | yes | -| held | hold released | archived | yes | -| held | retention expires | held | hold wins | - -Open on this sketch: an item sitting in `flagged` when its retention window -expires. Row 5 currently drops it to `archived` unreviewed. The alternative is -that expiry cannot fire while a human review is outstanding — retention pauses. -``` - -#### Paper sketch example B — fake request/response pair - -For `questions/09-export-job-api.md`: - -```markdown -POST /v1/exports -{ - "channel_ids": ["ms-teams-legal", "ms-teams-trading"], - "from": "2025-01-01T00:00:00Z", - "to": "2025-12-31T23:59:59Z", - "format": "eml", - "include_attachments": true -} - -202 Accepted -{ - "export_id": "exp_9fK2mQ", - "state": "queued", - "estimated_messages": 418377, - "estimated_bytes": 12884901888, - "poll_url": "/v1/exports/exp_9fK2mQ", - "expires_at": "2026-08-10T14:00:00Z" -} - -GET /v1/exports/exp_9fK2mQ -200 OK -{ - "export_id": "exp_9fK2mQ", - "state": "partial_failure", - "messages_written": 418202, - "messages_failed": 175, - "failure_manifest_url": "https://.../exp_9fK2mQ-failures.csv", - "download_urls": ["https://.../exp_9fK2mQ-part-001.zip", "..."] -} - -Open on this sketch: `partial_failure` hands back a download plus a manifest of -what is missing. The alternative is all-or-nothing — 175 failures void the whole -12 GB export. Which does a compliance officer actually want at 4pm on a Friday? -``` - -#### Paper sketch example C — ASCII UI - -For `questions/11-reviewer-queue-layout.md`: - -```markdown -+----------------------------------------------------------------+ -| Review Queue [ Mine 42 ] [ Team 318 ] [ Overdue 7 ] | -+---------------------------+------------------------------------+ -| ! 2d K. Ondrusek | From: Kamil Ondrusek | -| "…move the block…" | To: trading-desk (14 members) | -| trading-desk | 2026-08-01 09:14 MS Teams | -|---------------------------| | -| 1d A. Whitfield | Policy hit: BLOCK-TRADE-LANGUAGE | -| "confirming size" | Confidence: 0.91 | -| trading-desk | | -|---------------------------| > can you move the block before | -| 4h R. Iyer | the close? size is 40k | -| "attached the deck" | | -| legal-general | [ Clear ] [ Escalate ] [ Hold ] | -+---------------------------+------------------------------------+ - -Open on this sketch: the policy hit and its confidence sit in the detail pane, -so the list gives no reason to pick one item over another beyond age. Should the -list rank by confidence instead of age, and show the rule name per row? -``` - -### Tier 2 — runnable sketch (available, and gated) - -Every other plan2code step forbids writing code during planning. **Pathfinder is the one exception**, because some questions genuinely cannot be settled on paper: "does this state model actually hold once you push it through the ugly cases?", "what should this feel like?" A paper state table always looks fine. Driving it by hand for ninety seconds is where it falls over. - -**All three gates must open before you write a line of code:** - -1. The paper sketch was tried and did not settle it. Not skipped — tried. Say what the paper sketch failed to resolve. -2. There is an obvious way to run it in this project — an existing runtime and task runner. Do not add a package manager, language, or framework for a sketch. -3. The user says go. Ask explicitly: *"Paper didn't settle row 5. I can build a throwaway terminal app under `specs/audit-export/pathfinder/sketch-01/` that lets you drive the state machine by hand — about 60 lines, one command, deleted after. Go?"* - -Any gate that stays shut: stay on paper, or convert the question to a `grill`. - -#### Rules for a runnable sketch - -1. **Throwaway from day one, and clearly marked.** Its README's first line is the banner, and its second says what question it exists to answer. -2. **It lives ONLY at `specs//pathfinder/sketch-NN/`** — never in the project's own source tree, never beside the module it is sketching for. This is where pathfinder deliberately departs from upstream: upstream co-locates prototypes with the real code; pathfinder quarantines them, because `specs/` is gitignored scratch and the project tree is not. -3. **One command to run.** Print the exact command to the user. They must not have to remember a path or a flag. If the project has a task runner, use the runner's own idiom, but keep the entry point inside `sketch-NN/`. -4. **No persistence.** State lives in memory. Persistence is what the sketch is checking, not something it leans on. If the question is specifically about storage, use a local file named so its disposability is obvious. -5. **Skip all polish.** No tests, no error handling beyond what makes it run, no abstractions, no "we might want X later." -6. **Surface the full relevant state after every action** (logic) **or on every variant switch** (UI). The user must see the whole picture change, not a delta. -7. **Never merged.** The sketch is not lifted into the project. Only the validated decision it produced survives, in the `## Answer`. Reference the sketch directory from `## Evidence` so a later reader can re-run it, but the code is scaffolding, not output. - -#### Pick the branch: logic or UI - -| Question shape | Branch | Artifact | -|---|---|---| -| "Does this state model / data model / rule hold?" | **Logic** | One tiny interactive terminal app | -| "What should this look like?" | **UI** | Several radically different variations, switchable | - -Getting this wrong wastes the entire sketch. If the question is genuinely ambiguous and the user is unreachable, default by what the question touches — a backend module or a rules engine points to logic, a page or component points to UI — and **state the assumption in the first lines of the sketch's README**, so the human can reject the framing before reading the code. - -**Logic branch.** Build the smallest interactive terminal app that pushes the machine through the cases that are hard to reason about on paper. Keep the logic itself pure — a reducer, a state machine, or a small set of pure functions over a plain data type — with the terminal shell as a thin wrapper that imports it and never the reverse. Each frame: clear the screen, print the whole current state one field per line, then print the key legend, e.g. `[f] flag [c] clear [e] escalate [h] hold [t] advance clock 1d [q] quit`. Re-render the entire frame after every keystroke; never append to scrollback. The whole frame fits on one screen. The interesting moment is the user saying "wait, that shouldn't have been possible" — that is a bug in the *idea*, which is the entire point. Add actions on request; sketches evolve. - -**UI branch.** Generate **several radically different variations side by side, switchable** — not one polished take. Default to 3, cap at 5. They must disagree about structure: different layout, different information hierarchy, different primary affordance. Three tweaked card grids is wallpaper, not a sketch. If two drafts come out similar, redo one with an explicit constraint against the shape they share. Switch by a URL search param plus a small floating bar (previous / current variant name / next), following whatever routing convention the project already uses — but with the files under `sketch-NN/`. Wire variants to stubbed data, never to real mutations; the question is what it should look like, not whether the backend works. The most valuable feedback is usually "I want the header from B with the list from C" — that hybrid IS the answer, and it goes in the `## Answer`. - -#### After a runnable sketch - -Record the verdict and the question it settled in `## Answer`. Record the sketch path, the run command, and what the user actually said while driving it in `## Evidence`. Leave the directory in place — it is gitignored scratch, it costs nothing, and the next session may want to re-run it. Never copy any of it into the project. - ---- - -## `legwork · HITL` or `legwork · AFK` - -The one type that DOES rather than decides. There is nothing here to research, sketch, or grill — a decision is simply blocked until some manual work happens. - -Typical: provisioning access to a system, signing up for a service so its API can actually be judged, moving a data sample somewhere it can be looked at, requesting a sandbox tenant, reading the codebase (`questions/00-codebase-context.md` is always this type). - -**It earns its place only by unblocking a decision, never by delivering the destination.** - -### AFK or HITL - -| Mode | When | How it resolves | -|---|---|---| -| `legwork · AFK` | The agent can do it with the tools it has — read the code, run a query, count rows, inspect a config | Do it, record the facts, resolve | -| `legwork · HITL` | It needs a human's hands, credentials, card, or signature | Hand over a precise numbered checklist and WAIT | - -Drive it alone wherever you can. Do not hand a human a checklist for work you could have done yourself. - -### The HITL checklist - -Numbered, specific, and verifiable — every line names the exact place to click, the exact value to use, and what the human should see when it worked. Plain English throughout: exact names and values where they carry the work, no Pathfinder vocabulary anywhere (see *Say it in plain English* in the grilling playbook). No `- [ ]` checkboxes; question files never carry them. - -```markdown -1. Go to https://console.vendor.example/settings/api and sign in with the - shared ops account (credentials in 1Password, item "Vendor Ops"). -2. Create an API key named `pathfinder-eval-2026-08`. Scope it to - read-only — untick "Write" and "Admin". -3. Copy the key into 1Password as a NEW item named "Vendor Eval Key". - Do not paste it into this chat or into any file under specs/. -4. On the same page, note the "Rate limit" value shown for the key - and tell me the number. -5. Under Settings > Data, note whether "Historical backfill" is listed - as included or as a paid add-on, and tell me which. - -Tell me when 1-5 are done, plus the two values from steps 4 and 5. -``` - -Immediately after the checklist, invoke the structured question tool: `Done` · `Blocked` · `Need help` · `Defer`; the question text names every value the human must include, and `Other` carries those values/details. Then stop and wait. Do not guess, proceed, or mark it resolved on the assumption it went fine. - -Handing over a checklist is a **Form B turn** in `trail.md` — close with `WAITING ON YOU` naming the checklist and the values you asked for, and no resume command. The human may be gone for hours, but the session is still theirs to come back to; only park it as a session end (Form A) once you are actually stopping. - -### What its `## Answer` records - -Two parts: **what was done**, and **the resulting facts later questions depend on**. Credentials locations (never the credentials), new URLs, row counts, version numbers, quota limits, table shapes, file paths. - -```markdown -## Answer - -**Done.** Read-only API key provisioned against the shared ops account and -stored in 1Password as "Vendor Eval Key". No key material is stored under specs/. - -**Facts other questions depend on** - -- Key location: 1Password item "Vendor Eval Key" (ops vault). -- Rate limit: 600 requests/minute per key, burst 1000. -- Historical backfill beyond 90 days is a paid add-on, not included in the - eval tier — so any evaluation against real 2024 traffic needs a purchase. -- Base URL for the eval tenant: https://eval-3f2.vendor.example/api/v2 - (differs from the production host in their docs). - -**Consequences** — the 90-day eval ceiling means the volume question cannot be -answered against real historical data on this tier; it has to be extrapolated -or the add-on has to be bought. That is a fresh decision, not one to make here. - -**Gist:** Read-only eval key in 1Password; 600 rpm; history capped at 90 days -without a paid add-on. -``` - -### The guard - -If the legwork turns out to BE the deliverable rather than an unblocker — you are migrating the data, not sampling it; you are building the integration, not evaluating it — **it is out of scope for pathfinder.** Stop. Say so plainly: - -> "This has stopped being legwork that unblocks a decision and become the work itself. Pathfinder plans; it doesn't build. I'm ruling this out of scope and it belongs in planning." - -Rule the question out with `rule-out --reason ""` (it marks the row `[-]` and adds the `## Out of scope` line), and hand off to `/plan2code-1-plan` for that piece. Never let pathfinder quietly become the implementation. - ---- - -## `grill · HITL` - -The default type: a decision only the human can make. Route to **the grilling playbook** — it owns the interrogation technique, structured-question-tool-first delivery, batching rules (up to three independent probes per turn), prose fallback when the tool is unavailable, and the recommend-then-ask pattern. - -Three things this playbook adds on top: - -- **Zoom before you grill.** Work Step 5 already had you read the claimed question plus anything it references. Bring the resolved neighbors' gists into the first message so the human is not re-litigating settled ground. -- **Batch probes, not question files.** One question file at a time is unchanged. A batch of three probes resolves ONE `questions/NN-*.md`; the next file starts only after this one's menu turn (§Cadence). -- **The human's own words.** A `grill` resolves only through live exchange. Never write the `## Answer` from what you inferred they would probably say — and a probe they skipped twice is unanswered, not decided. - -A good grill `## Answer` contains four things: - -1. **The decision** — stated flatly, in the human's terms, not hedged. -2. **What was rejected and why** — the alternatives that were live during the conversation, each with the reason it lost. This is the part that stops the decision from being reopened in three weeks. -3. **The consequences for other questions** — which open questions this constrains, which fog patches it just made sharp, which resolved answers it complicates. Name them; never number them in prose. -4. **A one-line bold Gist.** - ---- - -## Writing the `## Answer` - -Same anatomy for every type. Append it at Work Step 7; never edit `## Question` to match the answer. Then run `node "/pathfinder.mjs" resolve specs//pathfinder `: it sets `State: resolved` **and** `Resolved:` to today (from the clock; the date is what lets a brief report "decided on "), and writes the map row from your `**Gist:**`. It refuses an Answer with no Gist line. - -| Part | Required | Content | -|---|---|---| -| The decision (or, for `research`, the facts found) | Always | What was settled, stated flatly | -| Rejected alternatives, with reasons | When alternatives existed | Each option that lost, and why | -| Consequences | Always | Effects on other questions, named not numbered | -| `**Gist:**` | Always | One line, last | -| `## Evidence` | When there is any | Sources, sketch paths, transcript quotes, commands run | - -Worked example — `questions/03-export-format.md`: - -```markdown -## Answer - -**Decision.** Exports are written as one `.eml` file per message inside a ZIP, -with a top-level `manifest.csv` giving message id, channel, participants, -timestamp, SHA-256, and relative path. One ZIP per 2 GB, numbered `part-001`. - -**Rejected** - -- **Single NDJSON file.** Compact and trivially streamable, but the review - vendors named in Codebase context both ingest `.eml` natively and neither - parses NDJSON. Rejected because it moves the conversion cost onto the - customer's e-discovery team. -- **PST.** What the legal team asked for by name, but PST is a single-writer - format with a practical 50 GB ceiling and no first-party writer outside - Outlook. Rejected on the ceiling alone — the 2025 trading-desk export is - ~12 GB and growing 40% year over year, so the ceiling is 3 years out. -- **One ZIP, no parts.** Rejected because S3 presigned downloads over 5 GB - fail on several corporate proxies the support team has already seen. - -**Consequences** - -- Makes [Export job API](./questions/09-export-job-api.md) sharper: the - response must return an ARRAY of download URLs, not one. -- Constrains [Integrity attestation](./questions/12-integrity-attestation.md) — - a per-message SHA-256 already exists in the manifest, so attestation can hang - off the manifest rather than needing a separate hash pass. -- Kills the "streaming export" fog bullet: parts and streaming are exclusive. - Removed from `## Not yet specified`. - -**Gist:** One `.eml` per message in 2 GB ZIP parts, with a manifest.csv -carrying per-message SHA-256. -``` - -### The gist - -The gist is what gets copied into the map row. It is not a summary of the answer — it is the one line that lets a future session decide, at a glance, whether to open the file. - -- One line. Fits in a table row without wrapping twice. -- Says what was DECIDED, not what was discussed. "Chose ZIP parts" is weak; "One `.eml` per message in 2 GB ZIP parts" is judgeable. -- Carries the number or name that matters, if there is one. -- Never the full answer. If it needs a semicolon and a subordinate clause, cut it. - -The map row it produces — gist, then the `Resolved:` date in italics: - -```markdown -- [x] [Export format](./questions/03-export-format.md) — one `.eml` per message in 2 GB ZIP parts, manifest.csv carries SHA-256 *(2026-08-03)* -``` - ---- - -## Graduating the fog (Work Step 8) - -`## Not yet specified` is the fog: in-scope questions you can *see* coming but could not phrase sharply when you wrote the map. Resolving a question clears the fog immediately ahead of it. Step 8 is where you collect what just became visible. - -**The test is whether you can state the question precisely NOW — not whether you can answer it.** A question you cannot act on for weeks still gets a file, with `Blocked by:` filled in. A question you could answer this minute but cannot phrase without hand-waving stays fog. - -### Procedure - -1. **Re-read `## Not yet specified` in full.** Every bullet, every session, after every resolution. Not the ones you remember — you are assuming no memory of prior sessions, and the bullet that graduates is usually the one you forgot was there. -2. **Ask of each bullet: did the answer just make this sharp?** Can you now write a `## Question` paragraph a stranger could act on, without "we'll need to figure out" anywhere in it? -3. **If yes, write the question file NOW** — in this same session, before Work Step 9. Its `NN` is `frontier`'s `nextNN` (max existing + 1, from the directory, never reused). Fill all six schema lines, with `Blocked by:` wired in the same pass. `reconcile` then adds its `[ ]` or `[!]` row to `## Question Checklist`. -4. **DELETE the bullet from `## Not yet specified`.** Immediately, in the same edit as writing the file. -5. **If no, leave the bullet alone** — untouched, not reworded into something that merely sounds sharper. -6. **Re-check the counts.** One fog patch may graduate into three questions, or into none. Both are normal. A patch that graduates into three was written at the right coarseness; a patch that graduates into exactly one every time was probably a question all along. - -### The bullet you left behind - -**A fog bullet still sitting in `## Not yet specified` after its question file exists is the single most common drift in this skill.** It is quiet — nothing errors, the map still renders — and it is corrosive: - -- The Clearing Gate requires `## Not yet specified` to be EMPTY. A stale bullet blocks the gate forever, so the map never clears even when every question is resolved. -- A later session reads the bullet, does not recognize the question file as the same thing under a different phrasing, and writes a duplicate. Now two files hold half a decision each. -- It violates the rule that detail lives in exactly one place. - -Detection is cheap: after writing any graduated question file, re-read `## Not yet specified` top to bottom and confirm the bullet is gone. If a bullet reads like a question you have already written a file for, delete the bullet — the file always wins. - -### Ruling a question out of scope mid-work - -The destination fixes the scope. When a resolution reveals that a question — the one you just claimed, or another on the map — sits past the destination: - -1. Decide the one-line reason. Do NOT write a `## Answer`; there is no decision, only a scope boundary. -2. Run `node "/pathfinder.mjs" rule-out specs//pathfinder --reason ""`. It sets `State: out-of-scope`, adds the reason under `## Question`, marks the row `[-]` and adds the linked line to `## Out of scope`. -3. Handle its `stranded` list: questions whose `Blocked by:` names it. A blocker that is `out-of-scope` will never be `resolved`, so the dependent is permanently blocked. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting. - -Out-of-scope work never graduates back. The frontier stops at the destination. It returns only if the destination is redrawn, and then as a fresh effort with a fresh map. - -```markdown -## Out of scope - -- [Slack connector](./questions/08-slack-connector.md) — the destination names - MS Teams only; Slack is a separate effort with its own compliance posture. -``` - -### Re-framing or deleting a question the answer invalidated - -An answer can also break questions that already exist. Three cases: - -| What happened | Do this | -|---|---| -| The question still matters but is asked wrong | **Re-frame.** Rewrite `## Question` in place. Keep `NN`, keep the file, keep the links. Add one line noting which answer forced the re-frame. | -| The question no longer exists — the answer subsumed it | **Delete the file, then run `reconcile`** (it drops the map row). Add one line to the answering question's `## Answer` consequences saying what it absorbed. Do not renumber anything. | -| The question is now two questions | **Re-frame the original to the narrower half; write a new file at max+1 for the other.** Wire `Blocked by:` between them if one gates the other. | - -Never leave a question standing that you know is wrong on the theory that a later session will notice. It will not — it assumes no memory, and a well-formed `## Question` reads as intentional. - -Two hard constraints on all three cases: **`NN` is never reused and never renumbered** — links and `Blocked by:` lines would rot silently. And run `reconcile` straight after any re-frame or deletion, so the index never disagrees with the files (it drops the row of a deleted file and adds one for a new file). \ No newline at end of file diff --git a/skills/plan2code-0-pathfinder/references/trail.md b/skills/plan2code-0-pathfinder/references/trail.md deleted file mode 100644 index 2fe2e13..0000000 --- a/skills/plan2code-0-pathfinder/references/trail.md +++ /dev/null @@ -1,86 +0,0 @@ -# Trail Footer - -> Loaded at the top of the skill. Read once; it applies to EVERY response in both modes. Defines the map visual and the pathed resume command that close each turn. -> -> **Backend note.** The glyphs, the two forms, and the discipline are identical either way. On `**Backend:** github` the inputs come from the sub-issue query rather than the checklist, and Form A's command is the map issue URL — see `github-issues.md`. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes. - -The trail is how a human with no memory of the last session sees, at a glance, how far the map has come and what is left — and copies the exact command to resume without hunting for a path that lives in gitignored `specs/`. It closes every response once a map exists. - -It is **presentation only**, rebuilt fresh from the files every response and never written to disk. The script draws it; you choose its form. - -``` -node "/pathfinder.mjs" trail specs//pathfinder --form A|B|C [--item "" ...] --text -``` - -`--text` prints the footer itself: paste it verbatim as the last thing in the response. Use it for Forms A and B. For Form C leave `--text` off: the JSON carries the same `text` plus the `menu` the question tool needs. Run `reconcile` first in a session (Work Step 2) so the files it reads are settled. - ---- - -## When it renders, and which form - -The **turn type** picks the form, never the map's status. This is the one decision the script cannot make for you. - -| Situation | Footer | -|---|---| -| `map.md` exists and the turn **ends the session** — Session End, a cleared map, a fully blocked frontier, a parked grill | **Form A**: the trail, then the resume command | -| `map.md` exists and the turn **asks the human something** — a probe batch, a sketch put up for reaction, a `legwork · HITL` checklist, the Chart Step 2 destination grill, the Chart Step 4 frontier grill | **Form B**: the trail, then the waiting notice. Never a resume command | -| `map.md` exists and the turn **offers the menu after a recorded decision** — the continue-or-stop fork of the Work cadence | **Form C**: the trail, the `OR START FRESH` command, then the question tool | -| Intent Gate (Step 0), the no-fog off-ramp, or any route-and-stop before Step 5 | **None** — no map on disk yet, and no path to resume | - -One idea per session, so there is only ever one trail. - -### What the script draws (so you can read it, not build it) - -``` -🧭 audit-log-export · Working · 2/6 cleared - START ●━●━◉··○··○··⊘··⊝ ····⚑ - ● done · ◉ here · ○ open · ⊘ blocked · ⊝ out of scope · ⚑ destination · ~4 fog - 1 Codebase context ✔ · 2 Export format ✔ · 3 Row-count ceiling ◀ here · 4 Export authorization - 5 Testing posture · 6 Delivery channel (blocked:3) · 7 SIEM push (out of scope) - Confidence: solid, but Risk is borderline. - -WAITING ON YOU · answer here, in this conversation: -Q2 Ceiling behaviour past the cap (re-ask) · Q3 Who sees the truncation warning -``` - -- The heading counts resolved questions over every question except out-of-scope ones. -- One glyph per question in `NN` order: `●` resolved, `◉` claimed, `○` open, `⊘` blocked, `⊝` out of scope. A solid `━` leads into a walked stop (`●`, `◉`); `··` leads into one still ahead. `····⚑` stands for the fog; with no fog the path ends `━⚑` once every stop is walked (or ruled out) and `··⚑` while any is still ahead. A cleared map ends `━⚑ arrived` and drops both legend lines. -- The named legend numbers stops by position, and `(blocked:3)` points at stop 3. -- The confidence line is the map's four internal scores reduced to plain English: `solid` (all ≥ 20), `solid, but is borderline` (all ≥ 18, some at 18-19), `not yet — still need work` (any < 18). The raw numbers never reach the human. No `**Confidence:**` line on the map, no confidence line in the trail. - ---- - -## Form A — the turn ends the session - -The command follows the map's status: `/plan2code-0-pathfinder specs//pathfinder --web` while `Charting` / `Working`; `/plan2code-1-plan --web` once `Cleared`; and `/plan2code-init` first when `## Ground rules` records `AGENTS.md` absent and it still is. The path is the exact argument Auto-Discovery resolves an idea from, so the human pastes it back with zero edits. - -## Form B — the turn asks the human something - -Pass every outstanding item as `--item`, at its stable number (`--item "Q1 Duration model"`), so a partial reply is cheap and a dropped probe is visible to both of you. The script refuses more than three: the three-probe cap. - -**Emit no resume command on a Form B turn.** There is nothing to resume — the session is alive and holding a claim. A resume command here reads as *we're done*, and the human either walks away mid-decision or burns the next turn asking what you meant. This is the single most common way the footer misfires, and it costs the batch the round trips batching was introduced to save. - -One exception: `grilling.md`'s unreachable-human procedure. Parking a mid-grill question and stopping IS a session end — use Form A, and say in the body that the question is parked mid-grill with its batch outstanding. - -## Form C — the menu after a recorded decision - -Used ONLY on the Work cadence's fork-menu turn (resolve.md §Cadence), immediately after `resolve` recorded an `## Answer`. The script refuses it while a question is claimed or once the map is `Cleared`. Pass `--resolved-this-session `, and `--heavy` when the decision just recorded was heavy, contested, or `Locked: yes`. - -It prints the stop branch, labeled `OR START FRESH · new conversation, paste:`, and returns `menu`: the header, the question text, up to three takeable questions plus `Start fresh`, and which option to mark `RECOMMENDED` (a question early in the session; `Start fresh` after ~3 resolved or a heavy decision, with the reason in the question text, "to keep me sharp"). - -Then invoke the structured question tool with that menu. Put each question's gist or newly-unblocked note (from `resolve`'s `unblocked`) in its description. The automatic `Other` path lets the human name a frontier question not shown (`menu.more`). - -Rules for Form C: - -- **The command label is mandatory and exact.** It makes the command the stop branch, not a farewell. Never render a bare command on a menu turn. -- **The choice itself always uses the structured tool.** Never print `NEXT UP` as a prose menu when the tool exists. -- **Form C never replaces Form B.** A turn that asks probes, shows a sketch, or hands over a checklist is Form B, no command. Form C fires only between decisions, when nothing is claimed. -- If the human walks away mid-menu, nothing is stranded: no claim is open, and the command to come back is already on screen. - ---- - -## Discipline - -- **Never print a bare resume command on a turn that asks a question.** Before you choose the form, ask whether the response above it ends with something for them to answer: mid-question (probes, sketch, checklist) → Form B, no exceptions but the parked-grill one; between decisions at the fork-menu → Form C. -- **Draw it, never type it.** A hand-built trail drifts from the files; the script reads them every time. If the trail disagrees with the checklist above it, run `reconcile`, but only at session start or while nothing is claimed: `reconcile` resets a claim with no answer to `open`, so mid-question it would drop your own live claim. With a claim open, finish that question instead; `resolve` rebuilds the checklist, and the next trail is drawn from it. On `github` (the script cannot read the tracker), build it by hand from the sub-issue query, following "What the script draws" exactly. -- **One trail.** Never render two ideas' trails, and never invent a stop the map does not list. diff --git a/skills/plan2code-0-pathfinder/references/web-console/building.md b/skills/plan2code-0-pathfinder/references/web-console/building.md deleted file mode 100644 index 7f74c6b..0000000 --- a/skills/plan2code-0-pathfinder/references/web-console/building.md +++ /dev/null @@ -1,498 +0,0 @@ -# Build Sessions on the Web Console - -For `/plan2code-3-implement`, `/plan2code-3-implement-review` and -`/plan2code-quick-task`. Read `console.md` first: everything there still -applies (the wait loop, one post per send, `finish` before `stop`, the house -rules). This file adds what a build needs, because a build is mostly you -working, and the page has to be told so. - -**The console changes where you ask, not what you build.** Every rule of the -workflow stands: the same specs, the same checkbox writes to disk after every -task, the same sign-off wording, the same "no git commands". The files under -`specs/` and the code are the record. The page is a window onto them. - ---- - -## Opening - -Open first, before reading the spec — the page shows a starting screen while -you work out the phase: - -``` -node "" open --workflow implement -``` - -| Workflow you are running | `--workflow` | `--spec` | -| --- | --- | --- | -| `/plan2code-3-implement` | `implement` | `specs/` | -| `/plan2code-3-implement-review` | `implement-review` | `specs/` | -| `/plan2code-quick-task` | `quick-task` | leave it out | - -`--spec` is what the page builds a resume command from if you ever cannot -answer a stop yourself. Pass it to `open` when you already know the spec; -otherwise post `"specDir": "specs/"` and a real `title` (": -Phase 3") in your first update, once the phase is chosen, or with the phase -question as its first item if there is one to ask. `--file` works on `open` -too, but opening bare and posting the task list as your first update gets -them the page while you are still composing. - -**Launched from the dashboard?** Then the session is already open and the -person is watching it — `open --resume --no-open --workflow ` -(plus `--spec` once known) instead of a fresh `open`, exactly as console.md → -Launches says. Everything below is unchanged; the only difference is whose -session it was a minute ago. - -The first payload for a phase you are about to build: - -```jsonc -{ - "headline": { "stage": "Phase 3: API layer", "cleared": 0, "total": 9 }, - "docs": [ - { "id": "phase", "title": "Phase 3 tasks", "version": 1, "blocks": [ - { "id": "tasks", "state": "settled", "md": "- [ ] **Task 3.1:** ...\n- [ ] **Task 3.2:** ..." } - ]}, - { "id": "phasefile", "title": "phase-3.md", "version": 1, "blocks": [ - { "id": "body", "state": "settled", "md": "...the whole phase-3.md file, verbatim..." } - ]} - ], - "agent": { "status": "working", "activity": "Checking the prerequisites", "quietMinutes": 15 } -} -``` - -`headline.cleared` / `total` are tasks done out of tasks in the phase: the -progress bar is the first thing someone watching a build looks at. The session -meter counts the build's tasks from `cleared` as it rises, so keep it current, -and start every phase (a second one in the same run too) at `"cleared": 0`. - -`"version": 1` is for the first phase of a session only. A doc's version -never goes back (console.md → House rules, rule 9), so a later phase in the -same session reposts `phase` and `phasefile` at one more than the version the -page holds, with the new phase's title and content. The same goes for -`report` at sign-off and `review` in a mid-session review: version 1 the -first time, then up from wherever the page has it. - -`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab — -the person can read the prerequisites and task specs while you build. Re-post -it whenever the file changes, which is every task: the checkbox write that -ticks the list above ticks the file too, and the Phase Completion Summary -lands in it at the end. It renders as markdown, so the file's checkboxes show -as ticks exactly as they stand on disk. - ---- - -## While you build - -Post after every task, in the same breath as writing its checkbox to disk. -Write the patch file into the session's own folder (the `session` path `open` -printed), never into the project or into `~/.plan2code/console/` directly: - -```jsonc -{ - "headline": { "cleared": 4 }, - "docs": [ - { "id": "phase", "version": 5, "blocks": [ { "id": "tasks", "state": "settled", "md": "...the whole list, 4 ticked..." } ] }, - { "id": "phasefile", "version": 5, "blocks": [ { "id": "body", "state": "settled", "md": "...phase-3.md as it now stands on disk..." } ] } - ], - "agent": { "activity": "Task 5 of 9: the rate limiter" } -} -``` - -- **`activity`** is one plain sentence saying what you are doing now. The page - shows it beside Planny and in place of "questions coming". No internal - vocabulary, no loop completion markers. Number tasks by their position in - the phase, of the phase's task count (`Task 5 of 9`), not by the file's - `5.5`-style labels: the phase is already in the headline. The page rewrites - the old form as a safety net. -- **`quietMinutes`** is how long you might go without posting (1 to 60). The - page calls a working agent stuck after two minutes of silence unless you say - otherwise, and a build task can honestly take twenty. Set it to the longest - gap you expect, usually 10 to 30. Every post is also a heartbeat. **Clear it - (`"quietMinutes": null`) whenever you go back to waiting**: it only counts - while you are `working`, but leaving it set invites a stale value later. -- `blocks` inside a doc are replaced whole, so post the whole task list each - time. It is small. The same goes for `phasefile`: re-read `phase-X.md` and - post it fresh, because the checkbox write just changed it. -- If the task list grows mid-build, raise `headline.total` in the same post; - the page never shows more done than the total, but the bar reads truer when - you keep it current. -- Do not call `wait` while building. There is nothing to collect, and the page - holds anything the person sends until you next look. - -A build may receive a `Subagents:` standing instruction, on `open` output or a -`chat` check between tasks. Follow console.md → Standing instructions for -handing independent tasks to helpers and reporting them as `helpers`. Keep the -per-task progress posts, the checkbox writes, the chat checks and the sign-off -with you. - -### Quick questions between tasks - -The person can ask a Quick question on the Ask tab at any point in a build -(console.md → Quick questions). After each task's progress post, check for -one before starting the next task: - -``` -node "" chat --session -``` - -| Exit | What you do | -| --- | --- | -| `0` | Answer everything waiting, under console.md → Quick questions, in one post, then start the next task. A `workspace` list in the output is a change to the session's folders (console.md → Workspace): take it into account from the next task on; it needs no reply. | -| `10` | Nothing waiting. Carry on. | -| `20` | The server is gone: `open --resume ` as usual, then carry on. | - -This is an instant check, not a wait: it never sleeps and never touches card -sends. It does not replace `wait` at a gate, and no build calls `wait` -mid-build for cards. An approved chat edit is made here, between tasks, never -in the middle of one. - -A blocker (`[!]`), a `SPEC NOTE` and a verified or assumed prerequisite are -not questions. Put them in the phase doc as they happen, and in the report. - -### When the workflow asks something - -Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }` in -the SAME post, and go into the wait loop. When the answer lands, set `working` -again and carry on. - -A question stops the build. Never leave yourself `working` with a question -open, and never "carry on while you decide": the page reads `working` as "not -your turn", and the person is left looking at a question they cannot answer. -If there is other work the answer does not touch, finish it before you ask, -then ask and wait. - -| Moment | `kind` | Notes | -| --- | --- | --- | -| Several phases can be picked | `choice` | One option per phase, `detail` = status and task count, `token` = the phase number. Put the "run another agent on a different phase" tip in `body`. | -| A phase is already in progress | `confirm` | "Resume Phase 3?" `yes` / `no`. | -| `SPEC CONFLICT` | `choice` or `text` | The conflict in `body`, the readings as options where there are clear ones. Never guess on architecture. | -| Test failures | `choice` | `1` Fix now, `2` Document and proceed, `3` Investigate first. | -| A small phase, continue with the next? | `confirm` | | -| A spec gap only they can close | `text` | | -| Something learned for AGENTS.md | `confirm` | The proposed lines in `consequences`. | - -Titles stay plain: "Which phase next", "Tests are failing", "Keep going?". - ---- - -## Sign-off - -Put the Completion Report on the page as a doc, then ask for approval as a -`review` item pointing at it. The review offer rides on this card, as a verdict -ahead of the approval buttons — not on the finish after it, where it could -only ever be offered once nothing could come of it: - -```jsonc -{ - "docs": [{ "id": "report", "title": "Completion report", "version": 1, "blocks": [ - { "id": "summary", "state": "settled", "md": "## Summary\n\n..." }, - { "id": "files", "state": "settled", "md": "## Files\n\n..." }, - { "id": "verify", "state": "settled", "md": "## How to check it\n\n..." } - ]}], - "items": [{ - "id": "signoff", "kind": "review", "title": "Approve this phase", "doc": "report", - "body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, or say what to change.", - "verdicts": [ - { "id": "review", "label": "Review the code first" }, - { "id": "approve", "label": "Approve this phase" }, - { "id": "changes", "label": "I want changes" } - ], - "token": { "review": "review", "approve": "approved", "changes": "needs changes" }, - "nothingYet": "Nothing is marked complete until you approve.", - "gate": { "id": "signoff", "authoritative": true }, - "fallbackText": "Reply \"approved\" to mark this phase complete, \"review\" to run the code review first, or describe any issues." - }], - "agent": { "status": "waiting", "quietMinutes": null } -} -``` - -`reply` carries `Approve this phase: approved`, which is the terminal's -`approved`. If the note that came with an approval asks for a change, treat it -as "describe any issues": do the change first and ask again. `changes` means -exactly what it says: address it, bump the report's version (a later phase's -report starts above the last one's, too), and reopen the -item (`"status": "reopened"`) with a reply in its `thread`. `review` is the -person asking for the code review before they approve anything — see "The -review, mid-session" below. - -`gate` marks the one approval that counts. The server refuses a second open -authoritative gate, which is what keeps a composed workflow from asking for -sign-off twice. - ---- - -## After approval: the finish - -Do everything the workflow does on approval (the checkboxes, the summary, the -upcoming phases, the commit command) and print it in the terminal as usual. -Then post the finish, wait for the dashboard button as console.md → Finishing -says, and `stop`: - -```jsonc -{ - "items": [{ "id": "signoff", "status": "answered", "answer": { "verdict": "approve" } }], - "run": { "event": "implement-phase", "id": "phase-3", "tasks": 9 }, - "finish": { - "headline": "Phase 3 is done", - "body": "9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -A && git commit -m \"...\" -m \"AI Assisted\"\n```", - "command": "/plan2code-3-implement specs/lunch-vote/overview.md", - "doc": "report", - "dashboard": true - }, - "agent": { "status": "waiting" } -} -``` - -`finish.command` is the next pipeline step, the same one the terminal names: -the next `/plan2code-3-implement`, or `/plan2code-4-finalize` after the last -phase. An `implement` finish never carries `review`: the offer was on the -sign-off card, and approving past it was the answer. `implement-review` ends -the same way; that phase was reviewed already. Only a finished `quick-task` -still offers the review on its finish — see below. - -`run` gives the approved phase its final score on the session meter (console.md → -Posting an update → Session meter), in the same post that records the approval; -it takes over what the build already counted from `cleared`, never adds to it: -`implement-phase` for Implement, `implement-review-phase` for Implement + -Review, id `phase-N`, and `tasks`: how many of the phase's tasks were -completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a -twelve-task phase weighs four times a three-task one; leave `tasks` out and -every phase weighs the same. Quick task and a standalone Review are counted when -their session opens, so they post no `run` for that; a review run on the page -after a build reports its own (below). - ---- - -## The review, mid-session - -The same focused review runs from either of two doors: - -- **`implement`:** the `review` verdict on the sign-off card, before anything - is approved. A note sent with it is theirs — read it as focus for the - review. Settle the card with it in the same post that goes back to work: - - ```jsonc - { - "items": [{ "id": "signoff", "status": "answered", "answer": { "verdict": "review" } }], - "headline": { "stage": "Reviewing Phase 3", "cleared": 0, "total": 0 }, - "run": { "event": "review", "id": "review" }, - "agent": { "status": "working", "activity": "Reviewing the 7 files this phase changed", "quietMinutes": 15 } - } - ``` - -- **`quick-task`:** the **Review it now** button on the finished screen, which - `finish.review` puts there. It arrives through the wait loop as an action - `{ "i": "__review", "type": "review" }`, like any send. Take it up with the - same post minus the `items` line, plus `"finish": null` — that takes the - session off its ending and back to work. - -Either way, the post that takes the review up carries `"run": { "event": -"review", "id": "review" }`: the review runs inside this skill's session, so no -launch scores it on the session meter. Never resume the session under -`--workflow review` for it as well, or it counts twice. - -A finish carrying `review` keeps the session alive for the answer, so a -`quick-task` that just posted one keeps waiting, for up to about ten minutes. -A quick-task finish carries both `review` and `"dashboard": true` and waits -for whichever comes first: - -| What arrives | What you do | -| --- | --- | -| An action `{ "i": "__review", "type": "review" }` | Take the review up (below). | -| An action `{ "i": "__dashboard", "type": "dashboard" }` | Take the session back as the dashboard (console.md → Finishing). | -| An action `{ "i": "__done", "type": "done" }` | `stop` the server. The session is over. | -| `wait` exit `20` | The server is gone, not necessarily the tab. Resume it (`open --resume --no-open --workflow `) and keep waiting. | -| Nothing after about ten minutes | `stop` the server. The page then shows the terminal command for a review instead of a button that would go nowhere. | - -**Read references/review.md** and run Review Mode with these overrides: - -- **Scope is Focused, and already decided:** the exact change set of this - session (files created or modified by the phase or the quick task, plus the - tests and docs changed for it). Do not ask about scope. Use overview.md and - the phase file for spec compliance; they do not widen the scope. -- **No commit instructions and no next-conversation routing** mid-review. The - way back out carries both. -- The page takes the whole report, so the "top 10 of 15+" rule does not apply, - and tables go in the doc. - -### The findings - -The full Review Mode report as a doc, and the fix choice as one `multi` item: - -```jsonc -{ - "docs": [{ "id": "review", "title": "Review findings", "version": 1, "blocks": [ - { "id": "report", "state": "settled", "md": "## Overview\n\n...\n\n## Findings\n\n| # | Severity | Issue | File |\n..." } - ]}], - "items": [{ - "id": "fixes", "kind": "multi", "title": "Which to fix", "required": false, "doc": "review", - "body": "Tick what should be fixed now. Anything left unticked is written up as still open. Nothing changes until you send.", - "options": [ - { "k": "1", "text": "Critical: token is logged in plain text", "detail": "src/auth.ts:42. Fix: redact before logging." }, - { "k": "2", "text": "Warning: missing null check on the user lookup", "detail": "src/users.ts:88. Fix: ..." }, - { "k": "3", "text": "Suggestion: repeated query could be batched", "detail": "src/report.ts:17. Fix: ..." } - ], - "presets": [ - { "label": "Critical and warnings", "ks": ["1", "2"] }, - { "label": "All of them", "ks": ["1", "2", "3"] } - ], - "token": { "1": "1", "2": "2", "3": "3" }, - "fallbackText": "Reply H to fix Critical + Warning findings, A to fix all findings, or S 1,3,5 to fix specific findings." - }], - "agent": { "status": "waiting", "quietMinutes": null } -} -``` - -`"doc": "review"` puts a **Read "Review findings" in full** button on the -card, so the report is one click from the list rather than behind a tab -nobody notices. Always carry it. - -Read the reply as Review Mode's fix choice: `Which to fix: 1, 2` is `S 1,2`, -every finding ticked is `A`, and `skip` (or nothing ticked) is "fix none, -keep them as unresolved". Leave out `presets` a set would not change (no -warnings, one finding). With **zero findings** there is no item: say so in the -doc and go straight to the way back out. - -### Fixing - -Settle the `fixes` item in the same post that goes back to work — -`"status": "answered"` with the `answer` they sent (`{ "ks": ["1", "2"] }`, -or `{ "ks": [] }` when nothing was ticked). The server records their send on -the item, but only you decide it is settled; left open it stays on the page -as an outstanding question, beside the card you ask next. Then follow Review -Mode's Post-Fix Flow, posting `activity` per fix ("Fix 2 of 3: the null -check") and `quietMinutes` as in a build. - -### The way back out - -**`implement` — back to the sign-off.** The review was the preamble to an -approval that has not happened yet, so this is where it lands. Fold the review -results and any still-open findings into the report doc and bump it, then -reopen the sign-off **without the review verdict** — re-offering a review that -just ran reads as though nothing happened: - -```jsonc -{ - "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": "approve", "label": "Approve this phase" }, - { "id": "changes", "label": "I want changes" } - ], - "thread": [{ "who": "agent", "text": "Review done: 2 of 3 findings fixed; the rest is written up in the findings tab." }] - }], - "agent": { "status": "waiting", "quietMinutes": null } -} -``` - -Review Mode's own closing gate ("Reply approved to commit") is this card: -approving the phase now covers the fixes too, so there is no separate "Check -the fixes" step. On approval, continue at "After approval: the finish". - -**`quick-task` — the closing gate, then the finish.** Review Mode's closing -gate ("Reply approved to commit, or request changes") becomes a `review` item -titled "Check the fixes", `doc: "review"`, verdicts `approve` ("The fixes look -right") and `changes`, token `approved` / `needs changes`. When it clears, -settle it in the same post as the new finish — `"status": "answered"` plus -`"answer": { "verdict": "approve" }` (or `"changes"`) — post the finish -**without** `review`, then `stop`. An item left open survives on the page as -a question still owed, above the ending itself: - -- `headline`: "The review is done" -- `body`: findings by severity, what was fixed, what is still open, and the - commit command for the fixes, in the project's commit format. -- `command`: the same next step as the finish before it. -- `doc`: `"review"`. - ---- - -## Implement + Review (`implement-review`) - -The same build, then Stage 2 publishes the findings exactly as above (the -`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes" -item: Stage 4 is the only gate. The post that starts Stage 2's review carries -`"run": { "event": "review", "id": "review" }`, as above: in this workflow it -scores the review stage's 1 point on the meter as it begins, and the phase's -final `run` leaves that point out. Stage 4 is the sign-off above **without the -review verdict** — the phase was already reviewed — with the review results -and unresolved findings in the report doc, header "Reviewed and ready for -sign-off" in the item's `body`. The finish never carries `review`, and its -post carries `"run": { "event": "implement-review-phase", "id": "phase-N", "tasks": N }` -with the count of completed tasks. - ---- - -## Quick task (`quick-task`) - -- Open with the first clarifying question. Clarifying questions go out as - `text` or `choice`, at most three at a time. -- Post `"stopWarning": "A quick task saves nothing until it is built, so stopping now loses what we have worked out."` - at the start, and `"stopWarning": ""` once the build is under way. -- **Scope check:** a `choice`, "Too big for a quick task?", options - `1` Continue (lightweight format) and `2` Escalate to a full plan, with the - measured counts against the thresholds in `body`. -- **Feature name** (escalating): `text` with - `"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"` and a kebab-case placeholder. -- **The plan:** a `plan` doc (Summary, Files to change, Steps, Verify) and a - `review` item "Build this plan?" with verdicts `yes` ("Build it"), `modify` - ("Change the plan"), `escalate` ("Plan it properly instead") and `abort` - ("Stop here", `"danger": true`), token equal to the ids. -- **Building** after `yes`: settle the verdict (`"status": "answered"` plus - `"answer": { "verdict": "yes" }`) in the post that starts the build, and - open a **Build progress** tab in that same post, the way an Implement phase - gets its tasks tab. The plan's steps are the task list and `total` is their - number: - - ```jsonc - { - "stopWarning": "", - "items": [{ "id": "", "status": "answered", "answer": { "verdict": "yes" } }], - "headline": { "stage": "Building", "cleared": 0, "total": 4 }, - "docs": [{ "id": "tasks", "title": "Build progress", "version": 1, "blocks": [ - { "id": "tasks", "state": "settled", "md": "- [ ] Step one\n- [ ] Step two\n- [ ] Step three\n- [ ] Step four" } - ]}], - "agent": { "status": "working", "activity": "Step 1 of 4: step one", "quietMinutes": 10 } - } - ``` - - Then post after every step, exactly as "While you build": bump the doc's - `version` and repost the whole list with that step ticked, raise - `headline.cleared`, and set `agent.activity` to the next step ("Step 2 of 4: - step two"). Never go silent for the whole build: a quick task with many steps - is the case this tab is for. Check for a Quick question between steps, and do - not call `wait` until the build is done. -- **The finish after the build:** `command` is the commit command, filled in, - in the project's commit format (AGENTS.md), with - `"where": "When you are happy with it, commit it from your terminal:"`, and - `review` on offer — the **Review it now** button, since a quick task has no - sign-off card to put it on — and `"dashboard": true`, so the finished screen - also offers **Back to the dashboard**. Both are required: a finish without - `dashboard` leaves the person on a dead end. Keep waiting for whichever - button is pressed, and everything after that is "The review, mid-session" - above. -- **Escalated / aborted:** settle the verdict the same way in the finish post — - finish with `"command": "/plan2code-1-plan"` and the - PLAN-DRAFT's path in `body`, no review; or `"command": "/plan2code-quick-task"`. - Both set `"dashboard": true`: an abort of a quick task saves nothing to - resume, so it is not a pause. - ---- - -## Stop requests during a build - -The Stop button only works on the person's turn, so it never lands mid-task. -When `__stop` arrives: - -- **implement / implement-review:** Implementation Mode's abort, without the - "are you sure" (the page asked): the phase stays `[/]`, list completed and - remaining tasks, post `finish` with the resume command - (`/plan2code-3-implement specs//overview.md`), then `stop`. An - implement abort is a pause: a headline starting "Paused", no `dashboard`, - `stop` at once. -- **quick-task:** say in `finish.body` what was worked out, and that nothing was - saved unless it was built; `"command": "/plan2code-quick-task"`. - -A mid-build `__dashboard` (the top bar's triangle, console.md → Stop requests → -"Back to the dashboard, mid-workflow") lands the same way, only on the person's -turn. Save exactly as for `__stop` above (an implement phase stays `[/]`), but -post no finish and do not `stop`: resume as the dashboard instead, with one -terminal line naming what was saved and the resume command. diff --git a/skills/plan2code-0-pathfinder/references/web-console/console.md b/skills/plan2code-0-pathfinder/references/web-console/console.md deleted file mode 100644 index 99c3b67..0000000 --- a/skills/plan2code-0-pathfinder/references/web-console/console.md +++ /dev/null @@ -1,1412 +0,0 @@ -# The Web Console - -A local page in the person's browser where they answer your questions, read what -you have drafted, and approve things, instead of typing into the terminal. - -> **Not open yet? Open it now, then read on.** Once the person has picked the -> browser (or passed `--web`, or launched this from the dashboard's menu — then -> resume instead, see Launches), `node "" open --workflow ` is -> your very next command: before this file, before the project, before any -> thinking about the first question. It returns in well under a second, the -> browser is already on its way while it runs, and the page shows a starting -> screen that names the skill until your first `post` replaces it. Every second -> spent reading first is a second the person stares at a terminal. - -**``** below means the directory holding this skill's `SKILL.md`, and -`` means `/references/web-console/console.mjs`. If you do not -know where the skill was loaded from: a global install puts every Plan2Code -skill under `~/.agents/skills//` (this file sits at -`~/.agents/skills//references/web-console/console.md`), and an -earlier session may have left this console's directory in -`~/.plan2code/console/console-dir`. `node "" help` prints a summary -of this file. Always quote the path: install paths contain spaces. -Requires Node 18+. Nothing to install, no dependencies, no build step. - -**The console changes where you ask, not what you ask.** Every rule of this -workflow still applies: the same questions, the same order, the same gates, the -same cap of three questions at a time, the same recap before anything is recorded. -You are not allowed to answer your own questions just because a form makes it easy. - -> **The one rule that keeps the page alive: while the session is open, every -> turn ends on a `wait` call, never on text.** `wait` exit `10` means "nobody -> has answered yet", not "done": relay one line and run `wait` again in the -> same turn, as many times as it takes. A turn that ends without a `wait` -> running strands the person's next click. Details: The wait loop, below. - ---- - -## Deciding whether to use it - -### First, whether it can work here - -Nothing below is specific to one agent or one harness: it is `node`, a loopback -port, and seven subcommands (`open`, `post`, `wait`, `chat`, `keep`, `status`, -`stop`). But three things have to be true, and two of them -you can check before you offer anything. - -1. **Node 18 or newer is on PATH.** `node --version`. Anything older exits with - a message naming the version it found. -2. **You are running on the person's own machine.** The page is served on - `127.0.0.1`, so their browser can only reach it if that is their machine too. - If you know you are in a cloud VM or a remote sandbox, do not offer it at - all: a link they cannot open is worse than no link. For the cases you cannot - know, `open` checks for you and adds `"remote": ""` and a `note` to - its output when the environment looks like SSH, a dev container, a Codespace - or Gitpod. It still starts, because a forwarded port often works. When you - see that field, give them the link, ask whether it opened, and move to the - terminal if it did not. -3. **You can run a foreground command for a minute at a time** and read its exit - code. See the wait loop. - -If any of those fail, say so in one line and work in the terminal. That path is -fully supported and loses nothing. - -### Then, ask - -Ask once, at the start, through the structured question tool if you have one. -If you have none, ask it as an ordinary numbered question in prose. Either way -it is one question with two answers: - -> **How would you like to work through this?** -> -> - **In your browser** (suggested) — a page opens with the questions laid out, -> what we have agreed so far, and everything saved as you go. Easier to follow, -> and far easier if you are walking through this with someone else. -> - **Here in the terminal** — one question at a time, right where you are. - -If they pick the terminal, ignore the rest of this file. If the console fails to -start for any reason, say so in one line and carry on in the terminal: never let -this block the session. - -Either way, tell them they can switch whenever they like, because they can. The -files under `specs/` are the only source of truth, and neither channel owns them. - ---- - -## Starting it - -1. Run `open` — do it now, even before the first question exists, and before - you have read the project. `--file` is optional, and a session with nothing - on it shows them a starting screen ("Starting Pathfinder", Planny in - flight) until your first `post` lands. `--title` is optional too: it - defaults to the project's folder name, and you can post a real `title` - once you know what the session is about: - ``` - node "" open --workflow pathfinder - ``` - `--workflow` is whichever you are running: `dashboard`, `init`, - `init-update`, `pathfinder`, `quick-task`, `plan`, `revise-plan`, - `document`, `implement`, `implement-review`, `review`, `finalize` or - `handoff`. Get it - right: the page decides from it whether to offer a brief, what stopping - early costs, and which command resumes the session if you cannot say. - `dashboard` is the special one: the page draws the skill menu itself, and - your job is the `menu` payload and the launch hand-off — see the workflow - notes. - It prints one line: `{"ok":true,"sid":"...","session":"...","url":"http://127.0.0.1:PORT/s/TOKEN/","terminalLine":"→ Look at the web console: http://127.0.0.1:PORT/s/TOKEN/"}`. - It also tries to open the browser by itself. When it removed session - folders or scratch files older than 30 days, the line also carries - `swept: { sessions, scratch }` — housekeeping, nothing to relay to the - person. - - To open with questions already on the page instead, write the payload to a - temporary JSON file first — a file, not a heredoc, because heredocs do not - work in PowerShell, which is the default shell on Windows — and pass it as - `--file `. Opening first is the better order: the page is in - front of them while you work out what to ask, instead of after. - - Write temporary payload files into the session's own folder (the `session` - path `open` prints), never into the project or into - `~/.plan2code/console/` directly. The session folder is removed with the - session after 30 idle days, and stray `.json` / `.mjs` files left in the - console folder are swept on the same clock. - - **Building?** For `implement`, `implement-review` and `quick-task`, also read - `building.md` beside this file once the session is open. A build is mostly you - working rather than asking, and that file covers the progress the page - shows, the sign-off and the review offer it carries, and the review button - after a finished quick task. - -2. If you opened without `--file`, post the first batch of questions as soon - as you have them (see Posting an update). If getting there takes a while - (reading the project, finding the spec), post an `agent.activity` line - first so the page says what you are doing. Either way, tell the person, in plain - words, on one line: the link, and how many questions are waiting. Repeat the link in your - message text, not only in a command output, because terminal scrollback - gets lost. While a console session is open, end every terminal message - with the latest `terminalLine` from `open`, `post` or `wait`, verbatim - (`→ Look at the web console: `). - -3. Go into the wait loop below. - -Keep `session` (the session id). Every later command needs `--session `. - ---- - -## The wait loop - -This is the part that matters most. **Never try to block for the whole time a -person takes.** Call `wait` in bounded slices and read the exit code. - -``` -node "" wait --session --seconds 240 -``` - -**Size the slice to your own shell timeout, not to this example.** Use the -longest slice your harness safely allows, with `--seconds` comfortably below -its single-command limit, so the command returns by itself rather than being -killed: - -| Your limit on one command | Use | -| --- | --- | -| 5 minutes or more | `--seconds 240`, with the tool timeout set to 300000 ms | -| about 2 minutes | `--seconds 90` | -| 60 seconds, or you cannot tell | `--seconds 45` | - -Shorter slices only mean more of them. `wait` is a poller that holds nothing: -killing it mid-slice loses nothing, and neither does starting the next one. A -result that has been handed over is marked collected only after it is printed, -so even a kill at the worst possible moment costs you a repeat, never an answer. - -| Exit | Meaning | What you do | -| --- | --- | --- | -| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace) and `subagents` (the helpers switch, see Standing instructions). | Handle the cards (if any), the chat (if any), any `workspace` changes and any `subagents` block, then post once (below, Quick questions, Workspace and Standing instructions). | -| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. | -| `20` | The server is gone. | `open --resume `, give them the new link, then keep waiting. | -| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. | - -Do not poll faster than this. Do not spin on `status`. Exit 10 is not a finished -turn: never emit a final response or stop after an arbitrary number of slices; -relay one line and immediately call `wait` again. Do not give up: people step -away from a session and come back. The same holds after a `finish`: keep -waiting (resuming the server on exit `20`) until the dashboard or done press -or about ten minutes with nothing, because the Ask tab stays live and its -messages only arrive through `wait`. Ending your turn earlier strands them. - -**The turn never ends on a wait.** While a console session is open, including -after a finish that offers a button (Back to the dashboard, Review it now), the -last thing in every turn you take is a `wait` call, never a line of text. The -line you relay after exit `10` goes in the same turn as the next `wait`, so -write it and call `wait` straight after. A turn that ends with the session open -and no `wait` running is a bug the person feels at once: their button press -sits unread until they ask why. If you catch yourself about to write a closing -summary while the page is still open, call `wait` first. - -**Collect promptly.** A question someone has sent is locked on the page for as -long as you are mid-turn on it: they can read, move around and answer the other -open questions, but not that one, because a change made then would reach nobody. -It unlocks the moment your update lands, whether you settled the question or -replied and left it open. Until then a send is also blocked outright, so a slow -turn of yours is a person sitting on their hands. `open` and `status` both -report `pendingResult: true` while one is waiting to be picked up. - -### Handling a send - -The result looks like this: - -```jsonc -{ - "type": "submit", - "actions": [ - { "i": "q2", "type": "answer", "kind": "choice", "k": "A" }, - { "i": "q3", "type": "answer", "kind": "text", "text": "audit-export" }, - { "i": "q3", "type": "comment", "text": "Please keep the header row.", - "images": [{ "path": "/home/sam/.plan2code/console/sessions/20260923-101500-ab12cd/uploads/3f2b9c1e-8a4d-4f6e-9b7a-2c5d1e0f4a6b.jpg", "name": "header.png" }], - "files": [{ "path": "/home/sam/.plan2code/console/sessions/20260923-101500-ab12cd/uploads/7c1d0a4e-5b2f-4e8a-9d3c-1f6e2b8a0c5d.pdf", "name": "api-spec.pdf" }] } - ], - "reply": "File format: a\nWhat to call it: audit-export\nNote on What to call it: Please keep the header row.\n Image: /home/sam/.plan2code/console/sessions/20260923-101500-ab12cd/uploads/3f2b9c1e-8a4d-4f6e-9b7a-2c5d1e0f4a6b.jpg (header.png)\n File: /home/sam/.plan2code/console/sessions/20260923-101500-ab12cd/uploads/7c1d0a4e-5b2f-4e8a-9d3c-1f6e2b8a0c5d.pdf (api-spec.pdf)" -} -``` - -**`reply` is the important field.** It is what the person would have typed in the -terminal, one line per question, built from the `token` map you supplied. Treat it -as their typed answer and follow the normal workflow from there. - -Every part of an answer survives into it, joined by `; ` when there is more than -one: a verdict and the note that came with it, a checklist state and what they -wrote down, a reordered list and its new order. `actions` carries the same thing -with structure, for when you need the detail. - -A `comment` action may carry `images` and `files`, each `[{ path, name }]`: -screenshots in the first, text, code and PDF documents in the second. `reply` -then has one ` Image: ()` or ` File: ()` line per -attachment under the note, in the order they were attached. **Open every path -with your file-read tool before you answer the note** — it is what they are -pointing at. If a file cannot be read (your tool does not read PDF, say), tell -them so in your reply rather than guessing what is in it. The files live in the -session's `uploads/`, outside the project; never copy them into it yourself — see Keeping attachments. - -A send is the person talking to you. Act on it in that turn: do not wait for -terminal input to confirm it, do not ask whether to proceed, do not merely -summarise it back. - -Then, in ONE `post`, do all of: - -- mark each answered item `"status": "answered"` and record its `answer` -- reply to every note in that item's `thread` (shape below) -- answer any Quick questions that came with it, in `chat.replies` (see Quick - questions) -- publish the next batch of questions -- set `"agent": { "status": "waiting" }` - -One post is one atomic update, so the page never shows a half-changed state. - -### Replying to a note - -A `comment` is the person talking to you about that card, often asking -something. It shows in the card's **Notes on this** panel, and so does your -answer: - -```jsonc -{ "items": [{ "id": "p4", "thread": [ - { "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." } -] }] } -``` - -- Every entry is `{ "who": "agent", "text": "" }`. `text`, not - `md`: the page reads nothing else. An entry with no `text` is rejected. -- The server writes their note into the thread as it arrives. Do not repeat - it, and send only your new entries: `thread` appends. -- Answer what they asked, in the thread, even when you also change a doc or - re-ask the question. "I've updated the doc" alone leaves the question in the - panel with no answer under it. - -### Recording the answer - -`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`, -`{ "text": "audit-export" }`, `{ "yes": true }`, `{ "verdict": "changes", "text": "..." }`, -`{ "done": [0,1], "state": "done" }`, `{ "rows": [...] }`. - -A settled question stops being a form and becomes a record: the page states the -answer back in its own words ("A · Continue without it"), marks the option they -picked, and locks everything else. That is the whole point of settling one, so -record the answer every time. - -The server writes what they sent onto the item as `submitted` when Send is -pressed, and the page falls back to it, so a question you forget is not a blank -card. Treat that as the safety net it is, not as a reason to leave `answer` out: -`submitted` is the raw click, while `answer` is what you decided it meant, and -only the second survives you reopening or rewording the question. - ---- - -## Keeping attachments - -Note attachments live in the session's `uploads/`, which is swept after 30 idle days. Before you write any file under `specs//` that links to or cites one (plans, the overview, phase files, Pathfinder question files and the map), keep it first: - -``` -node "" keep --session --upload --name --spec specs/ --from -``` - -`path` and `name` are the attachment's, from the `comment` action. It prints `{ ok, path, link, image, reused }`. Paste `link` as it is: `![name](link)` for an image, `[name](link)` for a document. The same upload always gets the same name (`attachments/-<8-char id>.`), so keeping it again just reuses the copy. Name the kept file in your next update. Leave uncited attachments where they are. Quick-question attachments are never kept. Exit 3 means the path was refused. Say so, and link nothing. - ---- - -## Briefs (Pathfinder only) - -The page shows a **Write a brief** button when `workflow` is `pathfinder`, -because that is the workflow with a brief playbook. The person picks a range and -presses it; nothing else about the session changes. - -It arrives through the wait loop like any other send: - -```jsonc -{ - "type": "submit", - "actions": [{ "i": "__brief", "type": "brief", "range": "since 2026-09-15" }], - "reply": "Write a brief covering everything since 2026-09-15." -} -``` - -`range` is one of `today`, `this week`, `since ` or `full`, which is -the range grammar the brief playbook already parses. `reply` says the same thing -in words, so a workflow that only reads `reply` needs no new code path. The -`__brief` id is not an item and matches nothing; it marks the action as being -about the session rather than about a question. - -Run your normal brief procedure, write the file where it belongs, and then put -the same report on the page as a doc: - -```jsonc -{ - "docs": [{ - "id": "brief", - "title": "Brief", - "version": 2, - "note": "Covers this week", - "blocks": [{ "id": "body", "state": "settled", "md": "# ...the whole brief..." }] - }], - "agent": { "status": "waiting" } -} -``` - -One block holding the whole report is right here: a brief is read start to -finish, not block by block, and it gets Save as HTML, Print and Save buttons -that work on the document as a whole. Save as HTML appears only on the doc with -the id `brief`. Reuse the id `brief` so a second brief replaces the first -rather than growing a row of tabs, and bump `version`. - -Say in chat where the file went, as you always would. The page is a second copy -for reading and printing, never the record. - ---- - -## Stop requests - -The page has a **Stop session** button. Pressing it sends, in one submit, any -answers the person had staged plus one more action: - -```jsonc -{ "type": "submit", - "actions": [ /* staged answers and notes, as usual */, - { "i": "__stop", "type": "stop" } ], - "reply": "...the answer lines...\nStop here and save my place, so I can pick this up later." } -``` - -`__stop` is not an item and matches nothing; like `__brief` (and a build's -`__review` and `__done`, see `building.md`, the dashboard's `__launch`, -below, and `__dashboard`, from a finished screen or mid-workflow, see -Finishing and "Back to the dashboard, mid-workflow" below), it marks the -action as being about the session. It arrives through `wait` with exit `0`, like -any send. It is the person ending the session, so act on it in this turn: - -1. **Handle the answers under the workflow's own rules, and record only what is - final.** A confirmed recap, an approval verdict, a finished checklist with its - values. A pick that still owes its recap is not an answer yet: save it where - the workflow keeps unfinished work (Pathfinder: the question's `## Evidence`, - with the probes still outstanding and your recommendation for each) and never - write a provisional `## Answer`. Do not claim a question the person picked - from a menu in the same send. -2. **Save your place** the way the workflow does when a session ends. -3. **Post `finish`** (below) with a headline starting "Paused" (the page and - `open --resume` both key off that word), a body naming what was saved and - anything still open, and the resume command. Name a question that was left - mid-way, so they can ask for it by name next time. -4. **`stop`** the server. - -Do not publish new questions and do not ask whether they are sure: the page -already asked. - -The page only offers Stop on the person's turn. From the moment they press Send -until your reply lands, the button is disabled, so a stop never arrives while -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. - -### Back to the dashboard, mid-workflow - -On every workflow but the dashboard, a triangle left of Stop session takes the -person back to the dashboard. It follows Stop's rules exactly: only on their -turn, a confirm first (with your `stopWarning`), and the staged answers ride -along in the same submit: - -```jsonc -{ "type": "submit", - "actions": [ /* staged answers and notes, as usual */, - { "i": "__dashboard", "type": "dashboard" } ], - "reply": "...the answer lines...\nSave my place and take me back to the dashboard, right here in this session." } -``` - -It is the same `__dashboard` a finished screen sends; with no `finish` on the -page it means "stop, then go home". Act on it in this turn: - -1. **Handle the answers** exactly as step 1 above. -2. **Save your place** exactly as step 2 above. -3. **Resume as the dashboard:** `open --resume --no-open --workflow - dashboard`, then ONE post with `"finish": null`, the `menu` payload and - `"agent": { "status": "waiting" }`. Then read the dashboard skill - (`~/.agents/skills/plan2code/SKILL.md`) and carry on as the dashboard - from its "The menu" section, in this same conversation. - -No `finish` and no `stop` in between: the menu is the ending. Say what you -saved in one terminal line, since no finish card will. A workflow with nothing -to save (a quick task not yet built) just goes home. - -### Saying what stopping would cost - -Some points in a workflow have nothing on disk yet, and stopping there loses the -answers given so far: Pathfinder before its map exists, Planning before a -checkpoint. The page cannot know where you are, so tell it: - -```jsonc -{ "stopWarning": "The map is not written yet, so stopping now loses today's answers." } -``` - -It is shown in the page's Stop dialog, and the button changes from "Stop and -save" to "Stop anyway". Post `"stopWarning": ""` once stopping is safe again. -For `plan` sessions the page assumes a warning until you post that empty string. - -### Say where the files are - -Post `"specDir": "specs/"` once the folder exists (or pass `--spec` to -`open` when it already does). If you ever cannot answer a stop yourself (your -session died, the server went away), the page builds the resume command from -it; without it, the page can only offer the bare command, which asks which -idea. - ---- - -## Quick questions - -The page has an **Ask** tab, always the last one, on every workflow. There the -person can ask anything, about this project's files or in general, at any -time, without waiting for a card. Their messages reach you at your next -check-in, through the `wait` you already run (and, in a build, the instant -`chat` check). Chat rides its own channel: a message never blocks a card send, -and a card send never blocks a message. The page handles its own refusals, so -you never see them: `too-long` past 4,000 characters, `limit` after 10 -messages, `offline` when no agent is connected or the session has finished, -`stale` after a new conversation started. - -### How chat arrives - -- `wait` exit `0` may carry `chat: [...]` beside `actions`, or, when no card - was sent, be `type: "chat"` with `actions: []`. No exit code changes. -- `reply` gains one block per entry after the card lines: - - ``` - Quick question: Where does the export go? - About: Export format - Image: /home/sam/.plan2code/console/sessions/20260923-101500-ab12cd/uploads/3f2b9c1e-8a4d-4f6e-9b7a-2c5d1e0f4a6b.jpg (shot.png) - File: /home/sam/.plan2code/console/sessions/20260923-101500-ab12cd/uploads/9e4b2d7a-1c3f-4a6e-8b5d-0f2c7a9e3b1d.json (config.json) - Approved: edit r7 - Note: keep the old name working too - New conversation started. Treat earlier chat as closed. - ``` - - Typed text past its first line is indented, so only a real entry ever - starts a line. -- Each `chat` entry carries `seq`, `conversation` and `kind`: `message` - (`text`, optional `about`, `images` and `files`), `decision` (`re`, - `decision` `approve` or `decline`, optional `text`) or `reset`. -- `about` is set only when the person attached it with **+ Add context**. The - page never adds one on its own, so a message without it is a general - question, not one about the card on screen. -- Open every `Image:` and `File:` path with your file-read tool before you - answer, as for notes. -- `node "" chat --session ` checks right now and never sleeps: - exit `0` with `{ chat, reply, terminalLine }`, `10` with `{ chat: [] }` when - nothing is waiting, `20` when the server is gone. It never reads or collects - card sends; those stay with `wait`. - -### Answering - -**Every message gets a reply, always.** The Ask tab is the person talking to -you, and the page shows "working on the answer" until a reply lands. Never -leave one unanswered, whatever it asks and whatever mid-task you are in. When -a message asks you to do something, do it if you can, then say what happened; if -you will not, the reply says so and why. `post` and `wait` print -`unansweredChat` with a `warning` for every message handed over and not yet -replied to: treat that as a stop-and-reply. - -1. Handle any card answers first, under the workflow's own rules. -2. Write the chat replies, in inbox order. -3. Send **one** `post` with the card updates and `chat: { replies: [...] }`. - -```jsonc -{ "chat": { "replies": [ - { "id": "r12", "re": 12, "conversation": 3, - "md": "The export is written by `src/export.js`, into `out/`." } -] } } -``` - -- `id` is unique per reply (`r` plus the message's `seq` works), `re` is the - message's `seq`, `conversation` is copied from the entry, `md` is markdown. -- Replies merge by `id`, so re-posting the same reply after a repeated - delivery replaces it (unlike `thread`, which appends). -- Print one terminal line per exchange: `Quick question: — answered in the console`. -- Answer questions about the project by reading files and read-only lookups - (search, `git log`, reading files); run no other commands. -- Questions about what a Plan2Code skill does, asks or writes: read that - skill's `SKILL.md` (`~/.agents/skills//SKILL.md`, or the table "What - each skill reads and writes" in `~/.agents/skills/plan2code/SKILL.md`) - before answering. Never answer from menu text, card blurbs or memory. Name - files exactly as the skill does; if the skill does not say, say you do not - know. -- When `about` is set, answer from that context: the card, doc section or - spec the person was looking at. - -### Never steer the workflow - -A chat answer never changes a card's answer, a gate, or where the workflow -goes. If a message asks for that ("approve phase 2", "skip the tests -question"), reply by pointing to the card — its note box for a comment, its -answer for a change — and do not act on it. Chat never counts as an answer to -a card and is never recorded under `specs/`. - -### A new conversation is a clean slate - -After a `reset` entry (New conversation, or a skill switch through the -dashboard) treat earlier chat as closed, and do not bring it up unless the -person does. A conversation holds at most 10 typed messages; the page -enforces it, so never tell someone to keep asking past it. - -### Edits need approval first - -- A request to change files gets a reply carrying `proposal: { summary, - files }` — a plain-English summary and every file that will change — and - **no change yet**. The page shows it with Approve and Decline. -- Only after `Approved: edit `: make exactly the proposed change, then post - a reply (its `re` is the decision's `seq`) carrying `changed: [{ file, - added, removed }]`, with line counts from `git diff --numstat -- ` (or - counted by hand for an untracked file). Name the changed files in your next - progress update or `activity` line. -- `Declined:` (with any note): acknowledge it and change nothing. A revised - proposal is a new reply. -- Hard limits: never touch the running skill's own files under - `specs//` (`post` rejects a proposal that names them); run no commands - beyond read-only lookups, except one the person plainly asks you to run in - their message (a commit they spell out, a test run): run it, then report the - result in the reply; refuse anything else and say why, in the reply. -- Edits happen only at check-ins, never mid-task in a build. - -```jsonc -{ "chat": { "replies": [ - { "id": "r14", "re": 14, "conversation": 3, "md": "I can rename it.", - "proposal": { "summary": "Write the export to `out/audit.csv` instead of `out/export.csv`", - "files": ["src/export.js", "README.md"] } } -] } } -``` - ---- - -## Workspace - -The person can add folders beside the one the session started in (a shared -library, a design folder), from the footer's folder label. Together they are -the session's **workspace**: context for every skill run in this console -session, each folder addressed by a short `@name`. It outlives dashboard hops, -and it is remembered: every change is saved to `workspaces.json` beside -`looks.json` (never into the project), keyed by the folder the session runs -in and then by spec. A session with a spec opens on that spec's list, one with -none on the project's; a spec with nothing saved starts as a copy of the -project's list. The dashboard's picker swaps the list as the selection moves, -and a `specDir` you post mid-run takes the current list with it. There is -nothing for you to load: `open` prints the list, and a switch of spec on a -resume reaches you as ordinary workspace changes on your next `wait`. - -### What you are told - -`open` (fresh or `--resume`) prints the whole list under `workspace`: - -```jsonc -{ "ok": true, "sid": "…", "url": "…", - "workspace": { - "folders": [ - { "name": "shop", "path": "/home/sam/code/shop", "original": true }, - { "name": "shared", "path": "/home/sam/code/shared-ui", "description": "Button and form styles" } - ], - "missing": ["old-docs"] - } } -``` - -`missing` (only when there is one) names folders no longer on disk. After -`open`, you hear only of changes, each exactly once: - -- `wait` exit `0` carries them beside a send or chat as `workspace: [...]` - (`{ kind, name, path, description?, from? }`, `kind` one of `added`, - `renamed`, `described`, `removed`, `missing`, `found`), with one - `Workspace: …` line each at the end of `reply` - (`Workspace: added @shared — /home/sam/code/shared-ui`). A change alone never - ends a slice: exit `10` counts it as `pendingWorkspace` and it rides on the - next send. -- `chat` hands changes over at once, with or without a Quick question, as - `{ chat, workspace, reply }`. - -Act on a change in the same turn it arrives: drop a removed folder, use the -new name after a rename, note a missing one. No reply is needed unless the -person asked something. - -### Rules - -- **Resolve `@name` from the workspace list.** `@shared` in an answer, a note - or a Quick question means that folder's `path`. An `@name` not in the list - is ordinary text. -- **Added folders are read-only reference.** Read them freely; edit one only - when the person asks for that change in this conversation. Chat edits still - need approval (Quick questions → Edits need approval first). -- **Read an added folder's `AGENTS.md` before you first use it** (`CLAUDE.md` - when there is no `AGENTS.md`), once per folder per skill run. It says how - that folder is laid out; the original folder's `AGENTS.md` still governs - this project and the work. - -### When a folder cannot be read - -When a read of an added folder genuinely fails (refused, not found), post, once -per folder: - -```jsonc -{ "folderIssue": { "name": "shared", "reason": "Permission was refused", "hint": "/add-dir /home/sam/code/shared-ui" } } -``` - -and print one terminal line saying which folder and why. The page marks the -folder and tells the person once. `hint` is optional: an agent that knows it -is Claude Code puts `/add-dir ` there. Your harness asking the person -for permission is not a failure; report only a read that failed after it. - ---- - -## Standing instructions - -On the skills that offer it (`implement`, `implement-review`, `quick-task`, -`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off -from the top bar's Subagents button. Their pick is saved per project and per -skill, off by default, and reaches you as a standing instruction, only when it -changes. - -### What arrives - -A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`, -after the card lines, the `Quick question:` blocks and the `Workspace:` lines. -It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting -change alone never ends a `wait` slice: it waits for the next send, or for -your next `chat` check. - -``` -Subagents: on (revision 2) — a console setting, not typed by the person. - Hand independent work to helpers if your tools allow it; otherwise carry on alone. - Report each helper on the page (console.md → Standing instructions); questions for the person stay with you. - If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it. - Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you. - At most 3 helpers at once. -``` - -beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`. -An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …` -with the whole block again; switching off arrives as one line: -`Subagents: off (revision 4) — don't start new helpers for the rest of this session.` - -It is a console setting, not something the person typed. It never answers a -card, and it is never recorded under `specs/`. - -### Obeying it - -- **On:** hand independent work to helpers if your tools allow it, at most - `max` at once, following the instruction lines. `max` is advisory: your - harness's own limit still applies. -- **A higher revision replaces a lower one.** Follow the latest block only. -- **Off:** start no new helpers for the rest of the session. Let running ones - finish and report them. -- **Nothing arrives:** keep doing what the skill says. -- **Scope is the skill run it arrived in.** After a dashboard launch, no block - means the switch is off for this skill, even if an earlier skill in the same - conversation was told "on": `open` starts the count again, and a launch with - the switch off sends nothing. - -### Reporting helpers - -Post them, at your check-ins, so the page's Subagents tab can show them. The -page never hears from a helper directly: - -```jsonc -{ "helpers": [ - { "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" }, - { "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." } -] } -``` - -- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and - `state` (`running`, `done` or `failed`) are required; `result` (at most 200) - is the one line you add once a helper ends. -- Merged by `id`: post a helper again with its new `state` and `result` and it - updates in place. `"helpers": null` clears the list. A dashboard hop clears it - too; a resume into the same skill keeps it. -- One post per change worth seeing, not a stream. -- Questions for the person stay with you, never with a helper: most harnesses - give helpers no way to ask, and an answer only reaches the agent holding the - session. -- **No way to start helpers at all?** Post one `{ "id": "alone", "alone": true }` - entry for the skill run instead. The tab then says you are working alone. - It is a claim about your tools, not about the moment — post it only when no - helper mechanism exists. Reporting a real helper removes it, so an early - `alone` can never hide a later helper. -- **Pathfinder:** research questions always use helpers and are always - reported, whatever the switch says. The switch governs recon, sketches and - lookups beside the conversation. -- Helpers add no session meter points. Post no `run` for them. - ---- - -## Launches (dashboard only) - -A `dashboard` session is not a conversation: the page draws a menu of every -Plan2Code skill, and the one send that matters is the pick. It arrives -through the wait loop like any other: - -```jsonc -{ "type": "submit", - "actions": [{ "i": "__launch", "type": "launch", - "skill": "plan2code-3-implement", "workflow": "implement", - "spec": "specs/lunch-vote" }], - "reply": "Start Implement (/plan2code-3-implement) for specs/lunch-vote, right here in this session." } -``` - -`__launch` names no question; like `__stop` (and `__brief`, `__review`, -`__done` and `__dashboard`) it is about the session. `skill` -is the skill's install name, `workflow` the `--workflow` it runs under, and -`spec` the picker's selected spec dir — present only when the launched skill -takes a spec and the person picked one; absent means "start from scratch". -The dashboard skill's own prompt (src/plan2code.md) drives the hand-off; -the rule that makes it work, for whatever agent holds the session next, is: - -**A session handed to you is resumed, never re-opened — and resumed first.** -`open --resume --no-open --workflow ` (plus `--spec -` when the action carried one, and `--title ""` if you already -know it) comes before reading the skill file: one command both reuses the -live server and turns the page from the menu into your starting screen, so -the person sees the pick land while you read (`--title` and `--spec` are -honored on resume the same way). A resume to or from `dashboard` also -clears the page: the last skill's questions, sections, docs, headline and -finish are dropped, so you start on a blank page and post your own. A skill -run inline from another (a quick task's review) keeps the page it was -handed. A -fresh `open` would strand the page the person is watching on the dashboard's -session while your questions went to a page nobody has open. - -> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your -> own file-read tool and follow it from the top instead.** Every Plan2Code -> skill below the dashboard ships `disable-model-invocation: true` on -> purpose — it exists to be read and followed inline, not launched as a -> sub-skill — and calling one through a skill-invocation tool errors out and -> strands the hand-off mid-launch. - -Its Interface step is already answered by having been launched, so start -where its real work starts. - -The menu itself is the page's own list — you never send it. The page knows -the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan` -(`{ hasAgents, specs: [{ dir, name, state, detail, touched }] }`), and the -picker at the top of the menu greys the cards that do not fit the selected -spec's pipeline stage — or hides them outright while the **Hide unavailable -workflows** switch under the picker is on (the default; kept in `looks.json` -as `hideUnavailable`). The scan is a snapshot of that `open` — a spec created -mid-session appears the next time the session resumes as a dashboard, not -live. What a dashboard posts is what it knows about this project: - -```jsonc -{ - "menu": { - "note": "one line under the title — what you made of the project", - "recommend": "plan2code-init", - "details": { "plan2code-3-implement": "Phase 2 of 4 is next" } - }, - "agent": { "status": "waiting" } -} -``` - -`recommend` flags one card "Suggested", `details` adds a line under a card's -blurb keyed by skill name, `note` sits under the page title. All optional; -leave the field out entirely and the page falls back to the selected spec's -own next step. These fields describe the initially selected spec. If the -person switches specs or starts fresh, the page derives the suggestion and -detail from the project scan instead. - -From the click until the resume lands, the page shows a getting-ready screen; -from the resume until your first payload, the new skill's starting screen. Do -the resume first and that first `post` before anything slow. - ---- - -## Workflow notes - -What each workflow needs from the page beyond the general rules above. The -workflow's own prompt points here. Builds (`implement`, `implement-review`, -`quick-task`) have their own file, `building.md`. - -### Dashboard - -The whole file above is the note: open `--workflow dashboard`, post `menu`, -wait, and on `__launch` hand the session to the skill it names. Sends carry -no answers, so there is nothing to record. A `__stop` before a pick ends the -session the usual way — `finish` (paused headline, `"command": "/plan2code"`) -then `stop`. - -### Init and Init Update - -Setup conversations: every confirmation and Q&A item goes through the page. -For `init` and `init-update` the finished AGENTS.md also lands as a doc so a -browser-only person can read what was written — marked `"saved": "AGENTS.md"`, -since the file itself is already on disk. A completed run finishes with **no** -`command`: the page shows the "All done" line. Nothing is on disk to resume -mid-run, so a stop's finish command is the bare `/plan2code-init` or -`/plan2code-init-update` — the skill starts over either way. - -### Documentation (`document`) - -The questions are few — which draft, a clarification, the sign-off — but the -docs are the point: post each phase file as a doc as it is written, so a -browser-only person watches the spec take shape. Each one mirrors a file on -disk, so carry its `saved` path. Pass `--spec specs/` -once the folder is known; it is what the resume command needs. Finish -commands follow the pipeline: the sign-off's is -`/plan2code-3-implement specs//overview.md`. - -### Review (`review`) - -Scope questions up front — run standalone with nothing named, the first is -a `choice`, "What should I review?", built from a quick scan (branch changes, -uncommitted changes, specs, files you name; each option with its size), -never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`), -then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding -id, carrying `"doc": "report"` so the card links straight to the findings. -Settle that item (`"status": "answered"` plus the `answer` they sent) in -the same post that takes the picks up: left open it stays on the page as a -question still owed, next to whatever you ask next. Post `activity` while you -read — a real review is long stretches of you working, and the page should -say so rather than hint at questions. When the -session was launched from the dashboard, resume the session you were handed -(`open --resume --no-open --workflow review`), never a fresh `open`. A -review run from a build's review button stays in the build's session, under -its workflow: `building.md` → The review, mid-session. On completion the finish's `command` is the suggested -commit when fixes landed — filled in, in the AGENTS.md format, with -`"where": "When you are happy with it, commit it from your terminal:"` — -otherwise leave `command` out. The completion finish carries `"dashboard": true` -so the finished screen offers **Back to the dashboard**; keep waiting for the -press. A stop mid-review loses nothing on disk, so its finish is the bare -`/plan2code-review` (a pause, so no dashboard button). - -### Handoff (`handoff`) - -One gate: the next-task confirmation, then the document itself as a doc — -that is what the person is there to download. The finish carries no -`command`: the doc download is the point, and the dashboard button and the -"All done" line cover what comes next. - -### Pathfinder - -- Every probe, recap and menu goes through the page. -- Post `"stopWarning"` while no map exists (Steps 0 to 4) and `"stopWarning": ""` - once it does, and `"specDir": "specs/"` when the folder is created. -- Chart Step 8's research subagents must all report back before the - finish (Finishing → Nothing of yours may still be running); the finish - body then names what each one found. -- Report every research subagent as a helper, whatever the Subagents switch - says (Standing instructions → Reporting helpers). -- At every session end, post `finish` (headline, `body`, and Form A's command as - `command`) BEFORE `stop`. Someone who spent the session in the browser never - sees the Trail Footer, and without this their last screen promises a question - that is never coming. -- Post `run` `pathfinder-chart` (id `map`) when a new map is first written, - and `pathfinder-research` (id = the question's file slug; on `github`, `q`) as each research - subagent reports back, or when you resolve a `research` question yourself - (Posting an update → Session meter). Other questions score through their - answers, so there is nothing to post for them. -- The scope probe is **Leave for later**: "Which of these features are we - leaving out this time?" as a `multi` with a recommended preset. Every option - names a feature, and its `detail` ends "(Leaving this out = …)". Never phrase - an option as a rule to keep. - -### Planning - -- Open with `--workflow plan`, first thing. Every question and sign-off gate - goes through the page, phase breakdowns as an editable `list`. -- Planning has no mid-session save before the Large checkpoint or Phase 7, so for - a stop before then say plainly in `finish.body` that nothing was kept, and use - `"command": "/plan2code-1-plan"`. After the checkpoint, post - `"stopWarning": ""`. -- At every session end, post `finish` BEFORE `stop`; on completion that is - `"command": "/plan2code-2-document"`, and at the Large checkpoint it is - `/plan2code-1-plan`. The closing message is printed to a terminal the - browser user is not watching. -- The Large checkpoint finish is a pause: a headline starting "Paused", no - `dashboard`, and `stop` at once. - -### Revision (`revise-plan`) - -Revision is a short run of gates, and each maps onto a kind you already know: - -| Step | On the page | -| --- | --- | -| 1, Change Analysis | A `recap` item, "Is this the change?", with the affected-areas table in `summary`. | -| 2, Impact Assessment | The Revision Impact Summary as a doc (`id: "impact"`), and a `review` item "Approve the spec changes" pointing at it: verdicts `approve` ("Approve these spec changes"), `refine` ("Refine the plan") and `abort` ("Abort", `"danger": true`), token equal to the ids, `nothingYet`: "No spec file changes until you approve." | -| 3 to 5 | Nothing to ask. Post `activity` while you edit, then the Revision Complete summary as a doc. | -| 6, Cleanup | A `confirm` per rename or removal, the paths in `consequences`. | - -Revision's own rule holds on the page too: **no option, verdict or label ever -offers to execute or implement.** Pass `--spec specs/` to `open`, or -post `specDir` once you know it. The -finish command is `/plan2code-3-implement specs//overview.md`; an -abort's is `/plan2code-1b-revise-plan specs//overview.md`. - -### Finalize - -Finalize is a run of reports and gates, and each maps onto a kind you already -know: - -| Step | On the page | -| --- | --- | -| 1, Task Completion Audit | The audit table as a doc (`id: "audit"`). If incomplete tasks exist, a `choice` with the three options — return to implementation, mark partially complete, abandon — with the counts against the thresholds in `body`. | -| 2, Implementation Verification | The verification results as a doc. Nothing to ask unless an issue needs their decision. | -| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) so the page reader sees it land. | -| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. | -| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. | -| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/` after the move). | - -Post `activity` as each step starts, before its doc or question lands — reading -the spec, running `specs.mjs status` or `archive --dry-run`, checking the -implementation — the same way Review does. A step with no card of its own -(2, 3) is otherwise a stretch of silence the page can only show as "Starting -Finalize". - -Pass `--spec specs/` to `open`, or post `specDir` once you know it. -Stopping mid-finalize loses nothing -— the specs are untouched until Step 3's summary write — so a stop's finish -just says where it paused and uses `"command": "/plan2code-4-finalize -specs//overview.md"`. On success the finish's `command` is the -suggested commit when Step 4 doc updates landed (with `"where"` adjusted, as a -quick task's is), otherwise leave `command` out. The -completion summary is printed to a terminal the browser user is not watching, -so put it in `finish.body`. - -## Posting an update - -``` -node "" post --session --file -``` - -Write `` into the session's own folder (the `session` path `open` -printed), never into the project or into `~/.plan2code/console/` directly: -the session folder goes with the session after 30 idle days, and stray -`.json` / `.mjs` files in the console folder are swept on the same clock. - -Set `{"agent":{"status":"working"}}` as soon as you start thinking about a send, -so the page can say so, then send the real update when you are done. -Add `activity` inside `agent` (one plain sentence) when what you are doing -takes a while and is worth naming: the page shows it in place of "thinking", -and it is what moves the page off its starting screen before the first -question or doc lands: -`{"agent":{"status":"working","activity":"Reading the plan"}}`. - -The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs` -merge by `id` (an unknown id is added), and `thread` appends. Send only -what changed. A whole-file rewrite would put the entire session back into your -context on every turn. - -**Never write a timestamp.** The server stamps every time you leave out. - -If a patch is rejected the exit code is `3`, stderr says exactly why, and nothing -is written. Fix it and post again. The checks are listed under House rules. - -### Session meter - -The page's top bar shows a meter of how much work this console session has -done (green, yellow, red), so the person knows when a fresh session would be -sharper. It is advice only and never blocks anything. The console counts -launches itself: Plan, Revise plan, Document, Review, Quick task, Init, Init -update and Finalize score when their session opens, and there is nothing to -post for them. - -It counts answers itself too: every card the person answers in a send adds to -the skill run's tally when `wait` hands the send to you, and every 2 answers -score a point, so a long back-and-forth weighs more than a short one. Notes, -Quick questions and buttons such as Stop or the dashboard do not count. - -Per-unit work is yours to report, with `run` in any post: - -```jsonc -{ "run": { "event": "implement-phase", "id": "phase-2", "tasks": 9 } } -``` - -- `event` is one of `pathfinder-chart`, `pathfinder-question` (scores - nothing now: answers count instead), `pathfinder-research`, `plan`, - `revise-plan`, `document`, `implement-phase`, `implement-review-phase`, - `review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`. - An unknown event is exit `3`. -- `id` names the unit: a question's file slug, `phase-N`, `map`. The same id - posted again in the same skill run is ignored, so a repeated post never - counts twice. -- `tasks` goes only with `implement-phase` and `implement-review-phase`: the - number of tasks the phase completed (marked `[x]`; blocked `[!]` tasks do - not count), a whole number from 1 to 999. A built phase scores by its size, - one point per 3 tasks rounded up, and Implement + Review one more for the - review. Always send it: without it a phase scores a flat 2 (or 3), however - big it was. On any other event it is exit `3`. The console already counts a - build's tasks from `headline.cleared` as they are ticked off; the phase's - `run` takes that count over with the final score, so it never counts twice. -- One `run` per post. Which events a workflow reports is in its own notes - (Workflow notes → Pathfinder; `building.md` for Implement and for the - review run on the page after a build). - ---- - -## The payload - -```jsonc -{ - "title": "Audit export", - "headline": { - "stage": "Working", - "cleared": 4, "total": 9, - "confidence": "Looking solid, but one area still needs work.", - "note": "optional sentence shown above the list" - }, - "topics": [ { "id": "t2", "title": "How it behaves", "status": "current" } ], - "items": [ /* see kinds below */ ], - "docs": [ /* see Documents below */ ], - "finish": { /* only on the last patch -- see Finishing */ }, - "agent": { "status": "waiting" } -} -``` - -`headline.cleared` / `total` drive the progress bar. Fill them in. "How much -longer is this?" is the first thing anyone asks in a working session, and the -terminal cannot answer it. - -`finish` is the session's ending, and the only key that changes what the whole -page means: without it the page can only say "nothing right now", which is a -pause. See [Finishing](#finishing-and-cleaning-up). Leave it out until the last -patch. - -`confidence` must be the plain-English sentence, never raw scores. - -Two more top-level keys never reach the page state: `run` (Posting an update → -Session meter) and `folderIssue` (Workspace → When a folder cannot be read). -`post` lifts both out of the patch into the session's ledger, and `open ---file` does the same. - -### Every item - -**Give every new question a new `id`.** An id names one question for the whole session. The server drops a stale `submitted` record if you reword a question under an old id, but never rely on it: a fresh id is the only unambiguous way to ask something new. - -```jsonc -{ - "id": "q7", - "topic": "t2", - "kind": "choice", - "title": "Export format", // 2-4 plain words. A person who has never - // seen this workflow has to understand it. - "body": "The question, in markdown, with why it matters.", - "required": true, // false adds a "Skip this one" link - "doc": "report", // optional: a doc id; the card gets a - // "Read ... in full" button that opens it - "status": "open", // open | answered | reopened | skipped - "fallbackText": "the exact wording you would have printed in the terminal", - "token": { "A": "a", "B": "b" } // what each answer means as a typed reply -} -``` - -Always set `fallbackText` and `token`. They are what let a click mean the same -thing as a typed word, so nothing downstream has to know which channel was used. - -### The kinds - -| `kind` | Use it for | Extra fields | You get back | -| --- | --- | --- | --- | -| `choice` | one of several | `options[]`, `allowOther` | `{ k }` **or** `{ text }` | -| `multi` | any number of several | `options[]`, `presets[]` | `{ ks[], text? }` | -| `text` | free text | `placeholder`, `help`, `pattern`, `patternHint`, `templates` | `{ text }` | -| `confirm` | yes or no | `yesLabel`, `noLabel`, `danger`, `consequences` | `{ yes, text? }` | -| `recap` | play decisions back for agreement | `summary` (markdown) | `{ ok, text? }` | -| `review` | read something, then approve | `doc` (always, for this kind), `summary`, `verdicts[]` (each `{ id, label, danger? }`: `label`, not `text`), `nothingYet` | `{ verdict, text? }` | -| `checklist` | steps only they can do | `steps[]`, `valuesLabel` | `{ done[], state, text? }` | -| `menu` | what to do next | `options[]`, `command` | `{ k }` | -| `list` | reorder or edit a breakdown | `rows[{id,title,body}]` | `{ rows[] }` | -| `notice` | something to read, no answer | — | nothing | - -A `choice` answer carries **one of the two, never both**. The page offers -"Something else, in your own words" as a real option in the same radio group, so -picking an option and writing a sentence are alternatives: the last one touched -wins and the other is dropped. Read `k` if it is there, otherwise read `text`, -and do not treat `text` as a footnote on a pick. Set `"allowOther": false` to -drop that option when the listed ones genuinely are the whole set. - -`presets` on a `multi` are quick-pick buttons that tick a named set in one go, -`[{ "label": "Critical and warnings", "ks": ["1","2"] }]`. They only tick -boxes: the answer is still `ks`. - -`multi` is the other way round: there, `text` joins the ticks rather than -replacing them, because naming a third thing alongside two you picked is the -point. A note that qualifies an answer without being one belongs in the -question's own note box, and arrives as a `comment` action. - -An option is `{ "k": "A", "text": "short label", "detail": "the trade-off", "recommended": true }`. -`detail` is where the trade-off goes, and it is the difference between a person -choosing and a person guessing. At most one option may be `recommended`. - -`pattern` is a JavaScript regular expression validated live as they type, with -`patternHint` shown when it does not match. Use it for anything with a shape, -above all kebab-case names. This is something the terminal cannot do at all. - -Items appear on the page in the order you send them, and the person walks the -open ones with Previous / Next under the card. Send them in the order you want -them answered. - -### A placeholder is an offer, not decoration - -On a `text` question the page puts an **Autofill suggestion** button beside the -label, which drops the `placeholder` into the box as a real, editable value. Any -lead-in is stripped first, so `"For example: about 8 of us in one office"` fills -as `"About 8 of us in one office"`. - -Write the placeholder so it stands up as an answer on its own: a whole example, -in their voice, not a description of the kind of thing you want. It is the -closest this page gets to answering for them, so make it a good answer to accept -or a bad one to argue with, never a vague one. On a question with a `pattern`, -the example must satisfy the pattern. - -### Starter templates - -On the `text` card that asks for a **fresh idea** in Pathfinder, Plan and Quick -Task, add `"templates": "idea"`. The page then draws a row of starter templates -above the box: **Blank** first, then that skill's templates in the order the -person's Role puts them. A pick fills the box with editable text. What comes -back is only the text in the box, exactly as if they had typed it. No template -id travels, so read it like any answer. - -Set it only when you are asking for a new idea. A resumed map, PLAN-DRAFT or -Plan checkpoint gets no idea card, so there is no flag. Launched with a folder -of notes or an idea as the argument? Still set it, and put a one-line summary of -the notes (or the argument itself) in `placeholder`, so **Autofill suggestion** -offers it. `post` rejects the flag on any other kind, or with any value but -`"idea"` (exit 3). The terminal has no templates: don't mention them there. - -### Recommendations are optional, and often wrong to give - -Give a `recommended` option when you genuinely have the better answer and can say -why. Leave it out when the answer depends on what the business wants: a -recommendation there is an anchor, and people will rubber-stamp it. "Who is this -for?" is not yours to recommend. "Which format survives contact with Excel?" is. - -### Documents - -```jsonc -"docs": [{ - "id": "map", "title": "What we've agreed", "version": 2, - "stale": false, "note": "what changed in this version", - "saved": "specs/lunch-vote/pathfinder/map.md", - "blocks": [ - { "id": "b1", "state": "settled", "md": "## Where we're headed\n\n..." }, - { "id": "b2", "state": "assumed", "md": "### File format\n\nAssuming CSV..." }, - { "id": "b3", "state": "draft", "md": "### Still to work out\n\n- ..." } - ] -}] -``` - -Each doc becomes a tab. Patch individual blocks as decisions land rather than -rewriting the whole thing: blocks merge by `id`, so `{ "id": "b2", "state": -"settled" }` settles b2 and keeps its text, blocks you leave out stay as they -are, and a new `id` is added at the end. To remove one, send `{ "id": "b3", -"_delete": true }`. - -`state` is the point of this feature: - -- `settled` — decided, and it will not move -- `assumed` — you had to pick something to keep going, and it is still open. - The page marks it "Assumed for now, still open" with a dashed edge. -- `draft` — a placeholder, shown dimmed - -Marking assumptions honestly is what stops someone reading a half-finished -document as a set of decisions. Bump `version` and write a one-line `note` when -you change a doc, and set `stale: true` if answers have landed that it does not -reflect yet. - -`saved` is the path of the file this doc mirrors, when you already wrote one — -the page drops the Markdown download (on the doc's tab and on the way out) and -shows the path instead, because the file is already there. Leave it off docs -that exist only here: a hand-off's document is the thing they are taking with -them. - ---- - -## House rules the server enforces - -A patch that breaks one of these is rejected with exit `3` and a message: - -1. **At most three questions open at once.** The cap is the person's attention, - not the screen size. A screen that can show ten still only gets three. -2. **No internal vocabulary in a title.** Words like *grill*, *frontier*, *fog*, - *HITL*, *durable*, `Locked:` and `Blocked by:` are bookkeeping. They never - reach a person. -3. **At most one recommended option per question.** -4. **No loop completion markers** (`TASK_COMPLETE`, `PHASE_COMPLETE` and the rest). -5. **No bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a - number.** The metrics collector scrapes that pattern. Hyphenate it - (`Requirements-clarity 22/25`) or reword. -6. **Chat replies hold together** (`chat.replies`). Each needs a unique `id`, - an `re` naming a real message or decision `seq`, an integer `conversation` - and non-empty `md`. A `proposal` needs a `summary` and project-relative - `files`, none under the running skill's `specs//`. `changed` is a - list of `{ file, added, removed }`. Rules 4 and 5 cover reply text too. -7. **`run` and `folderIssue` are well formed.** A `run` needs a known `event` - (Session meter) and a non-empty `id`; a `folderIssue` needs non-empty - `name` and `reason` strings, and `hint`, when present, is one too. Rules 4 - and 5 cover `reason` and `hint`. -8. **`helpers` entries are well formed** (Standing instructions → Reporting - helpers): an array of objects, each with a unique `id`, a `title`, an `ask` - and a known `state` within their limits, plus at most one `alone` entry. - Rules 4 and 5 cover `title`, `ask` and `result`. -9. **A doc's `version` never goes back.** Sending a known doc a lower - `version` than the page holds is refused: it is almost always a stale or - copied payload. The same version again is fine, and a dashboard hop starts - every doc fresh. Anything else reusing a doc id in the same session (a - build's second phase, a second report or review) continues from the - version the page holds. - -These are workflow rules you already follow. The server just makes them checkable. - ---- - -## Finishing, and cleaning up - -Three steps, in this order. **Post the finish, wait up to about ten minutes for -a press, then stop the server.** A pause (below) still stops straight away. -Stopping first leaves the person staring at a page that says "leave this tab -open, the next question will appear here on its own" about a session that is -over, and the one thing they need is a command in a terminal they are not -looking at. - -**Nothing of yours may still be running.** Before the finish, every -subagent or background job you started this session must have reported -back. They run inside your terminal's process, not the console's: the page -cannot see them, and the moment it says the session ended, the person is -free to close that terminal and kill them mid-write. While you wait, post -`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}` -and update the count as each returns. Never write a `finish.body` that says -work "is running in the background" or "will finish on its own". Mark every -reported helper `done` or `failed` before the finish, so the Subagents tab -never ends on a row still running. - -### 1. Post the finish - -The same closer you are about to print in the terminal, as data: - -```jsonc -{ - "finish": { - "headline": "The map is written", - "body": "Everything you decided is on disk under `specs/lunch-vote/pathfinder/`, one file per decision. The **The map** tab has the whole picture.", - "command": "/plan2code-0-pathfinder specs/lunch-vote/pathfinder", - "doc": "map", - "dashboard": true - }, - "agent": { "status": "waiting" } -} -``` - -| Field | | | -| --- | --- | --- | -| `headline` | required | What just happened, in plain words. Becomes the card's title. | -| `command` | optional | The exact thing they run next, when there is one — the same string as your Trail Footer's Form A. Rendered with a Copy button that is always on show. Leave it out when nothing is left to run: the page shows an "All done" line with `/plan2code` instead. **No placeholders**: a rendered command is copied and run verbatim, and a patch carrying `<` or `>` in it is rejected. | -| `dashboard` | optional | `true` puts a **Back to the dashboard** button on the finished screen. Set it on every ending except a pause, and keep waiting for the press (below). | -| `body` | optional | Markdown. Where the files landed, what to read first. | -| `where` | optional | Overrides "Run this in the terminal where you started Plan2Code, in a new conversation:". | -| `doc` | optional | Id of the document to offer as a Markdown download on the way out. Defaults to the first one. | -| `console` | optional | Whether the copied text asks the next session to use the web console. Leave it out: it follows from the command. | -| `review` | optional | A finished `quick-task` only: `true` or `{ "label": "..." }` puts a **Review it now** button on the finished screen. `implement` offers the review on its sign-off card instead — before approval, where it can still change the outcome. See `building.md`. | - -**Write the bare command.** Every Plan2Code skill has a console — the -dashboard and all twelve skills behind it — so for any of them the page -appends ` --web` to what it shows and copies, so someone who worked here -lands back here instead of being asked the interface question as though -they were new. Every one of those skills takes that flag in its argument as -the answer. Do not write `Use the web console for this session.` into the -command; if it is there, the page swaps it for `--web`. A command that is not -a Plan2Code skill gets nothing appended. Set `"console": false` if they have -asked to go back to the terminal. - -The page then says the session is finished rather than paused, offers the -command, tells them they can close the tab, and stops treating the server going -away as a fault. Send is disabled, and anything they staged and never sent is -named rather than quietly lost. - -Settle whatever the session ends on. An item still `open` when the finish -lands freezes exactly as it stands: a send it carries shows as the final word -on it, and one that was never answered shows as a question that ran out of -time. If their last send was a verdict you are closing on — the review's -`approve`, the plan's `yes`, the fixes pick — the finish post is the same post -that marks it `"status": "answered"` with the `answer` they sent, exactly as -"Handling a send" already has you do everywhere else. - -Post it even when you are also printing the footer in the terminal. Someone who -has spent the whole session in the browser has no reason to look anywhere else. - -The chat stays readable after a finish, and the page disables its Send. A -message sent just before the finish can still arrive: while you wait for the -dashboard press, answer any chat `wait` delivers, as in Quick questions. - -### After the finish: the dashboard button - -A **pause** is an ending that keeps a place to come back to: a stop request, -an abort that keeps its place to resume, or a checkpoint that saves and ends -(Plan's Large checkpoint). A pause's headline starts with "Paused", it never -carries `dashboard`, and you `stop` at once. - -Every other finish carries `"dashboard": true`. Then keep calling `wait` in the -usual slices for up to about ten minutes: - -| What arrives | What you do | -| --- | --- | -| An action `{ "i": "__dashboard", "type": "dashboard" }` | `open --resume --no-open --workflow dashboard` (the resume re-runs the project scan), then ONE post with `"finish": null`, the `menu` payload and `"agent": { "status": "waiting" }`. Then read the dashboard skill (`~/.agents/skills/plan2code/SKILL.md`) and carry on as the dashboard from its "The menu" section, in this same conversation. The same action can also arrive before any finish, from the top bar's triangle: see Stop requests → "Back to the dashboard, mid-workflow". | -| An action `__review` or `__done` | As `building.md` says (quick task only). | -| `wait` exit `20` | The server is gone, not necessarily the tab. `open --resume --no-open --workflow `, then keep waiting: their Ask messages and the dashboard button still need you. Give up only when the resume itself fails. | -| Nothing after about ten minutes | `stop` the server. The page swaps the button for the `/plan2code` command. | - -### 2. Stop the server - -``` -node "" stop --session -``` - -If you forget, it shuts itself down after 30 minutes of silence. Stop it anyway. -The page keeps the hand-off on screen after the server has gone: everything it -needs is already in `state.json`, and the Copy button is the one action that -still works on a page whose server has died. - -`node "" status` lists sessions for this project, including any whose -answers were submitted but never picked up. - ---- - -## When things go wrong - -| Situation | What to do | -| --- | --- | -| `open` fails | Say so in one line, carry on in the terminal. Never block on this. | -| `wait` returns `20` | `open --resume `, give them the new link. Nothing they typed is lost. | -| They close the tab | Nothing happens. Drafts are saved. Reopening the link restores everything. | -| Your session ends mid-flight | Their answers still land on disk. A fresh session runs `status` (or `open --resume`, which reports `pendingResult: true`), and `wait` returns them. An uncollected result is never discarded. | -| They ask to go back to the terminal | `stop` the session and continue. The files under `specs/` are unchanged. | -| The session ends and they are still in the browser | Post `finish` **before** `stop`, and wait for the dashboard button first unless it is a pause. See Finishing, above. Without it their last screen says the next question is coming, and then says contact was lost. | -| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. | -| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. | -| Picking up a paused session | `open --resume ` (or `open --session `) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. | -| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. | -| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. | -| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. | - ---- - -## Worked example - -Opening a pathfinder session with the first two questions: - -```json -{ - "workflow": "pathfinder", - "title": "Audit export", - "headline": { "stage": "Charting", "cleared": 0, "total": 6, - "note": "Six quick questions to work out what we're building." }, - "topics": [ { "id": "t1", "title": "What we're building", "status": "current" } ], - "items": [ - { "id": "q1", "topic": "t1", "kind": "choice", "title": "What you end up with", - "body": "When this is done, what exists that does not exist now?", - "options": [ - { "k": "A", "text": "A plan, ready to build from", - "detail": "We write the decisions down. Nothing is built yet.", "recommended": true }, - { "k": "B", "text": "One decision settled", - "detail": "We answer the single question blocking everyone, and stop there." }, - { "k": "C", "text": "A change already made", - "detail": "Small enough to just do. We would skip planning entirely." } - ], - "token": { "A": "a", "B": "b", "C": "c" }, - "fallbackText": "Q1 - What you end up with: a) a plan b) one decision c) a change already made. My guess: a." }, - - { "id": "q2", "topic": "t1", "kind": "text", "title": "Who uses it", - "body": "Who uses the result, and what do they do with it the day it lands?", - "placeholder": "For example: compliance reviewers, who open it in Excel every Monday.", - "fallbackText": "Q2 - Who uses the result, and what do they do with it the day it lands?" } - ], - "agent": { "status": "waiting" } -} -``` diff --git a/skills/plan2code-0-pathfinder/references/web-console/console.mjs b/skills/plan2code-0-pathfinder/references/web-console/console.mjs deleted file mode 100644 index 0dba067..0000000 --- a/skills/plan2code-0-pathfinder/references/web-console/console.mjs +++ /dev/null @@ -1,1355 +0,0 @@ -#!/usr/bin/env node -// Plan2Code Web Console - the CLI the agent drives. -// -// open create or resume a session, publish a payload, start the server, print the URL -// post publish a new payload (an update) to a running session -// wait block for a bounded slice, then report. Exit code says what happened. -// chat collect Quick question messages right now, never waiting -// keep copy a cited note attachment into specs//attachments/ -// status list sessions, or show one -// stop shut a session's server down -// -// The design point: the SERVER is long-lived and detached; the WAITER is a short -// foreground command the agent re-invokes. A twenty-minute human session then -// never has to live inside a single tool call, and nothing the harness does to -// background tasks can destroy the human's work. -// -// Exit codes from `wait`: -// 0 done. stdout is the result JSON. -// 10 still waiting. stdout is a one-line progress summary. Call wait again. -// 20 the server is gone. Run `open --resume ` and re-share the URL. -// 30 the person pressed Cancel. - -import fs from "node:fs"; -import path from "node:path"; -import { spawn } from "node:child_process"; - -import { - CHAT_FILE, - HERE, - HOME_DIR, - SESSIONS_DIR, - appendEvent, - appendLedger, - applyPatch, - attachmentName, - bindLoopback, - blankState, - chatReplyLines, - collectChat, - deliverableChat, - die, - ensureDir, - fileStamp, - forgetWorkspace, - handOff, - handleFile, - healthOk, - initialWorkspace, - isOpen, - lastLaunchId, - listHandles, - newSessionId, - newToken, - nextLaunchId, - nowIso, - parseArgs, - pendingChatCount, - unansweredChat, - pendingWorkspaceChanges, - pidAlive, - print, - projectRoot, - proseProblems, - readChat, - readJson, - readLedger, - readSubagentCursor, - readSubagentSetting, - readWorkspace, - reapHandles, - rememberedWorkspace, - remoteWarning, - removeScratch, - removeSessions, - repoRoots, - resetSubagentCursor, - scanProject, - SESSION_MAX_AGE_MS, - sessionDir, - sleepSync, - specKey, - staleScratch, - staleSessions, - sweepUploads, - switchWorkflow, - terminalLine, - updateState, - UPLOAD_MAX_AGE_MS, - validate, - validateChat, - workspaceForAgent, - writeCursor, - writeJsonAtomic, - writeSubagentCursor, - writeWorkspaceCursor, -} from "./lib.mjs"; -import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js"; -import { blockFor, offered } from "./public/subagents.js"; -import { changeLine } from "./public/workspace.js"; - -// Mirrors the server's absolute lifetime cap: a handle older than this cannot -// still be one of our servers, so its pid gets no second look. -const MAX_SERVER_LIFE_MS = 4 * 60 * 60 * 1000; - -const argv = process.argv.slice(2); -const cmd = argv[0]; -const args = parseArgs(argv.slice(1)); - -// PLAN2CODE_CONSOLE_TRACE=1 prints where the time goes, to stderr: the -// start path is what stands between someone and their first look at the page, -// and it is only worth optimising with numbers in hand. -const TRACE = Boolean(process.env.PLAN2CODE_CONSOLE_TRACE); -function trace(what) { - if (TRACE) process.stderr.write(`trace ${Math.round(performance.now())}ms ${what}\n`); -} - -/* ----------------------------------------------------------------- open */ - -// Cache this console's directory where a later agent session can find it. -// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so -// console-dir there is a stable place to look: the next skill that offers the -// console points its agent at the file rather than making it search the skill -// install dirs again. Written by `open` alone, which starts every session: a -// `wait` or a `post` every few seconds need not rewrite it each time. -function leavePointer() { - try { - ensureDir(HOME_DIR); - fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n"); - } catch { - /* a pointer we cannot leave costs nothing */ - } -} - -async function cmdOpen() { - trace("open: start"); - leavePointer(); - const { project, worktree, branch } = repoRoots(); - reapHandles(project); - trace("open: project found"); - - let sid = args.resume || args.session; - let dir; - let state; - // A new skill run for the meter: a fresh open, or a resume into another workflow. - let launched = true; - // Everything `open` does to a stored state, as a step it can take twice: - // once now, on the read below, so a bad payload is refused before anything - // starts, and again on a fresh read under the state lock when it writes, so - // a send the person made in between is kept rather than written over. - let reshape = (s) => s; - - if (sid) { - sid = path.basename(sid); - dir = sessionDir(sid); - if (!fs.existsSync(dir)) die(`no session "${sid}" to resume`, 1); - state = readJson(path.join(dir, "state.json")); - if (!state) die(`session "${sid}" has no state`, 1); - // A resume can also be a hand-off: the dashboard launches another skill - // into its own session, and the first thing that skill needs is for the - // page to stop being a dashboard. Letting the flags restate these fields - // on resume means one command both reuses the server and turns the page, - // rather than a resume plus a whole extra post. - const switching = args.workflow && args.workflow !== state.workflow; - launched = Boolean(switching); - // Going through the dashboard is a fresh start: a skill launched from - // the menu gets a clean page, not the last skill's questions and tabs - // under its own name. The staged draft goes too, since its item ids - // belonged to the old questions. A skill run inline from another (a - // quick task's review) never passes the dashboard, so it keeps the page. - const hop = switching && (args.workflow === "dashboard" || state.workflow === "dashboard"); - if (hop) fs.rmSync(path.join(dir, "draft.json"), { force: true }); - reshape = (s) => { - // Resuming takes a pause back down. A paused finish is a bookmark -- - // "saved here, pick it up later" -- and picking it up is exactly what - // this is. Left in place, the page keeps saying PAUSED over every - // question the resumed session asks, because `finish` is a scalar and - // only an explicit `finish: null` patch clears it. A real ending is - // different: re-sharing a finished session's link should still show its - // card, so only a headline that says "paused" comes down. Done before - // --file applies, so a patch can still post a finish of its own. - if (s.finish && /^\s*paused\b/i.test(String(s.finish.headline || ""))) { - delete s.finish; - // The questions still open at the pause were the old session's asks, - // already narrated in the finish body so the next session can name - // them. Whatever the resumed session still needs it asks again, in its - // own words -- kept, the leftovers sit beside the new asks as - // duplicates nobody owns. Settled items stay: they are the record. - s.items = (s.items || []).filter((i) => !isOpen(i)); - // And the topics that only the dropped items lived under, so a new - // item reusing an old topic id does not inherit a stale title. - const liveTopics = new Set(s.items.map((i) => i.topic)); - s.topics = (s.topics || []).filter((t) => liveTopics.has(t.id)); - } - if (hop) { - s = switchWorkflow(s, { - workflow: args.workflow, - title: typeof args.title === "string" ? args.title : path.basename(worktree), - specDir: args.spec, - }); - } else if (switching) s.workflow = args.workflow; - if (args.title) s.title = args.title; - if (args.spec) s.specDir = args.spec; - // Every resume clears the wake-up flag: a server restart, a launch from - // the dashboard, a Back-to-dashboard return. Cleared here rather than by - // the page because the page cannot write state, and a replay on a return - // is exactly what the decision rules out. - delete s.wake; - return s; - }; - } else { - sid = newSessionId(); - // Named, not made: the folder is created once --file has passed, so a - // rejected first payload leaves no empty session behind for nothing to sweep. - dir = sessionDir(sid); - state = blankState({ - sid, - project, - workflow: args.workflow, - // Until the agent knows what the session is about, the folder it runs - // in is the honest name, and it lets `open` go before any thinking. - title: typeof args.title === "string" ? args.title : path.basename(worktree), - specDir: args.spec, - }); - // Only a freshly opened dashboard plays Planny's wake-up. - if (args.workflow === "dashboard") state.wake = true; - } - - // A first payload's meter and folder reports, as `post` takes them: checked - // now, before anything is written, and appended once the launch is. - let openRun; - let openIssue; - let patch = null; - if (args.file) { - patch = readJson(path.resolve(args.file)); - if (!patch) die(`could not read --file ${args.file} as JSON`, 2); - ({ run: openRun, folderIssue: openIssue } = patch); - delete patch.run; - delete patch.folderIssue; - } - const base = reshape; - const settle = (s) => { - s = base(s); - // On every open, so a resume from another worktree refreshes both. - s.worktree = worktree; - s.branch = branch; - return s; - }; - reshape = (s) => (patch ? applyPatch(settle(s), patch) : settle(s)); - state = settle(state); - if (patch) { - ledgerFromPost(dir, openRun, openIssue, state.workflow); - try { - state = applyPatch(state, patch); - } catch (e) { - die(e.message, 3); - } - const problems = validate(state); - if (problems.length) return failValidation(problems); - } - ensureDir(dir); - - // A fresh session needs a fresh server, and a server is a whole Node boot: - // the slowest thing `open` does, bar the browser. Start both now, before - // the scan and the state write, so their start-up runs alongside them - // instead of after. The server does look at the state as it boots, and on - // a fresh session finds none yet: it takes the worktree from its command - // line, not from the state, and picks the state up on its first request or - // poll tick. No page can reach it before it is listening, and the state is - // on disk long before a browser gets there. - const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null; - const reusable = existing && pidAlive(existing.pid) ? healthOk(existing) : Promise.resolve(false); - let boot = null; - if (!existing) boot = await startServer(project, worktree, sid, dir); - - // The dashboard's spec picker reads its inventory straight off the session - // state, so the scan belongs to `open` rather than to the agent: filesystem - // facts, recomputed every time the session becomes (or stays) a dashboard, - // never something a model has to remember to fetch. Rooted at the worktree's - // 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; - - // Under the state lock, which a send on the page takes too: the result and - // the state are read fresh here and the state is rebuilt from that read, so - // nothing the person sent since the read above is lost or stamped over. - let carried = false; - let written; - try { - written = updateState(dir, (fresh) => { - const next = fresh ? reshape(fresh) : state; - if (scan) next.scan = scan; - - // Clear a result the agent already collected, and ONLY that one. - // - // An unconsumed result is answers a person pressed Send on that nobody has - // picked up yet. Deleting it here is exactly the documented crash-recovery - // case ("your session died, press Send anyway, the next session picks it - // up") and deleting it destroys their work silently. - const resultPath = path.join(dir, "result.json"); - const waiting = readJson(resultPath); - if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true }); - carried = Boolean(waiting && !waiting.consumedAt); - - // Do not stamp over "submitted" either: the phase is how the page knows a - // send is still in flight. - if (!carried) next.phase = "collecting"; - return next; - }); - } catch (e) { - written = { error: e.message }; - } - if (!written || written.error) { - // A server just started for this state would only serve a page that never starts. - if (boot) boot.kill(); - die(`could not write the session state: ${written ? written.error : "unknown"}`, 1); - } - state = written.state; - appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] }); - // A new agent conversation has been told nothing yet (FR-6). - try { - resetSubagentCursor(dir); - } catch {} - trace("open: state written"); - - // Dashboard launches are recorded too (they score nothing), so the folder - // issues the page shows reset with every skill run. Never fatal: the meter - // is advice, and the page must not wait on it. - try { - if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow }); - for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line); - } catch {} - const workspace = workspaceOnOpen(dir, worktree, state.specDir); - - // Month-old sessions and scratch files: listed before the print so the - // agent can see what went, removed after it so the page waits for nothing. - // 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 swept = - sweptSessions.length || sweptScratch.length - ? { swept: { sessions: sweptSessions, scratch: sweptScratch } } - : {}; - const sweep = () => { - sweepUploads(SESSIONS_DIR, Date.now(), UPLOAD_MAX_AGE_MS, sid).catch(() => {}); - removeSessions(SESSIONS_DIR, sweptSessions).catch(() => {}); - removeScratch(HOME_DIR, sweptScratch).catch(() => {}); - }; - - // A standing instruction the new agent is owed, as `subagents` and a - // `reply` holding only its lines; neither key when nothing is owed. - const subagentsOwed = () => { - awaitSubagentSync(dir, state.workflow); - const [out, cursor] = withSubagents(dir, { reply: "" }); - return [out.subagents ? out : {}, cursor]; - }; - - // Reuse a live server if one is already serving this session. - if (existing && (await reusable)) { - if (!args["no-open"]) openBrowser(existing.url); - const [owed, subCursor] = subagentsOwed(); - print({ - ok: true, - sid, - session: dir, - url: existing.url, - reused: true, - pendingResult: carried, - terminalLine: terminalLine(existing.url), - workspace, - ...owed, - ...swept, - ...remoteWarning(), - }); - advanceSubagents(dir, subCursor); - sweep(); - return; - } - - // A handle whose pid is alive but is not ours (the pid was reused) leaves - // this for last: nothing could be started until that was known. - let started = boot || (await startServer(project, worktree, sid, dir)); - let handle = await awaitHandle(started); - if (!handle && started.handoff) { - // The handover went wrong somewhere (a platform that will not pass the - // socket, a server that died taking it). Once more the old way, where - // the server binds its own port: slower, and certain. - started.kill(); - started = await startServer(project, worktree, sid, dir, { handoff: false }); - handle = await awaitHandle(started); - } - if (!handle) { - const log = tail(path.join(dir, "server.log"), 12); - die(`the console server did not start within 8s.\n${log}`, 1); - } - trace("open: server listening"); - // Unref'd, or the cap itself would hold the process open for its full span. - await Promise.race([started.released, new Promise((r) => setTimeout(r, 2000).unref())]); - trace("open: socket handed over"); - - // The early tab went to the port `open` bound. If the server ended up - // anywhere else, that tab is a dead end, so send the browser to the real one. - if (!args["no-open"] && handle.url !== started.opened) openBrowser(handle.url); - const remote = remoteWarning(); - const notes = []; - if (remote.note) notes.push(remote.note); - if (carried) notes.push("Answers are already waiting. Run `wait` to collect them."); - const [owed, subCursor] = subagentsOwed(); - print({ - ok: true, - sid, - session: dir, - url: handle.url, - port: handle.port, - pid: handle.pid, - pendingResult: carried, - terminalLine: terminalLine(handle.url), - workspace, - ...owed, - ...swept, - ...(remote.remote ? { remote: remote.remote } : {}), - ...(notes.length ? { note: notes.join(" ") } : {}), - }); - advanceSubagents(dir, subCursor); - // After the print, never before it: the page and the link wait for nothing. - sweep(); -} - -/** - * The workspace as `open` hands it to the agent, and the cursor seeded to - * match: the agent now has the whole list, so no change up to here is owed. - * Read-only on workspace.json, which only the server writes; on a fresh - * session the server has not made it yet, so what was remembered for this - * folder and spec stands in, the same list the server is about to make. - */ -function workspaceOnOpen(dir, worktree, specDir) { - const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry); - const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id); - try { - writeWorkspaceCursor(dir, ws.version || 0); - } catch {} - return workspaceForAgent({ ...ws, missing }); -} - -function isFolder(p) { - try { - return fs.statSync(p).isDirectory(); - } catch { - return false; - } -} - -/** - * Start a detached server for the session, and the browser with it. - * - * The browser is the slowest thing in the whole start: from `start ` to - * its first request is most of a second on Windows, far longer than the - * server takes to boot. So the port is bound HERE, the link exists while the - * server is still booting, and the browser is sent at once. The bound socket - * is then handed to the server over an IPC channel; a request that arrives - * before the handover waits in the socket's queue, and one this process - * happened to accept is passed across as a socket of its own. Nothing the - * browser sends is refused or lost on the way. - * - * The order is timed. The server is spawned first, because its boot is the - * longest step the agent waits on. The bind comes next and overlaps that - * boot: a process's first listen() blocks for ~50ms on Windows while the - * socket stack loads, which is time the server spends booting anyway. - */ -async function startServer(project, worktree, sid, dir, { handoff = true } = {}) { - const token = newToken(); - const handlePath = handleFile(project, sid); - ensureDir(path.dirname(handlePath)); - fs.rmSync(handlePath, { force: true }); - - const logFd = fs.openSync(path.join(dir, "server.log"), "a"); - const child = spawn( - process.execPath, - [ - path.join(HERE, "server.mjs"), - // Always `--flag=value`, never two words: a base64url token can start - // with "--", and parseArgs would read it as the next flag and leave the - // server with `token: true`. The paths get the same form for the same reason. - `--session=${dir}`, - `--token=${token}`, - `--project=${project}`, - // The checkout the session runs in, which the state does not hold yet - // on a fresh open. See WORKTREE in server.mjs. - `--worktree=${worktree}`, - ...(handoff ? ["--handoff"] : []), - ...(args["idle-ms"] ? [`--idle-ms=${args["idle-ms"]}`] : []), - ], - { - // Detached, because harness-managed background tasks get killed at - // assorted timeouts and on compaction, which would take the human's - // half-finished answers with them. Detached processes are immune. - detached: true, - // Redirecting stdio to a file is what lets the child outlive us. The - // IPC channel is only for the handover, and is closed straight after. - stdio: ["ignore", logFd, logFd, ...(handoff ? ["ipc"] : [])], - // windowsHide defaults to FALSE, and `detached` on Windows gives the - // child its own console window which "once enabled, cannot be disabled". - // Omit this and every handoff flashes a black box at the user. - windowsHide: true, - } - ); - fs.closeSync(logFd); - let exited = false; - child.on("exit", () => (exited = true)); - child.on("error", () => (exited = true)); - trace("open: server spawned"); - - let opened = null; - let released = Promise.resolve(); - if (handoff) { - const pre = await bindLoopback(); - trace("open: port bound"); - // No socket to give (the bind failed): the server binds its own, and the - // channel is let go once it has. - released = handOff(child, pre); - if (pre && !args["no-open"]) opened = `http://127.0.0.1:${pre.address().port}/s/${token}/`; - } else child.unref(); - // Each spawn blocks for a moment (tens of ms for cmd.exe on Windows), so - // the browser's comes after the server's: the server's boot is what the - // agent waits on, and the browser's lead is most of a second regardless. - if (opened) { - openBrowser(opened); - trace("open: browser sent"); - } - return { - handlePath, - handoff, - opened, - released, - dead: () => exited, - kill: () => { - try { - child.kill(); - } catch {} - }, - }; -} - -// Learn the port by waiting for the handle file, not by parsing stdout: -// stdout went to the log file, and the file handshake is race-free and is -// the same code path the reap sweep uses. Checked every 10ms: the file is -// tiny, and a coarse tick here is dead time added to every first paint. -// Null when the server died first, or never showed up. -async function awaitHandle(started) { - const deadline = Date.now() + 8000; - while (Date.now() < deadline) { - const handle = readJson(started.handlePath); - if (handle && handle.url) return handle; - if (started.dead()) return null; - await new Promise((r) => setTimeout(r, 10)); - } - return null; -} - -function failValidation(problems) { - process.stderr.write("console: the payload was rejected, nothing was written.\n"); - for (const p of problems) process.stderr.write(" - " + p + "\n"); - // exitCode, not exit(): the agent has to read these lines to fix the patch, - // and process.exit() can truncate a pipe Node has not flushed. - process.exitCode = 3; -} - -/* ----------------------------------------------------------------- post */ - -function cmdPost() { - const dir = mustSession(); - const file = args.file; - if (!file) die("post needs --file ", 2); - const patch = readJson(path.resolve(file)); - if (!patch) die(`could not read --file ${file} as JSON`, 2); - - const statePath = path.join(dir, "state.json"); - const before = readJson(statePath); - if (!before) die("that session has no state", 1); - - // Meter and folder reports go to the ledger, never into state.json. Checked - // here, before anything is written: a rejected post appends nothing. - const { run, folderIssue } = patch; - delete patch.run; - delete patch.folderIssue; - const ledgerLines = ledgerFromPost(dir, run, folderIssue, before.workflow); - - // The patch is applied to a fresh read under the state lock, never to the - // read above: a send the person made in between is in the file, and a write - // built on the older read would take it away. Nothing in here may exit, so - // the lock is always let go; a refusal is carried out and reported after. - let refused = null; - let problems = []; - let written; - try { - written = updateState(dir, (fresh) => { - if (!fresh) { - refused = ["that session has no state", 1]; - return null; - } - let next; - try { - next = applyPatch(fresh, patch); - } catch (e) { - refused = [e.message, 3]; - return null; - } - problems = validate(next); - if (!problems.length && patch.chat) problems = validateChat(next, readChat(dir)); - return problems.length ? null : next; - }); - } catch (e) { - die(e.message, 1); - } - if (refused) die(...refused); - if (problems.length) return failValidation(problems); - const next = written.state; - - for (const line of ledgerLines) appendLedger(dir, line); - // A build scores its tasks as it clears them (meter.js, PROGRESS_WORKFLOWS), - // after any `run` in the same post, so a phase finished here ends its count. - if (patch.headline && typeof patch.headline === "object") { - const ledger = readLedger(dir); - const progress = progressEntry(ledger, lastLaunchId(ledger), next.workflow, patch.headline.cleared); - if (progress) appendLedger(dir, progress); - } - appendEvent(dir, { type: "post", items: (patch.items || []).length }); - - const open = next.items.filter((i) => isOpen(i) && i.required !== false).length; - // Only a live server's link: no handle, no line, never a dead link. - const handle = listHandles(projectRoot()).find((h) => h.sid === path.basename(dir)); - print({ - ok: true, - items: next.items.length, - open, - phase: next.phase, - ...unansweredNote(dir, next), - ...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}), - }); -} - -/** - * The ledger lines a post's `run` and `folderIssue` stand for, or exit 3 on - * the first bad one. Ids are scoped by the skill run in progress, so the same - * `run` posted twice counts once, and `phase-2` in one Implement run never - * collides with `phase-2` in the next. - */ -function ledgerFromPost(dir, run, issue, workflow) { - if (run === undefined && issue === undefined) return []; - const launch = lastLaunchId(readLedger(dir)); - const lines = []; - if (run !== undefined) { - const event = run && typeof run === "object" ? run.event : undefined; - if (!RUN_EVENTS.has(event)) die(`run: unknown event "${event}"`, 3); - if (typeof run.id !== "string" || !run.id.trim()) die("run: id required", 3); - if (run.tasks !== undefined) { - if (!TASK_EVENTS.has(event)) die(`run: tasks only goes with ${[...TASK_EVENTS].join(" or ")}`, 3); - if (!isTaskCount(run.tasks)) die(`run: tasks must be a whole number from 1 to ${MAX_TASKS}`, 3); - } - lines.push({ kind: "run", id: `${launch}:${run.id}`, event, workflow, ...(run.tasks !== undefined ? { tasks: run.tasks } : {}) }); - } - if (issue !== undefined) { - const text = (v) => typeof v === "string" && v.trim() !== ""; - const ok = - issue && typeof issue === "object" && text(issue.name) && text(issue.reason) && (issue.hint === undefined || text(issue.hint)); - if (!ok) die("folderIssue must be { name, reason, hint? }, each a non-empty string", 3); - const problems = proseProblems(JSON.stringify([issue.reason, issue.hint || ""]), "folderIssue"); - if (problems.length) die(problems.join("\n "), 3); - lines.push({ - kind: "folder-issue", - id: `${launch}:${issue.name}`, - name: issue.name, - reason: issue.reason, - ...(issue.hint ? { hint: issue.hint } : {}), - }); - } - return lines; -} - -/* ----------------------------------------------------------------- wait */ - -async function cmdWait() { - const dir = mustSession(); - // "240s" reads as 240. A --seconds with no number in it at all would make - // the deadline NaN, and the slice would end at once with exit 10: a busy - // loop, not a wait. So that is refused rather than guessed at. - const given = args.seconds; - const asked = typeof given === "string" ? Number.parseFloat(given) : NaN; - if (given !== undefined && !Number.isFinite(asked)) { - die(`--seconds must be a number, got "${args.seconds}"`, 2); - } - const seconds = Math.max(5, given === undefined ? 240 : asked); - const sid = path.basename(dir); - const project = projectRoot(); - const resultPath = path.join(dir, "result.json"); - const chatPath = path.join(dir, CHAT_FILE); - const deadline = Date.now() + seconds * 1000; - const pendingChat = () => deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {})); - - // A result may already be sitting there: the person can finish the form even - // when the agent's session died, and a fresh agent picks it up here. - const liveUrl = () => listHandles(project).find((h) => h.sid === sid)?.url || ""; - const existing = readJson(resultPath); - if (existing && !existing.consumedAt) return consume(dir, resultPath, existing, liveUrl(), pendingChat()); - const earlyChat = pendingChat(); - if (earlyChat.length) return deliverChat(dir, sid, earlyChat, liveUrl()); - - // A stat every 50ms, and a read only when the file has moved. The old tick - // was a full read and parse every 400ms, which put up to 0.4s between the - // person pressing Send and the agent starting on it, on every single send. - let healthAt = 0; - // A busy server (right after a post, say) can miss one health check without - // being gone. Only a missing handle or dead pid is proof at once; a server - // that merely does not answer must fail three checks in a row, each with a - // longer look, before the slice ends with exit 20. - let healthMisses = 0; - // Null, not the current stamp: a result written between the check above and - // this line would otherwise read as already seen and wait out the slice. - let seen = null; - let chatSeen = null; - while (Date.now() < deadline) { - const stamp = fileStamp(resultPath); - if (stamp && stamp !== seen) { - const result = readJson(resultPath); - if (result && !result.consumedAt) return consume(dir, resultPath, result, liveUrl(), pendingChat()); - // Unreadable for a moment (a lock, a scanner): look again next tick. - seen = result ? stamp : null; - } - - // The chat inbox beside it, on the same tick: a Quick question ends the - // slice as surely as a card send does. - const chatStamp = fileStamp(chatPath); - if (chatStamp !== chatSeen) { - chatSeen = chatStamp; - const entries = pendingChat(); - if (entries.length) return deliverChat(dir, sid, entries, liveUrl()); - } - - if (Date.now() - healthAt > 5000) { - healthAt = Date.now(); - const handle = listHandles(project).find((h) => h.sid === sid); - if (!handle || !pidAlive(handle.pid)) { - print(serverGone(sid)); - process.exitCode = 20; - return; - } - if (await healthOk(handle, 4000)) healthMisses = 0; - else if (++healthMisses >= 3) { - print(serverGone(sid)); - process.exitCode = 20; - return; - } else healthAt = Date.now() - 3000; // look again in about 2s, not 5s - } - sleepSync(50); - } - - const state = readJson(path.join(dir, "state.json")) || {}; - const items = (state.items || []).filter((i) => i.required !== false); - const answered = items.filter((i) => !isOpen(i)).length; - const draft = readJson(path.join(dir, "draft.json"), {}); - const staged = Object.keys(draft.staged || {}).length; - const handle = listHandles(project).find((h) => h.sid === sid); - - print({ - status: "waiting", - sid, - elapsed: fmtMs(Date.now() - Date.parse(state.created || nowIso())), - answered, - total: items.length, - staged, - url: handle ? handle.url : "", - message: "Waiting on your answer in the web console", - next: "NOT FINISHED, do not end your turn or write a summary: relay the message in one line, then run this same wait command again right now. Repeat until the exit code is not 10.", - pendingChat: 0, - ...unansweredNote(dir, state), - // A workspace change alone never ends a slice: it rides on the next send. - pendingWorkspace: pendingWorkspaceChanges(dir).length, - ...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}), - }); - process.exitCode = 10; -} - -// Quick questions already handed over with no reply yet. Always empty when all are answered. -function unansweredNote(dir, state) { - const seqs = unansweredChat(dir, state); - return seqs.length - ? { unansweredChat: seqs, warning: "Quick questions " + seqs.join(", ") + " have no reply yet and the page still shows them as pending. Reply to each now (chat.replies, re = seq): do what was asked when you can, or say why you will not." } - : {}; -} - -function serverGone(sid) { - return { - status: "server-gone", - sid, - message: "The console server is not running. Start it again with `open --resume --no-open`, then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.", - }; -} - -// Quick questions and nothing else: an ordinary exit 0 with no card actions. -function deliverChat(dir, sid, entries, url) { - const [withWs, changes] = withWorkspace(dir, { - type: "chat", - at: nowIso(), - sid, - actions: [], - chat: entries, - reply: chatReplyLines(entries), - }); - const [out, subCursor] = withSubagents(dir, withWs); - print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) }); - advanceCursor(dir, entries); - advanceWorkspace(dir, changes); - advanceSubagents(dir, subCursor); - process.exitCode = 0; -} - -// The workspace changes the agent is owed, added to what it is about to read: -// the list as `workspace`, and one line each at the end of `reply`. -function withWorkspace(dir, out) { - const changes = pendingWorkspaceChanges(dir); - if (!changes.length) return [out, changes]; - const reply = [out.reply, ...changes.map(changeLine)].filter(Boolean).join("\n"); - return [{ ...out, workspace: changes, reply }, changes]; -} - -// Print first, then this, as with the chat cursor: a kill in between can only -// hand the same change over again, never skip one. -function advanceWorkspace(dir, changes) { - if (!changes.length) return; - try { - writeWorkspaceCursor(dir, Math.max(...changes.map((c) => c.version))); - } catch {} -} - -// The server rewrites the session's setting for a new workflow only once its -// watcher sees the state `open` just wrote, so a launch or hop that read the -// file at once would find the old workflow's and owe the agent nothing until -// its next pickup. Give the server a moment to catch up instead, never -// writing the file ourselves (FR-7). A session with no setting file at all is -// an older server, which never writes one: a short look, not the full wait. -const SUBAGENT_SYNC_WAIT_MS = 1500; -const SUBAGENT_SYNC_MISSING_MS = 250; -function awaitSubagentSync(dir, workflow) { - if (!offered(workflow)) return; - const start = Date.now(); - for (;;) { - const setting = readSubagentSetting(dir); - if (setting && setting.workflow === workflow) return; - const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS; - if (Date.now() - start >= budget) return; - sleepSync(25); - } -} - -// The Subagents switch the agent is owed, added to what it is about to read: -// the setting as `subagents`, and its lines last in `reply`, after card lines, -// Quick questions and Workspace lines (FR-9). Read from the session's own -// setting file only, which only the server writes (FR-7). A setting for -// another workflow is the server not having caught up with a hop yet: it -// rides on the next pickup instead. -function withSubagents(dir, out) { - const setting = readSubagentSetting(dir); - if (!setting) return [out, null]; - const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow; - if (setting.workflow !== workflow) return [out, null]; - const block = blockFor(setting, readSubagentCursor(dir)); - if (!block) return [out, null]; - const reply = [out.reply, ...block.lines].filter(Boolean).join("\n"); - return [{ ...out, subagents: block.field, reply }, block.cursor]; -} - -// After the print, like advanceWorkspace(): a kill in between repeats the -// block at the next pickup, never loses it. -function advanceSubagents(dir, cursor) { - if (!cursor) return; - try { - writeSubagentCursor(dir, cursor); - } catch {} -} - -// Print first, then this, exactly as consume() stamps a result: a kill in -// between can only hand the same chat over again, and collectChat() drops -// anything that already has a reply. -function advanceCursor(dir, entries) { - if (!entries.length) return; - try { - writeCursor(dir, Math.max(...entries.map((e) => e.seq))); - } catch {} - appendEvent(dir, { type: "chat-collect", count: entries.length }); -} - -/* ----------------------------------------------------------------- chat */ - -// The instant check a build makes between tasks. Never sleeps, and never -// touches result.json: card sends stay with `wait`. -async function cmdChat() { - const dir = mustSession(); - const sid = path.basename(dir); - const handle = listHandles(projectRoot()).find((h) => h.sid === sid); - if (!handle || !pidAlive(handle.pid) || !(await healthOk(handle))) { - print(serverGone(sid)); - process.exitCode = 20; - return; - } - const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {})); - const changes = pendingWorkspaceChanges(dir); - const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n"); - const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply }); - if (!entries.length && !changes.length && !subCursor) { - print({ chat: [] }); - process.exitCode = 10; - return; - } - print({ ...out, terminalLine: terminalLine(handle.url) }); - advanceCursor(dir, entries); - advanceWorkspace(dir, changes); - advanceSubagents(dir, subCursor); - process.exitCode = 0; -} - -/** - * Hand a result to the agent, then mark it collected. In that order. - * - * Both halves of this guard the same thing, and it matters most in agents other - * than the one this was built against: plenty of harnesses cap a single shell - * call well below a wait slice and kill it at their own timeout. - * - * Printing before stamping means such a kill can only ever cause the NEXT wait - * to hand the same result over twice, which the agent can absorb. The other - * order loses answers someone pressed Send on, silently and permanently. - * - * And exiting by setting `exitCode` rather than calling process.exit(): stdout - * to a pipe is asynchronous, and process.exit() truncates whatever Node has not - * flushed. That would throw the result away just as thoroughly. - */ -function consume(dir, resultPath, result, url, chat = []) { - const collected = { ...result, consumedAt: nowIso() }; - // The link, any chat and any workspace change ride on what the agent reads, - // never on result.json itself. - const withChat = { ...collected, chat }; - if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n"); - const [withWs, changes] = withWorkspace(dir, withChat); - const [out, subCursor] = withSubagents(dir, withWs); - print(url ? { ...out, terminalLine: terminalLine(url) } : out); - try { - writeJsonAtomic(resultPath, collected); - } catch {} - appendEvent(dir, { type: "consume", kind: result.type }); - ledgerAnswers(dir, result); - advanceCursor(dir, chat); - advanceWorkspace(dir, changes); - advanceSubagents(dir, subCursor); - process.exitCode = result.type === "cancel" ? 30 : 0; -} - -// One `answer` ledger line per item the person answered in this send, for -// the session meter. The id carries the send's stamp, so a send collected -// twice (a kill before consumedAt was written) still counts once, while the -// same question answered again in a later round counts again: that round was -// real back-and-forth. Never fatal: the meter is advice. -function ledgerAnswers(dir, result) { - if (!result || result.type !== "submit" || !Array.isArray(result.actions)) return; - try { - const launch = lastLaunchId(readLedger(dir)); - const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow; - const items = new Set(); - for (const a of result.actions) { - if (a && a.type === "answer" && typeof a.i === "string" && !a.i.startsWith("__")) items.add(a.i); - } - for (const i of items) appendLedger(dir, { kind: "answer", id: `${launch}:answer:${result.at}:${i}`, workflow }); - } catch {} -} - -/* ----------------------------------------------------------------- keep */ - -// Copy one of the session's note attachments into specs//attachments/, so -// a spec file can cite it after the session is swept. Run by the agent, never -// the server: the server still never writes into a project. -function cmdKeep() { - const usage = "keep needs --session --upload --name --spec specs/"; - if ([args.upload, args.name, args.spec].some((v) => typeof v !== "string")) die(usage, 2); - const dir = mustSession(); - const state = readJson(path.join(dir, "state.json")); - if (!state) die("that session has no state", 1); - const project = state.project; - - const upload = path.resolve(args.upload); - if (!inside(path.join(dir, "uploads"), upload)) die("upload is not in this session's uploads folder", 3); - const spec = path.resolve(project, args.spec); - const attachments = path.join(spec, "attachments"); - if (!inside(project, spec) || !inside(fs.realpathSync(project), realNearest(attachments))) { - die("spec folder is outside the project", 3); - } - if (!fs.existsSync(upload) || !fs.statSync(upload).isFile()) die("no such upload", 3); - - const file = attachmentName({ upload, name: args.name }); - const target = path.join(attachments, file); - fs.mkdirSync(attachments, { recursive: true }); - let reused = false; - try { - fs.copyFileSync(upload, target, fs.constants.COPYFILE_EXCL); - } catch (err) { - if (err.code !== "EEXIST") throw err; - reused = true; - } - - const slashes = (p) => p.split(path.sep).join("/"); - const linkBase = typeof args.from === "string" ? path.dirname(path.resolve(project, args.from)) : spec; - const kept = slashes(path.relative(project, target)); - print({ - ok: true, - path: kept, - link: slashes(path.relative(linkBase, target)), - image: path.extname(target) === ".jpg", - reused, - }); - appendEvent(dir, { type: "keep", id: path.basename(upload, path.extname(upload)), path: kept }); -} - -// Whether child sits strictly under parent. path.relative handles drive -// letters and POSIX alike; Windows paths fold case, as the server's do. -function inside(parent, child) { - const fold = (s) => (process.platform === "win32" ? s.toLowerCase() : s); - const rel = path.relative(fold(path.resolve(parent)), fold(path.resolve(child))); - return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel); -} - -// p with its nearest existing ancestor's symlinks and junctions resolved, so a -// linked specs/, spec or attachments/ folder cannot carry a copy out of the project. -function realNearest(p) { - let existing = p; - while (!fs.existsSync(existing)) existing = path.dirname(existing); - return path.join(fs.realpathSync(existing), path.relative(existing, p)); -} - -/* --------------------------------------------------------------- forget */ - -// Drop the folder list remembered for one spec (Finalize, once the spec is -// archived). The project's own list and every other spec's are untouched. -function cmdForget() { - if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/", 2); - let spec = specKey(args.spec); - if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/")); - const worktree = repoRoots().worktree; - print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) }); -} - -/* ----------------------------------------------------------------- help */ - -function cmdHelp() { - process.stdout.write(`console.mjs — the Plan2Code web console. A detached server, a loopback -port, and the filesystem as transport; this CLI is the whole agent surface. - - open [--file ] [--workflow ] [--title ""] [--spec ] - [--session|--resume ] [--no-open] [--idle-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 - 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, - path, description?, original? }], missing? }, the folders this - console session reads as context, addressed as @name. The list is - remembered per folder and spec in workspaces.json beside looks.json. - May also print subagents: { state, revision, max, instruction } and - a reply holding only its "Subagents: ..." lines, when a standing - instruction (the page's Subagents switch) is owed to you. - post --session --file - Merge a patch into the session. Prints terminalLine while the - server is live. Exit 3 = rejected; stderr says why. A patch may - carry run: { event, id, tasks? } (session meter points) and folderIssue: - { name, reason, hint? } (a workspace folder you could not read); - both go to the ledger, never into the state. A patch may also - carry helpers: [{ id, title, ask, state, result? }] or one - { id: "alone", alone: true }, merged by id, for the Subagents tab - (see console.md → Standing instructions). - wait --session [--seconds ] - A bounded wait slice, sized below your shell timeout. Exit 0 = the - result is on stdout, 10 = still waiting ("Waiting on your answer - in the web console"; call again), 20 = server gone (open --resume - ), 30 = cancelled. Exits 0 and 10 carry terminalLine. - Exit 0 may carry "chat" (Quick questions); with no card send it - is type: "chat" and actions is empty. Exit 0 may also carry - "workspace" (changes since you last heard, each once, with a - "Workspace: ..." line in reply); exit 10 counts them as - pendingWorkspace, and a change alone never ends a slice. - Exit 0 may also carry "subagents" (a console setting, not typed - by the person, with its "Subagents: ..." lines last in reply); a - setting change alone never ends a slice either. - chat --session - Collect Quick questions, workspace changes and a Subagents - setting change now, never waiting, never touching card sends. - Exit 0 = { chat, workspace, subagents?, reply, terminalLine }, - 10 = none, 20 = server gone. - terminalLine is "→ Look at the web console: ": end your terminal - messages with it during a console session. - keep --session --upload --name --spec specs/ [--from ] - Copy a cited note attachment into specs//attachments/. Prints - { ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or - missing. Paste link as it is. - forget --spec specs/ - Drop the workspace folders remembered for that spec, in this - folder (Finalize, after archiving it). Prints { ok, spec, forgot }; - forgot is false when nothing was saved. Exit 2 = bad usage. - status [--session ] [--all] - One session, or every session belonging to this project. - stop --session | --all - Shut a session's server down. Always post finish first. - - workflows: dashboard · init · init-update · pathfinder · quick-task · plan · - revise-plan · document · implement · implement-review · review · - finalize · handoff - - A session handed to you by the dashboard (a --session id): resume it with - "open --resume --no-open --workflow --title " -- never a - fresh "open", which would strand the page the person is watching. - - The full contract is console.md beside this file. Build sessions - (implement, implement-review, quick-task) also read building.md. -`); -} - -/* --------------------------------------------------------------- status */ - -async function cmdStatus() { - const project = projectRoot(); - if (args.session || args.sid) { - const dir = mustSession(); - const state = readJson(path.join(dir, "state.json")) || {}; - const handle = listHandles(project).find((h) => h.sid === path.basename(dir)); - const result = readJson(path.join(dir, "result.json")); - return print({ - sid: state.sid, - session: dir, - workflow: state.workflow, - title: state.title, - phase: state.phase, - items: (state.items || []).length, - open: (state.items || []).filter(isOpen).length, - url: handle ? handle.url : "", - live: handle ? pidAlive(handle.pid) : false, - pendingResult: Boolean(result && !result.consumedAt), - pendingChat: pendingChatCount(dir, state), - }); - } - - let sids = []; - try { - sids = fs.readdirSync(SESSIONS_DIR).sort().reverse(); - } catch { - return print({ sessions: [] }); - } - const handles = listHandles(project); - const rows = []; - for (const sid of sids.slice(0, Number(args.limit || 20))) { - const dir = sessionDir(sid); - const state = readJson(path.join(dir, "state.json")); - if (!state) continue; - if (!args.all && state.project !== project) continue; - const handle = handles.find((h) => h.sid === sid); - const result = readJson(path.join(dir, "result.json")); - rows.push({ - sid, - workflow: state.workflow, - title: state.title, - phase: state.phase, - created: state.created, - live: handle ? pidAlive(handle.pid) : false, - url: handle ? handle.url : "", - pendingResult: Boolean(result && !result.consumedAt), - pendingChat: pendingChatCount(dir, state), - }); - } - print({ sessions: rows }); -} - -/* ----------------------------------------------------------------- stop */ - -async function cmdStop() { - const project = projectRoot(); - const handles = listHandles(project); - const targets = args.all - ? handles - : handles.filter((h) => h.sid === path.basename(args.session || args.sid || "")); - if (!targets.length) return print({ ok: true, stopped: 0 }); - - let stopped = 0; - let skipped = 0; - for (const h of targets) { - // Identify the process before killing it. A handle file can outlive a - // reboot in the system temp directory, and PIDs get reused; without this - // check `stop --all` can kill an unrelated program that happens to have - // inherited the number. /health returning our own sid is the only proof: - // a live pid and a young handle are not, since a server that died a - // minute ago leaves exactly that behind for any process to inherit. A - // busy server gets a second, longer look, and still has to answer as - // ours; one that does not is left alone, and only its handle goes. - const young = Date.now() - Date.parse(h.startedAt || 0) < MAX_SERVER_LIFE_MS; - const ours = (await healthOk(h)) || (young && pidAlive(h.pid) && (await healthOk(h, 5000))); - if (!ours) { - skipped++; - try { - fs.rmSync(h.handlePath, { force: true }); - } catch {} - continue; - } - try { - process.kill(h.pid); - stopped++; - } catch {} - try { - fs.rmSync(h.handlePath, { force: true }); - } catch {} - } - print({ ok: true, stopped, ...(skipped ? { skippedStaleHandles: skipped } : {}) }); -} - -/* ---------------------------------------------------------------- utils */ - -function mustSession() { - const raw = args.session || args.sid; - if (!raw) die("--session is required", 2); - const dir = fs.existsSync(raw) ? path.resolve(raw) : sessionDir(path.basename(raw)); - if (!fs.existsSync(dir)) die(`no session at ${dir}`, 1); - return dir; -} - -function tail(file, lines) { - try { - return fs.readFileSync(file, "utf8").split("\n").slice(-lines).join("\n"); - } catch { - return "(no server log)"; - } -} - -function fmtMs(ms) { - if (!Number.isFinite(ms) || ms < 0) return "0s"; - const s = Math.round(ms / 1000); - if (s < 60) return `${s}s`; - const m = Math.floor(s / 60); - return `${m}m ${s % 60}s`; -} - -/** - * Best-effort, never fatal. If we cannot open a browser we still printed the URL, - * and the URL is the primary channel. - */ -function openBrowser(url) { - try { - if (process.env.NO_BROWSER || process.env.PLAN2CODE_NO_BROWSER) return; - // Do not try from a place where there is no browser to open. - if (process.env.SSH_CONNECTION || process.env.REMOTE_CONTAINERS) return; - - // A browser of their choosing: a command line, run through the shell, - // with the link appended. The token is base64url, so the quoted link - // carries nothing a shell would read. - const custom = process.env.PLAN2CODE_BROWSER; - if (custom) { - spawn(`${custom} "${url}"`, { shell: true, detached: true, stdio: "ignore", windowsHide: true }).unref(); - return; - } - - const plat = process.platform; - if (plat === "win32") { - // The empty "" is the mandatory window-title argument: omit it and - // `start` treats a quoted URL as the title and opens nothing. - spawn(process.env.COMSPEC || "cmd.exe", ["/d", "/s", "/c", "start", '""', `"${url}"`], { - windowsVerbatimArguments: true, - detached: true, - stdio: "ignore", - windowsHide: true, - }).unref(); - return; - } - if (plat === "darwin") { - spawn("open", [url], { detached: true, stdio: "ignore" }).unref(); - return; - } - // Linux and friends. WSL first: xdg-open there either is absent or opens a - // Linux browser that cannot reach the Windows host. - if (isWsl()) { - const exe = which("wslview") ? "wslview" : "powershell.exe"; - const argsFor = exe === "wslview" ? [url] : ["-NoProfile", "-Command", "Start-Process", `"${url}"`]; - spawn(exe, argsFor, { detached: true, stdio: "ignore" }).unref(); - return; - } - if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return; // headless - spawn(process.env.BROWSER || "xdg-open", [url], { detached: true, stdio: "ignore" }).unref(); - } catch { - /* never fatal */ - } -} - -function isWsl() { - if (process.platform !== "linux") return false; - try { - return /microsoft/i.test(fs.readFileSync("/proc/version", "utf8")); - } catch { - return false; - } -} - -function which(bin) { - const dirs = (process.env.PATH || "").split(path.delimiter); - return dirs.some((d) => { - try { - fs.accessSync(path.join(d, bin), fs.constants.X_OK); - return true; - } catch { - return false; - } - }); -} - -/* ------------------------------------------------------------- dispatch */ - -const COMMANDS = { - open: cmdOpen, - post: cmdPost, - wait: cmdWait, - chat: cmdChat, - keep: cmdKeep, - forget: cmdForget, - status: cmdStatus, - stop: cmdStop, - help: cmdHelp, -}; - -// Say which Node is too old, rather than dying later inside a health check with -// "fetch is not defined". Whatever agent is driving this has to be able to read -// the failure, tell the person in one line, and carry on in the terminal. -const nodeMajor = Number.parseInt(process.versions.node, 10); -if (Number.isFinite(nodeMajor) && nodeMajor < 18) { - process.stderr.write( - `console: needs Node 18 or newer, found ${process.versions.node}. ` + - `Say so in one line and carry on in the terminal.\n` - ); - process.exit(2); -} - -if (!cmd || !Object.hasOwn(COMMANDS, cmd)) { - process.stderr.write( - "console: usage: console.mjs [--session ] [--file ] [--seconds N]\n" - ); - process.exit(2); -} - -// 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"]; -for (const flag of VALUE_FLAGS) { - if (flag in args && typeof args[flag] !== "string") die(`--${flag} needs a value`, 2); -} - -await COMMANDS[cmd](); diff --git a/skills/plan2code-0-pathfinder/references/web-console/lib.mjs b/skills/plan2code-0-pathfinder/references/web-console/lib.mjs deleted file mode 100644 index f4bc3d1..0000000 --- a/skills/plan2code-0-pathfinder/references/web-console/lib.mjs +++ /dev/null @@ -1,2160 +0,0 @@ -// Plan2Code Web Console - shared helpers. -// -// Two directories with deliberately different durability: -// -// runtime handle os.tmpdir()/plan2code-console//.json -// port, pid, token, url. Losing it on reboot is correct, -// because the server is gone too. (Jupyter's jpserver-.json pattern.) -// -// session state ~/.plan2code/console/sessions// -// the request, the human's draft, the result, the event log. -// Deliberately NOT under specs/: that keeps the console clear of -// the metrics confidence scraper and the loop's completion-marker -// parser, and it survives a `git clean`. -// -// Node built-ins only. No build step. - -import fs from "node:fs"; -import net from "node:net"; -import os from "node:os"; -import path from "node:path"; -import crypto from "node:crypto"; -import { execFileSync } from "node:child_process"; -import { fileURLToPath } from "node:url"; - -import { CHAT_LIMIT } from "./public/chat.js"; -import { DOC_TYPES } from "./public/answers.js"; -import { defaultName } from "./public/workspace.js"; -import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js"; - -export const HERE = path.dirname(fileURLToPath(import.meta.url)); -export const PUBLIC_DIR = path.join(HERE, "public"); - -export const HOME_DIR = - process.env.PLAN2CODE_CONSOLE_HOME || - path.join(os.homedir(), ".plan2code", "console"); -export const SESSIONS_DIR = path.join(HOME_DIR, "sessions"); - -// The person's own settings (colors, theme), shared by every session. Lives in -// HOME_DIR rather than beside a session precisely because it is NOT session -// state: a browser ties localStorage to the origin, and the origin carries the -// ephemeral port, so the file under this dir is the only copy of a preference -// that survives the next session's new port. -// Model menus for the `plan2code` launcher. The shipped list (bin/models.json) is the -// authors' and is overwritten by every install; the user's additions (models.json) are -// theirs. The launcher reads both. PLAN2CODE_MODELS_DIR moves them, for tests. -const PLAN2CODE_DIR = process.env.PLAN2CODE_MODELS_DIR || path.join(os.homedir(), ".plan2code"); -export const SHIPPED_MODELS_FILE = path.join(PLAN2CODE_DIR, "bin", "models.json"); -export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json"); - -export const LOOKS_FILE = path.join(HOME_DIR, "looks.json"); - -// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs), -// so every session within the hour reuses one lookup. -export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json"); - -// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a -// test run (or a second sandboxed instance) shares one handle directory with -// the real thing, and `stop --all` reaches outside its own world and kills a -// session someone is actually using. -export const RUNTIME_DIR = process.env.PLAN2CODE_CONSOLE_HOME - ? path.join(process.env.PLAN2CODE_CONSOLE_HOME, "runtime") - : path.join(os.tmpdir(), "plan2code-console"); - -export const SCHEMA = 1; - -/* ------------------------------------------------------------------ args */ - -export function parseArgs(argv) { - const out = { _: [] }; - for (let i = 0; i < argv.length; i++) { - const a = argv[i]; - if (a.startsWith("--")) { - const eq = a.indexOf("="); - if (eq > -1) out[a.slice(2, eq)] = a.slice(eq + 1); - else if (argv[i + 1] && !argv[i + 1].startsWith("--")) out[a.slice(2)] = argv[++i]; - else out[a.slice(2)] = true; - } else out._.push(a); - } - return out; -} - -export function print(obj) { - process.stdout.write(JSON.stringify(obj) + "\n"); -} - -export function die(msg, code = 1) { - process.stderr.write("console: " + msg + "\n"); - process.exit(code); -} - -/* ------------------------------------------------------------------- fs */ - -export function ensureDir(dir) { - fs.mkdirSync(dir, { recursive: true }); - return dir; -} - -// Atomic replace. The waiter polls result.json and WILL land mid-write eventually. -// -// The retry loop is not paranoia: on Windows, antivirus and the search indexer -// hold transient locks that surface as EPERM/EBUSY from rename. It is intermittent, -// unreproducible on demand, and looks exactly like a logic bug. Retry from day one. -export function writeJsonAtomic(file, data) { - const tmp = file + "." + process.pid + ".tmp"; - const body = JSON.stringify(data, null, 2); - let lastErr; - for (let attempt = 0; attempt < 4; attempt++) { - try { - const fd = fs.openSync(tmp, "w"); - try { - fs.writeFileSync(fd, body); - fs.fsyncSync(fd); - } finally { - fs.closeSync(fd); - } - fs.renameSync(tmp, file); - return body; - } catch (err) { - lastErr = err; - if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break; - sleepSync(40 * (attempt + 1)); - } - } - try { - fs.rmSync(tmp, { force: true }); - } catch {} - throw lastErr; -} - -// A cheap "has this file changed?" fingerprint: one stat instead of a read and -// a parse. An atomic write replaces the file, so a new write always moves at -// least one of these. "" for a file that is not there. -export function fileStamp(file) { - try { - const st = fs.statSync(file, { throwIfNoEntry: false }); - return st ? `${st.mtimeMs}:${st.size}:${st.ino}` : ""; - } catch { - return ""; - } -} - -export function readJson(file, fallback = null) { - try { - return JSON.parse(fs.readFileSync(file, "utf8")); - } catch { - return fallback; - } -} - -export function appendEvent(dir, event) { - const line = JSON.stringify({ at: nowIso(), ...event }); - fs.appendFileSync(path.join(dir, "events.ndjson"), line + "\n"); - return line; -} - -/* ----------------------------------------------------- the state lock */ - -// state.json has two writers in two processes: console.mjs (`open` and `post`, -// the agent's side) and the server (`/submit` stamps the phase and records -// what was sent on each item). Each writer reads the file, changes it and -// writes it back, so two of them overlapping lose whichever wrote first. Every -// read-modify-write of state.json therefore runs under this lock, a file -// created with O_EXCL beside it. The sections it guards are a read, a merge -// and a write, milliseconds long, so a lock older than LOCK_STALE_MS, or one -// whose holder has died, is a crash left behind and is broken. The wait runs -// past the stale age, so a writer always gets in eventually. -export const STATE_LOCK_FILE = "state.json.lock"; -const LOCK_STALE_MS = 5000; -const LOCK_WAIT_MS = 7000; - -function lockStale(lock) { - try { - const st = fs.statSync(lock); - if (Date.now() - st.mtimeMs > LOCK_STALE_MS) return true; - const pid = Number.parseInt(fs.readFileSync(lock, "utf8"), 10); - return Number.isInteger(pid) && pid > 0 && pid !== process.pid && !pidAlive(pid); - } catch (err) { - // Gone between the failed create and this look: free, so try again. - return err.code === "ENOENT"; - } -} - -// Run fn while holding the session's state lock, and release it however fn -// ends. fn must not call process.exit(): the release would never run, and the -// next writer would wait out the stale age. -export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) { - const lock = path.join(dir, lockName); - const deadline = Date.now() + LOCK_WAIT_MS; - let fd = null; - for (let attempt = 0; fd === null; attempt++) { - try { - fd = fs.openSync(lock, "wx"); - } catch (err) { - // EPERM / EACCES: on Windows, a lock being deleted still blocks a create. - if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err; - if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`); - if (err.code === "EEXIST" && lockStale(lock)) { - try { - fs.rmSync(lock, { force: true }); - } catch {} - continue; - } - sleepSync(Math.min(5 * (attempt + 1), 50)); - } - } - try { - try { - fs.writeSync(fd, String(process.pid)); - } finally { - fs.closeSync(fd); - } - return fn(); - } finally { - try { - fs.rmSync(lock, { force: true }); - } catch {} - } -} - -// The one way to change state.json: under the lock, read it fresh, hand it to -// fn (null when there is no state yet, with the raw text beside it), and write -// back whatever fn returns. A null return writes nothing. Returns the written -// state and its text, or null. -export function updateState(dir, fn) { - const file = path.join(dir, "state.json"); - return withStateLock(dir, () => { - let text = null; - try { - text = fs.readFileSync(file, "utf8"); - } catch {} - let state = null; - try { - state = text === null ? null : JSON.parse(text); - } catch {} - const next = fn(state, text); - if (!next) return null; - return { state: next, text: writeJsonAtomic(file, next) }; - }); -} - -export function sleepSync(ms) { - // Node built-ins only, and this runs in short one-shot CLI commands. - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); -} - -export function nowIso() { - return new Date().toISOString(); -} - -/* -------------------------------------------------------------- sessions */ - -// Both roots a session needs, found the way git discovers a repository: walk -// up to the first `.git`, follow a `gitdir:` file (a linked worktree or a -// submodule) and its `commondir`. Read off the filesystem rather than asked of -// `git rev-parse`, because on Windows each git process costs 150ms or more -// and `open` sits between the person and their first look at the page. -// -// project the COMMON dir's parent, so every worktree shares a project key -// worktree the checkout's own top level, where its specs/ lives -// branch the checkout's current branch, read from its own git dir's HEAD -// (so a linked worktree reports its own branch, not the main -// checkout's); "" on a detached HEAD or outside a repository -// -// The environment variables that relocate a repository are git's business, -// so when one is set this asks git, exactly as it used to. -const rootsCache = new Map(); - -export function repoRoots(cwd = process.cwd()) { - const key = path.resolve(cwd); - if (!rootsCache.has(key)) rootsCache.set(key, findRoots(key)); - return rootsCache.get(key); -} - -function findRoots(cwd) { - // The native realpath, like git, spells the path out in full: an 8.3 short - // name in the cwd (C:\Users\JUSTIN~1.PAR) must key the same project as the - // long one, or two spellings of one checkout get separate handle spaces. - const real = (p) => { - for (const fn of [fs.realpathSync.native, fs.realpathSync]) { - try { - return fn(p); - } catch {} - } - return p; - }; - if (process.env.GIT_DIR || process.env.GIT_WORK_TREE || process.env.GIT_COMMON_DIR) { - try { - // The branch comes off the git dir's HEAD, as in the walk below, not - // from `--abbrev-ref HEAD`: that fails the whole call on a repository - // with no commits yet, and cannot name an unborn branch anyway. - const [common, top, gitDir] = execFileSync( - "git", - ["rev-parse", "--path-format=absolute", "--git-common-dir", "--show-toplevel", "--absolute-git-dir"], - { cwd, stdio: ["ignore", "pipe", "ignore"], encoding: "utf8" } - ) - .trim() - .split(/\r?\n/); - if (common) { - return { - project: real(path.dirname(common)), - worktree: real(top || cwd), - branch: gitDir ? branchAt(gitDir) : "", - }; - } - } catch {} - return { project: real(cwd), worktree: real(cwd), branch: "" }; - } - for (let dir = cwd; ; ) { - const git = gitDirAt(dir); - if (git) { - const common = readText(path.join(git, "commondir")).trim(); - const commonDir = common ? path.resolve(git, common) : git; - return { project: real(path.dirname(commonDir)), worktree: real(dir), branch: branchAt(git) }; - } - const up = path.dirname(dir); - if (up === dir) return { project: real(cwd), worktree: real(cwd), branch: "" }; - dir = up; - } -} - -// The branch a git dir's HEAD names: `ref: refs/heads/` gives . -// A bare hash (a detached HEAD) or an unreadable file gives "". -function branchAt(gitDir) { - const m = /^ref:\s*refs\/heads\/(.+?)\s*$/m.exec(readText(path.join(gitDir, "HEAD"))); - return m ? m[1] : ""; -} - -// The git dir that `/.git` names, or null when there is no usable one. -// A directory without HEAD is not a repository, and git keeps walking past it. -function gitDirAt(dir) { - const dotGit = path.join(dir, ".git"); - let st; - try { - st = fs.statSync(dotGit); - } catch { - return null; - } - let git = dotGit; - if (st.isFile()) { - const m = /^gitdir:\s*(.+?)\s*$/m.exec(readText(dotGit)); - if (!m) return null; - git = path.resolve(dir, m[1]); - } - return fs.existsSync(path.join(git, "HEAD")) ? git : null; -} - -export function projectRoot(cwd = process.cwd()) { - return repoRoots(cwd).project; -} - -// The worktree's own top level. projectRoot() keys sessions on the COMMON git -// dir so every worktree shares one handle space -- but the specs a dashboard -// shows are the ones on disk under the caller, so the scan roots here instead. -export function worktreeRoot(cwd = process.cwd()) { - return repoRoots(cwd).worktree; -} - -export function cwdHash(dir) { - return crypto.createHash("sha1").update(dir.toLowerCase()).digest("hex").slice(0, 8); -} - -export function newSessionId() { - const d = new Date(); - const p = (n) => String(n).padStart(2, "0"); - const stamp = `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p( - d.getMinutes() - )}${p(d.getSeconds())}`; - return `${stamp}-${crypto.randomBytes(3).toString("hex")}`; -} - -export function sessionDir(sid) { - return path.join(SESSIONS_DIR, sid); -} - -export const UPLOAD_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; -const SESSION_ID = /^\d{8}-\d{6}-[0-9a-f]{6}$/; - -/** - * Remove the attachments uploaded in sessions nobody has touched for a month. - * - * "Touched" is state.json's mtime: every agent post and every page send writes - * it. Only the `uploads` child of a directory shaped like a session id is ever - * removed -- session text (state, drafts, results, events) is never touched -- - * and the path is built from `sessionsDir` plus that validated name, never from - * anything a client sent. Resolves to the sids swept. - */ -export async function sweepUploads(sessionsDir, now, maxAgeMs, skipSid) { - let entries; - try { - entries = await fs.promises.readdir(sessionsDir, { withFileTypes: true }); - } catch { - return []; - } - const swept = []; - for (const entry of entries) { - if (!entry.isDirectory() || entry.name === skipSid || !SESSION_ID.test(entry.name)) continue; - const dir = path.join(sessionsDir, entry.name); - try { - const { mtimeMs } = await fs.promises.stat(path.join(dir, "state.json")); - if (now - mtimeMs <= maxAgeMs) continue; - await fs.promises.rm(path.join(dir, "uploads"), { recursive: true, force: true }); - swept.push(entry.name); - } catch {} - } - return swept; -} - -// The name a kept attachment gets under specs//attachments/: the same upload always yields the same name. -export function attachmentName({ upload, name }) { - const label = typeof name === "string" ? name : ""; - const slug = - label - .slice(0, label.length - path.extname(label).length) - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-+|-+$/g, "") - .slice(0, 40) - .replace(/-+$/, "") || "attachment"; - const base = path.basename(String(upload || "")); - return `${slug}-${base.slice(0, 8)}${path.extname(base).toLowerCase()}`; -} - -// Sessions and their uploads age out on the same clock: a month untouched. -export const SESSION_MAX_AGE_MS = UPLOAD_MAX_AGE_MS; - -const PDF_MAGIC = Buffer.from("%PDF-", "ascii"); - -/** - * Whether an uploaded document is what its extension says: null when it is, - * "type" when it is not. The browser's MIME type and the file name are both - * claims the client makes; only the bytes are evidence. A PDF must open with - * `%PDF-`; a text file must be strict UTF-8 with no NUL byte, which is what - * keeps a renamed binary out. An empty text file is fine. - */ -export function checkDocument(buf, ext) { - const type = Object.prototype.hasOwnProperty.call(DOC_TYPES, ext) ? DOC_TYPES[ext] : null; - if (!type) return "type"; - if (type.kind === "pdf") { - return buf.length >= PDF_MAGIC.length && buf.subarray(0, PDF_MAGIC.length).equals(PDF_MAGIC) ? null : "type"; - } - if (buf.includes(0)) return "type"; - try { - new TextDecoder("utf-8", { fatal: true }).decode(buf); - } catch { - return "type"; - } - return null; -} - -/** - * The sessions nobody has touched for `maxAgeMs`: names of directories shaped - * like a session id (never `skipSid`) whose state.json mtime is that old. - * A directory with no readable state.json is skipped, never guessed at. - * - * Synchronous, because `open` reports the list before it prints and deletes - * after. No exceptions for paused sessions or unread sends: a month-old - * session is gone whole (a locked decision). - */ -export function staleSessions(sessionsDir, now, maxAgeMs, skipSid) { - let entries; - try { - entries = fs.readdirSync(sessionsDir, { withFileTypes: true }); - } catch { - return []; - } - const stale = []; - for (const entry of entries) { - if (!entry.isDirectory() || entry.name === skipSid || !SESSION_ID.test(entry.name)) continue; - try { - const { mtimeMs } = fs.statSync(path.join(sessionsDir, entry.name, "state.json")); - if (now - mtimeMs > maxAgeMs) stale.push(entry.name); - } catch {} - } - return stale; -} - -/** - * Remove whole session directories. Every name is re-checked against the - * session-id pattern, and the path is built only from `sessionsDir` plus that - * validated name. Resolves to the sids actually removed. - */ -export async function removeSessions(sessionsDir, sids) { - const removed = []; - for (const sid of sids) { - if (typeof sid !== "string" || !SESSION_ID.test(sid)) continue; - try { - await fs.promises.rm(path.join(sessionsDir, sid), { recursive: true, force: true }); - removed.push(sid); - } catch {} - } - return removed; -} - -// The console folder's own files that no sweep may ever remove: the person's -// looks, the folders remembered per project and spec, the Subagents switch -// saved per project and workflow, the pointer to this console's directory, -// and the cached release check. -export const PROTECTED_CONSOLE_FILES = new Set([ - "looks.json", - "workspaces.json", - "subagents.json", - "console-dir", - "update-check.json", -]); - -function isScratchName(name) { - return ( - typeof name === "string" && - name === path.basename(name) && - /\.(json|mjs)$/.test(name) && - !PROTECTED_CONSOLE_FILES.has(name) - ); -} - -/** - * Leftover scratch files (agent patches, helper scripts) at the top of the - * console folder: regular files ending in .json or .mjs, never a protected - * name, a directory or a symlink, whose mtime is older than `maxAgeMs`. - */ -export function staleScratch(consoleDir, now, maxAgeMs) { - let entries; - try { - entries = fs.readdirSync(consoleDir, { withFileTypes: true }); - } catch { - return []; - } - const stale = []; - for (const entry of entries) { - if (!entry.isFile() || !isScratchName(entry.name)) continue; - try { - const st = fs.lstatSync(path.join(consoleDir, entry.name)); - if (st.isFile() && now - st.mtimeMs > maxAgeMs) stale.push(entry.name); - } catch {} - } - return stale; -} - -// Every name re-checked against the same rule before anything is removed. -export async function removeScratch(consoleDir, names) { - const removed = []; - for (const name of names) { - if (!isScratchName(name)) continue; - try { - await fs.promises.rm(path.join(consoleDir, name), { force: true }); - removed.push(name); - } catch {} - } - return removed; -} - -/* ------------------------------------------------------------- cleanup */ - -// What User Preferences -> Cleanup never removes. The console folder keeps its -// 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) and the models the person added. -const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]); -export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]); -// 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 `..tmp` between its write and its -// rename -- and removing one mid-write loses another session's change. -export const STRAY_GRACE_MS = 60 * 60 * 1000; - -// Bytes under `p`, never following a symlink: a link counts as itself. -async function diskBytes(p) { - let st; - try { - st = await fs.promises.lstat(p); - } catch { - return 0; - } - if (!st.isDirectory()) return st.size; - let entries; - try { - entries = await fs.promises.readdir(p); - } catch { - return 0; - } - let total = 0; - for (const name of entries) total += await diskBytes(path.join(p, name)); - return total; -} - -// The newest mtime of anything under `p`, never following a symlink. A folder -// counts by its files, since rewriting a file never touches its folder's -// mtime; an empty folder counts by its own. Anything unreadable on the way -// down answers Infinity, so it reads as just touched and stays. -function newestMtime(p) { - let st; - try { - st = fs.lstatSync(p); - } catch { - return Infinity; - } - if (!st.isDirectory()) return st.mtimeMs; - let entries; - try { - entries = fs.readdirSync(p); - } catch { - return Infinity; - } - if (!entries.length) return st.mtimeMs; - let newest = 0; - for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name))); - return newest; -} - -function entryKind(entry) { - if (entry.isSymbolicLink()) return "link"; - return entry.isDirectory() ? "folder" : "file"; -} - -function strayEntries(dir, kept, where, now) { - let entries; - try { - entries = fs.readdirSync(dir, { withFileTypes: true }); - } catch { - return []; - } - const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS; - return entries - .filter((e) => !kept.has(e.name)) - .map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) })) - .filter((e) => settled(e.path)); -} - -/** - * Everything Cleanup would remove, worked out on the server and never taken - * from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule - * `open` sweeps by, plus every file in the folder that old, so a resumed - * session or a saved draft keeps it), anything at the top of the console folder that is - * not kept, and -- only when the console runs from its default home inside - * `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays - * touched within `STRAY_GRACE_MS` are left for a later scan. A - * console running from another home (tests, dev) never reaches ~/.plan2code. - * Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`. - */ -export async function cleanupFindings({ - consoleDir = HOME_DIR, - plan2codeDir = PLAN2CODE_DIR, - now = Date.now(), - maxAgeMs = SESSION_MAX_AGE_MS, - skipSid, -} = {}) { - const found = []; - const sessionsDir = path.join(consoleDir, "sessions"); - for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) { - if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue; - found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) }); - } - found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now)); - if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) { - found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now)); - } - const items = []; - let bytes = 0; - for (const f of found) { - const size = await diskBytes(f.path); - bytes += size; - items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path }); - } - return { items, bytes }; -} - -/** - * Remove what Cleanup found, limited to `ids` the page was shown. The list is - * worked out afresh first and only ids on it are touched, so a name from the - * page is never a path, and anything that stopped qualifying since the scan - * (a session touched again) stays. A link is unlinked, never followed. - * Resolves to `{ removed: [id], bytes, failed: [id] }`. - */ -export async function removeCleanup(ids, opts = {}) { - const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string")); - const { items } = await cleanupFindings(opts); - const removed = []; - const failed = []; - let bytes = 0; - for (const item of items) { - if (!wanted.has(item.id)) continue; - try { - if (item.kind === "link") await fs.promises.unlink(item.path); - else await fs.promises.rm(item.path, { recursive: true, force: true }); - removed.push(item.id); - bytes += item.bytes; - } catch { - failed.push(item.id); - } - } - return { removed, bytes, failed }; -} - -/** - * A spec's overview.md, read-only, or null. `specDir` is relative to `root`; - * the file's realpath must sit inside the root's, so `../`, an absolute path - * and a symlink pointing outside all come back null. - */ -export async function readOverview(root, specDir) { - if (!root || !specDir || typeof specDir !== "string" || path.isAbsolute(specDir)) return null; - try { - const file = path.resolve(root, specDir, "overview.md"); - const [realFile, realRoot] = await Promise.all([fs.promises.realpath(file), fs.promises.realpath(root)]); - // path.relative, not a prefix test: a root of `C:\` or `/` already ends - // in the separator, and `root + sep` would then match nothing at all. - const rel = path.relative(realRoot, realFile); - if (!rel || rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) return null; - return await fs.promises.readFile(realFile, "utf8"); - } catch { - return null; - } -} - -// The line every CLI command hands the agent to end its terminal messages with. -export function terminalLine(url) { - return `→ Look at the web console: ${url}`; -} - -export function runtimeDirFor(project) { - return path.join(RUNTIME_DIR, cwdHash(project)); -} - -export function handleFile(project, sid) { - return path.join(runtimeDirFor(project), sid + ".json"); -} - -export function newToken() { - return crypto.randomBytes(16).toString("base64url"); -} - -/* ---------------------------------------------------------- project scan */ - -// What the dashboard needs to know about the repo it was opened in: whether -// AGENTS.md exists, and where every spec under specs/ sits in the pipeline. -// These are filesystem facts, not agent judgment, so the console computes -// them itself on every `open` (and every resume back to the dashboard) and -// puts them on the session state. The page lights the right cards straight -// from it; the agent keeps only the opinion (note / recommend / details). - -// Where a spec folder stands, named after the step its files are ready for. -// "unrecognized" is a folder with files but no pipeline shape: it launches -// Pathfinder or Plan (the files may be reference docs) but unlocks nothing -// else, exactly like picking no spec at all. -export const SPEC_STATES = new Set([ - "exploring", - "mapped", - "planned", - "documented", - "building", - "built", - "unrecognized", -]); - -function maxMtime(dir, depth = 4, budget = { n: 400 }) { - let best = 0; - if (depth < 0 || budget.n <= 0) return best; - let entries; - try { - entries = fs.readdirSync(dir, { withFileTypes: true }); - } catch { - return best; - } - for (const e of entries) { - if (budget.n-- <= 0) break; - if (e.name.startsWith(".")) continue; - const p = path.join(dir, e.name); - try { - if (e.isDirectory()) best = Math.max(best, maxMtime(p, depth - 1, budget)); - else best = Math.max(best, fs.statSync(p).mtimeMs); - } catch {} - } - return best; -} - -function readText(file) { - try { - return fs.readFileSync(file, "utf8"); - } catch { - return ""; - } -} - -// A spec folder's pipeline position, from its files alone. Furthest artifact -// wins: an overview beats a draft beats a map, so a spec mid-way through two -// stages reports the later one. -function classifySpec(dir, names) { - const has = (re) => names.some((n) => re.test(n)); - const pfDir = path.join(dir, "pathfinder"); - const overview = names.includes("overview.md"); - const phases = names.filter((n) => /^phase-.*\.md$/i.test(n)); - const drafts = names.filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n)); - const planDraft = drafts.length > 0; - const planConv = has(/^PLAN-CONVERSATION.*\.md$/i); - const liveDraft = drafts.filter((n) => !/-prev\.md$/i.test(n)).sort().reverse()[0] || drafts[0]; - const draftStatus = liveDraft - ? (readText(path.join(dir, liveDraft)).match(/\*\*Status:\*\*\s*([^\n]+)/) || [])[1] || "" - : ""; - const resumeAt = draftStatus.match(/Resume at Phase\s*(\d+)/i); - - if (phases.length) { - let done = 0; - let open = 0; - for (const f of phases) { - const text = readText(path.join(dir, f)); - done += (text.match(/^- \[[xX]\]/gm) || []).length; - open += (text.match(/^- \[[ /!]\]/gm) || []).length; - } - const total = done + open; - if (open === 0 && done > 0) return { state: "built", detail: "all tasks done" }; - if (done > 0) return { state: "building", detail: `${done} of ${total} tasks done` }; - return { - state: "documented", - detail: `${phases.length} phase${phases.length === 1 ? "" : "s"}, ${total || "?"} tasks ready`, - }; - } - // An overview with no phase files means Document was interrupted mid-write; - // its next step is the same as a finished plan's. - if (overview) return { state: "planned", detail: "plan drafted" }; - // A draft Pathfinder (or an interrupted Plan) left mid-way says so in its - // Status line: Plan still has phases to run before Document can start. - if (resumeAt) return { state: "mapped", detail: `plan draft, resume at Phase ${resumeAt[1]}` }; - if (planDraft) return { state: "planned", detail: "plan drafted" }; - if (isDir(pfDir)) { - const mapText = readText(path.join(pfDir, "map.md")); - const m = mapText.match(/\*\*Status:\*\*\s*([^\n]+)/); - const status = m ? m[1].replace(/\*+/g, "").trim() : ""; - if (/^cleared/i.test(status)) return { state: "mapped", detail: "all decisions made" }; - let qTotal = 0; - let qDone = 0; - const qDir = path.join(pfDir, "questions"); - try { - for (const q of fs.readdirSync(qDir)) { - if (!q.endsWith(".md")) continue; - qTotal++; - if (/^State:\s*resolved/m.test(readText(path.join(qDir, q)))) qDone++; - } - } catch {} - return { - state: "exploring", - detail: qTotal ? `${qDone} of ${qTotal} decisions made` : "getting started", - }; - } - // A conversation log with no draft is a plan session interrupted before it - // wrote anything: Plan resumes it, same as a cleared map. - if (planConv) return { state: "mapped", detail: "planning in progress" }; - return { state: "unrecognized", detail: "files on disk" }; -} - -function isDir(p) { - try { - return fs.statSync(p).isDirectory(); - } catch { - return false; - } -} - -/** - * Scan /specs into picker entries, most recently touched first. - * `touched` is the newest file mtime inside the folder — last write wins, - * which is the honest reading of "the one you were working on". - */ -export function scanProject(root) { - const specsDir = path.join(root, "specs"); - const specs = []; - let names = []; - try { - names = fs.readdirSync(specsDir); - } catch {} - for (const name of names) { - if (name.startsWith(".")) continue; - const dir = path.join(specsDir, name); - if (!isDir(dir)) continue; - // A spec deleted mid-scan (or unreadable) must not kill `open`: the - // picker just never shows it. - let files; - try { - files = fs.readdirSync(dir); - } catch { - continue; - } - specs.push({ - dir: `specs/${name}`, - name, - ...classifySpec(dir, files), - touched: maxMtime(dir), - }); - } - specs.sort((a, b) => b.touched - a.touched || a.name.localeCompare(b.name)); - return { - at: nowIso(), - hasAgents: fs.existsSync(path.join(root, "AGENTS.md")), - specs, - }; -} - -/* -------------------------------------------------------------- liveness */ - -// PID reuse is real, so process.kill(pid, 0) is necessary but not sufficient. -// The /health check whose sid matches the handle is the authoritative test: -// it is what distinguishes "our server" from "some process that inherited the PID". -export function pidAlive(pid) { - if (!pid) return false; - try { - process.kill(pid, 0); - return true; - } catch (err) { - return err.code === "EPERM"; - } -} - -export async function healthOk(handle, timeoutMs = 1500) { - if (!handle || !handle.url) return false; - const ctrl = new AbortController(); - const timer = setTimeout(() => ctrl.abort(), timeoutMs); - try { - // No explicit Host header: it is a forbidden header name, so fetch drops it - // silently. Requesting 127.0.0.1 directly sets the right one anyway, which - // is what the server's allow-list checks. - const res = await fetch(`http://127.0.0.1:${handle.port}/health`, { signal: ctrl.signal }); - if (!res.ok) return false; - const body = await res.json(); - return body && body.sid === handle.sid; - } catch { - return false; - } finally { - clearTimeout(timer); - } -} - -export function listHandles(project) { - const dir = runtimeDirFor(project); - let names = []; - try { - names = fs.readdirSync(dir).filter((n) => n.endsWith(".json")); - } catch { - return []; - } - return names - .map((n) => readJson(path.join(dir, n))) - .filter(Boolean) - .map((h) => ({ ...h, handlePath: path.join(dir, h.sid + ".json") })); -} - -// Delete handle files whose process is gone. Runs on every `open`, so stale -// entries never accumulate. Windows gives us no reliable shutdown signal, so -// sweeping on startup is how the tmp dir stays clean. -export function reapHandles(project) { - let reaped = 0; - for (const h of listHandles(project)) { - if (!pidAlive(h.pid)) { - try { - fs.rmSync(h.handlePath, { force: true }); - reaped++; - } catch {} - } - } - return reaped; -} - -/* -------------------------------------------------------------- handover */ - -// A loopback socket, bound and listening, for `open` to hand to the server it -// spawns (see startServer in console.mjs). Null if the bind fails. -export function bindLoopback() { - return new Promise((resolve) => { - // pauseOnConnect: a connection that lands here before the handover is - // passed on untouched, not read from. Collected from the first moment, - // so none can arrive before anybody is listening for it. - const srv = net.createServer({ pauseOnConnect: true }); - srv.early = []; - srv.on("connection", (sock) => srv.early.push(sock)); - srv.once("error", () => resolve(null)); - srv.listen(0, "127.0.0.1", () => resolve(srv)); - }); -} - -// Give the bound socket to the server, pass on anything that connected in the -// meantime, then let go of both the socket and the channel. With no socket -// (`pre` null) the server is told to bind its own. Settles either way; a -// server that never takes the socket is caught by whoever waits on its handle. -export function handOff(child, pre) { - const early = pre ? pre.early : []; - return new Promise((resolve) => { - let done = false; - const finish = async () => { - if (done) return; - done = true; - try { - pre?.close(); - } catch {} - // Each passed-on socket is acknowledged by the server once it holds it. - // Letting go of the channel before that drops the socket in transit, - // and with it the browser's first request. - let owed = 0; - let settle = null; - const held = new Promise((r) => (settle = r)); - const onAck = (m) => m && m.type === "conn-held" && --owed <= 0 && settle(); - child.on("message", onAck); - for (const sock of early) { - try { - child.send({ type: "conn" }, sock); - owed++; - } catch {} - } - if (owed > 0 && !child.exitCode) { - await Promise.race([held, new Promise((r) => setTimeout(r, 2000).unref())]); - } - child.off("message", onAck); - try { - child.disconnect(); - } catch {} - child.unref(); - resolve(); - }; - child.on("message", (m) => m && m.type === "listening" && finish()); - child.on("exit", finish); - child.on("error", finish); - try { - if (pre) child.send({ type: "listen", port: pre.address().port }, pre, (err) => err && finish()); - else child.send({ type: "own" }); - } catch { - finish(); - } - }); -} - -/* ----------------------------------------------------------- patch merge */ - -const APPEND_KEYS = new Set(["thread"]); - -function isPlainObject(v) { - return v !== null && typeof v === "object" && !Array.isArray(v); -} - -// Reject prototype-pollution attempts before they reach the merge. -function guard(obj, where) { - if (isPlainObject(obj) && Object.prototype.hasOwnProperty.call(obj, "__proto__")) { - throw new Error(`"__proto__" is not a valid key (in ${where})`); - } - return obj; -} - -function mergeOne(target, patch, where) { - const out = { ...(target || {}) }; - for (const [k, v] of Object.entries(guard(patch, where))) { - if (v === null) delete out[k]; - else if (APPEND_KEYS.has(k) && Array.isArray(v)) out[k] = [...(out[k] || []), ...v]; - else out[k] = v; - } - return out; -} - -// Merge a keyed collection: a known id merges one level, an unknown id appends. -// Named fields are replaced whole; thread appends. -function mergeKeyed(current, patchList, idKey, defaults, where) { - const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : []; - for (const entry of patchList) { - guard(entry, where); - const id = entry[idKey]; - if (!id) throw new Error(`every ${where} entry needs "${idKey}"`); - const i = out.findIndex((x) => x[idKey] === id); - if (entry._delete) { - if (i !== -1) out.splice(i, 1); - } else if (i === -1) out.push(mergeOne({ ...defaults, [idKey]: id }, entry, where)); - else out[i] = mergeOne(out[i], entry, where); - } - return out; -} - -const ITEM_DEFAULTS = { - status: "open", - required: true, - allowOther: true, - options: [], - thread: [], -}; - -// The question a card asks. If a patch rewrites any of these on a known id, it -// is a new question wearing an old id. -const QUESTION_FIELDS = ["kind", "title", "body", "options", "steps", "rows", "summary", "doc", "verdicts"]; - -/** - * Merge item patches by id, and keep a reused id from inheriting the person's - * old answer. `submitted` is the server's record of what they sent to the - * PREVIOUS question. When a patch changes what an item asks and doesn't itself - * settle it, that record (and any stale `answer`) is dropped, so the page shows - * the new question as open instead of "Sent, waiting for Plan2Code" forever. - */ -function dropStaleSubmissions(currentItems, before, patchList) { - const merged = mergeKeyed(currentItems, patchList, "id", ITEM_DEFAULTS, "items"); - for (const entry of patchList) { - const prev = (before || []).find((x) => x.id === entry.id); - if (!prev || (prev.submitted === undefined && prev.answer === undefined)) continue; - const rewritten = QUESTION_FIELDS.some( - (f) => f in entry && JSON.stringify(entry[f]) !== JSON.stringify(prev[f]), - ); - const settles = entry.status === "answered" || entry.status === "skipped" || "answer" in entry; - // A settled question edited in place (a typo in its body) stays settled; only an - // explicit reopen turns it into a new question. - const wasSettled = prev.status === "answered" || prev.status === "skipped"; - // A different kind is never a typo fix: a multi turned confirm is another question. - const kindChanged = "kind" in entry && entry.kind !== prev.kind; - const reopens = entry.status === "open" || entry.status === "reopened" || kindChanged; - if (!rewritten || settles || (wasSettled && !reopens)) continue; - const item = merged.find((x) => x.id === entry.id); - if (wasSettled && !("status" in entry)) item.status = "open"; - if (!("submitted" in entry)) delete item.submitted; - delete item.answer; - } - return merged; -} - -// A thread entry is `{ who, text }`, and the page reads nothing else. Models -// borrow the shape of the replies and doc blocks they also write, so `from` / -// `role` and `md` / `body` / `content` are lifted into place: left as they came, -// each became a "Plan2Code" bubble with nothing in it. An entry with no words -// at all is refused. The person's own notes are recorded by the server when -// they send, so an agent that echoes one back is not shown it twice. -const THREAD_TEXT_KEYS = ["text", "md", "body", "content"]; - -function normalizeThreads(patchList, currentItems) { - return patchList.map((entry) => { - if (!isPlainObject(entry) || entry.thread == null) return entry; - if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`); - const prev = (currentItems || []).find((x) => x && x.id === entry.id); - const said = new Set( - ((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()), - ); - const thread = []; - for (const m of entry.thread) { - if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`); - guard(m, "thread"); - const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim()); - if (!key) { - throw new Error( - `item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "" }; the page shows nothing else.`, - ); - } - const { from, role, md, body, content, ...rest } = m; - const who = (m.who || from || role) === "user" ? "user" : "agent"; - const text = m[key]; - if (who === "user" && said.has(text.trim())) continue; - thread.push({ ...rest, who, text }); - } - return { ...entry, thread }; - }); -} - -const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] }; - -// Blocks merge by id like docs do, so a patch that only settles a block's -// state keeps its text. Blocks left out of the patch stay as they are. -function mergeDocs(current, patchList) { - // A doc's version only moves forward. One going back is a stale or copied - // payload (last phase's progress script, say), and the page would quietly - // show the old content under the new run's name. - for (const entry of patchList) { - if (!isPlainObject(entry) || typeof entry.version !== "number") continue; - const prev = (current || []).find((d) => d && d.id === entry.id); - if (prev && typeof prev.version === "number" && entry.version < prev.version) { - throw new Error( - `doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` + - "Versions only go up: bump it, and check the payload is the current one." - ); - } - } - const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs"); - for (const entry of patchList) { - if (!Array.isArray(entry.blocks)) continue; - const doc = merged.find((d) => d.id === entry.id); - if (!doc) continue; - const prev = (current || []).find((d) => d.id === entry.id); - doc.blocks = mergeKeyed(prev?.blocks, entry.blocks, "id", {}, "blocks"); - } - return merged; -} - -/** - * Apply an agent patch to the session state. - * - * Scalars replace, `null` deletes, `agent`/`headline` merge one level, - * `items`/`topics`/`docs` merge by id, and so do a doc's `blocks`. The agent - * sends only what changed: a whole-file rewrite would put the entire state - * back into the agent's context on every turn, and the state grows with the - * session. - */ -export function applyPatch(state, patch) { - guard(patch, "patch"); - patch = liftActivity(patch); - const next = { ...state }; - for (const [k, v] of Object.entries(patch)) { - if (v === null) { - delete next[k]; - continue; - } - switch (k) { - case "agent": - case "headline": - next[k] = mergeOne(next[k], v, k); - break; - case "items": - if (!Array.isArray(v)) throw new Error('"items" must be an array'); - next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items)); - break; - case "topics": - if (!Array.isArray(v)) throw new Error('"topics" must be an array'); - next.topics = mergeKeyed(next.topics, v, "id", {}, "topics"); - break; - case "helpers": - // The agent's report of its helpers, for the page's Subagents tab. - // Only `post` writes it; the server's /submit never touches it. - if (!Array.isArray(v)) throw new Error('"helpers" must be an array'); - if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }'); - next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers"); - // A real helper report supersedes the working-alone marker, whether it - // arrives after one or beside one. - if (next.helpers.some((h) => isPlainObject(h) && h.alone !== true)) - next.helpers = next.helpers.filter((h) => !(isPlainObject(h) && h.alone === true)); - break; - case "docs": - if (!Array.isArray(v)) throw new Error('"docs" must be an array'); - next.docs = mergeDocs(next.docs, v); - break; - case "chat": { - // The agent's side of the Quick question chat. The person's side is - // the inbox, which only the server writes; nothing else lives here. - if (!isPlainObject(v)) throw new Error('"chat" must be an object'); - guard(v, "chat"); - const extra = Object.keys(v).filter((key) => key !== "replies"); - if (extra.length) throw new Error(`"chat" only takes "replies" (not ${extra.map((key) => `"${key}"`).join(", ")})`); - const chat = { ...(next.chat || {}) }; - if (v.replies != null) { - if (!Array.isArray(v.replies)) throw new Error('"chat.replies" must be an array'); - chat.replies = mergeKeyed(chat.replies, v.replies, "id", {}, "chat.replies"); - } - next.chat = chat; - break; - } - default: - next[k] = v; - } - } - return stampTimes(state, next); -} - -// `activity` belongs under `agent`, which is the only place the page reads it. -// Sent at the top level it would be stored where nothing looks, and the page -// would sit on its starting screen while the skill works. -function liftActivity(patch) { - if (!Object.prototype.hasOwnProperty.call(patch, "activity")) return patch; - const { activity, ...rest } = patch; - if (rest.agent === null) return rest; - const agent = isPlainObject(rest.agent) ? rest.agent : {}; - return { ...rest, agent: "activity" in agent ? agent : { ...agent, activity } }; -} - -// The agent never writes a timestamp. Models do not reliably know the time, -// and a wrong `since` makes the page's elapsed counters nonsense. -function stampTimes(before, next) { - const now = nowIso(); - if (next.agent) { - const changed = !before.agent || before.agent.status !== next.agent.status; - if (changed && !next.agent.since) next.agent = { ...next.agent, since: now }; - else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now }; - } - if (Array.isArray(next.items)) { - for (const entry of next.items) { - if (Array.isArray(entry.thread)) { - for (const m of entry.thread) if (!m.at) m.at = now; - } - } - } - if (Array.isArray(next.docs)) { - for (const d of next.docs) { - const prev = (before.docs || []).find((x) => x.id === d.id); - if (!prev || prev.version !== d.version) d.at = d.at || now; - } - } - next.updatedAt = now; - return next; -} - -/* --------------------------------------------------------- house rules */ - -export const ITEM_KINDS = new Set([ - "choice", - "multi", - "text", - "confirm", - "recap", - "review", - "checklist", - "menu", - "list", - "notice", -]); - -// grilling.md keeps an explicit do-not-say list: this bookkeeping vocabulary is -// internal and must never reach the human. In the terminal that is a prompt rule -// the model can drift from. Routing through a server makes it mechanical. -const JARGON = [ - /\bgrill(ing|ed)?\b/i, - /\bfrontier\b/i, - /\bfog\b/i, - /\bHITL\b/, - /\bAFK\b/, - /\bdurable\b/i, - /Locked:/, - /Blocked by:/, - /\bState:\s/, -]; - -// The loop parses these out of agent output; pathfinder forbids them under specs/. -const FORBIDDEN_TOKENS = - /\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/; - -// plan2code-metrics scrapes confidence with patterns that do NOT require a -// percent sign, so a bare "Requirements 22" in a rendered doc can poison a run's -// metrics. Keep those four words away from bare numbers. -const METRICS_BAIT = /\b(Requirements?|Feasibility|Integration|Risk)[:\s|]+\d{1,2}\b/; - -// The marker and metrics-bait scan on its own, for agent text that never -// reaches state.json (a post's `run` / `folderIssue`). Problems as sentences. -export function proseProblems(prose, subject = "text") { - const problems = []; - if (FORBIDDEN_TOKENS.test(prose)) { - problems.push(`${subject} contains a loop completion marker (${prose.match(FORBIDDEN_TOKENS)[0]}); the loop scans for these`); - } - if (METRICS_BAIT.test(prose)) { - problems.push( - `${subject} contains "${prose.match(METRICS_BAIT)[0]}" — the metrics collector scrapes that pattern. ` + - `Hyphenate it (Requirements-clarity 22/25) or reword.` - ); - } - return problems; -} - -export const MAX_OPEN_REQUIRED = 3; - -/** - * Validate a merged state before it is written. - * - * Returns an array of human-readable problems. An empty array means the patch - * is good. These checks turn four prose rules into mechanical ones. - */ -export function validate(state) { - const problems = []; - - if (!Array.isArray(state.items)) return ['"items" must be an array']; - - const ids = new Set(); - for (const item of state.items) { - if (!item.id) problems.push("every item needs an id"); - if (ids.has(item.id)) problems.push(`duplicate item id "${item.id}"`); - ids.add(item.id); - - if (!ITEM_KINDS.has(item.kind)) { - problems.push(`item "${item.id}" has unknown kind "${item.kind}" (one of: ${[...ITEM_KINDS].join(", ")})`); - } - if (typeof item.title !== "string" || !item.title.trim()) { - problems.push(`item "${item.id}" needs a plain-English title`); - } else { - for (const re of JARGON) { - if (re.test(item.title)) { - problems.push( - `item "${item.id}" title contains internal vocabulary (${re.source}). Titles are read by people who have never seen this workflow.` - ); - break; - } - } - } - if ((item.kind === "choice" || item.kind === "multi") && !Array.isArray(item.options)) { - problems.push(`item "${item.id}" is a ${item.kind} and needs "options"`); - } - if ((item.kind === "choice" || item.kind === "multi") && Array.isArray(item.options)) { - for (const o of item.options) { - if (!o || typeof o.k !== "string" || !o.k.trim()) { - problems.push(`item "${item.id}" has an option with no "k" (its key, like "A")`); - } else if (typeof o.text !== "string" || !o.text.trim()) { - problems.push( - `item "${item.id}" option "${o.k}" needs "text" (the label) and optionally "detail". Options use "text"/"detail", not "label"/"desc".` - ); - } - } - } - if (item.verdicts != null) { - if (!Array.isArray(item.verdicts) || !item.verdicts.length) { - problems.push(`item "${item.id}" "verdicts" must be a non-empty array of { id, label }`); - } else { - for (const v of item.verdicts) { - if (!v || typeof v.id !== "string" || !v.id.trim()) { - problems.push(`item "${item.id}" has a verdict with no "id"`); - } else if (typeof v.label !== "string" || !v.label.trim()) { - problems.push( - `item "${item.id}" verdict "${v.id}" needs a "label" (the button text). Verdicts use "label", not "text".` - ); - } - } - } - } - if (item.templates != null && (item.kind !== "text" || item.templates !== "idea")) { - problems.push(`item "${item.id}" has "templates": only a text item can carry it, and its only value is "idea".`); - } - // The page compiles it as the person types, and a pattern that does not - // compile throws there, on every keystroke, with nothing on screen to say why. - if (item.pattern != null) { - if (typeof item.pattern !== "string") { - problems.push(`item "${item.id}" "pattern" must be a string holding a JavaScript regular expression`); - } else { - try { - new RegExp(item.pattern); - } catch (e) { - problems.push(`item "${item.id}" "pattern" is not a valid JavaScript regular expression: ${e.message}`); - } - } - } - const recs = (item.options || []).filter((o) => o.recommended); - if (recs.length > 1) problems.push(`item "${item.id}" marks ${recs.length} options recommended; at most one`); - } - - const openRequired = state.items.filter((i) => i.required !== false && isOpen(i)); - if (openRequired.length > MAX_OPEN_REQUIRED) { - problems.push( - `${openRequired.length} questions are open at once. The cap is ${MAX_OPEN_REQUIRED} ` + - `(the ceiling is the person's attention, not the screen's). ` + - `Send the rest after these are answered, or mark some "required": false.` - ); - } - - // The session's own ending. Absent for every session that is still running, - // so only its shape is checked, never its presence. The command is optional: - // a finish with no command is a finished session with nothing left to run, - // and the page points at the dashboard instead of a next step. - const fin = state.finish; - if (fin != null) { - if (typeof fin !== "object" || Array.isArray(fin)) { - problems.push('"finish" must be an object'); - } else { - if (typeof fin.headline !== "string" || !fin.headline.trim()) { - problems.push('"finish" needs a plain-English "headline" saying what just happened'); - } - if (fin.command != null && (typeof fin.command !== "string" || !fin.command.trim())) { - problems.push('"finish.command" must be a non-empty string, or left out when there is nothing to run'); - } else if (fin.command != null && (fin.command.includes("<") || fin.command.includes(">"))) { - // A rendered command is copied and run verbatim. A leftover - // placeholder reaches someone who has no way to know what fills it. - problems.push(`"finish.command" still has a placeholder in it ("${fin.command}"). Fill it in.`); - } - if (fin.console != null && typeof fin.console !== "boolean") { - problems.push('"finish.console" must be true or false (or left out, to follow the command)'); - } - if (fin.dashboard != null && typeof fin.dashboard !== "boolean") { - problems.push('"finish.dashboard" must be true or false (or left out: no dashboard button)'); - } - // The review offer on a finished build: true, or an object carrying the - // button's heading. The heading is read by the person, so it faces the - // same vocabulary check as a title. - if (fin.review != null && typeof fin.review !== "boolean") { - if (typeof fin.review !== "object" || Array.isArray(fin.review)) { - problems.push('"finish.review" must be true, false, or { "label": "..." }'); - } else if (fin.review.label != null) { - if (typeof fin.review.label !== "string") { - problems.push('"finish.review.label" must be a string'); - } else { - const hit = JARGON.find((re) => re.test(fin.review.label)); - if (hit) problems.push(`"finish.review.label" contains internal vocabulary (${hit.source})`); - } - } - } - for (const re of JARGON) { - if (typeof fin.headline === "string" && re.test(fin.headline)) { - problems.push(`"finish.headline" contains internal vocabulary (${re.source})`); - break; - } - } - } - } - - // How long a silence is normal while the agent works (a build task). Bounded, - // because the page stops calling a quiet agent stuck for this long, and a - // huge number would hide a session that really has died. - const quiet = state.agent && state.agent.quietMinutes; - if (quiet != null && (typeof quiet !== "number" || !(quiet > 0) || quiet > 60)) { - problems.push('"agent.quietMinutes" must be a number of minutes between 1 and 60 (or null to clear it)'); - } - if (state.agent && state.agent.activity != null && typeof state.agent.activity !== "string") { - problems.push('"agent.activity" must be a short sentence saying what you are doing'); - } - - const gates = state.items.filter((i) => i.gate && i.gate.authoritative); - if (gates.length > 1) { - problems.push( - `${gates.length} authoritative approval gates are open (${gates - .map((g) => g.id) - .join(", ")}). Only one workflow may own sign-off at a time.` - ); - } - - // Scan what the AGENT wrote, never what the person typed. `submitted` is the - // server's record of an answer someone pressed Send on; if their own words - // happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch - // would be rejected and the session would wedge with no way out. - const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({ - ...rest, - thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread, - })); - const prose = - JSON.stringify(authored) + - JSON.stringify(state.docs || []) + - JSON.stringify(state.finish || {}) + - JSON.stringify(state.menu || {}); - problems.push(...proseProblems(prose)); - - // The agent's report of its helpers: the shape the page draws from - // (subagents.js), then the same prose scan as everything else it writes. - if (state.helpers != null) { - problems.push(...checkHelpers(state.helpers)); - for (const helper of Array.isArray(state.helpers) ? state.helpers : []) { - if (!isPlainObject(helper)) continue; - for (const field of ["title", "ask", "result"]) { - if (typeof helper[field] === "string") { - problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`)); - } - } - } - } - - return problems; -} - -export function isOpen(item) { - return item.status === "open" || item.status === "reopened"; -} - -export function blankState({ sid, workflow, title, project, specDir }) { - return { - schema: SCHEMA, - sid, - workflow: workflow || "pathfinder", - title: title || "Session", - project, - specDir: specDir || "", - created: nowIso(), - phase: "collecting", - agent: { status: "working", since: nowIso(), handled: 0 }, - headline: { stage: "", cleared: 0, total: 0, confidence: "", note: "" }, - topics: [], - items: [], - docs: [], - }; -} - -/** - * A resume that passes through the dashboard (a finished skill going back to - * it, or a launch from its menu) is a new skill taking the page over, so it - * starts from a blank page: the last skill's questions, sections, docs, - * helpers, headline and ending are its record on disk, not the next skill's - * opening. - * Only the session's identity carries across. `workspace.json`, - * `ledger.ndjson` and the cursors live beside `state.json`, so the workspace - * and the meter outlive every hop. - */ -export function switchWorkflow(state, { workflow, title, specDir }) { - return { ...blankState({ sid: state.sid, project: state.project, workflow, title, specDir }), created: state.created }; -} - -/* ------------------------------------------------------- the chat inbox */ - -// The Quick question chat rides its own channel beside the card slot, so the -// two never contend: a chat message never waits on an uncollected card send, -// and a card send never waits on chat. Every file has exactly one writer: -// -// chat.ndjson the server. One JSON line per entry: message / decision / reset. -// chat-cursor.json console.mjs. The last seq the agent was handed. -// state.json console.mjs `post`. The agent's replies, under chat.replies. -// (state.json as a whole has a second writer, the server's -// /submit, so every change to it goes through updateState().) -// -// The Workspace and the session meter follow the same rule, in files that -// switchWorkflow() never touches, so they carry across dashboard hops: -// -// workspace.json the server. Folders, version, change log, missing, remote. -// ledger.ndjson console.mjs. Append-only meter events and folder issues. -// workspace-cursor.json console.mjs. The last workspace version handed to the agent. -// subagents-setting.json the server. The Subagents switch for this session, with its revision. -// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent. -export const CHAT_FILE = "chat.ndjson"; -export const CHAT_CURSOR_FILE = "chat-cursor.json"; -export const WORKSPACE_FILE = "workspace.json"; - -/** - * The inbox's entries with `seq > afterSeq`. A final segment with no newline - * is a line still being written: it is left for the next read, never parsed - * half-way. A line that will not parse is skipped rather than thrown on. - */ -export function readChat(dir, afterSeq = 0) { - return readJsonLines(path.join(dir, CHAT_FILE)).filter((e) => Number.isInteger(e.seq) && e.seq > afterSeq); -} - -// Every whole, parsable object line of an ndjson file, in order. -function readJsonLines(file) { - let text; - try { - text = fs.readFileSync(file, "utf8"); - } catch { - return []; - } - const lines = text.split("\n"); - lines.pop(); // "" after a complete last line, or the half-written one - const out = []; - for (const line of lines) { - if (!line.trim()) continue; - try { - const entry = JSON.parse(line); - if (entry && typeof entry === "object") out.push(entry); - } catch {} - } - return out; -} - -// Single-writer rule: only server.mjs may call this. -export function appendChat(dir, entry) { - const last = readChat(dir).reduce((max, e) => Math.max(max, e.seq), 0); - return appendJsonLine(path.join(dir, CHAT_FILE), { ...entry, seq: last + 1, at: nowIso() }); -} - -// Append one JSON line to an ndjson file, returning what was stored. -function appendJsonLine(file, stored) { - let lead = ""; - try { - const st = fs.statSync(file); - // A fragment left by a crash mid-append must not swallow this line too. - if (st.size > 0) { - const fd = fs.openSync(file, "r"); - try { - const b = Buffer.alloc(1); - fs.readSync(fd, b, 0, 1, st.size - 1); - if (b[0] !== 0x0a) lead = "\n"; - } finally { - fs.closeSync(fd); - } - } - } catch {} - const line = lead + JSON.stringify(stored) + "\n"; - let lastErr; - for (let attempt = 0; attempt < 4; attempt++) { - try { - fs.appendFileSync(file, line); - return stored; - } catch (err) { - lastErr = err; - if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break; - sleepSync(40 * (attempt + 1)); - } - } - throw lastErr; -} - -export function readCursor(dir) { - const saved = readJson(path.join(dir, CHAT_CURSOR_FILE), { seq: 0 }); - const n = Number(saved && saved.seq); - return Number.isInteger(n) && n > 0 ? n : 0; -} - -// Never backwards: a slow collector finishing after a faster one must not -// hand the faster one's entries over again. -export function writeCursor(dir, seq) { - writeJsonAtomic(path.join(dir, CHAT_CURSOR_FILE), { seq: Math.max(readCursor(dir), seq) }); -} - -// The conversation the inbox is on: the one its last reset opened. -export function currentConversation(entries) { - for (let i = entries.length - 1; i >= 0; i--) { - const e = entries[i]; - if (e.kind === "reset") return { conversation: e.conversation, workflow: e.workflow || "", sinceSeq: e.seq }; - } - return { conversation: 0, workflow: "", sinceSeq: 0 }; -} - -// Typed messages only: Approve / Decline and resets never count to the limit. -export function typedCount(entries, conversation) { - return entries.filter((e) => e.kind === "message" && e.conversation === conversation).length; -} - -/** - * The chat block of a page frame: the current conversation's person entries - * from the inbox and the agent's replies from the state, as one list. A reply - * sits straight after the entry it answers; one naming nothing here goes last. - */ -export function chatForFrame(entries, state) { - const { conversation } = currentConversation(entries); - const person = entries - .filter((e) => (e.kind === "message" || e.kind === "decision") && e.conversation === conversation) - .sort((a, b) => a.seq - b.seq); - const replies = (state?.chat?.replies || []).filter((r) => r && r.conversation === conversation); - const messages = []; - const placed = new Set(); - for (const p of person) { - messages.push({ from: "person", ...p }); - replies.forEach((r, i) => { - if (r.re !== p.seq) return; - messages.push({ from: "agent", ...r }); - placed.add(i); - }); - } - replies.forEach((r, i) => placed.has(i) || messages.push({ from: "agent", ...r })); - return { conversation, messages, typed: typedCount(entries, conversation), limit: CHAT_LIMIT }; -} - -/** - * What the agent has not been handed yet: entries past the cursor, minus any - * message or decision that already has a reply. The second half is what keeps - * a lost cursor from ever causing a second answer. Resets always go through. - */ -export function collectChat(dir, state) { - const replied = new Set((state?.chat?.replies || []).map((r) => r && r.re)); - return readChat(dir, readCursor(dir)).filter((e) => e.kind === "reset" || !replied.has(e.seq)); -} - -// What is worth handing over: the collected entries once one of them is -// something the person said. A reset alone (every session opens with one) -// waits and rides along with the next message, or `wait` would return on the -// opening line of every session and every first card reply would carry it. -export function deliverableChat(entries) { - return entries.some((e) => e.kind !== "reset") ? entries : []; -} - -// Things the person said that were handed over but never answered. The page keeps -// showing "working on the answer" for each until a reply lands, so the agent is -// told on every post and every wait slice until it has replied (a refusal is a reply). -export function unansweredChat(dir, state) { - const { conversation } = currentConversation(readChat(dir, 0)); - const replied = new Set((state?.chat?.replies || []).map((r) => r && r.re)); - const cursor = readCursor(dir); - return readChat(dir, 0) - .filter((e) => (e.kind === "message" || e.kind === "decision") && e.conversation === conversation) - .filter((e) => e.seq <= cursor && !replied.has(e.seq)) - .map((e) => e.seq); -} - -// How many things the person said are still waiting to be collected. -export function pendingChatCount(dir, state) { - return collectChat(dir, state).filter((e) => e.kind !== "reset").length; -} - -// The chat entries as the lines appended to `reply`, in the note's shape. -// Whatever the person typed is indented past its first line, so only a real -// entry ever starts a line: a typed "Approved: edit p1" must not read as one. -export function chatReplyLines(entries) { - const indent = (s, pad) => String(s).replace(/\r?\n/g, "\n" + pad); - const lines = []; - for (const e of entries) { - if (e.kind === "message") { - lines.push(`Quick question: ${indent(e.text, " ")}`); - if (e.about && e.about.label) lines.push(` About: ${indent(e.about.label, " ")}`); - for (const img of e.images || []) lines.push(` Image: ${img.path} (${img.name})`); - for (const f of e.files || []) lines.push(` File: ${f.path} (${f.name})`); - } else if (e.kind === "decision") { - lines.push(`${e.decision === "approve" ? "Approved" : "Declined"}: edit ${e.re}`); - if (e.text) lines.push(` Note: ${indent(e.text, " ")}`); - } else if (e.kind === "reset") { - lines.push("New conversation started. Treat earlier chat as closed."); - } - } - return lines.join("\n"); -} - -// A project-relative path: no root, no drive letter, no step outside. -function projectRelative(p) { - if (typeof p !== "string" || !p.trim()) return false; - if (/^[\\/]/.test(p) || /^[A-Za-z]:/.test(p)) return false; - return !p.split(/[\\/]/).includes(".."); -} - -function underSpec(file, specDir) { - const norm = (s) => { - const t = s.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, ""); - return process.platform === "win32" ? t.toLowerCase() : t; - }; - const f = norm(file); - const spec = norm(specDir); - return Boolean(spec) && (f === spec || f.startsWith(spec + "/")); -} - -/** - * The house rules for the agent's chat replies, checked against the inbox - * they answer. Same shape as validate(): problems as sentences, [] when fine. - */ -export function validateChat(state, entries) { - const replies = state?.chat?.replies; - if (replies == null) return []; - if (!Array.isArray(replies)) return ['"chat.replies" must be an array']; - const problems = []; - const targets = new Set( - entries.filter((e) => e.kind === "message" || e.kind === "decision").map((e) => e.seq) - ); - const ids = new Set(); - for (const r of replies) { - if (!isPlainObject(r)) { - problems.push("every chat reply must be an object"); - continue; - } - const name = typeof r.id === "string" && r.id.trim() ? r.id : "(no id)"; - if (name === "(no id)") problems.push('every chat reply needs a non-empty string "id"'); - else if (ids.has(r.id)) problems.push(`duplicate chat reply id "${r.id}"`); - ids.add(r.id); - if (!Number.isInteger(r.re) || !targets.has(r.re)) { - problems.push(`chat reply "${name}" needs "re": the seq of the message or decision it answers`); - } - if (!Number.isInteger(r.conversation)) problems.push(`chat reply "${name}" needs an integer "conversation"`); - if (typeof r.md !== "string" || !r.md.trim()) problems.push(`chat reply "${name}" needs its answer in "md"`); - - const p = r.proposal; - if (p != null) { - if (!isPlainObject(p)) problems.push(`chat reply "${name}" "proposal" must be an object`); - else { - if (typeof p.summary !== "string" || !p.summary.trim()) { - problems.push(`chat reply "${name}" proposal needs a plain-English "summary"`); - } - if (!Array.isArray(p.files) || !p.files.length) { - problems.push(`chat reply "${name}" proposal needs "files": the project files it would change`); - } else { - for (const f of p.files) { - if (!projectRelative(f)) { - problems.push(`chat reply "${name}" proposal file "${f}" must be a project-relative path`); - } else if (state.specDir && underSpec(f, state.specDir)) { - problems.push(`a chat edit cannot touch the running skill's own files under ${state.specDir}/`); - } - } - } - } - } - - if (r.changed != null) { - const count = (n) => Number.isInteger(n) && n >= 0; - if (!Array.isArray(r.changed) || !r.changed.every((c) => isPlainObject(c) && typeof c.file === "string" && count(c.added) && count(c.removed))) { - problems.push(`chat reply "${name}" "changed" must be a list of { file, added, removed }`); - } - } - } - - const prose = JSON.stringify(replies.map((r) => [r && r.md, r && r.proposal && r.proposal.summary])); - problems.push(...proseProblems(prose, "a chat reply")); - return problems; -} - -/* -------------------------------------------------------- the workspace */ - -// The session's workspace.json, or null when the server has not made it yet. -export function readWorkspace(dir) { - return readJson(path.join(dir, WORKSPACE_FILE), null); -} - -// A fresh workspace: the original folder, named after itself, plus whatever -// was remembered for this folder and spec (rememberedWorkspace() below). -export function initialWorkspace(worktree, remembered = null) { - const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }; - if (remembered && remembered.original) { - if (remembered.original.name) original.name = remembered.original.name; - if (remembered.original.description) original.description = remembered.original.description; - } - const added = ((remembered && remembered.folders) || []).map((f, i) => ({ - id: "f" + (i + 1), - path: f.path, - name: f.name, - description: f.description || "", - ...(f.nested ? { nested: true } : {}), - })); - return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" }; -} - -/* ------------------------------------------------ remembered workspaces */ - -// The folder list outlives the console session: one file for the person, -// beside looks.json, keyed by the folder a session runs in and then by spec. -// Never under specs/: the paths are this machine's, and the server never -// writes into a project. -// -// { "projects": { "": { -// "path": "", -// "project": { original, folders, at }, // no spec picked -// "specs": { "specs/": { original, folders, at } } } } } -// -// `original` holds the first folder's name and description only (its path is -// always the session's own); `folders` the added ones as { path, name, -// description, nested? }. Two writers, the server on every change and -// `console.mjs forget`, each a read-modify-write of one key. -export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json"); - -const foldKey = (p) => { - const resolved = path.resolve(String(p || "")); - return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved; -}; - -// `specs/` with forward slashes and no trailing slash, or "" for none. -export function specKey(specDir) { - return String(specDir || "") - .trim() - .replace(/\\/g, "/") - .replace(/^\.\//, "") - .replace(/\/+$/, ""); -} - -function readStore() { - const saved = readJson(WORKSPACES_FILE, null); - return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} }; -} - -/** - * What was remembered for this folder and spec: `{ entry, from }`, where - * `from` is "spec" when the spec has its own list, "project" when it falls - * back to the project's (a spec's list starts as a copy of it), and null - * when nothing was ever saved. - */ -export function rememberedWorkspace(worktree, specDir) { - const project = readStore().projects[foldKey(worktree)]; - if (!project) return { entry: null, from: null }; - const spec = specKey(specDir); - if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" }; - return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null }; -} - -// The workspace's folders as the store keeps them. -export function rememberable(ws) { - const folders = (ws && ws.folders) || []; - const first = folders.find((f) => f.original) || {}; - return { - original: { name: first.name || "", description: first.description || "" }, - folders: folders - .filter((f) => !f.original) - .map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })), - at: nowIso(), - }; -} - -// Every server and `console.mjs forget` writes the one file, so each -// read-modify-write holds this lock beside it. -const WORKSPACES_LOCK = "workspaces.json.lock"; - -// Save the list for this folder and spec ("" for the project's own). -export function rememberWorkspace(worktree, specDir, ws) { - ensureDir(path.dirname(WORKSPACES_FILE)); - withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK); -} - -function saveRemembered(worktree, specDir, ws) { - const store = readStore(); - const key = foldKey(worktree); - const project = store.projects[key] || { path: path.resolve(worktree) }; - const spec = specKey(specDir); - if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) }; - else project.project = rememberable(ws); - store.projects[key] = project; - writeJsonAtomic(WORKSPACES_FILE, store); -} - -// Drop one spec's list (Finalize, once the spec is archived). True when there was one. -export function forgetWorkspace(worktree, specDir) { - const spec = specKey(specDir); - if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false; - return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK); -} - -function dropRemembered(worktree, spec) { - const store = readStore(); - const project = store.projects[foldKey(worktree)]; - if (!spec || !project || !project.specs || !project.specs[spec]) return false; - delete project.specs[spec]; - writeJsonAtomic(WORKSPACES_FILE, store); - return true; -} - -// Single-writer rule: only server.mjs may call this. -export function writeWorkspace(dir, ws) { - return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws); -} - -// What `open` hands the agent: names, paths and descriptions, nothing -// internal. `missing` names the folders that are gone, by their @name. -export function workspaceForAgent(ws) { - const all = (ws && ws.folders) || []; - const folders = all.map((f) => { - const out = { name: f.name, path: f.path }; - if (f.description) out.description = f.description; - if (f.original) out.original = true; - return out; - }); - const missing = ((ws && ws.missing) || []).map((id) => (all.find((f) => f.id === id) || {}).name).filter(Boolean); - return missing.length ? { folders, missing } : { folders }; -} - -/* ------------------------------------------------------ the meter ledger */ - -export const LEDGER_FILE = "ledger.ndjson"; - -/** - * Every ledger entry, in order. As with readChat(), a final segment with no - * newline is still being written and is left for the next read, and a line - * that will not parse is skipped. - */ -export function readLedger(dir) { - return readJsonLines(path.join(dir, LEDGER_FILE)); -} - -// Single-writer rule: only console.mjs may call this. -export function appendLedger(dir, entry) { - return appendJsonLine(path.join(dir, LEDGER_FILE), { ...entry, at: nowIso() }); -} - -// The id of the skill run in progress: the last launch's, or "L0" before any. -export function lastLaunchId(entries) { - for (let i = entries.length - 1; i >= 0; i--) if (entries[i].kind === "launch") return entries[i].id; - return "L0"; -} - -export function nextLaunchId(entries) { - return "L" + (entries.filter((e) => e.kind === "launch").length + 1); -} - -/* ---------------------------------------------------- the workspace cursor */ - -export const WORKSPACE_CURSOR_FILE = "workspace-cursor.json"; - -export function readWorkspaceCursor(dir) { - const saved = readJson(path.join(dir, WORKSPACE_CURSOR_FILE), { version: 0 }); - const n = Number(saved && saved.version); - return Number.isInteger(n) && n > 0 ? n : 0; -} - -// Never backwards, like writeCursor(): a killed `wait` may hand a change over -// twice, but never skips one. -export function writeWorkspaceCursor(dir, version) { - writeJsonAtomic(path.join(dir, WORKSPACE_CURSOR_FILE), { version: Math.max(readWorkspaceCursor(dir), version) }); -} - -// The workspace changes the agent has not been handed yet. -export function pendingWorkspaceChanges(dir) { - const cursor = readWorkspaceCursor(dir); - return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor); -} - -/* ------------------------------------------------------ the Subagents switch */ - -// The person's Subagents switch, remembered per project folder and workflow: -// -// { "": { "": { on, instruction, max } } } -// -// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the -// workflow's shipped default. -export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json"); -const SUBAGENTS_LOCK = "subagents.json.lock"; - -function readSubagentStore() { - const saved = readJson(SUBAGENTS_FILE, null); - return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {}; -} - -// The saved `{ on, instruction, max }` for this folder and workflow, or the -// default's when nothing (or something malformed) is saved. -export function subagentStoreEntry(worktree, workflow) { - const { on, instruction, max } = defaultSetting(workflow); - const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null; - const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null; - return saved && !saved.error ? saved : { on, instruction, max }; -} - -// Single-writer rule: only server.mjs may call this. -export function saveSubagentStoreEntry(worktree, workflow, value) { - ensureDir(path.dirname(SUBAGENTS_FILE)); - withStateLock( - path.dirname(SUBAGENTS_FILE), - () => { - const store = readSubagentStore(); - const key = foldKey(worktree); - const project = store[key] && typeof store[key] === "object" ? store[key] : {}; - store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } }; - writeJsonAtomic(SUBAGENTS_FILE, store); - }, - SUBAGENTS_LOCK - ); -} - -export const SUBAGENTS_SETTING_FILE = "subagents-setting.json"; - -const isCount = (n) => Number.isInteger(n) && n >= 0; - -// This session's switch, `{ workflow, on, instruction, max, revision }`, or -// null when there is none or it is malformed. -export function readSubagentSetting(dir) { - const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null); - if (!s || typeof s !== "object") return null; - if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null; - return s; -} - -// Single-writer rule: only server.mjs may call this. The revision never goes -// backwards within a session. -export function writeSubagentSetting(dir, setting) { - const previous = readSubagentSetting(dir); - const revision = Math.max(previous ? previous.revision : 0, setting.revision); - return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision }); -} - -export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json"; -const CURSOR_STATES = new Set(["none", "on", "off"]); - -// What the agent was last told: `{ revision, state }`. -export function readSubagentCursor(dir) { - const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null); - if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" }; - return { revision: saved.revision, state: saved.state }; -} - -// Single-writer rule: only console.mjs may call this. Never backwards, like -// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one. -export function writeSubagentCursor(dir, cursor) { - const old = readSubagentCursor(dir); - const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state }; - writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next); -} - -// The one place the cursor may go back: `open`, which starts a fresh agent. -export function resetSubagentCursor(dir) { - writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" }); -} - -// The `caps` of the last `open` event: what the agent's console copy can do. -export function latestOpenCaps(dir) { - const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open"); - const last = opens[opens.length - 1]; - return last && Array.isArray(last.caps) ? last.caps : []; -} - -/** - * Flag the case where the link cannot be opened by the person it is for. - * - * The page is served on 127.0.0.1, which is only their machine if the agent is - * ON their machine. An agent in a cloud VM, a remote sandbox or an SSH session - * hands over a link to its own loopback, and the person sees nothing. - * - * Reported rather than refused, on purpose: a devcontainer or a Codespace - * usually forwards the port automatically and works perfectly. What the agent - * needs is to know that it might not, so it can ask instead of insisting. - */ -export function remoteWarning() { - const signals = [ - ["SSH_CONNECTION", "an SSH session"], - ["SSH_CLIENT", "an SSH session"], - ["REMOTE_CONTAINERS", "a dev container"], - ["CODESPACES", "a GitHub Codespace"], - ["GITPOD_WORKSPACE_ID", "a Gitpod workspace"], - ]; - const hit = signals.find(([key]) => process.env[key]); - if (!hit) return {}; - return { - remote: hit[0], - note: - `This looks like ${hit[1]}, so http://127.0.0.1 is this machine, not necessarily theirs. ` + - `Give them the link, ask whether it opens, and go back to the terminal if it does not.`, - }; -} diff --git a/skills/plan2code-0-pathfinder/references/web-console/picker.mjs b/skills/plan2code-0-pathfinder/references/web-console/picker.mjs deleted file mode 100644 index e621cb4..0000000 --- a/skills/plan2code-0-pathfinder/references/web-console/picker.mjs +++ /dev/null @@ -1,265 +0,0 @@ -// Plan2Code Web Console - the native folder picker behind Workspace's Browse… -// -// A port of the launcher's picker (src/launcher/plan2code.js). The launcher -// is self-contained CommonJS copied alone to ~/.plan2code/bin/, and this -// console is ESM bundled into every skill, so the two cannot share a module: -// this is a copy, and a drift test in scripts/test-web-console.mjs fails the -// moment the launcher's picker changes without it. The prompt is a parameter -// here rather than the launcher's constant. -// -// Always spawned asynchronously: spawnSync would freeze the server's polling, -// chat and wait for as long as the dialog stayed open. -// -// Node built-ins only. - -import fs from "node:fs"; -import path from "node:path"; -import { spawn } from "node:child_process"; - -const IS_WINDOWS = process.platform === "win32"; -const IS_MAC = process.platform === "darwin"; - -export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace"; - -// Copied verbatim from src/launcher/plan2code.js; see the drift test. -export const WINDOWS_PICKER_SOURCE = ` -using System; -using System.Runtime.InteropServices; -using System.Threading; - -public static class Plan2CodeFolderPicker { - [ComImport, Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")] - private class FileOpenDialog {} - - [ComImport, Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IFileOpenDialog { - [PreserveSig] int Show(IntPtr owner); - void SetFileTypes(uint count, IntPtr specs); - void SetFileTypeIndex(uint index); - void GetFileTypeIndex(out uint index); - void Advise(IntPtr events, out uint cookie); - void Unadvise(uint cookie); - void SetOptions(uint options); - void GetOptions(out uint options); - void SetDefaultFolder(IShellItem item); - void SetFolder(IShellItem item); - void GetFolder(out IShellItem item); - void GetCurrentSelection(out IShellItem item); - void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name); - void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name); - void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title); - void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string label); - void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label); - void GetResult(out IShellItem item); - } - - [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IShellItem { - void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result); - void GetParent(out IShellItem parent); - void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name); - } - - [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)] - private static extern void SHCreateItemFromParsingName(string path, IntPtr bindContext, ref Guid iid, out IShellItem item); - - [DllImport("user32.dll", CharSet = CharSet.Unicode)] - private static extern IntPtr FindWindow(string className, string title); - - [DllImport("user32.dll")] - private static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int w, int h, uint flags); - - [DllImport("user32.dll")] - private static extern bool SetForegroundWindow(IntPtr hWnd); - - [DllImport("user32.dll")] - private static extern int GetSystemMetrics(int index); - - private const uint FOS_PICKFOLDERS = 0x20; - private const uint FOS_FORCEFILESYSTEM = 0x40; - private const uint FOS_PATHMUSTEXIST = 0x800; - private const uint SIGDN_FILESYSPATH = 0x80058000; - private const int ERROR_CANCELLED = unchecked((int)0x800704C7); - - private static void Raise(string title) { - for (int i = 0; i < 100; i++) { - IntPtr hwnd = FindWindow(null, title); - if (hwnd != IntPtr.Zero) { - int w = Math.Min(1100, GetSystemMetrics(0) - 80); - int h = Math.Min(750, GetSystemMetrics(1) - 80); - int x = (GetSystemMetrics(0) - w) / 2 + 40; - int y = (GetSystemMetrics(1) - h) / 2 + 40; - SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40); - SetForegroundWindow(hwnd); - return; - } - Thread.Sleep(50); - } - } - - public static string Pick(IntPtr owner, string title, string start) { - IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog(); - try { - uint options; - dialog.GetOptions(out options); - dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); - dialog.SetTitle(title); - if (!string.IsNullOrEmpty(start)) { - try { - Guid iid = typeof(IShellItem).GUID; - IShellItem folder; - SHCreateItemFromParsingName(start, IntPtr.Zero, ref iid, out folder); - dialog.SetFolder(folder); - } catch (Exception) {} - } - Thread raiser = new Thread(delegate() { Raise(title); }); - raiser.IsBackground = true; - raiser.Start(); - int hr = dialog.Show(owner); - if (hr == ERROR_CANCELLED) return null; - Marshal.ThrowExceptionForHR(hr); - IShellItem result; - dialog.GetResult(out result); - string path; - result.GetDisplayName(SIGDN_FILESYSPATH, out path); - return path; - } finally { - Marshal.ReleaseComObject(dialog); - } - } -} -`; - -// Resolve a command on PATH the way the shell would, including PATHEXT on Windows. -function findOnPath(command) { - const dirs = (process.env.PATH || "").split(path.delimiter).filter(Boolean); - const extensions = IS_WINDOWS ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [""]; - for (const dir of dirs) { - for (const ext of extensions) { - const candidate = path.join(dir.replace(/^"|"$/g, ""), command + ext); - try { - if (fs.statSync(candidate).isFile()) return candidate; - } catch {} - } - } - return null; -} - -/** - * The native folder picker for this OS, as a command to run: it prints the - * chosen folder, or nothing when the person cancels. Null when this OS has no - * picker we can drive. - */ -export function pickerCommand(start, prompt) { - if (IS_WINDOWS) { - const script = [ - "$ErrorActionPreference = 'Stop'", - "try {", - " [Console]::OutputEncoding = [Text.Encoding]::UTF8", - " Add-Type -AssemblyName System.Windows.Forms", - " [System.Windows.Forms.Application]::EnableVisualStyles()", - // A TopMost owner keeps the dialog in front of the console window that launched it. - " $owner = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true; ShowInTaskbar = $false }", - " try {", - " Add-Type -TypeDefinition $env:PLAN2CODE_PICKER_SOURCE", - " $picked = [Plan2CodeFolderPicker]::Pick($owner.Handle, $env:PLAN2CODE_PICKER_PROMPT, $env:PLAN2CODE_PICKER_START)", - " } catch {", - // Add-Type is blocked under Constrained Language Mode and some AppLocker policies; the - // old tree dialog still works there. - " $dialog = New-Object System.Windows.Forms.FolderBrowserDialog", - " $dialog.Description = $env:PLAN2CODE_PICKER_PROMPT", - " $dialog.SelectedPath = $env:PLAN2CODE_PICKER_START", - " $picked = if ($dialog.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) { $dialog.SelectedPath } else { $null }", - " }", - " if ($picked) { $picked }", - "} catch { exit 3 }", - ].join("\n"); - return { - command: "powershell.exe", - args: [ - "-NoProfile", - "-NonInteractive", - "-STA", - "-ExecutionPolicy", - "Bypass", - "-EncodedCommand", - Buffer.from(script, "utf16le").toString("base64"), - ], - env: { - PLAN2CODE_PICKER_PROMPT: prompt, - PLAN2CODE_PICKER_START: start, - PLAN2CODE_PICKER_SOURCE: WINDOWS_PICKER_SOURCE, - }, - }; - } - - if (IS_MAC) { - return { - command: "osascript", - args: [ - "-e", - "on run argv", - "-e", - `POSIX path of (choose folder with prompt "${prompt}" default location (POSIX file (item 1 of argv)))`, - "-e", - "end run", - start, - ], - }; - } - - if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return null; - if (findOnPath("zenity")) { - return { - command: "zenity", - args: ["--file-selection", "--directory", `--title=${prompt}`, `--filename=${start}${path.sep}`], - }; - } - if (findOnPath("kdialog")) { - return { command: "kdialog", args: ["--title", prompt, "--getexistingdirectory", start] }; - } - return null; -} - -/** - * Show the picker and settle on what the person did: `{ path }` for a pick, - * `{ cancelled: true }` when they closed it, `{ error }` when the picker - * itself failed or this OS has none. Pickers exit 0 or 1 with nothing printed - * when cancelled. - */ -export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) { - const picker = pickerCommand(start, prompt); - if (!picker) return Promise.resolve({ error: "picker-failed" }); - return new Promise((resolve) => { - let settled = false; - const settle = (result) => { - if (settled) return; - settled = true; - resolve(result); - }; - let child; - try { - child = spawnImpl(picker.command, picker.args, { - env: { ...process.env, ...(picker.env || {}) }, - // stderr is ignored, not piped: a pipe nobody reads fills up and - // blocks a chatty picker (GTK warnings) before it can exit. - stdio: ["ignore", "pipe", "ignore"], - windowsHide: true, - }); - } catch { - return settle({ error: "picker-failed" }); - } - let stdout = ""; - if (child.stdout) { - child.stdout.setEncoding?.("utf8"); - child.stdout.on("data", (chunk) => (stdout += chunk)); - } - child.on("error", () => settle({ error: "picker-failed" })); - child.on("close", (code) => { - const folder = stdout.trim(); - if (code === 0 && folder) return settle({ path: path.resolve(folder) }); - if (!folder && (code === 0 || code === 1)) return settle({ cancelled: true }); - settle({ error: "picker-failed" }); - }); - }); -} diff --git a/skills/plan2code-0-pathfinder/references/web-console/public/answers.js b/skills/plan2code-0-pathfinder/references/web-console/public/answers.js deleted file mode 100644 index 5e29c36..0000000 --- a/skills/plan2code-0-pathfinder/references/web-console/public/answers.js +++ /dev/null @@ -1,1003 +0,0 @@ -// The page's pure logic: what the person answered, and what they asked for, in -// the words those things have to reach the agent as. -// -// Everything here is a pure function of an item and a value. That is the point -// of the file: app.js cannot be loaded outside a browser (it touches `document` -// at module scope and starts a session on import), so any logic that stays in -// it is logic no test can reach. Three defects in this exact code got as far as -// the screen before anyone noticed. It lives here so `node --test` can see it. -// -// No DOM, no `local`, no fetch. If a function in here needs any of those, it -// belongs in app.js instead. - -/* ----------------------------------------------------- the sent answer */ - -/** - * The value an in-flight send carries, or null if it carries no answer. - * - * A send can be a note on its own: someone asks a question about the question - * before answering it. That still goes in `local.sent`, because the note really - * is on its way, but it must NOT make the page treat the question as answered - * and lock the form. They have not answered it yet, and locking them out is how - * an open question becomes unanswerable. - */ -export function sentAnswer(sent) { - return sent && sent.value ? sent.value : null; -} - -/** - * What the person settled on, for a question that is no longer open. - * - * `answer` is what the agent recorded when it settled the question. `submitted` - * is what the server wrote down the moment Send was pressed. The second exists - * because the first depends on the agent remembering to do it, and a card that - * says "Settled" above an empty form is the worst thing this page can show. - */ -export function recordedAnswer(item) { - const a = item && item.answer && typeof item.answer === "object" ? item.answer : null; - const s = item && item.submitted && typeof item.submitted === "object" ? item.submitted : null; - if (!a && !s) return null; - return { ...(s || {}), ...(a || {}) }; -} - -/** - * A send the person made that the agent never settled, still sitting on an - * OPEN question. - * - * `local.sent` covers this while the same tab is alive; `submitted` is the - * server's own record of the send and survives a reload, a resume onto a new - * port, and a second tab. An open item that carries one, and has had no agent - * reply since, is "sent, waiting on Plan2Code" — not a question still - * waiting for them, which is what it reads as when an agent takes the answer - * and moves on without marking the item settled. - * - * Two ways out, both meaning the question is theirs again: - * - * - an agent message in the item's thread AFTER the send means the question - * is being asked again — the person gets a live form back, not a locked - * record of what they already said; - * - a recorded `answer` means the agent did settle it at some point (the - * status is just stale or the question was re-asked), so the leftover - * `submitted` is the old send, not one in flight. - */ -export function submittedAwaiting(item) { - const s = item && item.submitted; - if (!s || typeof s !== "object") return null; - if (item.answer && typeof item.answer === "object") return null; - const thread = Array.isArray(item.thread) ? item.thread : []; - const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at)); - return replied ? null : s; -} - -/** - * The note (and its attachments) the person last sent on an item, while the - * agent has yet to say anything after it. The server records it as `sentNote` - * on every send, so the page can show it in the Notes pane and in the Sent - * box instead of letting it vanish into a send that shows no sign of arriving. - * Any agent message from the send onwards, or one with no clock to compare, - * means it has been picked up. The person's own entries never count: the - * server writes their note into the thread as it arrives. - */ -export function noteAwaiting(item) { - const n = item && item.sentNote; - if (!n || typeof n !== "object") return null; - const thread = Array.isArray(item.thread) ? item.thread : []; - const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at)); - return picked ? null : n; -} - -/** - * Who said a thread entry and what they said. The contract is `{ who, text }` - * and the server lifts anything else into it, but sessions written before that - * hold `{ from, md }` replies, which would otherwise draw as empty bubbles. - */ -export function threadWho(m) { - return m && (m.who || m.from || m.role) === "user" ? "user" : "agent"; -} - -export function threadText(m) { - if (!m) return ""; - for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k]; - return ""; -} - -/* -------------------------------------------------------------- labels */ - -export function optionLabel(item, k) { - const o = ((item && item.options) || []).find((x) => x.k === k); - if (!o) return String(k); - return o.k ? `${o.k} · ${o.text}` : o.text; -} - -export function verdictLabel(item, id) { - const list = (item && item.verdicts) || [ - { id: "approve", label: "Looks good, go ahead" }, - { id: "changes", label: "I want changes" }, - ]; - const v = list.find((x) => x.id === id); - return v ? verdictText(v) : String(id); -} - -// A verdict's button text. `label` is the contract; `text` is what menu -// options use, and an agent that borrows it must not get blank buttons. -export function verdictText(v) { - return v.label || v.text || v.id; -} - -export const CHECK_STATE_LABEL = { - done: "All done", - blocked: "I am stuck", - help: "I need help", - defer: "Later", -}; - -/** - * The answer as lines to show back, in the page's words rather than the - * agent's shorthand: "A · Run the setup first", not "a". - */ -export function answerLines(item, v) { - const out = []; - if (!v) return out; - if (v.skipped) out.push("Skipped"); - if (v.k) out.push(optionLabel(item, v.k)); - if (Array.isArray(v.ks)) for (const k of v.ks) out.push(optionLabel(item, k)); - if (typeof v.yes === "boolean") out.push(v.yes ? item.yesLabel || "Yes" : item.noLabel || "No"); - if (typeof v.ok === "boolean") { - out.push(v.ok ? item.yesLabel || "Yes, that is right" : item.noLabel || "Not quite"); - } - if (v.verdict) out.push(verdictLabel(item, v.verdict)); - if (v.state) out.push(CHECK_STATE_LABEL[v.state] || String(v.state)); - if (Array.isArray(v.done) && v.done.length) { - out.push(`Steps done: ${v.done.map((n) => n + 1).join(", ")}`); - } - if (Array.isArray(v.rows) && v.rows.length) { - out.push(`${v.rows.length} steps, in the order you set`); - } - return out; -} - -/** - * A single-choice answer, which is one thing or the other and never both. - * - * Picking an option and then writing "none of these, because…" used to send - * both, joined, with the pick first: an answer that argued with itself. The - * rule lives here rather than in the two click handlers that apply it, so it - * is one statement that a test can hold to. - * - * Returns null when there is nothing to stage, which is what "they have not - * answered yet" looks like everywhere else in the page. - */ -export function choiceAnswer({ k, text } = {}) { - if (k) return { type: "answer", kind: "choice", k }; - const said = String(text || "").trim(); - return said ? { type: "answer", kind: "choice", text: said } : null; -} - -/* -------------------------------------------------------- the brief ask */ - -/** - * The words a brief request reaches the agent as. - * - * This is not an answer, but it is the same kind of thing and it belongs to the - * same rule: a string the agent parses, so it has to be exactly right, so it - * has to be somewhere a test can see it. `range` is the Pathfinder brief - * playbook's own grammar -- `today`, `this week`, `since `, `full`. - */ -export function briefPhrase(range) { - const r = String(range || "today").trim(); - if (r === "full") return "Write a full brief."; - if (r.startsWith("since ")) return `Write a brief covering everything ${r}.`; - return `Write a brief for ${r}.`; -} - -/* ---------------------------------------------------- the autofill text */ - -// A placeholder is a suggestion nobody can edit, and it vanishes the moment you -// type. On a question whose example is most of a good answer, retyping it is -// busywork, so offer it as a value instead. The lead-in ("For example:") is the -// agent talking about the example, not part of it, so it is stripped. -// -// Two rules keep the stripping from mangling a real answer: -// -// The lead-in must be FOLLOWED by a separator. Without that, "Egypt office" -// loses its "Eg" and "Exampled output" loses its "Example". -// -// A bare hyphen only separates when it has space around it. "For example - a" -// is a lead-in; the hyphen in "example-name-here" is part of the name, and a -// kebab-case suggestion must survive intact for a field with a `pattern`. -// -// "Say" is deliberately not in the list: "Say when you need it by" is a -// question far more often than it is a preamble. -const EXAMPLE_LEAD = - /^\s*(?:for\s+(?:example|instance)|examples?|such\s+as|e\.?\s?g\.?|i\.?\s?e\.?)(?:\s+-\s+|\s*[:,.]\s*|\s+)/i; - -/** - * The placeholder, as a value someone could accept as their own answer. - * Empty string when there is nothing worth offering. - */ -export function suggestionFrom(item) { - const raw = String((item && item.placeholder) || "").trim(); - if (!raw) return ""; - const stripped = raw.replace(EXAMPLE_LEAD, "").trim(); - if (!stripped) return ""; - // Recapitalise only when a lead-in was actually removed, and never on a - // field with a shape to match: "audit-export" must not become "Audit-export". - if (stripped !== raw && !item.pattern && /^[a-z]/.test(stripped)) { - return stripped[0].toUpperCase() + stripped.slice(1); - } - return stripped; -} - -/* ------------------------------------------------------ the hand-off */ - -// The badge each workflow wears. Shared with the server, which writes it into -// the page it serves so the first paint already names the session instead of -// flashing a placeholder until the script arrives. -export const WORKFLOW_LABEL = { - dashboard: "Dashboard", - init: "Setting up", - "init-update": "Refreshing", - pathfinder: "Pathfinder", - plan: "Planning", - "revise-plan": "Revising the plan", - document: "Documenting", - implement: "Building", - "implement-review": "Building + review", - review: "Review", - "quick-task": "Quick task", - finalize: "Wrapping up", - handoff: "Handoff", -}; - -export function workflowLabel(workflow) { - return WORKFLOW_LABEL[workflow] || workflow || "Session"; -} - -// The workflows that ship the console (install.js bundles it into every -// skill as `additionalReferences`). Any other next step has no browser page -// to open, and asking for one would send the next session looking for -// something that is not there. -export const CONSOLE_WORKFLOWS = [ - "/plan2code", - "/plan2code-init", - "/plan2code-init-update", - "/plan2code-0-pathfinder", - "/plan2code-quick-task", - "/plan2code-1-plan", - "/plan2code-1b-revise-plan", - "/plan2code-2-document", - "/plan2code-3-implement", - "/plan2code-3-implement-review", - "/plan2code-review", - "/plan2code-4-finalize", - "/plan2code-handoff", -]; - -// Rides on the end of the command as part of the skill's argument. Every -// console skill takes it as the answer to "web console or terminal?" instead -// of asking again. It must stay clear of "brief", "recap" and "minutes": -// pathfinder reads any of those in its argument as a request for a brief. -export const CONTINUE_IN_CONSOLE = "--web"; - -// The long form the skills still accept. A command that carries it is copied -// with the flag instead, which is shorter and reads as the parameter it is. -const CONSOLE_SENTENCE = /\s*Use the web console for this session\.?/gi; - -/** - * What the Copy button on the finished screen puts on the clipboard. - * - * Someone who worked the whole session in the browser should land back in the - * browser, not be asked the interface question as though they were new. The - * `--web` flag goes on the same line as the command, because what follows a - * slash command is its argument, and a pasted second line is not reliably that. - * A command written with the long sentence is copied with the flag instead. - * - * `fin.console` overrides the inference either way; otherwise it follows from - * whether the next step is a workflow that has a console at all. - */ -export function handoffText(fin) { - const raw = String((fin && fin.command) || "").trim(); - if (!raw) return ""; - const cmd = raw.replace(CONSOLE_SENTENCE, "").trim(); - const capable = - typeof fin.console === "boolean" - ? fin.console - : cmd !== raw || CONSOLE_WORKFLOWS.some((w) => cmd === w || cmd.startsWith(w + " ")); - // An agent that already wrote the flag should not get it twice. - if (!capable || /(^|\s)--web\b/.test(cmd)) return cmd; - return `${cmd} ${CONTINUE_IN_CONSOLE}`; -} - -/** - * A finish is a pause when its headline says so. There is no flag to read: - * the stop playbook asks the agent to write "a headline that says it is - * paused rather than done", so the page reads the same words the person - * does. A session that ends on its own says nothing of the sort. - */ -export function finishPaused(fin) { - return /^\s*paused\b/i.test(String((fin && fin.headline) || "")); -} - -// The line a finished session shows when it has nothing left to run. Split so -// the page can render the backticked command as code; joined with a space they -// read as one sentence. -export const ALL_DONE_LEAD = "All done, nothing left to run."; -export const ALL_DONE_REST = "To start something else, run `/plan2code` in a new conversation to open the dashboard."; -export const DASHBOARD_COMMAND = "/plan2code"; - -/** - * Which hand-off a finish gets: a pause always offers its resume command, a - * finish with a command offers it as the next step, and one without has - * nothing left to run. - */ -export function handoffShape(fin) { - if (finishPaused(fin)) return "paused"; - return String((fin && fin.command) || "").trim() ? "next" : "all-done"; -} - -/* ------------------------------------------------------------ stopping */ - -// What a stop request reads as, the way a typed message would. It goes to the -// agent as part of `reply`, so the same caution applies as to the hand-off -// 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."; - -/** - * 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: - * while Plan2Code has the ball it may be halfway through writing their last - * answers into the files, and a request landing then is how a question ends up - * half recorded. `waiting` is the caller's "the agent is working or a reply is - * owed, and it has not gone adrift" -- an agent that has stopped checking in - * never replies, and a button greyed out forever would lock the person in. An - * uncollected send still blocks even then, because the server takes one at a - * time. - */ -export function turnGate({ gone = false, pendingResult = false, waiting = false } = {}) { - if (gone) return "gone"; - if (pendingResult) return "pending"; - if (waiting) return "waiting"; - return null; -} - -// What the top bar's Back to the dashboard button reads as to the agent. It -// goes in `reply` like the stop, so the same caution applies: nothing -// Pathfinder would read as asking for a brief. -export const HOME_REPLY = "Save my place and take me back to the dashboard, right here in this session."; - -const HOME_TITLES = { - gone: "Not connected right now.", - pending: "Your last answers are still being picked up. You can leave once they have been.", - waiting: "Plan2Code is working on your answers. You can leave once it replies.", -}; - -/** - * The top bar's Back to the dashboard button. Hidden on the dashboard itself, - * on a finished screen (which carries its own way back) and while a stop is - * under way; otherwise pressable on the person's turn, like Stop session. - * Once pressed it waits for the page to turn, unless the agent has gone - * adrift: then it comes back, and a second press is safe because the server - * refuses a duplicate while the first is uncollected. - */ -export function homeButtonState({ workflow, finished = false, stopping = false, homeward = false, adrift = false, ...turn } = {}) { - if (!workflow || workflow === "dashboard" || finished || stopping) return { hidden: true, disabled: true, title: "" }; - if (homeward && !adrift) return { hidden: false, disabled: true, title: "Opening the dashboard…" }; - const gate = turnGate(turn); - return { - hidden: false, - disabled: Boolean(gate), - title: gate ? HOME_TITLES[gate] : "Back to the dashboard. Your place is saved first.", - }; -} - -/** - * The resume command the PAGE can offer when the agent cannot: it stopped - * listening, or went away without posting a finish. Built only from what the - * session state says, never guessed. - * - * Pathfinder resumes from its folder, so it needs `specDir` (`specs/`), - * which the workflow posts once the folder exists. Without one the bare - * command still works: Pathfinder asks which idea. Planning finds its own - * draft and takes no path. The implementation steps, Revision and - * Finalization take the spec's overview.md, and without it they ask which - * spec (or find the only one). A quick task keeps nothing on disk to resume - * from, so its command starts it again. - */ -export function resumeCommand({ workflow, specDir } = {}) { - const raw = String(specDir || "").trim().replace(/\\/g, "/").replace(/\/+$/, ""); - // Only a real relative specs/ path. Anything else would be run verbatim by - // someone with no way to tell it was wrong. - const dir = /^specs\/[a-z0-9][a-z0-9._-]*$/i.test(raw) ? raw : ""; - const withOverview = (cmd) => (dir ? `${cmd} ${dir}/overview.md` : cmd); - switch (workflow) { - case "dashboard": - return "/plan2code"; - case "init": - return "/plan2code-init"; - case "init-update": - return "/plan2code-init-update"; - case "plan": - return "/plan2code-1-plan"; - case "quick-task": - return "/plan2code-quick-task"; - case "document": - return withOverview("/plan2code-2-document"); - case "implement": - return withOverview("/plan2code-3-implement"); - case "implement-review": - return withOverview("/plan2code-3-implement-review"); - case "review": - return "/plan2code-review"; - case "revise-plan": - return withOverview("/plan2code-1b-revise-plan"); - case "finalize": - return withOverview("/plan2code-4-finalize"); - case "handoff": - return "/plan2code-handoff"; - default: - return dir ? `/plan2code-0-pathfinder ${dir}/pathfinder` : "/plan2code-0-pathfinder"; - } -} - -/* ------------------------------------------------ after a build is done */ - -// What the two buttons on a finished build's hand-off reach the agent as. They -// go in `reply` like any typed message, so the same caution applies as to the -// other session phrases: plain words, nothing Pathfinder would read as a brief. -export const REVIEW_REPLY = - "Review what was just built before I go: run the focused code review on this session's changes, here on the page."; -export const DONE_REPLY = "No review, thanks. I am done: close the session."; -export const DASHBOARD_REPLY = "Take me back to the dashboard, right here in this session."; - -// Shown under the Back to the dashboard button: the press picks up in the same -// conversation, which carries a long skill's context into the next one. -export const DASHBOARD_NOTE = - "This picks up in the same conversation. That's fine after a quick or small skill; after a long one, type `/clear` in your terminal and run `/plan2code` for a clean start."; - -/** - * Whether a finish offers the way back to the dashboard. The agent opts in - * with `finish.dashboard: true`, so a skill that predates the button never - * shows one nobody answers; a pause never offers it. - */ -export function dashboardOffer(fin) { - return Boolean(fin && fin.dashboard === true && !finishPaused(fin)); -} - -/** - * Whether a finish carries the offer to review what was just built. The agent - * posts `finish.review` as `true` or as `{ "label": "..." }` on a finished - * quick task (an implementation phase offers the review earlier, as a verdict - * on its sign-off card). - */ -export function reviewOffer(fin) { - const r = fin && fin.review; - if (!r) return null; - const label = typeof r === "object" && typeof r.label === "string" ? r.label.trim() : ""; - return { label: label || "Review what was just built" }; -} - -/* ------------------------------------------------------- the dashboard */ - -// The skills the dashboard offers, in the order it offers them. The page owns -// this list rather than the session state: the catalog is product UI, fixed -// for everyone, and the alternative — the agent posting it — would put a dozen -// cards of boilerplate through the patch channel every time the menu opened. -// `menu` in the state can still say what the agent knows: a `recommend` skill -// to highlight and a `details` line per card ("Phase 2 of 4 is next"). -// -// `workflow` is the name the skill resumes the session under: the dashboard -// hands its session over, and this is what turns the page into that skill's -// console. A test holds this list against the skills install.js builds, so a -// new skill cannot ship without a card here. -export const CATALOG_GROUPS = [ - { id: "setup", title: "First, the project" }, - { id: "pipeline", title: "The steps, in order" }, - { id: "extra", title: "Useful any time" }, -]; - -// `spec: true` marks the cards that take a spec folder as their target: when -// the picker has a spec selected, its `dir` rides along in the `__launch` -// action so the launched skill knows which spec it was picked for. -export const SKILL_CATALOG = [ - { - skill: "plan2code-init", - command: "/plan2code-init", - workflow: "init", - group: "setup", - chip: "Set up", - title: "Set up this project", - blurb: "Reads your project and writes AGENTS.md, the guide every later step works from.", - about: - "Plan2Code reads the whole project: how it is organized, how it runs, and where the sharp edges are. Then it writes AGENTS.md, the guide every later step steers by. It asks a few questions as it goes, so nothing important gets guessed. Run this once per project, or again when the project has moved on.", - }, - { - skill: "plan2code-init-update", - command: "/plan2code-init-update", - workflow: "init-update", - group: "setup", - chip: "Set up", - title: "Refresh AGENTS.md", - blurb: "Brings AGENTS.md and its notes up to date with what the project has learned lately.", - about: - "The project moved on since AGENTS.md was written: new commands, new habits, new gotchas. This re-reads the project, asks what changed, and folds it into AGENTS.md and the notes beside it. Cheaper than a fresh setup, and whatever is still right is kept.", - }, - { - skill: "plan2code-0-pathfinder", - command: "/plan2code-0-pathfinder", - workflow: "pathfinder", - group: "pipeline", - chip: "Step 0", - spec: true, - title: "Pathfinder", - blurb: "A foggy idea becomes a clear list of decisions, settled one question at a time.", - about: - "You have a rough idea and a lot of unknowns. Pathfinder asks one question at a time: who it is for, what it must do, what could go wrong. Each answer is written down in a spec folder. It ends with a list of decisions clear enough to plan from, and nothing gets built yet.", - }, - { - skill: "plan2code-1-plan", - command: "/plan2code-1-plan", - workflow: "plan", - group: "pipeline", - chip: "Step 1", - spec: true, - title: "Plan", - blurb: "Requirements, technical design and your approval: the shape of what gets built.", - about: - "Turns what you bring into a real plan: a finished Pathfinder map, a folder of design notes, or just the idea in your head. You get requirements, a technical design, a phase-by-phase breakdown, and a final version to approve before anything is built. This is where 'what are we building' becomes 'how it gets built'.", - }, - { - skill: "plan2code-1b-revise-plan", - command: "/plan2code-1b-revise-plan", - workflow: "revise-plan", - group: "pipeline", - chip: "Step 1b", - spec: true, - title: "Revise the plan", - blurb: "Requirements changed mid-build? Adjust the plan without starting over.", - about: - "Requirements moved mid-build: a feature added, a rule dropped, a deadline pulled in. This adjusts the existing spec for the change, shows you what it affects, and only rewrites what actually has to move. The approved plan stays the plan.", - }, - { - skill: "plan2code-2-document", - command: "/plan2code-2-document", - workflow: "document", - group: "pipeline", - chip: "Step 2", - spec: true, - title: "Document", - blurb: "The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do.", - about: - "Writes the plan as numbered phase files. Each phase is a checklist of tasks small enough to just do, with the details a builder needs right there. This is the file the build step works from, and the thing a later session can pick up cold.", - }, - { - skill: "plan2code-3-implement", - command: "/plan2code-3-implement", - workflow: "implement", - group: "pipeline", - chip: "Step 3", - spec: true, - title: "Implement", - blurb: "Builds the next phase, task by task, with a report and your sign-off at the end.", - about: - "Builds the next phase of the spec. Tasks get checked off one by one, with progress and the occasional decision landing on this page as it goes. It ends with a report of what was built and a sign-off card you approve before the phase counts as done.", - }, - { - skill: "plan2code-3-implement-review", - command: "/plan2code-3-implement-review", - workflow: "implement-review", - group: "pipeline", - chip: "Step 3", - spec: true, - title: "Implement + review", - blurb: "One phase built, then a careful review of the changes, then your sign-off. All in one run.", - about: - "The same build as Implement, with a review folded in before sign-off. The phase is built, then a fresh pass hunts for problems in exactly what changed, you pick what gets fixed, and only then does the sign-off card arrive.", - }, - { - skill: "plan2code-4-finalize", - command: "/plan2code-4-finalize", - workflow: "finalize", - group: "pipeline", - chip: "Step 4", - spec: true, - title: "Finalize", - blurb: "Checks the work, writes the summary, files the specs away and suggests the commit message.", - about: - "The closer. Checks every task against the spec, makes sure the build actually works, writes the summary into overview.md, updates the project docs, and suggests the commit message. Run it when the feature is done. It leaves the project tidy behind it.", - }, - { - skill: "plan2code-quick-task", - command: "/plan2code-quick-task", - workflow: "quick-task", - group: "extra", - chip: "Utility", - title: "Quick task", - blurb: "Too small for the full process? A quick plan, then it just builds it.", - about: - "A fix, a tweak, a small feature. Not worth a spec folder. Describe it, confirm the one-line plan, and it builds it right there, with a report at the end. The fast lane for work the full process would over-plan.", - }, - { - skill: "plan2code-review", - command: "/plan2code-review", - workflow: "review", - group: "extra", - chip: "Utility", - title: "Review", - blurb: "A second opinion on the changes. Problems ranked, and you pick what gets fixed.", - about: - "A fresh-eyes pass over what changed: bugs, gaps, and the things the builder was too close to see. Problems come back ranked with a suggestion each, you pick which ones get fixed, and it fixes them.", - }, - { - skill: "plan2code-handoff", - command: "/plan2code-handoff", - workflow: "handoff", - group: "extra", - chip: "Utility", - title: "Handoff", - blurb: "Pack this conversation into a document a fresh session can pick up cold.", - about: - "Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.", - }, -]; - -// A workflow by the name its dashboard card gives it ("Implement"), for the -// screens that speak of it as a thing being started rather than as a badge. -export function workflowTitle(workflow) { - const entry = SKILL_CATALOG.find((e) => e.workflow === workflow); - return entry ? entry.title : workflowLabel(workflow); -} - -// Every skill gets its own Planny on the starting and waiting screens, drawn -// as a