mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 20:45:33 -08:00
Sync upstream into v2.7.0: the git board skill replaces git-commit (ticket-free), and console docs and tests are split up
AI Assisted
This commit is contained in:
1 parent
6114914dd6
commit
f328406bb5
103 files changed
+17636
-9991
No files matched your search
+37
-19
@@ -10,13 +10,14 @@
|
||||
* devin --permission-mode bypass [extra args] -- /plan2code
|
||||
* codex --dangerously-bypass-approvals-and-sandbox [extra args] $plan2code
|
||||
*
|
||||
* Codex starts a skill with `$name` rather than `/name`. When more than one CLI is installed it asks which one, with the last pick as the default; with only
|
||||
* one installed it uses that. `--cli claude` / `--cli devin` skips the question. Before starting
|
||||
* it asks which model to run, from the curated list in models.json (shipped with every
|
||||
* install) plus any models the user added in User Preferences; Enter keeps the model the CLI
|
||||
* last used, and `--model` skips the question. Any other arguments are forwarded to the CLI. Self-contained, Node
|
||||
* built-ins only: install.js copies this file to ~/.plan2code/bin/ and points the global
|
||||
* shims at it.
|
||||
* Codex starts a skill with `$name` rather than `/name`. When more than one CLI is installed
|
||||
* it asks which one, with the last pick as the default; with only one installed it uses that.
|
||||
* `--cli claude` / `--cli devin` / `--cli codex` skips the question. Before starting it asks
|
||||
* which model to run, from the curated list in models.json (shipped with every install) plus
|
||||
* any models the user added in User Preferences; Enter keeps the model the CLI last used, and
|
||||
* `--model` (or Codex's `-m`) skips the question. Any other arguments are forwarded to the CLI.
|
||||
* Self-contained, Node built-ins only: install.js copies this file to ~/.plan2code/bin/ and
|
||||
* points the global shims at it.
|
||||
*
|
||||
* `--pick-folder` (passed by the desktop shortcut, never forwarded to the CLI) asks for the
|
||||
* project folder with a native folder picker first, starting on the folder picked last time.
|
||||
@@ -101,16 +102,22 @@ const CLIS = [
|
||||
{
|
||||
id: 'claude',
|
||||
label: 'Claude Code',
|
||||
install: 'npm i -g @anthropic-ai/claude-code',
|
||||
prompt: '/plan2code',
|
||||
args: (extra) => ['/plan2code', '--permission-mode', 'bypassPermissions', ...extra],
|
||||
},
|
||||
{
|
||||
id: 'devin',
|
||||
label: 'Devin',
|
||||
install: 'https://devin.ai',
|
||||
prompt: '/plan2code',
|
||||
args: (extra) => ['--permission-mode', 'bypass', ...extra, '--', '/plan2code'],
|
||||
},
|
||||
{
|
||||
id: 'codex',
|
||||
label: 'Codex',
|
||||
install: 'npm i -g @openai/codex',
|
||||
prompt: '$plan2code',
|
||||
// Codex mentions a skill with `$name`; the prompt is its one positional argument.
|
||||
args: (extra) => ['--dangerously-bypass-approvals-and-sandbox', ...extra, '$plan2code'],
|
||||
},
|
||||
@@ -124,9 +131,9 @@ const SKILL_STEPS = [
|
||||
' 3. Start your agent there, then type /plan2code (Claude Code, Devin) or $plan2code (Codex).',
|
||||
];
|
||||
|
||||
/** The CLI ids as prose: "`claude`, `devin` or `codex`". */
|
||||
function cliIdList() {
|
||||
const ids = CLIS.map((cli) => '`' + cli.id + '`');
|
||||
/** The CLI ids as prose: "`claude`, `devin` or `codex`", or without the backticks for `quote` ''. */
|
||||
function cliIdList(quote = '`') {
|
||||
const ids = CLIS.map((cli) => quote + cli.id + quote);
|
||||
return `${ids.slice(0, -1).join(', ')} or ${ids[ids.length - 1]}`;
|
||||
}
|
||||
|
||||
@@ -362,14 +369,17 @@ async function chooseCli(requested) {
|
||||
if (requested !== undefined) {
|
||||
const known = CLIS.find((cli) => cli.id === requested);
|
||||
if (!known) {
|
||||
console.error(`${ce.red('plan2code:')} --cli takes ${CLIS.map((cli) => cli.id).join(', ')}${requested ? `, not "${requested}"` : ''}.`);
|
||||
console.error(`${ce.red('plan2code:')} --cli takes ${cliIdList('')}${requested ? `, not "${requested}"` : ''}.`);
|
||||
return { code: 2 };
|
||||
}
|
||||
const found = installed.find((cli) => cli.id === requested);
|
||||
if (!found) {
|
||||
console.error(`${ce.red('plan2code:')} the \`${known.id}\` CLI was not found on your PATH.`);
|
||||
console.error(`Install ${known.label}, open a new terminal, and run \`plan2code\` again.`);
|
||||
for (const step of SKILL_STEPS) console.error(step);
|
||||
console.error('');
|
||||
console.error(`To use ${known.label}:`);
|
||||
console.error(` 1. Install it: ${known.install}`);
|
||||
console.error(' 2. Open a new terminal and cd into the project you want to work on.');
|
||||
console.error(` 3. Run \`plan2code --cli ${known.id}\` there, or start ${known.label} and type ${known.prompt}.`);
|
||||
}
|
||||
if (found) announceCli(found);
|
||||
return found ? { cli: found } : { code: 127 };
|
||||
@@ -397,7 +407,7 @@ async function chooseCli(requested) {
|
||||
installed.forEach((cli, i) =>
|
||||
console.log(` ${c.cyan(`${i + 1})`)} ${cli.label}${cli.id === lastCli ? ` ${c.dim('(last used)')}` : ''}`)
|
||||
);
|
||||
console.log(c.dim('You can also skip this launcher and run `/plan2code` straight from your agent.'));
|
||||
console.log(c.dim('You can also skip this launcher and run `/plan2code` (`$plan2code` in Codex) straight from your agent.'));
|
||||
for (;;) {
|
||||
const answer = (await ask(`Choice ${c.green(`[${defaultIndex + 1}]`)}: `)).trim().toLowerCase();
|
||||
if (!answer) return { cli: installed[defaultIndex] };
|
||||
@@ -409,9 +419,17 @@ async function chooseCli(requested) {
|
||||
}
|
||||
}
|
||||
|
||||
/** True when the forwarded arguments already pick a model (`--model <name>` / `--model=<name>`). */
|
||||
function hasModelFlag(args) {
|
||||
return args.some((arg) => arg === '--model' || arg.startsWith('--model='));
|
||||
/**
|
||||
* True when the forwarded arguments already pick a model: `--model <name>` / `--model=<name>`,
|
||||
* and for Codex also its short form, `-m <name>` / `-m=<name>` / `-m<name>`.
|
||||
*/
|
||||
function hasModelFlag(args, cliId) {
|
||||
return args.some(
|
||||
(arg) =>
|
||||
arg === '--model' ||
|
||||
arg.startsWith('--model=') ||
|
||||
(cliId === 'codex' && arg.startsWith('-m'))
|
||||
);
|
||||
}
|
||||
|
||||
/** `[{ id, label }]` from a parsed models file for one CLI; anything malformed is skipped. */
|
||||
@@ -613,7 +631,7 @@ async function launch() {
|
||||
console.log(`Opening Plan2Code in ${c.cyan(folder)}`);
|
||||
}
|
||||
|
||||
if (!hasModelFlag(extraArgs)) await chooseModel(cli, extraArgs);
|
||||
if (!hasModelFlag(extraArgs, cli.id)) await chooseModel(cli, extraArgs);
|
||||
|
||||
const args = cli.args(extraArgs);
|
||||
const options = { cwd, stdio: 'inherit' };
|
||||
@@ -651,4 +669,4 @@ async function launch() {
|
||||
// Run only when invoked directly; requiring the file (the tests do) is load-only.
|
||||
if (require.main === module) launch();
|
||||
|
||||
module.exports = { mergeModels, modelEntries, renderBanner, paint };
|
||||
module.exports = { mergeModels, modelEntries, renderBanner, paint, hasModelFlag };
|
||||
@@ -12,7 +12,7 @@ Read references/grilling.md
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before Step 0: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow pathfinder` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then <D>/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.
|
||||
The FIRST thing you do, before anything else in this file — before Step 0: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow pathfinder` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/pathfinder.md. 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-launches.md), then Step 0.
|
||||
|
||||
## Backend
|
||||
|
||||
@@ -140,7 +140,7 @@ Close EVERY response with the trail once the map exists. You pick the form by wh
|
||||
|
||||
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).
|
||||
**Web console:** at session end or on a `__stop`, post `finish` (Form A's command) BEFORE `stop` (notes/pathfinder.md).
|
||||
|
||||
```
|
||||
⋅
|
||||
|
||||
@@ -8,7 +8,7 @@ Senior software architect and technical PM. Analyze requirements critically, ask
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before looking for a draft: ask **web console** (suggested — far easier for sign-offs with a non-engineer) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow plan` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then <D>/console.md → Planning notes. `--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 the AGENTS.md check.
|
||||
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before looking for a draft: ask **web console** (suggested — far easier for sign-offs with a non-engineer) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow plan` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/plan.md. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console-launches.md), then the AGENTS.md check.
|
||||
|
||||
## Project Context (BLOCKING)
|
||||
|
||||
@@ -52,7 +52,7 @@ Before Phase 1, run `node "<S>/specs.mjs" list` from the project root (`<S>`: `s
|
||||
- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4
|
||||
- Status "Escalated from Quick Task - Resume at Phase 2": Acknowledge, verify requirements, skip to Phase 2
|
||||
- Status "Draft" or "Complete": Ask user how to proceed
|
||||
- No PLAN-DRAFT: Begin at Phase 1. Console: its idea card carries `"templates": "idea"` (console.md → Starter templates)
|
||||
- No PLAN-DRAFT: Begin at Phase 1. Console: its idea card carries `"templates": "idea"` (console.md → The kinds)
|
||||
|
||||
---
|
||||
|
||||
@@ -269,7 +269,7 @@ When complete (PLAN-DRAFT created), tell user:
|
||||
2. **Next: `/plan2code-2-document`** (NOT implementation)
|
||||
3. Documentation auto-discovers planning files
|
||||
|
||||
**On the web console:** at every session end, and on a `__stop`, post `finish` BEFORE `stop`, per console.md → Planning.
|
||||
**On the web console:** at every session end, and on a `__stop`, post `finish` BEFORE `stop`, per notes/plan.md.
|
||||
|
||||
**Closing example:**
|
||||
> "Planning complete. Created in `specs/<feature-name>/`:
|
||||
|
||||
@@ -8,7 +8,7 @@ Senior software architect updating implementation specs when requirements change
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before Step 1, before reading a spec: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow revise-plan` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-1b-revise-plan/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir; add `--spec specs/<feature-name>` if known, else post `specDir` later), then <D>/console.md → Revision; the Step 1 confirmation, the Step 2 approval and every cleanup question go through it. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console.md → Launches), then Step 1.
|
||||
The FIRST thing you do, before anything else in this file — before Step 1, before reading a spec: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow revise-plan` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-1b-revise-plan/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir; add `--spec specs/<feature-name>` if known, else post `specDir` later), then read <D>/console.md and <D>/notes/revise-plan.md; the Step 1 confirmation, the Step 2 approval and every cleanup question go through it. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Step 1.
|
||||
|
||||
## Rules
|
||||
|
||||
@@ -240,4 +240,4 @@ Work summary — tell user: change type, tasks added/modified/removed, phases re
|
||||
|
||||
Returning context: Revised specs in `specs/<feature-name>/`. Run `/plan2code-3-implement --web` in a new conversation to continue implementation.
|
||||
|
||||
**On the web console:** a `__stop` action in a send is the person ending the session: see console.md → Stop requests. Specs change only at Step 3, so a stop before then saves nothing and needs none. At every session end post `finish` BEFORE `stop`: `"command": "/plan2code-3-implement specs/<feature-name>/overview.md"` when revised, or the revise-plan command on an abort. The closing box above is printed to a terminal the browser user is not watching.
|
||||
**On the web console:** a `__stop` action in a send is the person ending the session: see console-stop.md. Specs change only at Step 3, so a stop before then saves nothing and needs none. At every session end post `finish` BEFORE `stop`: `"command": "/plan2code-3-implement specs/<feature-name>/overview.md"` when revised, or the revise-plan command on an abort. The closing box above is printed to a terminal the browser user is not watching.
|
||||
@@ -8,7 +8,7 @@ Technical writer transforming planning documents into precise, complete implemen
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else — before Auto-Discovery: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow document` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec` once known), then <D>/console.md → Documentation. 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 Auto-Discovery. `__stop` ends it; post `finish` BEFORE `stop` at every end.
|
||||
The FIRST thing you do, before anything else — before Auto-Discovery: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow document` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec` once known), then read <D>/console.md and <D>/notes/document.md. 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-launches.md), then Auto-Discovery. `__stop` ends it; post `finish` BEFORE `stop` at every end.
|
||||
|
||||
## Scripts
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Orchestrate one implementation phase and its focused independent review as a sin
|
||||
|
||||
## Web Console
|
||||
|
||||
The FIRST thing you do, before anything else in this file: Implementation Mode's Interface question — **web console** or **terminal**? On the web console, run `node "<D>/console.mjs" open --workflow implement-review` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-3-implement-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then follow <D>/building.md → Implement + Review: the Stage 2 findings go out as the page's fix list, Stage 4 is the only sign-off item, and the Stage 5 `finish` never carries the review offer. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console.md → Launches), then the spec.
|
||||
The FIRST thing you do, before anything else in this file: Implementation Mode's Interface question — **web console** or **terminal**? On the web console, run `node "<D>/console.mjs" open --workflow implement-review` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-3-implement-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md, <D>/building.md and <D>/notes/implement.md in one batch (all of it; its Implement + Review section covers Stages 2–5), and <D>/building-review.md when Stage 2 starts: the Stage 2 findings go out as the page's fix list, Stage 4 is the only sign-off item, and the Stage 5 `finish` never carries the review offer. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then the spec.
|
||||
|
||||
## Controlling Contract
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Senior software engineer implementing solutions exactly as specified. Follow spe
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before reading a spec, before Phase 1: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow implement` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-3-implement/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then <D>/console.md and <D>/building.md; progress, every question and the sign-off go through it. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console.md → Launches), then the spec.
|
||||
The FIRST thing you do, before anything else in this file — before reading a spec, before Phase 1: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow implement` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-3-implement/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md, <D>/building.md and <D>/notes/implement.md in one batch; progress, every question and the sign-off go through it. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then the spec.
|
||||
|
||||
## Scripts
|
||||
|
||||
@@ -209,10 +209,10 @@ On user "approved":
|
||||
| Phase X+1: [Name] | Z | [One-sentence goal] |
|
||||
|
||||
5. Write a one-line subject for the phase, then give the user the `command` from `commit-msg.mjs --subject "<subject>" --add-all`. It enforces the format: subject ≤100 chars and EXACTLY TWO -m flags (subject, `AI Assisted`), no body. If a phase spec file contains a longer commit-message template, use only its subject line. The diff is the body; the PR is the explanation. On Windows PowerShell 5.1 (no `&&`), give `add` and `commit` as two commands instead.
|
||||
6. **If more phases:** "NEXT STEP: Start NEW conversation and run: `/plan2code-3-implement --web`"
|
||||
6. **If more phases:** "NEXT STEP: Start NEW conversation and run: `/plan2code-3-implement specs/<feature>/overview.md --web`"
|
||||
7. **If final phase:** "NEXT STEP: Start NEW conversation and run: `/plan2code-4-finalize --web`"
|
||||
8. Mention `/plan2code-1b-revise-plan --web` option
|
||||
9. **On the web console:** post `finish` with the next step — never a review offer; it was on the sign-off card — then wait and `stop` per building.md.
|
||||
9. **On the web console:** post `finish` with the next step — never a review offer; it was on the sign-off card — then wait and `stop` per notes/implement.md.
|
||||
|
||||
Planny (continuing):
|
||||
```
|
||||
|
||||
@@ -8,7 +8,7 @@ QA engineer and technical lead performing rigorous final validation. Verify spec
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before the Required Context check, before Step 1: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow finalize` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec specs/<feature-name>` if known, else post `specDir` later), then <D>/console.md → Finalize; the audit options, the doc-update approval and every cleanup confirmation go through it. 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 the Required Context check.
|
||||
The FIRST thing you do, before anything else in this file — before the Required Context check, before Step 1: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow finalize` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec specs/<feature-name>` if known, else post `specDir` later), then read <D>/console.md and <D>/notes/finalize.md; the audit options, the doc-update approval and every cleanup confirmation go through it. 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-launches.md), then the Required Context check.
|
||||
|
||||
## Scripts
|
||||
|
||||
@@ -64,7 +64,7 @@ Complete steps in order. Report progress after each.
|
||||
| `[x]` | Completed | Completed | Verify implementation exists |
|
||||
| `[?]` | Assumed complete | Completed | List it: it was never verified |
|
||||
| `[ ]` / `[/]` | Not started / started | Incomplete | Flag INCOMPLETE |
|
||||
| `[!]` | Blocked | Incomplete | Document blocker |
|
||||
| `[!]` | Blocked | Blocked (its own column; `totals.blocked`, not in `totals.incomplete`) | Document blocker |
|
||||
|
||||
2. Build the audit table from each phase's `tasks` (Completed = `complete` + `assumed`; Incomplete = `pending` + `in-progress`; each phase's `openTasks`, `blockedTasks` and `assumedTasks` name them; the Total row is `totals`):
|
||||
|
||||
@@ -78,7 +78,7 @@ Complete steps in order. Report progress after each.
|
||||
|
||||
3. Completion is `completionPercent` (Completed / Total). Report any `error` in `checks` too (e.g. a phase marked `[x]` in overview.md with open tasks).
|
||||
|
||||
#### If incomplete tasks exist:
|
||||
#### If incomplete or blocked tasks exist (`totals.incomplete + totals.blocked > 0`):
|
||||
|
||||
```markdown
|
||||
INCOMPLETE TASKS DETECTED
|
||||
@@ -343,8 +343,8 @@ If you discovered undocumented commands, dependency quirks, gotchas (>5min cost)
|
||||
|
||||
(Step 7 already delivered the completion summary — don't repeat it.)
|
||||
|
||||
Suggested commit (only if README, CHANGELOG, or other tracked docs were updated): the `command` from `commit-msg.mjs --subject "chore: finalize and archive <feature-name>"`.
|
||||
Suggested commit (only if README, CHANGELOG, or other tracked docs were updated): the `command` from `commit-msg.mjs --subject "chore: finalize and archive <feature-name>"`. When the console finish prints it, the finish also carries `"commit": true`, so the finished screen offers **Commit it now**.
|
||||
|
||||
Returning context: Feature complete. Specs archived to `specs--completed/<feature-name>/`.
|
||||
|
||||
**On the web console:** a `__stop` action in a send ends the session: see console.md → Stop requests. At every session end post `finish` BEFORE `stop`, per console.md → Finalize — the completion summary is printed to a terminal the browser user is not watching.
|
||||
**On the web console:** a `__stop` action in a send ends the session: see console-stop.md. At every session end post `finish` BEFORE `stop`, per notes/finalize.md — the completion summary is printed to a terminal the browser user is not watching.
|
||||
@@ -88,7 +88,7 @@ const lines = (s) => s.split(/\r?\n/).filter(Boolean);
|
||||
function requireRepo() {
|
||||
const top = git(["rev-parse", "--show-toplevel"], process.cwd());
|
||||
if (!top.ok || !top.out) {
|
||||
fail(EXIT.NOT_FOUND, "not-a-repo", "This directory is not inside a git repository.", "Run the Git commit skill to start one, then come back.");
|
||||
fail(EXIT.NOT_FOUND, "not-a-repo", "This directory is not inside a git repository.", "Run the Git skill to start one, then come back.");
|
||||
}
|
||||
return top.out;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ Careful release scribe. Work out the right version from the default branch, find
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before reading the repository: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow changelog` before reading (<D>: references/web-console/ beside this SKILL.md, ~/.agents/skills/plan2code-changelog/references/web-console/ globally, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md → Changelog. Every question goes through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`) take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console.md → Launches), then Step 1. On the console, a `__stop` action is the person ending the session (console.md → Stop requests); at every session end post `finish` BEFORE `stop`.
|
||||
The FIRST thing you do, before anything else in this file, before reading the repository: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow changelog` before reading (<D>: references/web-console/ beside this SKILL.md, ~/.agents/skills/plan2code-changelog/references/web-console/ globally, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/changelog.md. Every question goes through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`) take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Step 1. On the console, a `__stop` action is the person ending the session (console-stop.md); at every session end post `finish` BEFORE `stop`.
|
||||
|
||||
## Scripts
|
||||
|
||||
@@ -38,7 +38,7 @@ Optional: a note on what the work is, for example `/plan2code-changelog the expo
|
||||
|
||||
## Steps
|
||||
|
||||
1. **State.** Run `state`. Exit 3 `not-a-repo` → say so and stop (the Git commit skill can start one). Exit 3 `no-changelog` → offer to start `CHANGELOG.md` with a `# Changelog` title and one entry for this work, then continue. `onDefault` with no `commits` and no `uncommitted` → say there is nothing new on this branch and stop.
|
||||
1. **State.** Run `state`. Exit 3 `not-a-repo` → say so and stop (the Git skill can start one). Exit 3 `no-changelog` → offer to start `CHANGELOG.md` with a `# Changelog` title and one entry for this work, then continue. `onDefault` with no `commits` and no `uncommitted` → say there is nothing new on this branch and stop.
|
||||
2. **Classify.** Use the highest that applies. **Major**: a breaking change (ask, never assume). **Minor**: a new capability a user can see, or any path in `addedSkills`. **Patch**: fixes, behavior changes, docs, internals. Read `commits`, `files`, `uncommitted` and the diff where the subject is unclear.
|
||||
3. **Version.**
|
||||
- `canExtend` (the branch already owns an entry above `base`, it is not released and no other branch has it): keep `branchTop.version` and add to it. If the classification needs more than `entryBump` (a minor change under a patch-sized version), propose renumbering with `bump --from <base.version> --kind <kind>`: the heading changes, the content stays.
|
||||
@@ -48,12 +48,12 @@ Optional: a note on what the work is, for example `/plan2code-changelog the expo
|
||||
- No `base` (no default branch to compare): ask which version to start from.
|
||||
Show the choice as `main is at X, the branch has Y, so Z (reason)`. A new or renumbered dated heading gets `today`; when you extend a dated entry whose date is not `today`, offer to refresh it.
|
||||
4. **Suggest entries.** Compare `entry` with the gap (`commits`, `files`, `uncommitted`). Anything the entry already says is covered. Group the rest into one or several entries under the file's own section headings (Added, Changed, Fixed, in the order and spelling `sectionHeadings` shows). Name the internal-only work you left out. Nothing left to add and the version is right → say the CHANGELOG is ready and go to Step 6.
|
||||
5. **Edit and approve.** Show the suggested entries so each can be edited, removed or added to (console.md → Changelog has the cards). Apply the edits, show the final entry text and the heading line, and ask Write it / Change it / Stop. On yes, write `CHANGELOG.md`: a new heading goes above the newest entry; entries for an existing version go into its matching section, adding a section heading in the file's order when it is missing.
|
||||
5. **Edit and approve.** Show the suggested entries so each can be edited, removed or added to (notes/changelog.md has the cards). Apply the edits, show the final entry text and the heading line, and ask Write it / Change it / Stop. On yes, write `CHANGELOG.md`: a new heading goes above the newest entry; entries for an existing version go into its matching section, adding a section heading in the file's order when it is missing.
|
||||
6. **package.json.** When `package.exists`, `package.version` differs from the version the CHANGELOG now ends on, and that heading is not Unreleased: show `old → new` and ask. On yes run `set-package-version`. When `package.lockfile`, remind the person to refresh it (`npm install`); do not run it. When it already matches, say so.
|
||||
7. **Hand off.** Ask: run Git commit next? (yes / no). Yes → launch Git commit right here, as the dashboard's card does: on the console run `open --resume <sid> --no-open --workflow git-commit` (no `finish`, no `stop`), then open `~/.agents/skills/plan2code-git-commit/SKILL.md` with your file-read tool (never a skill-invocation tool) and follow it from the top, its Interface step already answered; in the terminal just read and follow it. No → Session End. This skill never commits itself.
|
||||
7. **Hand off.** Ask: Commit this now? (yes / no). Yes → hand off to Git right here: on the console run `open --resume <sid> --no-open --workflow git` (no `finish`, no `stop`), then read `~/.agents/skills/plan2code-git/SKILL.md` with your file-read tool (never a skill-invocation tool) and start with its commit flow, its Interface step already answered; in the terminal just read and follow it, starting with its commit flow. No → Session End. This skill never commits itself.
|
||||
|
||||
## Session End
|
||||
|
||||
Reached only when they declined Git commit (a yes hands the session to that skill instead). Terminal: the version, the entries written and the `package.json` change. Web console: post `finish` (headline, a body with the version and entries, `"dashboard": true`, no `command`) BEFORE `stop`, then keep waiting for the dashboard press (console.md → Finishing). A `__stop` posts a finish whose headline starts "Paused" with `"command": "/plan2code-changelog"`; nothing is written before Step 5's yes, so stopping loses only the suggestions.
|
||||
Reached only when they declined to commit now (a yes hands the session to Git instead). Terminal: the version, the entries written and the `package.json` change. Web console: post `finish` (headline, a body with the version and entries, `"dashboard": true`, no `command`) BEFORE `stop`, then keep waiting for the dashboard press (console-finish.md). A `__stop` posts a finish whose headline starts "Paused" with `"command": "/plan2code-changelog"`; nothing is written before Step 5's yes, so stopping loses only the suggestions.
|
||||
|
||||
Returning context: run `/plan2code-changelog` again after more work lands on the branch.
|
||||
@@ -1,307 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
// git-state.mjs: what the Git commit skill needs to know about the repository.
|
||||
//
|
||||
// The skill's questions about git have one correct answer each: which branch is
|
||||
// the default, what is staged, which files are risky, what a push would be. They
|
||||
// live here so no prompt works them out by eye or per shell. This script only
|
||||
// reads: it never changes the repository, the index or the working tree. The
|
||||
// agent runs git init, switch, add, commit and push itself, each behind a yes.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { EXIT, fail, out, parseArgs, run } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
git-state.mjs: read-only facts about the git repository. JSON on stdout. It never
|
||||
changes the repository.
|
||||
|
||||
node git-state.mjs state
|
||||
node git-state.mjs branch-check --name <branch>
|
||||
node git-state.mjs init-check
|
||||
|
||||
state Run from inside a repository. Prints { ok, root, branch, detached,
|
||||
hasCommits, defaultBranch, defaultFrom, onDefault, inProgress,
|
||||
conflicted, staged, unstaged, untracked, nothingToCommit,
|
||||
sensitive, large, remotes, upstream, ahead, behind, unpublished,
|
||||
push }.
|
||||
branch null when HEAD is detached.
|
||||
defaultBranch origin/HEAD, else local main, else master, else
|
||||
(no commits yet, on main or master) that branch,
|
||||
else null. defaultFrom says which: origin/HEAD,
|
||||
local-main, local-master, unborn, null.
|
||||
inProgress merge, rebase, cherry-pick, revert or null.
|
||||
staged, unstaged, untracked, conflicted
|
||||
[{ path, status }]; a conflicted file is listed
|
||||
only under conflicted.
|
||||
sensitive paths that look like secrets (.env, keys,
|
||||
credentials); left out unless the person insists.
|
||||
large [{ path, bytes }] for files over 5 MB.
|
||||
ahead, behind commits against the upstream; null without one.
|
||||
unpublished commits exist and the branch has no upstream.
|
||||
push null when there is nothing to push, no remote, no
|
||||
commits or HEAD is detached; otherwise
|
||||
{ command, setsUpstream, remote, needsRemoteChoice }.
|
||||
branch-check Is --name a usable new branch name here? Prints { ok, name, valid,
|
||||
exists }. Exit 4 when the name is invalid or already taken.
|
||||
init-check Run anywhere. Can git init be offered in this folder? Prints { ok,
|
||||
path, safe, reason?, insideRepo, repoRoot?, hasGitignore,
|
||||
suggestedIgnore }. safe is false (reason: inside-repo, home or
|
||||
root) for a folder that is already in a repository, the home
|
||||
folder and a drive root. suggestedIgnore lists .gitignore lines
|
||||
for what is in the folder (node_modules/, .env, build output).
|
||||
|
||||
Exit: 0 ok · 1 crash · 2 bad arguments · 3 not a git repository · 4 invalid or
|
||||
taken branch name.
|
||||
`;
|
||||
|
||||
const LARGE_BYTES = 5 * 1024 * 1024;
|
||||
// An untracked folder is one entry in the status; its files are listed
|
||||
// separately so a .env inside a new folder is still caught. Every name is
|
||||
// checked, but only the first STAT_LIMIT files are sized, so a forgotten
|
||||
// node_modules cannot make this slow.
|
||||
const STAT_LIMIT = 2000;
|
||||
const CONFLICT = new Set(["DD", "AU", "UD", "UA", "DU", "AA", "UU"]);
|
||||
|
||||
function git(args, cwd, { raw = false } = {}) {
|
||||
try {
|
||||
const stdout = execFileSync("git", args, {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
// Without this, git status refreshes the index on disk: a write.
|
||||
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
|
||||
});
|
||||
return { ok: true, out: raw ? stdout : stdout.trim() };
|
||||
} catch {
|
||||
return { ok: false, out: "" };
|
||||
}
|
||||
}
|
||||
|
||||
function requireRepo() {
|
||||
const top = git(["rev-parse", "--show-toplevel"], process.cwd());
|
||||
if (!top.ok || !top.out) {
|
||||
fail(EXIT.NOT_FOUND, "not-a-repo", "This directory is not inside a git repository.", "Run git-state.mjs init-check to see whether this folder can start one.");
|
||||
}
|
||||
return top.out;
|
||||
}
|
||||
|
||||
// Basename tests for files that probably hold secrets.
|
||||
const ENV_OK = new Set([".env.example", ".env.sample", ".env.template"]);
|
||||
function isSensitive(file) {
|
||||
const b = file.split("/").pop();
|
||||
if (b === ".env" || (b.startsWith(".env.") && !ENV_OK.has(b))) return true;
|
||||
if (/\.(pem|key|p12|pfx|keystore|jks)$/.test(b)) return true;
|
||||
if (/^id_(rsa|dsa|ecdsa|ed25519)/.test(b)) return true;
|
||||
if (/^credentials.*\.json$/.test(b) || b.endsWith(".credentials")) return true;
|
||||
if (b === ".npmrc" || b === ".pypirc" || b === ".netrc") return true;
|
||||
return b.startsWith("secrets.");
|
||||
}
|
||||
|
||||
function inProgress(root) {
|
||||
const dir = git(["rev-parse", "--absolute-git-dir"], root).out;
|
||||
if (!dir) return null;
|
||||
const has = (n) => fs.existsSync(path.join(dir, n));
|
||||
if (has("MERGE_HEAD")) return "merge";
|
||||
if (has("rebase-merge") || has("rebase-apply")) return "rebase";
|
||||
if (has("CHERRY_PICK_HEAD")) return "cherry-pick";
|
||||
if (has("REVERT_HEAD")) return "revert";
|
||||
return null;
|
||||
}
|
||||
|
||||
function defaultBranch(root, branch, hasCommits) {
|
||||
const head = git(["symbolic-ref", "-q", "--short", "refs/remotes/origin/HEAD"], root);
|
||||
if (head.ok && head.out) return { name: head.out.replace(/^origin\//, ""), from: "origin/HEAD" };
|
||||
if (git(["show-ref", "--verify", "-q", "refs/heads/main"], root).ok) return { name: "main", from: "local-main" };
|
||||
if (git(["show-ref", "--verify", "-q", "refs/heads/master"], root).ok) return { name: "master", from: "local-master" };
|
||||
if (!hasCommits && (branch === "main" || branch === "master")) return { name: branch, from: "unborn" };
|
||||
return { name: null, from: null };
|
||||
}
|
||||
|
||||
// git status --porcelain=v1 -z: "XY path" entries; a rename or copy is followed
|
||||
// by one more field holding the original path.
|
||||
function parseStatus(root) {
|
||||
const res = git(["status", "--porcelain=v1", "-z", "--untracked-files=normal"], root, { raw: true });
|
||||
const files = { staged: [], unstaged: [], untracked: [], conflicted: [] };
|
||||
const fields = res.out.split("\0");
|
||||
for (let i = 0; i < fields.length; i++) {
|
||||
const f = fields[i];
|
||||
if (f.length < 4) continue;
|
||||
const x = f[0];
|
||||
const y = f[1];
|
||||
const p = f.slice(3);
|
||||
if (x === "R" || x === "C" || y === "R" || y === "C") i++;
|
||||
if (x === "?" && y === "?") files.untracked.push({ path: p, status: "?" });
|
||||
else if (CONFLICT.has(x + y)) files.conflicted.push({ path: p, status: x + y });
|
||||
else {
|
||||
if (x !== " " && x !== "?") files.staged.push({ path: p, status: x });
|
||||
if (y !== " " && y !== "?") files.unstaged.push({ path: p, status: y });
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
function riskyFiles(root, files) {
|
||||
const names = new Set();
|
||||
for (const list of [files.staged, files.unstaged, files.untracked, files.conflicted]) {
|
||||
for (const f of list) if (!f.path.endsWith("/")) names.add(f.path);
|
||||
}
|
||||
if (files.untracked.some((f) => f.path.endsWith("/"))) {
|
||||
const all = git(["ls-files", "-o", "--exclude-standard", "-z"], root, { raw: true });
|
||||
for (const n of all.out.split("\0")) if (n) names.add(n);
|
||||
}
|
||||
const sensitive = [];
|
||||
const large = [];
|
||||
let statted = 0;
|
||||
for (const p of names) {
|
||||
if (isSensitive(p)) sensitive.push(p);
|
||||
if (statted >= STAT_LIMIT) continue;
|
||||
statted++;
|
||||
try {
|
||||
const st = fs.statSync(path.join(root, p));
|
||||
if (st.isFile() && st.size > LARGE_BYTES) large.push({ path: p, bytes: st.size });
|
||||
} catch {
|
||||
// a deletion, or a file that vanished
|
||||
}
|
||||
}
|
||||
return { sensitive: sensitive.sort(), large: large.sort((a, b) => a.path.localeCompare(b.path)) };
|
||||
}
|
||||
|
||||
function pushPlan(root, { branch, hasCommits, remotes, upstream, ahead }) {
|
||||
if (!branch || !hasCommits || !remotes.length) return null;
|
||||
if (upstream) {
|
||||
const configured = git(["config", "--get", `branch.${branch}.remote`], root).out;
|
||||
const remote = configured || upstream.split("/")[0];
|
||||
if (remote === "." || !ahead) return null;
|
||||
return { command: "git push", setsUpstream: false, remote, needsRemoteChoice: false };
|
||||
}
|
||||
const remote = remotes.length === 1 ? remotes[0] : remotes.includes("origin") ? "origin" : remotes[0];
|
||||
return { command: `git push -u ${remote} ${branch}`, setsUpstream: true, remote, needsRemoteChoice: remotes.length > 1 };
|
||||
}
|
||||
|
||||
function state() {
|
||||
const root = requireRepo();
|
||||
const branchRef = git(["symbolic-ref", "--short", "-q", "HEAD"], root);
|
||||
const branch = branchRef.ok && branchRef.out ? branchRef.out : null;
|
||||
const hasCommits = git(["rev-parse", "-q", "--verify", "HEAD"], root).ok;
|
||||
const def = defaultBranch(root, branch, hasCommits);
|
||||
const files = parseStatus(root);
|
||||
const { sensitive, large } = riskyFiles(root, files);
|
||||
const remotes = git(["remote"], root).out.split(/\r?\n/).filter(Boolean);
|
||||
|
||||
const up = branch ? git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], root) : { ok: false };
|
||||
const upstream = up.ok && up.out ? up.out : null;
|
||||
let ahead = null;
|
||||
let behind = null;
|
||||
if (upstream) {
|
||||
const counts = git(["rev-list", "--left-right", "--count", "@{u}...HEAD"], root).out.split(/\s+/).map(Number);
|
||||
if (counts.length === 2 && counts.every(Number.isFinite)) [behind, ahead] = counts;
|
||||
}
|
||||
const unpublished = hasCommits && !!branch && !upstream;
|
||||
|
||||
out({
|
||||
ok: true,
|
||||
root,
|
||||
branch,
|
||||
detached: branch === null,
|
||||
hasCommits,
|
||||
defaultBranch: def.name,
|
||||
defaultFrom: def.from,
|
||||
onDefault: !!branch && !!def.name && branch === def.name,
|
||||
inProgress: inProgress(root),
|
||||
conflicted: files.conflicted,
|
||||
staged: files.staged,
|
||||
unstaged: files.unstaged,
|
||||
untracked: files.untracked,
|
||||
nothingToCommit: !files.staged.length && !files.unstaged.length && !files.untracked.length && !files.conflicted.length,
|
||||
sensitive,
|
||||
large,
|
||||
remotes,
|
||||
upstream,
|
||||
ahead,
|
||||
behind,
|
||||
unpublished,
|
||||
push: pushPlan(root, { branch, hasCommits, remotes, upstream, ahead }),
|
||||
});
|
||||
}
|
||||
|
||||
function branchCheck(args) {
|
||||
const name = (args.name || "").trim();
|
||||
if (!name) fail(EXIT.USAGE, "missing-name", "--name is required.", "Example: branch-check --name feature/export-csv");
|
||||
const root = requireRepo();
|
||||
const suggestion = "Use lowercase words joined by '-' under a prefix such as feature/, fix/, chore/ or docs/ (feature/export-csv).";
|
||||
// check-ref-format --branch also expands @{-1}; a changed name is not a name.
|
||||
const checked = name.startsWith("-") ? { ok: false } : git(["check-ref-format", "--branch", name], root);
|
||||
if (!checked.ok || checked.out !== name) {
|
||||
fail(EXIT.INVALID, "invalid-name", `"${name}" is not a valid git branch name.`, suggestion);
|
||||
}
|
||||
const exists = git(["show-ref", "--verify", "-q", `refs/heads/${name}`], root).ok;
|
||||
if (exists) fail(EXIT.INVALID, "branch-exists", `A branch named "${name}" already exists.`, `Pick another name, for example "${name}-2".`);
|
||||
// git cannot hold both feature and feature/x: a branch is a file in refs/heads.
|
||||
const heads = git(["for-each-ref", "--format=%(refname:short)", "refs/heads"], root).out.split(/\r?\n/).filter(Boolean);
|
||||
const clash = heads.find((h) => name.startsWith(`${h}/`) || h.startsWith(`${name}/`));
|
||||
if (clash) fail(EXIT.INVALID, "branch-conflict", `"${name}" clashes with the existing branch "${clash}" (one is a folder of the other).`, "Pick a name that is not nested under an existing branch.");
|
||||
out({ ok: true, name, valid: true, exists: false });
|
||||
}
|
||||
|
||||
// Top-level names that should not go into a first commit.
|
||||
const IGNORE_DIRS = ["node_modules", "dist", "build", "out", ".next", "coverage", "target", "__pycache__", ".venv", "venv"];
|
||||
|
||||
function suggestedIgnore(dir) {
|
||||
let names = [];
|
||||
try {
|
||||
names = fs.readdirSync(dir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const lines = [];
|
||||
for (const d of IGNORE_DIRS) if (names.includes(d)) lines.push(`${d}/`);
|
||||
const envs = names.filter((n) => n === ".env" || (n.startsWith(".env.") && !ENV_OK.has(n)));
|
||||
if (envs.length) {
|
||||
lines.push(".env", ".env.*");
|
||||
if (names.includes(".env.example")) lines.push("!.env.example");
|
||||
}
|
||||
if (names.includes(".DS_Store")) lines.push(".DS_Store");
|
||||
if (names.includes("Thumbs.db")) lines.push("Thumbs.db");
|
||||
if (names.some((n) => n.endsWith(".log"))) lines.push("*.log");
|
||||
return lines;
|
||||
}
|
||||
|
||||
const sameFolder = (a, b) => (process.platform === "win32" || process.platform === "darwin" ? a.toLowerCase() === b.toLowerCase() : a === b);
|
||||
|
||||
function initCheck() {
|
||||
const cwd = fs.realpathSync.native(process.cwd());
|
||||
const top = git(["rev-parse", "--show-toplevel"], cwd);
|
||||
const insideRepo = top.ok && !!top.out;
|
||||
let home = os.homedir();
|
||||
try {
|
||||
home = fs.realpathSync.native(home);
|
||||
} catch {
|
||||
// a home folder that no longer exists cannot be the current folder
|
||||
}
|
||||
let safe = true;
|
||||
let reason;
|
||||
if (insideRepo) [safe, reason] = [false, "inside-repo"];
|
||||
else if (sameFolder(cwd, home)) [safe, reason] = [false, "home"];
|
||||
else if (cwd === path.parse(cwd).root) [safe, reason] = [false, "root"];
|
||||
const result = { ok: true, path: cwd, safe };
|
||||
if (reason) result.reason = reason;
|
||||
result.insideRepo = insideRepo;
|
||||
if (insideRepo) result.repoRoot = top.out;
|
||||
result.hasGitignore = fs.existsSync(path.join(cwd, ".gitignore"));
|
||||
result.suggestedIgnore = suggestedIgnore(cwd);
|
||||
out(result);
|
||||
}
|
||||
|
||||
run(USAGE, async (argv) => {
|
||||
const args = parseArgs(argv, { values: ["name"] });
|
||||
const [cmd, ...extra] = args._;
|
||||
if (!cmd) fail(EXIT.USAGE, "missing-command", "A subcommand is required: state, branch-check or init-check.", "Run with --help for usage.");
|
||||
if (extra.length) fail(EXIT.USAGE, "stray-argument", `Unexpected argument(s): ${extra.join(" ")}.`, "Run with --help for usage.");
|
||||
if (cmd === "state") return state();
|
||||
if (cmd === "branch-check") return branchCheck(args);
|
||||
if (cmd === "init-check") return initCheck();
|
||||
fail(EXIT.USAGE, "unknown-command", `Unknown subcommand "${cmd}".`, "Use state, branch-check or init-check.");
|
||||
});
|
||||
@@ -1,58 +0,0 @@
|
||||
# 🔀 GIT COMMIT MODE
|
||||
|
||||
Start all GIT COMMIT MODE responses with '🔀'
|
||||
|
||||
## Role
|
||||
|
||||
Careful committer. Read what changed, write a clear message, suggest a split when the work is really two jobs, and push only when asked. Nothing leaves the machine without a yes.
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before reading the repository: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow git-commit` before reading (<D>: references/web-console/ beside this SKILL.md, ~/.agents/skills/plan2code-git-commit/references/web-console/ globally, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md → Git commit. Every question goes through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`) take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console.md → Launches), then Step 1. On the console, a `__stop` action is the person ending the session (console.md → Stop requests); at every session end post `finish` BEFORE `stop`.
|
||||
|
||||
## Scripts
|
||||
|
||||
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-git-commit/scripts/` globally). Run them from the project folder. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says.
|
||||
|
||||
- `node "<S>/git-state.mjs" state`: read-only snapshot. `branch`, `detached`, `defaultBranch`, `onDefault`, `inProgress`, `conflicted`, `staged`, `unstaged`, `untracked`, `nothingToCommit`, `sensitive`, `large`, `remotes`, `ahead`, `behind`, `push`. Exit 3 `not-a-repo`.
|
||||
- `node "<S>/git-state.mjs" branch-check --name <name>`: is the name usable? Exit 4 means invalid or taken.
|
||||
- `node "<S>/git-state.mjs" init-check`: can `git init` be offered here? `safe`, `reason`, `hasGitignore`, `suggestedIgnore`.
|
||||
- `node "<S>/commit-msg.mjs" --subject "<subject>" --files <path> [--files <path> ...]`: the commit command (one `--files` per path). Exit 4 means the subject or a path breaks a rule: rephrase it.
|
||||
|
||||
## Project context
|
||||
|
||||
Read `./AGENTS.md` when it exists, for commit conventions (subject style, branch names). Never block on it.
|
||||
|
||||
## Argument
|
||||
|
||||
An optional commit subject, for example `/plan2code-git-commit fix timeout on report export`. `--web` is the console flag, not part of the subject.
|
||||
|
||||
## Rules
|
||||
|
||||
- `git status` never with `-uall`.
|
||||
- Stage named files only. Never `git add -A` or `git add .`.
|
||||
- Never amend unless asked. Never `--no-verify`. Never force-push.
|
||||
- A failed hook: diagnose it, fix the cause, re-stage the group's files, make a NEW commit. A hook that fails on a problem unrelated to the staged changes is reported to the person, not worked around.
|
||||
- Never push, create a branch or run `git init` without an explicit yes. The commit itself needs a yes unless the subject came as the argument.
|
||||
- `sensitive` and `large` files are left out and named. Include one only if the person insists after a warning.
|
||||
- The message is exactly what `commit-msg.mjs` builds: `<subject>`, a blank line, `AI Assisted`. Subject at most 100 characters, about why. No other AI attribution.
|
||||
- Run no tests and no review before committing (Implement and Review do that).
|
||||
- On Windows PowerShell 5.1 (no `&&`), run `add` and `commit` as two commands.
|
||||
|
||||
## Steps
|
||||
|
||||
1. **State.** Run `state`. Exit 3 → Step 1b. `inProgress` or `conflicted` → say what is in progress (a merge, a rebase, files with conflicts) and stop: finish it first.
|
||||
1b. **Not a repository.** Run `init-check`. `safe: false` → explain (the home folder or a drive root) and stop. `safe` → ask before `git init`, naming the folder. On yes run it. If `hasGitignore` is false and `suggestedIgnore` is not empty, propose that `.gitignore` for approval, write it, then continue at Step 3 (the first commit; no push offer later because there is no remote; say it can be added with `git remote add origin <url>`).
|
||||
2. **Nothing to commit.** If `push` is not null, go to Step 7. Otherwise say the tree is clean and everything is pushed (or that there is no remote), and finish.
|
||||
3. **Branch.** When `onDefault` (or `detached`) and `hasCommits`, offer a new branch named `<type>/<short-description>` (types: feature, fix, chore, docs, refactor, test) from the changes. Run any name the person types through `branch-check`. On yes: `git switch -c <name>`. Skipping is always fine (on a detached HEAD, warn that commits there are easy to lose). When `defaultBranch` is null say why there is no offer.
|
||||
4. **Read the changes.** `git diff`, `git diff --cached` and the untracked files (an `untracked` path ending in `/` is a folder: list its files with `git ls-files -o --exclude-standard -- <folder>` and stage them by name). If the person staged some files, work from that staged set and leave the rest alone (say what was left). Decide whether the work is one concern or several.
|
||||
5. **Message.** One concern: draft a subject, or use the argument and skip approval; ask Yes / Edit / No. Several: always suggest whole-file groups, each with a subject, naming any file that mixes concerns and which group took it; ask Approve / Change it / One commit instead (asked even when the subject came as the argument). Mention `sensitive` and `large` files you are leaving out.
|
||||
6. **Commit.** For each group in order: when there is more than one group, run `git reset -q` first so only that group is staged; then run `commit-msg.mjs --subject "<s>" --files ...` and its `command` (or `add`, then `commit`). Finish with `git log --oneline -<n>`.
|
||||
7. **Push.** Run `state` again. When `push` is not null, offer it: show the commits that would go (`git log --oneline HEAD --not --remotes`) and `push.command`. `setsUpstream` → say the branch will be created on the remote. `needsRemoteChoice` → ask which of `remotes`. Run only `git push` or `git push -u <remote> <branch>`. If `behind` is above 0, say a push will likely be rejected. A rejected push: report it, suggest `git pull --rebase`, run nothing more.
|
||||
8. **Finish.** What was committed (hashes and subjects) and whether it was pushed.
|
||||
|
||||
## Session End
|
||||
|
||||
Terminal: the summary from Step 8. Web console: post `finish` (headline, a body listing the commits and the push result, no `command`, `"dashboard": true`) BEFORE `stop`, then keep waiting for the dashboard press (console.md → Finishing). A `__stop` posts a finish whose headline starts "Paused" with `"command": "/plan2code-git-commit"`.
|
||||
|
||||
Returning context: run `/plan2code-git-commit` again for the next commit.
|
||||
@@ -0,0 +1,883 @@
|
||||
#!/usr/bin/env node
|
||||
// git.mjs: what the Git skill knows and says about the repository.
|
||||
//
|
||||
// One script for the terminal and the git board. It reports where the
|
||||
// repository stands, and for every action it builds the exact git command plus
|
||||
// the confirm text that names the branch, the remote, the commits or files and
|
||||
// the command itself, so both channels show the same words. It also checks
|
||||
// branch names, deletes and cleanups, reads a stopped rebase, sorts git's
|
||||
// errors into kinds with a next step, and prints pull-request links. It only
|
||||
// reads: the agent runs every command it prints, and guard() refuses the forms
|
||||
// the skill's rules ban.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { EXIT, consoleLib, fail, gitRepo, out, parseArgs, readText, run } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
git.mjs: read-only facts and exact commands for the Git skill. JSON on stdout.
|
||||
It never changes the repository: the agent runs every command it prints.
|
||||
|
||||
node git.mjs state
|
||||
node git.mjs plan <op> [flags]
|
||||
node git.mjs branch-check --name <branch>
|
||||
node git.mjs init-check
|
||||
node git.mjs delete-check --branch <branch>
|
||||
node git.mjs cleanup-list
|
||||
node git.mjs conflicts
|
||||
node git.mjs pr-url [--branch <branch>] [--base <branch>]
|
||||
node git.mjs classify-error --file <stderr.txt>
|
||||
|
||||
state Prints { ok, root, branch, detached, hasCommits,
|
||||
defaultBranch, defaultFrom, onDefault, inProgress, conflicted,
|
||||
staged, unstaged, untracked, nothingToCommit, sensitive, large,
|
||||
remotes, upstream, ahead, behind, unpublished, push, git, next }.
|
||||
branch null when HEAD is detached.
|
||||
defaultBranch origin/HEAD, else local main, else master, else
|
||||
(no commits yet, on main or master) that branch,
|
||||
else null. defaultFrom says which: origin/HEAD,
|
||||
local-main, local-master, unborn, null.
|
||||
inProgress merge, rebase, cherry-pick, revert or null.
|
||||
staged, unstaged, untracked, conflicted
|
||||
[{ path, status }]; a conflicted file is listed
|
||||
only under conflicted.
|
||||
sensitive paths that look like secrets (.env, keys,
|
||||
credentials); left out unless the person insists.
|
||||
large [{ path, bytes }] for files over 5 MB.
|
||||
remotes remote names.
|
||||
ahead, behind commits against the upstream; null without one.
|
||||
unpublished commits exist and the branch has no upstream.
|
||||
push null when there is nothing to push, no remote, no
|
||||
commits or HEAD is detached; otherwise
|
||||
{ command, setsUpstream, remote, needsRemoteChoice }.
|
||||
git the board's snapshot (state.git).
|
||||
next the likely next action: continue or abort while
|
||||
an operation is stopped, else commit with changes,
|
||||
pull when behind, push when ahead, publish when
|
||||
unpublished; null when there is nothing to do.
|
||||
plan <op> Prints { ok, op, ask, confirm?, command | commands, network,
|
||||
timeoutMs?, env?, card? }. When ask is true, post confirm as a
|
||||
card verbatim (or put card to the person); then run command, or
|
||||
each of commands in order, exactly as printed.
|
||||
confirm { title, body, danger, consequences }; consequences
|
||||
ends with the exact command(s).
|
||||
network true: run with GIT_TERMINAL_PROMPT=0.
|
||||
timeoutMs stop the command after this long.
|
||||
env other variables to set for the command.
|
||||
card a choice for the person before anything runs:
|
||||
dirty { files, reason, options: commit-first, cancel }
|
||||
switch { files, options: bring?, commit-first,
|
||||
cancel, reason? } (no bring when git would
|
||||
refuse; reason names the files)
|
||||
remote { remotes, preset } (no command: plan again
|
||||
with --remote)
|
||||
ops:
|
||||
refresh git fetch --prune (--all with
|
||||
several remotes), 30 s cap.
|
||||
pull --ff-only, or --rebase when the
|
||||
branch and its upstream split.
|
||||
push new commits to the upstream.
|
||||
publish [--remote <r>] push -u to a remote.
|
||||
switch --branch <b> a local branch, or <remote>/<name>
|
||||
for a remote-only one.
|
||||
create --name <n> [--from <ref>] a new branch, never published.
|
||||
delete --branch <b> a local branch; never a remote one.
|
||||
cleanup --select <b> [--select <b> ...]
|
||||
branches from cleanup-list.
|
||||
abort the stopped merge, rebase,
|
||||
cherry-pick or revert.
|
||||
continue stage the resolved files, then
|
||||
continue it.
|
||||
branch-check Is --name a usable new branch name here? Prints { ok, name, valid,
|
||||
exists }. Exit 4: invalid-name (stderr), branch-exists (switchTo),
|
||||
exists-on-remote (remote, switchTo) or branch-conflict.
|
||||
init-check Run anywhere. Can git init be offered in this folder? Prints { ok,
|
||||
path, safe, reason?, insideRepo, repoRoot?, hasGitignore,
|
||||
suggestedIgnore, branch, commands }. commands start the
|
||||
repository on branch: main, unless init.defaultBranch is set.
|
||||
safe is false (reason: inside-repo, home or root) for a
|
||||
folder that is already in a repository, the home
|
||||
folder and a drive root. suggestedIgnore lists .gitignore lines
|
||||
for what is in the folder (node_modules/, .env, build output).
|
||||
delete-check What deleting --branch would lose. Prints { ok, branch, merged,
|
||||
gone, onlyHere: { count, commits: [{ sha, subject }] (first 10) },
|
||||
remoteCopy: { ref, hasAll } | null, flag: -d | -D, sentence }.
|
||||
cleanup-list Prints { ok, merged, gone }: local branches merged into the default
|
||||
branch, and branches whose remote copy was deleted. Never the
|
||||
current or the default branch.
|
||||
conflicts The stopped operation. Prints { ok, op, step, total, commit:
|
||||
{ sha, subject } | null, files: [{ path, status, markers }],
|
||||
ready }. ready: no file still has conflict markers. Exit 4
|
||||
nothing-in-progress.
|
||||
pr-url Prints { ok, url, host, kind, needsKind } for --branch (the current
|
||||
branch) into --base (the default branch). needsKind: the host is
|
||||
unknown and has no saved answer, so url is null; ask its kind
|
||||
once. Exit 4 not-pushed without an upstream, is-base when the
|
||||
branch is --base itself (a push to the default branch).
|
||||
classify-error Run anywhere. Sorts git's stderr saved in --file. Prints { ok,
|
||||
kind, next, files? }: kind is rejected, auth, dirty (files),
|
||||
conflict, diverged, network or other.
|
||||
|
||||
Exit: 0 ok · 1 crash · 2 bad arguments · 3 not a git repository · 4 invalid
|
||||
input, or nothing to do · 5 refused by a rule.
|
||||
`;
|
||||
|
||||
let R; // git-repo.mjs, loaded once main() runs
|
||||
|
||||
const g = (args, cwd, opts) => R.git(args, cwd, opts);
|
||||
|
||||
function requireGit() {
|
||||
const floor = R.gitFloor();
|
||||
if (!floor.ok) fail(EXIT.REFUSED, "git-too-old", floor.message, "Install or update git (2.23 or newer), then try again.");
|
||||
}
|
||||
|
||||
function requireRepo() {
|
||||
const top = g(["rev-parse", "--show-toplevel"], process.cwd());
|
||||
if (!top.ok || !top.out) {
|
||||
fail(EXIT.NOT_FOUND, "not-a-repo", "This directory is not inside a git repository.", "Run git.mjs init-check to see whether this folder can start one.");
|
||||
}
|
||||
return top.out;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- commands, guarded */
|
||||
|
||||
/** A command as one line for a person to read: args joined by spaces, quoted when they hold a space or quote. */
|
||||
export function display(command) {
|
||||
return command.map((a) => (a === "" || /[\s"']/.test(a) ? `"${a.replace(/"/g, '\\"')}"` : a)).join(" ");
|
||||
}
|
||||
|
||||
/**
|
||||
* The skill's banned forms, refused before any command is printed: no force
|
||||
* push, no hook skipping, no amend, no remote delete, no blanket add. A crash,
|
||||
* not a handled failure, because no rule-following caller ever builds one.
|
||||
*/
|
||||
export function guard(command) {
|
||||
if (!Array.isArray(command) || command[0] !== "git" || !command.every((a) => typeof a === "string")) {
|
||||
fail(EXIT.CRASH, "forbidden-command", 'A command must be an args array starting with "git".');
|
||||
}
|
||||
// The subcommand is the first word after git's own options (-c key=value, -C dir).
|
||||
let i = 1;
|
||||
while (i < command.length && command[i].startsWith("-")) i += command[i] === "-c" || command[i] === "-C" ? 2 : 1;
|
||||
const sub = command[i];
|
||||
const rest = command.slice(i + 1);
|
||||
// Paths after "--" are file names, never options: a file called -A is legal,
|
||||
// and one called --force must not trip the flag checks.
|
||||
const opts = rest.includes("--") ? rest.slice(0, rest.indexOf("--")) : rest;
|
||||
const banned =
|
||||
opts.some((a) => a === "--force" || a === "--force-with-lease" || a.startsWith("--force-with-lease=") || a === "--no-verify" || a === "--amend") ||
|
||||
(sub === "push" && opts.some((a) => a === "-f" || /^-[a-zA-Z]*f/.test(a) || a === "--delete" || a === "-d" || a === "--prune" || a === "--mirror" || a.startsWith(":") || a.startsWith("+"))) ||
|
||||
(sub === "commit" && opts.some((a) => a === "-n" || a === "-a" || a === "--all" || /^-[a-zA-Z]*a/.test(a))) ||
|
||||
(sub === "add" && (opts.some((a) => a === "-A" || a === "--all" || a === "-u" || a === "--update") || rest.includes(".")));
|
||||
if (banned) fail(EXIT.CRASH, "forbidden-command", `Refusing to print a forbidden command: ${display(command)}.`);
|
||||
return command;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ the repository */
|
||||
|
||||
const refExists = (root, ref) => g(["show-ref", "--verify", "-q", ref], root).ok;
|
||||
const remoteNames = (root) => g(["remote"], root).out.split(/\r?\n/).filter(Boolean);
|
||||
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
||||
|
||||
async function prHosts() {
|
||||
return (await consoleLib()).readPrHosts();
|
||||
}
|
||||
|
||||
function readStatus(root) {
|
||||
return R.parseStatusV2(g(["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=normal"], root, { raw: true }).out);
|
||||
}
|
||||
|
||||
// The commit flow's lists and letters: a conflicted file only under conflicted.
|
||||
function fileLists(parsed) {
|
||||
const staged = [];
|
||||
const unstaged = [];
|
||||
const untracked = [];
|
||||
for (const f of parsed.files) {
|
||||
if (f.worktree === "?") {
|
||||
untracked.push({ path: f.path, status: "?" });
|
||||
continue;
|
||||
}
|
||||
if (f.index !== " ") staged.push({ path: f.path, status: f.index });
|
||||
if (f.worktree !== " ") unstaged.push({ path: f.path, status: f.worktree });
|
||||
}
|
||||
return { staged, unstaged, untracked, conflicted: parsed.conflicted.map((c) => ({ path: c.path, status: c.status })) };
|
||||
}
|
||||
|
||||
/** Everything a plan or check reads, from one status and one ref pass. */
|
||||
function repoState(root) {
|
||||
const parsed = readStatus(root);
|
||||
const refs = R.readRefs(root);
|
||||
const def = refs.length ? R.defaultBranchFromRefs(refs, parsed) : R.defaultBranch(root, parsed);
|
||||
const branches = R.branchesFromRefs(refs, root, { current: parsed.branch, defaultName: def.name });
|
||||
const lists = fileLists(parsed);
|
||||
// Tracked changes (staged, unstaged or conflicted); untracked files carry over a switch.
|
||||
const tracked = [...new Set([...lists.staged, ...lists.unstaged, ...lists.conflicted].map((f) => f.path))];
|
||||
return {
|
||||
root,
|
||||
parsed,
|
||||
def,
|
||||
branches,
|
||||
lists,
|
||||
tracked,
|
||||
branch: parsed.branch,
|
||||
current: branches.find((b) => b.current && !b.remote) || null,
|
||||
remotes: remoteNames(root),
|
||||
paths: R.gitPaths(root),
|
||||
};
|
||||
}
|
||||
|
||||
const localBranch = (s, name) => s.branches.find((b) => !b.remote && b.name === name) || null;
|
||||
const upstreamGone = (s) => !!s.parsed.upstream && (s.current?.gone || s.parsed.ahead === null);
|
||||
|
||||
function pushPlan(root, { branch, hasCommits, remotes, upstream, ahead }) {
|
||||
if (!branch || !hasCommits || !remotes.length) return null;
|
||||
if (upstream) {
|
||||
const configured = g(["config", "--get", `branch.${branch}.remote`], root).out;
|
||||
const remote = configured || upstream.split("/")[0];
|
||||
if (remote === "." || !ahead) return null;
|
||||
return { command: "git push", setsUpstream: false, remote, needsRemoteChoice: false };
|
||||
}
|
||||
const remote = remotes.length === 1 ? remotes[0] : remotes.includes("origin") ? "origin" : remotes[0];
|
||||
return { command: `git push -u ${remote} ${branch}`, setsUpstream: true, remote, needsRemoteChoice: remotes.length > 1 };
|
||||
}
|
||||
|
||||
const MARKER = /^(<{7}|={7}|>{7})( |$)/m;
|
||||
function hasMarkers(root, file) {
|
||||
const text = readText(path.join(root, file));
|
||||
return text !== null && MARKER.test(text);
|
||||
}
|
||||
|
||||
async function state({ root }) {
|
||||
const snap = R.snapshot(root, { prHosts: await prHosts() });
|
||||
const parsed = readStatus(root);
|
||||
const { branch, hasCommits, ahead, behind } = parsed;
|
||||
// For the commit flow, an upstream deleted on the remote is no upstream.
|
||||
const upstream = parsed.upstream && ahead !== null ? parsed.upstream : null;
|
||||
const def = R.defaultBranch(root, parsed);
|
||||
const files = fileLists(parsed);
|
||||
const { sensitive, large } = R.readChanges(root, parsed);
|
||||
const remotes = remoteNames(root);
|
||||
const unpublished = hasCommits && !!branch && !upstream;
|
||||
const inProgress = snap.inProgress ?? null;
|
||||
|
||||
let next = null;
|
||||
if (inProgress) next = (snap.conflicted || []).some((c) => c.markers) ? "abort" : "continue";
|
||||
else if (parsed.files.length || parsed.conflicted.length) next = "commit";
|
||||
else if (behind > 0) next = "pull";
|
||||
else if (ahead > 0) next = "push";
|
||||
else if (unpublished && remotes.length) next = "publish";
|
||||
|
||||
out({
|
||||
ok: true,
|
||||
root,
|
||||
branch,
|
||||
detached: branch === null,
|
||||
hasCommits,
|
||||
defaultBranch: def.name,
|
||||
defaultFrom: def.from,
|
||||
onDefault: !!branch && !!def.name && branch === def.name,
|
||||
inProgress,
|
||||
conflicted: files.conflicted,
|
||||
staged: files.staged,
|
||||
unstaged: files.unstaged,
|
||||
untracked: files.untracked,
|
||||
nothingToCommit: !files.staged.length && !files.unstaged.length && !files.untracked.length && !files.conflicted.length,
|
||||
sensitive,
|
||||
large,
|
||||
remotes,
|
||||
upstream,
|
||||
ahead,
|
||||
behind,
|
||||
unpublished,
|
||||
push: pushPlan(root, { branch, hasCommits, remotes, upstream, ahead }),
|
||||
git: snap,
|
||||
next,
|
||||
});
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- name checks */
|
||||
|
||||
const NAME_HINT = "Use lowercase words joined by '-' under a prefix such as feature/, fix/, chore/ or docs/ (feature/export-csv).";
|
||||
|
||||
/** Fails (exit 4) unless `name` is a valid branch name no local or remote branch already holds. */
|
||||
function checkName(root, name) {
|
||||
// check-ref-format --branch also expands @{-1}; a changed name is not a name.
|
||||
const checked = name.startsWith("-") ? { ok: false, err: "" } : g(["check-ref-format", "--branch", name], root);
|
||||
if (!checked.ok || checked.out !== name) {
|
||||
fail(EXIT.INVALID, "invalid-name", `"${name}" is not a valid git branch name.`, NAME_HINT, checked.err ? { stderr: checked.err } : undefined);
|
||||
}
|
||||
if (refExists(root, `refs/heads/${name}`)) {
|
||||
fail(EXIT.INVALID, "branch-exists", `A branch named "${name}" already exists.`, `Switch to it, or pick another name, for example "${name}-2".`, { switchTo: { branch: name } });
|
||||
}
|
||||
for (const remote of remoteNames(root)) {
|
||||
if (refExists(root, `refs/remotes/${remote}/${name}`)) {
|
||||
fail(EXIT.INVALID, "exists-on-remote", `"${name}" exists on ${remote}.`, `Switch to ${remote}/${name} to work on it, or pick another name.`, {
|
||||
remote,
|
||||
switchTo: { branch: `${remote}/${name}` },
|
||||
});
|
||||
}
|
||||
}
|
||||
// git cannot hold both feature and feature/x: a branch is a file in refs/heads.
|
||||
const heads = g(["for-each-ref", "--format=%(refname:short)", "refs/heads"], root).out.split(/\r?\n/).filter(Boolean);
|
||||
const clash = heads.find((h) => name.startsWith(`${h}/`) || h.startsWith(`${name}/`));
|
||||
if (clash) {
|
||||
fail(EXIT.INVALID, "branch-conflict", `"${name}" clashes with the existing branch "${clash}" (one is a folder of the other).`, "Pick a name that is not nested under an existing branch.", { branch: clash });
|
||||
}
|
||||
}
|
||||
|
||||
function requireValue(value, flag, example) {
|
||||
const v = (value || "").trim();
|
||||
if (!v) fail(EXIT.USAGE, `missing-${flag}`, `--${flag} is required.`, `Example: ${example}`);
|
||||
return v;
|
||||
}
|
||||
|
||||
function branchCheck({ root, name }) {
|
||||
const n = requireValue(name, "name", "branch-check --name feature/export-csv");
|
||||
checkName(root, n);
|
||||
out({ ok: true, name: n, valid: true, exists: false });
|
||||
}
|
||||
|
||||
// Top-level names that should not go into a first commit.
|
||||
const IGNORE_DIRS = ["node_modules", "dist", "build", "out", ".next", "coverage", "target", "__pycache__", ".venv", "venv"];
|
||||
|
||||
function suggestedIgnore(dir) {
|
||||
let names = [];
|
||||
try {
|
||||
names = fs.readdirSync(dir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const lines = [];
|
||||
for (const d of IGNORE_DIRS) if (names.includes(d)) lines.push(`${d}/`);
|
||||
const envs = names.filter((n) => n === ".env" || (n.startsWith(".env.") && !R.ENV_OK.has(n)));
|
||||
if (envs.length) {
|
||||
lines.push(".env", ".env.*");
|
||||
for (const n of R.ENV_OK) if (names.includes(n)) lines.push(`!${n}`);
|
||||
}
|
||||
if (names.includes(".DS_Store")) lines.push(".DS_Store");
|
||||
if (names.includes("Thumbs.db")) lines.push("Thumbs.db");
|
||||
if (names.some((n) => n.endsWith(".log"))) lines.push("*.log");
|
||||
return lines;
|
||||
}
|
||||
|
||||
const sameFolder = (a, b) => (process.platform === "win32" || process.platform === "darwin" ? a.toLowerCase() === b.toLowerCase() : a === b);
|
||||
|
||||
function initCheck() {
|
||||
const cwd = fs.realpathSync.native(process.cwd());
|
||||
const top = g(["rev-parse", "--show-toplevel"], cwd);
|
||||
const insideRepo = top.ok && !!top.out;
|
||||
let home = os.homedir();
|
||||
try {
|
||||
home = fs.realpathSync.native(home);
|
||||
} catch {
|
||||
// a home folder that no longer exists cannot be the current folder
|
||||
}
|
||||
let safe = true;
|
||||
let reason;
|
||||
if (insideRepo) [safe, reason] = [false, "inside-repo"];
|
||||
else if (sameFolder(cwd, home)) [safe, reason] = [false, "home"];
|
||||
else if (cwd === path.parse(cwd).root) [safe, reason] = [false, "root"];
|
||||
const result = { ok: true, path: cwd, safe };
|
||||
if (reason) result.reason = reason;
|
||||
result.insideRepo = insideRepo;
|
||||
if (insideRepo) result.repoRoot = top.out;
|
||||
result.hasGitignore = fs.existsSync(path.join(cwd, ".gitignore"));
|
||||
result.suggestedIgnore = suggestedIgnore(cwd);
|
||||
// A new repository starts on main, not git's legacy master, unless the
|
||||
// person set init.defaultBranch themselves. Two commands rather than
|
||||
// `git init -b`, which needs git 2.28 (the floor here is 2.23).
|
||||
const configured = g(["config", "--get", "init.defaultBranch"], cwd);
|
||||
const branch = (configured.ok && configured.out.trim()) || "main";
|
||||
result.branch = branch;
|
||||
result.commands = [["git", "init"], ["git", "symbolic-ref", "HEAD", `refs/heads/${branch}`]];
|
||||
out(result);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- plan <op> */
|
||||
|
||||
const PLANS = {
|
||||
refresh: planRefresh,
|
||||
pull: planPull,
|
||||
push: planPush,
|
||||
publish: planPublish,
|
||||
switch: planSwitch,
|
||||
create: planCreate,
|
||||
delete: planDelete,
|
||||
cleanup: planCleanup,
|
||||
abort: planAbort,
|
||||
continue: planContinue,
|
||||
};
|
||||
|
||||
/** The confirm's last lines: the exact command(s), one per line, as a person would type them. */
|
||||
function consequences(commands) {
|
||||
return "```\n" + commands.map(display).join("\n") + "\n```";
|
||||
}
|
||||
|
||||
function plan({ root, ...args }, [op]) {
|
||||
const ops = Object.keys(PLANS).join(", ");
|
||||
if (!op) fail(EXIT.USAGE, "missing-op", `plan needs an op: ${ops}.`, "Run with --help for usage.");
|
||||
if (!Object.hasOwn(PLANS, op)) fail(EXIT.USAGE, "unknown-op", `Unknown plan op "${op}".`, `Use one of: ${ops}.`);
|
||||
const p = PLANS[op](repoState(root), args);
|
||||
const list = p.command ? [p.command] : p.commands || [];
|
||||
list.forEach(guard);
|
||||
const result = { ok: true, op, ask: !!p.ask };
|
||||
if (p.confirm) result.confirm = { title: p.confirm.title, body: p.confirm.body, danger: !!p.confirm.danger, consequences: consequences(list) };
|
||||
if (p.command) result.command = p.command;
|
||||
if (p.commands) result.commands = p.commands;
|
||||
result.network = !!p.network;
|
||||
if (p.timeoutMs) result.timeoutMs = p.timeoutMs;
|
||||
if (p.env) result.env = p.env;
|
||||
if (p.card) result.card = p.card;
|
||||
out(result);
|
||||
}
|
||||
|
||||
function requireBranch(s, what) {
|
||||
if (!s.branch) fail(EXIT.REFUSED, "detached", `HEAD is detached, so there is no branch to ${what}.`, "Switch to a branch first.");
|
||||
}
|
||||
|
||||
function requireRemote(s, exit = EXIT.REFUSED) {
|
||||
if (!s.remotes.length) fail(exit, "no-remote", "This repository has no remote.", "Add one with git remote add <name> <url>, then try again.");
|
||||
}
|
||||
|
||||
function planRefresh(s) {
|
||||
// No remote, nothing to fetch: a Refresh is the person asking the board to
|
||||
// look at the folder again (edits made in their editor), which the reread
|
||||
// that follows does. Nothing to run.
|
||||
if (!s.remotes.length) return { ask: false, commands: [] };
|
||||
const command = s.remotes.length > 1 ? ["git", "fetch", "--all", "--prune"] : ["git", "fetch", "--prune"];
|
||||
return { ask: false, command, network: true, timeoutMs: 30000 };
|
||||
}
|
||||
|
||||
function planPull(s) {
|
||||
requireBranch(s, "pull into");
|
||||
const { upstream, ahead, behind } = s.parsed;
|
||||
if (!upstream) fail(EXIT.INVALID, "no-upstream", `${s.branch} has no upstream to pull from.`, "Publish the branch first (plan publish).");
|
||||
if (upstreamGone(s)) fail(EXIT.INVALID, "upstream-gone", `${s.branch}'s upstream ${upstream} no longer exists on the remote.`, "Publish it again, or switch to another branch.");
|
||||
if (behind === 0) fail(EXIT.INVALID, "up-to-date", `${s.branch} already has everything on ${upstream}.`, "Refresh first if you expect new commits.");
|
||||
if (ahead === 0) return { ask: false, command: ["git", "pull", "--ff-only"], network: true };
|
||||
// A split: replay the unpushed commits on top. Never stashed, never autostashed.
|
||||
const pull = { command: ["git", "pull", "--rebase"], network: true, env: { GIT_EDITOR: "true" } };
|
||||
const changed = [...new Set([...s.lists.staged, ...s.lists.unstaged].map((f) => f.path))];
|
||||
if (!changed.length) return { ...pull, ask: false };
|
||||
return {
|
||||
...pull,
|
||||
ask: true,
|
||||
card: { kind: "dirty", files: changed, reason: "git pull --rebase needs a clean tree: these files have changes.", options: ["commit-first", "cancel"] },
|
||||
};
|
||||
}
|
||||
|
||||
function planPush(s) {
|
||||
requireBranch(s, "push");
|
||||
requireRemote(s);
|
||||
const { upstream, ahead, behind } = s.parsed;
|
||||
const remote = s.current?.upstreamRemote || (upstream ? upstream.split("/")[0] : null);
|
||||
if (!upstream || upstreamGone(s) || !remote || remote === "." || !(ahead > 0)) {
|
||||
fail(EXIT.INVALID, "nothing-to-push", `${s.branch} has no new commits to push to an upstream.`, upstream && !upstreamGone(s) ? "Commit first." : "Publish the branch first (plan publish).");
|
||||
}
|
||||
const log = g(["log", "--oneline", "-n", "20", "@{u}..HEAD"], s.root).out.split(/\r?\n/).filter(Boolean);
|
||||
let body = log.map((line) => `- ${line}`).join("\n");
|
||||
// A branch tracking another name (feature/x on origin/main): the push still goes to its own name.
|
||||
if (upstream !== `${remote}/${s.branch}`) body += `\n\nYour upstream is ${upstream}; this push goes to ${remote}/${s.branch} instead.`;
|
||||
if (behind > 0) body += `\n\nThe remote has ${plural(behind, "commit")} you don't have, so this push will likely be rejected: Pull first.`;
|
||||
return {
|
||||
ask: true,
|
||||
command: ["git", "push", remote, s.branch],
|
||||
network: true,
|
||||
confirm: { title: `Push ${plural(ahead, "commit")} to ${remote}/${s.branch}?`, body, danger: false },
|
||||
};
|
||||
}
|
||||
|
||||
function planPublish(s, { remote: chosen }) {
|
||||
requireBranch(s, "publish");
|
||||
requireRemote(s);
|
||||
if (!s.parsed.hasCommits) fail(EXIT.INVALID, "no-commits", `${s.branch} has no commits to publish yet.`, "Commit first.");
|
||||
// An upstream deleted on the remote can be published again.
|
||||
if (s.parsed.upstream && !upstreamGone(s)) fail(EXIT.INVALID, "already-published", `${s.branch} already tracks ${s.parsed.upstream}.`, "Use plan push to send new commits.");
|
||||
if (chosen && !s.remotes.includes(chosen)) fail(EXIT.INVALID, "unknown-remote", `There is no remote named "${chosen}".`, `Use one of: ${s.remotes.join(", ")}.`);
|
||||
if (!chosen && s.remotes.length > 1) {
|
||||
return { ask: true, network: true, card: { kind: "remote", remotes: s.remotes, preset: s.remotes.includes("origin") ? "origin" : s.remotes[0] } };
|
||||
}
|
||||
const remote = chosen || s.remotes[0];
|
||||
const n = Number(g(["rev-list", "--count", "HEAD", "--not", `--remotes=${remote}`], s.root).out) || 0;
|
||||
return {
|
||||
ask: true,
|
||||
command: ["git", "push", "-u", remote, s.branch],
|
||||
network: true,
|
||||
confirm: { title: `Publish ${s.branch} to ${remote}?`, body: n ? `Creates ${s.branch} on ${remote} and pushes ${plural(n, "commit")}.` : `Creates ${s.branch} on ${remote}; its commits are already there.`, danger: false },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Which of `paths` exist in `target`'s tree: one git cat-file --batch-check
|
||||
* for all of them. --batch-check reads one object name per line, so a path
|
||||
* holding a newline would split into two queries and shift every answer after
|
||||
* it; those few are asked one at a time with cat-file -e instead.
|
||||
*/
|
||||
function inTree(root, target, paths) {
|
||||
const opts = { cwd: root, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" } };
|
||||
const plain = paths.filter((p) => !p.includes("\n"));
|
||||
const odd = paths.filter((p) => p.includes("\n"));
|
||||
const found = [];
|
||||
if (plain.length) {
|
||||
try {
|
||||
const res = execFileSync("git", ["cat-file", "--batch-check"], {
|
||||
...opts,
|
||||
input: plain.map((p) => `${target}:${p}`).join("\n") + "\n",
|
||||
encoding: "utf8",
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
});
|
||||
const lines = res.split("\n");
|
||||
found.push(...plain.filter((_, i) => lines[i] && !lines[i].endsWith(" missing")));
|
||||
} catch {
|
||||
// An unreadable target means no path is known to be in it.
|
||||
}
|
||||
}
|
||||
for (const p of odd) {
|
||||
try {
|
||||
execFileSync("git", ["cat-file", "-e", `${target}:${p}`], opts);
|
||||
found.push(p);
|
||||
} catch {
|
||||
// Not in the target's tree.
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* The changed files git switch would refuse to carry to `target`: a changed
|
||||
* tracked path that differs between HEAD and the target, or an untracked path
|
||||
* the target has.
|
||||
*/
|
||||
function wouldRefuse(s, target) {
|
||||
const changed = new Set(s.tracked);
|
||||
for (const f of s.parsed.files) if (f.origPath) changed.add(f.origPath);
|
||||
const differ = s.parsed.hasCommits ? g(["diff", "--name-only", "-z", "HEAD", target, "--"], s.root, { raw: true }).out.split("\0").filter(Boolean) : [];
|
||||
const tracked = differ.filter((p) => changed.has(p));
|
||||
const untracked = [];
|
||||
for (const f of s.parsed.files) {
|
||||
if (f.worktree !== "?") continue;
|
||||
if (!f.path.endsWith("/")) untracked.push(f.path);
|
||||
else untracked.push(...g(["ls-files", "-o", "--exclude-standard", "-z", "--", f.path], s.root, { raw: true }).out.split("\0").filter(Boolean));
|
||||
}
|
||||
return [...new Set([...tracked, ...inTree(s.root, target, untracked)])];
|
||||
}
|
||||
|
||||
/** The switch card, or null when nothing needs asking. `always`: ask about carried changes too. */
|
||||
function switchCard(s, target, { always }) {
|
||||
const refused = wouldRefuse(s, target);
|
||||
if (!refused.length && !(always && s.tracked.length)) return null;
|
||||
const card = { kind: "switch", files: [...new Set([...s.tracked, ...refused])], options: ["bring", "commit-first", "cancel"] };
|
||||
if (refused.length) {
|
||||
card.options = ["commit-first", "cancel"];
|
||||
card.reason = `git switch would refuse: ${refused.join(", ")} ${refused.length === 1 ? "differs" : "differ"} on ${target}.`;
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
function planSwitch(s, { branch }) {
|
||||
const b = requireValue(branch, "branch", "plan switch --branch main");
|
||||
if (b === s.branch) fail(EXIT.INVALID, "already-on", `Already on ${b}.`, "Pick another branch.");
|
||||
let command;
|
||||
if (!b.startsWith("-") && localBranch(s, b)) command = ["git", "switch", b];
|
||||
else if (!b.startsWith("-") && s.remotes.some((r) => b.startsWith(`${r}/`)) && refExists(s.root, `refs/remotes/${b}`)) {
|
||||
// --track creates a local branch under the remote name: an existing one
|
||||
// (tracking something else) makes git refuse, so say so up front.
|
||||
const taken = localBranch(s, b.slice(b.indexOf("/") + 1));
|
||||
if (taken) {
|
||||
fail(EXIT.INVALID, "branch-exists", `A local branch named "${taken.name}" already exists (tracking ${taken.upstream || "nothing"}).`, `Switch to ${taken.name}, or delete it first.`, { switchTo: { branch: taken.name } });
|
||||
}
|
||||
command = ["git", "switch", "--track", b];
|
||||
}
|
||||
else fail(EXIT.INVALID, "unknown-branch", `There is no branch named "${b}".`, "Refresh, then pick a branch from the list.");
|
||||
const card = switchCard(s, b, { always: true });
|
||||
return card ? { ask: true, command, network: false, card } : { ask: false, command, network: false };
|
||||
}
|
||||
|
||||
/** Where a new branch starts: origin/<default>, else the local default, else the current branch, else HEAD. */
|
||||
function defaultStart(s) {
|
||||
const d = s.def.name;
|
||||
if (d && refExists(s.root, `refs/remotes/origin/${d}`)) return `origin/${d}`;
|
||||
if (d && refExists(s.root, `refs/heads/${d}`)) return d;
|
||||
if (s.branch && s.parsed.hasCommits) return s.branch;
|
||||
if (s.parsed.oid) return s.parsed.oid.slice(0, 7);
|
||||
fail(EXIT.INVALID, "no-commits", "There are no commits to start a branch from yet.", "Commit first.");
|
||||
}
|
||||
|
||||
function planCreate(s, { name, from }) {
|
||||
const n = requireValue(name, "name", "plan create --name feature/export-csv");
|
||||
checkName(s.root, n);
|
||||
let start = (from || "").trim();
|
||||
if (start) {
|
||||
if (start.startsWith("-") || !g(["rev-parse", "--verify", "--quiet", `${start}^{commit}`], s.root).ok) {
|
||||
fail(EXIT.INVALID, "bad-from", `"${start}" is not a branch or commit here.`, "Pick a branch from the list, or leave --from out.");
|
||||
}
|
||||
} else start = defaultStart(s);
|
||||
// --no-track: a branch started from origin/main must not take origin/main as its upstream.
|
||||
const command = ["git", "switch", "--no-track", "-c", n, start];
|
||||
const card = switchCard(s, start, { always: false });
|
||||
return card ? { ask: true, command, network: false, card } : { ask: false, command, network: false };
|
||||
}
|
||||
|
||||
function requireLocal(s, branch) {
|
||||
const b = requireValue(branch, "branch", "--branch feature/old-work");
|
||||
const row = localBranch(s, b);
|
||||
if (!row) fail(EXIT.INVALID, "unknown-branch", `There is no local branch named "${b}".`, "Pick a branch from the list.");
|
||||
return row;
|
||||
}
|
||||
|
||||
function planDelete(s, { branch }) {
|
||||
const row = requireLocal(s, branch);
|
||||
const b = row.name;
|
||||
if (row.current) fail(EXIT.REFUSED, "refused", `${b} is the branch you are on.`, "Switch to another branch first.");
|
||||
if (b === s.def.name) fail(EXIT.REFUSED, "refused", `${b} is the default branch.`, "The default branch is never deleted here.");
|
||||
const check = deleteCheck(s, row);
|
||||
if (row.merged && !row.gone) {
|
||||
return { ask: true, command: ["git", "branch", check.flag, b], confirm: { title: `Delete ${b}?`, body: `It is merged into ${s.def.name}.`, danger: false } };
|
||||
}
|
||||
// Red only when commits would really be lost: a branch git calls unmerged
|
||||
// (merged elsewhere, say into origin/main but not main) with nothing of its
|
||||
// own still needs -D, but deleting it loses nothing.
|
||||
return { ask: true, command: ["git", "branch", "-D", b], confirm: { title: `Delete ${b}?`, body: check.sentence, danger: check.onlyHere.count > 0 } };
|
||||
}
|
||||
|
||||
/**
|
||||
* The flag for deleting a branch merged into the default. git branch -d checks
|
||||
* the branch's upstream, or HEAD without one, not the default branch, so it
|
||||
* refuses a merged branch HEAD does not contain; -D is safe there, since the
|
||||
* merge into the default already shows nothing is lost.
|
||||
*/
|
||||
function mergedFlag(s, row) {
|
||||
const reference = row.upstream && !row.gone ? row.upstream : "HEAD";
|
||||
return g(["merge-base", "--is-ancestor", `refs/heads/${row.name}`, reference], s.root).ok ? "-d" : "-D";
|
||||
}
|
||||
|
||||
function planCleanup(s, { select }) {
|
||||
const picked = [...new Set((select || []).map((b) => b.trim()).filter(Boolean))];
|
||||
if (!picked.length) fail(EXIT.USAGE, "missing-select", "plan cleanup needs at least one --select <branch>.", "Run cleanup-list for the branches that can go.");
|
||||
const { merged, gone } = cleanupList(s);
|
||||
for (const b of picked) {
|
||||
if (!merged.includes(b) && !gone.includes(b)) fail(EXIT.INVALID, "not-cleanable", `${b} is not in the cleanup list.`, "Run cleanup-list for the branches that can go.", { branch: b });
|
||||
}
|
||||
const commands = picked.map((b) => ["git", "branch", gone.includes(b) ? "-D" : mergedFlag(s, localBranch(s, b)), b]);
|
||||
const lines = [];
|
||||
const m = picked.filter((b) => merged.includes(b));
|
||||
const x = picked.filter((b) => gone.includes(b));
|
||||
if (m.length) lines.push(`Merged into ${s.def.name}: ${m.join(", ")}.`);
|
||||
if (x.length) lines.push(`Their remote copy was deleted: ${x.join(", ")}.`);
|
||||
return {
|
||||
ask: true,
|
||||
commands,
|
||||
confirm: { title: `Delete ${picked.length} ${picked.length === 1 ? "branch" : "branches"}?`, body: lines.join("\n\n"), danger: x.some((b) => deleteCheck(s, localBranch(s, b)).onlyHere.count > 0) },
|
||||
};
|
||||
}
|
||||
|
||||
function requireInProgress(s) {
|
||||
const op = R.inProgressOp(s.paths);
|
||||
if (!op) fail(EXIT.INVALID, "nothing-in-progress", "No merge, rebase, cherry-pick or revert is in progress.", "Nothing to abort or continue.");
|
||||
return op;
|
||||
}
|
||||
|
||||
function planAbort(s) {
|
||||
return { ask: false, command: ["git", requireInProgress(s), "--abort"] };
|
||||
}
|
||||
|
||||
function planContinue(s) {
|
||||
const op = requireInProgress(s);
|
||||
const files = s.lists.conflicted.map((c) => ({ path: c.path, markers: hasMarkers(s.root, c.path) }));
|
||||
const still = files.filter((f) => f.markers).map((f) => f.path);
|
||||
if (still.length) {
|
||||
fail(EXIT.REFUSED, "still-conflicted", `${still.join(", ")} still ${still.length === 1 ? "has" : "have"} conflict markers.`, "Resolve them, then continue.", { files: still });
|
||||
}
|
||||
const resolved = files.map((f) => f.path);
|
||||
const commands = [...(resolved.length ? [["git", "add", "--", ...resolved]] : []), ["git", "-c", "core.editor=true", op, "--continue"]];
|
||||
return { ask: false, commands };
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------- delete and cleanup */
|
||||
|
||||
/** The remote copy of a local branch: its upstream, else <remote>/<name>; null when none exists. */
|
||||
function remoteCopy(s, row) {
|
||||
const candidates = [];
|
||||
if (row.upstream && row.upstreamRemote && row.upstreamRemote !== ".") candidates.push(row.upstream);
|
||||
for (const r of s.remotes) candidates.push(`${r}/${row.name}`);
|
||||
const ref = candidates.find((c) => refExists(s.root, `refs/remotes/${c}`));
|
||||
if (!ref) return null;
|
||||
const left = g(["rev-list", "--count", `refs/heads/${row.name}`, "--not", `refs/remotes/${ref}`], s.root).out;
|
||||
return { ref, hasAll: left === "0" };
|
||||
}
|
||||
|
||||
function deleteCheck(s, row) {
|
||||
const b = row.name;
|
||||
const copy = remoteCopy(s, row);
|
||||
// Commits on no other branch and no remote, the branch's own remote copy aside,
|
||||
// so the sentence can say whether that copy still has them. Before --branches
|
||||
// and --remotes, git matches --exclude without the refs/heads/ or refs/remotes/ prefix.
|
||||
const not = ["--not", `--exclude=${b}`, "--branches", ...(copy ? [`--exclude=${copy.ref}`] : []), "--remotes"];
|
||||
const count = Number(g(["rev-list", "--count", `refs/heads/${b}`, ...not], s.root).out) || 0;
|
||||
const commits = count
|
||||
? g(["log", "-n", "10", "--format=%h%x00%s", `refs/heads/${b}`, ...not], s.root)
|
||||
.out.split(/\r?\n/)
|
||||
.filter(Boolean)
|
||||
.map((line) => {
|
||||
const [sha, subject] = line.split("\0");
|
||||
return { sha, subject: subject || "" };
|
||||
})
|
||||
: [];
|
||||
let sentence;
|
||||
if (!count) sentence = `No commits exist only on ${b}.`;
|
||||
else {
|
||||
const lead = `${count} ${count === 1 ? "commit exists" : "commits exist"} only on ${b}`;
|
||||
sentence = copy?.hasAll ? `${lead}, and ${copy.ref} still has ${count === 1 ? "it" : "them"}.` : `${lead}, and no remote copy has ${count === 1 ? "it" : "them"}.`;
|
||||
}
|
||||
return {
|
||||
branch: b,
|
||||
merged: row.merged,
|
||||
gone: row.gone,
|
||||
onlyHere: { count, commits },
|
||||
remoteCopy: copy,
|
||||
flag: row.merged && !row.gone ? mergedFlag(s, row) : "-D",
|
||||
sentence,
|
||||
};
|
||||
}
|
||||
|
||||
/** Local branches that can go: merged into the default, or their remote copy deleted (gone wins). */
|
||||
function cleanupList(s) {
|
||||
const merged = [];
|
||||
const gone = [];
|
||||
for (const b of s.branches) {
|
||||
if (b.remote || b.current || b.name === s.def.name) continue;
|
||||
if (b.gone) gone.push(b.name);
|
||||
else if (b.merged) merged.push(b.name);
|
||||
}
|
||||
return { merged, gone };
|
||||
}
|
||||
|
||||
function deleteCheckCmd({ root, branch }) {
|
||||
const s = repoState(root);
|
||||
out({ ok: true, ...deleteCheck(s, requireLocal(s, branch)) });
|
||||
}
|
||||
|
||||
function cleanupListCmd({ root }) {
|
||||
out({ ok: true, ...cleanupList(repoState(root)) });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------- conflicts, errors, links */
|
||||
|
||||
const OP_HEAD = { merge: "MERGE_HEAD", "cherry-pick": "CHERRY_PICK_HEAD", revert: "REVERT_HEAD", rebase: "REBASE_HEAD" };
|
||||
|
||||
function readNumber(file) {
|
||||
const n = parseInt(readText(file) || "", 10);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
function headCommit(root, ref) {
|
||||
const res = g(["log", "-1", "--format=%h%x00%s", ref, "--"], root);
|
||||
if (!res.ok || !res.out) return null;
|
||||
const [sha, subject] = res.out.split("\0");
|
||||
return { sha, subject: subject || "" };
|
||||
}
|
||||
|
||||
function conflicts({ root }) {
|
||||
const s = repoState(root);
|
||||
const op = requireInProgress(s);
|
||||
let step = null;
|
||||
let total = null;
|
||||
if (op === "rebase") {
|
||||
const merge = s.paths["rebase-merge"];
|
||||
const apply = s.paths["rebase-apply"];
|
||||
if (merge && fs.existsSync(merge)) [step, total] = [readNumber(path.join(merge, "msgnum")), readNumber(path.join(merge, "end"))];
|
||||
else if (apply) [step, total] = [readNumber(path.join(apply, "next")), readNumber(path.join(apply, "last"))];
|
||||
}
|
||||
const files = s.lists.conflicted.map((c) => ({ path: c.path, status: c.status, markers: hasMarkers(root, c.path) }));
|
||||
out({ ok: true, op, step, total, commit: headCommit(root, OP_HEAD[op]), files, ready: !files.some((f) => f.markers) });
|
||||
}
|
||||
|
||||
// First match wins, in this order.
|
||||
const ERROR_KINDS = [
|
||||
["rejected", ["[rejected]", "non-fast-forward", "fetch first"], "Pull first, then push again."],
|
||||
[
|
||||
"auth",
|
||||
["Authentication failed", "could not read Username", "terminal prompts disabled", "Permission denied (publickey)", "The requested URL returned error: 403"],
|
||||
"This tool never handles logins. Sign in from your terminal (ssh-add, or your git credential helper), then try again.",
|
||||
],
|
||||
["dirty", ["would be overwritten by", "You have unstaged changes", "Please commit your changes or stash them"], "Commit first, or cancel."],
|
||||
["conflict", ["CONFLICT (", "could not apply", "Resolve all conflicts manually"], "Resolve the conflicts, or abort."],
|
||||
// A pull --ff-only the remote outran since the last look: the board plans a
|
||||
// rebase pull once it has seen the split.
|
||||
["diverged", ["Not possible to fast-forward", "Diverging branches can't be fast-forwarded"], "Refresh, then Pull again: it rebases your commits onto the remote's."],
|
||||
[
|
||||
"network",
|
||||
["Could not resolve host", "timed out", "Connection refused", "Couldn't connect to server", "Failed to connect", "unable to access", "Could not read from remote repository", "does not appear to be a git repository"],
|
||||
"Check your network or VPN, and the remote's address, then Refresh.",
|
||||
],
|
||||
];
|
||||
|
||||
function classifyError({ file }) {
|
||||
const f = requireValue(file, "file", "classify-error --file <session>/git-stderr.txt");
|
||||
const text = readText(f);
|
||||
if (text === null) fail(EXIT.INVALID, "unreadable-file", `Cannot read ${f}.`, "Save git's stderr to a file in the session folder and pass its path.");
|
||||
const found = ERROR_KINDS.find(([, needles]) => needles.some((n) => text.includes(n)));
|
||||
if (!found) return out({ ok: true, kind: "other", next: "Read git's message above." });
|
||||
const [kind, , next] = found;
|
||||
const result = { ok: true, kind, next };
|
||||
// git lists the files in the way, one per tab-indented line.
|
||||
if (kind === "dirty") result.files = text.split(/\r?\n/).filter((l) => l.startsWith("\t")).map((l) => l.trim()).filter(Boolean);
|
||||
out(result);
|
||||
}
|
||||
|
||||
async function prUrlCmd({ root, branch, base }) {
|
||||
const s = repoState(root);
|
||||
const b = (branch || "").trim() || s.branch;
|
||||
if (!b) fail(EXIT.REFUSED, "detached", "HEAD is detached, so there is no branch to open a pull request for.", "Switch to a branch, or pass --branch.");
|
||||
const row = localBranch(s, b);
|
||||
if (!row) fail(EXIT.INVALID, "unknown-branch", `There is no local branch named "${b}".`, "Pick a branch from the list.");
|
||||
const into = (base || "").trim() || s.def.name;
|
||||
if (!into) fail(EXIT.INVALID, "no-base", "There is no default branch to open the pull request against.", "Pass --base <branch>.");
|
||||
// A pull request from a branch into itself is no pull request (a push to main).
|
||||
if (into === b) fail(EXIT.INVALID, "is-base", `${b} is the branch pull requests go into, so there is nothing to open.`, "Post no link for this push.");
|
||||
const remote = row.upstream && !row.gone ? R.readRemotes(root, await prHosts()).find((r) => r.name === row.upstreamRemote) : null;
|
||||
if (!remote) fail(EXIT.INVALID, "not-pushed", `${b} is not on a remote yet.`, "Publish it first (plan publish).");
|
||||
out({ ok: true, url: R.prUrl(remote, { base: into, head: b }), host: remote.host, kind: remote.kind, needsKind: !!remote.host && !remote.kind });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ main */
|
||||
|
||||
const COMMANDS = {
|
||||
state,
|
||||
plan,
|
||||
"branch-check": branchCheck,
|
||||
"init-check": initCheck,
|
||||
"delete-check": deleteCheckCmd,
|
||||
"cleanup-list": cleanupListCmd,
|
||||
conflicts,
|
||||
"pr-url": prUrlCmd,
|
||||
"classify-error": classifyError,
|
||||
};
|
||||
const NO_REPO = new Set(["init-check", "classify-error"]);
|
||||
|
||||
async function main(argv) {
|
||||
const args = parseArgs(argv, { values: ["name", "branch", "from", "remote", "base", "file"], lists: ["files", "select"] });
|
||||
const [cmd, ...extra] = args._;
|
||||
const names = Object.keys(COMMANDS).join(", ");
|
||||
if (!cmd) fail(EXIT.USAGE, "missing-command", `A subcommand is required: ${names}.`, "Run with --help for usage.");
|
||||
if (!Object.hasOwn(COMMANDS, cmd)) fail(EXIT.USAGE, "unknown-command", `Unknown subcommand "${cmd}".`, `Use one of: ${names}.`);
|
||||
if (extra.length > (cmd === "plan" ? 1 : 0)) fail(EXIT.USAGE, "stray-argument", `Unexpected argument(s): ${extra.join(" ")}.`, "Run with --help for usage.");
|
||||
R = await gitRepo();
|
||||
if (!NO_REPO.has(cmd)) {
|
||||
requireGit();
|
||||
args.root = requireRepo();
|
||||
}
|
||||
return COMMANDS[cmd](args, extra);
|
||||
}
|
||||
|
||||
// Run as a script; imported (by the tests, for guard()), do nothing.
|
||||
const isMain = (() => {
|
||||
try {
|
||||
return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
if (isMain) run(USAGE, main);
|
||||
@@ -0,0 +1,118 @@
|
||||
# 🔀 GIT MODE
|
||||
|
||||
Start all GIT MODE responses with '🔀'
|
||||
|
||||
## Role
|
||||
|
||||
Careful git operator. Read where the repository stands, do what the person asks with branches, pulls, pushes and commits, and say plainly what each step did. Nothing leaves the machine without a yes.
|
||||
|
||||
## Interface
|
||||
|
||||
An instruction in the argument (`/plan2code-git switch to main`, `/plan2code-git commit and push`, a commit subject) runs in the terminal at once: do not ask about the console. With no argument, the FIRST thing you do, before anything else in this file, before reading the repository: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow git` before reading (<D>: references/web-console/ beside this SKILL.md, ~/.agents/skills/plan2code-git/references/web-console/ globally, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/git.md. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`) take it and do not ask; drop the flag. Launched by the dashboard, or by a **Commit it now** or Changelog hand-off? Its session is already open: resume it with `--workflow git` (console-launches.md). Handed off to commit (Commit it now, Changelog's yes): post `reread`, then run the Commit flow from step 1 over every changed file (risky ones left out and named), its cards above the board; afterwards the board is theirs with Push lit. On the console, a `__stop` action is the person ending the session (console-stop.md); at every session end post `finish` BEFORE `stop`.
|
||||
|
||||
## Project context
|
||||
|
||||
Read `./AGENTS.md` when it exists, for commit conventions (subject style, branch names). Never block on it.
|
||||
|
||||
## Argument
|
||||
|
||||
Optional: a plain instruction (`switch to main`, `pull`, `commit and push`, `delete old-branch`) or a commit subject. `--web` is the console flag, not part of an instruction. A bare phrase that reads as a commit subject (`fix timeout on report export`) is a commit with that subject, as the old Git commit skill took it.
|
||||
|
||||
## Rules
|
||||
|
||||
- Never force-push, in any form.
|
||||
- Never amend unless asked. Never `--no-verify`.
|
||||
- Stage named files only. Never `git add -A` or `git add .`.
|
||||
- Never push or publish without an explicit yes.
|
||||
- Never delete a remote branch. Deleting a local branch needs a yes.
|
||||
- `git status` never with `-uall`.
|
||||
- A failed hook: diagnose it, fix the cause, re-stage the group's files, make a NEW commit. A hook that fails on a problem unrelated to the staged changes is reported to the person, not worked around.
|
||||
- The message is exactly what `commit-msg.mjs` builds: `<subject>`, a blank line, `AI Assisted`. Subject at most 100 characters, about why. No other AI attribution.
|
||||
- `sensitive` and `large` files are left out and named. Include one only if the person insists after a warning.
|
||||
- Run no tests and no review before committing (Implement and Review do that).
|
||||
- On Windows PowerShell 5.1 (no `&&`), run separate commands.
|
||||
- Run exactly the `command` (or each of `commands`, in order) that `git.mjs plan` prints, and nothing in its place. Post its `confirm` verbatim as the card.
|
||||
- Run a `network: true` command with `GIT_TERMINAL_PROMPT=0` (plus any `env` it gives), under the plan's `timeoutMs` when there is one.
|
||||
- One action per turn. Never queue a second click behind the first.
|
||||
- The scripts and the console never write to the repository. Only you do, and only behind these rules.
|
||||
|
||||
## Scripts
|
||||
|
||||
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-git/scripts/` globally). Run them from the project folder. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says.
|
||||
|
||||
`git.mjs` only reads. Exit 0 ok · 1 crash · 2 bad arguments · 3 not a git repository · 4 invalid input, or nothing to do · 5 refused by a rule (`git-too-old`, `detached`, `refused`, `still-conflicted`). Post `plan`'s `confirm` as a card verbatim, and run its `command` (or each of `commands`, in order) exactly as printed.
|
||||
|
||||
- `node "<S>/git.mjs" state`: the commit flow's facts (`branch`, `defaultBranch`, `onDefault`, `inProgress`, `conflicted`, `staged`, `unstaged`, `untracked`, `nothingToCommit`, `sensitive`, `large`, `remotes`, `upstream`, `ahead`, `behind`, `unpublished`, `push`), plus `git` (the board's snapshot) and `next`, the likely next action. Exit 3 `not-a-repo`.
|
||||
- `node "<S>/git.mjs" plan <op> [flags]`: `ask`, `confirm`, `command` or `commands`, `network` (run with `GIT_TERMINAL_PROMPT=0`), `timeoutMs`, `env`, `card` (`dirty`, `switch` or `remote`: ask it before running anything). Ops: `refresh`, `pull`, `push`, `publish [--remote <r>]`, `switch --branch <b>`, `create --name <n> [--from <ref>]`, `delete --branch <b>`, `cleanup --select <b> ...`, `abort`, `continue`. Exit 4 means nothing to do (`up-to-date`, `nothing-to-push`, `no-upstream`, `already-on`, ...).
|
||||
- `node "<S>/git.mjs" branch-check --name <name>`: is the name free? Exit 4 `invalid-name`, `branch-exists` or `exists-on-remote` (both with `switchTo`), `branch-conflict`.
|
||||
- `node "<S>/git.mjs" init-check`: can `git init` be offered here? `safe`, `reason`, `hasGitignore`, `suggestedIgnore`, and `branch` with the `commands` that start the repository on it.
|
||||
- `node "<S>/git.mjs" delete-check --branch <b>`: `merged`, `gone`, `onlyHere` (count and commits), `remoteCopy`, `flag`, `sentence`.
|
||||
- `node "<S>/git.mjs" cleanup-list`: `merged` and `gone` branch names.
|
||||
- `node "<S>/git.mjs" conflicts`: the stopped operation's `op`, `step` of `total`, `commit`, `files` (with `markers`), `ready`. Exit 4 `nothing-in-progress`.
|
||||
- `node "<S>/git.mjs" pr-url [--branch <b>] [--base <b>]`: `url`, `host`, `kind`; `needsKind: true` means ask once what kind of host it is. Exit 4 `not-pushed`.
|
||||
- `node "<S>/git.mjs" classify-error --file <stderr file>`: `kind` (`rejected`, `auth`, `dirty`, `conflict`, `diverged`, `network`, `other`), `next`, and `files` for `dirty`.
|
||||
- `node "<S>/commit-msg.mjs" --subject "<subject>" --files <path> [--files <path> ...]`: the commit command (one `--files` per path). Exit 4 means the subject or a path breaks a rule: rephrase it.
|
||||
|
||||
## The board
|
||||
|
||||
On the console the page draws the board itself from `state.git`; you never post it. Each click arrives through the wait loop as one `__git` action (`{ "i": "__git", "type": "git", "op": "switch", "branch": "main" }`, field shapes in notes/git.md), with `reply` the plain instruction the terminal would get. One action per turn:
|
||||
|
||||
1. Post an `activity` line ("Pulling from origin…"); collecting the click already set the page to working.
|
||||
2. Run `git.mjs plan <op>` with the action's fields as flags.
|
||||
3. With `ask: true`: a `confirm` becomes a `confirm` card, posted verbatim (`danger` and `consequences` as given; `files` as a `[{ path, state }]` table where the plan names files). A `card` of kind `switch`, `dirty` or `remote` becomes a `choice` card with exactly its `options`, labelled **Switch and bring them** (`bring`), **Commit first** (`commit-first`) and **Cancel** (`cancel`), or for `remote` one option per remote with `preset` recommended; put git's `reason` in `body` when given. Then wait for the answer. A `remote` pick plans `publish --remote <it>` again and asks its `confirm`.
|
||||
4. Run the command(s).
|
||||
5. In ONE post: `{ "reread": true }`, the `git-result` notice (one line: what happened, with short hashes, and after a push or publish the link from `pr-url`), `board: { describe }` when changes remain (a short kebab-case description of them, for the Create prompt), posted with `--wait`.
|
||||
|
||||
On a non-zero exit, save git's stderr to the session folder, run `classify-error --file <it>`, quote git's error verbatim in the `git-result` notice with `next`, and post `reread` the same way. A Refresh failure posts `reread: { refreshFailed: true }`. An `auth` kind gets a card saying this tool never handles logins, with `next`. A plan that exits 4 or 5 runs nothing: its `message` and `next` are the `git-result` notice. A `conflict` kind, or `state` showing `inProgress` after the command, is not a failure line: post `reread` and go to Conflict help.
|
||||
|
||||
## Actions
|
||||
|
||||
- **refresh, pull, switch, create** run on the click when the plan says `ask: false` (a clean tree, a fast-forward).
|
||||
- **push, publish, delete, cleanup** always ask first, with the plan's `confirm`.
|
||||
- **switch** with changes: **Switch and bring them** runs the switch; **Commit first** runs the Commit flow over the changed files, then the switch; **Cancel** does nothing but the `git-result` line. A pull's `dirty` card works the same way, with the pull in place of the switch.
|
||||
- **create** with `then: "commit"` creates the branch, then continues the Commit flow on it with the action's `files` (and `ignore`, as for commit).
|
||||
- **commit** commits only the paths in `files`. With `ignore[]`, first propose those `.gitignore` lines as a doc plus a `review` card (approve / change), write them on approve, and add `.gitignore` to the commit.
|
||||
- **abort**, **continue**: `plan abort` / `plan continue`, then `reread`.
|
||||
- **pr-host**: the server already saved the answer; post `reread` only.
|
||||
- **done**: Session End.
|
||||
- Deleting a branch on the remote is never offered and never run.
|
||||
|
||||
## Conflict help
|
||||
|
||||
When a pull, or a rebase or merge already in progress, stops on conflicts:
|
||||
|
||||
1. Ask "Resolve them for me?" (a `choice`): **Yes** / **I'll fix it** / **Abort pull**, its `detail` saying it puts the branch back exactly as it was.
|
||||
2. On yes, at every stop: run `conflicts`, resolve each file, then post a doc with the stop's summary (step N of M, the commit being replayed, each file with a one-line reason) and a per-file diff, plus a `review` card with the verdicts **Continue**, **Change it** and **Abort pull** (`danger`). Run `plan continue`'s commands only after **Continue**. **Change it** takes their note and asks again at the same stop.
|
||||
3. A file you cannot resolve with confidence is named with its clash and left alone, never guessed: **Abort pull** runs `plan abort`; **I'll fix it** leaves the markers, and the board's Continue appears once none remain.
|
||||
4. Abort is offered at every stop. Never push or publish during conflict help. Skipping a commit, editing a file git did not flag, or reordering is only ever a proposal named in that stop's summary.
|
||||
5. Afterwards post a summary card (commits replayed, each resolved file with its reason, "N commits ready to push") and `run: { "event": "git-conflict", "id": "conflict-<n>" }` once, whether it ended resolved or aborted.
|
||||
|
||||
In the terminal the same stops are asked in prose, with the diff printed.
|
||||
|
||||
## Commit flow
|
||||
|
||||
1. **State.** Run `state`. Exit 3 → 1b. `inProgress` or `conflicted` → say what is in progress and go to Conflict help.
|
||||
1b. **Not a repository.** Run `init-check`. `safe: false` → explain (inside another repository, the home folder or a drive root) and stop. `safe` → ask before `git init`, naming the folder and its first branch (`branch`, `main` unless `init.defaultBranch` says otherwise). On yes run `commands` in order (never a bare `git init`, which may start on `master`). If `hasGitignore` is false and `suggestedIgnore` is not empty, propose that `.gitignore` for approval, write it, then continue at 4 (the first commit; no push offer later because there is no remote; say it can be added with `git remote add origin <url>`).
|
||||
2. **Nothing to commit.** If `push` is not null, go to 7. Otherwise say the tree is clean and everything is pushed (or that there is no remote), and stop.
|
||||
3. **Branch.** On the board, skip this: the page's **You're on main** line already offered it, and its answer arrives as `create` with `then: "commit"`. In the terminal, when `onDefault` (or `detached`) and `hasCommits`, offer one drafted branch name `<type>/<short-description>` (types: feature, fix, chore, docs, refactor, test; `feature/export-csv`). Run any name the person types through `branch-check`, then `plan create`. Skipping is always fine (on a detached HEAD, warn that commits there are easy to lose). When `defaultBranch` is null say why there is no offer.
|
||||
4. **Read the changes.** `git diff`, `git diff --cached` and the untracked files (an `untracked` path ending in `/` is a folder: list its files with `git ls-files -o --exclude-standard -- <folder>` and stage them by name). If the person staged some files, work from that staged set and leave the rest alone (say what was left). On the board, only the paths the action named, or every changed file on a hand-off. Decide whether the work is one concern or several.
|
||||
5. **Message.** One concern: draft a subject, or use the argument and skip approval; ask **Yes** / **Edit** / **No**. Several: always suggest whole-file groups, each with a subject, naming any file that mixes concerns and which group took it; ask **Approve** / **Change it** / **One commit instead** (asked even when the subject came as the argument). Name the `sensitive` and `large` files you are leaving out.
|
||||
6. **Commit.** For each group in order: with more than one group, run `git reset -q` first so only that group is staged; then run `commit-msg.mjs --subject "<s>" --files <a> --files <b>` (`--files` once per path) and its `command` (or `add`, then `commit`). Finish with `git log --oneline -<n>`. On the console post `run: { "event": "git-commits", "id": "<first short hash>", "commits": <n> }` with the `reread` and a `git-result` line naming the hashes, so the board lights Push.
|
||||
7. **Push.** In the terminal, stop after committing with a one-line push hint and no push prompt. `commit and push` (or a push the person asks for) runs `plan push` / `plan publish` and asks its `confirm`. A rejected push: report it, suggest Pull, run nothing more.
|
||||
|
||||
## Terminal
|
||||
|
||||
- **No instruction:** print the status from `state` (branch, ahead/behind, changed files) and ask what to do, `next` first.
|
||||
- **After an action:** show the new state and one line naming the likely next step, then stop. A follow-up reply runs it; there is no "what next?" loop.
|
||||
- **Several actions in one instruction** (`commit and push`): state the plan in one line, run each step in order, ask each ask-first confirm at its own step with the same `confirm` text the board shows, and stop at the first failure with git's error and `classify-error`'s `next`.
|
||||
- **An unclear instruction:** offer the two or three likely readings through the question tool, the state-based guess first. Never run on a guess.
|
||||
- Print the pull-request link from `pr-url` after a push or publish (`needsKind` → ask the host's kind once and say it is remembered).
|
||||
|
||||
## Session End
|
||||
|
||||
- **Done on the board, with something done this session:** post `finish` with a headline, a `body` listing the commits with hashes, pushes, and branches created or deleted, no `command`, and `"dashboard": true`. Then keep waiting for the dashboard press (console-finish.md).
|
||||
- **Done with nothing done:** resume as the dashboard at once (`open --resume <sid> --no-open --workflow dashboard`, then read the dashboard skill, post its menu and follow its "Coming back from another skill"), with no finish screen.
|
||||
- **A `__stop`:** a finish whose headline starts "Paused", with `"command": "/plan2code-git"`, then `stop`.
|
||||
- **Terminal:** the last state line is enough.
|
||||
|
||||
Returning context: run `/plan2code-git` again for the next action.
|
||||
@@ -9,7 +9,7 @@ and can open files, but they cannot see this conversation. Write for them.
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before inferring the next task: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow handoff` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-handoff/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md. The next-task confirmation and any clarifying questions go through it, and the finished handoff lands on the page as a doc with the download the page offers. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console.md → Launches), then the one hard rule. On the console, a `__stop` action is the person ending the session (console.md → Stop requests); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console.md → Finishing).
|
||||
The FIRST thing you do, before anything else in this file — before inferring the next task: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow handoff` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-handoff/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/handoff.md. The next-task confirmation and any clarifying questions go through it, and the finished handoff lands on the page as a doc with the download the page offers. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then the one hard rule. On the console, a `__stop` action is the person ending the session (console-stop.md); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console-finish.md).
|
||||
|
||||
## The one hard rule: capture the next task, and confirm it with the user
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Interactive Q&A flow to update an existing `AGENTS.md` with new learnings and pr
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before the Awareness Context: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow init-update` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-init-update/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md. Every question in the Q&A flow and the restructure offer go through it. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console.md → Launches), then Awareness Context. On the console, a `__stop` action is the person ending the session (console.md → Stop requests); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console.md → Finishing).
|
||||
The FIRST thing you do, before anything else in this file — before the Awareness Context: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow init-update` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-init-update/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/init.md. Every question in the Q&A flow and the restructure offer go through it. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Awareness Context. On the console, a `__stop` action is the person ending the session (console-stop.md); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console-finish.md).
|
||||
|
||||
## Scripts
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Analyze this codebase and create `AGENTS.md` to guide future AI coding agents (C
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before exploring the codebase: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow init` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-init/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md. Every confirmation — the restructure offer, the AI-agent file-sync prompt — goes through it, and the finished AGENTS.md lands on the page as a doc marked `saved` (the file is already on disk — no download offered). Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console.md → Launches), then Content. On the console, a `__stop` action is the person ending the session (console.md → Stop requests); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console.md → Finishing).
|
||||
The FIRST thing you do, before anything else in this file — before exploring the codebase: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow init` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-init/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/init.md. Every confirmation — the restructure offer, the AI-agent file-sync prompt — goes through it, and the finished AGENTS.md lands on the page as a doc marked `saved` (the file is already on disk — no download offered). Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Content. On the console, a `__stop` action is the person ending the session (console-stop.md); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console-finish.md).
|
||||
|
||||
## Scripts
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Senior software architect. Analyze requirements, ask clarifying questions, deliv
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before asking what to build: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow quick-task` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-quick-task/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/building.md. Every question, the scope check and the plan go through it; once the task is built, the finish offers a review of it on the page. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console.md → Launches), then the AGENTS.md check.
|
||||
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before asking what to build: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow quick-task` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-quick-task/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md, <D>/building.md and <D>/notes/quick-task.md in one batch. Every question, the scope check and the plan go through it; once the task is built, the finish offers a review of it on the page. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then the AGENTS.md check.
|
||||
|
||||
## Project Context (BLOCKING)
|
||||
|
||||
@@ -49,7 +49,7 @@ Check for `./AGENTS.md` first:
|
||||
╰┬─┬╯
|
||||
```
|
||||
|
||||
Ask what feature the user wants, then ask follow-up questions until 100% clear. Console: that first card carries `"templates": "idea"` (console.md → Starter templates).
|
||||
Ask what feature the user wants, then ask follow-up questions until 100% clear. Console: that first card carries `"templates": "idea"` (console.md → The kinds).
|
||||
|
||||
## Scope Validation
|
||||
|
||||
@@ -158,4 +158,4 @@ Ready to implement? (yes / modify / escalate / abort)
|
||||
|
||||
Work summary — tell user: task name, plan delivered (or PLAN-DRAFT created if escalated).
|
||||
|
||||
**On the web console:** a `__stop` action in a send is the person ending the session: see console.md → Stop requests. At every session end (built, escalated, aborted) post `finish` BEFORE `stop`, as building.md → Quick task describes. After a build, keep waiting for the review button's answer before you stop.
|
||||
**On the web console:** a `__stop` action in a send is the person ending the session: see console-stop.md. At every session end (built, escalated, aborted) post `finish` BEFORE `stop`, as notes/quick-task.md describes. After a build, keep waiting for the review button's answer before you stop.
|
||||
@@ -8,7 +8,7 @@ Critical review specialist -- experienced senior engineer providing independent
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before the scope detection: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow review` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md. Scope questions, the findings report and the pick-what-gets-fixed menu all go through it; the report lands on the page as a doc. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console.md → Launches), then Process. Read inside a build session for its review button? Skip this section — building.md's overrides govern, the session is already running. On the console, a `__stop` action is the person ending the session (console.md → Stop requests); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console.md → Finishing).
|
||||
The FIRST thing you do, before anything else in this file — before the scope detection: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow review` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/review.md. Scope questions, the findings report and the pick-what-gets-fixed menu all go through it; the report lands on the page as a doc. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Process. Read inside a build session for its review button? Skip this section — building-review.md's overrides govern, the session is already running. On the console, a `__stop` action is the person ending the session (console-stop.md); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console-finish.md).
|
||||
|
||||
## Scripts
|
||||
|
||||
@@ -42,7 +42,7 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
| **Branch** | "review my changes", or picked when asked | Branch changes vs main |
|
||||
| **Full** | "full review" or names a subsystem | Entire codebase/subsystem |
|
||||
|
||||
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Scope already decided by a host workflow (a build's review, `building.md`) = use it. 4) Standalone with nothing named = scan, then ask (Step 1). Never default to `branch` silently. Ambiguous? Ask.
|
||||
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Scope already decided by a host workflow (a build's review, `building-review.md`) = use it. 4) Standalone with nothing named = scan, then ask (Step 1). Never default to `branch` silently. Ambiguous? Ask.
|
||||
|
||||
**Thoroughness:** Scope controls WHAT is reviewed, not HOW DEEPLY. Every review is thorough.
|
||||
|
||||
|
||||
+11
-12
@@ -11,8 +11,8 @@ The front door. One page in the person's browser lists every Plan2Code skill; th
|
||||
The console is the whole point of this skill — do not ask "browser or terminal"; open it, and open it FIRST. The person is looking at nothing until you do, so the page comes before any other reading or exploring.
|
||||
|
||||
1. Your very first command: `node "<D>/console.mjs" open --workflow dashboard`, where `<D>` is references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code/references/web-console/ globally, or the dir in ~/.plan2code/console/console-dir). No `--title` needed — it defaults to the folder name. The page is up and usable at once: the cards and the project scan come from the console itself.
|
||||
2. Now read <D>/console.md, then post the menu payload (below).
|
||||
3. Wait. The wait loop is console.md's, unchanged; every send here is a pick, a stop, or a message.
|
||||
2. Now read <D>/console.md and <D>/console-launches.md (once per conversation — skip any you already read), then post the menu payload (below) with `post --wait`.
|
||||
3. Wait. The turn is console.md's, unchanged; every send here is a pick, a stop, or a message.
|
||||
4. On a pick, you BECOME that skill (below). Dashboard duties end there.
|
||||
|
||||
If `open` fails outright, fall back without drama: list the skills in the terminal as a numbered menu and run the pick's command.
|
||||
@@ -27,8 +27,7 @@ The page draws the cards itself — you never send the list. It also knows the r
|
||||
"note": "one line under the title — what you made of the project",
|
||||
"recommend": "plan2code-init", // a skill name, or omit
|
||||
"details": { "plan2code-3-implement": "Phase 2 of 4 is next" }
|
||||
},
|
||||
"agent": { "status": "waiting" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -59,7 +58,7 @@ Ground truth for menu notes and Ask-tab answers. For anything beyond this table,
|
||||
| 4-finalize | spec + code | summary in `overview.md`; moves the spec to `specs--completed/` |
|
||||
| handoff | conversation, spec, git | `<timestamp>-handoff.md` (OS temp or `handoffs/`) |
|
||||
| changelog | `CHANGELOG.md`, `package.json`, git history | `CHANGELOG.md` entries, `package.json` version; no commits |
|
||||
| git-commit | git status, diffs, `AGENTS.md` | commits; optional branch, `.gitignore`, push; no spec writes |
|
||||
| git | git status, branches, diffs, `AGENTS.md` | commits, branches; optional `.gitignore`, push, publish; no spec writes |
|
||||
|
||||
## A pick arrives
|
||||
|
||||
@@ -79,14 +78,14 @@ A card click is a send whose action carries the skill:
|
||||
|
||||
On it, in this turn:
|
||||
|
||||
1. **Resume the session as that skill — before reading anything**, in one command:
|
||||
1. **Resume the session as that skill — before reading anything**, in one command: run the send's `resume` exactly as given. It is
|
||||
|
||||
```
|
||||
node "<D>/console.mjs" open --resume <sid> --no-open --workflow <its workflow> --spec <action.spec>
|
||||
```
|
||||
|
||||
`<its workflow>` is the action's `workflow` field (mapped below). Pass `--spec` only when the action carried one; `--title` is optional — post a real title once you know what the run is about. Never a fresh `open` — that strands the page they are watching on the dashboard's session. `--no-open` keeps the browser put: the page they already have IS the session, and this one command both reuses the server and turns it into the new skill's starting screen, while you read.
|
||||
2. **Read the skill's file with your own file-read tool.** Installs put every skill beside this one at `~/.agents/skills/<skill>/SKILL.md` — `<skill>` is the action's `skill` field.
|
||||
`<its workflow>` is the action's `workflow` field (mapped below), and `--spec` is there only when the action carried one; `--title` is optional — post a real title once you know what the run is about. Never a fresh `open` — that strands the page they are watching on the dashboard's session. `--no-open` keeps the browser put: the page they already have IS the session, and this one command both reuses the server and turns it into the new skill's starting screen, while you read.
|
||||
2. **Read the skill's file with your own file-read tool**: the send's `skillFile`, or `~/.agents/skills/<skill>/SKILL.md` — `<skill>` is the action's `skill` field. Do not read console.md again; read only the notes or building files its Interface names.
|
||||
3. **Follow the skill file from the top.** Its Interface step is already answered — the console is open, this is the session, you are mid-turn. Start where its real work starts: for most skills the AGENTS.md check; for pathfinder, Step 0's gate. When it tells you to open a console session, you already have: skip to its first `post`.
|
||||
|
||||
The page shows a getting-ready screen from the click until the resume lands, then the skill's own starting screen until its first payload — so resume first, and post before anything slow; an `activity` line says what you are doing meanwhile.
|
||||
@@ -101,14 +100,14 @@ If `skill` is not in the table below, say so on the page and stay the dashboard.
|
||||
| plan2code-1-plan | plan | | plan2code-review | review |
|
||||
| plan2code-1b-revise-plan | revise-plan | | plan2code-4-finalize | finalize |
|
||||
| plan2code-quick-task | quick-task | | plan2code-handoff | handoff |
|
||||
| plan2code-git-commit | git-commit | | plan2code-changelog | changelog |
|
||||
| plan2code-git | git | | plan2code-changelog | changelog |
|
||||
|
||||
## Coming back from another skill
|
||||
|
||||
You arrive here mid-conversation after a `__dashboard` press — from a finished screen, or mid-workflow from the top bar's triangle once that skill saved its place — having already run `open --resume <sid> --no-open --workflow dashboard` and posted `"finish": null` with the menu (console.md → Finishing; Stop requests → "Back to the dashboard, mid-workflow"). Skip Interface steps 1–2; your first job is the menu judgment: re-read `state.scan`, which the resume refreshed — the spec you just worked on is usually the most recently touched. Then the usual wait loop and launches.
|
||||
You arrive here mid-conversation after a `__dashboard` press — from a finished screen, or mid-workflow from the top bar's triangle once that skill saved its place — having already run `open --resume <sid> --no-open --workflow dashboard` (the send's `resume`; it cleared the last skill's page, its finish included — console-finish.md, console-stop.md). Skip Interface steps 1–2; your first job is the menu judgment, then post the menu with `--wait`: re-read `state.scan`, which the resume refreshed — the spec you just worked on is usually the most recently touched. Then the usual wait loop and launches.
|
||||
|
||||
## While it waits
|
||||
|
||||
- Bounded slices per console.md, using the longest safe slice: exit 10 → relay one line and immediately wait again — never end the turn after an arbitrary number of slices; exit 20 → `open --resume <sid>` (no `--workflow` — it stays `dashboard` until a launch overwrites it); exit 30 → they cancelled, ask in the terminal what they want.
|
||||
- A `__stop` action is the person ending the session before picking: post `finish` (a headline that says paused, `"command": "/plan2code"`) then `stop`, per console.md → Stop requests.
|
||||
- Keep `agent.status` honest: `waiting` while the menu is theirs, `working` with `activity` while a launch becomes a skill.
|
||||
- A `__stop` action is the person ending the session before picking: post `finish` (a headline that says paused, `"command": "/plan2code"`) then `stop`, per console-stop.md.
|
||||
- The console keeps `agent.status` honest: collecting a pick sets `working`, and waiting on the menu sets `waiting`. Post an `activity` while a launch becomes a skill.
|
||||
@@ -22,17 +22,21 @@ export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
|
||||
|
||||
export class CliError extends Error {
|
||||
constructor(exit, error, message, next) {
|
||||
constructor(exit, error, message, next, extra) {
|
||||
super(message);
|
||||
this.exit = exit;
|
||||
this.error = error;
|
||||
this.next = next;
|
||||
this.extra = extra;
|
||||
}
|
||||
}
|
||||
|
||||
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
|
||||
export function fail(exit, error, message, next) {
|
||||
throw new CliError(exit, error, message, next);
|
||||
/**
|
||||
* Throw a handled failure: the run() wrapper prints it and sets the exit code.
|
||||
* `extra` adds fields to the failure JSON (a branch to switch to, the files).
|
||||
*/
|
||||
export function fail(exit, error, message, next, extra) {
|
||||
throw new CliError(exit, error, message, next, extra);
|
||||
}
|
||||
|
||||
export function out(obj) {
|
||||
@@ -97,7 +101,7 @@ export async function run(usage, main) {
|
||||
await main(argv);
|
||||
} catch (err) {
|
||||
if (err instanceof CliError) {
|
||||
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
|
||||
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}), ...(err.extra || {}) });
|
||||
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
|
||||
process.exitCode = err.exit;
|
||||
return;
|
||||
@@ -233,6 +237,29 @@ export function consoleLib() {
|
||||
return consoleLibPromise;
|
||||
}
|
||||
|
||||
// The one read-only git reader (git-repo.mjs) ships beside lib.mjs, so the git
|
||||
// skill's scripts read the repository with exactly the code the console uses.
|
||||
const GIT_REPO_CANDIDATES = [
|
||||
path.join(HERE, "..", "references", "web-console", "git-repo.mjs"), // installed skill
|
||||
path.join(HERE, "..", "web-console", "git-repo.mjs"), // src/skill-scripts in the repo
|
||||
];
|
||||
|
||||
let gitRepoPromise;
|
||||
export function gitRepo() {
|
||||
gitRepoPromise ||= (async () => {
|
||||
for (const candidate of GIT_REPO_CANDIDATES) {
|
||||
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
|
||||
}
|
||||
fail(
|
||||
EXIT.NOT_FOUND,
|
||||
"git-repo-missing",
|
||||
`The web console's git-repo.mjs is not beside this script (looked in ${GIT_REPO_CANDIDATES.join(", ")}).`,
|
||||
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
|
||||
);
|
||||
})();
|
||||
return gitRepoPromise;
|
||||
}
|
||||
|
||||
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
|
||||
export function version() {
|
||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
# The Review, Mid-Session, on the Web Console
|
||||
|
||||
Part of the build contract (`building.md`). Read when the person asks for the
|
||||
review on the page: the `review` verdict on Implement's sign-off card, the
|
||||
**Review it now** button on a finished quick task, or Implement + Review's
|
||||
Stage 2.
|
||||
|
||||
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
|
||||
{
|
||||
"settle": true,
|
||||
"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 `settle`, 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 — there is no timeout after
|
||||
a finish.
|
||||
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-finish.md` → After the finish). |
|
||||
| An action `{ "i": "__done", "type": "done" }` | `stop` the server. The session is over. |
|
||||
| `wait` exit `20` | The server is gone. Resume it (`open --resume <sid> --workflow <yours>`), give them the new link, and keep waiting. |
|
||||
| The session ends without a press (the terminal closes) | The server sweeps itself after its idle window; 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,
|
||||
posted with `--wait`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"docs": [{ "id": "review", "title": "Review findings", "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"] }
|
||||
]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
`"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 (`"settle": true`) in the same post that goes back to
|
||||
work. 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. A send with nothing ticked settles as `{ "ks": [] }`. 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, then reopen the
|
||||
sign-off **without the review verdict** — re-offering a review that just ran
|
||||
reads as though nothing happened — and post the build's `headline` back (the
|
||||
review set it to its own stage):
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "cleared": 9, "total": 9 },
|
||||
"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." }]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
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 `notes/implement.md` → 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"`, `"nothingYet": false` (the fixes are already made), verdicts `approve` ("The fixes look
|
||||
right") and `changes`, token `approved` / `needs changes`. When it clears,
|
||||
settle it (`"settle": true`) in the same post as the new finish, post the finish
|
||||
**without** `review` (and with `dashboard: true`), then keep waiting for its
|
||||
buttons as `console-finish.md` says; `stop` only on `__done`. 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`: one commit for the whole quick task, its changes and the fixes
|
||||
together, in the project's commit format (not a second command beside the
|
||||
first), with `commit: true` so **Commit it now** is still on offer.
|
||||
- `headline`: the quick task's own again, e.g. `{ "cleared": 4, "total": 4 }`.
|
||||
- `doc`: `"review"`.
|
||||
+51
-407
@@ -1,10 +1,12 @@
|
||||
# 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.
|
||||
`/plan2code-quick-task`. Everything in `console.md` still applies (the turn,
|
||||
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. Then read your workflow's own notes: `notes/implement.md` (Implement
|
||||
and Implement + Review) or `notes/quick-task.md`. `building-review.md` is read
|
||||
only when a review is asked for on the page.
|
||||
|
||||
**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
|
||||
@@ -18,10 +20,6 @@ task, the same sign-off wording, the same "no git commands". The files under
|
||||
Open first, before reading the spec — the page shows a starting screen while
|
||||
you work out the phase:
|
||||
|
||||
```
|
||||
node "<CONSOLE>" open --workflow implement
|
||||
```
|
||||
|
||||
| Workflow you are running | `--workflow` | `--spec` |
|
||||
| --- | --- | --- |
|
||||
| `/plan2code-3-implement` | `implement` | `specs/<feature>` |
|
||||
@@ -32,103 +30,59 @@ node "<CONSOLE>" open --workflow implement
|
||||
answer a stop yourself. Pass it to `open` when you already know the spec;
|
||||
otherwise post `"specDir": "specs/<feature>"` and a real `title` ("<feature>:
|
||||
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.
|
||||
question as its first item if there is one to ask.
|
||||
|
||||
**Launched from the dashboard?** Then the session is already open and the
|
||||
person is watching it — `open --resume <sid> --no-open --workflow <yours>`
|
||||
(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.
|
||||
person is watching it — run the `resume` the launch carried (`open --resume
|
||||
<sid> --no-open --workflow <yours>`, plus `--spec` once known) instead of a
|
||||
fresh `open`, exactly as `console-launches.md` says. Everything below is
|
||||
unchanged; the only difference is whose session it was a minute ago.
|
||||
|
||||
---
|
||||
|
||||
## 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:
|
||||
Post after every task, in the same breath as writing its checkbox to disk,
|
||||
with no `--wait`. Your notes file shows the exact post; every one carries:
|
||||
|
||||
```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
|
||||
- **`headline.cleared` / `total`**: tasks done out of tasks in the run. The
|
||||
progress bar is the first thing someone watching a build looks at, and on
|
||||
Implement (and Implement + Review) the session meter counts the build's tasks
|
||||
from `cleared` as it rises; a quick task scores once, when it opens. Start every
|
||||
phase (a second one in the same run too) at `"cleared": 0`. If the task list
|
||||
grows mid-build, raise `headline.total` in the same post.
|
||||
- **`agent.activity`**: 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.
|
||||
the run, of the 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.
|
||||
- **`agent.quietMinutes`** (on the post that starts the build): how long you
|
||||
might go without posting (1 to 60; the page always allows at least two). 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. It only counts while you are working, so it
|
||||
holds across the questions you ask: set it once.
|
||||
- **The task list re-read from disk** (Implement): the doc blocks that mirror
|
||||
the spec are `file` blocks, so a progress post re-reads them with
|
||||
`"refresh": true` rather than repeating the text. A quick task's plan lives
|
||||
only on the page, so its steps block stays `md` (`notes/quick-task.md`).
|
||||
Versions move by themselves.
|
||||
|
||||
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
|
||||
`chat` check between tasks. Follow `console-subagents.md` 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:
|
||||
(`console-chat.md`). After each task's progress post, check for one before
|
||||
starting the next task:
|
||||
|
||||
```
|
||||
node "<CONSOLE>" chat --session <sid>
|
||||
@@ -136,9 +90,9 @@ node "<CONSOLE>" chat --session <sid>
|
||||
|
||||
| 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. |
|
||||
| `0` | Answer everything waiting, under `console-chat.md`, in one post, then start the next task. A `workspace` list in the output is a change to the session's folders (`console-workspace.md`): 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 <sid>` as usual, then carry on. |
|
||||
| `20` | The server is gone: `open --resume <sid> --workflow <yours>`, give them the new link, 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`
|
||||
@@ -150,11 +104,11 @@ 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.
|
||||
Publish it with `post --wait`: a new question hands the turn over by itself
|
||||
(status `waiting`). When the answer lands, collecting it
|
||||
sets you `working` again; carry on.
|
||||
|
||||
A question stops the build. Never leave yourself `working` with a question
|
||||
A question stops the build. Never post `"status": "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,
|
||||
@@ -174,320 +128,10 @@ 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",
|
||||
"commit": true,
|
||||
"dashboard": true
|
||||
},
|
||||
"agent": { "status": "waiting" }
|
||||
}
|
||||
```
|
||||
|
||||
`"commit": true` is there because the body prints a git command: the finished
|
||||
screen gets a **Commit it now** button, and its `__commit` press is handled as
|
||||
console.md → Finishing says (resume as `git-commit`, same session). Leave it out
|
||||
when the body prints no commit.
|
||||
|
||||
`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 <sid> --no-open --workflow <yours>`) 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": "<the Build this plan? item's 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 — `"commit": true` (the **Commit it now** button;
|
||||
console.md → Finishing) and `"dashboard": true`, so the finished screen
|
||||
also offers **Back to the dashboard**. Review and dashboard 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:
|
||||
When `__stop` arrives (`console-stop.md`):
|
||||
|
||||
- **implement / implement-review:** Implementation Mode's abort, without the
|
||||
"are you sure" (the page asked): the phase stays `[/]`, list completed and
|
||||
@@ -498,8 +142,8 @@ When `__stop` arrives:
|
||||
- **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
|
||||
A mid-build `__dashboard` (the top bar's triangle, `console-stop.md` → "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.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Keeping Attachments
|
||||
|
||||
Part of the web console contract (`console.md`). Read when a file you write
|
||||
under `specs/<idea>/` cites a note's attachment.
|
||||
|
||||
Note attachments are swept with the session. Before a file under `specs/<idea>/`
|
||||
cites one, keep it:
|
||||
|
||||
```
|
||||
node "<CONSOLE>" keep --session <sid> --upload <path> --name <name> --spec specs/<idea> --from <the file you are writing>
|
||||
```
|
||||
|
||||
It prints `{ ok, path, link, image, reused }`: paste `link` as it is
|
||||
(`` for an image, `[name](link)` otherwise) and name the kept file
|
||||
in your next update. Uncited and Quick-question attachments stay where they
|
||||
are. Exit 3 means refused: say so, link nothing.
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
# Quick Questions on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Read the first time `wait` or
|
||||
`chat` hands you a Quick question.
|
||||
|
||||
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 has checked in for a few minutes (a finish alone does
|
||||
not end the chat: you may still be waiting on its buttons),
|
||||
`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/<sid>/uploads/3f2b9c1e.jpg (shot.png)
|
||||
File: /home/sam/.plan2code/console/sessions/<sid>/uploads/9e4b2d7a.json (config.json)
|
||||
Declined: edit r7
|
||||
Note: keep the old name working too (only a decline carries one)
|
||||
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 "<CONSOLE>" chat --session <sid>` 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: [...] }`
|
||||
(`chat.replies`).
|
||||
|
||||
```jsonc
|
||||
{ "chat": { "replies": [
|
||||
{ "re": 12, "conversation": 3,
|
||||
"md": "The export is written by `src/export.js`, into `out/`." }
|
||||
] } }
|
||||
```
|
||||
|
||||
- `re` is the message's `seq`, `conversation` is copied from the entry, `md` is
|
||||
markdown. `id` is optional: left out, it is `r<re>`. Give one only when you
|
||||
send two replies to the same message.
|
||||
- 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: <first ~60 characters
|
||||
of the 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>/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 <id>`: 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 -- <files>` (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/<idea>/` (`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"] } }
|
||||
] } }
|
||||
```
|
||||
|
||||
## What the server checks
|
||||
|
||||
Each reply needs a unique `id` (or none, to take `r<re>`), 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/<idea>/`. `changed` is a list of `{ file, added,
|
||||
removed }`. The house rules on completion markers and metric-like words cover
|
||||
reply text too.
|
||||
|
||||
## The same chat 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.
|
||||
@@ -0,0 +1,118 @@
|
||||
# Finishing a Web Console Session
|
||||
|
||||
Part of the web console contract (`console.md`). Read before your first `finish`
|
||||
post, and when a send carries `__commit` or a finished screen's `__dashboard`.
|
||||
A stop request or the mid-workflow way home is `console-stop.md`.
|
||||
|
||||
Three steps, in this order. **Post the finish, keep waiting for a press —
|
||||
there is no timeout — and stop the server when the session ends.** 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. Post it on every session end, not only the last one: an off-ramp
|
||||
that routes elsewhere, a checkpoint that saves and stops, a stop request.
|
||||
|
||||
**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
|
||||
{
|
||||
"settle": true,
|
||||
"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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| 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. |
|
||||
| `commit` | optional | `true` on a finished `quick-task`, `implement`, `implement-review`, `review` or `finalize` whose finish prints a git command puts a **Commit it now** button on the finished screen. The press arrives as `__commit` (below). |
|
||||
| `review` | optional | A finished `quick-task` only: `true` or `{ "label": "..." }` puts a **Review it now** button on the finished screen (`notes/quick-task.md`, `building-review.md`). `implement` offers the review on its sign-off card instead — before approval, where it can still change the outcome. |
|
||||
|
||||
**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 settles it (`"settle": true`).
|
||||
|
||||
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 open after a finish for as long as you are still listening (the
|
||||
review and dashboard buttons live as long as you do); the page only turns Send
|
||||
off once you have gone quiet. So while you wait for a button press, answer any
|
||||
chat `wait` delivers (`console-chat.md`).
|
||||
|
||||
## 2. After the finish: the buttons
|
||||
|
||||
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 post it without `--wait` and `stop` at once.
|
||||
|
||||
Every other finish carries `"dashboard": true` and goes up with `post --wait`;
|
||||
keep waiting in the usual slices. There is no timeout after a finish: the
|
||||
buttons live exactly as long as you are listening, so a press an hour later
|
||||
works like a press a minute later.
|
||||
|
||||
| What arrives | What you do |
|
||||
| --- | --- |
|
||||
| An action `{ "i": "__dashboard", "type": "dashboard" }` | Run the `resume` it carries (`open --resume <sid> --no-open --workflow dashboard`; it re-runs the project scan and clears the page, the finish included), read the dashboard skill (`skillFile`, or `~/.agents/skills/plan2code/SKILL.md`), then post its `menu` with `--wait` and carry on as the dashboard from its "Coming back from another skill", in this same conversation. |
|
||||
| An action `__review` or `__done` | As `building-review.md` says (quick task only). |
|
||||
| An action `{ "i": "__commit", "type": "commit" }` | Commit it now: run the `resume` it carries (`open --resume <sid> --no-open --workflow git`; no `finish`, no `stop`; the resume gives Git a clean page, the finish included, as a dashboard launch does), then open the Git skill (`skillFile`, or `~/.agents/skills/plan2code-git/SKILL.md`) with your file-read tool and follow it, starting with the commit flow over the board (the person pressed Commit it now), then the board with Push lit. Leave the commit command you printed in the finish where it is for the terminal. |
|
||||
| `wait` exit `20` | The server is gone. `open --resume <sid> --workflow <yours>` (it gets a new link: give it to them; the browser opens it), then keep waiting: their Ask messages and the dashboard button still need you. Give up only when the resume itself fails. |
|
||||
| The session ends without a press (the terminal closes, the conversation ends) | The server sweeps itself once its idle window passes, and the page swaps the buttons for the matching commands — nothing pressable dies silently. A press that lands in the meantime is kept on disk (`pendingResult`) for a resumed session. |
|
||||
|
||||
## 3. Stop the server
|
||||
|
||||
```
|
||||
node "<CONSOLE>" stop --session <sid>
|
||||
```
|
||||
|
||||
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 "<CONSOLE>" status` lists sessions for this project, including any whose
|
||||
answers were submitted but never picked up.
|
||||
@@ -0,0 +1,65 @@
|
||||
# Launches: the Dashboard on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Read when you are the
|
||||
dashboard. The dashboard skill's own prompt (`plan2code/SKILL.md`) has the
|
||||
menu judgment and the launch steps; this is what the page does around them.
|
||||
|
||||
## A launch
|
||||
|
||||
```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.",
|
||||
"resume": "node \"…/console.mjs\" open --resume <sid> --no-open --workflow implement --spec specs/lunch-vote",
|
||||
"skillFile": "…/plan2code-3-implement/SKILL.md" }
|
||||
```
|
||||
|
||||
`spec` is the picker's selected spec dir, present only when the launched skill
|
||||
takes a spec and the person picked one. `resume` is the one command to run
|
||||
first, before reading anything: it reuses the live server and turns the page
|
||||
from the menu into the skill's starting screen while you read. `skillFile` is
|
||||
the skill to read next (absent outside an install: then
|
||||
`~/.agents/skills/<skill>/SKILL.md`).
|
||||
|
||||
**A session handed to you is resumed, never re-opened.** 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. `--title` and `--spec` are honored on
|
||||
resume. A resume to or from `dashboard`, or into `git` from any skill, clears
|
||||
the page: the last skill's questions, sections, docs, headline and finish are
|
||||
dropped, so the new skill starts blank and posts its own. A skill run inline
|
||||
from another (a quick task's review) never resumes, and keeps the page it was
|
||||
handed.
|
||||
|
||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
||||
> own file-read tool and follow it from the top.** Every Plan2Code skill below
|
||||
> the dashboard ships `disable-model-invocation: true` on purpose, and calling
|
||||
> one through a skill-invocation tool errors out and strands the hand-off.
|
||||
|
||||
Its Interface step is already answered by having been launched. You have read
|
||||
`console.md` already: do not read it again; read only the notes or building
|
||||
files its Interface names.
|
||||
|
||||
From the click until the resume lands, the page shows a getting-ready screen;
|
||||
from the resume until the skill's first payload, its starting screen. Resume
|
||||
first, and post before anything slow.
|
||||
|
||||
## What the page already knows
|
||||
|
||||
`state.scan` is `{ hasAgents, isGit, pending, specs: [{ dir, name, state, detail, touched }] }`,
|
||||
a snapshot of the last `open` (a spec created mid-session appears the next time
|
||||
the session resumes as a dashboard). `pending` is how many files a commit would
|
||||
take (`null` when git cannot say): the Git card never greys out, shows the count
|
||||
when there is one, and outside a repository says Git can start one. The picker
|
||||
greys the cards that do not fit the selected spec — or hides them, while the
|
||||
**Hide unavailable workflows** switch under it is on (the default).
|
||||
|
||||
The `menu` you post (`note`, `recommend`, `details`) describes the initially
|
||||
selected spec; leave any field out and the page falls back to that spec's own
|
||||
next step, and it derives both again from the scan when the person switches
|
||||
specs or starts fresh. Post it with `--wait`; waiting on the menu is the
|
||||
person's turn by itself.
|
||||
|
||||
A `__stop` before a pick ends the session the usual way: `finish` (paused
|
||||
headline, `"command": "/plan2code"`) then `stop` (`console-stop.md`).
|
||||
@@ -0,0 +1,56 @@
|
||||
# The Session Meter on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Your workflow notes give the
|
||||
exact `run` to post; read this only if one is refused.
|
||||
|
||||
### 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, Finalize, Git and Changelog 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`,
|
||||
`git`, `changelog`, `git-commits` and `git-conflict` (Git's own, see
|
||||
`notes/git.md`).
|
||||
An unknown event is exit `3`. Post only the events your notes name: a skill
|
||||
that scores when its session opens (the list above this one) already has its
|
||||
points, and a `run` for it scores the same work twice.
|
||||
- `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. It must be non-empty.
|
||||
- `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.
|
||||
- `commits` goes only with `git-commits`: how many commits Git just made, a
|
||||
whole number from 1 to 999. A Git run scores one point per 2 commits,
|
||||
rounded down; on any other event it is exit `3`.
|
||||
- One `run` per post. Which events a workflow reports is in its own notes
|
||||
(`notes/pathfinder.md`, `notes/git.md`; `building.md` for Implement and for
|
||||
the review run on the page after a build).
|
||||
|
||||
`run` never reaches the page state: `post` (and `open --file`) lift it into the
|
||||
session's ledger.
|
||||
|
||||
---
|
||||
@@ -0,0 +1,97 @@
|
||||
# Stop Requests on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Read when a send carries
|
||||
`__stop` or `__dashboard`, or your workflow notes say to post a `stopWarning`.
|
||||
|
||||
## 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 every `__` action it is
|
||||
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. Settle only the final cards (`"settle": [...]`).
|
||||
2. **Save your place** the way the workflow does when a session ends.
|
||||
3. **Post `finish`** (`console-finish.md`) 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, without
|
||||
`--wait`. 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.",
|
||||
"resume": "node \"…/console.mjs\" open --resume <sid> --no-open --workflow dashboard" }
|
||||
```
|
||||
|
||||
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. **Go home:** run the `resume` the send carried (it turns the page back into
|
||||
the dashboard and drops this skill's page), read the dashboard skill
|
||||
(`skillFile`, or `~/.agents/skills/plan2code/SKILL.md`), then post its
|
||||
`menu` with `--wait` and carry on as the dashboard from its "Coming back
|
||||
from another skill", 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.
|
||||
|
||||
## Picking up a paused session
|
||||
|
||||
`open --resume <sid>` (or `open --session <sid>`) 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.
|
||||
@@ -0,0 +1,85 @@
|
||||
# Standing Instructions: Helpers on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Read when a `Subagents:` block
|
||||
arrives, or when your workflow notes say to report helpers.
|
||||
|
||||
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, on until switched off, 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-subagents.md); 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. Anything else is exit `3`, and
|
||||
the house rules on completion markers and metric-like words cover `title`,
|
||||
`ask` and `result`.
|
||||
- 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. At most one `alone` entry.
|
||||
- **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.
|
||||
- Before any `finish`, mark every reported helper `done` or `failed`
|
||||
(`console-finish.md`).
|
||||
@@ -0,0 +1,20 @@
|
||||
# When Things Go Wrong on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Read when something goes 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 <sid>`, 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 (`console-finish.md`). 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 <sid>` clears a paused `finish` and the questions left open at it; re-ask what you still need (`console-stop.md` → Picking up a paused session). |
|
||||
| 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. |
|
||||
| A patch is refused (exit `3`) | stderr names every problem; nothing was written. Fix them and post again. A `version` refusal means the payload is stale: drop `version` and let it move by itself. |
|
||||
| A doc block's `file` is refused | It must be a file inside the project, under 512 KB; `select` only takes `tasks`. |
|
||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||
@@ -0,0 +1,80 @@
|
||||
# The Workspace on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Read when `open` lists more
|
||||
than one folder, a `Workspace:` line arrives, or someone writes `@name`.
|
||||
|
||||
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 (`console-chat.md` → 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 <path>` there. Your harness asking the person
|
||||
for permission is not a failure; report only a read that failed after it.
|
||||
|
||||
A `folderIssue` needs non-empty `name` and `reason` strings, and `hint`, when
|
||||
present, is one too; anything else is exit `3`. It goes to the session's
|
||||
ledger, never into the page state.
|
||||
+251
-1292
File diff suppressed because it is too large.
Load diff
+352
-36
@@ -64,6 +64,7 @@ import {
|
||||
readChat,
|
||||
readJson,
|
||||
readLedger,
|
||||
readPrHosts,
|
||||
readSubagentCursor,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
@@ -86,6 +87,7 @@ import {
|
||||
terminalLine,
|
||||
updateState,
|
||||
UPLOAD_MAX_AGE_MS,
|
||||
resolveDocFiles,
|
||||
validate,
|
||||
validateChat,
|
||||
workspaceForAgent,
|
||||
@@ -94,7 +96,8 @@ import {
|
||||
writeSubagentCursor,
|
||||
writeWorkspaceCursor,
|
||||
} from "./lib.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { snapshot } from "./git-repo.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_COMMITS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { blockFor, offered } from "./public/subagents.js";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
|
||||
@@ -165,9 +168,19 @@ async function cmdOpen() {
|
||||
// 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");
|
||||
// belonged to the old questions. Git counts as a launch from anywhere:
|
||||
// Commit it now on a finished screen and Changelog's "Commit this now?"
|
||||
// both stand in for its dashboard card, and a finish left
|
||||
// behind would keep the page on the old ending above the new questions
|
||||
// (or the new board). A hop also drops the last run's state.git, since
|
||||
// switchWorkflow() starts from a blank state.
|
||||
// A skill run inline from another (a quick task's review) never switches
|
||||
// through here, so it keeps the page.
|
||||
const hop =
|
||||
switching &&
|
||||
(args.workflow === "dashboard" ||
|
||||
state.workflow === "dashboard" ||
|
||||
args.workflow === "git");
|
||||
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 --
|
||||
@@ -180,6 +193,15 @@ async function cmdOpen() {
|
||||
// --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;
|
||||
// A new agent picking the session up: its own working turn, timed
|
||||
// from now, not the paused run's last status.
|
||||
s.agent = { status: "working", since: nowIso() };
|
||||
// The old run's warning about what a stop would lose is about its
|
||||
// unsaved work; the new run posts its own when it has some.
|
||||
delete s.stopWarning;
|
||||
// So is its count: the open questions it counted are dropped below,
|
||||
// and the page falls back to its own tally until the new run posts.
|
||||
s.headline = { stage: "", cleared: 0, total: 0, confidence: "", note: "" };
|
||||
// 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
|
||||
@@ -229,15 +251,26 @@ async function cmdOpen() {
|
||||
// now, before anything is written, and appended once the launch is.
|
||||
let openRun;
|
||||
let openIssue;
|
||||
let openReread;
|
||||
let patch = null;
|
||||
if (args.file) {
|
||||
patch = readJson(path.resolve(args.file));
|
||||
if (!patch) die(`could not read --file ${args.file} as JSON`, 2);
|
||||
patch = readPatch(args.file);
|
||||
if (!patch) die(`could not read --file ${args.file} as one JSON object`, 2);
|
||||
({ run: openRun, folderIssue: openIssue } = patch);
|
||||
delete patch.run;
|
||||
delete patch.folderIssue;
|
||||
openReread = liftReread(patch, args.workflow || state.workflow);
|
||||
}
|
||||
const base = reshape;
|
||||
if (patch) {
|
||||
// Against the page as this open leaves it (a hop starts blank), so a
|
||||
// refresh never re-reads the last skill's files into the new page.
|
||||
try {
|
||||
patch = resolveDocFiles(patch, base(structuredClone(state)), worktree);
|
||||
} catch (e) {
|
||||
die(e.message, 3);
|
||||
}
|
||||
}
|
||||
const settle = (s) => {
|
||||
s = base(s);
|
||||
// On every open, so a resume from another worktree refreshes both.
|
||||
@@ -268,7 +301,13 @@ async function cmdOpen() {
|
||||
// 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);
|
||||
// A live pid gets a second, longer look before it is given up on, as `stop`
|
||||
// gives one: a server busy right after a post can miss the first, and a
|
||||
// second server for the same session strands the page on the first.
|
||||
const reusable =
|
||||
existing && pidAlive(existing.pid)
|
||||
? healthOk(existing).then((ok) => ok || healthOk(existing, 5000))
|
||||
: Promise.resolve(false);
|
||||
let boot = null;
|
||||
if (!existing) boot = await startServer(project, worktree, sid, dir);
|
||||
|
||||
@@ -279,6 +318,9 @@ async function cmdOpen() {
|
||||
// own top level: `project` is the common-dir key so linked worktrees share
|
||||
// sessions, but each shows the specs on its own disk.
|
||||
const scan = state.workflow === "dashboard" ? scanProject(worktree) : null;
|
||||
// The git board's data, the same way: the console's own read-only snapshot
|
||||
// (git-repo.mjs), taken before the lock so no git process runs under it.
|
||||
const gitSnap = state.workflow === "git" ? snapshot(worktree, { prHosts: readPrHosts() }) : null;
|
||||
|
||||
// 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
|
||||
@@ -289,6 +331,9 @@ async function cmdOpen() {
|
||||
written = updateState(dir, (fresh) => {
|
||||
const next = fresh ? reshape(fresh) : state;
|
||||
if (scan) next.scan = scan;
|
||||
// A launch or hop starts the board fresh; a plain resume (a server
|
||||
// restart) keeps the last word on whether a Refresh failed.
|
||||
if (gitSnap) next.git = launched ? gitBlock(gitSnap, openReread ?? { refreshFailed: false }) : gitBlock(gitSnap, openReread, fresh?.git);
|
||||
|
||||
// Clear a result the agent already collected, and ONLY that one.
|
||||
//
|
||||
@@ -556,6 +601,26 @@ async function awaitHandle(started) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// A patch from a file, or from stdin with `--file -`: a heredoc piped into
|
||||
// the command saves the agent writing a file first, one tool call a turn.
|
||||
// A file PowerShell wrote comes with a BOM (Out-File / Set-Content in 5.1) or
|
||||
// in UTF-16 (its `>`), and both are the documented Windows route, so both read.
|
||||
function readPatch(file) {
|
||||
try {
|
||||
const buf = fs.readFileSync(file === "-" ? 0 : path.resolve(file));
|
||||
let text;
|
||||
if (buf[0] === 0xff && buf[1] === 0xfe) text = buf.subarray(2).toString("utf16le");
|
||||
else if (buf[0] === 0xfe && buf[1] === 0xff) text = Buffer.from(buf.subarray(2)).swap16().toString("utf16le");
|
||||
else text = buf.toString("utf8");
|
||||
// A patch is one JSON object: an array, string or number would merge
|
||||
// into the state as junk keys ("0", "1"...) and still report ok.
|
||||
const patch = JSON.parse(text.replace(/^\uFEFF/, ""));
|
||||
return patch && typeof patch === "object" && !Array.isArray(patch) ? patch : null;
|
||||
} catch {
|
||||
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");
|
||||
@@ -566,23 +631,44 @@ function failValidation(problems) {
|
||||
|
||||
/* ----------------------------------------------------------------- post */
|
||||
|
||||
function cmdPost() {
|
||||
async function cmdPost() {
|
||||
// `post --wait <seconds>` is a post and then a wait in one command: one tool
|
||||
// call per turn instead of two. A rejected post never waits (exit 3).
|
||||
if (args.wait !== undefined && args.wait !== true && !Number.isFinite(Number.parseFloat(args.wait))) {
|
||||
die("post --wait takes the slice in seconds, as wait --seconds does", 2);
|
||||
}
|
||||
if (!postOnce()) return;
|
||||
if (args.wait === undefined) return;
|
||||
// A bare --wait takes the slice from --seconds, as wait does.
|
||||
args.seconds = args.wait === true ? args.seconds : args.wait;
|
||||
return cmdWait();
|
||||
}
|
||||
|
||||
function postOnce() {
|
||||
const dir = mustSession();
|
||||
const file = args.file;
|
||||
if (!file) die("post needs --file <path to a JSON patch>", 2);
|
||||
const patch = readJson(path.resolve(file));
|
||||
if (!patch) die(`could not read --file ${file} as JSON`, 2);
|
||||
let patch = readPatch(file);
|
||||
if (!patch) die(`could not read --file ${file} as one JSON object`, 2);
|
||||
|
||||
const statePath = path.join(dir, "state.json");
|
||||
const before = readJson(statePath);
|
||||
if (!before) die("that session has no state", 1);
|
||||
try {
|
||||
patch = resolveDocFiles(patch, before, before.worktree || repoRoots().worktree);
|
||||
} catch (e) {
|
||||
die(e.message, 3);
|
||||
}
|
||||
|
||||
// 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 reread = liftReread(patch, before.workflow);
|
||||
const ledgerLines = ledgerFromPost(dir, run, folderIssue, before.workflow);
|
||||
// Taken before the lock: git processes must not run while it is held.
|
||||
const snap = reread === undefined ? null : snapshot(before.worktree || repoRoots().worktree, { prHosts: readPrHosts() });
|
||||
|
||||
// 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
|
||||
@@ -604,6 +690,14 @@ function cmdPost() {
|
||||
refused = [e.message, 3];
|
||||
return null;
|
||||
}
|
||||
// The result card and the fresh board land in this one write.
|
||||
if (snap) {
|
||||
next.git = gitBlock(snap, reread, fresh.git);
|
||||
// The footer names the branch too: after a switch or a create it is
|
||||
// the new one, and mid-rebase the one being rebased.
|
||||
const onBranch = snap.head && (snap.head.branch || snap.head.rebasing);
|
||||
if (onBranch) next.branch = onBranch;
|
||||
}
|
||||
problems = validate(next);
|
||||
if (!problems.length && patch.chat) problems = validateChat(next, readChat(dir));
|
||||
return problems.length ? null : next;
|
||||
@@ -625,9 +719,9 @@ function cmdPost() {
|
||||
}
|
||||
appendEvent(dir, { type: "post", items: (patch.items || []).length });
|
||||
|
||||
const open = next.items.filter((i) => isOpen(i) && i.required !== false).length;
|
||||
const open = next.items.filter((i) => isOpen(i) && i.required !== false && i.kind !== "notice").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));
|
||||
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === path.basename(dir));
|
||||
print({
|
||||
ok: true,
|
||||
items: next.items.length,
|
||||
@@ -636,6 +730,40 @@ function cmdPost() {
|
||||
...unansweredNote(dir, next),
|
||||
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* A patch's `reread`, the agent's "re-read the repo" signal on the git board
|
||||
* (FR-10), lifted out of the patch, or exit 3 when it is malformed or not on a
|
||||
* git session. state.git itself is the console's own: a patch never carries it.
|
||||
*/
|
||||
function liftReread(patch, workflow) {
|
||||
if (Object.hasOwn(patch, "git")) die("state.git is the console's own: post reread instead", 3);
|
||||
const { reread } = patch;
|
||||
delete patch.reread;
|
||||
if (reread === undefined) return undefined;
|
||||
const flagOnly =
|
||||
reread && typeof reread === "object" && !Array.isArray(reread) && Object.keys(reread).length === 1 && typeof reread.refreshFailed === "boolean";
|
||||
if (reread !== true && !flagOnly) die("reread must be true or { refreshFailed: true|false }", 3);
|
||||
if (workflow !== "git") die("reread only goes with the git workflow", 3);
|
||||
return reread;
|
||||
}
|
||||
|
||||
/**
|
||||
* The new state.git from a snapshot. The agent's refreshFailed wins; without
|
||||
* one, a newer FETCH_HEAD means a refresh worked, and anything else keeps the
|
||||
* last word on it.
|
||||
*/
|
||||
function gitBlock(snap, reread, previous) {
|
||||
let refreshFailed;
|
||||
if (reread && typeof reread === "object") refreshFailed = reread.refreshFailed;
|
||||
else if (snap.lastFetch && (!previous?.lastFetch || Date.parse(snap.lastFetch) > Date.parse(previous.lastFetch))) refreshFailed = false;
|
||||
else refreshFailed = Boolean(previous?.refreshFailed);
|
||||
// A failed fetch still touches FETCH_HEAD, so its time is not a refresh:
|
||||
// the board keeps saying when the last one that worked was.
|
||||
if (refreshFailed === true && reread && typeof reread === "object") return { ...snap, lastFetch: previous?.lastFetch ?? null, refreshFailed };
|
||||
return { ...snap, refreshFailed };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -656,7 +784,19 @@ function ledgerFromPost(dir, run, issue, workflow) {
|
||||
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 (run.commits !== undefined) {
|
||||
if (event !== "git-commits") die("run: commits only goes with git-commits", 3);
|
||||
const ok = Number.isInteger(run.commits) && run.commits >= 1 && run.commits <= MAX_COMMITS;
|
||||
if (!ok) die(`run: commits must be a whole number from 1 to ${MAX_COMMITS}`, 3);
|
||||
}
|
||||
lines.push({
|
||||
kind: "run",
|
||||
id: `${launch}:${run.id}`,
|
||||
event,
|
||||
workflow,
|
||||
...(run.tasks !== undefined ? { tasks: run.tasks } : {}),
|
||||
...(run.commits !== undefined ? { commits: run.commits } : {}),
|
||||
});
|
||||
}
|
||||
if (issue !== undefined) {
|
||||
const text = (v) => typeof v === "string" && v.trim() !== "";
|
||||
@@ -690,7 +830,7 @@ async function cmdWait() {
|
||||
}
|
||||
const seconds = Math.max(5, given === undefined ? 240 : asked);
|
||||
const sid = path.basename(dir);
|
||||
const project = projectRoot();
|
||||
const project = sessionProject(dir);
|
||||
const resultPath = path.join(dir, "result.json");
|
||||
const chatPath = path.join(dir, CHAT_FILE);
|
||||
const deadline = Date.now() + seconds * 1000;
|
||||
@@ -703,6 +843,7 @@ async function cmdWait() {
|
||||
if (existing && !existing.consumedAt) return consume(dir, resultPath, existing, liveUrl(), pendingChat());
|
||||
const earlyChat = pendingChat();
|
||||
if (earlyChat.length) return deliverChat(dir, sid, earlyChat, liveUrl());
|
||||
markWaiting(dir);
|
||||
|
||||
// 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
|
||||
@@ -713,6 +854,17 @@ async function cmdWait() {
|
||||
// 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;
|
||||
// The check in flight, if any. Aborted on every way out, so a fetch left
|
||||
// running never holds the process (and the agent) past the print.
|
||||
let health = null;
|
||||
const healthStop = new AbortController();
|
||||
try {
|
||||
return await pollSlice();
|
||||
} finally {
|
||||
healthStop.abort();
|
||||
}
|
||||
|
||||
async function pollSlice() {
|
||||
// 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;
|
||||
@@ -735,7 +887,10 @@ async function cmdWait() {
|
||||
if (entries.length) return deliverChat(dir, sid, entries, liveUrl());
|
||||
}
|
||||
|
||||
if (Date.now() - healthAt > 5000) {
|
||||
// The health check runs beside the polling, never in its way: awaited
|
||||
// inline, a slow /health (a busy server, just after a send) held a
|
||||
// finished send back for up to the whole fetch timeout.
|
||||
if (!health && Date.now() - healthAt > 5000) {
|
||||
healthAt = Date.now();
|
||||
const handle = listHandles(project).find((h) => h.sid === sid);
|
||||
if (!handle || !pidAlive(handle.pid)) {
|
||||
@@ -743,18 +898,25 @@ async function cmdWait() {
|
||||
process.exitCode = 20;
|
||||
return;
|
||||
}
|
||||
if (await healthOk(handle, 4000)) healthMisses = 0;
|
||||
const check = { done: false, ok: false };
|
||||
health = check;
|
||||
healthOk(handle, 4000, healthStop.signal).then((ok) => Object.assign(check, { done: true, ok }));
|
||||
}
|
||||
if (health && health.done) {
|
||||
const { ok } = health;
|
||||
health = null;
|
||||
if (ok) 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);
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
|
||||
const state = readJson(path.join(dir, "state.json")) || {};
|
||||
const items = (state.items || []).filter((i) => i.required !== false);
|
||||
const items = (state.items || []).filter((i) => i.required !== false && i.kind !== "notice");
|
||||
const answered = items.filter((i) => !isOpen(i)).length;
|
||||
const draft = readJson(path.join(dir, "draft.json"), {});
|
||||
const staged = Object.keys(draft.staged || {}).length;
|
||||
@@ -770,13 +932,13 @@ async function cmdWait() {
|
||||
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.
|
||||
@@ -791,7 +953,7 @@ function serverGone(sid) {
|
||||
return {
|
||||
status: "server-gone",
|
||||
sid,
|
||||
message: "The console server is not running. Start it again with `open --resume <sid> --no-open`, then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
|
||||
message: "The console server is not running. Start it again with `open --resume <sid> --workflow <yours>` (it gets a new link: give it to the person; without --no-open the browser opens it), then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -895,7 +1057,7 @@ function advanceCursor(dir, entries) {
|
||||
async function cmdChat() {
|
||||
const dir = mustSession();
|
||||
const sid = path.basename(dir);
|
||||
const handle = listHandles(projectRoot()).find((h) => h.sid === sid);
|
||||
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === sid);
|
||||
if (!handle || !pidAlive(handle.pid) || !(await healthOk(handle))) {
|
||||
print(serverGone(sid));
|
||||
process.exitCode = 20;
|
||||
@@ -940,10 +1102,12 @@ function consume(dir, resultPath, result, url, 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);
|
||||
const hop = hopFor(path.basename(dir), result);
|
||||
print({ ...out, ...hop, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
try {
|
||||
writeJsonAtomic(resultPath, collected);
|
||||
} catch {}
|
||||
markWorking(dir, result);
|
||||
appendEvent(dir, { type: "consume", kind: result.type });
|
||||
ledgerAnswers(dir, result);
|
||||
advanceCursor(dir, chat);
|
||||
@@ -952,6 +1116,70 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||
}
|
||||
|
||||
// A collected send is the agent's turn: the page says so at once, without the
|
||||
// agent spending a whole post on "working" before it starts. The activity
|
||||
// line belonged to the last stretch of work, so it goes; quietMinutes stays,
|
||||
// since the page only counts it while working. Never fatal.
|
||||
// The send is no longer waiting to be picked up either, so the phase the
|
||||
// server set on it goes back to collecting (status and post report it).
|
||||
function markWorking(dir, result) {
|
||||
if (!result) return;
|
||||
try {
|
||||
updateState(dir, (s) => {
|
||||
if (!s) return null;
|
||||
if (result.type !== "submit") return s.phase === "submitted" ? { ...s, phase: "collecting" } : null;
|
||||
// The cards this send carried, so `settle: true` settles what the agent
|
||||
// was handed and never a later send still waiting to be collected.
|
||||
const ids = [...new Set((result.actions || []).filter((a) => a && (a.type === "answer" || a.type === "skip") && typeof a.i === "string" && !a.i.startsWith("__")).map((a) => a.i))];
|
||||
return applyPatch({ ...s, phase: "collecting", collected: { at: result.consumedAt || nowIso(), ids } }, { agent: { status: "working", activity: null } });
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Waiting on an open question (or a finished screen's buttons) is the
|
||||
// person's turn, whatever the last post said: an agent that replied to a note
|
||||
// and went back to `wait` without restating its status left the page on
|
||||
// "working" with nobody working. With nothing open it stays as it is: an
|
||||
// agent waiting out its research subagents is still working. Only a change
|
||||
// is written.
|
||||
function markWaiting(dir) {
|
||||
try {
|
||||
updateState(dir, (s) => {
|
||||
if (!s || !s.agent || s.agent.status !== "working") return null;
|
||||
// The dashboard's menu and the git board are the page's own, and theirs
|
||||
// to click whenever the agent is waiting.
|
||||
const theirTurn =
|
||||
s.finish || s.workflow === "dashboard" || s.workflow === "git" || (s.items || []).some((i) => isOpen(i) && i.kind !== "notice");
|
||||
return theirTurn ? applyPatch(s, { agent: { status: "waiting" } }) : null;
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The session hops a send can ask for, each with the one command that makes
|
||||
// it and the skill file to follow after, so the agent copies instead of
|
||||
// assembling `open --resume …` from the action's fields.
|
||||
const HOP_ACTIONS = {
|
||||
launch: (a) => ({ workflow: a.workflow, spec: a.spec, skill: a.skill }),
|
||||
dashboard: () => ({ workflow: "dashboard", skill: "plan2code" }),
|
||||
commit: () => ({ workflow: "git", skill: "plan2code-git" }),
|
||||
};
|
||||
|
||||
function hopFor(sid, result) {
|
||||
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
|
||||
const action = actions.find((a) => a && Object.hasOwn(HOP_ACTIONS, a.type) && typeof a.i === "string" && a.i.startsWith("__"));
|
||||
if (!action) return {};
|
||||
const { workflow, spec, skill } = HOP_ACTIONS[action.type](action);
|
||||
if (typeof workflow !== "string" || !/^[a-z-]+$/.test(workflow)) return {};
|
||||
const quote = (v) => (/[\s"]/.test(v) ? `"${v.replace(/"/g, '\\"')}"` : v);
|
||||
const specArg = typeof spec === "string" && spec ? ` --spec ${quote(spec)}` : "";
|
||||
const out = { resume: `node "${path.join(HERE, "console.mjs")}" open --resume ${sid} --no-open --workflow ${workflow}${specArg}` };
|
||||
if (typeof skill === "string" && /^[a-z0-9-]+$/.test(skill)) {
|
||||
const file = path.resolve(HERE, "..", "..", "..", skill, "SKILL.md");
|
||||
if (fs.existsSync(file)) out.skillFile = file;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -984,7 +1212,20 @@ function cmdKeep() {
|
||||
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);
|
||||
// Compared as real paths: Windows hands the same folder out both long
|
||||
// (C:\Users\Justin.Parker) and 8.3 (C:\Users\JUSTIN~1.PAR), and the reply's
|
||||
// path need not be spelled the way this session's directory is.
|
||||
// A path that does not exist (yet) resolves through its nearest real parent,
|
||||
// so a missing upload still reads as missing, not as somewhere else.
|
||||
const real = (p) => {
|
||||
try {
|
||||
return fs.realpathSync.native(p);
|
||||
} catch {
|
||||
const parent = path.dirname(path.resolve(p));
|
||||
return parent === path.resolve(p) ? path.resolve(p) : path.join(real(parent), path.basename(p));
|
||||
}
|
||||
};
|
||||
if (!inside(real(path.join(dir, "uploads")), real(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))) {
|
||||
@@ -992,7 +1233,23 @@ function cmdKeep() {
|
||||
}
|
||||
if (!fs.existsSync(upload) || !fs.statSync(upload).isFile()) die("no such upload", 3);
|
||||
|
||||
const file = attachmentName({ upload, name: args.name });
|
||||
// The file the link is written for has to be in the project too, or the
|
||||
// relative link would point out of it.
|
||||
if (typeof args.from === "string" && !inside(project, path.resolve(project, args.from))) {
|
||||
die("--from is outside the project", 3);
|
||||
}
|
||||
|
||||
// One upload, one copy: kept again under another name, the copy it already
|
||||
// has (named for the same upload id) is the one reused.
|
||||
// Named from the real path: an 8.3 spelling (7CF881~1.JPG) would name the
|
||||
// copy after the short form and miss the copy this upload already has.
|
||||
const named = attachmentName({ upload: real(upload), name: args.name });
|
||||
const suffix = named.slice(named.lastIndexOf("-"));
|
||||
let existing = null;
|
||||
try {
|
||||
existing = fs.readdirSync(attachments).find((f) => f.endsWith(suffix));
|
||||
} catch {}
|
||||
const file = existing || named;
|
||||
const target = path.join(attachments, file);
|
||||
fs.mkdirSync(attachments, { recursive: true });
|
||||
let reused = false;
|
||||
@@ -1047,6 +1304,8 @@ function cmdForget() {
|
||||
/* ----------------------------------------------------------------- help */
|
||||
|
||||
function cmdHelp() {
|
||||
const topic = args._[0];
|
||||
if (topic !== undefined) return helpTopic(String(topic));
|
||||
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.
|
||||
|
||||
@@ -1064,15 +1323,21 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
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 <sid> --file <patch.json>
|
||||
post --session <sid> --file <patch.json | -> [--wait <N>]
|
||||
Merge a patch into the session. Prints terminalLine while the
|
||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||
server is live. Exit 3 = rejected; stderr says why. --wait <N>
|
||||
then waits up to N seconds in the same command (two JSON lines;
|
||||
the exit code is the wait's). The patch may carry settle: true
|
||||
(or a list of item ids) to mark the latest send's cards answered
|
||||
with what was sent; doc blocks may carry file: "<path>" (and
|
||||
select: "tasks"), read from the project, and a doc refresh: true
|
||||
re-reads them. A doc's version moves up by itself. 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).
|
||||
(help subagents).
|
||||
wait --session <sid> [--seconds <N>]
|
||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||
@@ -1085,7 +1350,11 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
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.
|
||||
setting change alone never ends a slice either. A hop
|
||||
(__launch, __dashboard, __commit) carries resume, the exact
|
||||
open --resume command, and skillFile when installed. Collecting
|
||||
a send sets the page to working; a wait with a question open
|
||||
hands the turn back.
|
||||
chat --session <sid>
|
||||
Collect Quick questions, workspace changes and a Subagents
|
||||
setting change now, never waiting, never touching card sends.
|
||||
@@ -1102,23 +1371,59 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
folder (Finalize, after archiving it). Prints { ok, spec, forgot };
|
||||
forgot is false when nothing was saved. Exit 2 = bad usage.
|
||||
status [--session <sid>] [--all]
|
||||
One session, or every session belonging to this project.
|
||||
One session, or (--all) every session on this machine, every project.
|
||||
stop --session <sid> | --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 · git-commit · changelog
|
||||
finalize · handoff · git · changelog
|
||||
|
||||
A session handed to you by the dashboard (a --session id): resume it with
|
||||
"open --resume <sid> --no-open --workflow <yours> --title <t>" -- never a
|
||||
"open --resume <sid> --no-open --workflow <yours>" (the resume it carries) -- 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.
|
||||
The contract is console.md beside this file, read once; the rest is
|
||||
read when its moment comes. help <topic> prints one; help topics lists
|
||||
them. Build sessions (implement, implement-review, quick-task) also read
|
||||
building.md.
|
||||
`);
|
||||
}
|
||||
|
||||
// The contract's topic files, by the name console.md's index gives them.
|
||||
// Printing one saves an agent the path hunt: it already runs this CLI.
|
||||
const HELP_TOPICS = {
|
||||
console: "console.md",
|
||||
building: "building.md",
|
||||
"building-review": "building-review.md",
|
||||
finish: "console-finish.md",
|
||||
stop: "console-stop.md",
|
||||
attachments: "console-attachments.md",
|
||||
chat: "console-chat.md",
|
||||
workspace: "console-workspace.md",
|
||||
subagents: "console-subagents.md",
|
||||
launches: "console-launches.md",
|
||||
dashboard: "console-launches.md",
|
||||
meter: "console-meter.md",
|
||||
trouble: "console-trouble.md",
|
||||
};
|
||||
for (const f of fs.existsSync(path.join(HERE, "notes")) ? fs.readdirSync(path.join(HERE, "notes")) : []) {
|
||||
if (f.endsWith(".md")) HELP_TOPICS[f.slice(0, -3)] ??= `notes/${f}`;
|
||||
}
|
||||
HELP_TOPICS["init-update"] ??= HELP_TOPICS.init;
|
||||
HELP_TOPICS["implement-review"] ??= HELP_TOPICS.implement;
|
||||
|
||||
function helpTopic(topic) {
|
||||
const names = Object.keys(HELP_TOPICS).sort();
|
||||
if (topic === "topics") {
|
||||
print({ topics: Object.fromEntries(names.map((n) => [n, HELP_TOPICS[n]])) });
|
||||
return;
|
||||
}
|
||||
const file = Object.hasOwn(HELP_TOPICS, topic) ? HELP_TOPICS[topic] : null;
|
||||
if (!file) die(`no help topic "${topic}". Topics: ${names.join(", ")}`, 2);
|
||||
process.stdout.write(fs.readFileSync(path.join(HERE, file), "utf8"));
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- status */
|
||||
|
||||
async function cmdStatus() {
|
||||
@@ -1126,7 +1431,7 @@ async function cmdStatus() {
|
||||
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 handle = listHandles(sessionProject(dir)).find((h) => h.sid === path.basename(dir));
|
||||
const result = readJson(path.join(dir, "result.json"));
|
||||
return print({
|
||||
sid: state.sid,
|
||||
@@ -1176,7 +1481,10 @@ async function cmdStatus() {
|
||||
/* ----------------------------------------------------------------- stop */
|
||||
|
||||
async function cmdStop() {
|
||||
const project = projectRoot();
|
||||
// --all is this folder's sessions; one named session is found wherever
|
||||
// the command runs from.
|
||||
const named = !args.all && (args.session || args.sid) ? sessionDir(path.basename(args.session || args.sid)) : null;
|
||||
const project = named && fs.existsSync(named) ? sessionProject(named) : projectRoot();
|
||||
const handles = listHandles(project);
|
||||
const targets = args.all
|
||||
? handles
|
||||
@@ -1224,6 +1532,14 @@ function mustSession() {
|
||||
return dir;
|
||||
}
|
||||
|
||||
// The project a session belongs to, from its own state: a command run from
|
||||
// another folder (an agent whose shell moved) still finds the session's
|
||||
// server, rather than reporting it gone and starting a second one.
|
||||
function sessionProject(dir) {
|
||||
const state = readJson(path.join(dir, "state.json"));
|
||||
return (state && typeof state.project === "string" && state.project) || projectRoot();
|
||||
}
|
||||
|
||||
function tail(file, lines) {
|
||||
try {
|
||||
return fs.readFileSync(file, "utf8").split("\n").slice(-lines).join("\n");
|
||||
@@ -1339,7 +1655,7 @@ if (Number.isFinite(nodeMajor) && nodeMajor < 18) {
|
||||
|
||||
if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
|
||||
process.stderr.write(
|
||||
"console: usage: console.mjs <open|post|wait|chat|keep|status|stop|help> [--session <id>] [--file <patch.json>] [--seconds N]\n"
|
||||
"console: usage: console.mjs <open|post|wait|chat|keep|forget|status|stop|help> [--session <id>] [--file <patch.json>] [--seconds N]\n"
|
||||
);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,542 @@
|
||||
// git-repo.mjs: the one read-only reader of a git repository.
|
||||
//
|
||||
// Everything the git board and the dashboard need to know about a repository
|
||||
// comes from here: the worktree status, the branch table, the default branch,
|
||||
// a merge or rebase in progress, the remotes and their web addresses, when it
|
||||
// was last fetched, and the pull-request link. This module only reads: it
|
||||
// never changes the repository, the index or the working tree, and every git
|
||||
// call carries GIT_OPTIONAL_LOCKS=0 so a background look cannot take the index
|
||||
// lock out from under a commit. The console imports it directly; the git
|
||||
// skill's scripts reach it through common.mjs. Node built-ins only.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
import { prUrl } from "./public/pr-url.js";
|
||||
|
||||
export { prUrl };
|
||||
|
||||
/* ----------------------------------------------------------- running git */
|
||||
|
||||
/** Run git with an args array (never a shell). { ok, out, err }. */
|
||||
export function git(args, cwd, { raw = false, timeout } = {}) {
|
||||
try {
|
||||
const stdout = execFileSync("git", args, {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
windowsHide: true,
|
||||
timeout,
|
||||
// Without this, git status refreshes the index on disk: a write.
|
||||
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
|
||||
});
|
||||
return { ok: true, out: raw ? stdout : stdout.trim(), err: "" };
|
||||
} catch (e) {
|
||||
return { ok: false, out: "", err: String(e?.stderr || e?.message || "").trim() };
|
||||
}
|
||||
}
|
||||
|
||||
// git switch and git switch -c arrived in 2.23 (August 2019).
|
||||
const FLOOR = [2, 23, 0];
|
||||
let floorResult = null;
|
||||
|
||||
/** Is git on PATH and at least 2.23? Checked once per process. */
|
||||
export function gitFloor() {
|
||||
if (floorResult) return floorResult;
|
||||
const res = git(["--version"]);
|
||||
const version = res.ok ? res.out.replace(/^git version\s+/, "") || null : null;
|
||||
const m = version && version.match(/^(\d+)\.(\d+)\.(\d+)/);
|
||||
if (!version) {
|
||||
floorResult = { ok: false, version: null, message: "git is not installed or not on PATH." };
|
||||
} else {
|
||||
const parts = m ? m.slice(1, 4).map(Number) : [0, 0, 0];
|
||||
const cmp = parts.map((n, i) => n - FLOOR[i]).find((d) => d !== 0) || 0;
|
||||
floorResult = m && cmp >= 0
|
||||
? { ok: true, version }
|
||||
: { ok: false, version, message: `The git board needs git 2.23 or newer (found ${version}). Update git, then try again.` };
|
||||
}
|
||||
return floorResult;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- worktree status */
|
||||
|
||||
// The fields before the path in each porcelain v2 entry kind.
|
||||
const PATH_AFTER = { 1: 8, 2: 9, u: 10 };
|
||||
|
||||
function pathField(record, fields) {
|
||||
let at = 0;
|
||||
for (let k = 0; k < fields; k++) {
|
||||
const next = record.indexOf(" ", at);
|
||||
if (next < 0) return "";
|
||||
at = next + 1;
|
||||
}
|
||||
return record.slice(at);
|
||||
}
|
||||
|
||||
const letter = (c) => (c === "." ? " " : c);
|
||||
|
||||
function fileState(x, y) {
|
||||
if (x === "A" || x === "?" || y === "A" || y === "?") return "new";
|
||||
if (x === "D" || y === "D") return "deleted";
|
||||
if (x === "R" || x === "C" || y === "R" || y === "C") return "renamed";
|
||||
return "modified";
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse `git status --porcelain=v2 -z --branch --untracked-files=normal`.
|
||||
* Untracked entries come back as files with index " " and worktree "?";
|
||||
* unmerged entries go only into `conflicted`. ahead/behind are null without
|
||||
* an upstream; hasCommits is false for "(initial)" or without branch headers.
|
||||
*/
|
||||
export function parseStatusV2(text) {
|
||||
const result = { oid: null, hasCommits: false, branch: null, upstream: null, ahead: null, behind: null, files: [], conflicted: [] };
|
||||
const fields = String(text || "").split("\0");
|
||||
for (let i = 0; i < fields.length; i++) {
|
||||
const rec = fields[i];
|
||||
if (!rec) continue;
|
||||
if (rec.startsWith("# ")) {
|
||||
const [key, ...rest] = rec.slice(2).split(" ");
|
||||
const value = rest.join(" ");
|
||||
if (key === "branch.oid") {
|
||||
result.oid = value === "(initial)" ? null : value;
|
||||
result.hasCommits = value !== "(initial)";
|
||||
} else if (key === "branch.head") result.branch = value === "(detached)" ? null : value;
|
||||
else if (key === "branch.upstream") result.upstream = value;
|
||||
else if (key === "branch.ab") {
|
||||
const m = value.match(/^\+(\d+) -(\d+)$/);
|
||||
if (m) [result.ahead, result.behind] = [Number(m[1]), Number(m[2])];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const kind = rec[0];
|
||||
if (kind === "?") {
|
||||
result.files.push({ path: rec.slice(2), index: " ", worktree: "?", state: "new" });
|
||||
continue;
|
||||
}
|
||||
if (!(kind in PATH_AFTER)) continue; // "!" ignored, anything unknown too
|
||||
const x = letter(rec[2]);
|
||||
const y = letter(rec[3]);
|
||||
const p = pathField(rec, PATH_AFTER[kind]);
|
||||
if (kind === "u") {
|
||||
result.conflicted.push({ path: p, status: rec.slice(2, 4) });
|
||||
continue;
|
||||
}
|
||||
const entry = { path: p, index: x, worktree: y, state: fileState(x, y) };
|
||||
// A rename or copy carries its original path as one more NUL field.
|
||||
if (kind === "2") entry.origPath = fields[++i] || "";
|
||||
result.files.push(entry);
|
||||
}
|
||||
if (!result.upstream) [result.ahead, result.behind] = [null, null];
|
||||
return result;
|
||||
}
|
||||
|
||||
export const LARGE_BYTES = 5 * 1024 * 1024;
|
||||
// Every name is checked for secrets, but only the first STAT_LIMIT files are
|
||||
// sized, so a forgotten node_modules cannot make this slow.
|
||||
export const STAT_LIMIT = 2000;
|
||||
|
||||
// Basename tests for files that probably hold secrets.
|
||||
export const ENV_OK = new Set([".env.example", ".env.sample", ".env.template"]);
|
||||
export function isSensitive(file) {
|
||||
const b = file.split("/").pop();
|
||||
if (b === ".env" || (b.startsWith(".env.") && !ENV_OK.has(b))) return true;
|
||||
if (/\.(pem|key|p12|pfx|keystore|jks)$/.test(b)) return true;
|
||||
if (/^id_(rsa|dsa|ecdsa|ed25519)/.test(b)) return true;
|
||||
if (/^credentials.*\.json$/.test(b) || b.endsWith(".credentials")) return true;
|
||||
if (b === ".npmrc" || b === ".pypirc" || b === ".netrc") return true;
|
||||
return b.startsWith("secrets.");
|
||||
}
|
||||
|
||||
/** Sensitive paths and files over 5 MB among `names` (paths from `root`). */
|
||||
export function riskyFiles(root, names) {
|
||||
const sensitive = [];
|
||||
const large = [];
|
||||
let statted = 0;
|
||||
for (const p of new Set(names)) {
|
||||
if (isSensitive(p)) sensitive.push(p);
|
||||
if (statted >= STAT_LIMIT) continue;
|
||||
statted++;
|
||||
try {
|
||||
const st = fs.statSync(path.join(root, p));
|
||||
if (st.isFile() && st.size > LARGE_BYTES) large.push({ path: p, bytes: st.size });
|
||||
} catch {
|
||||
// a deletion, or a file that vanished
|
||||
}
|
||||
}
|
||||
return { sensitive: sensitive.sort(), large: large.sort((a, b) => a.path.localeCompare(b.path)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* What a commit would take, from a parseStatusV2() result. An untracked
|
||||
* folder is one row (its files counted with one ls-files) and counts once;
|
||||
* risky files inside it still count towards heldBack.
|
||||
*/
|
||||
export function readChanges(root, parsed) {
|
||||
const listed = [];
|
||||
const untrackedDirs = [];
|
||||
const inside = [];
|
||||
for (const f of parsed?.files || []) {
|
||||
if (f.worktree === "?" && f.path.endsWith("/")) {
|
||||
const res = git(["ls-files", "-o", "--exclude-standard", "-z", "--", f.path], root, { raw: true });
|
||||
const names = res.out.split("\0").filter(Boolean);
|
||||
untrackedDirs.push({ path: f.path, files: names.length });
|
||||
inside.push(...names);
|
||||
} else listed.push(f);
|
||||
}
|
||||
const { sensitive, large } = riskyFiles(root, [...listed.map((f) => f.path), ...inside]);
|
||||
const risky = new Set([...sensitive, ...large.map((l) => l.path)]);
|
||||
const files = listed.map((f) => ({ path: f.path, state: f.state, risky: risky.has(f.path), staged: f.index !== " " }));
|
||||
return { count: files.length + untrackedDirs.length, heldBack: risky.size, files, untrackedDirs, sensitive, large };
|
||||
}
|
||||
|
||||
/* ------------------------------------------- branches and repository state */
|
||||
|
||||
/** origin/HEAD, else local main, else master, else (no commits, on main or master) that branch. */
|
||||
export function defaultBranch(root, { branch, hasCommits } = {}) {
|
||||
const head = git(["symbolic-ref", "-q", "--short", "refs/remotes/origin/HEAD"], root);
|
||||
if (head.ok && head.out) return { name: head.out.replace(/^origin\//, ""), from: "origin/HEAD" };
|
||||
if (git(["show-ref", "--verify", "-q", "refs/heads/main"], root).ok) return { name: "main", from: "local-main" };
|
||||
if (git(["show-ref", "--verify", "-q", "refs/heads/master"], root).ok) return { name: "master", from: "local-master" };
|
||||
if (!hasCommits && (branch === "main" || branch === "master")) return { name: branch, from: "unborn" };
|
||||
return { name: null, from: null };
|
||||
}
|
||||
|
||||
const REF_FIELDS = [
|
||||
"%(refname)",
|
||||
"%(refname:short)",
|
||||
"%(upstream:short)",
|
||||
"%(upstream:track)",
|
||||
"%(upstream:remotename)",
|
||||
"%(symref)",
|
||||
"%(committerdate:iso-strict)",
|
||||
"%(authorname)",
|
||||
"%(contents:subject)",
|
||||
];
|
||||
|
||||
function track(text) {
|
||||
const ahead = text.match(/ahead (\d+)/);
|
||||
const behind = text.match(/behind (\d+)/);
|
||||
return { ahead: ahead ? Number(ahead[1]) : 0, behind: behind ? Number(behind[1]) : 0, gone: text === "[gone]" };
|
||||
}
|
||||
|
||||
// Subjects and authors go into the board verbatim: drop control bytes, or a
|
||||
// crafted subject (a \x01 is legal in a commit message) forges a table row.
|
||||
const cleanText = (s) => (s || "").replace(/[\x00-\x1f\x7f]/g, " ");
|
||||
|
||||
/** Every ref under refs/heads and refs/remotes, from one for-each-ref. */
|
||||
export function readRefs(root) {
|
||||
const res = git(["for-each-ref", `--format=${REF_FIELDS.join("%00")}%01`, "refs/heads", "refs/remotes"], root, { raw: true });
|
||||
return res.out
|
||||
.split("\x01")
|
||||
.map((r) => r.replace(/^\r?\n/, ""))
|
||||
.filter(Boolean)
|
||||
.map((r) => {
|
||||
const [ref, short, upstream, trackText, upstreamRemote, symref, at, author, subject] = r.split("\0");
|
||||
return { ref, short, upstream, trackText, upstreamRemote, symref, last: { subject: cleanText(subject), author: cleanText(author), at: at || "" } };
|
||||
});
|
||||
}
|
||||
|
||||
/** The default branch read off refs already fetched: origin/HEAD's target, else main, else master, else the unborn branch. */
|
||||
export function defaultBranchFromRefs(refs, { branch, hasCommits } = {}) {
|
||||
const head = refs.find((r) => r.ref === "refs/remotes/origin/HEAD");
|
||||
if (head && head.symref) {
|
||||
const m = head.symref.match(/^refs\/remotes\/[^/]+\/(.+)$/);
|
||||
if (m) return { name: m[1], from: "origin/HEAD" };
|
||||
}
|
||||
if (refs.some((r) => r.ref === "refs/heads/main")) return { name: "main", from: "local-main" };
|
||||
if (refs.some((r) => r.ref === "refs/heads/master")) return { name: "master", from: "local-master" };
|
||||
if (!hasCommits && (branch === "main" || branch === "master")) return { name: branch, from: "unborn" };
|
||||
return { name: null, from: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Every local branch, plus a row for each remote branch no local branch
|
||||
* tracks or shares a name with, from the refs readRefs() already fetched
|
||||
* (and one --merged read against the default branch).
|
||||
*/
|
||||
export function branchesFromRefs(refs, root, { current, defaultName } = {}) {
|
||||
const refnames = new Set(refs.map((r) => r.ref));
|
||||
const local = [];
|
||||
const remote = [];
|
||||
for (const r of refs) {
|
||||
if (r.ref.startsWith("refs/heads/")) {
|
||||
const name = r.ref.slice("refs/heads/".length);
|
||||
const t = r.upstream ? track(r.trackText || "") : { ahead: null, behind: null, gone: false };
|
||||
local.push({
|
||||
name,
|
||||
current: name === current,
|
||||
default: name === defaultName,
|
||||
remote: null,
|
||||
upstream: r.upstream || null,
|
||||
upstreamRemote: r.upstreamRemote || null,
|
||||
ahead: t.ahead,
|
||||
behind: t.behind,
|
||||
gone: t.gone,
|
||||
merged: false,
|
||||
last: r.last,
|
||||
});
|
||||
} else if (r.ref.startsWith("refs/remotes/") && !r.ref.endsWith("/HEAD")) {
|
||||
const rest = r.ref.slice("refs/remotes/".length);
|
||||
const slash = rest.indexOf("/");
|
||||
if (slash < 0) continue;
|
||||
remote.push({ short: r.short, remote: rest.slice(0, slash), name: rest.slice(slash + 1), last: r.last });
|
||||
}
|
||||
}
|
||||
const tracked = new Set(local.map((b) => b.upstream).filter(Boolean));
|
||||
const names = new Set(local.map((b) => b.name));
|
||||
const remoteOnly = remote
|
||||
.filter((r) => !tracked.has(r.short) && !tracked.has(`${r.remote}/${r.name}`) && !names.has(r.name))
|
||||
.map((r) => ({
|
||||
name: r.name,
|
||||
current: false,
|
||||
default: r.name === defaultName,
|
||||
remote: r.remote,
|
||||
upstream: null,
|
||||
upstreamRemote: null,
|
||||
ahead: null,
|
||||
behind: null,
|
||||
gone: false,
|
||||
merged: false,
|
||||
last: r.last,
|
||||
}));
|
||||
|
||||
if (defaultName) {
|
||||
const defaultRef = refnames.has(`refs/remotes/origin/${defaultName}`)
|
||||
? `refs/remotes/origin/${defaultName}`
|
||||
: refnames.has(`refs/heads/${defaultName}`)
|
||||
? `refs/heads/${defaultName}`
|
||||
: null;
|
||||
if (defaultRef) {
|
||||
const merged = new Set(
|
||||
git(["for-each-ref", "--merged", defaultRef, "--format=%(refname)", "refs/heads"], root).out.split(/\r?\n/).filter(Boolean),
|
||||
);
|
||||
for (const b of local) b.merged = b.name !== defaultName && merged.has(`refs/heads/${b.name}`);
|
||||
}
|
||||
}
|
||||
return [...local, ...remoteOnly];
|
||||
}
|
||||
|
||||
/** Every local branch plus remote-only rows: readRefs() + branchesFromRefs() in one call. */
|
||||
export function readBranches(root, { current, defaultName } = {}) {
|
||||
return branchesFromRefs(readRefs(root), root, { current, defaultName });
|
||||
}
|
||||
|
||||
const GIT_PATHS = ["rebase-merge", "rebase-apply", "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "FETCH_HEAD"];
|
||||
|
||||
/** Where git keeps its marker files for this worktree, resolved against `root`. {} on failure. */
|
||||
export function gitPaths(root) {
|
||||
const res = git(["rev-parse", ...GIT_PATHS.flatMap((p) => ["--git-path", p])], root);
|
||||
const lines = res.ok ? res.out.split(/\r?\n/) : [];
|
||||
if (lines.length !== GIT_PATHS.length) return {};
|
||||
return Object.fromEntries(GIT_PATHS.map((name, i) => [name, path.resolve(root, lines[i])]));
|
||||
}
|
||||
|
||||
const exists = (p) => !!p && fs.existsSync(p);
|
||||
|
||||
/**
|
||||
* rebase, am, merge, cherry-pick, revert or null, first match wins, in that
|
||||
* order. The rebase dirs come first: a conflicted `merge` entry in an
|
||||
* interactive rebase leaves MERGE_HEAD beside rebase-merge/, and the outer
|
||||
* operation is the rebase. rebase-apply/applying is git's own am marker
|
||||
* (the rule its shell prompt uses); without it the dir is a rebase.
|
||||
*/
|
||||
export function inProgressOp(paths = {}) {
|
||||
if (exists(paths["rebase-merge"])) return "rebase";
|
||||
if (exists(paths["rebase-apply"])) return exists(path.join(paths["rebase-apply"], "applying")) ? "am" : "rebase";
|
||||
if (exists(paths.MERGE_HEAD)) return "merge";
|
||||
if (exists(paths.CHERRY_PICK_HEAD)) return "cherry-pick";
|
||||
if (exists(paths.REVERT_HEAD)) return "revert";
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The branch a rebase in progress is rewriting (rebase-merge/ or rebase-apply/
|
||||
* head-name), so the board can say "main, rebasing" rather than "not on a
|
||||
* branch": HEAD is detached while git replays, but the person is on main.
|
||||
*/
|
||||
export function rebasingBranch(paths = {}) {
|
||||
for (const dir of [paths["rebase-merge"], paths["rebase-apply"]]) {
|
||||
if (!dir) continue;
|
||||
try {
|
||||
const ref = fs.readFileSync(path.join(dir, "head-name"), "utf8").trim();
|
||||
if (ref.startsWith("refs/heads/")) return ref.slice("refs/heads/".length);
|
||||
} catch {}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** FETCH_HEAD's mtime as an ISO string; null when it was never fetched. */
|
||||
export function lastFetch(paths = {}) {
|
||||
try {
|
||||
return fs.statSync(paths.FETCH_HEAD).mtime.toISOString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------- remotes and pull requests */
|
||||
|
||||
function hostKind(host) {
|
||||
if (host === "github.com") return "github";
|
||||
if (host === "gitlab.com") return "gitlab";
|
||||
if (host === "bitbucket.org") return "bitbucket";
|
||||
if (host === "dev.azure.com" || host === "ssh.dev.azure.com" || host.endsWith(".visualstudio.com")) return "azure";
|
||||
return null;
|
||||
}
|
||||
|
||||
// user@host:path, but not a Windows drive (C:/repo) and not a URL.
|
||||
const SCP = /^(?:[^@/]+@)?([^:/]+):(?!\/\/)(.+)$/;
|
||||
|
||||
/** A remote URL as { host, web, kind }; web is always https:. null when it cannot be read. */
|
||||
export function parseRemoteUrl(url) {
|
||||
const raw = String(url || "").trim();
|
||||
let host;
|
||||
let port = "";
|
||||
let repoPath;
|
||||
let ssh = false;
|
||||
if (/^(https?|ssh):\/\//i.test(raw)) {
|
||||
let u;
|
||||
try {
|
||||
u = new URL(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
host = u.hostname.toLowerCase();
|
||||
ssh = u.protocol === "ssh:";
|
||||
if (!ssh && u.port) port = `:${u.port}`;
|
||||
// Already percent-encoded, which is what a web address needs.
|
||||
repoPath = u.pathname;
|
||||
} else {
|
||||
const m = raw.match(SCP);
|
||||
if (!m || /^[A-Za-z]$/.test(m[1])) return null;
|
||||
host = m[1].toLowerCase();
|
||||
ssh = true;
|
||||
repoPath = m[2];
|
||||
}
|
||||
repoPath = repoPath.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/, "");
|
||||
if (!host || !repoPath) return null;
|
||||
|
||||
// Azure DevOps SSH remotes name the repo as v3/<org>/<project>/<repo>.
|
||||
const v3 = repoPath.match(/^v3\/([^/]+)\/([^/]+)\/([^/]+)$/);
|
||||
if (ssh && v3 && host === "ssh.dev.azure.com") {
|
||||
return { host: "dev.azure.com", web: `https://dev.azure.com/${v3[1]}/${v3[2]}/_git/${v3[3]}`, kind: "azure" };
|
||||
}
|
||||
if (ssh && v3 && host === "vs-ssh.visualstudio.com") {
|
||||
const web = `https://${v3[1]}.visualstudio.com/${v3[2]}/_git/${v3[3]}`;
|
||||
return { host: `${v3[1]}.visualstudio.com`, web, kind: "azure" };
|
||||
}
|
||||
return { host, web: `https://${host}${port}/${repoPath}`, kind: hostKind(host) };
|
||||
}
|
||||
|
||||
// Userinfo out of a scheme URL: remotes like https://user:token@host/... are
|
||||
// real (Azure DevOps PATs especially), and this string lands in state.json and
|
||||
// every state frame. Scp-style user@host:path keeps its user.
|
||||
const stripUserinfo = (url) => url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@\s]*@/i, "$1");
|
||||
|
||||
/** Every remote's fetch URL, web address and host kind; unknown hosts take their kind from prHosts. */
|
||||
export function readRemotes(root, prHosts = {}) {
|
||||
const res = git(["remote", "-v"], root);
|
||||
const remotes = [];
|
||||
for (const line of res.out.split(/\r?\n/)) {
|
||||
const m = line.match(/^(\S+)\s+(.+?)\s+\(fetch\)$/);
|
||||
if (!m) continue;
|
||||
const parsed = parseRemoteUrl(m[2]);
|
||||
const host = parsed?.host || null;
|
||||
let kind = parsed?.kind || null;
|
||||
if (!kind && host && Object.hasOwn(prHosts || {}, host)) kind = prHosts[host];
|
||||
remotes.push({ name: m[1], url: stripUserinfo(m[2]), host, web: parsed?.web || null, kind });
|
||||
}
|
||||
return remotes;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------- snapshot and the count */
|
||||
|
||||
const MARKER = /^(<{7}|={7}|>{7})( |$)/m;
|
||||
|
||||
function hasMarkers(file) {
|
||||
try {
|
||||
return MARKER.test(fs.readFileSync(file, "utf8"));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function safe(fn, fallback) {
|
||||
try {
|
||||
return fn();
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The state.git snapshot of the worktree at `worktree` (its top level), from
|
||||
* about four git processes plus one ls-files per untracked folder. Never
|
||||
* throws: a git failure inside a section leaves that section empty.
|
||||
*/
|
||||
export function snapshot(worktree, { prHosts = {} } = {}) {
|
||||
const at = new Date().toISOString();
|
||||
const floor = gitFloor();
|
||||
if (!floor.ok) return { at, repo: true, error: floor.message };
|
||||
const status = git(["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=normal"], worktree, { raw: true });
|
||||
if (!status.ok && !git(["rev-parse", "--git-dir"], worktree).ok) return { at, repo: false };
|
||||
const parsed = safe(() => parseStatusV2(status.out), parseStatusV2(""));
|
||||
// The branch table's for-each-ref already reads every ref: the default
|
||||
// branch comes off it instead of three more probes. When it is empty the
|
||||
// standalone probes still answer (empty repo, odd ref state).
|
||||
const refs = safe(() => readRefs(worktree), []);
|
||||
const def = refs.length
|
||||
? defaultBranchFromRefs(refs, parsed)
|
||||
: safe(() => defaultBranch(worktree, parsed), { name: null, from: null });
|
||||
const branches = safe(() => branchesFromRefs(refs, worktree, { current: parsed.branch, defaultName: def.name }), []);
|
||||
const paths = safe(() => gitPaths(worktree), {});
|
||||
const remotes = safe(() => readRemotes(worktree, prHosts), []);
|
||||
const changes = safe(() => readChanges(worktree, parsed), { count: 0, heldBack: 0, files: [], untrackedDirs: [], sensitive: [], large: [] });
|
||||
|
||||
let pr = null;
|
||||
const cur = branches.find((b) => b.current && !b.remote);
|
||||
if (cur && cur.upstream && !cur.gone && !cur.default && def.name) {
|
||||
const remote = remotes.find((r) => r.name === cur.upstreamRemote);
|
||||
if (remote) pr = prUrl(remote, { base: def.name, head: cur.name });
|
||||
}
|
||||
|
||||
return {
|
||||
at,
|
||||
repo: true,
|
||||
hasCommits: parsed.hasCommits,
|
||||
head: {
|
||||
branch: parsed.branch,
|
||||
detached: parsed.branch ? null : parsed.oid ? parsed.oid.slice(0, 7) : null,
|
||||
...(parsed.branch ? {} : { rebasing: safe(() => rebasingBranch(paths), null) }),
|
||||
upstream: parsed.upstream,
|
||||
// Its remote copy was deleted (fetch --prune): the upstream name is
|
||||
// still configured, but there is nothing behind it to pull or push to.
|
||||
gone: Boolean(cur && cur.gone),
|
||||
ahead: parsed.ahead,
|
||||
behind: parsed.behind,
|
||||
},
|
||||
defaultBranch: def.name,
|
||||
inProgress: safe(() => inProgressOp(paths), null),
|
||||
conflicted: parsed.conflicted.map((c) => ({ ...c, markers: hasMarkers(path.join(worktree, c.path)) })),
|
||||
changes: { count: changes.count, heldBack: changes.heldBack, files: changes.files, untrackedDirs: changes.untrackedDirs },
|
||||
remotes,
|
||||
lastFetch: safe(() => lastFetch(paths), null),
|
||||
refreshFailed: false,
|
||||
branches,
|
||||
prUrl: pr,
|
||||
};
|
||||
}
|
||||
|
||||
/** How many paths a commit would take from `dir` (an untracked folder counts once); null when git cannot say. */
|
||||
export function countPending(dir) {
|
||||
const res = git(["status", "--porcelain=v2", "-z", "--untracked-files=normal"], dir, { raw: true, timeout: 3000 });
|
||||
if (!res.ok) return null;
|
||||
try {
|
||||
const parsed = parseStatusV2(res.out);
|
||||
return parsed.files.length + parsed.conflicted.length;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+292
-38
@@ -22,6 +22,7 @@ import crypto from "node:crypto";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { countPending } from "./git-repo.mjs";
|
||||
import { CHAT_LIMIT } from "./public/chat.js";
|
||||
import { DOC_TYPES } from "./public/answers.js";
|
||||
import { defaultName } from "./public/workspace.js";
|
||||
@@ -361,29 +362,11 @@ export function insideGitRepo(dir) {
|
||||
// How many paths git would commit from `dir`: modified, staged, deleted and
|
||||
// untracked (an untracked folder counts once), from one bounded `git status`.
|
||||
// null when git cannot say (not installed, not a repository, too slow), which
|
||||
// the page reads as "unknown", never as a clean tree. --no-optional-locks keeps
|
||||
// this background look from taking the index lock out from under a commit.
|
||||
// the page reads as "unknown", never as a clean tree. GIT_OPTIONAL_LOCKS=0 (set
|
||||
// by git-repo.mjs) keeps this background look from taking the index lock out
|
||||
// from under a commit.
|
||||
export function pendingFiles(dir) {
|
||||
try {
|
||||
const out = execFileSync("git", ["--no-optional-locks", "status", "--porcelain", "-z"], {
|
||||
cwd: dir,
|
||||
encoding: "utf8",
|
||||
timeout: 3000,
|
||||
windowsHide: true,
|
||||
maxBuffer: 8 * 1024 * 1024,
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
});
|
||||
const parts = out.split("\0").filter(Boolean);
|
||||
let n = 0;
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
n++;
|
||||
// A rename or copy carries its old path as one more field.
|
||||
if (/^[RC]/.test(parts[i])) i++;
|
||||
}
|
||||
return n;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return countPending(dir);
|
||||
}
|
||||
|
||||
export function projectRoot(cwd = process.cwd()) {
|
||||
@@ -535,12 +518,13 @@ export async function removeSessions(sessionsDir, sids) {
|
||||
|
||||
// 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.
|
||||
// saved per project and workflow, what each unknown git host is, 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",
|
||||
"pr-hosts.json",
|
||||
"console-dir",
|
||||
"update-check.json",
|
||||
]);
|
||||
@@ -667,6 +651,23 @@ function strayEntries(dir, kept, where, now) {
|
||||
.filter((e) => settled(e.path));
|
||||
}
|
||||
|
||||
// Finalize's archive, `<project>/specs--completed/<feature>/`: each feature
|
||||
// folder (or link) nobody has touched for `maxAgeMs`, judged by its newest
|
||||
// file. Loose files at the top are not specs and stay.
|
||||
function completedSpecs(project, now, maxAgeMs) {
|
||||
const dir = path.join(project, "specs--completed");
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return entries
|
||||
.filter((e) => e.isDirectory() || e.isSymbolicLink())
|
||||
.map((e) => ({ id: "completed:" + e.name, where: "completed", name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
||||
.filter((e) => now - newestMtime(e.path) > maxAgeMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything Cleanup would remove, worked out on the server and never taken
|
||||
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
|
||||
@@ -676,6 +677,7 @@ function strayEntries(dir, kept, where, now) {
|
||||
* `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.
|
||||
* Given a `project`, also its completed specs untouched for `maxAgeMs`.
|
||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
||||
*/
|
||||
export async function cleanupFindings({
|
||||
@@ -684,6 +686,7 @@ export async function cleanupFindings({
|
||||
now = Date.now(),
|
||||
maxAgeMs = SESSION_MAX_AGE_MS,
|
||||
skipSid,
|
||||
project,
|
||||
} = {}) {
|
||||
const found = [];
|
||||
const sessionsDir = path.join(consoleDir, "sessions");
|
||||
@@ -695,6 +698,7 @@ export async function cleanupFindings({
|
||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
||||
}
|
||||
if (project) found.push(...completedSpecs(project, now, maxAgeMs));
|
||||
const items = [];
|
||||
let bytes = 0;
|
||||
for (const f of found) {
|
||||
@@ -843,8 +847,13 @@ function classifySpec(dir, names) {
|
||||
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;
|
||||
// The task lines when the file has them (`- [ ] **Task 1.2:**`), so an
|
||||
// Acceptance Criteria checkbox is not counted as a task; every checkbox
|
||||
// in a file written before that format.
|
||||
const tasks = text.split(/\r?\n/).filter((l) => TASK_LINE_RE.test(l));
|
||||
const lines = tasks.length ? tasks.join("\n") : text;
|
||||
done += (lines.match(/^\s*[-*] \[[xX]\]/gm) || []).length;
|
||||
open += (lines.match(/^\s*[-*] \[[ /!]\]/gm) || []).length;
|
||||
}
|
||||
const total = done + open;
|
||||
if (open === 0 && done > 0) return { state: "built", detail: "all tasks done" };
|
||||
@@ -884,7 +893,7 @@ function classifySpec(dir, names) {
|
||||
// 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" };
|
||||
return { state: "unrecognized", detail: "no pipeline files yet" };
|
||||
}
|
||||
|
||||
function isDir(p) {
|
||||
@@ -954,10 +963,15 @@ export function pidAlive(pid) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function healthOk(handle, timeoutMs = 1500) {
|
||||
export async function healthOk(handle, timeoutMs = 1500, signal) {
|
||||
if (!handle || !handle.url) return false;
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
||||
// The caller's own abort ends the check at once (a wait that is done).
|
||||
if (signal) {
|
||||
if (signal.aborted) ctrl.abort();
|
||||
else signal.addEventListener("abort", () => ctrl.abort(), { once: true });
|
||||
}
|
||||
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
|
||||
@@ -1147,9 +1161,20 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
||||
// 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;
|
||||
// An explicit reopen counts as asking again even with the question's
|
||||
// words unchanged (the notes reopen with a status and a thread reply):
|
||||
// the last send stops being in flight, and its note moves to the thread.
|
||||
if ((!rewritten && !reopens) || settles || (wasSettled && !reopens)) continue;
|
||||
const item = merged.find((x) => x.id === entry.id);
|
||||
if (wasSettled && !("status" in entry)) item.status = "open";
|
||||
// What they wrote with that answer ("I want changes: rename tally") is the
|
||||
// context for the question being asked again, so it moves into the thread
|
||||
// rather than leaving with the record.
|
||||
const said = prev.submitted && typeof prev.submitted.text === "string" ? prev.submitted.text.trim() : "";
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
if (said && !thread.some((m) => m && m.who === "user" && String(m.text || "").trim() === said)) {
|
||||
item.thread = [...thread.filter((m) => !(m && m.who === "agent" && m.at === undefined)), { who: "user", text: said, at: prev.submitted.at }, ...thread.filter((m) => m && m.who === "agent" && m.at === undefined)];
|
||||
}
|
||||
if (!("submitted" in entry)) delete item.submitted;
|
||||
delete item.answer;
|
||||
}
|
||||
@@ -1217,10 +1242,174 @@ function mergeDocs(current, patchList) {
|
||||
if (!doc) continue;
|
||||
const prev = (current || []).find((d) => d.id === entry.id);
|
||||
doc.blocks = mergeKeyed(prev?.blocks, entry.blocks, "id", {}, "blocks");
|
||||
// A known doc whose content moved, sent with no version, is the next
|
||||
// version: the agent no longer has to track what the page holds, and a
|
||||
// repost of unchanged content is not a new version.
|
||||
if (prev && typeof entry.version !== "number" && typeof prev.version === "number") {
|
||||
const text = (blocks) => JSON.stringify((blocks || []).map((b) => [b.id, b.md, b.state]));
|
||||
if (text(prev.blocks) !== text(doc.blocks)) doc.version = prev.version + 1;
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* `settle` in a patch: the cards the person just answered, marked answered
|
||||
* with what they sent as the answer. `true` takes every open card from the
|
||||
* latest send (one send stamps every card it carries with the same `at`); a
|
||||
* list names the cards. An item the same patch settles itself keeps the
|
||||
* agent's own answer: settle only fills in what the patch left out.
|
||||
*/
|
||||
function settleItems(items, settle, patchItems, collected) {
|
||||
if (settle === undefined || settle === false) return items;
|
||||
if (settle !== true && !(Array.isArray(settle) && settle.every((id) => typeof id === "string"))) {
|
||||
throw new Error('"settle" must be true or a list of item ids');
|
||||
}
|
||||
const sent = (items || []).filter((i) => i && i.submitted && typeof i.submitted === "object");
|
||||
let ids;
|
||||
if (settle === true && collected && Array.isArray(collected.ids)) {
|
||||
// The send `wait` last handed over (state.collected, written as it was
|
||||
// collected): a later send the person made meanwhile is not the agent's yet.
|
||||
ids = sent.filter((i) => isOpen(i) && collected.ids.includes(i.id)).map((i) => i.id);
|
||||
} else if (settle === true) {
|
||||
const latest = sent.filter(isOpen).map((i) => String(i.submitted.at || "")).sort().pop();
|
||||
ids = sent.filter((i) => isOpen(i) && String(i.submitted.at || "") === latest).map((i) => i.id);
|
||||
} else {
|
||||
for (const id of settle) {
|
||||
// The same patch reopening it has already let go of what was sent; the
|
||||
// reopen wins below, so naming it is not an error.
|
||||
const reopening = (patchItems || []).some((e) => e && e.id === id && (e.status === "open" || e.status === "reopened"));
|
||||
if (!reopening && !sent.some((i) => i.id === id)) throw new Error(`settle: "${id}" has nothing sent to settle`);
|
||||
}
|
||||
ids = settle;
|
||||
}
|
||||
const own = new Map((patchItems || []).filter(isPlainObject).map((e) => [e.id, e]));
|
||||
return items.map((item) => {
|
||||
if (!ids.includes(item.id)) return item;
|
||||
const entry = own.get(item.id) || {};
|
||||
// The same patch reopening it (a `changes` verdict answered by a reworked
|
||||
// report) means it is not settled: no answer is recorded over the reopen.
|
||||
if (entry.status === "open" || entry.status === "reopened") return item;
|
||||
const { at, kind, ...answer } = item.submitted;
|
||||
return {
|
||||
...item,
|
||||
// A "Skip this one" send settles as skipped, not as an answer.
|
||||
status: "status" in entry ? item.status : answer.skipped === true ? "skipped" : "answered",
|
||||
...("answer" in entry ? {} : { answer }),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// A question the patch puts in front of the person: new, or reopened.
|
||||
function asksSomething(patchItems, before) {
|
||||
return (patchItems || []).some((e) => {
|
||||
if (!isPlainObject(e) || e._delete || e.kind === "notice") return false;
|
||||
const prev = (before || []).find((x) => x && x.id === e.id);
|
||||
if (!prev) return e.kind !== undefined && (e.status === undefined || e.status === "open");
|
||||
return e.status === "reopened" || (e.status === "open" && !isOpen(prev));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The agent block after a patch, with the rule kept here rather than in every
|
||||
* prompt: a patch that asks a question and says nothing of the status hands
|
||||
* the turn over (a question stops the work). `quietMinutes` stays put: the
|
||||
* page only counts it while working, and a build that asked a question goes
|
||||
* back to the same long tasks once it is answered.
|
||||
*/
|
||||
function settleAgent(next, patch, before) {
|
||||
const said = isPlainObject(patch.agent) ? patch.agent : null;
|
||||
const saidStatus = said && "status" in said;
|
||||
// A finish ends the working stretch too (nothing may still be running at
|
||||
// one): a pause posted without a wait would otherwise sit at "working".
|
||||
const finishes = isPlainObject(patch.finish);
|
||||
if (!saidStatus && (finishes || asksSomething(patch.items, before.items))) {
|
||||
next.agent = { ...(next.agent || {}), status: "waiting" };
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Doc blocks that name a file get their `md` from disk: a build's phase file
|
||||
* re-posted after every task was the biggest thing an agent typed, and every
|
||||
* word of it was already on disk. `{ "id": "body", "file": "specs/x/phase-3.md" }`
|
||||
* reads the file; `"select": "tasks"` keeps only its task checkbox lines; a doc
|
||||
* with `"refresh": true` re-reads every file block it already has. Paths are
|
||||
* relative to the worktree and must stay inside it. Runs in the CLI before
|
||||
* the merge, so applyPatch itself never touches the disk.
|
||||
*/
|
||||
export const DOC_FILE_MAX = 512 * 1024;
|
||||
const TASK_LINE_RE = /^\s*(?:[-*]|\d+\.)\s+\[.\]\s+\*\*Task\s/i;
|
||||
|
||||
export function resolveDocFiles(patch, state, worktree) {
|
||||
if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch;
|
||||
const root = path.resolve(worktree || state.worktree || process.cwd());
|
||||
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
|
||||
const read = (file, select, docId) => {
|
||||
if (typeof file !== "string" || !file.trim()) throw new Error(`doc "${docId}": a block's "file" must be a path`);
|
||||
const abs = path.resolve(root, file);
|
||||
let real;
|
||||
try {
|
||||
real = fs.realpathSync.native(abs);
|
||||
} catch {
|
||||
throw new Error(`doc "${docId}": no file at ${file}`);
|
||||
}
|
||||
const rootReal = (() => {
|
||||
try {
|
||||
return fs.realpathSync.native(root);
|
||||
} catch {
|
||||
return root;
|
||||
}
|
||||
})();
|
||||
// path.relative, not a prefix test: a worktree at a drive root ends in a
|
||||
// separator already, and win32's relative() folds case itself.
|
||||
const rel = path.relative(fold(rootReal), fold(real));
|
||||
if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error(`doc "${docId}": ${file} is outside the project`);
|
||||
const stat = fs.statSync(real);
|
||||
if (!stat.isFile()) throw new Error(`doc "${docId}": ${file} is not a file`);
|
||||
if (stat.size > DOC_FILE_MAX) throw new Error(`doc "${docId}": ${file} is larger than ${DOC_FILE_MAX / 1024} KB`);
|
||||
const text = fs.readFileSync(real, "utf8").replace(/\r\n/g, "\n");
|
||||
if (select === undefined) return text;
|
||||
if (select !== "tasks") throw new Error(`doc "${docId}": "select" only takes "tasks"`);
|
||||
const tasks = text.split("\n").filter((l) => TASK_LINE_RE.test(l)).map((l) => l.trim());
|
||||
if (!tasks.length) throw new Error(`doc "${docId}": ${file} has no task lines to select`);
|
||||
return tasks.join("\n");
|
||||
};
|
||||
const docs = patch.docs.map((entry) => {
|
||||
if (!isPlainObject(entry)) return entry;
|
||||
const { refresh, ...rest } = entry;
|
||||
let blocks = Array.isArray(rest.blocks) ? rest.blocks : undefined;
|
||||
if (refresh === true) {
|
||||
const prev = (state.docs || []).find((d) => d && d.id === entry.id);
|
||||
const named = new Set((blocks || []).map((b) => b && b.id));
|
||||
const again = ((prev && prev.blocks) || [])
|
||||
.filter((b) => b && typeof b.file === "string" && !named.has(b.id))
|
||||
.map((b) => ({ id: b.id, file: b.file, ...(b.select ? { select: b.select } : {}) }));
|
||||
if (!again.length && !blocks) throw new Error(`doc "${entry.id}": "refresh" found no file blocks to re-read`);
|
||||
blocks = [...(blocks || []), ...again];
|
||||
} else if (refresh !== undefined) throw new Error(`doc "${entry.id}": "refresh" must be true`);
|
||||
if (!blocks) return rest;
|
||||
const prevBlocks = (state.docs || []).find((d) => d && d.id === entry.id)?.blocks || [];
|
||||
return {
|
||||
...rest,
|
||||
blocks: blocks.map((b) => {
|
||||
if (!isPlainObject(b)) return b;
|
||||
const prevBlock = prevBlocks.find((x) => x && x.id === b.id);
|
||||
if (b.file === undefined || b.file === null) {
|
||||
// Typed text over a block that was a file: it stops being one, so a
|
||||
// later refresh cannot overwrite it and the prose scan sees it.
|
||||
return "md" in b && prevBlock && typeof prevBlock.file === "string" ? { ...b, file: null, select: null } : b;
|
||||
}
|
||||
// A file named again without `select` is the whole file, now and on
|
||||
// every refresh: an older select must not linger in the merge.
|
||||
const select = "select" in b ? b.select : null;
|
||||
return { state: prevBlock?.state || "settled", ...b, select, md: read(b.file, select ?? undefined, entry.id) };
|
||||
}),
|
||||
};
|
||||
});
|
||||
return { ...patch, docs };
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply an agent patch to the session state.
|
||||
*
|
||||
@@ -1233,6 +1422,8 @@ function mergeDocs(current, patchList) {
|
||||
export function applyPatch(state, patch) {
|
||||
guard(patch, "patch");
|
||||
patch = liftActivity(patch);
|
||||
const { settle, ...rest } = patch;
|
||||
patch = rest;
|
||||
const next = { ...state };
|
||||
for (const [k, v] of Object.entries(patch)) {
|
||||
if (v === null) {
|
||||
@@ -1277,7 +1468,12 @@ export function applyPatch(state, patch) {
|
||||
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");
|
||||
// A reply with no id is named for the message it answers (`r<seq>`),
|
||||
// so a repeat delivery re-posted the same way replaces, never doubles.
|
||||
const named = v.replies.map((r) =>
|
||||
isPlainObject(r) && (r.id === undefined || r.id === "") && Number.isInteger(r.re) ? { ...r, id: `r${r.re}` } : r,
|
||||
);
|
||||
chat.replies = mergeKeyed(chat.replies, named, "id", {}, "chat.replies");
|
||||
}
|
||||
next.chat = chat;
|
||||
break;
|
||||
@@ -1286,7 +1482,8 @@ export function applyPatch(state, patch) {
|
||||
next[k] = v;
|
||||
}
|
||||
}
|
||||
return stampTimes(state, next);
|
||||
if (settle !== undefined) next.items = settleItems(next.items || [], settle, patch.items, state.collected);
|
||||
return stampTimes(state, settleAgent(next, patch, state));
|
||||
}
|
||||
|
||||
// `activity` belongs under `agent`, which is the only place the page reads it.
|
||||
@@ -1305,8 +1502,10 @@ function liftActivity(patch) {
|
||||
function stampTimes(before, next) {
|
||||
const now = nowIso();
|
||||
if (next.agent) {
|
||||
// A status change starts its own clock: `since` merged along from the
|
||||
// last status would date a fresh working turn to when the session opened.
|
||||
const changed = !before.agent || before.agent.status !== next.agent.status;
|
||||
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
||||
if (changed) 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)) {
|
||||
@@ -1464,7 +1663,17 @@ export function validate(state) {
|
||||
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));
|
||||
// The dashboard's page is the menu: a card posted there is drawn nowhere,
|
||||
// yet counts as open (and keeps Stop live for a question nobody can see).
|
||||
if (state.workflow === "dashboard" && state.items.some((i) => isOpen(i))) {
|
||||
problems.push(
|
||||
'The dashboard draws no question cards: post its "menu" (and "agent"), and launch the skill a question belongs to.'
|
||||
);
|
||||
}
|
||||
|
||||
// A notice asks nothing (the git board keeps its result line open all
|
||||
// session), so it never takes one of the three slots.
|
||||
const openRequired = state.items.filter((i) => i.required !== false && i.kind !== "notice" && isOpen(i));
|
||||
if (openRequired.length > MAX_OPEN_REQUIRED) {
|
||||
problems.push(
|
||||
`${openRequired.length} questions are open at once. The cap is ${MAX_OPEN_REQUIRED} ` +
|
||||
@@ -1532,11 +1741,18 @@ export function validate(state) {
|
||||
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)');
|
||||
}
|
||||
// The page reads exactly two: anything else would leave it guessing whose
|
||||
// turn it is.
|
||||
if (state.agent && state.agent.status != null && !["working", "waiting"].includes(state.agent.status)) {
|
||||
problems.push(`"agent.status" must be "working" or "waiting" (not "${state.agent.status}")`);
|
||||
}
|
||||
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);
|
||||
// Open gates only: an approval already given (last phase's sign-off) is a
|
||||
// record, and must not stop the next phase from asking for its own.
|
||||
const gates = state.items.filter((i) => i.gate && i.gate.authoritative && isOpen(i));
|
||||
if (gates.length > 1) {
|
||||
problems.push(
|
||||
`${gates.length} authoritative approval gates are open (${gates
|
||||
@@ -1553,9 +1769,15 @@ export function validate(state) {
|
||||
...rest,
|
||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
||||
}));
|
||||
// A doc block read from a file (`file`) is the file's own words, already on
|
||||
// disk: the agent cannot reword it, and refusing it would wedge every post
|
||||
// that refreshes it. Only what the agent typed is scanned.
|
||||
const typedDocs = (state.docs || []).map((d) =>
|
||||
isPlainObject(d) && Array.isArray(d.blocks) ? { ...d, blocks: d.blocks.filter((b) => !(isPlainObject(b) && typeof b.file === "string")) } : d
|
||||
);
|
||||
const prose =
|
||||
JSON.stringify(authored) +
|
||||
JSON.stringify(state.docs || []) +
|
||||
JSON.stringify(typedDocs) +
|
||||
JSON.stringify(state.finish || {}) +
|
||||
JSON.stringify(state.menu || {});
|
||||
problems.push(...proseProblems(prose));
|
||||
@@ -1591,7 +1813,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
specDir: specDir || "",
|
||||
created: nowIso(),
|
||||
phase: "collecting",
|
||||
agent: { status: "working", since: nowIso(), handled: 0 },
|
||||
agent: { status: "working", since: nowIso() },
|
||||
headline: { stage: "", cleared: 0, total: 0, confidence: "", note: "" },
|
||||
topics: [],
|
||||
items: [],
|
||||
@@ -1601,7 +1823,8 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
|
||||
/**
|
||||
* 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
|
||||
* it, or a launch from its menu), or into Git from any skill
|
||||
* (Commit it now, Changelog's hand-off), 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.
|
||||
@@ -1770,8 +1993,12 @@ export function collectChat(dir, state) {
|
||||
// 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.
|
||||
// A run of resets (the session's opening one, then one per skill switch)
|
||||
// says one thing, so only the last of each run is handed over; it carries the
|
||||
// highest seq of the run, so the cursor still moves past all of them.
|
||||
export function deliverableChat(entries) {
|
||||
return entries.some((e) => e.kind !== "reset") ? entries : [];
|
||||
if (!entries.some((e) => e.kind !== "reset")) return [];
|
||||
return entries.filter((e, i) => !(e.kind === "reset" && entries[i + 1] && entries[i + 1].kind === "reset"));
|
||||
}
|
||||
|
||||
// Things the person said that were handed over but never answered. The page keeps
|
||||
@@ -2129,6 +2356,33 @@ export function saveSubagentStoreEntry(worktree, workflow, value) {
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- the PR host store */
|
||||
|
||||
// What kind of git host an unknown host is, so the git board can build its
|
||||
// pull-request link. One answer per host, for every project:
|
||||
//
|
||||
// { "<host>": "github" | "gitlab" | "bitbucket" | "azure" | "none" }
|
||||
export const PR_HOSTS_FILE = path.join(HOME_DIR, "pr-hosts.json");
|
||||
export const PR_HOST_KINDS = new Set(["github", "gitlab", "bitbucket", "azure", "none"]);
|
||||
const PR_HOSTS_LOCK = "pr-hosts.json.lock";
|
||||
|
||||
// The saved hosts as a plain object; malformed → {}, unknown kinds dropped.
|
||||
export function readPrHosts() {
|
||||
const saved = readJson(PR_HOSTS_FILE, null);
|
||||
if (!saved || typeof saved !== "object" || Array.isArray(saved)) return {};
|
||||
return Object.fromEntries(Object.entries(saved).filter(([, kind]) => PR_HOST_KINDS.has(kind)));
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this.
|
||||
export function savePrHost(host, kind) {
|
||||
ensureDir(path.dirname(PR_HOSTS_FILE));
|
||||
withStateLock(
|
||||
path.dirname(PR_HOSTS_FILE),
|
||||
() => writeJsonAtomic(PR_HOSTS_FILE, { ...readPrHosts(), [host]: kind }),
|
||||
PR_HOSTS_LOCK
|
||||
);
|
||||
}
|
||||
|
||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
||||
|
||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Changelog on the Web Console
|
||||
|
||||
Workflow notes for `changelog`, part of the web console contract (`console.md`).
|
||||
|
||||
Open with `--workflow changelog` (launched from the dashboard: resume the
|
||||
session instead). Post `activity` while you read the history and the diff. One
|
||||
card per step, each asked only when the step needs it:
|
||||
|
||||
| Step | On the page |
|
||||
| --- | --- |
|
||||
| Version | A `choice`, "Which version?": the computed version (recommended) with its reason in `body` (main is at X, the branch has Y), "Keep Y" when the branch's own entry could stay, and "Another version" (`allowOther`). A `choice` does not check what is typed, so check it yourself: anything that is not `X.Y.Z` gets the card again with a `thread` reply saying so. Left out when the entry is already right. |
|
||||
| Entries | A `list` titled "Entries to add": one row per suggested entry, `title` the entry line itself (the part they can edit) and `body` its section (`Added`, `Fixed`…). Removable and reorderable; `reply` names renames, additions and removals. A row they add has no section: ask, or file it where it reads best and say so. |
|
||||
| The result | The final entry as a doc (`id: "entry"`, marked `"saved": "CHANGELOG.md"` once written) plus a `review` card with verdicts `write` ("Write it"), `change` and `stop`. |
|
||||
| package.json | A `confirm` with the `old → new` in `consequences`. |
|
||||
| Commit this now? | A `confirm`, "Commit this now?". |
|
||||
|
||||
A yes to "Commit this now?" ends no session (no `finish`, no `stop`): settle
|
||||
the card, resume as `git` (`open --resume <sid> --no-open --workflow git`),
|
||||
then read `~/.agents/skills/plan2code-git/SKILL.md` with your file-read tool
|
||||
and start with its commit flow, in this same session, as a dashboard launch
|
||||
does (`console-launches.md`); the resume clears Changelog's page for it.
|
||||
Finish, on a no: `"dashboard": true` and the version and entries in `body`,
|
||||
with no `command`. A stop's finish is the bare `/plan2code-changelog`.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Documentation on the Web Console
|
||||
|
||||
Workflow notes for `document`, part of the web console contract (`console.md`).
|
||||
|
||||
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, and post it as a `file` block
|
||||
(`{ "id": "body", "file": "specs/<feature>/phase-2.md" }`) rather than pasting
|
||||
the text you just wrote. Pass `--spec specs/<feature>` 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/<feature>/overview.md`.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Finalize on the Web Console
|
||||
|
||||
Workflow notes for `finalize`, part of the web console contract (`console.md`).
|
||||
|
||||
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 or blocked tasks exist (`totals.incomplete + totals.blocked > 0`), 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`, as a `file` block on `overview.md`) 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/<feature>` 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/<feature>` 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/<feature>/overview.md"`. On success
|
||||
the finish's `command` is the suggested commit when Step 4 doc updates landed
|
||||
(with `"where": "When you are happy with it, commit it from your terminal:"`), otherwise leave `command` out.
|
||||
When the finish prints that suggested commit, it also carries `"commit": true`,
|
||||
so the finished screen offers **Commit it now** (`console-finish.md`). The
|
||||
completion summary is printed to a terminal the browser user is not watching,
|
||||
so put it in `finish.body`.
|
||||
@@ -0,0 +1,119 @@
|
||||
# Git on the Web Console
|
||||
|
||||
Workflow notes for `git`, part of the web console contract (`console.md`).
|
||||
|
||||
Open with `--workflow git` (launched from the dashboard, or by a **Commit it
|
||||
now** or Changelog hand-off: resume the session instead). Like the dashboard,
|
||||
the main column is drawn by the page itself: the git board, from `state.git`,
|
||||
which `open` and every `reread` snapshot through `git-repo.mjs`. **You never
|
||||
post `git`** (exit 3: `state.git` is the console's own). Your cards sit above
|
||||
the board in the usual card slot.
|
||||
|
||||
**A click** arrives as one session action, one per send, and the board locks
|
||||
until your next post lands:
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [{ "i": "__git", "type": "git", "op": "create",
|
||||
"name": "feature/export-csv", "from": "origin/main",
|
||||
"then": "commit", "files": ["src/a.js"], "ignore": ["dist/"] }],
|
||||
"reply": "Create feature/export-csv from origin/main. ..." }
|
||||
```
|
||||
|
||||
| `op` | Fields |
|
||||
| --- | --- |
|
||||
| `refresh`, `pull`, `push`, `abort`, `continue`, `done` | none (a `refresh` with no remote is "look again": `plan refresh` gives no commands, so just post `reread`) |
|
||||
| `publish` | `remote?` (left out when there are several: `plan publish` asks which) |
|
||||
| `switch`, `delete` | `branch` (a remote-only row is `<remote>/<name>`) |
|
||||
| `create` | `name`, `from`; `then: "commit"` with `files` (and `ignore`, when any) when it came from the commit panel's branch offer |
|
||||
| `cleanup` | `branches[]` |
|
||||
| `commit` | `files[]` (paths and untracked folders), `ignore[]` (folders to add to `.gitignore`) |
|
||||
| `pr-host` | `host`, `kind` (already saved by the page's `POST /pr-host`) |
|
||||
|
||||
`reply` is the plain instruction the terminal would get, so it reads like any
|
||||
answer. `__git` names no question, like `__stop`.
|
||||
|
||||
**After an action**, in ONE post (with `--wait`):
|
||||
|
||||
```jsonc
|
||||
{ "reread": true,
|
||||
"items": [{ "id": "git-result", "kind": "notice", "status": "open",
|
||||
"title": "Pushed 2 commits to origin/feature/x",
|
||||
"body": "a1b2c3d, e4f5a6b. [Open pull request](https://github.com/...)" }],
|
||||
"board": { "describe": "export-csv-button" } }
|
||||
```
|
||||
|
||||
- `reread` is `true`, or `{ "refreshFailed": true }` after a Refresh that
|
||||
failed (the board then says so beside the last refreshed time and keeps the
|
||||
last data). It goes only with the `git` workflow; anywhere else, or in any
|
||||
other shape, it is exit `3`. The console takes the snapshot inside the same
|
||||
locked write as your cards, so the result line and the fresh board land
|
||||
together.
|
||||
- `git-result` is a `notice` replaced every action (same id). The board shows
|
||||
it under its header, not in the card slot: what happened, with short hashes
|
||||
and, after a push or publish, the `pr-url` link. On a failure it quotes
|
||||
git's stderr verbatim with `classify-error`'s `next`.
|
||||
- `board.describe` is yours: a short kebab-case description of the changes
|
||||
still on the tree, which the Create prompt pre-fills. Post it with the
|
||||
reread whenever changes remain; leave it out otherwise.
|
||||
- The board is the person's to click whenever you wait, so `wait` hands the
|
||||
turn back by itself; no `agent` status is needed.
|
||||
|
||||
**Cards per `plan`.** `git.mjs plan <op>` decides whether to ask:
|
||||
|
||||
| `plan` says | On the page |
|
||||
| --- | --- |
|
||||
| `confirm` | A `confirm` card with its `title`, `body`, `danger` and `consequences` verbatim (the consequences end with the exact command). Where the plan names files, add them as `files: [{ "path", "state" }]`. |
|
||||
| `card.kind: "switch"` | A `choice`, "Bring your changes?": exactly the `options` given, labelled **Switch and bring them** (`bring`), **Commit first** (`commit-first`), **Cancel** (`cancel`); the files in `body`, and `reason` when git would refuse (then there is no `bring`). `allowOther: false`. |
|
||||
| `card.kind: "dirty"` | The same `choice` for a pull that needs a clean tree: **Commit first** / **Cancel**, `reason` in `body`. |
|
||||
| `card.kind: "remote"` | A `choice`, "Publish to which remote?": one option per remote, `preset` recommended. Then `plan publish --remote <it>` and its `confirm`. |
|
||||
| `ask: false` | No card: run it on the click. |
|
||||
| exit 4 or 5 | No card and nothing run: the `message` and `next` as the `git-result` notice. |
|
||||
|
||||
An `auth` failure gets a `notice` card saying the tool never handles logins,
|
||||
with `next`. The commit flow's own cards (message, groups, `git init`,
|
||||
`.gitignore`) are the rows below.
|
||||
|
||||
| Commit step | On the page |
|
||||
| --- | --- |
|
||||
| One commit | A `text` card whose `placeholder` is the drafted subject and whose `pattern` caps it at 100 characters, then a `confirm` "Commit this?" with the files in `consequences` and, as `files: [{ "path": "src/a.js", "state": "modified" }]` (states: modified, new, deleted, renamed), a collapsed **Show the N files** table on the card. With the subject given as the argument there is no card. |
|
||||
| A split | The groups as a doc (`id: "commits"`: each group's subject and files, and any file that mixes concerns) plus a `review` card with verdicts `approve`, `change` and `single` ("One commit instead"). Asked even when the subject came as the argument. |
|
||||
| Push | Not asked after a commit on the board: the board lights Push. `commit and push` (or a Push click) asks `plan push` / `plan publish`'s `confirm`. |
|
||||
| `git init` | A `confirm` naming the folder and its first branch (`init-check`'s `branch`, `danger: false`), its `consequences` `init-check`'s `commands`. Run those, not a bare `git init`. |
|
||||
| `.gitignore` | The proposed file, or the lines a `commit`'s `ignore[]` adds, as a doc plus a `review` card. |
|
||||
|
||||
Risky files (`sensitive`, `large`) are named in the card's `body`. On the
|
||||
board there is no branch-offer card: the commit panel's **You're on main**
|
||||
line asks it, and the answer arrives as `create` with `then: "commit"`.
|
||||
|
||||
**Conflict help.** A pull, rebase or merge stopped on conflicts asks first, a
|
||||
`choice` "Resolve them for me?": **Yes**, **I'll fix it**, **Abort pull**.
|
||||
On yes, every stop is a doc (`id: "conflict"`, replaced per stop, its version moving by itself: step N of M,
|
||||
the commit being replayed, each file with a one-line reason, then a per-file
|
||||
diff) plus a `review` card, fresh id per stop, `"nothingYet": false` (the resolution is already on disk), with the verdicts `continue`
|
||||
("Continue"), `change` ("Change it") and `abort` ("Abort pull", `danger`).
|
||||
Only **Continue** runs `plan continue`'s commands; **Abort pull** runs
|
||||
`plan abort` and the board is back on the exact original HEAD. A file you
|
||||
cannot resolve with confidence is named and left with its markers; **I'll fix
|
||||
it** leaves the markers too. The board's banner always offers Continue: a
|
||||
`continue` click is the person saying the files are fixed, so run `plan
|
||||
continue`; when it refuses (exit 5, markers left), post a `reread` with its
|
||||
`message` as the `git-result` notice, which also refreshes the banner's file
|
||||
list. Nothing is pushed during conflict help. At the end, a `notice`
|
||||
summary (commits replayed, each resolved file with its reason, "N commits
|
||||
ready to push").
|
||||
|
||||
**Meter events** (`console-meter.md`). Git scores on launch.
|
||||
Post `run: { "event": "git-commits", "id": "<first short hash>", "commits": N }`
|
||||
after each commit step (N commits made), and `run: { "event": "git-conflict",
|
||||
"id": "conflict-<n>" }` once per conflict help, resolved or aborted.
|
||||
|
||||
**Finishing** (`console-finish.md`). Done (`op: "done"`) with something done
|
||||
this session: a `finish` with a headline, the commits with hashes, pushes and
|
||||
branches created or deleted in `body`, no `command`, and `"dashboard": true`;
|
||||
keep waiting for the press. Done with nothing done: no finish screen — resume
|
||||
as `dashboard` at once (`open --resume <sid> --no-open --workflow dashboard`),
|
||||
read the dashboard skill (`~/.agents/skills/plan2code/SKILL.md`), post its
|
||||
`menu` with `--wait` and carry on from its "Coming back from another skill". A
|
||||
stop's finish is a pause, headline "Paused …", the bare `/plan2code-git`,
|
||||
then `stop`.
|
||||
@@ -0,0 +1,11 @@
|
||||
# Handoff on the Web Console
|
||||
|
||||
Workflow notes for `handoff`, part of the web console contract (`console.md`).
|
||||
|
||||
One gate: the next-task confirmation, then the document itself as a doc —
|
||||
that is what the person is there to download. Give it no `saved` and paste it
|
||||
as `md`: the handoff file often sits outside the project (the OS temp folder),
|
||||
where a `file` block is refused, and the download is the point. The finish carries no
|
||||
`command`: the doc download is the point, and the dashboard button and the
|
||||
"All done" line cover what comes next. Unless it is a pause, the finish carries
|
||||
`"dashboard": true` and you keep waiting for the press (`console-finish.md`).
|
||||
@@ -0,0 +1,155 @@
|
||||
# Implement on the Web Console
|
||||
|
||||
Workflow notes for `implement` and `implement-review`, part of the web console
|
||||
contract (`console.md`). Read `building.md` first.
|
||||
|
||||
## The first post of a phase
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "stage": "Phase 3: API layer", "cleared": 0, "total": 9 },
|
||||
"docs": [
|
||||
{ "id": "phase", "title": "Phase 3 tasks", "blocks": [
|
||||
{ "id": "tasks", "file": "specs/<feature>/phase-3.md", "select": "tasks" }
|
||||
]},
|
||||
{ "id": "phasefile", "title": "phase-3.md", "blocks": [
|
||||
{ "id": "body", "file": "specs/<feature>/phase-3.md" }
|
||||
]}
|
||||
],
|
||||
"agent": { "status": "working", "activity": "Checking the prerequisites", "quietMinutes": 15 }
|
||||
}
|
||||
```
|
||||
|
||||
`phase` is the task list, `phasefile` the whole `phase-X.md` as its own tab —
|
||||
the person can read the prerequisites and task specs while you build. Both are
|
||||
read from disk by the console: never paste the file. It renders as markdown, so
|
||||
the file's checkboxes show as ticks exactly as they stand on disk.
|
||||
|
||||
A later phase in the same session posts the same two docs with the new phase's
|
||||
title and file: their content changed, so their versions move up by themselves
|
||||
(a doc's version never goes back, and you no longer have to track it). Leave
|
||||
`version` out.
|
||||
|
||||
## After every task
|
||||
|
||||
In the same breath as writing the task's checkbox to disk:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "cleared": 4 },
|
||||
"docs": [ { "id": "phase", "refresh": true }, { "id": "phasefile", "refresh": true } ],
|
||||
"agent": { "activity": "Task 5 of 9: the rate limiter" }
|
||||
}
|
||||
```
|
||||
|
||||
`refresh` re-reads the file the checkbox write just changed, so both tabs tick
|
||||
in place; the Phase Completion Summary lands in `phasefile` the same way at the
|
||||
end. Then the `chat` check (`building.md` → Quick questions between tasks).
|
||||
|
||||
---
|
||||
|
||||
## 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", "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": { "approve": "approved", "changes": "needs changes" },
|
||||
"nothingYet": "Nothing is marked complete until you approve.",
|
||||
"gate": { "id": "signoff", "authoritative": true }
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
Posted with `--wait`. `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, update the report, 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 — read
|
||||
`building-review.md`.
|
||||
|
||||
`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. A later phase in the same session asks with a new id
|
||||
(`signoff-phase-2`, its title naming the phase, "Approve Phase 2", so the rail tells
|
||||
the two apart), since the last phase's approved card is a record: the same
|
||||
id posted again would only edit that record.
|
||||
|
||||
---
|
||||
|
||||
## 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-finish.md`
|
||||
says, and `stop`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"settle": true,
|
||||
"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",
|
||||
"commit": true,
|
||||
"dashboard": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`"commit": true` is there because the body prints a git command: the finished
|
||||
screen gets a **Commit it now** button, and its `__commit` press is handled as
|
||||
`console-finish.md` says (resume as `git` and open its commit flow, same
|
||||
session). Leave it out when the body prints no commit.
|
||||
|
||||
`finish.command` is the next pipeline step, the same one the terminal names:
|
||||
the next `/plan2code-3-implement specs/<feature>/overview.md`, or
|
||||
`/plan2code-4-finalize specs/<feature>/overview.md` 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.
|
||||
|
||||
`run` gives the approved phase its final score on the session meter
|
||||
(`console-meter.md`), 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. A review run on the page after a build reports its
|
||||
own (`building-review.md`).
|
||||
|
||||
---
|
||||
|
||||
## Implement + Review (`implement-review`)
|
||||
|
||||
The same build, then Stage 2 publishes the findings exactly as
|
||||
`building-review.md` → The findings (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" }`: 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.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Init and Init Update on the Web Console
|
||||
|
||||
Workflow notes for `init` and `init-update`, part of the web console contract
|
||||
(`console.md`).
|
||||
|
||||
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 (or as a `file` block:
|
||||
`{ "id": "body", "file": "AGENTS.md" }`, instead of pasting it). 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.
|
||||
@@ -0,0 +1,76 @@
|
||||
# Pathfinder on the Web Console
|
||||
|
||||
Workflow notes for `pathfinder`, part of the web console contract (`console.md`).
|
||||
|
||||
- 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/<idea>"` when the folder is created
|
||||
(`console-stop.md` → Saying what stopping would cost).
|
||||
- The fresh-idea card carries `"templates": "idea"` (`console.md` → The kinds).
|
||||
- A doc that is a file exactly as written (the map once it is on disk, a
|
||||
brief) goes up as a `file` block (`{ "id": "body", "file":
|
||||
"specs/<idea>/pathfinder/map.md" }`) rather than pasted. Keep `md` blocks
|
||||
where a block's `assumed` / `draft` state carries meaning.
|
||||
- Chart Step 8's research subagents must all report back before the
|
||||
finish (`console-finish.md` → 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 (`console-subagents.md` → 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<issue-number>`) as each research
|
||||
subagent reports back, or when you resolve a `research` question yourself
|
||||
(`console-meter.md`). 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.
|
||||
|
||||
## Briefs
|
||||
|
||||
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 <YYYY-MM-DD>` 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, as a `file` block on the file you wrote:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"docs": [{
|
||||
"id": "brief",
|
||||
"title": "Brief",
|
||||
"note": "Covers this week",
|
||||
"blocks": [{ "id": "body", "file": "specs/<idea>/pathfinder/briefs/<the brief>.md" }]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
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 Download 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; its version moves up by itself.
|
||||
|
||||
Say in chat where the file went, as you always would. The page is a second copy
|
||||
for reading and printing, never the record.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Planning on the Web Console
|
||||
|
||||
Workflow notes for `plan`, part of the web console contract (`console.md`).
|
||||
|
||||
- Open with `--workflow plan`, first thing. Every question and sign-off gate
|
||||
goes through the page, phase breakdowns as an editable `list`.
|
||||
- The fresh-idea card carries `"templates": "idea"` (`console.md` → The kinds).
|
||||
- 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": ""` (`console-stop.md`).
|
||||
- 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.
|
||||
@@ -0,0 +1,90 @@
|
||||
# Quick Task on the Web Console
|
||||
|
||||
Workflow notes for `quick-task`, part of the web console contract
|
||||
(`console.md`). Read `building.md` first.
|
||||
|
||||
## Quick task (`quick-task`)
|
||||
|
||||
- Open with the first clarifying question. Clarifying questions go out as
|
||||
`text` or `choice`, at most three at a time. The first, asking what to build,
|
||||
carries `"templates": "idea"` (`console.md` → The kinds).
|
||||
- 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 titled "Plan", one block per section, with the
|
||||
Steps written as a checklist so the build can tick them in place, and a
|
||||
`review` item "Build this plan?" (`"doc": "plan"`) with verdicts `yes`
|
||||
("Build it"), `modify` ("Change the plan"), `escalate` ("Plan it properly
|
||||
instead") and `abort` ("Stop here", `"danger": true`):
|
||||
|
||||
```jsonc
|
||||
{ "id": "plan", "title": "Plan", "blocks": [
|
||||
{ "id": "summary", "state": "settled", "md": "## Summary\n\n..." },
|
||||
{ "id": "files", "state": "settled", "md": "## Files to change\n\n- `src/a.ts` - ..." },
|
||||
{ "id": "steps", "state": "settled", "md": "## Steps\n\n- [ ] **1.** Step one\n- [ ] **2.** Step two\n- [ ] **3.** Step three\n- [ ] **4.** Step four" },
|
||||
{ "id": "verify", "state": "settled", "md": "## Verify\n\n- [ ] ..." }
|
||||
]}
|
||||
```
|
||||
|
||||
A `modify` reposts the changed blocks, Steps still a checklist; the version
|
||||
moves up by itself.
|
||||
- **Building** after `yes`: the Plan tab is the build's live task list, the
|
||||
way an Implement phase has its tasks tab. There is no separate progress tab.
|
||||
Settle the verdict (`"settle": true`) in the post that starts the build; the
|
||||
plan's steps are the tasks and `total` is their number:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"stopWarning": "",
|
||||
"settle": true,
|
||||
"headline": { "stage": "Building", "cleared": 0, "total": 4 },
|
||||
"agent": { "status": "working", "activity": "Task 1 of 4: step one", "quietMinutes": 10 }
|
||||
}
|
||||
```
|
||||
|
||||
Then post after every step, as `building.md` → While you build says, in the
|
||||
same breath as finishing it: repost the plan's `steps` block alone (blocks
|
||||
merge by id, so Summary, Files and Verify stay as they are) with that step
|
||||
ticked; raise `headline.cleared`; set `agent.activity` to the next step
|
||||
("Task 2 of 4: step two"). The plan lives only on the page, so this block is
|
||||
`md`, not `file`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "cleared": 1 },
|
||||
"docs": [{ "id": "plan", "blocks": [
|
||||
{ "id": "steps", "state": "settled", "md": "## Steps\n\n- [x] **1.** Step one\n- [ ] **2.** Step two\n- [ ] **3.** Step three\n- [ ] **4.** Step four" }
|
||||
]}],
|
||||
"agent": { "activity": "Task 2 of 4: step two" }
|
||||
}
|
||||
```
|
||||
|
||||
A step that cannot be done is `- [!]` with the reason after it, and is not
|
||||
counted in `cleared`. A step added mid-build goes into the list and raises
|
||||
`headline.total` in the same post. Tick each step the moment it is done,
|
||||
never in a batch at the end: the person is watching the Plan tab fill in.
|
||||
Check for a Quick question between steps, and do not call `wait` until the
|
||||
build is done. Tick the Verify block's boxes too as the checks pass, in the
|
||||
post that reports them.
|
||||
- **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 — `"commit": true` (the **Commit it now** button;
|
||||
`console-finish.md`) and `"dashboard": true`, so the finished screen
|
||||
also offers **Back to the dashboard**. Review and dashboard 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 `building-review.md`.
|
||||
- **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
|
||||
|
||||
See `building.md` → Stop requests during a build.
|
||||
@@ -0,0 +1,34 @@
|
||||
# Review on the Web Console
|
||||
|
||||
Workflow notes for `review`, part of the web console contract (`console.md`).
|
||||
A review run from a build's review button stays in the build's session, under
|
||||
its workflow: `building-review.md` governs it instead.
|
||||
|
||||
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-review.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 (`"settle": true`) 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 <sid> --no-open --workflow review`), never a fresh
|
||||
`open`.
|
||||
|
||||
Review Mode's closing gate ("Reply approved to commit, or request changes")
|
||||
is a `review` item titled "Check the fixes", `doc: "report"`, `"nothingYet":
|
||||
false` (the fixes are already on disk), verdicts `approve` and `changes`.
|
||||
|
||||
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; with one, `"commit": true` puts **Commit it
|
||||
now** beside it. 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).
|
||||
@@ -0,0 +1,18 @@
|
||||
# Revision on the Web Console
|
||||
|
||||
Workflow notes for `revise-plan`, part of the web console contract (`console.md`).
|
||||
|
||||
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`), `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/<feature>` to `open`, or
|
||||
post `specDir` once you know it. The finish command is
|
||||
`/plan2code-3-implement specs/<feature>/overview.md`; an abort's is
|
||||
`/plan2code-1b-revise-plan specs/<feature>/overview.md`.
|
||||
@@ -3,7 +3,7 @@
|
||||
// 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
|
||||
// this is a copy, and a drift test in scripts/test-web-console-logic.mjs fails the
|
||||
// moment the launcher's picker changes without it. The prompt is a parameter
|
||||
// here rather than the launcher's constant.
|
||||
//
|
||||
|
||||
@@ -40,6 +40,18 @@ export function recordedAnswer(item) {
|
||||
return { ...(s || {}), ...(a || {}) };
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the agent wrote in the item's thread after the person's last send
|
||||
* and has not settled it: the question is being asked again, so what they sent
|
||||
* belongs back on the form rather than gone.
|
||||
*/
|
||||
export function agentRepliedAfterSend(item) {
|
||||
const s = item && item.submitted;
|
||||
if (!s || typeof s !== "object" || (item.answer && typeof item.answer === "object")) return false;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
return thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
}
|
||||
|
||||
/**
|
||||
* A send the person made that the agent never settled, still sitting on an
|
||||
* OPEN question.
|
||||
@@ -103,10 +115,19 @@ export function threadText(m) {
|
||||
|
||||
/* -------------------------------------------------------------- labels */
|
||||
|
||||
// A key worth showing: one or two letters or digits (A, 2) a person can say
|
||||
// back in the terminal. A word key (commit-first, yes) is an id for the agent,
|
||||
// and as a chip beside its own label it is noise.
|
||||
export function showKey(k, text) {
|
||||
if (k == null) return false;
|
||||
const key = String(k);
|
||||
return /^[A-Za-z0-9]{1,2}$/.test(key) && key.toLowerCase() !== String(text || "").trim().toLowerCase();
|
||||
}
|
||||
|
||||
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;
|
||||
return showKey(o.k, o.text) ? `${o.k} · ${o.text}` : o.text;
|
||||
}
|
||||
|
||||
export function verdictLabel(item, id) {
|
||||
@@ -247,7 +268,7 @@ export const WORKFLOW_LABEL = {
|
||||
"quick-task": "Quick task",
|
||||
finalize: "Wrapping up",
|
||||
handoff: "Handoff",
|
||||
"git-commit": "Git commit",
|
||||
git: "Git",
|
||||
changelog: "Changelog",
|
||||
};
|
||||
|
||||
@@ -273,7 +294,7 @@ export const CONSOLE_WORKFLOWS = [
|
||||
"/plan2code-review",
|
||||
"/plan2code-4-finalize",
|
||||
"/plan2code-handoff",
|
||||
"/plan2code-git-commit",
|
||||
"/plan2code-git",
|
||||
"/plan2code-changelog",
|
||||
];
|
||||
|
||||
@@ -383,14 +404,16 @@ const HOME_TITLES = {
|
||||
* 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 } = {}) {
|
||||
export function homeButtonState({ workflow, finished = false, stopping = false, homeward = false, adrift = false, warned = 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.",
|
||||
// With a stop warning up, the work since the last save is what leaving
|
||||
// loses: the tooltip says so rather than promising a saved place.
|
||||
title: gate ? HOME_TITLES[gate] : warned ? "Back to the dashboard. Work since the last save is not kept." : "Back to the dashboard. Your place is saved first.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -438,8 +461,8 @@ export function resumeCommand({ workflow, specDir } = {}) {
|
||||
return withOverview("/plan2code-4-finalize");
|
||||
case "handoff":
|
||||
return "/plan2code-handoff";
|
||||
case "git-commit":
|
||||
return "/plan2code-git-commit";
|
||||
case "git":
|
||||
return "/plan2code-git";
|
||||
case "changelog":
|
||||
return "/plan2code-changelog";
|
||||
default:
|
||||
@@ -456,7 +479,7 @@ 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.";
|
||||
export const COMMIT_REPLY = "Commit what was just built: start Git commit, right here in this session.";
|
||||
export const COMMIT_REPLY = "Commit what was just built: open Git's commit flow, 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.
|
||||
@@ -475,7 +498,7 @@ export function dashboardOffer(fin) {
|
||||
/**
|
||||
* Whether a finish offers to commit what was just built from this page. The
|
||||
* agent opts in with `finish.commit: true` on a build that ended with a git
|
||||
* command; the press starts Git commit in the same session, as the dashboard's
|
||||
* command; the press starts Git's commit flow in the same session, as the dashboard's
|
||||
* card does. A pause never offers it.
|
||||
*/
|
||||
export function commitOffer(fin) {
|
||||
@@ -495,6 +518,16 @@ export function reviewOffer(fin) {
|
||||
return { label: label || "Review what was just built" };
|
||||
}
|
||||
|
||||
/**
|
||||
* One offer button on a finish (review, done, commit, dashboard). A press of
|
||||
* any of them is the session's one answer, so it locks every button until the
|
||||
* finish goes away, not just until the agent collects the send: `asked` is
|
||||
* the pressed one, which keeps its "requested…" label.
|
||||
*/
|
||||
export function afterFinishButton(afterBuild, kind, pendingResult) {
|
||||
return { asked: afterBuild === kind, disabled: Boolean(afterBuild) || Boolean(pendingResult) };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- the dashboard */
|
||||
|
||||
// The skills the dashboard offers, in the order it offers them. The page owns
|
||||
@@ -666,18 +699,18 @@ export const SKILL_CATALOG = [
|
||||
title: "Changelog",
|
||||
blurb: "Checks the CHANGELOG version against the main branch and suggests entries for what is new.",
|
||||
about:
|
||||
"Works out the right version from the default branch, then compares your branch with the latest CHANGELOG entry and suggests the entries it is missing. You edit them before anything is written, it keeps package.json in step, and it offers to run Git commit next. If the newest version is not released or on another branch yet, it adds to that entry instead of starting a new one.",
|
||||
"Works out the right version from the default branch, then compares your branch with the latest CHANGELOG entry and suggests the entries it is missing. You edit them before anything is written, it keeps package.json in step, and it offers to commit the result in Git. If the newest version is not released or on another branch yet, it adds to that entry instead of starting a new one.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-git-commit",
|
||||
command: "/plan2code-git-commit",
|
||||
workflow: "git-commit",
|
||||
skill: "plan2code-git",
|
||||
command: "/plan2code-git",
|
||||
workflow: "git",
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Git commit",
|
||||
blurb: "Commits your changes with a clear message, suggests a split when it is really two jobs, and offers to push.",
|
||||
title: "Git",
|
||||
blurb: "Branches, pull, push and commits on one board that stays open while you work.",
|
||||
about:
|
||||
"Reads what changed and drafts the commit message for you to approve. On the main branch it offers a new one first, and when the work is really two jobs it suggests splitting it into separate commits. It asks before every commit and every push, and never force-pushes.",
|
||||
"Shows your branch, what is ahead or behind, and every local and remote branch. Switch, create, delete or clean up branches, pull (rebasing when they have split, with help on conflicts), push or publish, and commit with a clear message. It asks before every push, publish and delete, and never force-pushes.",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -701,7 +734,7 @@ export const START_POSES = [
|
||||
"quick-task",
|
||||
"review",
|
||||
"handoff",
|
||||
"git-commit",
|
||||
"git",
|
||||
"changelog",
|
||||
];
|
||||
|
||||
@@ -743,7 +776,6 @@ const NEXT_FOR_STATE = {
|
||||
|
||||
const ON = { on: true };
|
||||
export const GIT_INIT_NOTE = "Not a git repository yet: it offers to start one";
|
||||
export const GIT_CLEAN_REASON = "Nothing to commit: no changed or new files";
|
||||
export const pendingNote = (n) => `${n} file${n === 1 ? "" : "s"} to commit`;
|
||||
const off = (reason) => ({ on: false, reason });
|
||||
|
||||
@@ -775,12 +807,10 @@ export function cardAvailability(entry, scan, sel) {
|
||||
case "plan2code-handoff":
|
||||
case "plan2code-changelog":
|
||||
return ON;
|
||||
case "plan2code-git-commit":
|
||||
case "plan2code-git":
|
||||
// Never greyed: a clean tree still has branches to switch, pull and push.
|
||||
if (scan && scan.isGit === false) return { on: true, note: GIT_INIT_NOTE };
|
||||
// `pending` is null when git could not say: stay clickable then.
|
||||
if (scan && scan.isGit && Number.isInteger(scan.pending)) {
|
||||
return scan.pending === 0 ? off(GIT_CLEAN_REASON) : { on: true, note: pendingNote(scan.pending) };
|
||||
}
|
||||
if (scan && Number.isInteger(scan.pending) && scan.pending > 0) return { on: true, note: pendingNote(scan.pending) };
|
||||
return ON;
|
||||
case "plan2code-0-pathfinder":
|
||||
if (!state || state === "exploring") return { ...ON, next };
|
||||
@@ -982,6 +1012,13 @@ export function noteAction(id, text, attachments) {
|
||||
return action;
|
||||
}
|
||||
|
||||
// Typed text past its first line, indented, so only a real entry ever starts a
|
||||
// reply line: a typed "Idea name: foo" or " Image: C:\x" must not read as an
|
||||
// answer or an attachment. Chat's lines already do this.
|
||||
export function indentReply(text, pad = " ") {
|
||||
return String(text).replace(/\r?\n/g, "\n" + pad);
|
||||
}
|
||||
|
||||
// A note as `reply` lines, one indented `Image:` or `File:` line per
|
||||
// attachment in the order attached, so the agent can open each path with its
|
||||
// file-read tool. An image-only note reads exactly as it always did.
|
||||
@@ -990,7 +1027,7 @@ export function noteReplyLines(title, text, attachments) {
|
||||
const anyFile = list.some((a) => attachmentKind(a) === "file");
|
||||
const said = text || (list.length ? (anyFile ? "(attachments only)" : "(images only)") : "");
|
||||
return [
|
||||
`Note on ${title}: ${said}`,
|
||||
`Note on ${title}: ${indentReply(said)}`,
|
||||
...list.map((a) => ` ${attachmentKind(a) === "file" ? "File" : "Image"}: ${a.path} (${a.name})`),
|
||||
];
|
||||
}
|
||||
|
||||
+223
-28
@@ -303,6 +303,12 @@ h1 {
|
||||
|
||||
.progress-block { flex: 1 1 260px; min-width: 200px; max-width: 460px; margin-left: auto; }
|
||||
|
||||
/* When the progress block is hidden (the dashboard, the git board) nothing
|
||||
grows to fill the row, so the icon buttons would sit beside the title. The
|
||||
first takes the slack instead; with the block shown its flex already eats
|
||||
the space, so this costs nothing. */
|
||||
#btn-about { margin-left: auto; }
|
||||
|
||||
.progress-label {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
@@ -690,13 +696,13 @@ h1 {
|
||||
}
|
||||
.wake.dormant .wake-hint { opacity: 1; }
|
||||
|
||||
/* Skip: muted, bottom right, so it never competes with the animation. */
|
||||
/* Skip: bottom right, out of the animation's way but big enough to find. */
|
||||
.wake-skip {
|
||||
position: absolute; right: 14px; bottom: 14px;
|
||||
padding: 4px 12px; border: 1px solid var(--ink-3); border-radius: 4px;
|
||||
background: transparent; color: var(--ink-3);
|
||||
font: inherit; font-size: 0.8rem; letter-spacing: 0.08em; text-transform: uppercase;
|
||||
cursor: pointer; opacity: 0.7;
|
||||
position: absolute; right: 24px; bottom: 24px;
|
||||
min-width: 120px; padding: 10px 26px; border: 1.5px solid var(--ink-2); border-radius: 6px;
|
||||
background: var(--panel-2); color: var(--ink-2);
|
||||
font: inherit; font-size: 1rem; font-weight: 600; letter-spacing: 0.1em; text-transform: uppercase;
|
||||
cursor: pointer; opacity: 0.9;
|
||||
}
|
||||
.wake-skip:hover, .wake-skip:focus-visible { opacity: 1; color: var(--ink); border-color: var(--ink); }
|
||||
|
||||
@@ -878,6 +884,11 @@ h1 {
|
||||
padding: 6px 13px;
|
||||
border-radius: 99px;
|
||||
cursor: pointer;
|
||||
/* A doc titled with a sentence keeps the tab row to one line. */
|
||||
max-width: 22ch;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.view-tab:hover { background: var(--panel-2); color: var(--ink); }
|
||||
.view-tab[aria-current="true"] {
|
||||
@@ -947,12 +958,20 @@ h1 {
|
||||
padding-right: 32px;
|
||||
}
|
||||
|
||||
/* The column itself never scrolls; the card does. */
|
||||
/* The column itself never scrolls; the card does. The git board is the one
|
||||
exception, below: it stacks a card over the board, so the column takes the
|
||||
scroll there and both flow through it at natural height. */
|
||||
.main > .card:not(.is-primary) { flex-shrink: 100; min-height: 104px; }
|
||||
.main > .card.is-primary { flex-shrink: 1; min-height: 0; }
|
||||
/* A card with a growing answer box takes the column's full height above the
|
||||
pager, and still scrolls its own contents. app.js sizes the box to fill it. */
|
||||
.main > .card.is-primary.has-grow { flex: 1 1 auto; }
|
||||
/* More below the fold (app.js markMore): the bottom edge fades, so a card
|
||||
cut by the window never reads as finished. */
|
||||
.main > .card.has-more {
|
||||
-webkit-mask-image: linear-gradient(to bottom, #000 calc(100% - 56px), transparent);
|
||||
mask-image: linear-gradient(to bottom, #000 calc(100% - 56px), transparent);
|
||||
}
|
||||
.pager { flex: none; }
|
||||
|
||||
/* A document is read top to bottom and has no pinned furniture, so it goes back
|
||||
@@ -1069,7 +1088,7 @@ h1 {
|
||||
}
|
||||
.ask-about-chip > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ask-about-chip .attach-remove { position: static; flex: none; }
|
||||
.ask-actions { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
|
||||
.ask-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-top: 8px; }
|
||||
/* + Add context and its menu. It opens upward, over the list: the composer
|
||||
sits at the bottom of a pane that clips anything hanging below it. */
|
||||
.ask-context { position: relative; }
|
||||
@@ -1754,6 +1773,7 @@ input[type="text"].invalid { border-color: var(--warn); }
|
||||
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
||||
.btn.ghost:hover { background: var(--panel-2); color: var(--ink); }
|
||||
.btn.danger { border-color: var(--warn); color: var(--warn); }
|
||||
.btn.danger.is-on { background: var(--warn); color: #fff; }
|
||||
.btn.small { padding: 7px 13px; font-size: 13.5px; }
|
||||
/* Available, but not the step. Reads as a button, does not shout like one. */
|
||||
.btn.standby {
|
||||
@@ -1954,7 +1974,10 @@ input[type="text"].invalid { border-color: var(--warn); }
|
||||
|
||||
/* ----------------------------------------------------------- markdown */
|
||||
|
||||
.md { max-width: 68ch; }
|
||||
/* A word or path longer than the line breaks instead of widening the page;
|
||||
code blocks and tables keep their own scroll. */
|
||||
.md { max-width: 68ch; overflow-wrap: anywhere; }
|
||||
.md pre, .md .md-table { overflow-wrap: normal; }
|
||||
.md-h { font-family: var(--serif); font-weight: 600; margin: 22px 0 9px; line-height: 1.25; }
|
||||
h2.md-h { font-size: 21px; }
|
||||
h3.md-h { font-size: 17.5px; }
|
||||
@@ -1964,9 +1987,12 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
.md-li { margin-bottom: 5px; }
|
||||
.md-task { display: inline-block; width: 16px; color: var(--ink-3); font-weight: 700; }
|
||||
.md-task.is-done { color: var(--ok); }
|
||||
.md-task.is-blocked { color: var(--warn); }
|
||||
.md-task.is-doing { color: var(--accent); }
|
||||
.md-task.is-assumed { color: var(--stage); }
|
||||
.md-li.is-task {
|
||||
list-style: none; margin-left: -18px;
|
||||
display: grid; grid-template-columns: 16px 1fr; column-gap: 4px; align-items: baseline;
|
||||
display: grid; grid-template-columns: 16px minmax(0, 1fr); column-gap: 4px; align-items: baseline;
|
||||
}
|
||||
.md-li.is-task > :not(.md-task) { grid-column: 2; }
|
||||
.md-li.is-task > .md-p:last-child { margin-bottom: 0; }
|
||||
@@ -2000,23 +2026,17 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
transition: opacity 0.12s;
|
||||
}
|
||||
.md-pre-wrap:hover .md-copy, .md-copy:focus { opacity: 1; }
|
||||
/* Run it, on git blocks: Copy's twin, tucked under it so the wider
|
||||
"Press Ctrl+C" fallback label can never collide. */
|
||||
.md-run {
|
||||
position: absolute; top: 34px; right: 8px;
|
||||
font: 600 11.5px var(--sans);
|
||||
background: var(--panel); color: var(--ink-2);
|
||||
border: 1px solid var(--rule-2); border-radius: 6px;
|
||||
padding: 4px 9px; cursor: pointer; opacity: 0;
|
||||
transition: opacity 0.12s;
|
||||
}
|
||||
.md-pre-wrap:hover .md-run, .md-run:focus { opacity: 1; }
|
||||
/* The muted nudge on other command-looking blocks, a caption under the block. */
|
||||
/* The muted nudge on command-looking blocks, a caption under the block. */
|
||||
.md-run-hint {
|
||||
margin: -6px 2px 0;
|
||||
margin: 4px 2px 0;
|
||||
font: 11px var(--sans); color: var(--ink-3);
|
||||
opacity: 0.8;
|
||||
}
|
||||
/* No "paste it into the Ask tab" nudge where the command is the card's own
|
||||
action (a confirm's consequences, a finished screen's commit beside its
|
||||
Commit it now button). */
|
||||
.is-consequences .md-run-hint,
|
||||
.handoff .md-run-hint { display: none; }
|
||||
.md-hr { border: 0; border-top: 1px solid var(--rule); margin: 20px 0; }
|
||||
.md-table-wrap { overflow-x: auto; margin: 0 0 13px; }
|
||||
.md-table { border-collapse: collapse; width: 100%; font-size: 13.5px; }
|
||||
@@ -2065,6 +2085,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
.footer.is-dash .footer-summary,
|
||||
.footer.is-dash .footer-actions { display: none; }
|
||||
.footer.is-dash .footer-where { grid-column: 2; }
|
||||
.footer.is-dash-done .footer-actions { display: none; }
|
||||
.hint { font-size: 12.5px; color: var(--ink-3); display: flex; align-items: center; gap: 7px; }
|
||||
/* A label, not a sentence: the full reason rides in the hint's tooltip, and
|
||||
the dock already carries the ticking clock this would otherwise repeat. */
|
||||
@@ -2165,6 +2186,9 @@ button.waiting-jump:hover { text-decoration-color: var(--accent); }
|
||||
.icon-btn:hover .ab-dot { fill: var(--accent); }
|
||||
|
||||
a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
/* A link in a dialog (the update modal's release, Help's version) keeps the
|
||||
accent once visited: the browser's purple is unreadable on the dark theme. */
|
||||
.modal a:not(.btn), .modal a:not(.btn):visited { color: var(--accent); }
|
||||
.icon-btn .mg-body { fill: none; stroke: var(--ink-3); stroke-width: 1.4; stroke-linejoin: round; }
|
||||
.icon-btn .mg-line { fill: none; stroke: var(--ink-2); stroke-width: 1.4; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.icon-btn:hover .mg-body, .icon-btn:hover .mg-line { stroke: var(--accent); }
|
||||
@@ -2629,6 +2653,14 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
@media (max-width: 720px) {
|
||||
.looks-row { grid-template-columns: 1fr; }
|
||||
}
|
||||
/* User Preferences itself (not the dialogs borrowing .looks): wider, and only
|
||||
the body scrolls, so Back to default and Done never leave the screen. */
|
||||
.modal.prefs { max-width: 880px; }
|
||||
.modal.prefs[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
||||
.prefs-body { overflow-y: auto; min-height: 0; flex: 1 1 auto; margin-right: -12px; padding-right: 12px; padding-top: 10px; }
|
||||
/* A line scrolled up under the title fades out rather than being sliced. */
|
||||
.prefs-body { -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 12px); mask-image: linear-gradient(to bottom, transparent 0, #000 12px); }
|
||||
.modal.prefs .modal-actions { flex: none; margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--rule); }
|
||||
|
||||
/* The Workspace dialog: one entry per folder, the original first, then the
|
||||
Add row. Wide enough for a real path; the list scrolls, the Add row and the
|
||||
@@ -2972,13 +3004,14 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid var(--rule);
|
||||
}
|
||||
/* Wraps at the dashes rather than cut off: a command missing its end
|
||||
("/plan2code-3-implement-revi…") is no command at all. */
|
||||
.dash-card-cmd {
|
||||
font-family: var(--mono);
|
||||
font-size: 11.5px;
|
||||
color: var(--ink-3);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dash-card-go { color: var(--accent); font-weight: 700; transition: transform 0.15s ease; }
|
||||
.dash-card:hover:not(:disabled) .dash-card-go { transform: translateX(3px); }
|
||||
@@ -3474,8 +3507,8 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
100% { transform: translateX(8px); opacity: 0; }
|
||||
}
|
||||
|
||||
/* Git commit -- the arm reaches out and a new commit settles onto the branch
|
||||
line in step with it. */
|
||||
/* Git -- the arm reaches out and a new commit settles onto the branch line in
|
||||
step with it. */
|
||||
.pose .gc-reach { transform-origin: 0% 50%; animation: gc-reach 2.4s ease-in-out infinite; }
|
||||
@keyframes gc-reach {
|
||||
0%, 100% { transform: scaleX(0.9); }
|
||||
@@ -3616,3 +3649,165 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
}
|
||||
.status-help:hover { text-decoration-thickness: 2px; }
|
||||
.status-help:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 3px; }
|
||||
|
||||
/* ------------------------------------------------------------ git board */
|
||||
|
||||
/* The git workflow's main column stacks two things where every other view
|
||||
holds one: the agent's card on top and the board under it. Stacked children
|
||||
that each scrolled would put a scrollbar inside a scrollbar, so here the
|
||||
column takes the one scroll and both flow through it at natural height. */
|
||||
.main:has(> .git-board) {
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
/* Listed with .is-primary.has-grow too: that rule (a card with a growing note
|
||||
box takes the column's height and shrinks into it) outranks a plain .card
|
||||
here, and a card shrunk under the board spilled its buttons beneath it. */
|
||||
.main:has(> .git-board) > .card,
|
||||
.main:has(> .git-board) > .card.is-primary.has-grow,
|
||||
.main:has(> .git-board) > .git-board {
|
||||
flex: none;
|
||||
overflow-y: visible;
|
||||
min-height: 0;
|
||||
}
|
||||
/* Over the board a card's boxes cannot fill the column (it flows, it does not
|
||||
stretch), so a note box grows with what is typed instead, where the browser
|
||||
can, rather than scrolling inside a 96px box. */
|
||||
.main:has(> .git-board) > .card textarea { field-sizing: content; max-height: 50vh; }
|
||||
.main > .git-board {
|
||||
padding-right: 32px;
|
||||
display: grid;
|
||||
/* minmax(0, …): the column never takes the branch table's no-wrap width. */
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
align-content: start;
|
||||
gap: 14px;
|
||||
max-width: var(--card-width);
|
||||
}
|
||||
/* The board's header is a section lead, not a second card: the agent's card
|
||||
above is the column's only framed element. */
|
||||
.git-head {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
padding: 0 0 10px;
|
||||
border-bottom: 1px solid var(--rule);
|
||||
}
|
||||
.git-head-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px 14px; }
|
||||
.git-branch { margin: 0; font: 600 22px/1.2 var(--serif); overflow-wrap: anywhere; }
|
||||
.git-track { font-family: var(--mono); font-size: 14px; color: var(--ink-2); }
|
||||
.git-head-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; font-size: 13.5px; color: var(--ink-2); }
|
||||
.git-noremote { font-weight: 600; color: var(--stage); }
|
||||
.git-activity { color: var(--accent); }
|
||||
.git-pr { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding-top: 6px; border-top: 1px solid var(--rule); }
|
||||
.git-pr-open { text-decoration: none; }
|
||||
.git-pr-ask { font-size: 14px; color: var(--ink); }
|
||||
.git-pr-base { font-size: 13.5px; color: var(--ink-2); }
|
||||
.git-pr-base select, .git-field select, .git-field input, .git-search {
|
||||
font: inherit;
|
||||
font-size: 14px;
|
||||
padding: 6px 10px;
|
||||
color: var(--ink);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.git-warn, .git-op {
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--warn);
|
||||
border-left-width: 4px;
|
||||
border-radius: var(--radius);
|
||||
background: var(--warn-soft);
|
||||
color: var(--ink);
|
||||
}
|
||||
.git-op { display: grid; gap: 8px; border-color: var(--stage); background: var(--stage-soft); }
|
||||
.git-op-files { margin: 0; padding-left: 20px; font-size: 13.5px; }
|
||||
.git-op-left { color: var(--warn); }
|
||||
.git-op-clear { color: var(--ok); }
|
||||
.git-op-actions, .git-panel-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.git-note { margin: 0; color: var(--ink-2); }
|
||||
.git-result {
|
||||
padding: 10px 16px;
|
||||
border: 1px solid var(--accent-line);
|
||||
border-radius: var(--radius);
|
||||
background: var(--accent-soft);
|
||||
font-size: 14px;
|
||||
}
|
||||
.git-result-body .md-p { margin: 4px 0 0; }
|
||||
/* The result box is the line length here: git's stderr runs the full width. */
|
||||
.git-result-body.md { max-width: none; }
|
||||
/* Pinned to the pane's bottom while the board scrolls past: the column is
|
||||
the scroller on this view, and the bar is the board's last child, so
|
||||
bottom: 0 holds it on screen until the board's end comes up to dock it.
|
||||
Opaque so the table slips underneath, bordered so the seam reads. */
|
||||
.git-bar {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
z-index: 6;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
padding: 10px 0 8px;
|
||||
background: var(--bg);
|
||||
border-top: 1px solid var(--rule);
|
||||
}
|
||||
.git-done { margin-left: auto; }
|
||||
.git-panel {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
padding: 14px 18px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--accent-line);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
.git-panel-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.git-panel-title { margin: 0; font-size: 16px; }
|
||||
.git-group-title { margin: 4px 0 0; font-size: 13.5px; color: var(--ink-2); }
|
||||
.git-field-row { display: flex; flex-wrap: wrap; align-items: end; gap: 10px; }
|
||||
.git-field { display: grid; gap: 4px; font-size: 13px; color: var(--ink-2); }
|
||||
.git-field.is-wide { flex: 1 1 16em; }
|
||||
.git-new-name { font-family: var(--mono); }
|
||||
.git-name-status { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 0; font-size: 13.5px; color: var(--ink-2); }
|
||||
.git-name-status.is-free { color: var(--ok); }
|
||||
.git-name-status.is-invalid, .git-name-status.is-nested { color: var(--warn); }
|
||||
.git-name-status.is-local, .git-name-status.is-remote { color: var(--stage); }
|
||||
.git-offer { margin: 0 auto 0 0; font-size: 14px; }
|
||||
.git-sweep { margin: 0; padding: 0; list-style: none; display: grid; gap: 4px; font-family: var(--mono); font-size: 13.5px; }
|
||||
.git-ignore { margin-left: 8px; white-space: nowrap; }
|
||||
.git-tools { display: flex; gap: 8px; align-items: center; margin-bottom: 8px; }
|
||||
.git-search { flex: 1 1 auto; }
|
||||
.git-branches { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; }
|
||||
.git-table-wrap { overflow-x: auto; }
|
||||
.git-table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
|
||||
.git-table th {
|
||||
text-align: left;
|
||||
font-size: 11.5px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
color: var(--ink-3);
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--rule);
|
||||
}
|
||||
.git-table td { padding: 7px 8px; border-bottom: 1px solid var(--rule); vertical-align: top; }
|
||||
.git-table tr.is-current td { background: var(--accent-soft); }
|
||||
.git-table tr.is-held td { color: var(--ink-2); }
|
||||
.git-cell-name { overflow-wrap: anywhere; }
|
||||
/* A branch name stays whole beside its badges (feature/export-csv never splits
|
||||
as feature/export- / csv), and the headers stay on one line: a narrow column
|
||||
scrolls the table sideways instead. */
|
||||
.git-cell-name .git-name { white-space: nowrap; }
|
||||
.git-table th { white-space: nowrap; }
|
||||
.git-name, .git-path { font-family: var(--mono); }
|
||||
.git-badge { margin-left: 6px; font-size: 10px; padding: 2px 6px; }
|
||||
.git-badge.is-merged { color: var(--ok); background: var(--ok-soft); border-color: var(--ok); }
|
||||
.git-badge.is-gone, .git-badge.is-held { color: var(--stage); background: var(--stage-soft); border-color: var(--stage); }
|
||||
.git-cell-track { font-family: var(--mono); white-space: nowrap; color: var(--ink-2); }
|
||||
/* Stacked with blocks, not `display: grid`: a grid <td> stops being a table
|
||||
cell, and its row's separator no longer lines up with the others. */
|
||||
.git-cell-last > span { display: block; }
|
||||
.git-cell-last > .git-by { margin-top: 2px; }
|
||||
.git-by { font-size: 12px; color: var(--ink-3); }
|
||||
.git-cell-actions { white-space: nowrap; text-align: right; }
|
||||
.git-cell-actions .btn + .btn { margin-left: 6px; }
|
||||
.git-remote-only summary { cursor: pointer; font-weight: 600; color: var(--ink-2); padding: 4px 0; }
|
||||
.git-empty { margin: 0; font-size: 13.5px; color: var(--ink-3); }
|
||||
+1282
-113
File diff suppressed because it is too large.
Load diff
@@ -31,7 +31,7 @@ function answeredFlags(messages) {
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const m = messages[i];
|
||||
if (m.from === "agent") replyLater = true;
|
||||
else if (m.kind === "message") flags.set(m.seq, replyLater);
|
||||
else if (m.kind === "message" || m.kind === "decision") flags.set(m.seq, replyLater);
|
||||
}
|
||||
return flags;
|
||||
}
|
||||
@@ -63,7 +63,7 @@ export function chatView(frameChat, ui = {}) {
|
||||
decided: decisions.get(m.id) || null,
|
||||
});
|
||||
} else if (m.kind === "decision") {
|
||||
rows.push({ kind: "decision", decision: m.decision, text: m.text || "", re: m.re });
|
||||
rows.push({ kind: "decision", decision: m.decision, text: m.text || "", re: m.re, done: Boolean(answered.get(m.seq)) });
|
||||
} else if (m.kind === "message") {
|
||||
const row = {
|
||||
kind: "person",
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
// Plan2Code Web Console - the git board's rules: branch order, names, buttons and replies.
|
||||
//
|
||||
// Everything the board decides from a state.git snapshot (git-repo.mjs ->
|
||||
// snapshot()) lives here so it is tested without a browser: how the branch
|
||||
// list is ordered and folded, whether a new branch name is free, which action
|
||||
// buttons show and which are enabled, the plain sentence each button sends
|
||||
// the agent, the "Last refreshed" line, which files start ticked in the
|
||||
// commit dialog and the pull-request link. app.js only renders what these
|
||||
// say. No DOM access at module scope and only one import: the page and
|
||||
// `node --test` both import this file.
|
||||
|
||||
import { prUrl } from "./pr-url.js";
|
||||
|
||||
export const BRANCH_TYPES = Object.freeze(["feature", "fix", "chore", "docs", "refactor", "test"]);
|
||||
export const REMOTE_FOLD = 50;
|
||||
// Matches under a search are capped too, or one fold draws thousands of rows.
|
||||
const QUERY_CAP = 200;
|
||||
export const UNTRACKED_TICK_LIMIT = 200;
|
||||
|
||||
export const PR_HOST_LABELS = Object.freeze({
|
||||
github: "GitHub",
|
||||
gitlab: "GitLab",
|
||||
bitbucket: "Bitbucket",
|
||||
azure: "Azure DevOps",
|
||||
none: "None",
|
||||
});
|
||||
|
||||
const list = (v) => (Array.isArray(v) ? v : []);
|
||||
const blank = (v) => typeof v !== "string" || v.trim() === "";
|
||||
|
||||
// Milliseconds of a row's last commit; -Infinity when missing or unreadable, so it sorts last.
|
||||
function lastTime(row) {
|
||||
const t = Date.parse(row && row.last && row.last.at);
|
||||
return Number.isNaN(t) ? -Infinity : t;
|
||||
}
|
||||
|
||||
const newestFirst = (a, b) => {
|
||||
const ta = lastTime(a);
|
||||
const tb = lastTime(b);
|
||||
if (ta === tb) return 0;
|
||||
return tb > ta ? 1 : -1;
|
||||
};
|
||||
|
||||
/** The local row for the checked-out branch, or null. */
|
||||
export function currentRow(git) {
|
||||
return list(git && git.branches).find((b) => b && b.current && !b.remote) || null;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ branches */
|
||||
|
||||
/**
|
||||
* `{ top, remoteOnly }`: local rows with the current branch first, then the
|
||||
* default branch (once, when it is also the current one), then the rest by
|
||||
* last commit, newest first; remote-only rows newest first. Never mutates.
|
||||
*/
|
||||
export function orderBranches(branches) {
|
||||
const rows = list(branches).filter(Boolean);
|
||||
const local = rows.filter((b) => !b.remote);
|
||||
const current = local.find((b) => b.current) || null;
|
||||
const def = local.find((b) => b.default && b !== current) || null;
|
||||
const rest = local.filter((b) => b !== current && b !== def).sort(newestFirst);
|
||||
const top = [...(current ? [current] : []), ...(def ? [def] : []), ...rest];
|
||||
const remoteOnly = rows.filter((b) => b.remote).sort(newestFirst);
|
||||
return { top, remoteOnly };
|
||||
}
|
||||
|
||||
/** Rows whose name, `remote/name` (remote-only rows) or last subject contain `query`, ignoring case. */
|
||||
export function filterBranches(rows, query) {
|
||||
if (blank(query)) return rows;
|
||||
const q = query.trim().toLowerCase();
|
||||
return list(rows).filter((b) => {
|
||||
const fields = [b.name, b.remote ? `${b.remote}/${b.name}` : "", b.last && b.last.subject];
|
||||
return fields.some((f) => typeof f === "string" && f.toLowerCase().includes(q));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The remote-only section: `{ shown, hidden, open }`. Without a query the
|
||||
* first REMOTE_FOLD rows show (all with showAll) and `hidden` counts the
|
||||
* rest; a query shows every match and opens the section.
|
||||
*/
|
||||
export function foldRemote(rows, { showAll = false, query = "" } = {}) {
|
||||
const all = list(rows);
|
||||
if (!blank(query)) {
|
||||
// A query also caps what it draws: a monorepo remote can match thousands.
|
||||
const matches = filterBranches(all, query);
|
||||
const shown = showAll ? matches : matches.slice(0, QUERY_CAP);
|
||||
return { shown, hidden: matches.length - shown.length, open: true };
|
||||
}
|
||||
const shown = showAll ? all.slice() : all.slice(0, REMOTE_FOLD);
|
||||
return { shown, hidden: all.length - shown.length, open: false };
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- new branch */
|
||||
|
||||
/** `<type>/<desc>`; "" with no description. */
|
||||
export function composeBranchName({ type, description } = {}) {
|
||||
const kind = blank(type) ? "feature" : type.trim();
|
||||
const desc = String(description || "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
return desc ? `${kind}/${desc}` : "";
|
||||
}
|
||||
|
||||
// The first rule `git check-ref-format --branch` would break, as a sentence; null when none.
|
||||
function refFormatProblem(name) {
|
||||
if (name === "@") return 'A branch cannot be named just "@".';
|
||||
// git refuses it as a branch name (git switch -c HEAD), as branch-check does.
|
||||
if (name === "HEAD") return 'A branch cannot be named "HEAD".';
|
||||
if (name.startsWith("-")) return "Branch names cannot start with a dash.";
|
||||
if (name.includes(" ")) return "Branch names cannot contain spaces.";
|
||||
if (name.includes("..")) return 'Branch names cannot contain "..".';
|
||||
if (name.includes("@{")) return 'Branch names cannot contain "@{".';
|
||||
if (name.includes("\\")) return "Branch names cannot contain a backslash.";
|
||||
const special = name.match(/[~^:?*[]/);
|
||||
if (special) return `Branch names cannot contain "${special[0]}".`;
|
||||
if ([...name].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127)) {
|
||||
return "Branch names cannot contain control characters.";
|
||||
}
|
||||
if (name.endsWith("/")) return 'Branch names cannot end with "/".';
|
||||
if (name.endsWith(".")) return 'Branch names cannot end with ".".';
|
||||
const parts = name.split("/");
|
||||
if (parts.some((p) => p === "")) return 'Branch names cannot start with "/" or contain "//".';
|
||||
if (parts.some((p) => p.startsWith("."))) return 'No part of a branch name can start with ".".';
|
||||
if (parts.some((p) => p.endsWith(".lock"))) return 'No part of a branch name can end with ".lock".';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `name` can be created: the first of empty, invalid (with a
|
||||
* reason), local (already a local branch), remote (a remote-only branch),
|
||||
* nested (it and a local branch would be folders of each other) or free.
|
||||
*/
|
||||
export function nameStatus(name, git) {
|
||||
if (blank(name)) return { kind: "empty" };
|
||||
const reason = refFormatProblem(name);
|
||||
if (reason) return { kind: "invalid", reason };
|
||||
const rows = list(git && git.branches).filter(Boolean);
|
||||
const locals = rows.filter((b) => !b.remote);
|
||||
const local = locals.find((b) => b.name === name);
|
||||
if (local) return { kind: "local", branch: local.name };
|
||||
// The board shows a remote-only branch as origin/name, so that is taken too.
|
||||
const remote = rows.find((b) => b.remote && (b.name === name || `${b.remote}/${b.name}` === name));
|
||||
if (remote) return { kind: "remote", remote: remote.remote, branch: remote.name };
|
||||
const nested = locals.find((b) => name.startsWith(`${b.name}/`) || b.name.startsWith(`${name}/`));
|
||||
if (nested) return { kind: "nested", clash: nested.name };
|
||||
return { kind: "free" };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- buttons */
|
||||
|
||||
const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
||||
|
||||
const button = (shown, enabled, label, title) => ({ shown, enabled: shown && enabled, label, ...(title ? { title } : {}) });
|
||||
|
||||
/**
|
||||
* Every board button as `{ shown, enabled, label, title? }`. Pull is enabled
|
||||
* only with an upstream to pull from; Push shows with an upstream, Publish
|
||||
* without one. `busy` greys everything out but Done; an operation in
|
||||
* progress hides everything but Done (its banner carries Abort / Continue).
|
||||
*/
|
||||
export function boardActions(git, { busy = false } = {}) {
|
||||
const g = git || {};
|
||||
const head = g.head || {};
|
||||
const changes = g.changes || {};
|
||||
const count = Number(changes.count) || 0;
|
||||
const heldBack = Number(changes.heldBack) || 0;
|
||||
const hasCommits = g.hasCommits !== false;
|
||||
const hasRemote = list(g.remotes).length > 0;
|
||||
const detached = hasCommits && !head.branch;
|
||||
const ahead = Number(head.ahead) || 0;
|
||||
const free = !busy;
|
||||
|
||||
const done = button(true, true, "Done");
|
||||
const hidden = (label) => button(false, false, label);
|
||||
|
||||
if (g.inProgress) {
|
||||
return {
|
||||
refresh: hidden("Refresh"),
|
||||
pull: hidden("Pull"),
|
||||
push: hidden("Push"),
|
||||
publish: hidden("Publish"),
|
||||
commit: hidden("Commit"),
|
||||
cleanup: hidden("Clean up"),
|
||||
done,
|
||||
};
|
||||
}
|
||||
|
||||
const commitLabel = !hasCommits
|
||||
? "Make the first commit"
|
||||
: `Commit ${plural(count, "file", "files")}${heldBack > 0 ? ` · ${heldBack} held back` : ""}`;
|
||||
const commit = button(count > 0, free, commitLabel);
|
||||
|
||||
if (!hasCommits) {
|
||||
return {
|
||||
refresh: button(true, free, "Refresh", "Look at this folder again"),
|
||||
pull: hidden("Pull"),
|
||||
push: hidden("Push"),
|
||||
publish: hidden("Publish"),
|
||||
commit,
|
||||
cleanup: hidden("Clean up"),
|
||||
done,
|
||||
};
|
||||
}
|
||||
|
||||
const notOnBranch = "Not on a branch: switch to one first";
|
||||
// Shown without a remote too: it is how edits made outside reach the board
|
||||
// (the agent re-reads the folder; with a remote it fetches first).
|
||||
const refresh = button(true, free, "Refresh", hasRemote ? undefined : "Look at this folder again");
|
||||
|
||||
// An upstream whose remote copy was deleted is no upstream: nothing to pull
|
||||
// from or push to, and Publish (which plan publish allows again) is the way.
|
||||
const live = Boolean(head.upstream) && !head.gone;
|
||||
let pull;
|
||||
if (detached) pull = button(hasRemote, false, "Pull", notOnBranch);
|
||||
else if (head.upstream && head.gone) pull = button(hasRemote, false, "Pull", "Its remote copy was deleted: publish it again");
|
||||
else if (!head.upstream) pull = button(hasRemote, false, "Pull", "Nothing to pull from yet: publish first");
|
||||
else pull = button(hasRemote, free, "Pull");
|
||||
|
||||
const showPush = hasRemote && live && !detached;
|
||||
const push =
|
||||
ahead > 0
|
||||
? button(showPush, free, `Push · ${ahead} to push`)
|
||||
: button(showPush, false, "Push", "Nothing to push");
|
||||
|
||||
const showPublish = hasRemote && !live;
|
||||
const publish = detached ? button(showPublish, false, "Publish", notOnBranch) : button(showPublish, free, "Publish");
|
||||
|
||||
const cleanable = list(g.branches).some((b) => b && !b.remote && !b.current && !b.default && (b.merged || b.gone));
|
||||
const cleanup = button(!!g.defaultBranch && cleanable, free, "Clean up");
|
||||
|
||||
return { refresh, pull, push, publish, commit, cleanup, done };
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the board is still waiting on the agent: a card send not yet
|
||||
* settled, or a board click at `sentAt` (ms) with no agent post since
|
||||
* (`updatedAt`, the state's last post, ISO). Collecting a click takes
|
||||
* milliseconds, so "uncollected" alone leaves the bar live while the agent
|
||||
* runs git. An agent gone quiet (`adrift`) releases the lock.
|
||||
*/
|
||||
export function boardAwaiting({ sentAt = null, updatedAt = null, cardsAwaiting = 0, adrift = false } = {}) {
|
||||
if (adrift) return false;
|
||||
if (cardsAwaiting > 0) return true;
|
||||
if (!sentAt) return false;
|
||||
const posted = Date.parse(updatedAt);
|
||||
return !(posted > sentAt);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- replies */
|
||||
|
||||
const names = (v) => list(v).filter((s) => typeof s === "string" && s);
|
||||
|
||||
// "these 3 files: a, b, c" or "this file: a".
|
||||
function filePhrase(files, count) {
|
||||
const n = Number.isInteger(count) ? count : files.length;
|
||||
const shown = files.length ? `: ${files.join(", ")}` : "";
|
||||
return n === 1 ? `this file${shown}` : `these ${n} files${shown}`;
|
||||
}
|
||||
|
||||
/** The plain instruction a board button sends the agent, one sentence per op. */
|
||||
export function gitReply(op, fields = {}) {
|
||||
const f = fields || {};
|
||||
switch (op) {
|
||||
case "refresh":
|
||||
return "Refresh.";
|
||||
case "pull":
|
||||
return "Pull.";
|
||||
case "push":
|
||||
return "Push.";
|
||||
case "publish":
|
||||
// No remote named: there are several, and the agent asks which.
|
||||
return f.remote ? `Publish to ${f.remote}.` : "Publish.";
|
||||
case "switch":
|
||||
return `Switch to ${f.branch}.`;
|
||||
case "create": {
|
||||
const start = `Create ${f.name} from ${f.from}.`;
|
||||
if (f.then !== "commit") return start;
|
||||
const ignore = names(f.ignore);
|
||||
const tail = ignore.length ? ` Add ${ignore.join(", ")} to .gitignore.` : "";
|
||||
return `${start} Then commit ${filePhrase(names(f.files), f.count)}.${tail}`;
|
||||
}
|
||||
case "delete":
|
||||
return `Delete ${f.branch}.`;
|
||||
case "cleanup": {
|
||||
const branches = names(f.branches);
|
||||
const n = Number.isInteger(f.count) ? f.count : branches.length;
|
||||
return `Clean up ${plural(n, "branch", "branches")}${branches.length ? `: ${branches.join(", ")}` : ""}.`;
|
||||
}
|
||||
case "commit": {
|
||||
const ignore = names(f.ignore);
|
||||
const tail = ignore.length ? ` Add ${ignore.join(", ")} to .gitignore.` : "";
|
||||
return `Commit ${filePhrase(names(f.files), f.count)}.${tail}`;
|
||||
}
|
||||
case "abort":
|
||||
return `Abort the ${f.operation === "am" ? "git am" : f.operation || "rebase"}.`;
|
||||
case "continue":
|
||||
return `Continue the ${f.operation === "am" ? "git am" : f.operation || "rebase"}.`;
|
||||
case "pr-host":
|
||||
if (f.kind === "none" || !Object.hasOwn(PR_HOST_LABELS, f.kind)) return "This host is none of those.";
|
||||
return `This host is ${PR_HOST_LABELS[f.kind]}.`;
|
||||
case "done":
|
||||
return "I'm done.";
|
||||
default:
|
||||
return `${op}.`;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- time */
|
||||
|
||||
const UNITS = [
|
||||
["year", 365 * 24 * 3600],
|
||||
["month", 30 * 24 * 3600],
|
||||
["week", 7 * 24 * 3600],
|
||||
["day", 24 * 3600],
|
||||
["hour", 3600],
|
||||
["minute", 60],
|
||||
];
|
||||
|
||||
let rtf = null;
|
||||
|
||||
/** "2 hr. ago" style age of `iso`, in its largest whole unit; "" for an unreadable date. */
|
||||
export function relativeAge(iso, now = Date.now()) {
|
||||
const t = typeof iso === "number" ? iso : Date.parse(iso);
|
||||
if (iso === null || iso === undefined || iso === "" || Number.isNaN(t) || !Number.isFinite(Number(now))) return "";
|
||||
rtf = rtf || new Intl.RelativeTimeFormat("en", { numeric: "auto", style: "short" });
|
||||
const seconds = (t - Number(now)) / 1000;
|
||||
const unit = UNITS.find(([, size]) => Math.abs(seconds) >= size);
|
||||
if (!unit) return rtf.format(0, "second");
|
||||
return rtf.format(Math.round(seconds / unit[1]), unit[0]);
|
||||
}
|
||||
|
||||
/** The board's footer line: when the remotes were last fetched, and whether the last try failed. */
|
||||
export function refreshedLine(git, now = Date.now()) {
|
||||
const g = git || {};
|
||||
const age = g.lastFetch ? relativeAge(g.lastFetch, now) : "";
|
||||
const line = age ? `Last refreshed ${age}` : "Never refreshed";
|
||||
return g.refreshFailed ? `${line} · refresh failed` : line;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- commit */
|
||||
|
||||
/**
|
||||
* The paths ticked when the commit dialog opens. Staged files win: when any
|
||||
* file is staged, exactly those. Otherwise every file that is not risky,
|
||||
* plus each untracked folder of at most UNTRACKED_TICK_LIMIT files.
|
||||
*/
|
||||
export function commitTicks(changes) {
|
||||
const files = list(changes && changes.files).filter((f) => f && typeof f.path === "string");
|
||||
const staged = files.filter((f) => f.staged);
|
||||
if (staged.length) return new Set(staged.map((f) => f.path));
|
||||
const ticks = new Set(files.filter((f) => !f.risky).map((f) => f.path));
|
||||
for (const dir of list(changes && changes.untrackedDirs)) {
|
||||
if (dir && typeof dir.path === "string" && Number(dir.files) <= UNTRACKED_TICK_LIMIT) ticks.add(dir.path);
|
||||
}
|
||||
return ticks;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- pull requests */
|
||||
|
||||
/**
|
||||
* The pull-request link for the current branch into `base` (the default
|
||||
* branch unless the picker chose another): `{ url, needsKind, host }`, where
|
||||
* needsKind means the host's kind is unknown and the person must name it
|
||||
* (url is null then). null when the branch is not pushed, is gone upstream,
|
||||
* is the default branch, or its remote or the base is missing.
|
||||
*/
|
||||
export function boardPrLink(git, base) {
|
||||
const cur = currentRow(git);
|
||||
if (!cur || !cur.upstream || cur.gone || cur.default) return null;
|
||||
const target = base || (git && git.defaultBranch);
|
||||
if (!target) return null;
|
||||
const remote = list(git.remotes).find((r) => r && r.name === cur.upstreamRemote);
|
||||
if (!remote) return null;
|
||||
const needsKind = remote.kind === null || remote.kind === undefined;
|
||||
return {
|
||||
url: needsKind ? null : prUrl(remote, { base: target, head: cur.name }),
|
||||
needsKind,
|
||||
host: remote.host || null,
|
||||
};
|
||||
}
|
||||
@@ -20,6 +20,7 @@ export const HELP_TABS = Object.freeze([
|
||||
tab("dashboard", "The dashboard", true),
|
||||
tab("meter", "Session meter", false),
|
||||
tab("build", "Watching a build", false),
|
||||
tab("git", "The git board", false),
|
||||
tab("subagents", "Helpers (subagents)", false),
|
||||
tab("ask", "Ask a quick question", false),
|
||||
tab("finishing", "Stopping and finishing", false),
|
||||
@@ -44,6 +45,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
||||
if (dashboard && meterRed) return "meter";
|
||||
if (dashboard) return "dashboard";
|
||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||
if (workflow === "git") return "git";
|
||||
if (HELP_BUILD_WORKFLOWS.has(workflow)) return "build";
|
||||
return "about";
|
||||
}
|
||||
|
||||
+209
-101
@@ -24,6 +24,8 @@
|
||||
<link rel="modulepreload" href="/subagents.js" />
|
||||
<link rel="modulepreload" href="/mentions.js" />
|
||||
<link rel="modulepreload" href="/favicon.js" />
|
||||
<link rel="modulepreload" href="/git-board.js" />
|
||||
<link rel="modulepreload" href="/pr-url.js" />
|
||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="icon" type="image/png" sizes="192x192" href="/favicon.png" />
|
||||
@@ -37,8 +39,8 @@
|
||||
rail drawing that powers on centre stage, then glides into the rail.
|
||||
Hidden unless boot.js is playing it; placed entirely by app.css,
|
||||
because the CSP refuses style attributes. -->
|
||||
<div class="wake" id="wake" hidden aria-hidden="true">
|
||||
<svg class="wake-bot" viewBox="0 0 22 30" focusable="false">
|
||||
<div class="wake" id="wake" hidden>
|
||||
<svg class="wake-bot" viewBox="0 0 22 30" focusable="false" aria-hidden="true">
|
||||
<g class="body">
|
||||
<rect class="foot f1" x="5.7" y="27.1" width="3.6" height="1.7" rx="0.85" />
|
||||
<rect class="foot f2" x="12.7" y="27.1" width="3.6" height="1.7" rx="0.85" />
|
||||
@@ -58,7 +60,7 @@
|
||||
</g>
|
||||
</svg>
|
||||
<p class="wake-hint">Click to wake Planny</p>
|
||||
<button class="wake-skip" type="button">Skip</button>
|
||||
<button class="wake-skip" type="button" aria-label="Skip the intro">Skip</button>
|
||||
</div>
|
||||
|
||||
<header class="topbar">
|
||||
@@ -565,13 +567,15 @@
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
<!-- Git commit: saving a step. Beside a branch line with two commits on
|
||||
it, one arm reaches to set a third commit onto the line. -->
|
||||
<svg class="pose pose-git-commit" data-pose="git-commit" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
|
||||
<!-- Git: minding the branches. Beside a branch line with a second branch
|
||||
forking off it, one arm reaches to set a new commit onto the line. -->
|
||||
<svg class="pose pose-git" data-pose="git" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
|
||||
<ellipse class="shadow" cx="126" cy="198" rx="44" ry="5" />
|
||||
<g class="prop">
|
||||
<line class="lt gc-line" x1="204" y1="62" x2="204" y2="172" />
|
||||
<path class="lt" d="M204 152 Q226 140 226 112 L226 72" />
|
||||
<circle class="ac" cx="204" cy="82" r="7" />
|
||||
<circle class="ac" cx="226" cy="92" r="6" />
|
||||
<circle class="ac" cx="204" cy="112" r="7" />
|
||||
<circle class="ac gc-dot" cx="204" cy="142" r="7" />
|
||||
</g>
|
||||
@@ -649,6 +653,12 @@
|
||||
<rect x="3" y="9" width="18" height="6" rx="3" />
|
||||
<path d="M6 12h7" />
|
||||
</symbol>
|
||||
<symbol id="hi-git" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="6" cy="5" r="2" />
|
||||
<circle cx="6" cy="19" r="2" />
|
||||
<circle cx="18" cy="7" r="2" />
|
||||
<path d="M6 7v10M18 9a7 7 0 0 1-7 7H6" />
|
||||
</symbol>
|
||||
<symbol id="hi-subagents" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="7" cy="12" r="3.5" />
|
||||
<circle cx="18" cy="5" r="2" />
|
||||
@@ -737,8 +747,9 @@
|
||||
<p>
|
||||
<strong>It stays up while this tab is open.</strong> Close the tab and
|
||||
it shuts itself down <span data-fact="closedTabMinutes">2</span> minutes
|
||||
later, and after <span data-fact="maxLifeHours">4</span> hours
|
||||
regardless. Reopening the same link brings everything back: nothing you
|
||||
later. It also stops after <span data-fact="idleMinutes">30</span>
|
||||
minutes without hearing from anyone, and after
|
||||
<span data-fact="maxLifeHours">4</span> hours regardless. Reopening the same link brings everything back: nothing you
|
||||
typed is kept in the browser alone.
|
||||
</p>
|
||||
<h4>Two halves, both running</h4>
|
||||
@@ -782,7 +793,7 @@
|
||||
<ol class="help-rows">
|
||||
<li class="help-row">
|
||||
<dl>
|
||||
<dt>You see</dt><dd>The line beside Planny stays quiet for a minute or two while it is working.</dd>
|
||||
<dt>You see</dt><dd>The line beside Planny stays quiet for half a minute or more while it is working.</dd>
|
||||
<dt>Likely cause</dt><dd>A permission prompt is waiting in your terminal.</dd>
|
||||
<dt>Do this</dt><dd>Switch to the terminal and answer it.</dd>
|
||||
</dl>
|
||||
@@ -798,7 +809,7 @@
|
||||
<dl>
|
||||
<dt>You see</dt><dd><strong>Not connected</strong> (Planny faded, his star shut).</dd>
|
||||
<dt>Likely cause</dt><dd>The program behind this page shut itself down.</dd>
|
||||
<dt>Do this</dt><dd>Ask Plan2Code to resume the session, and use the new link.</dd>
|
||||
<dt>Do this</dt><dd>Ask Plan2Code to resume the session (or run the command again), and use the new link.</dd>
|
||||
</dl>
|
||||
</li>
|
||||
<li class="help-row">
|
||||
@@ -1561,7 +1572,7 @@
|
||||
<li><strong>Review.</strong> A second opinion on the changes. Problems ranked, and you pick what gets fixed.</li>
|
||||
<li><strong>Handoff.</strong> Pack this conversation into a document a fresh session can pick up cold.</li>
|
||||
<li><strong>Changelog.</strong> Checks the CHANGELOG version against the main branch and suggests entries for what is new.</li>
|
||||
<li><strong>Git commit.</strong> Commits your changes with a clear message, suggests a split when it is really two jobs, and offers to push.</li>
|
||||
<li><strong>Git.</strong> Branches, pull, push and commits on one board, asking before anything leaves your machine. See "The git board".</li>
|
||||
</ul>
|
||||
<h4>Picking a spec</h4>
|
||||
<p>
|
||||
@@ -1718,7 +1729,94 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Helpers (subagents) -->
|
||||
<!-- Tab 13: The git board -->
|
||||
<section class="help-panel" data-tab="git">
|
||||
<h3>The git board</h3>
|
||||
<p class="help-lead">
|
||||
The Git card opens one board for your repository: branches, pull,
|
||||
push and commits in one place. Every button is a request to
|
||||
Plan2Code, which runs the git commands and says what each one did.
|
||||
</p>
|
||||
<h4>The header</h4>
|
||||
<ul>
|
||||
<li>The branch you are on, and how far it is ahead of or behind its remote copy.</li>
|
||||
<li>
|
||||
<strong>Last refreshed</strong> says when the remotes were last
|
||||
fetched. <strong>Refresh</strong> fetches again; if that fails, the
|
||||
line says so.
|
||||
</li>
|
||||
<li>
|
||||
Once your branch is pushed, <strong>Open pull request</strong> opens
|
||||
your host's new pull request page, into the default branch or the
|
||||
one you pick beside it. The first time a host is unknown, the board
|
||||
asks which kind it is and remembers the answer.
|
||||
</li>
|
||||
</ul>
|
||||
<h4>The branch table</h4>
|
||||
<ul>
|
||||
<li>
|
||||
The branch you are on and the default branch come first, then the
|
||||
rest, newest commit first, each with <strong>Switch</strong> and
|
||||
<strong>Delete</strong>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Merged</strong> marks a branch already merged into the
|
||||
default branch, and <strong>Remote copy deleted</strong> one whose
|
||||
remote copy is gone. <strong>Clean up</strong> offers to delete those
|
||||
local branches in one go.
|
||||
</li>
|
||||
<li>
|
||||
Branches that exist only on the remote sit under
|
||||
<strong>Remote only</strong>, showing the first
|
||||
<span data-fact="remoteFold">50</span>; <strong>Show all</strong>
|
||||
lists the rest.
|
||||
</li>
|
||||
<li><strong>Search branches</strong> filters both lists by name or last commit.</li>
|
||||
</ul>
|
||||
<h4>What asks first</h4>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Push</strong>, <strong>Publish</strong>,
|
||||
<strong>Delete</strong> and <strong>Clean up</strong> always show
|
||||
exactly what will happen and wait for your yes. Deleting a branch
|
||||
that is not merged is a red confirm.
|
||||
</li>
|
||||
<li>
|
||||
Switching with uncommitted changes asks first: <strong>Switch and
|
||||
bring them</strong>, <strong>Commit first</strong> or
|
||||
<strong>Cancel</strong>. A pull that would touch your changes asks
|
||||
the same way.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Commit</strong> opens a list of your changed files to tick,
|
||||
and you approve the message before anything is committed.
|
||||
</li>
|
||||
<li>A remote branch is never deleted, and nothing is ever force-pushed.</li>
|
||||
</ul>
|
||||
<h4>One action at a time</h4>
|
||||
<p>
|
||||
While Planny works on a click, the bar is locked, so nothing queues
|
||||
up behind it. When it is done, a result line says what happened, with
|
||||
the commit hashes, and the board redraws from the repository as it now
|
||||
stands.
|
||||
</p>
|
||||
<h4>Done</h4>
|
||||
<p>
|
||||
<strong>Done</strong> ends the session. If anything happened, the last
|
||||
screen lists the commits, pushes and branches created or deleted, with
|
||||
<strong>Back to the dashboard</strong>. If nothing did, the page goes
|
||||
straight back to the dashboard.
|
||||
</p>
|
||||
<h4>In the terminal</h4>
|
||||
<p>
|
||||
The same skill takes plain instructions, such as
|
||||
<code>/plan2code-git switch to main</code> or
|
||||
<code>/plan2code-git commit and push</code>, and asks the same
|
||||
questions before every push, publish and delete.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 14: Helpers (subagents) -->
|
||||
<section class="help-panel" data-tab="subagents">
|
||||
<h3>Helpers (subagents)</h3>
|
||||
<p>
|
||||
@@ -1773,7 +1871,7 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 14: Ask a quick question -->
|
||||
<!-- Tab 15: Ask a quick question -->
|
||||
<section class="help-panel" data-tab="ask">
|
||||
<h3>Ask a quick question</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1864,7 +1962,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 15: Stopping and finishing -->
|
||||
<!-- Tab 16: Stopping and finishing -->
|
||||
<section class="help-panel" data-tab="finishing">
|
||||
<h3>Stopping and finishing</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1938,15 +2036,16 @@
|
||||
A finished screen (never a paused one) has a <strong>Back to the
|
||||
dashboard</strong> button. It turns this page back into the cards, in
|
||||
the same conversation, so the next step starts right here.
|
||||
Plan2Code listens for it for about ten minutes after the end. After
|
||||
that, or once the session has closed, the button becomes the
|
||||
<code>/plan2code</code> command to run in a new conversation instead.
|
||||
Plan2Code listens for it for as long as the session is open.
|
||||
Once the session has closed, the button becomes the
|
||||
<code>/plan2code</code> command to run in a new conversation
|
||||
instead.
|
||||
After a long step, a new conversation is the better choice anyway: it
|
||||
starts with a clean slate.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 16: Keyboard and preferences -->
|
||||
<!-- Tab 17: Keyboard and preferences -->
|
||||
<section class="help-panel" data-tab="prefs">
|
||||
<h3>Keyboard and preferences</h3>
|
||||
<p class="help-lead">
|
||||
@@ -2032,6 +2131,9 @@
|
||||
lists what Plan2Code doesn't need in your
|
||||
<code>~/.plan2code</code> folder: sessions nobody has opened for
|
||||
30 days, and files or folders that ended up there by mistake. It
|
||||
also lists this project's <code>specs--completed/</code> folders
|
||||
nobody has touched for 30 days; deleting one is permanent, since
|
||||
that folder is usually gitignored and git can't restore it. It
|
||||
shows each one with its size, and <strong>Delete these</strong>
|
||||
removes exactly that list. Your preferences, saved folders, models,
|
||||
the launcher and the session you are in always stay.
|
||||
@@ -2062,7 +2164,7 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 17: Privacy and where things are saved -->
|
||||
<!-- Tab 18: Privacy and where things are saved -->
|
||||
<section class="help-panel" data-tab="privacy">
|
||||
<h3>Privacy and where things are saved</h3>
|
||||
<p class="help-lead">
|
||||
@@ -2127,90 +2229,93 @@
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<dialog class="modal looks" id="looks-modal" aria-labelledby="looks-title">
|
||||
<dialog class="modal looks prefs" id="looks-modal" aria-labelledby="looks-title">
|
||||
<h2 id="looks-title">User Preferences</h2>
|
||||
<p class="modal-blurb">
|
||||
Kept on this machine, for every session you open here. Role only puts the
|
||||
starter templates most useful to you first; it never changes the questions
|
||||
you're asked.
|
||||
</p>
|
||||
<fieldset class="modal-ranges looks-row looks-role">
|
||||
<legend>Role</legend>
|
||||
<select id="looks-role" aria-label="Role"></select>
|
||||
<p class="help">Only puts the starter templates most useful to you first.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Theme</legend>
|
||||
<label><input type="radio" name="looks-theme" value="system" checked /> <span>Follow my system</span></label>
|
||||
<label><input type="radio" name="looks-theme" value="light" /> <span>Light</span></label>
|
||||
<label><input type="radio" name="looks-theme" value="dark" /> <span>Dark</span></label>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Card width</legend>
|
||||
<label><input type="radio" name="looks-width" value="narrow" /> <span>Narrow</span></label>
|
||||
<label><input type="radio" name="looks-width" value="comfortable" checked /> <span>Comfortable</span></label>
|
||||
<label><input type="radio" name="looks-width" value="wide" /> <span>Wide</span></label>
|
||||
<p class="help">How wide the question and documents are. On a smaller window they fit the space there is.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-accents">
|
||||
<legend>Highlight color</legend>
|
||||
<div class="swatches" id="looks-swatches"></div>
|
||||
<p class="help">
|
||||
Your highlight color marks what is yours to do, and Planny's
|
||||
star uses it while he works. Green, amber and red also mean done,
|
||||
staged and careful, so a highlight close to one of those can blur
|
||||
which is which.
|
||||
<div class="prefs-body">
|
||||
<p class="modal-blurb">
|
||||
Kept on this machine, for every session you open here. Role only puts the
|
||||
starter templates most useful to you first; it never changes the questions
|
||||
you're asked.
|
||||
</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-sounds">
|
||||
<legend>Sounds</legend>
|
||||
<label><input type="checkbox" id="looks-sound" checked /> <span>Play sounds</span></label>
|
||||
<div class="looks-row looks-sound-events" id="looks-sound-events">
|
||||
<label><input type="checkbox" data-sound="snore" checked /> <span>Planny snoring</span></label>
|
||||
<label><input type="checkbox" data-sound="bootup" checked /> <span>Planny waking up</span></label>
|
||||
<label><input type="checkbox" data-sound="startSkill" checked /> <span>Starting a skill</span></label>
|
||||
<label><input type="checkbox" data-sound="sessionStart" checked /> <span>Session opens</span></label>
|
||||
<label><input type="checkbox" data-sound="skillReady" checked /> <span>Skill is ready</span></label>
|
||||
<label><input type="checkbox" data-sound="sessionEnd" checked /> <span>Session ends</span></label>
|
||||
<label><input type="checkbox" data-sound="question" checked /> <span>New questions for you</span></label>
|
||||
<label><input type="checkbox" data-sound="chatReply" checked /> <span>Reply on the Ask tab</span></label>
|
||||
<label><input type="checkbox" data-sound="newTab" checked /> <span>New tab added</span></label>
|
||||
</div>
|
||||
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-cleanup">
|
||||
<legend>Cleanup</legend>
|
||||
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
|
||||
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
|
||||
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
|
||||
<span class="help" id="cleanup-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-models">
|
||||
<legend>Models</legend>
|
||||
<div class="models-tabs" role="group" aria-label="Which agent">
|
||||
<button type="button" class="btn small ghost" id="models-tab-claude" aria-pressed="true">Claude</button>
|
||||
<button type="button" class="btn small ghost" id="models-tab-devin" aria-pressed="false">Devin</button>
|
||||
</div>
|
||||
<div class="models-note">
|
||||
<p><strong>You usually don't need to change this.</strong> Plan2Code ships an up-to-date model list with every release. Add a model here only when a new one comes out before Plan2Code has been updated.</p>
|
||||
<ul>
|
||||
<li>Restart <code>plan2code</code> to see a change in its model menu.</li>
|
||||
<li>At any time, run <code>plan2code --model <id></code>, or pick your model inside your agent before running a skill.</li>
|
||||
<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>
|
||||
<li>Devin models are limited to Low, Medium and High effort.</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="models-list" id="models-shipped" aria-label="Built-in models"></div>
|
||||
<div class="models-list" id="models-user" aria-label="Models you added"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="models-add">Add a model</button>
|
||||
<button type="button" class="btn small ghost" id="models-reset">Reset to default</button>
|
||||
<span class="help" id="models-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-row looks-role">
|
||||
<legend>Role</legend>
|
||||
<select id="looks-role" aria-label="Role"></select>
|
||||
<p class="help">Only puts the starter templates most useful to you first.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Theme</legend>
|
||||
<label><input type="radio" name="looks-theme" value="system" checked /> <span>Follow my system</span></label>
|
||||
<label><input type="radio" name="looks-theme" value="light" /> <span>Light</span></label>
|
||||
<label><input type="radio" name="looks-theme" value="dark" /> <span>Dark</span></label>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Card width</legend>
|
||||
<label><input type="radio" name="looks-width" value="narrow" /> <span>Narrow</span></label>
|
||||
<label><input type="radio" name="looks-width" value="comfortable" checked /> <span>Comfortable</span></label>
|
||||
<label><input type="radio" name="looks-width" value="wide" /> <span>Wide</span></label>
|
||||
<p class="help">How wide the question and documents are. On a smaller window they fit the space there is.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-accents">
|
||||
<legend>Highlight color</legend>
|
||||
<div class="swatches" id="looks-swatches"></div>
|
||||
<p class="help">
|
||||
Your highlight color marks what is yours to do, and Planny's
|
||||
star uses it while he works. Green, amber and red also mean done,
|
||||
staged and careful, so a highlight close to one of those can blur
|
||||
which is which.
|
||||
</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-sounds">
|
||||
<legend>Sounds</legend>
|
||||
<label><input type="checkbox" id="looks-sound" checked /> <span>Play sounds</span></label>
|
||||
<div class="looks-row looks-sound-events" id="looks-sound-events">
|
||||
<label><input type="checkbox" data-sound="snore" checked /> <span>Planny snoring</span></label>
|
||||
<label><input type="checkbox" data-sound="bootup" checked /> <span>Planny waking up</span></label>
|
||||
<label><input type="checkbox" data-sound="startSkill" checked /> <span>Starting a skill</span></label>
|
||||
<label><input type="checkbox" data-sound="sessionStart" checked /> <span>Session opens</span></label>
|
||||
<label><input type="checkbox" data-sound="skillReady" checked /> <span>Skill is ready</span></label>
|
||||
<label><input type="checkbox" data-sound="sessionEnd" checked /> <span>Session ends</span></label>
|
||||
<label><input type="checkbox" data-sound="question" checked /> <span>New questions for you</span></label>
|
||||
<label><input type="checkbox" data-sound="chatReply" checked /> <span>Reply on the Ask tab</span></label>
|
||||
<label><input type="checkbox" data-sound="newTab" checked /> <span>New tab added</span></label>
|
||||
</div>
|
||||
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-cleanup">
|
||||
<legend>Cleanup</legend>
|
||||
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. It also lists this project's <code>specs--completed/</code> folders nobody has touched for 30 days; deleting one is permanent, since that folder is usually gitignored and git can't restore it. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
|
||||
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
|
||||
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
|
||||
<span class="help" id="cleanup-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-models">
|
||||
<legend>Models</legend>
|
||||
<div class="models-tabs" role="group" aria-label="Which agent">
|
||||
<button type="button" class="btn small ghost" id="models-tab-claude" aria-pressed="true">Claude</button>
|
||||
<button type="button" class="btn small ghost" id="models-tab-devin" aria-pressed="false">Devin</button>
|
||||
<button type="button" class="btn small ghost" id="models-tab-codex" aria-pressed="false">Codex</button>
|
||||
</div>
|
||||
<div class="models-note">
|
||||
<p><strong>You usually don't need to change this.</strong> Plan2Code ships an up-to-date model list with every release. Add a model here only when a new one comes out before Plan2Code has been updated.</p>
|
||||
<ul>
|
||||
<li>Restart <code>plan2code</code> to see a change in its model menu.</li>
|
||||
<li>At any time, run <code>plan2code --model <id></code>, or pick your model inside your agent before running a skill.</li>
|
||||
<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>
|
||||
<li>Devin models are limited to Low, Medium and High effort.</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="models-list" id="models-shipped" aria-label="Built-in models"></div>
|
||||
<div class="models-list" id="models-user" aria-label="Models you added"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="models-add">Add a model</button>
|
||||
<button type="button" class="btn small ghost" id="models-reset">Reset to default</button>
|
||||
<span class="help" id="models-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="looks-reset">Back to default</button>
|
||||
<button type="button" class="btn primary" id="looks-done">Done</button>
|
||||
@@ -2436,6 +2541,9 @@
|
||||
<li>
|
||||
Run this in your terminal (not in this page or your agent):
|
||||
<div class="update-command" id="update-command"></div>
|
||||
It opens the installer's menu. Back at your prompt with no output at all? npm
|
||||
could not reach the repository and hid the reason: run
|
||||
<code>git ls-remote https://github.com/jparkerweb/plan2code.git</code> to see it.
|
||||
</li>
|
||||
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
|
||||
</ol>
|
||||
|
||||
@@ -25,17 +25,27 @@ export const WEIGHTS = Object.freeze({
|
||||
"init-update": 2,
|
||||
finalize: 1,
|
||||
handoff: 0,
|
||||
"git-commit": 1,
|
||||
git: 1,
|
||||
// Scores 0 itself: Git's commits are tallied per run (COMMITS_PER_POINT).
|
||||
"git-commits": 0,
|
||||
"git-conflict": 1,
|
||||
changelog: 1,
|
||||
});
|
||||
|
||||
// Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder,
|
||||
// implement and implement-review score only through the agent's `run`
|
||||
// reports; dashboard and handoff never score; git-commit and changelog score 1 on launch.
|
||||
// reports; dashboard and handoff never score; git and changelog score 1 on
|
||||
// launch (Git then adds its commit tally and conflict help).
|
||||
export const LAUNCH_COUNTED = Object.freeze(
|
||||
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize", "git-commit", "changelog"])
|
||||
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize", "git", "changelog"])
|
||||
);
|
||||
|
||||
// Git's commits weigh what they add up to: each `git-commits` run carries
|
||||
// `commits`, and a skill run scores one point per COMMITS_PER_POINT commits,
|
||||
// rounded down. MAX_COMMITS is the most one run may report. Tune here.
|
||||
export const COMMITS_PER_POINT = 2;
|
||||
export const MAX_COMMITS = 999;
|
||||
|
||||
const weightOf = (key) => (Object.prototype.hasOwnProperty.call(WEIGHTS, key) ? WEIGHTS[key] : 0);
|
||||
|
||||
// The event names an agent may report in `run`.
|
||||
@@ -128,7 +138,7 @@ const WORKFLOW_NAMES = Object.freeze({
|
||||
"init-update": "Init update",
|
||||
finalize: "Finalize",
|
||||
handoff: "Handoff",
|
||||
"git-commit": "Git commit",
|
||||
git: "Git",
|
||||
changelog: "Changelog",
|
||||
});
|
||||
|
||||
@@ -145,7 +155,7 @@ const LAUNCH_LABELS = Object.freeze({
|
||||
init: "Init started",
|
||||
"init-update": "Init update started",
|
||||
finalize: "Finalize started",
|
||||
"git-commit": "Git commit started",
|
||||
git: "Git started",
|
||||
changelog: "Changelog started",
|
||||
});
|
||||
const RUN_LABELS = Object.freeze({
|
||||
@@ -163,7 +173,9 @@ const RUN_LABELS = Object.freeze({
|
||||
"init-update": "Init update run",
|
||||
finalize: "Finalize run",
|
||||
handoff: "Handoff written",
|
||||
"git-commit": "Git commit run",
|
||||
git: "Git run",
|
||||
"git-commits": "Commits in Git",
|
||||
"git-conflict": "Git conflict help",
|
||||
changelog: "Changelog run",
|
||||
});
|
||||
|
||||
@@ -180,6 +192,7 @@ export function breakdownFrom(entries) {
|
||||
const seen = new Set();
|
||||
const rows = [];
|
||||
const answers = new Map(); // launch id -> { row, count, workflow }
|
||||
const commits = new Map(); // launch id -> { row, count }
|
||||
const builds = new Map(); // launch id -> the row of the build in progress
|
||||
const reviewed = new Set(); // launch ids whose built-in review has scored
|
||||
for (const entry of Array.isArray(entries) ? entries : []) {
|
||||
@@ -188,6 +201,20 @@ export function breakdownFrom(entries) {
|
||||
if (seen.has(entry.id)) continue;
|
||||
seen.add(entry.id);
|
||||
}
|
||||
// A click on the git board is not back-and-forth: Git's answers score nothing.
|
||||
if (entry.kind === "answer" && entry.workflow === "git") continue;
|
||||
if (entry.kind === "run" && entry.event === "git-commits") {
|
||||
if (!Number.isInteger(entry.commits) || entry.commits < 1) continue;
|
||||
const launch = launchOf(entry.id);
|
||||
let tally = commits.get(launch);
|
||||
if (!tally) {
|
||||
tally = { row: { label: "", points: 0 }, count: 0 };
|
||||
commits.set(launch, tally);
|
||||
rows.push(tally.row);
|
||||
}
|
||||
tally.count += entry.commits;
|
||||
continue;
|
||||
}
|
||||
if (entry.kind === "answer") {
|
||||
const launch = launchOf(entry.id);
|
||||
let tally = answers.get(launch);
|
||||
@@ -255,6 +282,10 @@ export function breakdownFrom(entries) {
|
||||
const where = WORKFLOW_NAMES[workflow] ? ` in ${WORKFLOW_NAMES[workflow]}` : "";
|
||||
row.label = `${count} ${count === 1 ? "answer" : "answers"}${where}`;
|
||||
}
|
||||
for (const { row, count } of commits.values()) {
|
||||
row.points = Math.floor(count / COMMITS_PER_POINT);
|
||||
row.label = `${count} ${count === 1 ? "commit" : "commits"} in Git`;
|
||||
}
|
||||
return rows.filter((row) => row.points > 0).map(({ label, points }) => ({ label, points }));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// Plan2Code Web Console - the pull-request link for a branch.
|
||||
//
|
||||
// One pure builder for the four host shapes in the git-dashboard spec
|
||||
// (overview.md -> Pull-request URL shapes). git-repo.mjs re-exports it for the
|
||||
// snapshot, and the board's base picker rebuilds the link in the browser with
|
||||
// the same code. No DOM access at module scope and no imports: the server,
|
||||
// git-repo.mjs, the page and `node --test` all import this file.
|
||||
|
||||
// GitHub's compare path keeps the "/" in a branch name; each segment is
|
||||
// encoded on its own.
|
||||
const segments = (branch) => branch.split("/").map(encodeURIComponent).join("/");
|
||||
const q = encodeURIComponent;
|
||||
|
||||
const SHAPES = {
|
||||
github: (web, base, head) => `${web}/compare/${segments(base)}...${segments(head)}?quick_pull=1`,
|
||||
gitlab: (web, base, head) =>
|
||||
`${web}/-/merge_requests/new?merge_request%5Bsource_branch%5D=${q(head)}&merge_request%5Btarget_branch%5D=${q(base)}`,
|
||||
azure: (web, base, head) => `${web}/pullrequestcreate?sourceRef=${q(head)}&targetRef=${q(base)}`,
|
||||
bitbucket: (web, base, head) => `${web}/pull-requests/new?source=${q(head)}&dest=${q(base)}`,
|
||||
};
|
||||
|
||||
/**
|
||||
* The "open a pull request" link for `head` into `base` on a remote, or null
|
||||
* when the host has no known shape (kind null or "none"), the remote has no
|
||||
* web address, or the result would not be an https: link.
|
||||
*/
|
||||
export function prUrl({ web, kind } = {}, { base, head } = {}) {
|
||||
const shape = SHAPES[kind];
|
||||
if (!shape || !web || !base || !head) return null;
|
||||
const url = shape(String(web).replace(/\/+$/, ""), base, head);
|
||||
try {
|
||||
return new URL(url).protocol === "https:" ? url : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -20,9 +20,54 @@ import { marked } from "./vendor/marked.esm.js";
|
||||
// read the same way) is protocol-relative and would not, so it is refused.
|
||||
const SAFE_PROTOCOL = /^(https?:|mailto:|#|\/(?![/\\]))/i;
|
||||
|
||||
// A note attachment kept into the spec (`console.mjs keep`) is cited by a
|
||||
// relative path ending in attachments/<slug>-<id8>.<ext>; the server serves
|
||||
// exactly those from the session's spec, so the link and the image work.
|
||||
const KEPT_ATTACHMENT = /^(?:\.{0,2}\/)*(?:[\w.-]+\/)*attachments\/([a-z0-9-]{1,40}-[0-9a-f-]{8}\.[a-z0-9]{1,5})$/i;
|
||||
|
||||
// A link or image the page cannot follow (a relative path into the project,
|
||||
// a remote image the CSP refuses) still says where it points.
|
||||
function unreachable(parent, href) {
|
||||
const where = String(href || "").trim();
|
||||
if (!where || /^(javascript|data|vbscript):/i.test(where)) return;
|
||||
parent.appendChild(document.createTextNode(" ("));
|
||||
parent.appendChild(el("code", null, where));
|
||||
parent.appendChild(document.createTextNode(")"));
|
||||
}
|
||||
|
||||
// An html token that is only an HTML comment: it renders as nothing, as it
|
||||
// would in any markdown viewer. Anything else html stays literal text.
|
||||
function isComment(t) {
|
||||
return t.type === "html" && /^\s*<!--[\s\S]*?-->\s*$/.test(String(t.raw ?? t.text ?? ""));
|
||||
}
|
||||
|
||||
const TASK_MARKERS = {
|
||||
"/": { mark: "◐", label: "in progress", cls: "is-doing" },
|
||||
"!": { mark: "!", label: "blocked", cls: "is-blocked" },
|
||||
"?": { mark: "?", label: "assumed", cls: "is-assumed" },
|
||||
};
|
||||
|
||||
// A list item opening with one of TASK_MARKERS: the marker comes off its
|
||||
// first text token (so it is not drawn twice) and its look comes back.
|
||||
function takeMarker(item) {
|
||||
const first = item.tokens && item.tokens[0];
|
||||
const leaf = first && Array.isArray(first.tokens) && first.tokens[0];
|
||||
const m = /^\[([/!?])\]\s+/.exec((first && first.text) || "");
|
||||
if (!m || !leaf || leaf.type !== "text" || !String(leaf.text || "").startsWith(m[0])) return null;
|
||||
first.text = first.text.slice(m[0].length);
|
||||
leaf.text = leaf.text.slice(m[0].length);
|
||||
if (typeof leaf.raw === "string" && leaf.raw.startsWith(m[0])) leaf.raw = leaf.raw.slice(m[0].length);
|
||||
if (Array.isArray(leaf.tokens) && leaf.tokens[0] && leaf.tokens[0].type === "text") {
|
||||
leaf.tokens[0].text = String(leaf.tokens[0].text || "").replace(m[0], "");
|
||||
}
|
||||
return TASK_MARKERS[m[1]];
|
||||
}
|
||||
|
||||
function safeHref(href) {
|
||||
if (!href) return null;
|
||||
const trimmed = String(href).trim();
|
||||
const kept = KEPT_ATTACHMENT.exec(trimmed);
|
||||
if (kept) return "/attachments/" + kept[1].toLowerCase();
|
||||
// Blocks javascript: and data: hrefs before they can reach the DOM, and a
|
||||
// protocol-relative `//host` (or `/\host`), which leaves the page for another site.
|
||||
return SAFE_PROTOCOL.test(trimmed) ? trimmed : null;
|
||||
@@ -74,6 +119,7 @@ function inlineInto(parent, tokens) {
|
||||
const href = safeHref(t.href);
|
||||
if (!href) {
|
||||
inlineInto(parent, t.tokens);
|
||||
unreachable(parent, t.href);
|
||||
break;
|
||||
}
|
||||
const a = el("a");
|
||||
@@ -87,8 +133,12 @@ function inlineInto(parent, tokens) {
|
||||
}
|
||||
case "image": {
|
||||
const src = safeHref(t.href);
|
||||
if (!src) {
|
||||
// Only same-origin images load (the CSP's img-src is 'self'), so a
|
||||
// remote one gets the text-and-path treatment rather than a broken
|
||||
// image and a console error.
|
||||
if (!src || /^https?:/i.test(src)) {
|
||||
parent.appendChild(document.createTextNode(t.text || ""));
|
||||
unreachable(parent, t.href);
|
||||
break;
|
||||
}
|
||||
const img = el("img", "md-img");
|
||||
@@ -98,6 +148,8 @@ function inlineInto(parent, tokens) {
|
||||
break;
|
||||
}
|
||||
default:
|
||||
// A comment is a note to tools (a spec's METRICS_JSON), never shown.
|
||||
if (isComment(t)) break;
|
||||
// Includes `html`: rendered as literal text, never parsed.
|
||||
parent.appendChild(document.createTextNode(t.raw ?? t.text ?? ""));
|
||||
}
|
||||
@@ -105,11 +157,9 @@ function inlineInto(parent, tokens) {
|
||||
}
|
||||
|
||||
// What a fenced code block offers beside Copy, from its first non-empty line:
|
||||
// `'run'` gets a Run it button (git commands — the one kind a person keeps
|
||||
// copying into Ask by hand), `'hint'` a muted note that pasting it into Ask
|
||||
// may get the agent to run it, and `null` nothing extra. A leading `/` is a
|
||||
// skill command for a new conversation, never a terminal command, so it gets
|
||||
// neither.
|
||||
// `'hint'` a muted note that pasting it into Ask may get the agent to run it,
|
||||
// and `null` nothing extra. A leading `/` is a skill command for a new
|
||||
// conversation, never a terminal command, so it gets nothing.
|
||||
const COMMAND_WORDS =
|
||||
/^(git|node|npm|npx|pnpm|yarn|bun|deno|python3?|pip3?|brew|curl|wget|docker|kubectl|terraform|make|cmake|cargo|go|java|mvn|gradle|gh|aws|az|gcloud|jq|ssh|scp|rsync|chmod|chown|mkdir|cp|mv|rm|ls|cd|cat|echo|export|source|bash|sh|zsh|fish|pwsh|powershell|cmd|systemctl|service|apt|apt-get|dnf|yum|pacman|tar|unzip|zip)\b/i;
|
||||
|
||||
@@ -119,7 +169,6 @@ export function runHint(text) {
|
||||
.map((line) => line.trim())
|
||||
.find((line) => line.length > 0);
|
||||
if (!firstLine || firstLine.startsWith("/")) return null;
|
||||
if (/^git(\s|$)/.test(firstLine)) return "run";
|
||||
if (firstLine.startsWith("#!")) return "hint";
|
||||
return COMMAND_WORDS.test(firstLine) ? "hint" : null;
|
||||
}
|
||||
@@ -161,14 +210,8 @@ function blockInto(parent, tokens) {
|
||||
// textContent, so a fenced block containing markup is inert.
|
||||
pre.appendChild(el("code", null, t.text));
|
||||
wrap.appendChild(copyButton(t.text, "md-copy"));
|
||||
const hint = runHint(t.text);
|
||||
if (hint === "run") {
|
||||
const run = el("button", "md-run", "Run it");
|
||||
run.type = "button";
|
||||
wrap.appendChild(run);
|
||||
}
|
||||
wrap.appendChild(pre);
|
||||
if (hint === "hint") {
|
||||
if (runHint(t.text) === "hint") {
|
||||
wrap.appendChild(el("p", "md-run-hint", "The agent may be able to run this — paste it into the Ask tab"));
|
||||
}
|
||||
parent.appendChild(wrap);
|
||||
@@ -181,12 +224,21 @@ function blockInto(parent, tokens) {
|
||||
const list = el(t.ordered ? "ol" : "ul", "md-list");
|
||||
if (t.ordered && typeof t.start === "number" && t.start !== 1) list.start = t.start;
|
||||
for (const item of t.items || []) {
|
||||
const li = el("li", "md-li" + (item.task ? " is-task" : ""));
|
||||
// The spec's other task markers ([/] in progress, [!] blocked,
|
||||
// [?] assumed), which marked does not know: drawn like a task box
|
||||
// rather than left as a bullet reading "[!]".
|
||||
const other = !item.task && takeMarker(item);
|
||||
const li = el("li", "md-li" + (item.task || other ? " is-task" : ""));
|
||||
if (item.task) {
|
||||
const box = el("span", "md-task" + (item.checked ? " is-done" : ""));
|
||||
box.textContent = item.checked ? "✓" : "·";
|
||||
box.setAttribute("aria-label", item.checked ? "done" : "not done");
|
||||
li.appendChild(box);
|
||||
} else if (other) {
|
||||
const box = el("span", "md-task " + other.cls);
|
||||
box.textContent = other.mark;
|
||||
box.setAttribute("aria-label", other.label);
|
||||
li.appendChild(box);
|
||||
}
|
||||
blockInto(li, item.tokens);
|
||||
list.appendChild(li);
|
||||
@@ -224,6 +276,7 @@ function blockInto(parent, tokens) {
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
if (isComment(t)) break;
|
||||
// Unknown or raw html block: show the source, do not interpret it.
|
||||
const p = el("p", "md-p");
|
||||
p.textContent = t.raw ?? t.text ?? "";
|
||||
|
||||
@@ -88,7 +88,7 @@ export function cleanSetting(input) {
|
||||
// The non-editable part of every "on" block (FR-8).
|
||||
export const FRAME_LINES = Object.freeze([
|
||||
"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.",
|
||||
"Report each helper on the page (console-subagents.md); 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.',
|
||||
]);
|
||||
|
||||
|
||||
+107
-11
@@ -55,6 +55,8 @@ import {
|
||||
removeCleanup,
|
||||
remoteWarning,
|
||||
saveSubagentStoreEntry,
|
||||
PR_HOST_KINDS,
|
||||
savePrHost,
|
||||
specKey,
|
||||
subagentStoreEntry,
|
||||
typedCount,
|
||||
@@ -129,6 +131,31 @@ const EXT_ALT = UPLOAD_EXTS.join("|");
|
||||
const UPLOAD_ANY_ROUTE = new RegExp(`^/uploads/([0-9a-f-]{36})\\.(${EXT_ALT})$`);
|
||||
const UPLOAD_NAME = new RegExp(`^[0-9a-f-]{36}\\.(${EXT_ALT})$`);
|
||||
|
||||
// A kept attachment's name, as attachmentName() in lib.mjs writes it:
|
||||
// <slug>-<first 8 of the upload id>.<the upload's extension>.
|
||||
const KEPT_ROUTE = new RegExp(`^/attachments/([a-z0-9-]{1,40}-[0-9a-f-]{8}\\.(${EXT_ALT}))$`);
|
||||
|
||||
function keptPath(name) {
|
||||
const state = readState() || {};
|
||||
if (typeof state.specDir !== "string" || !state.specDir.trim()) return null;
|
||||
const root = path.resolve(state.worktree || process.cwd());
|
||||
const dir = path.resolve(root, state.specDir, "attachments");
|
||||
const file = path.join(dir, name);
|
||||
try {
|
||||
const real = fs.realpathSync.native(file);
|
||||
const realDir = fs.realpathSync.native(dir);
|
||||
const realRoot = fs.realpathSync.native(root);
|
||||
const inside = (p, base) => {
|
||||
const rel = path.relative(base.toLowerCase(), p.toLowerCase());
|
||||
return rel && !rel.startsWith("..") && !path.isAbsolute(rel);
|
||||
};
|
||||
if (path.dirname(real).toLowerCase() !== realDir.toLowerCase() || !inside(real, realRoot)) return null;
|
||||
return fs.statSync(real).isFile() ? real : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function uploadPath(id, ext = "jpg") {
|
||||
if (!UPLOAD_EXTS.includes(ext)) return null;
|
||||
const result = path.join(UPLOADS_DIR, id + "." + ext);
|
||||
@@ -222,6 +249,8 @@ const SERVABLE = new Set([
|
||||
"subagents.js",
|
||||
"mentions.js",
|
||||
"favicon.js",
|
||||
"git-board.js",
|
||||
"pr-url.js",
|
||||
"start-stop.mp3",
|
||||
"next.mp3",
|
||||
"insert.mp3",
|
||||
@@ -598,7 +627,14 @@ function ensureConversation(state) {
|
||||
let entry = null;
|
||||
if (!last.conversation) {
|
||||
entry = appendChat(DIR, { kind: "reset", conversation: 1, workflow: state.workflow, reason: "start" });
|
||||
} else if (last.workflow !== state.workflow && (last.workflow === "dashboard" || state.workflow === "dashboard")) {
|
||||
} else if (
|
||||
last.workflow !== state.workflow &&
|
||||
// The same switches `open --resume` treats as a hop (a blank page, the
|
||||
// agent's replies included): through the dashboard, or into git from
|
||||
// anywhere (Commit it now, Changelog's "Commit this now?"). Without a new
|
||||
// conversation, the old questions would show as unanswered again.
|
||||
(last.workflow === "dashboard" || state.workflow === "dashboard" || state.workflow === "git")
|
||||
) {
|
||||
entry = appendChat(DIR, {
|
||||
kind: "reset",
|
||||
conversation: last.conversation + 1,
|
||||
@@ -728,7 +764,8 @@ function recordSubmitted(state, actions) {
|
||||
// JSON.parse makes "__proto__" an own property, and it would then be
|
||||
// written back into state.json and re-read forever.
|
||||
if (Object.prototype.hasOwnProperty.call(rest, "__proto__")) delete rest["__proto__"];
|
||||
item.submitted = { at, ...rest };
|
||||
// A skip says so on the record, so settling it can record a skip.
|
||||
item.submitted = { at, ...rest, ...(type === "skip" ? { skipped: true } : {}) };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -804,13 +841,14 @@ function touch() {
|
||||
lastContact = Date.now();
|
||||
}
|
||||
|
||||
const MODEL_CLIS = ["claude", "devin"];
|
||||
// The CLIs the launcher reads a model list for (src/launcher/plan2code.js listModels).
|
||||
const MODEL_CLIS = ["claude", "devin", "codex"];
|
||||
const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/;
|
||||
// Devin's XHigh and Max efforts are never offered, curated or added.
|
||||
const MODEL_EFFORT_BLOCKED = /-(xhigh|max)$/i;
|
||||
|
||||
/**
|
||||
* The user's added models: { claude: [{id,label}], devin: [...] }. Returns { models } or
|
||||
* The user's added models: { claude: [{id,label}], devin: [...], codex: [...] }. Returns { models } or
|
||||
* { error }. Blank rows are dropped; ids are trimmed and made unique per CLI; a label
|
||||
* defaults to the id. Nothing else in the body survives.
|
||||
*/
|
||||
@@ -1134,13 +1172,19 @@ const server = http.createServer((req, res) => {
|
||||
? asked
|
||||
: ""
|
||||
: state.specDir;
|
||||
// Most specs have no overview.md yet, which is normal, not an error: 204
|
||||
// keeps the browser console free of a failed request per pick.
|
||||
const noOverview = () => {
|
||||
res.writeHead(204, baseHeaders({ "cache-control": "no-store" }));
|
||||
res.end();
|
||||
};
|
||||
readOverview(state.worktree || state.project, spec)
|
||||
.then((text) =>
|
||||
typeof text === "string"
|
||||
? send(res, 200, text, "text/markdown; charset=utf-8", { "cache-control": "no-store" })
|
||||
: json(res, 404, { error: "no overview" })
|
||||
: noOverview()
|
||||
)
|
||||
.catch(() => json(res, 404, { error: "no overview" }));
|
||||
.catch(noOverview);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1268,11 +1312,38 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// What an unknown git host is, for the git board's pull-request link. Saved
|
||||
// to pr-hosts.json for every project; nothing is written under the project.
|
||||
// The page follows it with a __git pr-host action, and the agent's reread
|
||||
// rebuilds the link.
|
||||
if (pathname === "/pr-host" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const { host: raw, kind } = body && typeof body === "object" ? body : {};
|
||||
if (typeof raw !== "string" || !raw || raw.length > 253 || !/^[a-z0-9.-]+$/i.test(raw)) {
|
||||
return json(res, 400, { error: "bad-host" });
|
||||
}
|
||||
// Hosts are looked up lowercased (git-repo.mjs parseRemoteUrl).
|
||||
const host = raw.toLowerCase();
|
||||
if (!PR_HOST_KINDS.has(kind)) return json(res, 400, { error: "bad-kind" });
|
||||
const state = readState();
|
||||
if (!state || state.workflow !== "git") return json(res, 400, { error: "not-git" });
|
||||
try {
|
||||
savePrHost(host, kind);
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
appendEvent(DIR, { type: "pr-host", host, kind });
|
||||
return json(res, 200, { ok: true });
|
||||
});
|
||||
}
|
||||
|
||||
// The launcher's model menu: what ships (read-only here) and what the user added.
|
||||
if (pathname === "/models" && req.method === "GET") {
|
||||
const saved = readJson(USER_MODELS_FILE, null) || {};
|
||||
const { models } = cleanModels(saved);
|
||||
return json(res, 200, { shipped: shippedModels(), user: models || { claude: [], devin: [] } });
|
||||
return json(res, 200, { shipped: shippedModels(), user: models || Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []])) });
|
||||
}
|
||||
|
||||
if (pathname === "/models" && req.method === "POST") {
|
||||
@@ -1292,18 +1363,19 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
|
||||
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
|
||||
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
|
||||
// still finds. Never this session, never a path the page sent.
|
||||
// ~/.plan2code and the project's old completed specs; `{ delete: [id] }`
|
||||
// removes those of the ids a fresh scan still finds. Never this session,
|
||||
// never a path the page sent.
|
||||
if (pathname === "/cleanup" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
if (body && Array.isArray(body.delete)) {
|
||||
return removeCleanup(body.delete, { skipSid: SID })
|
||||
return removeCleanup(body.delete, { skipSid: SID, project: sessionWorktree() || PROJECT })
|
||||
.then((done) => json(res, 200, { ok: true, ...done }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
}
|
||||
return cleanupFindings({ skipSid: SID })
|
||||
return cleanupFindings({ skipSid: SID, project: sessionWorktree() || PROJECT })
|
||||
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
});
|
||||
@@ -1371,6 +1443,30 @@ const server = http.createServer((req, res) => {
|
||||
return readRaw(req, 0, () => json(res, 415, { error: "type" }));
|
||||
}
|
||||
|
||||
// A note attachment the agent kept into the spec (`console.mjs keep`), so a
|
||||
// doc citing `attachments/<name>` shows the image or opens the file. Read
|
||||
// only, and only one exact name shape (the one `keep` writes) directly
|
||||
// inside <worktree>/<specDir>/attachments/: nothing else in the project.
|
||||
if (pathname.startsWith("/attachments/") || req.url.startsWith("/attachments/")) {
|
||||
if (req.method !== "GET") return json(res, 405, { error: "method" });
|
||||
const m = KEPT_ROUTE.exec(req.url);
|
||||
const file = m && m[0] === pathname ? keptPath(m[1]) : null;
|
||||
if (!file) return json(res, 404, { error: "not found" });
|
||||
let buf;
|
||||
try {
|
||||
buf = fs.readFileSync(file);
|
||||
} catch {
|
||||
return json(res, 404, { error: "not found" });
|
||||
}
|
||||
const ext = m[2].toLowerCase();
|
||||
if (ext === "jpg") return send(res, 200, buf, "image/jpeg", { "cache-control": "private, max-age=3600" });
|
||||
const pdf = DOC_TYPES[ext].kind === "pdf";
|
||||
return send(res, 200, buf, pdf ? "application/pdf" : "text/plain; charset=utf-8", {
|
||||
...(pdf ? {} : { "content-security-policy": "sandbox" }),
|
||||
"cache-control": "private, max-age=3600",
|
||||
});
|
||||
}
|
||||
|
||||
// Matched on the raw request line as well as the parsed path: URL parsing
|
||||
// folds `..` segments away, and nothing that needed folding is an upload.
|
||||
// GET and DELETE take images and documents alike.
|
||||
|
||||
Reference in new issue
Block a user