mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 20:45:33 -08:00
Harden the shared console install, launcher, Loop staging, spec state and prompts
AI Assisted
This commit is contained in:
1 parent
120c259d9c
commit
3ee96834bf
130 files changed
+5988
-1434
No files matched your search
+57
-18
@@ -18,8 +18,15 @@
|
||||
* that agent (marked `(last used)`), or keeps the agent's own last-used model when none is
|
||||
* recorded, and `--model` (or Codex's `-m`) skips the question. Right after the agent is chosen, when it has a
|
||||
* flag for skipping permission prompts (every built-in does; a custom agent only with bypassArgs),
|
||||
* it asks whether to turn them off, Yes by default; `--keep-permissions` answers no, and with no
|
||||
* terminal to ask on they are off. Any other arguments are forwarded to the CLI.
|
||||
* it asks at a keyboard, on every launch, whether to turn them off, Yes by default and nothing
|
||||
* remembered (Codex's question also names its sandbox, which the flag turns off too).
|
||||
*
|
||||
* Permission flags (never forwarded to the CLI):
|
||||
* --bypass-permissions turn the agent's permission prompts off without asking; the only way
|
||||
* a run with no terminal (a script, a pipe) starts with them off
|
||||
* --keep-permissions keep the prompts on without asking (if both are given, this wins)
|
||||
* With no terminal to ask on and neither flag, the prompts stay on. Any other arguments are
|
||||
* forwarded to the CLI.
|
||||
* Self-contained, Node built-ins only, with one exception: the shared agent list and lookup
|
||||
* rule (agents.json and agent-lookup.mjs, installed beside this file in ~/.plan2code/bin/) are
|
||||
* loaded by dynamic import inside chooseCli() so the command, the web console and the desktop
|
||||
@@ -64,6 +71,7 @@ const PICK_FOLDER_FLAG = '--pick-folder';
|
||||
const CLI_FLAG = '--cli';
|
||||
const CLASSIC_FLAG = '--classic';
|
||||
const KEEP_PERMISSIONS_FLAG = '--keep-permissions';
|
||||
const BYPASS_PERMISSIONS_FLAG = '--bypass-permissions';
|
||||
// Where install.js puts the desktop app, and the one file in it the launcher starts.
|
||||
// PLAN2CODE_APP names a different executable (the tests start a stand-in this way).
|
||||
const APP_DIR = path.join(os.homedir(), '.plan2code', 'app');
|
||||
@@ -1069,21 +1077,50 @@ async function chooseCli(requested, { fromShortcut } = {}) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to start the agent with permission prompts off. Asked only for an agent that has a flag
|
||||
* for it (a custom agent may have none), with Yes as the default; `--keep-permissions` answers no
|
||||
* without asking, and with no terminal to ask on the prompts are off.
|
||||
* What turning the prompts off drops, in the words the keyboard question uses: Codex's flag also
|
||||
* turns off its sandbox, so its question names both.
|
||||
*/
|
||||
async function chooseBypass(cli, keep) {
|
||||
function bypassDrops(cli) {
|
||||
return cli.id === 'codex' ? 'approval prompts and its sandbox' : 'permission prompts';
|
||||
}
|
||||
|
||||
/**
|
||||
* The keyboard question's lines for an agent with a bypass flag: the heading, the line naming
|
||||
* what the flag drops, the prompt, and the hint after an answer it cannot read.
|
||||
*/
|
||||
function bypassQuestion(cli) {
|
||||
const drops = bypassDrops(cli);
|
||||
return {
|
||||
heading: `Turn ${cli.label}'s ${drops} off?`,
|
||||
detail:
|
||||
cli.id === 'codex'
|
||||
? `It would read, edit and run commands in this project without asking, outside its sandbox (${cli.bypassArgs.join(' ')}).`
|
||||
: `It would read, edit and run commands in this project without asking (${cli.bypassArgs.join(' ')}).`,
|
||||
prompt: `Turn ${drops} off?`,
|
||||
hint: `Type n to keep the ${drops}, or press Enter to turn them off.`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to start the agent with permission prompts off. Asked only for an agent that has a flag
|
||||
* for it (a custom agent may have none), on every launch at a keyboard, with Yes as the default
|
||||
* and no answer remembered. `--keep-permissions` answers no and `--bypass-permissions` answers yes
|
||||
* without asking. With no terminal to ask on the prompts stay on unless `--bypass-permissions`
|
||||
* was passed: a run nobody watches never drops them silently.
|
||||
*/
|
||||
async function chooseBypass(cli, { keep = false, bypass = false } = {}) {
|
||||
if (!cli.bypassArgs || !cli.bypassArgs.length || keep) return false;
|
||||
if (!process.stdin.isTTY) return true;
|
||||
if (bypass) return true;
|
||||
if (!process.stdin.isTTY) return false;
|
||||
const question = bypassQuestion(cli);
|
||||
console.log('');
|
||||
console.log(c.bright(`Turn ${cli.label}'s permission prompts off?`));
|
||||
console.log(c.dim(`It would read, edit and run commands in this project without asking (${cli.bypassArgs.join(' ')}).`));
|
||||
console.log(c.bright(question.heading));
|
||||
console.log(c.dim(question.detail));
|
||||
for (;;) {
|
||||
const answer = (await ask(`Prompts off? ${c.green('[Y/n]')}: `)).trim().toLowerCase();
|
||||
const answer = (await ask(`${question.prompt} ${c.green('[Y/n]')}: `)).trim().toLowerCase();
|
||||
if (!answer || answer === 'y' || answer === 'yes') return true;
|
||||
if (answer === 'n' || answer === 'no') return false;
|
||||
console.log(c.yellow('Type n to keep the prompts, or press Enter to turn them off.'));
|
||||
console.log(c.yellow(question.hint));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1546,10 +1583,12 @@ async function launch() {
|
||||
}
|
||||
const fromShortcut = argv.includes(PICK_FOLDER_FLAG);
|
||||
const classic = argv.includes(CLASSIC_FLAG);
|
||||
const keepPermissions = argv.includes(KEEP_PERMISSIONS_FLAG);
|
||||
const { cli: requestedCli, rest: extraArgs } = takeCliFlag(
|
||||
argv.filter((arg) => arg !== PICK_FOLDER_FLAG && arg !== CLASSIC_FLAG && arg !== KEEP_PERMISSIONS_FLAG)
|
||||
);
|
||||
const permissions = {
|
||||
keep: argv.includes(KEEP_PERMISSIONS_FLAG),
|
||||
bypass: argv.includes(BYPASS_PERMISSIONS_FLAG),
|
||||
};
|
||||
const ownFlags = new Set([PICK_FOLDER_FLAG, CLASSIC_FLAG, KEEP_PERMISSIONS_FLAG, BYPASS_PERMISSIONS_FLAG]);
|
||||
const { cli: requestedCli, rest: extraArgs } = takeCliFlag(argv.filter((arg) => !ownFlags.has(arg)));
|
||||
|
||||
printIntro();
|
||||
await releaseNotice();
|
||||
@@ -1599,7 +1638,7 @@ async function launch() {
|
||||
// terminal flow (asked late if the app fails to start). An agent the setup page started runs
|
||||
// in this terminal even with the app installed: the waiting setup tab is owed the hand-over.
|
||||
const app = !setup && !classic && hasDisplay() ? findApp() : null;
|
||||
let bypass = app ? null : await chooseBypass(cli, keepPermissions);
|
||||
let bypass = app ? null : await chooseBypass(cli, permissions);
|
||||
|
||||
if (!cwdSettled) {
|
||||
const picked = await projectCwd(fromShortcut);
|
||||
@@ -1622,7 +1661,7 @@ async function launch() {
|
||||
console.log(`Opened the Plan2Code app in ${c.cyan(cwd)} ${c.dim('(run `plan2code --classic` to stay in this terminal)')}`);
|
||||
return process.exit(0);
|
||||
}
|
||||
if (bypass === null) bypass = await chooseBypass(cli, keepPermissions);
|
||||
if (bypass === null) bypass = await chooseBypass(cli, permissions);
|
||||
|
||||
const args = cli.args(extraArgs, { bypass });
|
||||
const options = { cwd, stdio: 'inherit', ...(cli.fullPath ? { fromFullPath: true } : {}) };
|
||||
@@ -1659,4 +1698,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 = { normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd };
|
||||
module.exports = { bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd };
|
||||
@@ -146,6 +146,8 @@ Two disciplines keep this file useful:
|
||||
|
||||
Record what you could **not** determine as an explicit gap. Gaps at recon time are often the first real fog bullets.
|
||||
|
||||
On `local`, `node "<S>/pathfinder.mjs" add specs/<idea>/pathfinder --name "Codebase context" --type legwork-afk --question "<what the recon establishes>"` writes the file (it refuses any other name as `00`); append the `## Answer` below to it, and Step 7's `reconcile` marks it resolved and dates it. Without the script, write the whole file by hand.
|
||||
|
||||
### The literal file
|
||||
|
||||
```markdown
|
||||
@@ -398,6 +400,8 @@ Write the four dimension labels **hyphenated exactly as shown** — `Requirement
|
||||
|
||||
Say once, at Step 5: *"This map lives in gitignored `specs/` — local to you, not shared. `git add -f` it to track it."*
|
||||
|
||||
On `local`, write it with `node "<S>/pathfinder.mjs" init specs/<idea>/pathfinder --destination "<agreed lines>" --scores R,F,I,K --fog "<bullet>"` (one `--fog` per bullet; `--rule` adds a project ground rule, `--out` an out-of-scope line). It writes this structure at its Step 5 state: the banner, `**Status:** Charting`, the scores in the hyphenated form, the comments, `**Backend:** local` and the `AGENTS.md` line as found on disk, the standing ground rules, the fog, and a row for each question file already written. It refuses to overwrite a map and refuses a map with no fog (the off-ramp below). The template is the fallback when the script cannot run, and the reference for what `init` writes.
|
||||
|
||||
```markdown
|
||||
> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.
|
||||
|
||||
@@ -467,12 +471,12 @@ plan, not at shipped code. Continuous streaming to external systems is not on th
|
||||
[-] out of scope. Resolved rows carry the one-line gist from the question's Answer,
|
||||
then the Resolved: date in italics — briefs filter on these dates. -->
|
||||
|
||||
- [x] [Codebase context](./questions/00-codebase-context.md) — Node/Express/Knex/React with a BullMQ-to-S3 export precedent; `audit_events` is 180M rows partitioned monthly, no `actor_id` index, `requireAdmin` has no tenant scoping. *(2026-08-03)*
|
||||
- [x] [Export format](./questions/01-export-format.md) — CSV with a UTF-8 BOM and RFC 4180 quoting, plus a sidecar SHA-256 manifest; JSONL rejected because recipients open these in Excel. *(2026-08-03)*
|
||||
- [x] [Codebase context](./questions/00-codebase-context.md): Node/Express/Knex/React with a BullMQ-to-S3 export precedent; `audit_events` is 180M rows partitioned monthly, no `actor_id` index, `requireAdmin` has no tenant scoping. *(2026-08-03)*
|
||||
- [x] [Export format](./questions/01-export-format.md): CSV with a UTF-8 BOM and RFC 4180 quoting, plus a sidecar SHA-256 manifest; JSONL rejected because recipients open these in Excel. *(2026-08-03)*
|
||||
- [/] [Row-count ceiling](./questions/02-row-count-ceiling.md)
|
||||
- [ ] [Export authorization](./questions/03-export-authorization.md)
|
||||
- [!] [Delivery channel](./questions/05-delivery-channel.md) — Blocked by 02
|
||||
- [-] [SIEM push connector](./questions/06-siem-push-connector.md) — out of scope, see below
|
||||
- [!] [Delivery channel](./questions/05-delivery-channel.md): Blocked by 02
|
||||
- [-] [SIEM push connector](./questions/06-siem-push-connector.md): out of scope, see below
|
||||
|
||||
## Not yet specified
|
||||
|
||||
@@ -497,7 +501,7 @@ plan, not at shipped code. Continuous streaming to external systems is not on th
|
||||
<!-- Work consciously ruled past the destination. Never graduates; returns only if the
|
||||
destination is redrawn, and then as a fresh effort. One line each: gist plus why. -->
|
||||
|
||||
- [SIEM push connector](./questions/06-siem-push-connector.md) — scheduled push to Splunk or
|
||||
- [SIEM push connector](./questions/06-siem-push-connector.md): scheduled push to Splunk or
|
||||
similar. The destination ends at an operator-initiated export; anything continuous is a
|
||||
different effort with a different owner.
|
||||
- Redesign of the `audit_events` schema. The write path is untouched by this destination;
|
||||
@@ -515,6 +519,8 @@ Six contiguous `Key: value` lines after the H1. Not YAML. No frontmatter delimit
|
||||
|
||||
`## Question` is written at charting. `## Answer` is appended only when the question resolves. `## Evidence` holds sources, links, and artifacts, and a `research` subagent writes into it during Chart Step 8 without deciding anything.
|
||||
|
||||
On `local`, `node "<S>/pathfinder.mjs" add specs/<idea>/pathfinder --name "<name>" --question "<text>"` writes an open question in this shape and adds its map row: `NN` is `nextNN`, `--type` is `grill` (the default), `research`, `sketch`, `legwork-hitl` or `legwork-afk`, plus `--blocked-by "02, 04"`, `--locked`, `--recommended "<answer to react to>"` and one `--evidence` per bullet. Add the rest of the `## Question` detail (sub-decisions, why it is locked) to the file afterwards. It refuses a name already on the map and a `Blocked by:` number with no file. The templates below are the fallback when the script cannot run.
|
||||
|
||||
### An open question
|
||||
|
||||
```markdown
|
||||
|
||||
@@ -343,7 +343,7 @@ If a decision survives all six with no answer, it is not ready to leave the map.
|
||||
| Drip-feeding one probe at a time | Twelve open questions on the map, one probe per response, the human gives up on session four | Batch up to three independent probes. On a charted map the human's round trips are the scarce resource, not your token budget. |
|
||||
| Losing a probe the human skipped | Sent three, got two back, moved on and never mentioned the third | Diff the batch. Lead the next turn with what came back empty, restated in full. |
|
||||
| A batch of naked questions | Three one-liners with no recommendations and no why-it-matters | Every probe in a batch carries its own recommendation and its own stake. Otherwise you have offloaded the thinking, not the round trips. |
|
||||
| Asking in prose when the tool exists | Numbered Q blocks or a loose "which one?" despite AskUserQuestion being available | Put every answer control in the structured UI. Use descriptions for trade-offs and `Other` for composition. Prose may provide context or an artifact immediately before the tool, never the question itself. |
|
||||
| Asking in prose when the tool exists | Numbered Q blocks or a loose "which one?" despite the question tool being available | Put every answer control in the structured UI. Use descriptions for trade-offs and `Other` for composition. Prose may provide context or an artifact immediately before the tool, never the question itself. |
|
||||
| Flattening a gnarly probe into labels | An architectural decision reduced to three option labels with no useful descriptions | Keep the tool, not the flattening: put the real trade-off in each description, preserve `Other`, and recap the reasoning before recording. |
|
||||
| Treating an artifact as an excuse for prose | An ASCII UI followed by "thoughts?" | Show the artifact, then invoke the structured tool with pointed reaction probes naming the rows/elements. |
|
||||
| Retreating to prose over a fixable batch | Two probes collide on the short header, or one label bundles three answers | Rename the headers; split the bundled probe. Reshape the batch, never the decision. |
|
||||
|
||||
@@ -101,7 +101,7 @@ Pathfinder writes `specs/<idea>/PLAN-DRAFT-<YYYYMMDD>.md` with the header line:
|
||||
|
||||
`**Status:** Phase 3 Complete - Resume at Phase 4`
|
||||
|
||||
`/plan2code-1-plan` **already recognizes that exact string.** Its "Check for Existing Progress" block, which runs before Phase 1, reads:
|
||||
(`gate` prints this line as `planDraftStatus`: copy it from there.) `/plan2code-1-plan` **already recognizes that exact string.** Its "Check for Existing Progress" block, which runs before Phase 1, reads:
|
||||
|
||||
`- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4`
|
||||
|
||||
@@ -114,7 +114,7 @@ Consequences of that being a literal string match:
|
||||
- The file must be named `PLAN-DRAFT-<YYYYMMDD>.md` and live directly in `specs/<idea>/`. `PLAN-DRAFT-*.md` is a reserved name inside `pathfinder/` — never write it there.
|
||||
- Use the date in `gate`'s `planDraftPath` (it reads the clock). Do not guess it. On `github` (no `gate`), take today's date from the shell and check `ls specs/<idea>/` for an existing draft.
|
||||
|
||||
**Discovery is shell-only.** `specs/` is gitignored, so Glob silently returns nothing and every downstream skill would report "no PLAN-DRAFT found". Use `ls specs/` and `ls specs/<idea>/` (Bash) or `Get-ChildItem specs/` (PowerShell) — the same rule 1-plan and `/plan2code-2-document` follow when they look for the file you are about to write.
|
||||
**Discovery is shell-only.** `specs/` is gitignored, so a file search silently returns nothing and every downstream skill would report "no PLAN-DRAFT found". Use `ls specs/` and `ls specs/<idea>/` (Bash) or `Get-ChildItem specs/` (PowerShell) — the same rule 1-plan and `/plan2code-2-document` follow when they look for the file you are about to write.
|
||||
|
||||
**Do not append `## Planning Metrics` or any metrics comment.** Pathfinder is not a metered step. 1-plan's Phase 7 owns that block and will add it when it finishes the plan. Do not emit any of the completion tokens listed in the skill's Rules anywhere under `specs/`.
|
||||
|
||||
@@ -411,7 +411,7 @@ Nothing to commit — `specs/` is gitignored. Say so once, then stop.
|
||||
| Symptom | Cause | Fix |
|
||||
|---|---|---|
|
||||
| 1-plan starts at Phase 1 and re-asks for requirements | The status string does not match byte for byte | Compare against the quoted line above; watch for en dashes and casing |
|
||||
| 1-plan cannot find the draft at all | Glob was used to discover `specs/` | Shell only: `ls specs/` |
|
||||
| 1-plan cannot find the draft at all | A file search was used to discover `specs/` | Shell only: `ls specs/` |
|
||||
| `/plan2code-2-document` asks which of two drafts to use | The replace-in-place bullet was dropped from the footer | Merge the two drafts into the pathfinder-dated one, delete the other, restore the footer |
|
||||
| The finished plan is missing requirements the map decided | The verification bullet was dropped from the footer | Re-derive 2.1 and 2.2 from the resolved answers, restore the footer |
|
||||
| Metrics report a planning confidence nobody scored | A percent sign, or a bare dimension word followed by a number, reached the file | Hyphenate the dimension labels and drop the percent sign |
|
||||
|
||||
@@ -40,8 +40,8 @@ Each question file carries six contiguous `Key: value` lines after its H1 — NO
|
||||
|
||||
## Markers and blocking
|
||||
|
||||
**Map markers**, rebuilt from the files every session: `[ ]` open — **these rows ARE the frontier** · `[/]` claimed · `[x]` resolved · `[!]` open but blocked · `[-]` out of scope. Resolved rows carry the gist plus the `Resolved:` date in italics: `— <gist> *(YYYY-MM-DD)*`.
|
||||
**Map markers**, rebuilt from the files every session: `[ ]` open — **these rows ARE the frontier** · `[/]` claimed · `[x]` resolved · `[!]` open but blocked · `[-]` out of scope. Resolved rows carry the gist plus the `Resolved:` date in italics, after a colon: `[x] [<name>](./questions/<file>): <gist> *(YYYY-MM-DD)*`. A map written before this format has an em dash there; both read the same, since a row is its checkbox and link.
|
||||
|
||||
`scripts/pathfinder.mjs` implements exactly these rules (`reconcile` rebuilds the markers, `frontier` computes blocking, `lint` checks the schema), so this file is the reference for reading its output and for writing a question file. Apply the rules by hand only when the script cannot run.
|
||||
`scripts/pathfinder.mjs` implements exactly these rules (`init` writes the map, `add` writes a question file and its row, `reconcile` rebuilds the markers, `frontier` computes blocking, `lint` checks the schema), so this file is the reference for reading its output and for writing a question file by hand. Apply the rules by hand only when the script cannot run.
|
||||
|
||||
**Unblocked** ⟺ every `NN` in `Blocked by:` is `resolved`. **Stranded:** a blocker gone `out-of-scope` never resolves — the question is not merely blocked. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
|
||||
@@ -521,7 +521,7 @@ The map row it produces — gist, then the `Resolved:` date in italics:
|
||||
|
||||
1. **Re-read `## Not yet specified` in full.** Every bullet, every session, after every resolution. Not the ones you remember — you are assuming no memory of prior sessions, and the bullet that graduates is usually the one you forgot was there.
|
||||
2. **Ask of each bullet: did the answer just make this sharp?** Can you now write a `## Question` paragraph a stranger could act on, without "we'll need to figure out" anywhere in it?
|
||||
3. **If yes, write the question file NOW** — in this same session, before Work Step 9. Its `NN` is `frontier`'s `nextNN` (max existing + 1, from the directory, never reused). Fill all six schema lines, with `Blocked by:` wired in the same pass. `reconcile` then adds its `[ ]` or `[!]` row to `## Question Checklist`.
|
||||
3. **If yes, write the question file NOW** — in this same session, before Work Step 9. Its `NN` is `frontier`'s `nextNN` (max existing + 1, from the directory, never reused). Fill all six schema lines, with `Blocked by:` wired in the same pass. `reconcile` then adds its `[ ]` or `[!]` row to `## Question Checklist`. On `local`, `node "<S>/pathfinder.mjs" add specs/<idea>/pathfinder --name "<name>" --question "<text>" [--type ...] [--blocked-by "NN"]` does all of this in one step (chart.md, the question-file template); write the file by hand only when the script cannot run.
|
||||
4. **DELETE the bullet from `## Not yet specified`.** Immediately, in the same edit as writing the file.
|
||||
5. **If no, leave the bullet alone** — untouched, not reworded into something that merely sounds sharper.
|
||||
6. **Re-check the counts.** One fog patch may graduate into three questions, or into none. Both are normal. A patch that graduates into three was written at the right coarseness; a patch that graduates into exactly one every time was probably a question all along.
|
||||
|
||||
@@ -6,8 +6,9 @@
|
||||
// each row carries, which questions are on the frontier, which are blocked or
|
||||
// stranded, what NN comes next, what the Trail Footer looks like, which
|
||||
// clearing checks pass, which dates fall in a brief's range. This script
|
||||
// computes all of it and performs the bookkeeping writes (reconcile, claim,
|
||||
// resolve, rule out), so the agent spends its attention on the decisions.
|
||||
// computes all of it and performs the bookkeeping writes (init, add,
|
||||
// reconcile, claim, resolve, rule out), so the agent spends its attention on
|
||||
// the decisions.
|
||||
//
|
||||
// It never writes an ## Answer, never decides a question, never scores
|
||||
// confidence. Those stay with the agent and the human.
|
||||
@@ -20,6 +21,28 @@ const USAGE = `
|
||||
pathfinder.mjs: Pathfinder map bookkeeping. JSON on stdout (trail: --text prints the footer itself).
|
||||
<map> is specs/<idea>/pathfinder, specs/<idea>, <idea>, or a path to map.md.
|
||||
|
||||
node pathfinder.mjs init <map> --destination "<one or two lines>" --scores R,F,I,K
|
||||
--fog "<bullet>" [--fog ...] [--rule "<ground rule>" ...]
|
||||
[--out "<out-of-scope line>" ...] [--dry-run]
|
||||
Chart Step 5: writes map.md from the template (creating the idea folder
|
||||
and questions/): **Status:** Charting, the destination, the ground rules
|
||||
(Backend local, AGENTS.md as found on disk, the standing rules, then each
|
||||
--rule), the fog, an index of any question files already written.
|
||||
--scores are the four confidence scores out of 25, in order
|
||||
Requirements-clarity, Feasibility-technical, Integration-points,
|
||||
Risk-assessment. Refuses an existing map, and a map with no --fog (no fog
|
||||
is the Step 4 off-ramp: no map).
|
||||
|
||||
node pathfinder.mjs add <map> --name "<question name>" --question "<text>"
|
||||
[--type grill|research|sketch|legwork-hitl|legwork-afk]
|
||||
[--blocked-by "02, 04"] [--locked] [--recommended "<text>"]
|
||||
[--evidence "<line>" ...] [--slug <kebab-name>] [--dry-run]
|
||||
Chart Steps 3 and 6, Work Step 8: writes questions/NN-<slug>.md from the
|
||||
template (NN is nextNN, State open, the type defaults to grill) and adds
|
||||
its row to the map when one exists. Refuses a name already used, 00 for
|
||||
anything but codebase-context (and that name at any other NN), a
|
||||
checkbox or loop token in the text; a Blocked by: NN must exist.
|
||||
|
||||
node pathfinder.mjs reconcile <map> [--dry-run]
|
||||
Work Step 2. Files win: an ## Answer under a non-resolved State becomes
|
||||
resolved; a missing Resolved: date is backfilled from Claimed: (today if
|
||||
@@ -62,7 +85,8 @@ pathfinder.mjs: Pathfinder map bookkeeping. JSON on stdout (trail: --text prints
|
||||
The Clearing Gate's mechanical checks and the handoff preflight: zero
|
||||
[ ] [/] [!] rows, empty fog, a Gist on every resolved answer, an existing
|
||||
PLAN-DRAFT to update in place, the four hard caps, the map's scores >= 18.
|
||||
Lists what stays your judgment.
|
||||
Lists what stays your judgment, and prints the PLAN-DRAFT's byte-exact
|
||||
**Status:** line (planDraftStatus).
|
||||
|
||||
node pathfinder.mjs lint <map>
|
||||
Standing rules: loop tokens anywhere under specs/<idea>/, checkboxes or
|
||||
@@ -84,6 +108,25 @@ const SCHEMA_KEYS = ["Type", "State", "Blocked by", "Claimed", "Resolved", "Lock
|
||||
const TYPES = ["grill · HITL", "research · AFK", "sketch · HITL", "legwork · HITL", "legwork · AFK"];
|
||||
const STATES = ["open", "claimed", "resolved", "out-of-scope"];
|
||||
const GLYPH = { x: "●", "/": "◉", " ": "○", "!": "⊘", "-": "⊝" };
|
||||
// What sits between a row's link and its tail (gist, blocker, out-of-scope
|
||||
// note) and between an ## Out of scope link and its reason. Maps written
|
||||
// before it carried an em dash there; rows are found by checkbox and link, so
|
||||
// both read the same.
|
||||
const SEP = ": ";
|
||||
// The PLAN-DRAFT hand-off status /plan2code-1-plan resumes from, byte for byte
|
||||
// (DRAFT_STATUSES in specs.mjs reads the same string; a test holds them equal).
|
||||
const PLAN_DRAFT_STATUS = "Phase 3 Complete - Resume at Phase 4";
|
||||
// Written as the ground rules of every map init creates, after the Backend and
|
||||
// AGENTS.md lines (chart.md's map template carries the same ones).
|
||||
const STANDING_RULES = [
|
||||
"One question _file_ at a time; the fork-menu between decisions; a fresh session recommended after ~3. `research` questions may run as parallel subagents.",
|
||||
"Every user-facing question uses the structured question tool when available; probes batch at most three. Prose Q blocks are fallback only when the tool is unavailable.",
|
||||
"Questions are put to the human in plain English. Technical terms only where the term is the decision.",
|
||||
"HITL questions are answered by the human in their own words. Never self-answered.",
|
||||
"No new runtime dependency is assumed without a `research` question backing it.",
|
||||
"Sketches are throwaway and live only under `pathfinder/sketch-NN/`.",
|
||||
];
|
||||
const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||||
const DIMENSIONS = [
|
||||
{ key: "Requirements-clarity", word: "Requirements" },
|
||||
{ key: "Feasibility-technical", word: "Feasibility" },
|
||||
@@ -93,14 +136,22 @@ const DIMENSIONS = [
|
||||
|
||||
/* ------------------------------------------------------------- locating */
|
||||
|
||||
function locate(root, arg) {
|
||||
/**
|
||||
* The map's folders from the <map> argument. `create` (init, add) accepts an
|
||||
* idea folder that does not exist yet, as long as its name is kebab-case: the
|
||||
* command writing the first file creates it.
|
||||
*/
|
||||
function locate(root, arg, { create = false } = {}) {
|
||||
if (!arg) fail(EXIT.USAGE, "missing-map", "Name the map: specs/<idea>/pathfinder, specs/<idea>, or <idea>.", "Example: node pathfinder.mjs frontier specs/audit-export/pathfinder");
|
||||
let p = arg.replace(/\\/g, "/").replace(/\/+$/, "");
|
||||
if (/\/map\.md$/i.test(p)) p = p.replace(/\/map\.md$/i, "");
|
||||
let abs = path.isAbsolute(p) ? p : p.includes("/") ? path.join(root, p) : path.join(root, "specs", p);
|
||||
if (path.basename(abs) !== "pathfinder") abs = path.join(abs, "pathfinder");
|
||||
const ideaDir = path.dirname(abs);
|
||||
if (!isDir(ideaDir)) fail(EXIT.NOT_FOUND, "no-idea", `No idea folder at ${rel(root, ideaDir)}.`, "Check the idea name with `ls specs/` (shell, not Glob: specs/ is gitignored).");
|
||||
if (!isDir(ideaDir)) {
|
||||
if (!create) fail(EXIT.NOT_FOUND, "no-idea", `No idea folder at ${rel(root, ideaDir)}.`, "Check the idea name with `ls specs/` (shell, not a file search: specs/ is gitignored).");
|
||||
if (!KEBAB.test(path.basename(ideaDir))) fail(EXIT.USAGE, "bad-idea-name", `"${path.basename(ideaDir)}" is not a kebab-case idea name.`, "Use lowercase words joined by hyphens, for example audit-log-export.");
|
||||
}
|
||||
return { root, pf: abs, ideaDir, idea: path.basename(ideaDir), mapPath: path.join(abs, "map.md"), qDir: path.join(abs, "questions"), relPf: rel(root, abs) };
|
||||
}
|
||||
|
||||
@@ -204,7 +255,7 @@ function parseQuestion(file, text) {
|
||||
// Consequences under any of the names the playbooks use: a grill's
|
||||
// "Consequences", a research answer's "What this implies", or a stated
|
||||
// "breaks if reversed" for a locked decision.
|
||||
hasConsequences: answer ? /\*\*(Consequences|What this implies)\b|^#{2,6}\s*(Consequences|What this implies)\b|^\s*Consequences\s*[:—-]|\bif (this is |it is )?reversed\b|breaks if reversed/im.test(answer.body) : false,
|
||||
hasConsequences: answer ? /\*\*(Consequences|What this implies)\b|^#{2,6}\s*(Consequences|What this implies)\b|^\s*Consequences\s*[:\u2014-]|\bif (this is |it is )?reversed\b|breaks if reversed/im.test(answer.body) : false,
|
||||
hasEvidence: hasContent(evidence),
|
||||
researchComplete: evidence ? (evidence.body.match(/\*\*Research complete:\*\*\s*(\d{4}-\d{2}-\d{2})/) || [])[1] || null : null,
|
||||
questionText: question ? stripComments(question.body).trim() : "",
|
||||
@@ -346,10 +397,10 @@ function rowFor(q, byNN, nameOverride) {
|
||||
const link = `- [${q.marker}] [${name}](./questions/${q.file})`;
|
||||
if (q.marker === "x") {
|
||||
const date = q.resolved ? ` *(${q.resolved})*` : "";
|
||||
return q.gist ? `${link} — ${q.gist}${date}` : `${link}${date}`;
|
||||
return q.gist ? `${link}${SEP}${q.gist}${date}` : `${link}${date}`;
|
||||
}
|
||||
if (q.marker === "!") return `${link} — Blocked by ${openBlockers(q, byNN).join(", ")}`;
|
||||
if (q.marker === "-") return `${link} — out of scope, see below`;
|
||||
if (q.marker === "!") return `${link}${SEP}Blocked by ${openBlockers(q, byNN).join(", ")}`;
|
||||
if (q.marker === "-") return `${link}${SEP}out of scope, see below`;
|
||||
return link;
|
||||
}
|
||||
|
||||
@@ -365,11 +416,11 @@ function updateRow({ lines: block, rowLines, extra, m }, q, byNN, regenerate) {
|
||||
if (regenerate || !m) return [rowFor(q, byNN, name), ...extra];
|
||||
const oldMarker = m[1];
|
||||
if (oldMarker === q.marker) return block;
|
||||
const hasSuffix = /^\s*—/.test(m[4]);
|
||||
if (q.marker === "x" && !(oldMarker === "x" && hasSuffix)) return [rowFor(q, byNN, name), ...extra];
|
||||
if (q.marker === "!" || q.marker === "-" || oldMarker === "!" || oldMarker === "-" || oldMarker === "x") {
|
||||
// The tail ("— Blocked by", "— out of scope", a resolved row's gist and
|
||||
// date) belongs to the old marker.
|
||||
// A marker change that adds a tail ([x] gist and date, [!] blocker, [-]
|
||||
// note) or drops one (whatever follows an old [x], [!] or [-] link, in
|
||||
// either separator) writes the row fresh. The tail itself is never parsed:
|
||||
// the checkbox and the link are what make it a row.
|
||||
if (["x", "!", "-"].includes(q.marker) || ["x", "!", "-"].includes(oldMarker)) {
|
||||
return [rowFor(q, byNN, name), ...extra];
|
||||
}
|
||||
return [rowLines[0].replace(/\[(.)\]/, `[${q.marker}]`), ...rowLines.slice(1), ...extra];
|
||||
@@ -596,6 +647,244 @@ function drift(questions, map) {
|
||||
return d;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- init and add */
|
||||
|
||||
// The chart.md templates, in code: init and add write these, and the
|
||||
// templates in the references stay as the fallback for when the script
|
||||
// cannot run. The comments are written for the next session.
|
||||
const MAP_COMMENTS = {
|
||||
status: [
|
||||
"<!-- Status: Charting while the map is being built (Chart Steps 1-6) -> Working once the",
|
||||
" checklist is indexed (Chart Step 7) -> Cleared only when the Clearing Gate passes.",
|
||||
" A fresh session routes on this line, so it must be correct before the session ends. -->",
|
||||
],
|
||||
nextNN: [
|
||||
"<!-- Next NN: the number the next new question file takes. Kept by the script (reconcile",
|
||||
" adds it at Chart Step 7 and every write command raises it); it never goes down, so a",
|
||||
" deleted question's number is never reused. Never edit it by hand. -->",
|
||||
],
|
||||
confidence: [
|
||||
"<!-- Confidence: four dimensions, each scored out of 25, re-scored at every resolution.",
|
||||
" The Clearing Gate requires all four at 18/25 or better. Score against evidence. -->",
|
||||
],
|
||||
destination: [
|
||||
"<!-- Settled at Chart Step 2 and quoted as agreed. Every question is measured against it:",
|
||||
" in scope or past the edge, still needed or now moot. Change it only with the human",
|
||||
" present: a silent redraw invalidates every scope call already made. -->",
|
||||
],
|
||||
groundRules: [
|
||||
"<!-- Standing constraints for every session on this map. Read before choosing a question,",
|
||||
" obeyed while resolving it. Nothing here is re-asked. The Backend line comes first, then",
|
||||
" AGENTS.md: \"- `AGENTS.md` exists and governs.\" or, when it is missing, exactly",
|
||||
" \"- `AGENTS.md` is absent.\" (the handoff then routes to /plan2code-init first). -->",
|
||||
],
|
||||
glossary: [
|
||||
"<!-- Terms this effort uses precisely, as a table: | Term | Meaning here | Avoid |.",
|
||||
" Prevents two sessions meaning different things by the same word. -->",
|
||||
],
|
||||
checklist: [
|
||||
"<!-- Rebuilt from questions/ every session: the files are ground truth, this is an index.",
|
||||
" [ ] open (the frontier) · [/] claimed · [x] resolved · [!] open but blocked",
|
||||
" [-] out of scope. Resolved rows carry the one-line gist from the question's Answer,",
|
||||
" then the Resolved: date in italics; briefs filter on these dates. -->",
|
||||
],
|
||||
fog: [
|
||||
"<!-- The fog: in-scope areas you can see but cannot yet phrase as a question. Graduates into",
|
||||
" question files as answers land, and the graduated bullet is deleted from here.",
|
||||
" Do NOT pre-slice these into question-sized pieces: one bullet may become three",
|
||||
" questions, or none. Nothing already decided, already a question, or out of scope. -->",
|
||||
],
|
||||
outOfScope: [
|
||||
"<!-- Work consciously ruled past the destination. Never graduates; returns only if the",
|
||||
" destination is redrawn, and then as a fresh effort. One line each: gist plus why. -->",
|
||||
],
|
||||
};
|
||||
|
||||
const bulletsOf = (list) => (list || []).map((s) => s.trim()).filter(Boolean).map((s) => `- ${s}`);
|
||||
|
||||
function parseScores(v) {
|
||||
const nums = String(v || "").split(/[\s,]+/).filter(Boolean);
|
||||
if (nums.length !== 4 || nums.some((n) => !/^\d{1,2}$/.test(n) || Number(n) > 25)) {
|
||||
fail(EXIT.USAGE, "bad-scores", `--scores needs four whole numbers from 0 to 25${v ? `, not "${v}"` : ""}.`, "Order: Requirements-clarity, Feasibility-technical, Integration-points, Risk-assessment. Example: --scores 12,9,14,10 (charting scores are low by construction).");
|
||||
}
|
||||
return nums.map(Number);
|
||||
}
|
||||
|
||||
async function cmdInit(loc, args) {
|
||||
const dry = !!args["dry-run"];
|
||||
if (fs.existsSync(loc.mapPath)) fail(EXIT.REFUSED, "map-exists", `${loc.relPf}/map.md already exists; init never overwrites a map.`, "Resume it instead: run reconcile (Work Step 2), or frontier to see where it stands.");
|
||||
const destination = (args.destination || "").trim();
|
||||
if (!destination) fail(EXIT.USAGE, "missing-destination", "--destination is required: the one or two lines settled at Chart Step 2.", 'Example: --destination "A locked plan for exporting a filtered range of audit events as one file."');
|
||||
const scores = parseScores(args.scores);
|
||||
const fog = bulletsOf(args.fog);
|
||||
if (!fog.length) fail(EXIT.REFUSED, "no-fog", "No --fog: a map with nothing in ## Not yet specified is the Chart Step 4 off-ramp, not a map.", "Pass each fog bullet as --fog, or take the off-ramp: create no map, keep the codebase context, hand it to /plan2code-1-plan.");
|
||||
const agentsAbsent = !fs.existsSync(path.join(loc.root, "AGENTS.md"));
|
||||
const rules = [
|
||||
"- **Backend:** local",
|
||||
agentsAbsent ? "- `AGENTS.md` is absent." : "- `AGENTS.md` exists and governs. Its conventions are not re-litigated by any question here.",
|
||||
...STANDING_RULES.map((r) => `- ${r}`),
|
||||
...bulletsOf(args.rule),
|
||||
];
|
||||
const outOfScope = bulletsOf(args.out);
|
||||
// The same two refusals add applies: a checkbox line or a loop token never lands in a map.
|
||||
for (const t of [destination, ...fog, ...bulletsOf(args.rule), ...outOfScope]) {
|
||||
if (/^\s*[-*] \[.\]/m.test(t)) fail(EXIT.REFUSED, "checkbox", "A map never holds a checkbox line (the loop and metrics read checkboxes).", "Use plain bullets.");
|
||||
const tok = t.match(LOOP_TOKENS);
|
||||
if (tok) fail(EXIT.REFUSED, "loop-token", `${tok[0]} is a reserved loop completion token; it never belongs under specs/.`, "Reword it.");
|
||||
}
|
||||
const [r, f, i, k] = scores;
|
||||
const lines = [
|
||||
BANNER,
|
||||
"",
|
||||
`# Map: ${loc.idea}`,
|
||||
"",
|
||||
"*Decisions live in `questions/`, one file each. This file is just the index.*",
|
||||
"",
|
||||
"**Status:** Charting",
|
||||
`**Updated:** ${isoDate()}`,
|
||||
`**Confidence:** Requirements-clarity ${r}/25 · Feasibility-technical ${f}/25 · Integration-points ${i}/25 · Risk-assessment ${k}/25`,
|
||||
"",
|
||||
...MAP_COMMENTS.status, "",
|
||||
...MAP_COMMENTS.nextNN, "",
|
||||
...MAP_COMMENTS.confidence, "",
|
||||
"## Destination", "", destination, "", ...MAP_COMMENTS.destination, "",
|
||||
"## Ground rules", "", ...MAP_COMMENTS.groundRules, "", ...rules, "",
|
||||
"## Glossary", "", ...MAP_COMMENTS.glossary, "",
|
||||
"## Question Checklist", "", ...MAP_COMMENTS.checklist, "",
|
||||
"## Not yet specified", "", ...MAP_COMMENTS.fog, "", ...fog, "",
|
||||
"## Out of scope", "", ...MAP_COMMENTS.outOfScope, ...(outOfScope.length ? ["", ...outOfScope] : []),
|
||||
];
|
||||
let mapText = lines.join("\n") + "\n";
|
||||
// Question files written before the map (the Step 3 codebase context) get
|
||||
// their rows now, so the index starts out agreeing with the files.
|
||||
const questions = loadQuestions(loc);
|
||||
const byNN = derive(questions);
|
||||
if (questions.length) mapText = rebuildChecklist(mapText, questions, byNN).text;
|
||||
if (!dry) {
|
||||
fs.mkdirSync(loc.qDir, { recursive: true });
|
||||
fs.writeFileSync(loc.mapPath, mapText);
|
||||
}
|
||||
out({
|
||||
ok: true,
|
||||
map: `${loc.relPf}/map.md`,
|
||||
status: "Charting",
|
||||
agentsAbsent,
|
||||
indexed: questions.map((q) => ({ nn: q.nn, name: q.name, marker: `[${q.marker}]` })),
|
||||
nextNN: nextNN(loc, questions),
|
||||
dryRun: dry,
|
||||
mapWritten: !dry,
|
||||
next: "Write each question with add (Chart Step 6), then reconcile, set **Status:** Working and lint (Chart Step 7).",
|
||||
});
|
||||
}
|
||||
|
||||
const TYPE_WORDS = { grill: "grill · HITL", research: "research · AFK", sketch: "sketch · HITL" };
|
||||
|
||||
/** --type as written in a file ("legwork · AFK") or typed ("legwork-afk", "research"); grill by default. */
|
||||
function parseType(v) {
|
||||
if (v === undefined) return TYPES[0];
|
||||
const key = String(v).toLowerCase().replace(/[·\s_-]+/g, "-").replace(/^-+|-+$/g, "");
|
||||
const type = TYPES.find((t) => t.toLowerCase().replace(/[·\s]+/g, "-") === key) || TYPE_WORDS[key];
|
||||
if (!type) fail(EXIT.USAGE, "bad-type", `--type "${v}" is not a question type.`, "Use grill, research, sketch, legwork-hitl or legwork-afk (questions.md: Type meanings).");
|
||||
return type;
|
||||
}
|
||||
|
||||
function slugOf(name) {
|
||||
return name
|
||||
.normalize("NFKD")
|
||||
.replace(/\p{M}/gu, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 60)
|
||||
.replace(/-+$/, "");
|
||||
}
|
||||
|
||||
async function cmdAdd(loc, args) {
|
||||
const dry = !!args["dry-run"];
|
||||
const name = (args.name || "").trim();
|
||||
if (!name) fail(EXIT.USAGE, "missing-name", "--name is required: the question's name, its H1 and its map row.", 'Example: --name "Export authorization"');
|
||||
if (/[\r\n]/.test(name)) fail(EXIT.USAGE, "bad-name", "--name is one line.", "Put the detail in --question.");
|
||||
const question = (args.question || "").trim();
|
||||
if (!question) fail(EXIT.USAGE, "missing-question", "--question is required: the ## Question text, phrased sharply.", 'Example: --question "Who may run an audit-log export, and over whose events?"');
|
||||
const type = parseType(args.type);
|
||||
const slug = args.slug !== undefined ? String(args.slug) : slugOf(name);
|
||||
if (!KEBAB.test(slug)) fail(EXIT.USAGE, "bad-slug", args.slug !== undefined ? `--slug "${slug}" is not kebab-case.` : `"${name}" gives no usable file name.`, "Pass --slug with lowercase words joined by hyphens.");
|
||||
const recommended = (args.recommended || "").trim();
|
||||
const evidence = bulletsOf(args.evidence);
|
||||
for (const t of [name, question, recommended, ...evidence]) {
|
||||
if (/^\s*[-*] \[.\]/m.test(t)) fail(EXIT.REFUSED, "checkbox", "A question file never holds a checkbox line (the loop and metrics read checkboxes).", "Use plain bullets.");
|
||||
const tok = t.match(LOOP_TOKENS);
|
||||
if (tok) fail(EXIT.REFUSED, "loop-token", `${tok[0]} is a reserved loop completion token; it never belongs under specs/.`, "Reword it.");
|
||||
}
|
||||
|
||||
const questions = loadQuestions(loc);
|
||||
const byNN = derive(questions);
|
||||
const same = questions.find((q) => q.file.replace(/^\d+-/, "") === `${slug}.md` || q.name.toLowerCase() === name.toLowerCase());
|
||||
if (same) fail(EXIT.REFUSED, "duplicate", `${same.file} already holds "${same.name}"; one file per decision.`, "Work in that file, or name this question apart from it (--name, or --slug for the file name).");
|
||||
const nn = nextNN(loc, questions);
|
||||
if (nn === "00" && slug !== "codebase-context") fail(EXIT.REFUSED, "reserved-00", `This would be question 00, and 00 is always 00-codebase-context.md.`, 'Add the codebase context first (Chart Step 3): --name "Codebase context" --type legwork-afk.');
|
||||
if (nn !== "00" && slug === "codebase-context") fail(EXIT.REFUSED, "reserved-name", `codebase-context is question 00's name; this would be ${nn}-codebase-context.md.`, "Name this question for its own decision.");
|
||||
const blockedBy = args["blocked-by"] === undefined ? [] : parseBlockers(String(args["blocked-by"]));
|
||||
const missing = blockedBy.filter((b) => !byNN.has(b));
|
||||
if (missing.length) fail(EXIT.NOT_FOUND, "no-blocker", `Blocked by ${missing.join(", ")}, which ${missing.length === 1 ? "is not a question" : "are not questions"} in questions/.`, "Name blockers by an existing NN (frontier lists them); a blocker is written before what it blocks.");
|
||||
const file = `${nn}-${slug}.md`;
|
||||
const full = path.join(loc.qDir, file);
|
||||
if (fs.existsSync(full)) fail(EXIT.REFUSED, "exists", `questions/${file} already exists.`, "Run reconcile, then frontier for the next NN.");
|
||||
|
||||
const text = [
|
||||
BANNER,
|
||||
"",
|
||||
`# ${name}`,
|
||||
"",
|
||||
`Type: ${type}`,
|
||||
"State: open",
|
||||
`Blocked by: ${blockedBy.length ? blockedBy.join(", ") : "none"}`,
|
||||
"Claimed: none",
|
||||
"Resolved: none",
|
||||
`Locked: ${args.locked ? "yes" : "no"}`,
|
||||
"",
|
||||
"## Question",
|
||||
"",
|
||||
question,
|
||||
...(recommended ? ["", `Recommended answer to react to: ${recommended}`] : []),
|
||||
"",
|
||||
"## Evidence",
|
||||
...(evidence.length ? ["", ...evidence] : []),
|
||||
].join("\n") + "\n";
|
||||
if (!dry) {
|
||||
fs.mkdirSync(loc.qDir, { recursive: true });
|
||||
fs.writeFileSync(full, text);
|
||||
}
|
||||
const q = { ...parseQuestion(full, text), path: full };
|
||||
const all = [...questions, q];
|
||||
const byNNAfter = derive(all);
|
||||
const after = String(parseInt(nn, 10) + 1).padStart(2, "0");
|
||||
const original = readText(loc.mapPath);
|
||||
let mapRow = null;
|
||||
let mapWritten = false;
|
||||
if (original !== null) {
|
||||
const mapText = rebuildChecklist(original, all, byNNAfter).text;
|
||||
mapRow = rowFor(q, byNNAfter);
|
||||
mapWritten = saveMap(loc, original, mapText, after, dry);
|
||||
}
|
||||
out({
|
||||
ok: true,
|
||||
nn,
|
||||
name,
|
||||
file: rel(loc.root, full),
|
||||
type,
|
||||
state: "open",
|
||||
marker: `[${q.marker}]`,
|
||||
blockedBy,
|
||||
locked: !!args.locked,
|
||||
mapRow,
|
||||
dryRun: dry,
|
||||
mapWritten,
|
||||
nextNN: after,
|
||||
...(original === null ? { next: "No map yet: init writes it at Chart Step 5 and indexes this file." } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------- commands */
|
||||
|
||||
async function cmdReconcile(loc, args) {
|
||||
@@ -805,7 +1094,7 @@ async function cmdRuleOut(loc, args) {
|
||||
q.state = "out-of-scope";
|
||||
const byNN = derive(questions);
|
||||
mapText = rebuildChecklist(mapText, questions, byNN).text;
|
||||
const line = `- [${q.name}](./questions/${q.file}) — ${reason}`;
|
||||
const line = `- [${q.name}](./questions/${q.file})${SEP}${reason}`;
|
||||
const mapNl = eol(mapText);
|
||||
const lines = mapText.split(/\r?\n/);
|
||||
const at = lines.findIndex((l) => /^## +Out of scope\s*$/i.test(l));
|
||||
@@ -834,7 +1123,7 @@ function confidenceLine(scores) {
|
||||
const vals = DIMENSIONS.map((d) => ({ word: d.word, v: scores[d.word] }));
|
||||
if (vals.some((x) => x.v === null)) return null;
|
||||
const low = vals.filter((x) => x.v < 18).map((x) => x.word);
|
||||
if (low.length) return `Confidence: not yet — ${low.join(", ")} still ${low.length === 1 ? "needs" : "need"} work.`;
|
||||
if (low.length) return `Confidence: not yet, ${low.join(", ")} still ${low.length === 1 ? "needs" : "need"} work.`;
|
||||
const border = vals.filter((x) => x.v < 20).map((x) => x.word);
|
||||
if (border.length) return `Confidence: solid, but ${border.join(", ")} ${border.length === 1 ? "is" : "are"} borderline.`;
|
||||
return "Confidence: solid.";
|
||||
@@ -1000,6 +1289,7 @@ async function cmdGate(loc) {
|
||||
caps,
|
||||
existingPlanDraft: drafts.length ? drafts.map((n) => rel(loc.root, path.join(loc.ideaDir, n))) : null,
|
||||
planDraftPath: drafts.length ? rel(loc.root, path.join(loc.ideaDir, drafts.sort().at(-1))) : `${rel(loc.root, loc.ideaDir)}/PLAN-DRAFT-${isoDate().replace(/-/g, "")}.md`,
|
||||
planDraftStatus: `**Status:** ${PLAN_DRAFT_STATUS}`,
|
||||
agentsAbsent: map.agentsAbsent,
|
||||
initFirst: needsInit(loc, map),
|
||||
judgment: [
|
||||
@@ -1215,7 +1505,8 @@ async function cmdBriefData(loc, args) {
|
||||
decided,
|
||||
// Link markup dropped (a brief has no links); placeholder bullets ("None yet.") skipped.
|
||||
// A link text may hold one level of brackets ("Retention [legal] hold").
|
||||
ruledOut: map.outOfScope.map((b) => b.replace(/\[((?:[^[\]]|\[[^\]]*\])+)\]\([^)]*\)/g, "$1")).filter((b) => !/^(none|nothing)\b[^—:]*\.?$/i.test(b.trim())),
|
||||
// A placeholder has no separator after it (an em dash in maps written before SEP).
|
||||
ruledOut: map.outOfScope.map((b) => b.replace(/\[((?:[^[\]]|\[[^\]]*\])+)\]\([^)]*\)/g, "$1")).filter((b) => !/^(none|nothing)\b[^\u2014:]*\.?$/i.test(b.trim())),
|
||||
ready,
|
||||
waiting,
|
||||
fog: map.fog,
|
||||
@@ -1230,12 +1521,14 @@ async function cmdBriefData(loc, args) {
|
||||
|
||||
run(USAGE, async (argv) => {
|
||||
const args = parseArgs(argv, {
|
||||
booleans: ["dry-run", "text", "heavy"],
|
||||
values: ["root", "form", "reason", "range", "resolved-this-session"],
|
||||
lists: ["item"],
|
||||
booleans: ["dry-run", "text", "heavy", "locked"],
|
||||
values: ["root", "form", "reason", "range", "resolved-this-session", "destination", "scores", "name", "question", "type", "blocked-by", "recommended", "slug"],
|
||||
lists: ["item", "fog", "rule", "out", "evidence"],
|
||||
});
|
||||
const cmd = args._[0];
|
||||
const commands = {
|
||||
init: cmdInit,
|
||||
add: cmdAdd,
|
||||
reconcile: cmdReconcile,
|
||||
frontier: cmdFrontier,
|
||||
claim: cmdClaim,
|
||||
@@ -1247,6 +1540,6 @@ run(USAGE, async (argv) => {
|
||||
"brief-data": cmdBriefData,
|
||||
};
|
||||
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", `Commands: ${Object.keys(commands).join(", ")}. Run with --help.`);
|
||||
const loc = locate(path.resolve(args.root || "."), args._[1]);
|
||||
const loc = locate(path.resolve(args.root || "."), args._[1], { create: cmd === "init" || cmd === "add" });
|
||||
await commands[cmd](loc, args);
|
||||
});
|
||||
@@ -6,13 +6,13 @@ Start all PATHFINDER MODE responses with '🧭 [PATHFINDER: Chart - Step X: Name
|
||||
|
||||
Pathfinder, not architect. An idea has arrived too big or unclear to plan. Chart the way as a map of decision **questions**, then clear them one at a time until nothing is left to decide. Hand off to `/plan2code-1-plan`.
|
||||
|
||||
Read references/grilling.md
|
||||
Read references/grilling.md at the first question you grill (Chart Step 2, or a `grill` question in Work), not before: the intent gate, backend choice and a brief never need it.
|
||||
|
||||
> Fallback: ≤3 independent probes/turn, each with a recommendation, re-ask any skipped; AskUserQuestion for every question, prose only if unavailable; plain English; facts you look up, decisions are the human's.
|
||||
> Fallback: ≤3 independent probes/turn, each with a recommendation, re-ask any skipped; the question tool for every question, prose only if unavailable; plain English; facts you look up, decisions are the human's.
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file — before Step 0: ask **web console** (suggested) or **terminal**? Console → run `node "<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.
|
||||
The FIRST thing you do, before anything else in this file — before Step 0: ask **web console** (browser page, 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. 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 0.
|
||||
|
||||
## Backend
|
||||
|
||||
@@ -51,7 +51,7 @@ Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it
|
||||
|
||||
## Auto-Discovery and Mode Selection
|
||||
|
||||
⚠️ `specs/` is gitignored: NEVER use Glob; list it with `ls specs/` or `Get-ChildItem specs/`.
|
||||
⚠️ `specs/` is gitignored: NEVER use a file-search tool; list it with `ls specs/` or `Get-ChildItem specs/`.
|
||||
|
||||
**Brief/recap/minutes asked?** → read references/brief.md: `reconcile`, then `brief-data --range <range>` (`github`: its brief section), write plain-English `briefs/brief-<YYYYMMDD>.md` from the output, STOP. Never resolves.
|
||||
|
||||
@@ -80,13 +80,13 @@ Read references/chart.md
|
||||
|
||||
> Fallback: confirm the outcome with the human FIRST; only then grill the destination, then breadth-first; write the map and one question per sharp decision.
|
||||
|
||||
0. `[Chart - Step 0: Intent Gate]` **Before creating anything**, use AskUserQuestion for the outcome and WAIT: **chart a map** (foggy — Step 1), **`/plan2code-1-plan`** (clear — STOP), **`/plan2code-quick-task`** (tiny — STOP). HITL, never self-select "chart".
|
||||
0. `[Chart - Step 0: Intent Gate]` **Before creating anything**, use the question tool for the outcome and WAIT: **chart a map** (foggy — Step 1), **`/plan2code-1-plan`** (clear — STOP), **`/plan2code-quick-task`** (tiny — STOP). HITL, never self-select "chart".
|
||||
1. `[Chart - Step 1: Name and backend]` Only after the gate says "chart." Confirm the kebab-case idea name, then ask — HITL, never self-picked — **local files or GitHub Issues?** Recommend `local` for solo work; offer `github` only if preflight passes, naming the repo's visibility. THEN the first write.
|
||||
2. `[Chart - Step 2: Destination]` Grill until it is one or two lines. It fixes scope — settle it first.
|
||||
3. `[Chart - Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK`. On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter. Unfamiliar code? `/plan2code-xray` explains an area first.
|
||||
3. `[Chart - Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK` (`local`: `add` writes `00`, then its `## Answer`). On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter. Unfamiliar code? `/plan2code-xray` explains an area first.
|
||||
4. `[Chart - Step 4: Map the frontier]` Grill again **breadth-first**: fan out, never deep on one thread. Surface the open decisions and what is takeable now.
|
||||
5. `[Chart - Step 5: Create the map]` `**Status:** Charting`, Destination, Ground rules (backend first), an empty index, the fog in `## Not yet specified`. Say once where it lives and who sees it.
|
||||
6. `[Chart - Step 6: Write the questions]` One per decision you can phrase sharply NOW, dependency order, `Blocked by:` filled the same pass — on `github`, create all first, wire edges second. The rest stays fog. Testing is not charted here: `/plan2code-1-plan` Phase 1 asks it.
|
||||
5. `[Chart - Step 5: Create the map]` `**Status:** Charting`, Destination, Ground rules (backend first), an empty index, the fog in `## Not yet specified` (`local`: `init` writes it). Say once where it lives and who sees it.
|
||||
6. `[Chart - Step 6: Write the questions]` One per decision you can phrase sharply NOW, dependency order, `Blocked by:` filled the same pass (`local`: `add` each) — on `github`, create all first, wire edges second. The rest stays fog. Testing is not charted here: `/plan2code-1-plan` Phase 1 asks it.
|
||||
7. `[Chart - Step 7: Index]` `local`: `reconcile` fills `## Question Checklist` from the files (every missing row, with its marker). Either backend: set `**Status:** Working`. `local`: then `lint`.
|
||||
8. `[Chart - Step 8: Fire research]` One subagent per `research` question, in parallel. Each writes only its `## Evidence`, never decides. **Wait for all** (they die with the terminal), then Session End.
|
||||
|
||||
@@ -110,7 +110,7 @@ Assume NO memory of any prior session.
|
||||
5. `[Work - Step 5: Zoom]` Read the claimed question in full, plus any closed question it references. Obey `## Ground rules`.
|
||||
6. `[Work - Step 6: Resolve]` Route by type per the resolve playbook. HITL needs the human's own words.
|
||||
7. `[Work - Step 7: Record]` Write `## Answer`: the decision, what was rejected and why, consequences, a one-line `**Gist:**` last. Sources under `## Evidence`. Mark it resolved, dated today, index the gist + date on the map, bump `**Updated:**` (`local`: `resolve <NN>` does all four; its `unblocked` list feeds the menu).
|
||||
8. `[Work - Step 8: Graduate]` Fog now sharp? Write those questions (`local`: numbered from `nextNN`, then `reconcile` to index them), delete the graduated bullets. Past the destination? Rule it out of scope, one line in `## Out of scope` (`local`: `rule-out <NN> --reason "<why>"`; handle anything it reports `stranded`). Invalidated? Re-frame or rule out.
|
||||
8. `[Work - Step 8: Graduate]` Fog now sharp? Write those questions (`local`: `add` numbers and indexes each), delete the graduated bullets. Past the destination? Rule it out of scope, one line in `## Out of scope` (`local`: `rule-out <NN> --reason "<why>"`; handle anything it reports `stranded`). Invalidated? Re-frame or rule out.
|
||||
9. `[Work - Step 9: Menu]` Run The Clearing Gate. Not cleared: fork-menu (Form C; resolve.md §Cadence) — pick → Step 4, stop → Session End.
|
||||
|
||||
## The Clearing Gate
|
||||
@@ -130,7 +130,7 @@ Score the four dimensions (handoff.md rubric) and write them to the map's `**Con
|
||||
|
||||
## Trail Footer
|
||||
|
||||
Read references/trail.md
|
||||
Read references/trail.md before the first footer (your first response once the map exists), not before.
|
||||
|
||||
> Fallback: once the map exists, end every response with a marker path (`●` done · `◉` here · `○` open · `⊘` blocked · `⊝` out of scope) `START`→`⚑`, a named legend, a plain-English confidence note, then ONE closer: asking → Form B, `WAITING ON YOU`, no command; menu → Form C, `NEXT UP` + `OR START FRESH`; session end → Form A, `NEXT STEP` + resume command with `--web` (map issue URL on `github`).
|
||||
|
||||
|
||||
@@ -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 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.
|
||||
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before looking for a draft: ask **web console** (browser page, suggested) 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. Switchable anytime. The console is far easier for sign-offs with a non-engineer. 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)
|
||||
|
||||
@@ -57,7 +57,7 @@ Keep with you: every question, confidence score, decision and sign-off, Phases 3
|
||||
|
||||
### Check for Existing Progress
|
||||
|
||||
Before Phase 1, run `node "<S>/specs.mjs" list` from the project root (`<S>`: `scripts/` beside this SKILL.md, `~/.agents/skills/plan2code-1-plan/scripts/` globally). It reads gitignored `specs/` (Glob silently finds nothing there) and gives each spec's `planDrafts` with its **Status:** line (`-prev` copies are `archived`; ignore them). Route on that status:
|
||||
Before Phase 1, run `node "<S>/specs.mjs" list` from the project root (`<S>`: `scripts/` beside this SKILL.md, `~/.agents/skills/plan2code-1-plan/scripts/` globally). It reads gitignored `specs/` (a file search silently finds nothing there) and gives each spec's `planDrafts` with its **Status:** line (`-prev` copies are `archived`; ignore them). Route on that status:
|
||||
- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4
|
||||
- Status "Escalated from Quick Task - Resume at Phase 2" or "Escalated from Test - Resume at Phase 2": Acknowledge, verify requirements, skip to Phase 2
|
||||
- Status "Draft" or "Complete": Ask user how to proceed
|
||||
@@ -119,7 +119,7 @@ After confirmation, proceed with analysis:
|
||||
>
|
||||
> Say 'skip testing' to omit."
|
||||
|
||||
Default if skipped: Phase Testing `None`, Full Suite `Never`.
|
||||
Question skipped or unanswered: infer the posture from `AGENTS.md`'s `## Test map` (else its test commands): tests exist → Phase Testing `Targeted per phase`, Full Suite `Offered at Finalize`; none found → `None`, `Never`. Say what you inferred and from what in the sign-off's Testing line. 'skip testing' said outright still writes `None` and `Never`.
|
||||
|
||||
7. Report confidence score
|
||||
8. **Requirements Sign-Off:**
|
||||
@@ -131,7 +131,7 @@ After confirmation, proceed with analysis:
|
||||
> **Non-Functional:**
|
||||
> NFR-1: [req]
|
||||
> ...
|
||||
> **Testing:** [types, phase testing, full suite, approach, or None]
|
||||
> **Testing:** [types, phase testing, full suite, approach, or None; "inferred from the test map" when you chose it]
|
||||
>
|
||||
> **Confirm:** Complete and accurate? (approved / needs changes)
|
||||
|
||||
@@ -298,11 +298,10 @@ When complete (PLAN-DRAFT created), tell user:
|
||||
> ╲│ ★ │╱
|
||||
> │ ◡ │ Planning done! Ready for documentation!
|
||||
> ╰┬─┬╯
|
||||
> =============================================
|
||||
> NEXT STEP: Start a NEW conversation then run:
|
||||
> `/plan2code-2-document --web`
|
||||
> ```"
|
||||
|
||||
In the terminal, end with `NEXT STEP: /plan2code-2-document --web` in a NEW conversation. The web console's finish carries it, so print nothing there.
|
||||
|
||||
## Abort / Recovery
|
||||
|
||||
- **Abort:** Confirm with user, list files needing cleanup, stop workflow
|
||||
|
||||
@@ -27,7 +27,7 @@ The FIRST thing you do, before anything else in this file — before Step 1, bef
|
||||
|
||||
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-1b-revise-plan/scripts/` globally). Run from the project root; each prints one JSON object, and on a non-zero exit `next` says what to do. They only ever touch `specs/`.
|
||||
|
||||
- `node "<S>/specs.mjs" list`: the active specs (it reads gitignored `specs/`, where Glob silently finds nothing).
|
||||
- `node "<S>/specs.mjs" list`: the active specs (it reads gitignored `specs/`, where a file search silently finds nothing).
|
||||
- `node "<S>/specs.mjs" status <spec>`: phases, task counts by marker, `checks`, `pending`.
|
||||
- `node "<S>/specs.mjs" mark <spec> --phase <N> --to open`: re-open a completed phase in overview.md.
|
||||
|
||||
@@ -195,21 +195,10 @@ Report and resolve issues (every `error` in `checks` included), then rerun `stat
|
||||
│ ◡ │ All revised! Ready to continue!
|
||||
╰┬─┬╯
|
||||
|
||||
╔═══════════════════════════════════════════════════════════════════╗
|
||||
║ REVISION COMPLETE ║
|
||||
╠═══════════════════════════════════════════════════════════════════╣
|
||||
║ ║
|
||||
║ Specs have been updated. To continue implementation: ║
|
||||
║ ║
|
||||
║ 1. Start a NEW conversation ║
|
||||
║ 2. Use command: /plan2code-3-implement --web ║
|
||||
║ 3. Provide path: specs/<feature-name>/overview.md ║
|
||||
║ ║
|
||||
║ The command will auto-detect the next Phase to implement. ║
|
||||
║ ║
|
||||
╚═══════════════════════════════════════════════════════════════════╝
|
||||
```
|
||||
|
||||
In the terminal, end with `REVISION COMPLETE: start a NEW conversation and run /plan2code-3-implement --web with specs/<feature-name>/overview.md` (it finds the next phase itself). The web console's finish carries it, so print nothing there.
|
||||
|
||||
### STEP 6: Revision Cleanup
|
||||
|
||||
`🔄 [REVISION] Step 6: Revision Cleanup`
|
||||
@@ -250,4 +239,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:** specs change only at Step 3, so stopping before then saves nothing. The finish command is `/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:** specs change only at Step 3, so stopping before then saves nothing. The finish command is `/plan2code-3-implement specs/<feature-name>/overview.md` when revised, or the revise-plan command on an abort.
|
||||
@@ -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 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.
|
||||
The FIRST thing you do, before anything else in this file — before Auto-Discovery: ask **web console** (browser page, 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. 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 Auto-Discovery.
|
||||
|
||||
## Scripts
|
||||
|
||||
@@ -38,7 +38,7 @@ Keep with you: the breakdown, the task writing and every question. Strength and
|
||||
|
||||
## Auto-Discovery
|
||||
|
||||
`specs/` is gitignored, so Glob silently finds nothing there; `specs.mjs` reads it directly.
|
||||
`specs/` is gitignored, so a file search silently finds nothing there; `specs.mjs` reads it directly.
|
||||
|
||||
**Before asking user for input:**
|
||||
|
||||
@@ -103,7 +103,7 @@ Line numbers may only appear as SUPPLEMENTAL context alongside a semantic refere
|
||||
3. **Analyze** planning document thoroughly
|
||||
4. **Identify** phase boundaries by dependencies and deliverables
|
||||
5. **Use existing** `specs/<feature-name>/` directory
|
||||
6. **Write** `overview.md` first, copying from PLAN-DRAFT:
|
||||
6. **Write** `overview.md` first (header with the format marker, see Templates), copying from PLAN-DRAFT:
|
||||
- Summary (from Executive Summary)
|
||||
- Phase Checklist (Implementation Phases), directly under Summary
|
||||
- Parallel Execution Groups (filled in step 8)
|
||||
@@ -183,7 +183,7 @@ Use kebab-case for feature name (e.g., `user-authentication`).
|
||||
|
||||
### overview.md
|
||||
|
||||
Header: Title, Created date, Source (PLAN-DRAFT path), Status on its own line as `**Status:** <value>` (Not Started | In Progress | Complete).
|
||||
Header: Title, Created date, Source (PLAN-DRAFT path), Status on its own line as `**Status:** <value>` (Not Started | In Progress | Complete), then the format marker on its own line, `<!-- plan2code-format: 2 -->` (it makes `specs.mjs check` hold this spec to the current format rules as errors).
|
||||
|
||||
Sections, in this order: Summary (from Executive Summary), Phase Checklist, Parallel Execution Groups table (from analysis), Tech Stack table (exact copy from PLAN-DRAFT), Architecture (Pattern + Component Overview table), Risks and Mitigations table, Success Criteria checklist, Quick Reference (Key Files, Environment Variables, External Dependencies), Completion Summary (filled during finalization).
|
||||
|
||||
@@ -245,13 +245,10 @@ Paste the `comment` from `specs.mjs metrics specs/<feature-name> --step document
|
||||
╲│ ★ │╱
|
||||
│ ◡ │ Specs are ready! Time to build!
|
||||
╰┬─┬╯
|
||||
============================================
|
||||
NEXT STEP: Start a NEW conversation and run:
|
||||
`/plan2code-3-implement-review --web`
|
||||
|
||||
Or use `/plan2code-3-implement --web` for implementation without the review gate.
|
||||
```
|
||||
|
||||
In the terminal, end with `NEXT STEP: start a NEW conversation and run /plan2code-3-implement-review --web` (or `/plan2code-3-implement --web` for implementation without the review gate). The web console's finish carries it, so print nothing there.
|
||||
|
||||
## Abort Handling
|
||||
|
||||
If user says "abort", "cancel", "start over":
|
||||
|
||||
@@ -45,35 +45,13 @@ State:
|
||||
|
||||
> 🔬 [Review Mode] Implementation complete; reviewing before sign-off.
|
||||
|
||||
Read references/review.md
|
||||
Read references/review.md and references/review-in-build.md
|
||||
|
||||
Run Review Mode with this explicit scope:
|
||||
|
||||
- Scope is **Focused**.
|
||||
- Review the exact phase change set tracked in Stage 1, including any relevant tests and documentation changed for the phase.
|
||||
- Use overview.md and the active phase file for spec-compliance context; they do not broaden scope to other phases.
|
||||
- Read related callers, dependencies, and project files when needed to verify a finding, but do not turn them into unrelated review targets.
|
||||
- Review all changed files completely and apply the full focused-review depth required by Review Mode.
|
||||
- Review Mode's helper rule applies: a fresh helper runs the analysis when available, at the strength `helper-strength.md` gives for the phase's review (standard and high, or strongest and high when the phase touches security, auth or data), this session verifies every finding, and the Stage 4 report carries the Reviewed by line. The helper's brief carries the phase's `phase-X.md` and its change set only, never Stage 1's work notes.
|
||||
|
||||
Override Review Mode's completion and session-end behavior:
|
||||
|
||||
1. Do not provide commit instructions or next-conversation routing.
|
||||
2. Do not ask the user to approve the review or commit.
|
||||
3. If there are findings, present Review Mode's normal `H`, `A`, and `S` fix options and wait for the user's choice.
|
||||
4. If there are zero findings, proceed directly to Stage 4.
|
||||
5. If the user explicitly declines or defers findings, preserve them as unresolved and proceed to Stage 4.
|
||||
Run Review Mode as `references/review-in-build.md` says, over the exact phase change set tracked in Stage 1 (including the relevant tests and documentation changed for the phase). Findings go to the person as Review Mode's `H`, `A` and `S` options; zero findings go straight to Stage 4, and declined or deferred findings stay unresolved.
|
||||
|
||||
## Stage 3: Resolve Findings
|
||||
|
||||
When the user selects fixes, follow Review Mode's Post-Fix Flow to plan, apply, and verify them.
|
||||
|
||||
- Add every review-fix file to the phase change set.
|
||||
- Re-read every file modified by a fix and check for introduced issues.
|
||||
- Update the Phase Completion Summary if a fix materially changes the implementation summary or test results.
|
||||
- Do not mark the phase complete and do not ask for approval during fix processing.
|
||||
- Ignore Review Mode's `Reply approved to commit` instruction; selected-fix verification transitions directly to Stage 4.
|
||||
- When selected fixes are verified, preserve any unselected findings as unresolved and proceed to Stage 4.
|
||||
When the user selects fixes, apply and verify them as `references/review-in-build.md` says (Fixing). Every review-fix file joins the phase change set. Selected-fix verification goes straight to Stage 4 with any unselected findings kept as unresolved; do not mark the phase complete or ask for approval here.
|
||||
|
||||
## Stage 4: Final Implementation Sign-Off
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ The FIRST thing you do, before anything else in this file — before reading a s
|
||||
|
||||
- `node "<S>/specs.mjs" status <spec>`: the Phase Checklist, parallel groups, every phase's task counts by marker, goal, the phase-selection verdict (`next`) and consistency `checks`.
|
||||
- `node "<S>/specs.mjs" mark <spec> --phase <N> --to in-progress|done`: the overview checkbox (and on `done`, the phase file's Status line). It refuses to reset `[/]` to `[ ]`.
|
||||
- `node "<S>/commit-msg.mjs" --subject "<subject>" --add-all`: the commit command (`<subject>`, then `AI Assisted`).
|
||||
- `node "<S>/commit-msg.mjs" --subject "<subject>" --files <path> ...`: the commit command for the phase's own files (`<subject>`, then `AI Assisted`).
|
||||
|
||||
## Rules
|
||||
|
||||
@@ -32,7 +32,7 @@ The FIRST thing you do, before anything else in this file — before reading a s
|
||||
|
||||
## Required Context
|
||||
|
||||
Needs the spec files. `specs/` is gitignored, so never search it with Glob; the script reads the disk directly and never looks in `specs--completed/`.
|
||||
Needs the spec files. `specs/` is gitignored, so never search it with a file search; the script reads the disk directly and never looks in `specs--completed/`.
|
||||
|
||||
**Option 1: User provides an overview.md path** → `specs.mjs status <that path>`.
|
||||
|
||||
@@ -78,7 +78,7 @@ Before acting on `ask-resume` or `choose`, read the Notes of each `[/]` phase on
|
||||
|
||||
### Manual Check-Off
|
||||
|
||||
`next.tasks` lists each open task (`id`, `marker`, `text`, `detail` with any BLOCKED / User action note). The spec is not built, and Finalize stays unavailable on the dashboard, until each is `[x]`. Say so in one line, then ask about them **one at a time**, in order:
|
||||
`next.tasks` lists each open task (`id`, `marker`, `text`, `detail` with any BLOCKED / User action note). The spec is not built until each is `[x]`; Finalize stays unavailable on the dashboard until then, or until the only ones left are `[!]` tasks that each carry a written reason (`status`'s `finalizeReady`). Say so in one line, then ask about them **one at a time**, in order:
|
||||
|
||||
1. Show the task: id, `text`, and what `detail` says the person must do or check.
|
||||
2. Ask: "Is this done? (yes / not yet)". Console: a `confirm` item (`yesLabel` "Done, check it off", `noLabel` "Not yet"), posted with `--wait`, a new id per task.
|
||||
@@ -147,7 +147,7 @@ After all tasks:
|
||||
4. Use Completion Report Format
|
||||
5. Do NOT mark phase `[x]` until user says "approved"
|
||||
6. Address issues before re-requesting sign-off
|
||||
7. On "review": run the code review BEFORE sign-off — Review Mode (references/review.md in the installed skill, src/plan2code-review.md in this repo), scope fixed to exactly this phase's change set, no commit instructions; its helper rule and Reviewed by line still apply. Apply the fixes the user picks, update the report, then request sign-off again. The phase stays `[/]` throughout.
|
||||
7. On "review": run the code review BEFORE sign-off as `references/review-in-build.md` says, over exactly this phase's change set. Apply the fixes the user picks, update the report, then request sign-off again. The phase stays `[/]` throughout.
|
||||
8. **Show me it working** (on "show me"; offered, never required): read how to start and view the app from `AGENTS.md` (Commands). Missing: work it out from the project (`package.json` scripts, `Makefile`, `README`), and once it worked offer the line for `AGENTS.md`; cannot work it out: ask the person. Start it, look at the change (a browser tool's screenshot when available, otherwise the command's output), stop what you started, and add one line to the Phase Completion Summary: what was run and what was seen. Screenshots go on the web console page only, never under `specs/`. Then request sign-off again.
|
||||
|
||||
## Issue Handling
|
||||
@@ -207,7 +207,7 @@ On user "approved":
|
||||
| Phase X: [Name] | Y | [One-sentence goal] |
|
||||
| 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.
|
||||
5. Write a one-line subject for the phase, then give the user the `command` from `commit-msg.mjs --subject "<subject>" --files <path> ...`, one `--files` per file the phase created or changed. 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 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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Community Feedback Submission (STEP 6.5 detail)
|
||||
|
||||
> Loaded by `src/plan2code-4-finalize.md` STEP 6.5. This file has no character limit (see `AGENTS-architecture.md` Reference Files).
|
||||
> Loaded by `src/plan2code-4-finalize.md` STEP 6.5. This file has no character limit (see `AGENTS-architecture-install.md` Reference Files).
|
||||
|
||||
Everything in the payload is read from files, so a script builds it: the metrics from the `METRICS_JSON` comments the pipeline already wrote, the task counts from the phase files, your Step 5 answers from overview.md's `## User Feedback` table, the installed version, and a sha256 prefix of each prompt. Your part is the two judgment counts, the preview, and the user's approval.
|
||||
|
||||
|
||||
@@ -14,7 +14,11 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import { EXIT, HERE, fail, out, parseArgs, run, readText, isDir, rel, compactDate, clock, version, phaseFiles } from "./common.mjs";
|
||||
import { EXIT, HERE, fail, out, parseArgs, run, readText, isDir, rel, compactDate, clock, version, consoleModule } from "./common.mjs";
|
||||
|
||||
// The phase-file pick specs.mjs and the dashboard use (the console's
|
||||
// spec-files.mjs), bound in run() before any command.
|
||||
let pickPhaseFiles;
|
||||
|
||||
const USAGE = `
|
||||
feedback-payload.mjs: build and submit the community feedback payload. JSON on stdout.
|
||||
@@ -115,7 +119,7 @@ function parseFeedbackTable(overview) {
|
||||
function phaseTasks(dir) {
|
||||
const c = { total: 0, complete: 0, assumed: 0, blocked: 0 };
|
||||
// The same files specs.mjs reads: a stale sibling like phase-1-old.md is not counted.
|
||||
for (const n of phaseFiles(dir).values()) {
|
||||
for (const n of pickPhaseFiles(fs.readdirSync(dir)).values()) {
|
||||
for (const line of (readText(path.join(dir, n)) || "").split(/\r?\n/)) {
|
||||
// The same task line specs.mjs counts: 2.3, 3.6a, or a named 1.T.
|
||||
const m = line.match(/^\s*[-*] \[(.)\]\s+\*\*Task\s+\d+\.(?:\d+|[A-Za-z]+)[a-z]*\b/);
|
||||
@@ -371,6 +375,7 @@ async function cmdSubmit(args) {
|
||||
}
|
||||
|
||||
run(USAGE, async (argv) => {
|
||||
({ pickPhaseFiles } = await consoleModule("spec-files.mjs"));
|
||||
const args = parseArgs(argv, { booleans: ["dry-run", "truncate"], values: ["root", "out", "from"], lists: ["set"] });
|
||||
const cmd = args._[0];
|
||||
if (cmd === "build") return cmdBuild(args);
|
||||
|
||||
@@ -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 read <D>/console.md and <D>/notes/finalize.md; the audit options, the final review, 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.
|
||||
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 final review, the doc-update approval and every cleanup confirmation 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 Required Context check.
|
||||
|
||||
## Scripts
|
||||
|
||||
@@ -36,7 +36,7 @@ The FIRST thing you do, before anything else in this file — before the Require
|
||||
|
||||
### Required Context
|
||||
|
||||
Need all implementation spec files. If the user hasn't named the spec, run `specs.mjs list` (it reads gitignored `specs/` directly, where Glob silently finds nothing, and never offers `specs--completed/`, which holds archives only). Exactly one active spec → use it.
|
||||
Need all implementation spec files. If the user hasn't named the spec, run `specs.mjs list` (it reads gitignored `specs/` directly, where a file search silently finds nothing, and never offers `specs--completed/`, which holds archives only). Exactly one active spec → use it.
|
||||
|
||||
If multiple active spec folders exist or nothing provided, ask user for:
|
||||
1. The entire `specs/<feature-name>/` directory: `overview.md` and all `phase-X.md` files
|
||||
@@ -209,11 +209,12 @@ Add this summary to `overview.md` under `## Completion Summary`.
|
||||
|----------|-----------|--------|
|
||||
| `AGENTS.md` + `.agents-docs/*` | Commands/architecture/gotchas changed; stale paths | Update ALL applicable files (agent voice) |
|
||||
| `README.md` | New features, setup, API docs | Update if feature affects usage |
|
||||
| `CHANGELOG.md` | Version history | Add entry for feature |
|
||||
| `.env.example` | Environment variables | Add new required vars |
|
||||
| `API.md` / human docs | API documentation | Update with new endpoints |
|
||||
| `CLAUDE.md` | AI assistant context | Update if patterns changed |
|
||||
|
||||
The CHANGELOG is the Changelog skill's job (the web console's finish offers it): Finalize writes no entry.
|
||||
|
||||
Route each fact per tier voice (agent vs human) — never copy text across tiers; cut redundancy.
|
||||
|
||||
Report: table of documents needing updates with proposed changes. List each document with specific additions.
|
||||
@@ -323,7 +324,6 @@ Paste the `comment` from `specs.mjs metrics <spec's current path: specs--complet
|
||||
- `specs/<feature-name>/overview.md` - Added completion summary
|
||||
- [each file a Step 2.5 fix changed, if any]
|
||||
- `README.md` - [if updated]
|
||||
- `CHANGELOG.md` - [if updated]
|
||||
|
||||
### Archived Files
|
||||
[List all files moved to specs--completed/<feature-name>/]
|
||||
@@ -374,7 +374,7 @@ 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 Step 2.5 fixes landed or 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**.
|
||||
Suggested commit (only if Step 2.5 fixes landed or README 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>/`.
|
||||
|
||||
|
||||
@@ -185,8 +185,12 @@ async function prHosts() {
|
||||
return (await consoleModule("settings.mjs")).readPrHosts();
|
||||
}
|
||||
|
||||
// A status that failed (or ran past git()'s time limit) is an unknown tree,
|
||||
// never a clean one: a plan built on it would offer to commit nothing.
|
||||
function readStatus(root) {
|
||||
return R.parseStatusV2(g(["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=normal"], root, { raw: true }).out);
|
||||
const res = g(["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=normal"], root, { raw: true });
|
||||
if (!res.ok) fail(EXIT.CRASH, "status-failed", `git status failed: ${res.err || "no message"}`, "Run git status yourself to see why, then try again.");
|
||||
return R.parseStatusV2(res.out);
|
||||
}
|
||||
|
||||
// The commit flow's lists and letters: a conflicted file only under conflicted.
|
||||
|
||||
@@ -26,7 +26,7 @@ Determine it like this:
|
||||
2. **Present it to the user for confirmation before writing the file.** If you
|
||||
inferred a candidate, show it and ask them to confirm or correct it. If you
|
||||
genuinely can't infer one, ask them to tell you what the next agent should do.
|
||||
Use `AskUserQuestion` (offer your inferred task as the recommended option) or
|
||||
Use the question tool (offer your inferred task as the recommended option) or
|
||||
a plain question — either is fine.
|
||||
3. **Do not write the document until the user has confirmed or supplied the next
|
||||
task.** This gate is mandatory even when your inference feels obviously
|
||||
@@ -50,7 +50,7 @@ The dashboard lists the handoff for this checkout until it is picked up, and old
|
||||
|
||||
## If this touched a plan2code spec
|
||||
|
||||
`specs/` is gitignored — Glob/Grep and file search silently skip it. If the
|
||||
`specs/` is gitignored — file search and text search silently skip it. If the
|
||||
conversation worked inside `specs/<feature>/`, confirm the exact state before
|
||||
writing with `node "<S>/specs.mjs" status specs/<feature>` (`<S>` is `scripts/` beside this SKILL.md: `~/.agents/skills/plan2code-handoff/scripts/` globally), which reads the disk:
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ The FIRST thing you do, before anything else in this file — before the Awarene
|
||||
|
||||
## Awareness Context
|
||||
|
||||
Before making any updates, orient yourself to current project state: read `AGENTS.md` and `README.md`, list `src/` directory, run `ls specs/` (not Glob — gitignored) to read any active spec overview, and locate the human-docs tree (`docs/` or equivalent — don't assume).
|
||||
Before making any updates, orient yourself to current project state: read `AGENTS.md` and `README.md`, list `src/` directory, run `ls specs/` (not a file search — gitignored) to read any active spec overview, and locate the human-docs tree (`docs/` or equivalent — don't assume).
|
||||
|
||||
## Helpers
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ The FIRST thing you do, before anything else in this file — before exploring t
|
||||
|
||||
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-init/scripts/` globally). Run from the project root; each prints one JSON object, and on a non-zero exit `next` says what to do.
|
||||
|
||||
- `node "<S>/agents-md.mjs" inspect`: does AGENTS.md exist, its line count against 500, `structure` (`progressive` or `single-file`), sections, `.agents-docs/` files, broken links, orphans. Run it first.
|
||||
- `node "<S>/agents-md.mjs" inspect`: does AGENTS.md exist, its line count against 500, `structure` (`progressive` or `single-file`), sections, `.agents-docs/` files, broken links, orphans. Run it first. Any `notices` it returns (such as `specs--completed/` being gitignored, so finished specs are not backed up): tell the user once, in your closing summary.
|
||||
- `node "<S>/agents-md.mjs" filename "<Section Name>"`: a section's detail file name, its `Details:` link line and its two header lines.
|
||||
- `node "<S>/agent-files.mjs" detect` / `apply <id> ... [--dry-run]`: AI Agent File Sync (below).
|
||||
|
||||
|
||||
@@ -161,6 +161,6 @@ Ready to implement? (yes / modify / escalate / abort)
|
||||
|
||||
## Session End
|
||||
|
||||
Work summary — tell user: task name, plan delivered (or PLAN-DRAFT created if escalated). After a build, offer: "Reply `show me` to see it running." **Show me it working** (offered, never required): start the app as `AGENTS.md` Commands says (missing: work it out from `package.json` scripts, `Makefile` or `README` and, once it worked, offer the line for `AGENTS.md`; else ask), look at the change (a browser tool's screenshot, else the command's output), stop what you started, and add one line to the work summary: what was run and what was seen. Screenshots go on the web console page only.
|
||||
Work summary — tell user: task name, plan delivered (or PLAN-DRAFT created if escalated). After a build, offer: "Reply `show me` to see it running." A review the person asks for after the build runs as `references/review-in-build.md` says. **Show me it working** (offered, never required): start the app as `AGENTS.md` Commands says (missing: work it out from `package.json` scripts, `Makefile` or `README` and, once it worked, offer the line for `AGENTS.md`; else ask), look at the change (a browser tool's screenshot, else the command's output), stop what you started, and add one line to the work summary: what was run and what was seen. Screenshots go on the web console page only.
|
||||
|
||||
**On the web console:** after a build, keep waiting for the review button's answer before you stop.
|
||||
@@ -5,7 +5,7 @@ Principles to reason from, not a lookup table — adapt; when a case doesn't fit
|
||||
cleanly, say what you verified and ask.
|
||||
|
||||
- **Plan2Code Workflow Pipeline:** `/plan2code-1-plan` → `PLAN-*` files · `/plan2code-2-document` → `overview.md` + `phase-*.md` (the "spec docs") in `specs/<feature>/` · `/plan2code-3-implement` → checks off phase tasks, one phase per run · `/plan2code-4-finalize` → archives to `specs--completed/`.
|
||||
- **Find specs (any OS/shell):** `specs/` is gitignored, and search tools (Glob/Grep/project search) skip gitignored paths on many platforms — an empty search result is not evidence either way. Use `node "<S>/specs.mjs" list` (`<S>`: see Review Mode → Scripts) (feature dir unknown, or to see what is archived in `completed`) and `node "<S>/specs.mjs" status <spec>`: they read the disk directly. Its fields map onto the routing below: `planDrafts` with no `overview` · `overview` with no phases · each phase's `tasks.open` · a name in `completed`. If the script cannot run, read the expected files directly — file reads see gitignored paths. Conclude "no specs" only after `list` or a failed direct read.
|
||||
- **Find specs (any OS/shell):** `specs/` is gitignored, and search tools (file search, text search, project search) skip gitignored paths on many platforms — an empty search result is not evidence either way. Use `node "<S>/specs.mjs" list` (`<S>`: see Review Mode → Scripts) (feature dir unknown, or to see what is archived in `completed`) and `node "<S>/specs.mjs" status <spec>`: they read the disk directly. Its fields map onto the routing below: `planDrafts` with no `overview` · `overview` with no phases · each phase's `tasks.open` · a name in `completed`. If the script cannot run, read the expected files directly — file reads see gitignored paths. Conclude "no specs" only after `list` or a failed direct read.
|
||||
- **Reconcile three signals:** session context (what this conversation was doing — a fresh session may have none), user intent (what they asked reviewed), the disk check above. Disk wins on state; context wins on intent and on disk silence; no context → intent + disk decide.
|
||||
- **plan2code artifact reviewed (a plan, the spec docs, phases) — route on the reviewed feature's own `specs/<feature>/` state (another feature's specs prove nothing here), to the earliest unmet stage, suggesting only a step whose input exists:**
|
||||
- `PLAN-*` without `overview.md` → `/plan2code-2-document`
|
||||
|
||||
@@ -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-review.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: `references/review-in-build.md`, `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.
|
||||
|
||||
@@ -52,7 +52,7 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
|
||||
## Process
|
||||
|
||||
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, scan and use `ask_user_question` (Step 1) — never guess.
|
||||
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, scan and use the question tool (Step 1) — never guess.
|
||||
|
||||
**Reference files:** Companion files loaded via Read directives. Fallback rules inline if unavailable.
|
||||
|
||||
@@ -62,10 +62,10 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
|
||||
1. **User prompt** — use it.
|
||||
2. **Conversation context** — recent work? Those artifacts. Scope: `focused`.
|
||||
3. **Standalone, nothing named** — do not assume a target. Do a quick scan (no file reading): `review-scope.mjs`, `specs.mjs list`, recent commits. Then ask what to review (`ask_user_question`; a `choice` on the console, scope questions up front), offering only options the scan supports, each with its size: the branch's changes vs base (files, ~lines, `commits`), uncommitted changes only (when any), a spec/plan under `specs/` (when any), a named subsystem or full codebase, or specific files/folders (free text via Other). Recommend the likeliest first. Nothing found (`empty: true`, no specs)? Ask for files or a subsystem. Use the answer as the scope, then continue.
|
||||
3. **Standalone, nothing named** — do not assume a target. Do a quick scan (no file reading): `review-scope.mjs`, `specs.mjs list`, recent commits. Then ask what to review (the question tool; a `choice` on the console, scope questions up front), offering only options the scan supports, each with its size: the branch's changes vs base (files, ~lines, `commits`), uncommitted changes only (when any), a spec/plan under `specs/` (when any), a named subsystem or full codebase, or specific files/folders (free text via Other). Recommend the likeliest first. Nothing found (`empty: true`, no specs)? Ask for files or a subsystem. Use the answer as the scope, then continue.
|
||||
4. **Scan details** — `review-scope.mjs` diffs the branch against its base (`main`, else `master`, or `--base`) plus staged, unstaged and untracked changes: `files`, `counts`, `commits`, `mix`, `batchByRisk`. `empty: true` or exit 3 `not-a-repo`? Ask user what to review. Exit 3 `no-base`? Rerun with `--base <trunk>`, asking which branch is the trunk if unclear.
|
||||
|
||||
**Classify review type** from context (auto-detect; use `ask_user_question` only if ambiguous):
|
||||
**Classify review type** from context (auto-detect; use the question tool only if ambiguous):
|
||||
|
||||
| Signal | Type | Prioritize |
|
||||
|--------|------|-------------|
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Review Inside a Build
|
||||
> Read by Review, Implement, Implement + Review and Quick Task when a review runs inside a build: before a phase is signed off, or after a quick task is built. Never invoked as a skill. The web console's `building-review.md` adds only what the page does differently.
|
||||
|
||||
Run Review Mode (`references/review.md`, or this skill's own SKILL.md in Review) with these rules. They win over Review Mode's own scope questions, completion and session-end steps.
|
||||
|
||||
## Scope
|
||||
|
||||
- Scope is **Focused** and already decided. Do not ask about it.
|
||||
- The change set is exact: files created or modified in this build (the phase or the quick task), the artifacts its tasks name, and the tests and docs changed for it. Unrelated working-tree changes are not in it.
|
||||
- `overview.md` and the phase file give spec-compliance context. They never widen the scope to other phases.
|
||||
- Read callers, dependencies and project files when you need them to verify a finding. They are not review targets.
|
||||
- Review every changed file completely, at the full Focused depth Review Mode requires.
|
||||
|
||||
## Who reviews
|
||||
|
||||
A fresh helper runs the analysis when your tool can start one and helpers are not switched off, at the strength `references/helper-strength.md` gives (standard and high; strongest and high when the change touches security, auth or data). This session verifies every finding. The report carries the Reviewed by line. The helper's brief holds the phase file (when there is one) and the change set only, never the build's work notes.
|
||||
|
||||
## Ending the review
|
||||
|
||||
- No commit instructions, no next-conversation routing, and no request to approve the review or a commit. Ignore Review Mode's `Reply approved to commit`.
|
||||
- Findings: offer Review Mode's `H`, `A` and `S` fix options and wait. Zero findings: go straight back to the build's report. Findings the person declines or defers stay as unresolved.
|
||||
|
||||
## Fixing
|
||||
|
||||
Follow Review Mode's Post-Fix Flow. Add every fixed file to the change set, re-read each one and check it for new problems, and run the tests that cover the fixes (`references/test-runs.md`). Update the completion summary only when a fix changes what it says. Choosing fixes is never approval.
|
||||
|
||||
## Back to the build
|
||||
|
||||
- The phase stays `[/]` and no checkbox moves. Only the build's own sign-off prompt, asked after the review, can approve.
|
||||
- The final report adds **Review Results** (scope, files reviewed, the Reviewed by line, totals by severity, fixes applied) and **Unresolved Review Findings** (a short numbered list, or `None`), and its Verify section includes the fix checks.
|
||||
- A quick task has no sign-off: its summary carries the same review results and the commit command for the task and its fixes together.
|
||||
@@ -19,7 +19,9 @@ agents-md.mjs: inspect AGENTS.md and .agents-docs/. JSON on stdout.
|
||||
(progressive or single-file), every ## section with its line count and
|
||||
its Details link, the always-inline sections, .agents-docs/ files with
|
||||
their breadcrumb check, broken links, orphan section files (no link from
|
||||
AGENTS.md).
|
||||
AGENTS.md). With no AGENTS.md yet (Init's first run, so it is said
|
||||
once), "notices" warns when .gitignore keeps specs--completed/ out of
|
||||
git: finished specs archived there are not backed up.
|
||||
|
||||
node agents-md.mjs filename "<Section Name>"
|
||||
The detail file for a section: AGENTS-<kebab-case>.md, its link line
|
||||
@@ -66,6 +68,22 @@ function sectionsOf(text) {
|
||||
return outList;
|
||||
}
|
||||
|
||||
// A .gitignore line that keeps specs--completed/ out of git: the folder
|
||||
// itself, or a specs* pattern that takes it along.
|
||||
const IGNORES_COMPLETED_RE = /^\/?(?:specs--completed|specs-\*|specs\*)\/?(?:\*\*?)?$/;
|
||||
|
||||
/** The one-time notices for a project Init is about to set up. */
|
||||
function firstRunNotices(root) {
|
||||
const lines = (readText(path.join(root, ".gitignore")) || "").split(/\r?\n/).map((l) => l.trim());
|
||||
if (!lines.some((l) => IGNORES_COMPLETED_RE.test(l))) return [];
|
||||
return [
|
||||
{
|
||||
code: "specs-not-backed-up",
|
||||
message: "specs--completed/ is gitignored, so finished specs archived there are not in git and not backed up. Copy that folder somewhere safe, or remove its .gitignore line to commit it.",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function inspect(root) {
|
||||
const file = path.join(root, "AGENTS.md");
|
||||
const text = readText(file);
|
||||
@@ -86,7 +104,7 @@ function inspect(root) {
|
||||
})
|
||||
: [];
|
||||
if (text === null) {
|
||||
return { ok: true, root, exists: false, hasAgentsDocs: hasDocs, agentsDocs: docFiles, otherFiles: ["CLAUDE.md", "README.md", "PROJECT.md", "GEMINI.md", ".cursorrules", ".github/copilot-instructions.md"].filter((f) => fs.existsSync(path.join(root, f))) };
|
||||
return { ok: true, root, exists: false, notices: firstRunNotices(root), hasAgentsDocs: hasDocs, agentsDocs: docFiles, otherFiles: ["CLAUDE.md", "README.md", "PROJECT.md", "GEMINI.md", ".cursorrules", ".github/copilot-instructions.md"].filter((f) => fs.existsSync(path.join(root, f))) };
|
||||
}
|
||||
const sections = sectionsOf(text);
|
||||
const linked = new Set();
|
||||
|
||||
@@ -15,13 +15,14 @@ import { EXIT, fail, out, parseArgs, run } from "./common.mjs";
|
||||
const USAGE = `
|
||||
commit-msg.mjs: build the commit command from a subject. JSON on stdout.
|
||||
|
||||
node commit-msg.mjs --subject "<subject>" [--add-all | --files <path> ...]
|
||||
node commit-msg.mjs --subject "<subject>" [--files <path> ...]
|
||||
|
||||
--subject the one-line description (at most 100 characters). No double
|
||||
quotes (straight or curly), backticks, $, backslashes or ! in it,
|
||||
so the command pastes unchanged into bash, zsh and PowerShell.
|
||||
--add-all prefix the command with "git add -A &&".
|
||||
--files prefix it with "git add -- <files> &&" (repeat --files per path).
|
||||
--files prefix the command with "git add -- <files> &&" (repeat
|
||||
--files per path). Name the files the work changed: there is
|
||||
no add-everything option, so nothing unrelated gets staged.
|
||||
|
||||
Prints { ok, subject, message, command, add, commit }. The commit is two -m
|
||||
flags, exactly: subject, "AI Assisted". command is add && commit, one line for
|
||||
@@ -41,12 +42,12 @@ function quoteFile(f) {
|
||||
const p = f.replace(/\\/g, "/");
|
||||
if (/^[\w./:+][\w./:@+-]*$/.test(p)) return p;
|
||||
// PowerShell treats the curly single quotes as quote characters too.
|
||||
if (/['\u2018-\u201B]/.test(p)) fail(EXIT.INVALID, "unsafe-path", `The path ${p} contains a single quote, which cannot be quoted the same way in bash and PowerShell.`, "Use --add-all, or leave that file out and stage it by hand.");
|
||||
if (/['\u2018-\u201B]/.test(p)) fail(EXIT.INVALID, "unsafe-path", `The path ${p} contains a single quote, which cannot be quoted the same way in bash and PowerShell.`, "Leave that file out of --files and stage it by hand.");
|
||||
return `'${p}'`;
|
||||
}
|
||||
|
||||
run(USAGE, async (argv) => {
|
||||
const args = parseArgs(argv, { booleans: ["add-all"], values: ["subject"], lists: ["files"] });
|
||||
const args = parseArgs(argv, { values: ["subject"], lists: ["files"] });
|
||||
if (args._.length) fail(EXIT.USAGE, "stray-argument", `Unexpected argument(s): ${args._.join(" ")}.`, "Each path needs its own --files (e.g. --files a.js --files b.js); quote a subject with spaces.");
|
||||
const subject = (args.subject || "").trim();
|
||||
if (!subject) fail(EXIT.USAGE, "missing-subject", "--subject is required.", 'Example: --subject "Add the export endpoint"');
|
||||
@@ -56,9 +57,8 @@ run(USAGE, async (argv) => {
|
||||
// bash and zsh treat \ as an escape, and ! is history expansion in an
|
||||
// interactive bash or zsh.
|
||||
if (/["`$\\!\u201C-\u201F]/.test(subject)) fail(EXIT.INVALID, "unsafe-subject", "The subject contains a double quote (straight or curly), backtick, $, backslash or !, which bash, zsh and PowerShell read differently inside double quotes.", "Rephrase without those characters (single quotes are fine).");
|
||||
if (args["add-all"] && args.files) fail(EXIT.USAGE, "add-conflict", "Use --add-all or --files, not both.", "Pick one.");
|
||||
|
||||
const add = args["add-all"] ? "git add -A" : args.files ? `git add -- ${args.files.map(quoteFile).join(" ")}` : null;
|
||||
const add = args.files ? `git add -- ${args.files.map(quoteFile).join(" ")}` : null;
|
||||
const commit = `git commit -m "${subject}" -m "AI Assisted"`;
|
||||
out({
|
||||
ok: true,
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
// Node 18+ built-ins only, no build step: this ships inside every skill.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
|
||||
@@ -182,28 +183,8 @@ export function eol(text) {
|
||||
return text.includes("\r\n") ? "\r\n" : "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* phase-N.md per phase number. An exact phase-N.md always wins over a sibling
|
||||
* such as phase-1-old.md; more than one candidate is reported, never guessed.
|
||||
* Shared so every script that counts a spec's tasks reads the same files.
|
||||
*/
|
||||
export function phaseFiles(dir) {
|
||||
const files = new Map();
|
||||
const extra = new Map();
|
||||
for (const name of fs.readdirSync(dir).sort()) {
|
||||
const m = name.match(/^phase-(\d+)\b[^/]*\.md$/i);
|
||||
if (!m) continue;
|
||||
const n = Number(m[1]);
|
||||
const exact = new RegExp(`^phase-0*${n}\\.md$`, "i").test(name);
|
||||
if (!files.has(n)) files.set(n, name);
|
||||
else if (exact) {
|
||||
(extra.get(n) || extra.set(n, []).get(n)).push(files.get(n));
|
||||
files.set(n, name);
|
||||
} else (extra.get(n) || extra.set(n, []).get(n)).push(name);
|
||||
}
|
||||
files.extra = extra;
|
||||
return files;
|
||||
}
|
||||
// A spec's phase files are picked by pickPhaseFiles() in the web console's
|
||||
// spec-files.mjs (through consoleModule()), the one rule the dashboard uses.
|
||||
|
||||
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
|
||||
export function rel(root, p) {
|
||||
@@ -216,14 +197,19 @@ export function rel(root, p) {
|
||||
// fake a finished run. The one copy every skill script checks against.
|
||||
export const LOOP_TOKENS = /\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
|
||||
|
||||
// The metrics collector's own scrape patterns (plan2code-metrics/src/collector.ts).
|
||||
// The metrics collector's own scrape patterns. One shared source,
|
||||
// src/web-console/metrics-pattern.json (the console's bait scanner reads it,
|
||||
// the collector keeps a copy); a skill script is installed alone and cannot
|
||||
// read it, so these are copies and scripts/test-web-console-hardening.mjs fails
|
||||
// when any copy drifts. A label then a number in a table row counts only when
|
||||
// the number ends the row, so an ordinary risk-register row is left alone.
|
||||
export const SCRAPE = [
|
||||
{ name: "overall confidence with %", re: /(?:Overall|Final|Total)?\s*\**[Cc]onfidence\**[:\s*]+(\d{1,3})%/ },
|
||||
{ name: "confidence table cell", re: /[|]\s*[Cc]onfidence\s*[|]\s*(\d{1,3})/ },
|
||||
{ name: "bare Requirements + number", re: /[Rr]equirements?[:\s|]+(\d{1,2})/ },
|
||||
{ name: "bare Feasibility + number", re: /[Ff]easibility[:\s|]+(\d{1,2})/ },
|
||||
{ name: "bare Integration + number", re: /[Ii]ntegration[:\s|]+(\d{1,2})/ },
|
||||
{ name: "bare Risk + number", re: /[Rr]isk[:\s|]+(\d{1,2})/ },
|
||||
{ name: "bare Requirements + number", re: /[Rr]equirements?(?:[:\s]+|[ \t:]*\|[ \t:|]*(?=\d{1,2}(?:\/\d+)?[ \t]*\|?[ \t]*$))(\d{1,2})/m },
|
||||
{ name: "bare Feasibility + number", re: /[Ff]easibility(?:[:\s]+|[ \t:]*\|[ \t:|]*(?=\d{1,2}(?:\/\d+)?[ \t]*\|?[ \t]*$))(\d{1,2})/m },
|
||||
{ name: "bare Integration + number", re: /[Ii]ntegration(?:[:\s]+|[ \t:]*\|[ \t:|]*(?=\d{1,2}(?:\/\d+)?[ \t]*\|?[ \t]*$))(\d{1,2})/m },
|
||||
{ name: "bare Risk + number", re: /[Rr]isk(?:[:\s]+|[ \t:]*\|[ \t:|]*(?=\d{1,2}(?:\/\d+)?[ \t]*\|?[ \t]*$))(\d{1,2})/m },
|
||||
];
|
||||
|
||||
/** Every SCRAPE pattern that matches `text`, as `<name>: "<match>"`. */
|
||||
@@ -238,15 +224,26 @@ export function scrapeHits(text) {
|
||||
|
||||
/* --------------------------------------------------------- the web console */
|
||||
|
||||
// The web console ships beside these scripts in every installed skill
|
||||
// (references/web-console/), and in this repo it sits at src/web-console/. Its
|
||||
// scan.mjs is the one home of the spec-state classifier, and its settings.mjs
|
||||
// of the pull-request host store, so the scripts import them rather than keep
|
||||
// a second copy.
|
||||
const CONSOLE_DIR_CANDIDATES = [
|
||||
path.join(HERE, "..", "references", "web-console"), // installed skill
|
||||
path.join(HERE, "..", "web-console"), // src/skill-scripts in the repo
|
||||
];
|
||||
// The web console is installed once and shared by every skill: under
|
||||
// ~/.plan2code/console/<version>/, found through the console-dir pointer, and in
|
||||
// a checkout's built skills/ tree as the sibling skills/_console/<version>/. In
|
||||
// this repo it also sits at src/web-console/. Its scan.mjs is the one home of
|
||||
// the spec-state classifier, and its settings.mjs of the pull-request host
|
||||
// store, so the scripts import them rather than keep a second copy. A skill's
|
||||
// own references/web-console/ holds a stub and notes, and is tried first only
|
||||
// for a build that still carries a whole console.
|
||||
function consoleDirCandidates() {
|
||||
const dirs = [
|
||||
path.join(HERE, "..", "references", "web-console"), // a skill that carries a whole console
|
||||
path.join(HERE, "..", "web-console"), // src/skill-scripts in the repo
|
||||
];
|
||||
const v = version();
|
||||
if (v) dirs.push(path.join(HERE, "..", "..", "_console", v)); // a checkout's built skills/
|
||||
const home = process.env.PLAN2CODE_CONSOLE_HOME || path.join(os.homedir(), ".plan2code", "console");
|
||||
const pointed = (readText(path.join(home, "console-dir")) || "").trim();
|
||||
if (pointed) dirs.push(pointed); // the installed, shared console
|
||||
return dirs;
|
||||
}
|
||||
|
||||
const consoleModules = new Map();
|
||||
/** One of the web console's modules by file name ("scan.mjs"), imported once. */
|
||||
@@ -255,7 +252,7 @@ export function consoleModule(file) {
|
||||
consoleModules.set(
|
||||
file,
|
||||
(async () => {
|
||||
const candidates = CONSOLE_DIR_CANDIDATES.map((dir) => path.join(dir, file));
|
||||
const candidates = consoleDirCandidates().map((dir) => path.join(dir, file));
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
|
||||
}
|
||||
@@ -271,23 +268,20 @@ export function consoleModule(file) {
|
||||
return consoleModules.get(file);
|
||||
}
|
||||
|
||||
// The one read-only git reader (git-repo.mjs) ships beside scan.mjs, so the git
|
||||
// The one read-only git reader (git-repo.mjs) sits beside scan.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) {
|
||||
const candidates = consoleDirCandidates().map((dir) => path.join(dir, "git-repo.mjs"));
|
||||
for (const candidate of 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 web console's git-repo.mjs is not beside this script (looked in ${candidates.join(", ")}).`,
|
||||
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
|
||||
);
|
||||
})();
|
||||
|
||||
+117
-21
@@ -14,7 +14,7 @@
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, consoleModule, isoDate, phaseFiles, LOOP_TOKENS, scrapeHits } from "./common.mjs";
|
||||
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, consoleModule, isoDate, LOOP_TOKENS, scrapeHits } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
|
||||
@@ -25,7 +25,8 @@ specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
|
||||
phase count. Also the names already archived in specs--completed/.
|
||||
|
||||
node specs.mjs status <spec> [--root <dir>]
|
||||
One spec in full: the overview's Phase Checklist, Parallel Execution
|
||||
One spec in full: its dashboard state (state, stateDetail,
|
||||
finalizeReady; null before Document), the overview's Phase Checklist, Parallel Execution
|
||||
Groups, per-phase task counts by marker, task-numbering problems,
|
||||
completion, the implement phase-selection verdict ("next": choose,
|
||||
ask-resume, auto-start, checkoff or none), the pending
|
||||
@@ -37,7 +38,11 @@ specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
|
||||
checkbox under ## Tasks being a "- [ ] **Task N.M:**" line, no loop
|
||||
completion token and no bare metric word (outside a METRICS_JSON
|
||||
comment) in overview.md or a phase file. An indented " - Test:"
|
||||
sub-bullet is fine. Exit 4 with the problems when any is an error.
|
||||
sub-bullet is fine. The format rules (a phase file with no Status
|
||||
line, a checkbox under Notes, a task pointing at a line number, a [!]
|
||||
task with no reason) are errors when overview.md carries
|
||||
"<!-- plan2code-format: 2 -->" and warnings otherwise. Exit 4 with the
|
||||
problems when any is an error.
|
||||
|
||||
node specs.mjs check-draft <file|spec> [--root <dir>]
|
||||
Fail on a malformed PLAN-DRAFT (a path, or a spec's newest non-archived
|
||||
@@ -62,8 +67,9 @@ specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
|
||||
node specs.mjs mark <spec> --phase <N> --to open|in-progress|done [--dry-run]
|
||||
Set phase N's Phase Checklist marker in overview.md ([ ], [/], [x]).
|
||||
done also sets the phase file's Status line (**Status:**, **Status**:
|
||||
or Status:) to Complete (and warns if tasks are unfinished); open on a
|
||||
Complete phase sets it to In Progress. Warns when the phase file has no
|
||||
or Status:) to Complete (and warns if tasks are unfinished);
|
||||
in-progress sets it to In Progress, and so does open on a Complete
|
||||
phase. Warns when the phase file has no
|
||||
Status line. Refuses a phase with duplicate checklist rows, and refuses
|
||||
in-progress -> open (started work stays marked).
|
||||
|
||||
@@ -76,7 +82,9 @@ specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
|
||||
|
||||
node specs.mjs archive <spec> [--dry-run]
|
||||
Move specs/<name>/ to specs--completed/<name>/. Refuses if the target
|
||||
exists, or if <spec> is not a folder directly under specs/.
|
||||
exists, or if <spec> is not a folder directly under specs/. When the
|
||||
move has to copy, the source is removed only after every file name
|
||||
and size at the target matches it.
|
||||
|
||||
Markers: [ ] pending · [/] in progress · [x] complete · [!] blocked · [?] assumed.
|
||||
Exit: 0 ok · 2 bad arguments · 3 spec not found · 4 cannot parse / check
|
||||
@@ -123,11 +131,17 @@ function resolveSpec(root, arg, { allowArchived = false } = {}) {
|
||||
/* -------------------------------------------------------------- parsing */
|
||||
|
||||
// The task markers, the task-line (TASK_RE: marker, phase, task, sub-task
|
||||
// suffix), checkbox and Status-line patterns, and statusOf(), come from the web
|
||||
// console's spec-files.mjs, so this script and the dashboard read a spec the
|
||||
// same way. run() binds them once before any command, so the synchronous
|
||||
// readers below keep using them as plain module bindings.
|
||||
let MARKERS, TASK_RE, CHECKBOX_RE, STATUS_RE, statusOf;
|
||||
// suffix), checkbox and Status-line patterns, statusOf(), the phase-file pick
|
||||
// and deriveSpecState() come from the web console's spec-files.mjs, so this
|
||||
// script and the dashboard read a spec, and name its state, the same way.
|
||||
// run() binds them once before any command, so the synchronous readers below
|
||||
// keep using them as plain module bindings.
|
||||
let MARKERS, TASK_RE, CHECKBOX_RE, STATUS_RE, statusOf, pickPhaseFiles, deriveSpecState, BLOCK_REASON_RE;
|
||||
|
||||
/** A spec folder's phase files by number (Map, with `extra`), as the dashboard picks them. */
|
||||
function phaseFiles(dir) {
|
||||
return pickPhaseFiles(fs.readdirSync(dir));
|
||||
}
|
||||
|
||||
/** A markdown section's lines: from its heading to the next heading of the same or higher level. */
|
||||
function section(text, headingRe) {
|
||||
@@ -413,12 +427,18 @@ function specStatus(spec) {
|
||||
for (const p of phases) if (p.tasks) for (const k of Object.keys(totals)) totals[k] += p.tasks[k] || 0;
|
||||
const completed = totals.complete + totals.assumed;
|
||||
const completion = totals.total ? completed / totals.total : null;
|
||||
// The dashboard's state for this spec, from the same deriveSpecState() its
|
||||
// scan uses (null with no phase files: the scan reads earlier stages then).
|
||||
const derived = files.size ? deriveSpecState({ overview, phases: [...files.keys()].map((n) => ({ number: n, text: readText(path.join(spec.dir, files.get(n))) || "" })) }) : null;
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
spec: spec.rel,
|
||||
name: spec.name,
|
||||
overview: hasOverview ? "overview.md" : null,
|
||||
state: derived ? derived.state : null,
|
||||
stateDetail: derived ? derived.detail : null,
|
||||
finalizeReady: derived ? derived.finalizeReady : false,
|
||||
planDrafts: planDrafts(spec.dir),
|
||||
phases,
|
||||
parallelGroups: groups.groups,
|
||||
@@ -506,10 +526,11 @@ async function cmdList(args) {
|
||||
name: s.name,
|
||||
state: s.state,
|
||||
detail: s.detail,
|
||||
...(s.finalizeReady ? { finalizeReady: true } : {}),
|
||||
touched: s.touched ? new Date(s.touched).toISOString() : null,
|
||||
planDrafts: planDrafts(dir),
|
||||
overview: names.includes("overview.md"),
|
||||
phaseFiles: names.filter((n) => /^phase-\d+\b.*\.md$/i.test(n)).length,
|
||||
phaseFiles: pickPhaseFiles(names).size,
|
||||
pathfinder: isDir(path.join(dir, "pathfinder")),
|
||||
};
|
||||
});
|
||||
@@ -624,8 +645,9 @@ async function cmdMark(args) {
|
||||
lines[idx] = next;
|
||||
changes.push({ file: `${spec.rel}/overview.md`, line: row.line, from: `[${row.marker}]`, to: `[${target}]` });
|
||||
}
|
||||
// The phase file's Status line follows: done -> Complete; re-opening a Complete
|
||||
// phase -> In Progress (revise-plan), so the two files never disagree.
|
||||
// The phase file's Status line follows: done -> Complete; in-progress -> In
|
||||
// Progress (Implement claiming the phase); re-opening a Complete phase -> In
|
||||
// Progress (revise-plan), so the two files never disagree.
|
||||
let phaseText = null;
|
||||
let phasePath = null;
|
||||
let unfinished = [];
|
||||
@@ -637,13 +659,13 @@ async function cmdMark(args) {
|
||||
const parsed = parsePhaseFile(phasePath, number);
|
||||
unfinished = parsed.tasks.filter((t) => ["pending", "in-progress", "unknown"].includes(t.state)).map((t) => t.id);
|
||||
const status = statusOf(text);
|
||||
const want = target === "x" ? "Complete" : target === " " && status && /^complete$/i.test(status) ? "In Progress" : null;
|
||||
const want = target === "x" ? "Complete" : target === "/" ? "In Progress" : target === " " && status && /^complete$/i.test(status) ? "In Progress" : null;
|
||||
if (status && want && status !== want) {
|
||||
phaseText = text.replace(STATUS_RE, (_, before, _value, after) => before + want + after);
|
||||
changes.push({ file: `${spec.rel}/${file}`, field: "Status", from: status, to: want });
|
||||
}
|
||||
// done and open keep the Status line in step; with none to find, say so.
|
||||
if (!status && target !== "/") warnings.push(`${file} has no Status line, so only the Phase Checklist checkbox changed; add a "**Status:** <value>" line under its title.`);
|
||||
// Every mark keeps the Status line in step; with none to find, say so.
|
||||
if (!status) warnings.push(`${file} has no Status line, so only the Phase Checklist checkbox changed; add a "**Status:** <value>" line under its title.`);
|
||||
}
|
||||
if (!args["dry-run"]) {
|
||||
if (changes.some((c) => c.file.endsWith("overview.md"))) fs.writeFileSync(overviewPath, lines.join(eol(overview)));
|
||||
@@ -715,6 +737,27 @@ function listRel(dir, base = dir) {
|
||||
return outList.sort();
|
||||
}
|
||||
|
||||
// Every file under dir with its size, by forward-slash relative path: what
|
||||
// archive compares between the source and the target.
|
||||
function manifest(dir) {
|
||||
return new Map(listRel(dir).map((f) => [f, fs.statSync(path.join(dir, f)).size]));
|
||||
}
|
||||
|
||||
// The names and sizes in `want` that `got` lacks or holds at another size,
|
||||
// and the names `got` has beyond them, as one line each (empty: they match).
|
||||
function manifestDiff(want, got) {
|
||||
const lines = [];
|
||||
for (const [f, size] of want) {
|
||||
if (!got.has(f)) lines.push(`${f} is missing`);
|
||||
else if (got.get(f) !== size) lines.push(`${f} is ${got.get(f)} bytes, not ${size}`);
|
||||
}
|
||||
for (const f of got.keys()) if (!want.has(f)) lines.push(`${f} was not in the source`);
|
||||
return lines;
|
||||
}
|
||||
|
||||
// PLAN2CODE_ARCHIVE_FAULT is a test seam: "copy" skips the rename so the copy
|
||||
// path runs; "truncate" also cuts the first copied file short, the way a copy
|
||||
// that failed part-way leaves it.
|
||||
async function cmdArchive(args) {
|
||||
const root = path.resolve(args.root || ".");
|
||||
const spec = resolveSpec(root, args._[1]);
|
||||
@@ -723,9 +766,12 @@ async function cmdArchive(args) {
|
||||
fail(EXIT.REFUSED, "target-exists", `specs--completed/${spec.name}/ already exists; nothing was moved.`, "Ask the user whether to merge by hand or archive under another name.");
|
||||
}
|
||||
const files = listRel(spec.dir);
|
||||
const before = manifest(spec.dir);
|
||||
const fault = process.env.PLAN2CODE_ARCHIVE_FAULT || "";
|
||||
if (!args["dry-run"]) {
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
try {
|
||||
if (fault) throw Object.assign(new Error("rename skipped (PLAN2CODE_ARCHIVE_FAULT)"), { code: "EXDEV" });
|
||||
fs.renameSync(spec.dir, target);
|
||||
} catch (err) {
|
||||
// A rename across volumes (or a locked file on Windows) fails; copy then remove.
|
||||
@@ -734,6 +780,13 @@ async function cmdArchive(args) {
|
||||
} catch (copyErr) {
|
||||
fail(EXIT.INVALID, "archive-failed", `Could not move or copy ${spec.rel} (${err.code || err.message}; copy: ${copyErr.code || copyErr.message}).`, `Close anything holding files in ${spec.rel} open, check specs--completed/${spec.name} for a partial copy, then rerun.`);
|
||||
}
|
||||
if (fault === "truncate" && files.length) fs.truncateSync(path.join(target, files[0]), Math.max(0, before.get(files[0]) - 1));
|
||||
// The source goes only once the copy holds every file at the same size:
|
||||
// specs--completed/ is gitignored, so a short copy would be all that is left.
|
||||
const short = manifestDiff(before, manifest(target));
|
||||
if (short.length) {
|
||||
fail(EXIT.INVALID, "copy-unverified", `The copy of ${spec.rel} to specs--completed/${spec.name}/ does not match it (${short.slice(0, 5).join("; ")}${short.length > 5 ? `; and ${short.length - 5} more` : ""}); ${spec.rel} was left in place.`, `Delete the partial specs--completed/${spec.name}/, then rerun archive.`);
|
||||
}
|
||||
try {
|
||||
fs.rmSync(spec.dir, { recursive: true, force: true });
|
||||
} catch (rmErr) {
|
||||
@@ -743,11 +796,12 @@ async function cmdArchive(args) {
|
||||
}
|
||||
const sourceGone = args["dry-run"] ? null : !fs.existsSync(spec.dir);
|
||||
const moved = args["dry-run"] ? null : listRel(target);
|
||||
if (!args["dry-run"] && !(sourceGone && moved.length === files.length)) {
|
||||
const diff = args["dry-run"] ? [] : manifestDiff(before, manifest(target));
|
||||
if (!args["dry-run"] && !(sourceGone && !diff.length)) {
|
||||
fail(
|
||||
EXIT.INVALID,
|
||||
"archive-unverified",
|
||||
`The move of ${spec.rel} to specs--completed/${spec.name}/ did not verify: ${moved.length} of ${files.length} file(s) at the target, and ${spec.rel} ${sourceGone ? "is gone" : "still exists"}.`,
|
||||
`The move of ${spec.rel} to specs--completed/${spec.name}/ did not verify: ${moved.length} of ${files.length} file(s) at the target${diff.length ? ` (${diff.slice(0, 5).join("; ")})` : ""}, and ${spec.rel} ${sourceGone ? "is gone" : "still exists"}.`,
|
||||
`Compare ${spec.rel} with specs--completed/${spec.name}/ and finish the move by hand; archive refuses to rerun while the target exists.`
|
||||
);
|
||||
}
|
||||
@@ -825,7 +879,49 @@ async function cmdCheck(args) {
|
||||
}
|
||||
proseChecks(text, at(name), add);
|
||||
}
|
||||
checkReport("check", { spec: spec.rel, checked: names.map(at) }, problems);
|
||||
// The format rules: errors in a spec carrying Document's format marker,
|
||||
// warnings in one written before it, so specs people already have pass.
|
||||
const overviewText = readText(path.join(spec.dir, "overview.md")) || "";
|
||||
const marked = formatVersion(overviewText) >= FORMAT_VERSION;
|
||||
const level = marked ? "error" : "warn";
|
||||
for (const n of [...files.keys()].sort((a, b) => a - b)) formatChecks(path.join(spec.dir, files.get(n)), n, (code, message) => add(level, at(files.get(n)), code, message));
|
||||
checkReport("check", { spec: spec.rel, checked: names.map(at), format: marked ? FORMAT_VERSION : null }, problems);
|
||||
}
|
||||
|
||||
// The format marker Document writes into overview.md: a spec carrying it (at
|
||||
// FORMAT_VERSION or later) fails the format rules; one without it only warns.
|
||||
const FORMAT_VERSION = 2;
|
||||
const FORMAT_MARKER_RE = /^<!--\s*plan2code-format:\s*(\d+)\s*-->[ \t]*$/m;
|
||||
|
||||
function formatVersion(overview) {
|
||||
const m = (overview || "").match(FORMAT_MARKER_RE);
|
||||
return m ? Number(m[1]) : 0;
|
||||
}
|
||||
|
||||
// A file:line or "line N" reference: the spec's rule is to name a function or
|
||||
// symbol, since line numbers move. A `~` before the number marks it as
|
||||
// approximate, which is allowed.
|
||||
const LINE_REF_RE = /(?:\b[\w./-]+\.[A-Za-z][\w]{0,5}:\d+|\blines?\s+\d+)/i;
|
||||
|
||||
/** The format rules for one phase file, each reported through add(code, message). */
|
||||
function formatChecks(file, number, add) {
|
||||
const name = path.basename(file);
|
||||
const text = readText(file) || "";
|
||||
if (statusOf(text) === null) add("no-status", `${name} has no Status line; add "**Status:** Not Started" under its title`);
|
||||
const notes = section(text, /^#{1,6}\s+Notes\b/i);
|
||||
for (const [i, line] of (notes ? notes.lines : []).entries()) {
|
||||
if (CHECKBOX_RE.test(line)) add("notes-checkbox", `${name}:${notes.start + 2 + i} is a checkbox under Notes; notes are plain text, and work belongs in Tasks`);
|
||||
}
|
||||
const parsed = parsePhaseFile(file, number);
|
||||
const lines = text.split(/\r?\n/);
|
||||
for (const t of parsed.tasks) {
|
||||
if (LINE_REF_RE.test(lines[t.line - 1].replace(TASK_RE, ""))) {
|
||||
add("line-reference", `${name}:${t.line} (Task ${t.id}) points at a line number; name the function or symbol instead (line numbers move), or mark the number approximate with ~`);
|
||||
}
|
||||
if (t.state === "blocked" && !BLOCK_REASON_RE.test(lines[t.line - 1].replace(CHECKBOX_RE, "")) && !BLOCK_REASON_RE.test(t.detail)) {
|
||||
add("bare-blocked", `${name}:${t.line} (Task ${t.id}) is [!] with no reason; add "> BLOCKED: <why>. User action: <what>" under it`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const DRAFT_STATUSES = ["Draft", "Phase 3 Complete - Resume at Phase 4", "Escalated from Quick Task - Resume at Phase 2", "Escalated from Test - Resume at Phase 2", "Complete"];
|
||||
@@ -898,7 +994,7 @@ async function cmdCheckDraft(args) {
|
||||
run(USAGE, async (argv) => {
|
||||
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "step", "phase", "to", "task"], lists: ["set"] });
|
||||
const cmd = args._[0];
|
||||
({ MARKERS, TASK_ID_RE: TASK_RE, CHECKBOX_RE, STATUS_RE, statusOf } = await consoleModule("spec-files.mjs"));
|
||||
({ MARKERS, TASK_ID_RE: TASK_RE, CHECKBOX_RE, STATUS_RE, statusOf, pickPhaseFiles, deriveSpecState, BLOCK_REASON_RE } = await consoleModule("spec-files.mjs"));
|
||||
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, tick: cmdTick, archive: cmdArchive, check: cmdCheck, "check-draft": cmdCheckDraft };
|
||||
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, check, check-draft, metrics, mark, tick, archive. Run with --help.");
|
||||
await commands[cmd](args);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env node
|
||||
// Plan2Code Web Console - the forwarding stub every skill carries.
|
||||
//
|
||||
// The console itself is installed once, under ~/.plan2code/console/<version>/,
|
||||
// and shared by every skill. This file finds that copy through the
|
||||
// `console-dir` pointer, checks it is the version this skill was built for,
|
||||
// and runs it with the same arguments. Without a matching copy it prints one
|
||||
// plain line and exits 5, so the agent can offer the terminal instead.
|
||||
//
|
||||
// install.js bakes the version in below when it builds the skill.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
const VERSION = "__PLAN2CODE_VERSION__";
|
||||
const MISSING = "The Plan2Code console is missing or out of date. Run: plan2code update";
|
||||
|
||||
function sharedConsole() {
|
||||
const home = process.env.PLAN2CODE_CONSOLE_HOME || path.join(os.homedir(), ".plan2code", "console");
|
||||
// The installer always puts this version at <home>/<version>/, so look there first: console-dir
|
||||
// names whichever console opened last, which may be a source checkout or another version.
|
||||
const dirs = [path.join(home, VERSION)];
|
||||
try {
|
||||
const pointed = fs.readFileSync(path.join(home, "console-dir"), "utf8").trim();
|
||||
if (pointed) dirs.push(pointed);
|
||||
} catch {
|
||||
/* no pointer: the version folder alone */
|
||||
}
|
||||
for (const dir of dirs) {
|
||||
try {
|
||||
const entry = path.join(dir, "console.mjs");
|
||||
if (!fs.statSync(entry).isFile()) continue;
|
||||
if (fs.readFileSync(path.join(dir, "version.txt"), "utf8").trim() !== VERSION) continue;
|
||||
return entry;
|
||||
} catch {
|
||||
/* try the next place */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const entry = sharedConsole();
|
||||
if (!entry) {
|
||||
process.stderr.write(MISSING + "\n");
|
||||
process.exit(5);
|
||||
}
|
||||
// The shared console reads process.argv itself and sets its own exit code.
|
||||
await import(pathToFileURL(entry).href);
|
||||
@@ -18,10 +18,9 @@ A quick-task finish carries `review` and `dashboard:true` and waits for whicheve
|
||||
| `__done` | `stop` the server: the session is over |
|
||||
| `wait` exit 20 | `open --resume <sid> --workflow <yours>`, give the new link, keep waiting |
|
||||
|
||||
**Read `references/review.md`** and run Review Mode with these overrides:
|
||||
**Read `references/review.md`** and run the review as `references/review-in-build.md` says (on Finalize, Step 2.5 adds the whole feature's scope). Only what the page does differently is here:
|
||||
|
||||
- Scope is Focused and decided: the exact change set of this session (files created or modified by the phase or the quick task, or by the whole feature on Finalize, plus the tests and docs changed for it). Do not ask about scope. `overview.md` and the phase file give spec compliance; they do not widen scope.
|
||||
- The helper rule applies: a fresh helper runs the analysis when available, you verify every finding, and the report carries its Reviewed by line.
|
||||
- Scope is decided and not asked: the change set of this session. On Finalize it is the whole feature's (Step 2.5), not one phase.
|
||||
- No commit instructions and no next-conversation routing mid-review; the way back out carries both.
|
||||
- The page takes the whole report: the "top 10 of 15+" rule does not apply, and tables go in the doc.
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { spawn } from "node:child_process";
|
||||
|
||||
import { HERE, HOME_DIR, SESSIONS_DIR, appendEvent, ensureDir, nowIso, readJson, updateState } from "./files.mjs";
|
||||
import {
|
||||
CONSOLE_VERSION_DIR,
|
||||
appendLedger,
|
||||
bindLoopback,
|
||||
handOff,
|
||||
@@ -93,6 +94,9 @@ function trace(what) {
|
||||
// install dirs again. Written by `open` alone, which starts every session: a
|
||||
// `wait` or a `post` every few seconds need not rewrite it each time.
|
||||
function leavePointer() {
|
||||
// Only an installed console (a version folder) leaves it: a source checkout or an old per-skill
|
||||
// copy pointing console-dir at itself would leave every skill stub unable to find the shared one.
|
||||
if (!CONSOLE_VERSION_DIR.test(path.basename(HERE))) return;
|
||||
try {
|
||||
ensureDir(HOME_DIR);
|
||||
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
|
||||
@@ -686,16 +690,23 @@ async function startServer(project, worktree, sid, dir, { handoff = true, noBrow
|
||||
ensureDir(path.dirname(handlePath), 0o700);
|
||||
fs.rmSync(handlePath, { force: true });
|
||||
|
||||
// The token never goes on the command line, where any process on the
|
||||
// machine can read it (ps, Task Manager, /proc/<pid>/cmdline). It waits in a
|
||||
// one-shot file in the private session folder, named afresh for each spawn
|
||||
// so two opens racing on one session cannot read each other's, and the
|
||||
// server deletes it as soon as it has read it.
|
||||
const tokenName = `server-token-${newToken().slice(0, 12).replace(/[^A-Za-z0-9]/g, "x")}`;
|
||||
const tokenPath = path.join(dir, tokenName);
|
||||
fs.writeFileSync(tokenPath, token, { mode: 0o600 });
|
||||
const logFd = fs.openSync(path.join(dir, "server.log"), "a");
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
path.join(HERE, "server.mjs"),
|
||||
// Always `--flag=value`, never two words: a base64url token can start
|
||||
// with "--", and parseArgs would read it as the next flag and leave the
|
||||
// server with `token: true`. The paths get the same form for the same reason.
|
||||
// Always `--flag=value`, never two words: parseArgs would read a value
|
||||
// that starts with "--" as the next flag.
|
||||
`--session=${dir}`,
|
||||
`--token=${token}`,
|
||||
`--token-file=${tokenName}`,
|
||||
`--project=${project}`,
|
||||
// The checkout the session runs in, which the state does not hold yet
|
||||
// on a fresh open. See WORKTREE in server.mjs.
|
||||
@@ -721,8 +732,14 @@ async function startServer(project, worktree, sid, dir, { handoff = true, noBrow
|
||||
);
|
||||
fs.closeSync(logFd);
|
||||
let exited = false;
|
||||
child.on("exit", () => (exited = true));
|
||||
child.on("error", () => (exited = true));
|
||||
// A server that never started never took its token file: do not leave it.
|
||||
const dropTokenFile = () => {
|
||||
try {
|
||||
fs.rmSync(tokenPath, { force: true });
|
||||
} catch {}
|
||||
};
|
||||
child.on("exit", () => ((exited = true), dropTokenFile()));
|
||||
child.on("error", () => ((exited = true), dropTokenFile()));
|
||||
trace("open: server spawned");
|
||||
|
||||
let opened = null;
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
// Plan2Code Web Console - `post` and `wait`: publish a patch, then collect what the person sent.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { CONSOLE_VERSION_DIR } from "./sessions.mjs";
|
||||
import { HERE, appendEvent, fileStamp, nowIso, readJson, sleepSync, updateState, writeJsonAtomic } from "./files.mjs";
|
||||
import {
|
||||
appendLedger,
|
||||
@@ -716,8 +718,14 @@ const HOP_ACTIONS = {
|
||||
// flagged so the agent says so. In a
|
||||
// source tree no skill sits beside the console, so nothing can be told to be
|
||||
// missing and the stored skill stands.
|
||||
// The console is shared (~/.plan2code/console/<version>/), so the skills are
|
||||
// found in the agent skills store; the folder three levels up holds them only
|
||||
// when a skill carries its own console.
|
||||
function skillPath(skill) {
|
||||
return path.resolve(HERE, "..", "..", "..", skill, "SKILL.md");
|
||||
const candidates = [path.resolve(HERE, "..", "..", "..", skill, "SKILL.md")];
|
||||
// Only an installed console (a version folder) looks in the store: a source tree names no skill file.
|
||||
if (CONSOLE_VERSION_DIR.test(path.basename(HERE))) candidates.push(path.join(os.homedir(), ".agents", "skills", skill, "SKILL.md"));
|
||||
return candidates.find((file) => fs.existsSync(file)) || candidates[0];
|
||||
}
|
||||
|
||||
function pickupHop(action) {
|
||||
@@ -742,7 +750,7 @@ function pickupHop(action) {
|
||||
function handoffFor(result) {
|
||||
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
|
||||
if (!actions.some((a) => a && a.type === "stop" && a.i === "__stop" && a.handoff === true)) return {};
|
||||
const file = path.resolve(HERE, "..", "..", "..", "plan2code-handoff", "SKILL.md");
|
||||
const file = skillPath("plan2code-handoff");
|
||||
return fs.existsSync(file) ? { handoffSkill: file } : {};
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { SESSIONS_DIR, appendEvent, readJson } from "./files.mjs";
|
||||
import { attachmentName, healthOk, listHandles, pidAlive, projectRoot, repoRoots, sessionDir } from "./sessions.mjs";
|
||||
import { SERVER_MAX_LIFE_MS, attachmentName, healthOk, listHandles, pidAlive, projectRoot, repoRoots, resultWaiting, sessionDir } from "./sessions.mjs";
|
||||
import { removeSpec } from "./scan.mjs";
|
||||
import { isOpen, rule } from "./patches.mjs";
|
||||
import { pendingChatCount } from "./inbox.mjs";
|
||||
@@ -19,9 +19,6 @@ export function useCli(cli) {
|
||||
({ args, print, die, mustSession, sessionProject } = cli);
|
||||
}
|
||||
|
||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||
// still be one of our servers, so its pid gets no second look.
|
||||
const MAX_SERVER_LIFE_MS = 4 * 60 * 60 * 1000;
|
||||
|
||||
/* ----------------------------------------------------------------- keep */
|
||||
|
||||
@@ -284,7 +281,11 @@ export async function cmdStop() {
|
||||
// minute ago leaves exactly that behind for any process to inherit. A
|
||||
// busy server gets a second, longer look, and still has to answer as
|
||||
// ours; one that does not is left alone, and only its handle goes.
|
||||
const young = Date.now() - Date.parse(h.startedAt || 0) < MAX_SERVER_LIFE_MS;
|
||||
// A handle past the server's lifetime cap cannot still be one of our
|
||||
// servers, so its pid gets no second look, unless the session holds
|
||||
// answers nobody collected: the server outlives its cap for those.
|
||||
const young =
|
||||
Date.now() - Date.parse(h.startedAt || 0) < SERVER_MAX_LIFE_MS || (h.stateDir ? resultWaiting(h.stateDir) : false);
|
||||
const ours = (await healthOk(h)) || (young && pidAlive(h.pid) && (await healthOk(h, 5000)));
|
||||
if (!ours) {
|
||||
skipped++;
|
||||
|
||||
@@ -193,9 +193,10 @@ export function appendEvent(dir, event) {
|
||||
// writes it back, so two of them overlapping lose whichever wrote first. Every
|
||||
// read-modify-write of state.json therefore runs under this lock, a file
|
||||
// created with O_EXCL beside it. The sections it guards are a read, a merge
|
||||
// and a write, milliseconds long, so a lock older than LOCK_STALE_MS, or one
|
||||
// whose holder has died, is a crash left behind and is broken. The wait runs
|
||||
// past the stale age, so a writer always gets in eventually.
|
||||
// and a write, milliseconds long, so a lock whose holder has died is a crash
|
||||
// left behind and is broken; age alone breaks one only when no live holder is
|
||||
// named (lockStale below). The wait runs past the stale age, so a writer
|
||||
// always gets in once the holder is done or gone.
|
||||
export const STATE_LOCK_FILE = "state.json.lock";
|
||||
const LOCK_STALE_MS = 5000;
|
||||
// A pile-up of many writers (a burst of concurrent `post`s) queues behind
|
||||
@@ -204,12 +205,20 @@ const LOCK_STALE_MS = 5000;
|
||||
// writer that was never going to be denied, just slow to get its turn.
|
||||
const LOCK_WAIT_MS = 20000;
|
||||
|
||||
function lockStale(lock) {
|
||||
// The holder's pid decides first: a lock whose holder is still running is
|
||||
// held, however old it looks (a writer under a heavy machine can sit past the
|
||||
// stale age, and breaking its lock lets two writers in at once), and one whose
|
||||
// holder is gone is free at once. Age decides only when the pid cannot: an
|
||||
// empty file (the holder is between its create and its write, or died there)
|
||||
// or this process's own pid (a hold is synchronous, so a lock naming us while
|
||||
// we wait for it is a leftover from a process that had our number).
|
||||
export function lockStale(lock) {
|
||||
try {
|
||||
const st = fs.statSync(lock);
|
||||
if (Date.now() - st.mtimeMs > LOCK_STALE_MS) return true;
|
||||
const old = Date.now() - st.mtimeMs > LOCK_STALE_MS;
|
||||
const pid = Number.parseInt(fs.readFileSync(lock, "utf8"), 10);
|
||||
return Number.isInteger(pid) && pid > 0 && pid !== process.pid && !pidAlive(pid);
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) return old;
|
||||
return !pidAlive(pid);
|
||||
} catch (err) {
|
||||
// Gone between the failed create and this look: free, so try again.
|
||||
return err.code === "ENOENT";
|
||||
|
||||
@@ -19,8 +19,15 @@ export { prUrl };
|
||||
|
||||
/* ----------------------------------------------------------- running git */
|
||||
|
||||
// Every call here is a local read, milliseconds long. A git that hangs (a
|
||||
// credential helper waiting on a prompt nobody sees, a network drive gone
|
||||
// away, a hook or fsmonitor stuck) would otherwise hold the server's single
|
||||
// thread, and every page with it, for good. A caller may pass its own limit;
|
||||
// 0 means none.
|
||||
export const GIT_TIMEOUT_MS = 10000;
|
||||
|
||||
/** Run git with an args array (never a shell). { ok, out, err }. */
|
||||
export function git(args, cwd, { raw = false, timeout } = {}) {
|
||||
export function git(args, cwd, { raw = false, timeout = GIT_TIMEOUT_MS } = {}) {
|
||||
try {
|
||||
const stdout = execFileSync("git", args, {
|
||||
cwd,
|
||||
@@ -34,6 +41,7 @@ export function git(args, cwd, { raw = false, timeout } = {}) {
|
||||
});
|
||||
return { ok: true, out: raw ? stdout : stdout.trim(), err: "" };
|
||||
} catch (e) {
|
||||
if (e?.code === "ETIMEDOUT") return { ok: false, out: "", err: `git did not finish within ${timeout / 1000}s` };
|
||||
return { ok: false, out: "", err: String(e?.stderr || e?.message || "").trim() };
|
||||
}
|
||||
}
|
||||
@@ -512,6 +520,9 @@ export function snapshot(worktree, { prHosts = {} } = {}) {
|
||||
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 };
|
||||
// A repository whose status failed (or ran past git()'s time limit) has an
|
||||
// unknown tree, never a clean one: say so rather than draw an empty board.
|
||||
if (!status.ok) return { at, repo: true, error: status.err || "git status failed." };
|
||||
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
|
||||
|
||||
@@ -41,7 +41,7 @@ On `show`, run the workflow's **Show me it working** paragraph. Save screenshots
|
||||
Do what the workflow does on approval and print it in the terminal as usual, then:
|
||||
|
||||
```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}}
|
||||
{"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 -- src/vote.js && git commit -m \"...\" -m \"AI Assisted\"\n```","command":"/plan2code-3-implement specs/lunch-vote/overview.md","doc":"report","commit":true,"dashboard":true}}
|
||||
```
|
||||
|
||||
`commit:true` only when the body prints a commit. `command` is the next step: `/plan2code-3-implement specs/<feature>/overview.md`, or `/plan2code-4-finalize specs/<feature>/overview.md` after the last phase. No `review` on the finish.
|
||||
|
||||
@@ -689,11 +689,15 @@ const JARGON = [
|
||||
const FORBIDDEN_TOKENS =
|
||||
/\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
|
||||
|
||||
// plan2code-metrics scrapes confidence with patterns that do NOT require a
|
||||
// percent sign, so a bare "Requirements 22" in a rendered doc can poison a run's
|
||||
// metrics. Keep those four words away from bare numbers. The skill scripts'
|
||||
// copy is SCRAPE in src/skill-scripts/common.mjs; keep the two in step.
|
||||
const METRICS_BAIT = /\b(Requirements?|Feasibility|Integration|Risk)[:\s|]+\d{1,2}\b/;
|
||||
// plan2code-metrics scrapes the confidence breakdown from a rendered doc, so a
|
||||
// label and score it reads must not appear in agent text. The shapes live in
|
||||
// metrics-pattern.json beside this file; the skill scripts' copy is SCRAPE in
|
||||
// src/skill-scripts/common.mjs and the collector's is
|
||||
// plan2code-metrics/src/metrics-pattern.json. A test fails when they drift.
|
||||
const METRICS_BAIT = JSON.parse(fs.readFileSync(new URL("./metrics-pattern.json", import.meta.url), "utf8")).breakdown.map((b) => ({
|
||||
name: b.name,
|
||||
re: new RegExp(b.source, b.flags),
|
||||
}));
|
||||
|
||||
// The marker and metrics-bait scan on its own, for agent text that never
|
||||
// reaches state.json (a post's `run` / `folderIssue`). Problems as sentences.
|
||||
@@ -705,11 +709,13 @@ export function proseProblems(prose, subject = "text") {
|
||||
rule("", subject, `contains a loop completion marker (${marker[0]}); these are reserved. Reword it`, marker[0].toLowerCase().replaceAll("_", " ")),
|
||||
);
|
||||
}
|
||||
const bait = prose.match(METRICS_BAIT);
|
||||
if (bait) {
|
||||
for (const { name, re } of METRICS_BAIT) {
|
||||
const bait = prose.match(re);
|
||||
if (!bait) continue;
|
||||
problems.push(
|
||||
rule("", subject, `contains ${JSON.stringify(bait[0])}; the metrics collector scrapes that pattern. Hyphenate it or reword`, `${bait[1]}-score ${bait[0].match(/\d+$/)[0]}`),
|
||||
rule("", subject, `contains ${JSON.stringify(bait[0].trim())}; the metrics collector scrapes that pattern. Hyphenate it or reword`, `${name}-score ${bait[1]}`),
|
||||
);
|
||||
break;
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
@@ -700,6 +700,9 @@ export function cardAvailability(entry, scan, sel, lookup = stateFor) {
|
||||
|
||||
// Always on; a diagnosed bug is the one spec Quick Task is the next step for.
|
||||
if (rule.states === "any") return next ? { ...ON, next } : ON;
|
||||
// A building spec whose only unfinished tasks are blocked, each with a
|
||||
// written reason (the scan's finalizeReady), is ready for Finalize too.
|
||||
if (entry.skill === "plan2code-4-finalize" && state === "building" && sel.finalizeReady === true) return ON;
|
||||
// A state the table does not know is treated like files on disk.
|
||||
const taken = !sel || !sel.state ? "none" : lookup(sel.state) ? sel.state : "unrecognized";
|
||||
if (rule.states.includes(taken)) return rule.marksNext ? { ...ON, next } : ON;
|
||||
|
||||
@@ -1095,7 +1095,7 @@
|
||||
it shuts itself down <span data-fact="closedTabMinutes">2</span> minutes
|
||||
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
|
||||
<span data-fact="maxLifeHours">4</span> hours unless answers you sent are still waiting for the agent. Reopening the same link brings everything back: nothing you
|
||||
typed is kept in the browser alone.
|
||||
</p>
|
||||
<p class="for-app">
|
||||
@@ -1103,7 +1103,7 @@
|
||||
window and it shuts itself down <span data-fact="closedTabMinutes">2</span>
|
||||
minutes 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. When it
|
||||
<span data-fact="maxLifeHours">4</span> hours unless answers you sent are still waiting for the agent. When it
|
||||
stops, the app's own bar notices and brings it back on the same
|
||||
session, or offers <strong>Reconnect the console</strong>: nothing you
|
||||
typed is kept in the window alone.
|
||||
@@ -1287,8 +1287,8 @@
|
||||
from anyone, or
|
||||
</li>
|
||||
<li>
|
||||
after <span data-fact="maxLifeHours">4</span> hours, whatever is
|
||||
happening.
|
||||
after <span data-fact="maxLifeHours">4</span> hours, unless answers
|
||||
you sent are still waiting for the agent.
|
||||
</li>
|
||||
</ul>
|
||||
<p id="help-stuck-reconnect-text">
|
||||
@@ -3374,8 +3374,9 @@
|
||||
<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
|
||||
nobody has touched for 30 days, and deletes one only when git
|
||||
tracks it, so git can restore it; one git does not track (the
|
||||
folder is usually gitignored) is kept, with the reason shown. 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, and the
|
||||
@@ -3641,7 +3642,7 @@
|
||||
<section class="prefs-panel" data-tab="system">
|
||||
<fieldset data-section="cleanup" class="modal-ranges">
|
||||
<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>
|
||||
<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, and deletes one only when git tracks it, so git can restore it; one git does not track (the folder is usually gitignored) is kept, with the reason shown. 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>
|
||||
|
||||
@@ -18,27 +18,44 @@
|
||||
// editable surface, everything else on the host. field.el is the host div to
|
||||
// append; host.field is the facade itself, so a page test or a helper can
|
||||
// drive it.
|
||||
|
||||
import {
|
||||
Compartment,
|
||||
EditorState,
|
||||
EditorView,
|
||||
defaultKeymap,
|
||||
history,
|
||||
historyKeymap,
|
||||
keymap,
|
||||
markdown,
|
||||
markdownLanguage,
|
||||
placeholder,
|
||||
redo,
|
||||
} from "./vendor/codemirror.esm.js";
|
||||
import { livePreview } from "./notepad-editor.js";
|
||||
//
|
||||
// CodeMirror (half a megabyte) is not part of the page's start: it is
|
||||
// imported the first time a field is made, and every field after that gets
|
||||
// its editor at once. A field made before the import lands keeps what is set
|
||||
// on it (value, caret, disabled, aria-*, a focus asked for) and hands it to
|
||||
// its editor when it arrives. destroy() ends the editor; renderMain() calls
|
||||
// it, through destroyFields(), on every field it takes off the page.
|
||||
|
||||
// These listeners run as the editor's own DOM handlers, before its keymaps:
|
||||
// a preventDefault there (the mention popover's keys, a pure-image paste)
|
||||
// still beats CodeMirror's own handling.
|
||||
const HANDLED = ["keydown", "keyup", "paste", "blur", "focus"];
|
||||
|
||||
// CodeMirror's exports plus the live preview, once loaded; the import itself
|
||||
// while it is on its way. A failed import is forgotten, so the next field
|
||||
// asks again.
|
||||
let cm = null;
|
||||
let loading = null;
|
||||
|
||||
function loadEditor() {
|
||||
loading ??= Promise.all([import("./vendor/codemirror.esm.js"), import("./notepad-editor.js")]).then(
|
||||
([lib, editor]) => (cm = { ...lib, livePreview: editor.livePreview }),
|
||||
(err) => {
|
||||
loading = null;
|
||||
throw err;
|
||||
}
|
||||
);
|
||||
return loading;
|
||||
}
|
||||
|
||||
// Ends the editor of every Markdown field inside `root` (root included), for
|
||||
// a caller about to drop that part of the page.
|
||||
export function destroyFields(root) {
|
||||
if (!root || typeof root.querySelectorAll !== "function") return;
|
||||
if (root.field && typeof root.field.destroy === "function") root.field.destroy();
|
||||
for (const host of root.querySelectorAll(".md-host")) if (host.field) host.field.destroy();
|
||||
}
|
||||
|
||||
export function makeMdField({ id, className, value = "", placeholder: hint, label, disabled = false, maxLength = 0 } = {}) {
|
||||
const host = document.createElement("div");
|
||||
host.className = "md-host" + (className ? " " + className : "");
|
||||
@@ -61,76 +78,110 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
|
||||
};
|
||||
|
||||
let off = Boolean(disabled);
|
||||
const access = new Compartment();
|
||||
// editable, not only readOnly: a disabled field cannot take the focus,
|
||||
// which is the difference a textarea's own disabled attribute shows.
|
||||
let view = null;
|
||||
let gone = false;
|
||||
// What the field holds until its editor arrives.
|
||||
let text = String(value ?? "");
|
||||
let sel = null;
|
||||
let wantFocus = false;
|
||||
const aria = new Map();
|
||||
|
||||
let access = null;
|
||||
let stateOf = null;
|
||||
const accessOf = (on) =>
|
||||
on
|
||||
? [
|
||||
EditorState.readOnly.of(true),
|
||||
EditorView.editable.of(false),
|
||||
EditorView.contentAttributes.of({ "aria-disabled": "true" }),
|
||||
cm.EditorState.readOnly.of(true),
|
||||
cm.EditorView.editable.of(false),
|
||||
cm.EditorView.contentAttributes.of({ "aria-disabled": "true" }),
|
||||
]
|
||||
: [];
|
||||
|
||||
const extensions = [
|
||||
history(),
|
||||
keymap.of([{ key: "Mod-Shift-z", run: redo, preventDefault: true }, ...defaultKeymap, ...historyKeymap]),
|
||||
markdown({ base: markdownLanguage }),
|
||||
livePreview,
|
||||
EditorView.lineWrapping,
|
||||
EditorView.contentAttributes.of({ "aria-label": label || "Markdown text", "aria-multiline": "true", spellcheck: "true" }),
|
||||
EditorView.domEventHandlers(Object.fromEntries(HANDLED.map((type) => [type, (event) => fire(type, event)]))),
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (update.docChanged) fire("input");
|
||||
}),
|
||||
...(hint ? [placeholder(hint)] : []),
|
||||
...(maxLength
|
||||
? [
|
||||
EditorState.transactionFilter.of((tr) => {
|
||||
if (!tr.docChanged || tr.newDoc.length <= maxLength) return tr;
|
||||
return {
|
||||
changes: { from: 0, to: tr.startState.doc.length, insert: tr.newDoc.sliceString(0, maxLength) },
|
||||
selection: { anchor: Math.min(tr.newSelection.main.head, maxLength) },
|
||||
};
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
];
|
||||
const stateOf = (text) => EditorState.create({ doc: text, extensions: [...extensions, access.of(accessOf(off))] });
|
||||
const view = new EditorView({ state: stateOf(String(value ?? "")), parent: mount, root });
|
||||
// The stylesheets arrive after the first measure: measure again once they
|
||||
// have, or the lines would keep their unstyled height until the next edit.
|
||||
for (const sheet of sheets) sheet.addEventListener("load", () => view.requestMeasure());
|
||||
const build = () => {
|
||||
const { Compartment, EditorState, EditorView, defaultKeymap, history, historyKeymap, keymap, markdown, markdownLanguage, placeholder, redo, livePreview } = cm;
|
||||
access = new Compartment();
|
||||
// editable, not only readOnly: a disabled field cannot take the focus,
|
||||
// which is the difference a textarea's own disabled attribute shows.
|
||||
const extensions = [
|
||||
history(),
|
||||
keymap.of([{ key: "Mod-Shift-z", run: redo, preventDefault: true }, ...defaultKeymap, ...historyKeymap]),
|
||||
markdown({ base: markdownLanguage }),
|
||||
livePreview,
|
||||
EditorView.lineWrapping,
|
||||
EditorView.contentAttributes.of({ "aria-label": label || "Markdown text", "aria-multiline": "true", spellcheck: "true" }),
|
||||
EditorView.domEventHandlers(Object.fromEntries(HANDLED.map((type) => [type, (event) => fire(type, event)]))),
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (update.docChanged) fire("input");
|
||||
}),
|
||||
...(hint ? [placeholder(hint)] : []),
|
||||
...(maxLength
|
||||
? [
|
||||
EditorState.transactionFilter.of((tr) => {
|
||||
if (!tr.docChanged || tr.newDoc.length <= maxLength) return tr;
|
||||
return {
|
||||
changes: { from: 0, to: tr.startState.doc.length, insert: tr.newDoc.sliceString(0, maxLength) },
|
||||
selection: { anchor: Math.min(tr.newSelection.main.head, maxLength) },
|
||||
};
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
];
|
||||
stateOf = (t) => EditorState.create({ doc: t, extensions: [...extensions, access.of(accessOf(off))] });
|
||||
view = new EditorView({ state: stateOf(text), parent: mount, root });
|
||||
// The stylesheets arrive after the first measure: measure again once they
|
||||
// have, or the lines would keep their unstyled height until the next edit.
|
||||
for (const sheet of sheets) sheet.addEventListener("load", () => view.requestMeasure());
|
||||
if (sel) {
|
||||
const end = view.state.doc.length;
|
||||
view.dispatch({ selection: { anchor: Math.min(sel[0], end), head: Math.min(sel[1], end) } });
|
||||
}
|
||||
for (const [name, val] of aria) {
|
||||
if (val == null) view.contentDOM.removeAttribute(name);
|
||||
else view.contentDOM.setAttribute(name, val);
|
||||
}
|
||||
aria.clear();
|
||||
if (wantFocus && host.isConnected) view.focus();
|
||||
};
|
||||
|
||||
const field = {
|
||||
el: host,
|
||||
view,
|
||||
get value() {
|
||||
return view.state.doc.toString();
|
||||
get view() {
|
||||
return view;
|
||||
},
|
||||
set value(text) {
|
||||
get value() {
|
||||
return view ? view.state.doc.toString() : text;
|
||||
},
|
||||
set value(t) {
|
||||
// setState neither reports a change nor keeps the undo steps, exactly
|
||||
// the swap a textarea's value assignment makes. A fresh state parks its
|
||||
// caret at 0; a textarea's collapses to the end, so callers that fill
|
||||
// and focus (Autofill, quick answers, Reset to default) append as they
|
||||
// used to.
|
||||
view.setState(stateOf(String(text ?? "")));
|
||||
if (!view) {
|
||||
text = String(t ?? "");
|
||||
sel = [text.length, text.length];
|
||||
return;
|
||||
}
|
||||
view.setState(stateOf(String(t ?? "")));
|
||||
view.dispatch({ selection: { anchor: view.state.doc.length } });
|
||||
},
|
||||
get selectionStart() {
|
||||
if (!view) return sel ? Math.min(sel[0], sel[1]) : 0;
|
||||
const m = view.state.selection.main;
|
||||
return Math.min(m.anchor, m.head);
|
||||
},
|
||||
get selectionEnd() {
|
||||
if (!view) return sel ? Math.max(sel[0], sel[1]) : 0;
|
||||
const m = view.state.selection.main;
|
||||
return Math.max(m.anchor, m.head);
|
||||
},
|
||||
setSelectionRange(a, b) {
|
||||
view.dispatch({ selection: { anchor: a, head: b } });
|
||||
if (!view) sel = [a, b ?? a];
|
||||
else view.dispatch({ selection: { anchor: a, head: b } });
|
||||
},
|
||||
focus() {
|
||||
view.focus();
|
||||
if (view) view.focus();
|
||||
else wantFocus = true;
|
||||
},
|
||||
get disabled() {
|
||||
return off;
|
||||
@@ -138,7 +189,7 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
|
||||
set disabled(on) {
|
||||
off = Boolean(on);
|
||||
host.classList.toggle("is-disabled", off);
|
||||
view.dispatch({ effects: access.reconfigure(accessOf(off)) });
|
||||
if (view) view.dispatch({ effects: access.reconfigure(accessOf(off)) });
|
||||
},
|
||||
get classList() {
|
||||
return host.classList;
|
||||
@@ -150,10 +201,14 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
|
||||
return host.getBoundingClientRect();
|
||||
},
|
||||
setAttribute(name, val) {
|
||||
(name.startsWith("aria-") ? view.contentDOM : host).setAttribute(name, val);
|
||||
if (!name.startsWith("aria-")) host.setAttribute(name, val);
|
||||
else if (view) view.contentDOM.setAttribute(name, val);
|
||||
else aria.set(name, String(val));
|
||||
},
|
||||
removeAttribute(name) {
|
||||
(name.startsWith("aria-") ? view.contentDOM : host).removeAttribute(name);
|
||||
if (!name.startsWith("aria-")) host.removeAttribute(name);
|
||||
else if (view) view.contentDOM.removeAttribute(name);
|
||||
else aria.set(name, null);
|
||||
},
|
||||
addEventListener(type, fn) {
|
||||
if (!listeners.has(type)) listeners.set(type, new Set());
|
||||
@@ -172,11 +227,21 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
|
||||
fire("input");
|
||||
},
|
||||
destroy() {
|
||||
if (gone) return;
|
||||
gone = true;
|
||||
listeners.clear();
|
||||
view.destroy();
|
||||
if (view) view.destroy();
|
||||
},
|
||||
};
|
||||
if (off) host.classList.add("is-disabled");
|
||||
host.field = field;
|
||||
if (cm) build();
|
||||
else
|
||||
loadEditor().then(
|
||||
() => {
|
||||
if (!gone) build();
|
||||
},
|
||||
() => {}
|
||||
);
|
||||
return field;
|
||||
}
|
||||
@@ -305,13 +305,46 @@ function blockInto(parent, tokens) {
|
||||
}
|
||||
}
|
||||
|
||||
// The token trees of recent md() sources, newest last, so a redraw that draws
|
||||
// the same Markdown again (every agent post redraws every card) skips the
|
||||
// lexer. Only the tokens are kept, never the DOM: md() still builds fresh
|
||||
// nodes with their own listeners each call, so a caller may change what it
|
||||
// gets back. Bounded by count and by total source length; a source over the
|
||||
// length cap on its own is never kept.
|
||||
const MD_CACHE_ENTRIES = 200;
|
||||
const MD_CACHE_CHARS = 2_000_000;
|
||||
const mdCache = new Map();
|
||||
let mdCacheChars = 0;
|
||||
|
||||
function lexed(text) {
|
||||
const hit = mdCache.get(text);
|
||||
if (hit) {
|
||||
mdCache.delete(text);
|
||||
mdCache.set(text, hit);
|
||||
// A copy: drawing takes a task marker off its token (takeMarker), and the
|
||||
// kept tree must stay as the lexer made it.
|
||||
return structuredClone(hit);
|
||||
}
|
||||
const tokens = marked.lexer(text);
|
||||
if (text.length <= MD_CACHE_CHARS) {
|
||||
mdCache.set(text, structuredClone(tokens));
|
||||
mdCacheChars += text.length;
|
||||
for (const [key] of mdCache) {
|
||||
if (mdCache.size <= MD_CACHE_ENTRIES && mdCacheChars <= MD_CACHE_CHARS) break;
|
||||
mdCache.delete(key);
|
||||
mdCacheChars -= key.length;
|
||||
}
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/** Render markdown into a fresh element. Returns the element. */
|
||||
export function md(source, className = "md", options = {}) {
|
||||
const host = el("div", className);
|
||||
if (!source) return host;
|
||||
let tokens;
|
||||
try {
|
||||
tokens = marked.lexer(String(source));
|
||||
tokens = lexed(String(source));
|
||||
} catch {
|
||||
host.appendChild(el("p", "md-p", String(source)));
|
||||
return host;
|
||||
|
||||
@@ -8,7 +8,7 @@ import { startersFor } from "../starters.js";
|
||||
import { looks } from "../looks.js";
|
||||
import { thumbs, uploadUrl, docChip, attachTray, CHAT_IMAGES, attachFiles, incomingFiles, deleteUrl, sentAttachments, noteImages, attachRow, openPicview, refocusThumb } from "../uploads.js";
|
||||
import { attachMentions } from "../mention-box.js";
|
||||
import { makeMdField } from "../md-field.js";
|
||||
import { destroyFields, makeMdField } from "../md-field.js";
|
||||
import { pickerAccept, attachmentKind, noteAwaiting, threadWho, threadText } from "../answers.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { reconnectOffer } from "../continue-button.js";
|
||||
@@ -29,10 +29,19 @@ export const declineOpen = new Map();
|
||||
|
||||
const deciding = new Set();
|
||||
|
||||
// The Subagents dialog's instruction box, a Markdown field made once in
|
||||
// wireAsk into its #subagents-instruction mount.
|
||||
// The Subagents dialog's instruction box, a Markdown field made the first
|
||||
// time the dialog needs it, into its #subagents-instruction mount: made at
|
||||
// start-up, it would pull CodeMirror into every page load (md-field.js).
|
||||
let instrField = null;
|
||||
|
||||
function instr() {
|
||||
if (!instrField) {
|
||||
instrField = makeMdField({ className: "subagents-instruction", label: "Instruction", maxLength: 2000 });
|
||||
$("subagents-instruction").appendChild(instrField.el);
|
||||
}
|
||||
return instrField;
|
||||
}
|
||||
|
||||
// The frame's chat block, with `offline` worked out now rather than when the
|
||||
// frame was sent: the agent comes and goes between frames, and /ping keeps
|
||||
// agentLastSeen current. The frame's own verdict stands when there is no clock.
|
||||
@@ -66,7 +75,7 @@ export function askState() {
|
||||
// frame for the moment after a 409 stale, before the new frame lands.
|
||||
const askConversation = () => page.local.chat.conversation ?? askFrame().conversation;
|
||||
|
||||
export function renderAsk(main) {
|
||||
export function renderAsk(main, held = null) {
|
||||
const { frame, view: v, send: ss } = askState();
|
||||
// Anything drawn here has been seen: no dot for it later.
|
||||
const newest = newestReplyId(frame);
|
||||
@@ -77,7 +86,6 @@ export function renderAsk(main) {
|
||||
page.chatDot = false;
|
||||
askPaintedOffline = ss.state === "offline";
|
||||
|
||||
const pane = el("section", "ask-pane");
|
||||
const head = el("div", "ask-head");
|
||||
head.appendChild(el("h2", null, "Quick question"));
|
||||
head.appendChild(el("span", "ask-counter", v.counterText));
|
||||
@@ -86,17 +94,42 @@ export function renderAsk(main) {
|
||||
reset.disabled = ss.state === "offline" || chatResetting;
|
||||
reset.addEventListener("click", newConversation);
|
||||
head.appendChild(reset);
|
||||
pane.appendChild(head);
|
||||
|
||||
const list = el("div", "ask-list");
|
||||
list.setAttribute("role", "log");
|
||||
list.setAttribute("aria-live", "polite");
|
||||
if (!v.rows.length) list.appendChild(askStarters(ss));
|
||||
// The list is a live region (role="log"): one taken up from the last render
|
||||
// keeps every row that would draw the same, so a redraw announces nothing
|
||||
// and a new message is one appended row, the only thing read out.
|
||||
const kept = held && held.querySelector(":scope > .ask-list");
|
||||
const list = kept || el("div", "ask-list");
|
||||
if (!kept) {
|
||||
list.setAttribute("role", "log");
|
||||
list.setAttribute("aria-live", "polite");
|
||||
}
|
||||
const notes = new Map(v.rows.filter((r) => r.kind === "decision").map((r) => [r.re, r.text]));
|
||||
for (const r of v.rows) list.appendChild(askRow(r, ss, notes));
|
||||
pane.appendChild(list);
|
||||
pane.appendChild(askComposer(ss));
|
||||
main.appendChild(pane);
|
||||
const wanted = v.rows.length
|
||||
? v.rows.map((r) => [askRowKey(r, ss, notes), () => askRow(r, ss, notes)])
|
||||
: [[askStartersKey(ss), () => askStarters(ss)]];
|
||||
syncRows(list, wanted);
|
||||
|
||||
const composer = askComposer(ss);
|
||||
if (kept) {
|
||||
const oldHead = held.querySelector(":scope > .ask-head");
|
||||
const oldComposer = held.querySelector(":scope > .ask-composer");
|
||||
if (oldHead) oldHead.replaceWith(head);
|
||||
else held.insertBefore(head, list);
|
||||
if (oldComposer) {
|
||||
destroyFields(oldComposer);
|
||||
oldComposer.replaceWith(composer);
|
||||
} else held.appendChild(composer);
|
||||
if (held.parentNode !== main) main.appendChild(held);
|
||||
} else {
|
||||
if (held) {
|
||||
destroyFields(held);
|
||||
held.remove();
|
||||
}
|
||||
const pane = el("section", "ask-pane");
|
||||
pane.append(head, list, composer);
|
||||
main.appendChild(pane);
|
||||
}
|
||||
|
||||
// Back where the person left the list, unless something new arrived (or it
|
||||
// is the first look), which brings the newest row into view.
|
||||
@@ -106,6 +139,44 @@ export function renderAsk(main) {
|
||||
list.scrollTop = !saved || grew ? list.scrollHeight : saved.top;
|
||||
}
|
||||
|
||||
// What a row draws from: the row itself and every outside fact askRow() reads,
|
||||
// so two equal keys draw the same row and the one on the page can stay.
|
||||
// Each outside fact counts only on the rows that read it, or a send in flight
|
||||
// (chatSending) would redraw every row in the log.
|
||||
function askRowKey(r, ss, notes) {
|
||||
const offline = ss.state === "offline";
|
||||
if (r.kind === "decision") return JSON.stringify([r]);
|
||||
if (r.kind === "agent") {
|
||||
const open = Boolean(r.proposal && !r.decided);
|
||||
return JSON.stringify([r, notes.get(r.id) ?? null, open && [offline, deciding.has(r.id), declineOpen.has(r.id)]]);
|
||||
}
|
||||
return JSON.stringify([
|
||||
r,
|
||||
r.pending && r.failed ? [offline, chatSending] : null,
|
||||
!r.pending && r.waiting && r.working ? [offline, agentAdrift()] : null,
|
||||
(r.images || []).map((img) => thumbs.get(img.key) || ""),
|
||||
]);
|
||||
}
|
||||
|
||||
const askStartersKey = (ss) =>
|
||||
JSON.stringify(["starters", ss.canType, page.S.workflow, looks.role, Boolean(page.local.chat.about)]);
|
||||
|
||||
// Brings the live list's children in line with `wanted` ([key, make] pairs,
|
||||
// in order): a child whose key matches stays untouched, a changed one is
|
||||
// redrawn in its place, new ones are appended and leftovers removed.
|
||||
function syncRows(list, wanted) {
|
||||
const have = [...list.children];
|
||||
wanted.forEach(([key, make], i) => {
|
||||
const cur = have[i];
|
||||
if (cur && cur.dataset.rowKey === key) return;
|
||||
const node = make();
|
||||
node.dataset.rowKey = key;
|
||||
if (cur) cur.replaceWith(node);
|
||||
else list.appendChild(node);
|
||||
});
|
||||
for (const extra of have.slice(wanted.length)) extra.remove();
|
||||
}
|
||||
|
||||
// An empty conversation offers a few questions for this step, the role's
|
||||
// first. A click only fills the box: nothing is ever sent for the person.
|
||||
function askStarters(ss) {
|
||||
@@ -867,7 +938,7 @@ export function openSubagents() {
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
|
||||
radio.checked = radio.value === (on ? "on" : "off");
|
||||
}
|
||||
instrField.value = page.subagentsFrame.instruction ?? defaultInstruction(page.S.workflow);
|
||||
instr().value = page.subagentsFrame.instruction ?? defaultInstruction(page.S.workflow);
|
||||
$("subagents-max").value = String(page.subagentsFrame.max);
|
||||
const strength = STRENGTHS.includes(page.subagentsFrame.strength) ? page.subagentsFrame.strength : DEFAULT_STRENGTH;
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-strength"]')) radio.checked = radio.value === strength;
|
||||
@@ -889,7 +960,7 @@ export function openSubagents() {
|
||||
export function syncSubagentsFields() {
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const off = !picked || picked.value !== "on";
|
||||
instrField.disabled = off;
|
||||
instr().disabled = off;
|
||||
for (const id of ["subagents-max", "subagents-default"]) $(id).disabled = off;
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-strength"]')) radio.disabled = off;
|
||||
}
|
||||
@@ -914,7 +985,7 @@ export async function saveSubagents() {
|
||||
const save = $("subagents-save");
|
||||
const status = $("subagents-status");
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const text = instrField.value.trim();
|
||||
const text = instr().value.trim();
|
||||
// The shipped default is stored as null, so a later release's wording
|
||||
// reaches everyone who never changed it.
|
||||
const instruction = text === defaultInstruction(page.S.workflow) ? null : text;
|
||||
@@ -942,14 +1013,12 @@ export const askOfflineFlipped = () => (askState().send.state === "offline") !==
|
||||
|
||||
// The Subagents dialog's buttons, and dropping files onto the notes panel.
|
||||
export function wireAsk() {
|
||||
instrField = makeMdField({ className: "subagents-instruction", label: "Instruction", maxLength: 2000 });
|
||||
$("subagents-instruction").appendChild(instrField.el);
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) radio.addEventListener("change", syncSubagentsFields);
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-strength"]')) radio.addEventListener("change", syncStrengthHelp);
|
||||
lightDismiss($("subagents-modal"));
|
||||
$("btn-subagents").addEventListener("click", openSubagents);
|
||||
$("subagents-default").addEventListener("click", () => {
|
||||
instrField.value = defaultInstruction(page.S.workflow);
|
||||
instr().value = defaultInstruction(page.S.workflow);
|
||||
});
|
||||
$("subagents-save").addEventListener("click", saveSubagents);
|
||||
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
|
||||
|
||||
@@ -880,6 +880,23 @@ function buildChoice(card, item, staged) {
|
||||
clearRow(card, item);
|
||||
}
|
||||
|
||||
// A small eraser-style mark: a cross in a circle, drawn inline so it takes the
|
||||
// button's text color in both themes. Hidden from readers; the aria-label names it.
|
||||
function clearIcon() {
|
||||
const ns = "http://www.w3.org/2000/svg";
|
||||
const svg = document.createElementNS(ns, "svg");
|
||||
svg.setAttribute("viewBox", "0 0 24 24");
|
||||
svg.setAttribute("width", "14");
|
||||
svg.setAttribute("height", "14");
|
||||
svg.setAttribute("aria-hidden", "true");
|
||||
for (const d of ["M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z", "M9 9l6 6M15 9l-6 6"]) {
|
||||
const path = document.createElementNS(ns, "path");
|
||||
path.setAttribute("d", d);
|
||||
svg.appendChild(path);
|
||||
}
|
||||
return svg;
|
||||
}
|
||||
|
||||
// Takes a one-answer question back to how it arrived: no pick, and nothing in
|
||||
// "Something else" (its draft too, or the render would put the words straight
|
||||
// back). A radio group cannot be unticked by clicking it again, so without
|
||||
@@ -887,8 +904,10 @@ function buildChoice(card, item, staged) {
|
||||
// call it, and they only run for a form that has not been sent.
|
||||
function clearRow(card, item) {
|
||||
const row = el("div", "btn-row options-clear");
|
||||
const b = el("button", "btn small ghost", "Clear");
|
||||
const b = el("button", "btn small ghost clear-btn");
|
||||
b.type = "button";
|
||||
b.appendChild(clearIcon());
|
||||
b.appendChild(el("span", null, "Clear answer"));
|
||||
// An id so focus survives the render the click sets off (see withFocus).
|
||||
b.id = "clear-" + item.id;
|
||||
b.setAttribute("aria-label", "Clear your answer to this question");
|
||||
@@ -1307,9 +1326,16 @@ function buildReview(card, item, staged) {
|
||||
verdictText(v)
|
||||
);
|
||||
b.type = "button";
|
||||
b.addEventListener("click", () =>
|
||||
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "review", verdict: v.id }))
|
||||
);
|
||||
// A toggle: a screen reader hears which verdict is picked, not only sees
|
||||
// it in the fill. Set on the row at once, ahead of the redraw the stage
|
||||
// sets off, so the state never lags the click.
|
||||
b.setAttribute("aria-pressed", String(Boolean(on)));
|
||||
b.addEventListener("click", () => {
|
||||
for (const other of row.querySelectorAll("button[aria-pressed]")) {
|
||||
other.setAttribute("aria-pressed", String(other === b && !on));
|
||||
}
|
||||
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "review", verdict: v.id }));
|
||||
});
|
||||
row.appendChild(b);
|
||||
}
|
||||
card.appendChild(row);
|
||||
|
||||
@@ -46,6 +46,12 @@ function cleanupSummary(items, bytes) {
|
||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
||||
}
|
||||
|
||||
// A completed spec git does not track as it stands is never deleted (the
|
||||
// server refuses it), so it is listed apart as kept, out of the total and out
|
||||
// of what Delete these sends.
|
||||
const keptBack = (item) => item.where === "completed" && item.tracked === false;
|
||||
const deletable = () => ((cleanupFound && cleanupFound.items) || []).filter((i) => !keptBack(i));
|
||||
|
||||
function resetCleanup() {
|
||||
cleanupGen++;
|
||||
cleanupFound = null;
|
||||
@@ -59,19 +65,28 @@ function resetCleanup() {
|
||||
function renderCleanup() {
|
||||
const list = $("cleanup-list");
|
||||
list.replaceChildren();
|
||||
const items = (cleanupFound && cleanupFound.items) || [];
|
||||
const all = (cleanupFound && cleanupFound.items) || [];
|
||||
const items = deletable();
|
||||
const kept = all.filter(keptBack);
|
||||
$("cleanup-delete").hidden = !items.length;
|
||||
if (!items.length) return;
|
||||
const rows = (some) => some.map((item) => {
|
||||
const row = el("div", "cleanup-row");
|
||||
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
|
||||
return row;
|
||||
});
|
||||
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
|
||||
if (items.length > CLEANUP_SHOWN) {
|
||||
const more = el("details", "cleanup-more");
|
||||
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
|
||||
list.appendChild(more);
|
||||
if (items.length) {
|
||||
const bytes = Math.max(0, cleanupFound.bytes - kept.reduce((n, i) => n + (i.bytes || 0), 0));
|
||||
list.append(el("p", "cleanup-summary", cleanupSummary(items, bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
|
||||
if (items.length > CLEANUP_SHOWN) {
|
||||
const more = el("details", "cleanup-more");
|
||||
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
|
||||
list.appendChild(more);
|
||||
}
|
||||
}
|
||||
for (const item of kept) {
|
||||
const row = el("div", "cleanup-row cleanup-kept");
|
||||
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", "kept: git does not track it as it stands"));
|
||||
list.appendChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,17 +108,20 @@ async function scanCleanup() {
|
||||
renderCleanup();
|
||||
// Left in the status line, not cleared: it is the live region, so this is
|
||||
// what a screen reader hears when the scan finishes.
|
||||
const found = cleanupFound.items.length;
|
||||
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
|
||||
const found = deletable().length;
|
||||
const keptCount = cleanupFound.items.length - found;
|
||||
const keptNote = keptCount ? ` ${keptCount} old completed ${keptCount === 1 ? "spec is" : "specs are"} kept: git does not track ${keptCount === 1 ? "it" : "them"} as ${keptCount === 1 ? "it stands" : "they stand"}.` : "";
|
||||
setCleanupStatus((found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.") + keptNote, false);
|
||||
}
|
||||
|
||||
async function deleteCleanup() {
|
||||
if (!cleanupFound || !cleanupFound.items.length) return;
|
||||
const ids = deletable().map((i) => i.id);
|
||||
if (!ids.length) return;
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-delete").disabled = true;
|
||||
$("cleanup-scan").disabled = true;
|
||||
setCleanupStatus("Deleting…", false);
|
||||
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
|
||||
const { status, body } = await postJson("/cleanup", { delete: ids });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
@@ -112,15 +130,18 @@ async function deleteCleanup() {
|
||||
}
|
||||
const removed = (body.removed || []).length;
|
||||
const failed = (body.failed || []).length;
|
||||
// A completed spec git does not track is refused, and the server says why.
|
||||
const refused = (body.refused || []).length;
|
||||
// The server re-checks every id and keeps anything that changed since the
|
||||
// scan; say so, rather than let a count that came up short pass unremarked.
|
||||
const asked = cleanupFound.items.length;
|
||||
const kept = Math.max(0, asked - removed - failed);
|
||||
const asked = ids.length;
|
||||
const kept = Math.max(0, asked - removed - failed - refused);
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
|
||||
const keptLine = kept ? ` ${kept} ${kept === 1 ? "was" : "were"} kept because ${kept === 1 ? "it" : "they"} changed since the scan.` : "";
|
||||
setCleanupStatus((failed ? done + " " + failed + " could not be removed." : done) + keptLine, Boolean(failed));
|
||||
const refusalLine = refused && body.refusal ? " " + body.refusal : "";
|
||||
setCleanupStatus((failed ? done + " " + failed + " could not be removed." : done) + keptLine + refusalLine, Boolean(failed || refused));
|
||||
}
|
||||
|
||||
// The Cleanup section's buttons, and starting over whenever Preferences closes.
|
||||
|
||||
@@ -65,6 +65,7 @@ import { renderLoopSetup } from "./loop-setup.js";
|
||||
import { renderLaunching, renderWaiting } from "./starting.js";
|
||||
import { attachFiles, heldNotes, noteImages, pendingNotes, removeImage } from "../uploads.js";
|
||||
import { closeMentions } from "../mention-box.js";
|
||||
import { destroyFields } from "../md-field.js";
|
||||
import { buildPager, fitGrowBox, markFor, markMore, renderCard, renderEndItem, renderNotice } from "./cards.js";
|
||||
import { sendState, suggestState } from "../send-state.js";
|
||||
import { renderAgentsDoc, renderBriefButton, renderDoc, renderOverview } from "./docs.js";
|
||||
@@ -1608,16 +1609,31 @@ export function renderSidebar() {
|
||||
}
|
||||
}
|
||||
|
||||
// The Ask pane on screen when a render of the Ask tab began, held back from
|
||||
// the clear like the pose pane, so renderAsk() can take it up again: its list
|
||||
// is a live region, and a list rebuilt on every redraw would be announced
|
||||
// over and over instead of only its new rows.
|
||||
let heldAsk = null;
|
||||
|
||||
// Takes `node` off the page, ending the editor of every Markdown field in it.
|
||||
function discard(node) {
|
||||
destroyFields(node);
|
||||
node.remove();
|
||||
}
|
||||
|
||||
function renderMain() {
|
||||
const main = $("main");
|
||||
page.heldPose = main.querySelector(":scope > [data-pose]");
|
||||
for (const child of [...main.children]) if (child !== page.heldPose) child.remove();
|
||||
heldAsk = page.view === "ask" ? main.querySelector(":scope > .ask-pane") : null;
|
||||
for (const child of [...main.children]) if (child !== page.heldPose && child !== heldAsk) discard(child);
|
||||
try {
|
||||
paintMain(main);
|
||||
} finally {
|
||||
// Nothing took it up: this screen is not the same pose.
|
||||
page.heldPose?.remove();
|
||||
if (page.heldPose) discard(page.heldPose);
|
||||
page.heldPose = null;
|
||||
if (heldAsk) discard(heldAsk);
|
||||
heldAsk = null;
|
||||
}
|
||||
// Inside the render pass, before withFocus restores the card's scroll, so
|
||||
// the restore is measured against the box's final height.
|
||||
@@ -1636,7 +1652,11 @@ function paintMain(main) {
|
||||
if (page.view.startsWith("doc:")) return renderDoc(main, page.view.slice(4));
|
||||
if (isSpecFileView(page.view)) return renderOverview(main, page.view);
|
||||
if (page.view === AGENTS_VIEW) return renderAgentsDoc(main);
|
||||
if (page.view === "ask") return renderAsk(main);
|
||||
if (page.view === "ask") {
|
||||
const held = heldAsk;
|
||||
heldAsk = null;
|
||||
return renderAsk(main, held);
|
||||
}
|
||||
if (page.view === "subagents") return renderSubagents(main);
|
||||
|
||||
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
||||
@@ -1771,20 +1791,23 @@ export function renderFooter() {
|
||||
const summary = $("footer-summary");
|
||||
const notes = pendingNotes();
|
||||
const n = stagedCount();
|
||||
summary.replaceChildren();
|
||||
// Built off the page and swapped in only when it reads differently: the
|
||||
// summary is a live region and the footer renders on every tick, so a
|
||||
// rewrite with the same words would be announced again each time.
|
||||
const next = document.createElement("div");
|
||||
|
||||
const sent = awaitingReply();
|
||||
|
||||
if (!n && !notes.length && sent.length) {
|
||||
// "Answer a question above" is nonsense when everything answerable has
|
||||
// already gone. Say what is actually outstanding instead: their own send.
|
||||
summary.appendChild(el("strong", null, stranded() ? `${sent.length} saved, not picked up yet` : `${sent.length} with Plan2Code`));
|
||||
summary.appendChild(document.createTextNode(" · " + sent.map((i) => i.title).join(" · ")));
|
||||
next.appendChild(el("strong", null, stranded() ? `${sent.length} saved, not picked up yet` : `${sent.length} with Plan2Code`));
|
||||
next.appendChild(document.createTextNode(" · " + sent.map((i) => i.title).join(" · ")));
|
||||
} else if (finish()) {
|
||||
// Not "nothing to send yet". There is no yet.
|
||||
const fin = finish();
|
||||
summary.appendChild(el("strong", null, finishPaused(fin) ? "Paused." : "All done."));
|
||||
summary.appendChild(
|
||||
next.appendChild(el("strong", null, finishPaused(fin) ? "Paused." : "All done."));
|
||||
next.appendChild(
|
||||
document.createTextNode(
|
||||
n || notes.length
|
||||
? " Anything still waiting here was never sent."
|
||||
@@ -1796,7 +1819,7 @@ export function renderFooter() {
|
||||
)
|
||||
);
|
||||
} else if (!n && !notes.length) {
|
||||
summary.appendChild(
|
||||
next.appendChild(
|
||||
document.createTextNode(
|
||||
myTurn().length
|
||||
? "Nothing to send yet. Answer a question above, then press Send."
|
||||
@@ -1805,7 +1828,7 @@ export function renderFooter() {
|
||||
);
|
||||
} else {
|
||||
const strong = el("strong", null, `${n + notes.length} ready`);
|
||||
summary.appendChild(strong);
|
||||
next.appendChild(strong);
|
||||
const bits = [];
|
||||
for (const [id, v] of Object.entries(page.local.staged)) {
|
||||
const item = byId(id);
|
||||
@@ -1819,12 +1842,12 @@ export function renderFooter() {
|
||||
const item = byId(note.id);
|
||||
bits.push(`note on ${item ? item.title : "a question"}`);
|
||||
}
|
||||
summary.appendChild(document.createTextNode(" · " + bits.join(" · ")));
|
||||
next.appendChild(document.createTextNode(" · " + bits.join(" · ")));
|
||||
}
|
||||
|
||||
const held = finish() ? 0 : heldNotes().length;
|
||||
if (held) {
|
||||
summary.appendChild(
|
||||
next.appendChild(
|
||||
el(
|
||||
"div",
|
||||
"footer-held",
|
||||
@@ -1834,6 +1857,7 @@ export function renderFooter() {
|
||||
)
|
||||
);
|
||||
}
|
||||
if (summary.innerHTML !== next.innerHTML) summary.replaceChildren(...next.childNodes);
|
||||
|
||||
const state = sendState();
|
||||
const btn = $("btn-send");
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--rule);
|
||||
border-radius: var(--radius);
|
||||
padding: 24px 26px;
|
||||
--card-pad-b: 24px;
|
||||
padding: 24px 26px var(--card-pad-b);
|
||||
max-width: min(var(--card-width), 100%);
|
||||
box-shadow: var(--shadow);
|
||||
margin: 0 auto 18px;
|
||||
@@ -74,7 +75,15 @@
|
||||
/* ------------------------------------------------------------ options */
|
||||
|
||||
.options { list-style: none; margin: 20px 0 0; padding: 0; display: grid; gap: 9px; }
|
||||
.options-clear { margin-top: 10px; }
|
||||
/* Pinned to the foot of the card's scroll area, so a question taller than the
|
||||
window keeps its Clear in reach; it settles under the options at the end. */
|
||||
.options-clear {
|
||||
position: sticky; bottom: calc(var(--card-pad-b) * -1); z-index: 1;
|
||||
margin: 10px 0 calc(var(--card-pad-b) * -1); padding: 8px 0 var(--card-pad-b);
|
||||
background: linear-gradient(to bottom, transparent, var(--panel) 8px);
|
||||
}
|
||||
.clear-btn { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.clear-btn svg { flex: none; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
|
||||
|
||||
.option {
|
||||
display: flex;
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
.rail { border-right: 0; border-bottom: 1px solid var(--rule); }
|
||||
.sidebar, .aside { border: 0; border-bottom: 1px solid var(--rule); max-height: 30vh; }
|
||||
.main { padding: 18px 16px 30px; }
|
||||
.card { padding: 18px 16px; border-radius: 8px; }
|
||||
.card { --card-pad-b: 18px; padding: 18px 16px var(--card-pad-b); border-radius: 8px; }
|
||||
.main > .card { padding-right: 22px; }
|
||||
.card h2 { font-size: 21px; }
|
||||
/* Back to a wrapping row: the summary and Send take two lines here and fill
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
--panel-2: #fbf9f6;
|
||||
--ink: #1d1a17;
|
||||
--ink-2: #5d564d;
|
||||
--ink-3: #8f8779;
|
||||
/* Same hue as before, darkened to 4.56:1 on --bg (WCAG AA for body text). */
|
||||
--ink-3: #756e62;
|
||||
--rule: #e4ddd1;
|
||||
--rule-2: #cfc6b6;
|
||||
--accent: #206cc3;
|
||||
|
||||
+66
-35
@@ -235,7 +235,7 @@ function handover(req, res, ctx) {
|
||||
// The tab moved once; a second open in the same conversation is not a
|
||||
// hand-over, so the caller can open a browser without a failure note.
|
||||
if (state.setup.moved) return json(res, 409, { error: "moved" });
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "bad-url" });
|
||||
const target = typeof body?.url === "string" ? body.url : "";
|
||||
// Only another console's sign-in link is a legal destination.
|
||||
@@ -506,7 +506,7 @@ function events(req, res, ctx, url) {
|
||||
/* ---------------------------------------------------- settings and drafts */
|
||||
|
||||
function draft(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
// Debounced client-side; this is just the durable mirror. Twenty minutes
|
||||
// of someone's structured answers must not die with a closed tab.
|
||||
@@ -551,7 +551,7 @@ function looksGet(req, res) {
|
||||
}
|
||||
|
||||
function looksPost(req, res) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
// `set` carries only the keys one tab changed, merged onto what is on
|
||||
// disk, so a tab holding stale settings cannot undo another tab's change.
|
||||
@@ -573,7 +573,7 @@ function looksPost(req, res) {
|
||||
// is what console.mjs hands the agent at its next pickup. Never blocked by,
|
||||
// and never blocking, a card send.
|
||||
function subagentsPost(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const state = ctx.readState();
|
||||
if (!state || !offered(state.workflow)) return json(res, 400, { error: "not-offered" });
|
||||
@@ -605,7 +605,7 @@ function subagentsPost(req, res, ctx) {
|
||||
// The page follows it with a __git pr-host action, and the agent's reread
|
||||
// rebuilds the link.
|
||||
function prHost(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (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)) {
|
||||
@@ -762,7 +762,7 @@ function modelsGet(req, res) {
|
||||
}
|
||||
|
||||
function modelsPost(req, res) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const { models, error } = cleanModels(body && body.models);
|
||||
if (error) return json(res, 400, { error });
|
||||
@@ -829,7 +829,7 @@ function agentsGet(req, res) {
|
||||
// entry) is refused with 409 unless the page says `replace: true`, so a save
|
||||
// never silently drops what the person wrote there by hand.
|
||||
function agentsPost(req, res) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const { agents, error, index, field } = validateForSave(body && body.agents);
|
||||
if (error) return json(res, 400, { error, index, field });
|
||||
@@ -854,7 +854,7 @@ function agentsPost(req, res) {
|
||||
// Where a command would run from, for the form's Test button. Only looks: it
|
||||
// never runs the command.
|
||||
function agentsTest(req, res) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const command = typeof body?.command === "string" ? body.command.trim() : "";
|
||||
if (!command || command.length > 1024) return json(res, 400, { error: "command must be 1 to 1024 characters" });
|
||||
@@ -869,7 +869,7 @@ function agentsTest(req, res) {
|
||||
// ever saved, never a path the request carried. A built-in is materialized
|
||||
// as a new custom entry; a custom agent gets its command rewritten.
|
||||
function agentsUsePath(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const id = typeof body?.id === "string" ? body.id.trim() : "";
|
||||
if (!id) return json(res, 400, { error: "id is required" });
|
||||
@@ -944,7 +944,7 @@ function agentsUsePath(req, res, ctx) {
|
||||
// removes those of the ids a fresh scan still finds. Never this session,
|
||||
// never a path the page sent.
|
||||
function cleanup(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (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: ctx.sid, project: ctx.worktree() || ctx.project })
|
||||
@@ -990,7 +990,7 @@ function notepadTab(ctx, url, create) {
|
||||
}
|
||||
|
||||
function notepadText(req, res, ctx, url) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too-long" : "bad" });
|
||||
try {
|
||||
return json(res, 200, { ok: true, ...saveNote(notepadRoot(ctx), notepadTab(ctx, url, true), body && body.text) });
|
||||
@@ -1006,7 +1006,7 @@ function readJpeg(req, res, then) {
|
||||
req.resume();
|
||||
return json(res, 415, { error: "not-jpeg" });
|
||||
}
|
||||
return readRaw(req, MAX_BODY, (err, buf) => {
|
||||
return readRaw(req, res, MAX_BODY, (err, buf) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too-large" : "bad" });
|
||||
return then(buf);
|
||||
});
|
||||
@@ -1034,7 +1034,7 @@ function notepadThumb(req, res, ctx, url) {
|
||||
}
|
||||
|
||||
function notepadDelete(req, res, ctx, url) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: "bad" });
|
||||
try {
|
||||
removeImage(notepadRoot(ctx), notepadTab(ctx, url, false), body && body.id);
|
||||
@@ -1050,7 +1050,7 @@ function notepadDelete(req, res, ctx, url) {
|
||||
// ctx.dir and add nothing to the event log.
|
||||
function notepadTabRoute(act) {
|
||||
return (req, res, ctx) =>
|
||||
readBody(req, (err, body) => {
|
||||
readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: "bad" });
|
||||
try {
|
||||
return json(res, 200, { ok: true, ...act(notepadRoot(ctx), body && typeof body === "object" ? body : {}) });
|
||||
@@ -1230,7 +1230,7 @@ function upload(req, res, ctx) {
|
||||
};
|
||||
|
||||
if (contentType.startsWith("image/jpeg")) {
|
||||
return readRaw(req, MAX_BODY, (err, buf) => {
|
||||
return readRaw(req, res, MAX_BODY, (err, buf) => {
|
||||
if (err) return err.tooBig ? json(res, 413, { error: "too large" }) : json(res, 400, { error: String(err.message) });
|
||||
if (buf.length < 3 || buf[0] !== 0xff || buf[1] !== 0xd8 || buf[2] !== 0xff) {
|
||||
return json(res, 415, { error: "JPEG only" });
|
||||
@@ -1260,8 +1260,8 @@ function upload(req, res, ctx) {
|
||||
const name = uploadLabel(req, "");
|
||||
const ext = docExt(rawUploadName(req));
|
||||
// Refused on its name alone, but drained first, so the page gets the 415.
|
||||
if (!ext) return readRaw(req, 0, () => json(res, 415, { error: "type" }));
|
||||
return readRaw(req, MAX_DOC_BYTES, (err, buf) => {
|
||||
if (!ext) return readRaw(req, res, 0, () => json(res, 415, { error: "type" }));
|
||||
return readRaw(req, res, MAX_DOC_BYTES, (err, buf) => {
|
||||
if (err) return err.tooBig ? json(res, 413, { error: "too large" }) : json(res, 400, { error: String(err.message) });
|
||||
if (checkDocument(buf, ext)) return json(res, 415, { error: "type" });
|
||||
const saved = store(buf, ext);
|
||||
@@ -1272,7 +1272,7 @@ function upload(req, res, ctx) {
|
||||
});
|
||||
}
|
||||
|
||||
return readRaw(req, 0, () => json(res, 415, { error: "type" }));
|
||||
return readRaw(req, res, 0, () => json(res, 415, { error: "type" }));
|
||||
}
|
||||
|
||||
// A note attachment the agent kept into the spec (`console.mjs keep`), so a
|
||||
@@ -1412,7 +1412,7 @@ function recordSubmitted(state, actions) {
|
||||
// A link the page inside the desktop app cannot open itself (open-link.mjs).
|
||||
// http and https only; the page shows the link to paste when this says no.
|
||||
function openLinkRoute(req, res) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const href = linkToOpen(body && body.url);
|
||||
if (!href) return json(res, 400, { error: "only http and https links open" });
|
||||
@@ -1422,7 +1422,7 @@ function openLinkRoute(req, res) {
|
||||
}
|
||||
|
||||
function submit(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (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.actions) || body.actions.length === 0) {
|
||||
return json(res, 400, { error: "actions must be a non-empty array" });
|
||||
@@ -1528,7 +1528,7 @@ function submit(req, res, ctx) {
|
||||
// this route never looks at result.json, so a card send waiting to be
|
||||
// collected never holds up a question, and a question never holds up a card.
|
||||
function chat(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const state = ctx.readState() || {};
|
||||
@@ -1591,7 +1591,7 @@ function chat(req, res, ctx) {
|
||||
// Approve or Decline on an edit the agent proposed in the chat. `re` is the
|
||||
// proposing reply's id. Decisions never count toward the message limit.
|
||||
function chatDecision(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
|
||||
@@ -1705,7 +1705,7 @@ function loopSetupGet(req, res, ctx, url) {
|
||||
}
|
||||
|
||||
function loopSetupPost(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { ok: false, problems: ["the setup must be a JSON object"] });
|
||||
try {
|
||||
@@ -1732,7 +1732,7 @@ function workspaceGet(req, res, ctx, url) {
|
||||
}
|
||||
|
||||
function workspaceEdit(req, res, ctx, url) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
let answer;
|
||||
@@ -1749,7 +1749,7 @@ function workspaceEdit(req, res, ctx, url) {
|
||||
// The dashboard's picker sends it as the selection moves and before a
|
||||
// launch, so a skill opens on the list of the spec it was launched for.
|
||||
function workspaceScope(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
return readBody(req, res, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const spec = typeof body.spec === "string" ? body.spec : "";
|
||||
@@ -1765,7 +1765,7 @@ function workspaceScope(req, res, ctx) {
|
||||
|
||||
// Only ever returns a path: the page then adds it through /workspace/add.
|
||||
function workspaceBrowse(req, res, ctx) {
|
||||
return readBody(req, () => {
|
||||
return readBody(req, res, () => {
|
||||
ctx.workspace.browse().then(([code, body]) => json(res, code, body));
|
||||
});
|
||||
}
|
||||
@@ -1893,7 +1893,35 @@ function originOk(req, port) {
|
||||
|
||||
const MAX_BODY = 4 * 1024 * 1024;
|
||||
|
||||
function readBody(req, cb) {
|
||||
// The one way a body reader hands over: at most once, and a callback that
|
||||
// throws still gets its request answered. Before this, readBody's catch fed
|
||||
// a throw from the route's own callback back into that callback as a parse
|
||||
// error (a second run, a second answer), an 'error' after 'end' called it
|
||||
// again, and readRaw let the throw escape with the request left hanging. A
|
||||
// throw now answers 400 if nothing went out yet, or ends what was started,
|
||||
// and is rethrown on the next turn so the server's uncaughtException handler
|
||||
// still records it in events.ndjson.
|
||||
function deliverOnce(res, cb) {
|
||||
let done = false;
|
||||
return (err, value) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
try {
|
||||
cb(err, value);
|
||||
} catch (e) {
|
||||
try {
|
||||
if (!res.headersSent) json(res, 400, { error: "bad request" });
|
||||
else if (!res.writableEnded) res.end();
|
||||
} catch {}
|
||||
setImmediate(() => {
|
||||
throw e;
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function readBody(req, res, cb) {
|
||||
const deliver = deliverOnce(res, cb);
|
||||
// Collect Buffers and decode once at the end. Appending each chunk to a
|
||||
// string decodes it in isolation, so a multi-byte character split across a
|
||||
// chunk boundary becomes U+FFFD. Rare, silent, and impossible to reproduce
|
||||
@@ -1915,21 +1943,24 @@ function readBody(req, cb) {
|
||||
chunks.push(c);
|
||||
});
|
||||
req.on("end", () => {
|
||||
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
|
||||
if (tooBig) return deliver(Object.assign(new Error("too large"), { tooBig: true }));
|
||||
let body;
|
||||
try {
|
||||
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||
body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
||||
} catch (e) {
|
||||
cb(e);
|
||||
return deliver(e);
|
||||
}
|
||||
deliver(null, body);
|
||||
});
|
||||
req.on("error", (e) => cb(e));
|
||||
req.on("error", (e) => deliver(e));
|
||||
}
|
||||
|
||||
// The binary sibling of readBody, for image and document uploads, each with
|
||||
// its own cap. Past the cap it stops keeping chunks but drains the rest
|
||||
// instead of destroying the request: a destroyed socket reaches the page as a
|
||||
// network error, never as the 413 that lets it say the file was too large.
|
||||
function readRaw(req, limit, cb) {
|
||||
export function readRaw(req, res, limit, cb) {
|
||||
const deliver = deliverOnce(res, cb);
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
let tooBig = false;
|
||||
@@ -1943,8 +1974,8 @@ function readRaw(req, limit, cb) {
|
||||
chunks.push(c);
|
||||
});
|
||||
req.on("end", () => {
|
||||
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
|
||||
cb(null, Buffer.concat(chunks));
|
||||
if (tooBig) return deliver(Object.assign(new Error("too large"), { tooBig: true }));
|
||||
deliver(null, Buffer.concat(chunks));
|
||||
});
|
||||
req.on("error", (e) => cb(e));
|
||||
req.on("error", (e) => deliver(e));
|
||||
}
|
||||
+12
-25
@@ -7,7 +7,7 @@ import { isDeletableSpecDir } from "./public/answers.js";
|
||||
import { SPEC_STATES as STATE_TABLE } from "./public/spec-states.js";
|
||||
import { nowIso, readText } from "./files.mjs";
|
||||
import { insideGitRepo, pendingFiles } from "./sessions.mjs";
|
||||
import { countTasks, statusOf } from "./spec-files.mjs";
|
||||
import { deriveSpecState, pickPhaseFiles, statusOf } from "./spec-files.mjs";
|
||||
|
||||
// The task-line pattern lives in spec-files.mjs; re-exported for any importer
|
||||
// that still takes it from here.
|
||||
@@ -88,7 +88,8 @@ function classifySpec(dir, names) {
|
||||
const has = (re) => names.some((n) => re.test(n));
|
||||
const pfDir = path.join(dir, "pathfinder");
|
||||
const overview = names.includes("overview.md");
|
||||
const phases = names.filter((n) => /^phase-.*\.md$/i.test(n));
|
||||
const picked = pickPhaseFiles(names);
|
||||
const phases = [...picked.keys()].sort((a, b) => a - b).map((n) => picked.get(n));
|
||||
const drafts = names.filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n));
|
||||
const planDraft = drafts.length > 0;
|
||||
const planConv = has(/^PLAN-CONVERSATION.*\.md$/i);
|
||||
@@ -97,31 +98,17 @@ function classifySpec(dir, names) {
|
||||
const resumeAt = draftStatus.match(/Resume at Phase\s*(\d+)/i);
|
||||
|
||||
if (phases.length) {
|
||||
// countTasks() counts a file's task lines (every checkbox in a file
|
||||
// written before that format). An assumed-done task (`[?]`) counts as
|
||||
// done, and the detail names how many there are.
|
||||
let done = 0;
|
||||
let assumed = 0;
|
||||
let open = 0;
|
||||
for (const f of phases) {
|
||||
const n = countTasks(readText(path.join(dir, f)));
|
||||
done += n.done;
|
||||
assumed += n.assumed;
|
||||
open += n.open;
|
||||
}
|
||||
const finished = done + assumed;
|
||||
const total = finished + open;
|
||||
const suffix = assumed > 0 ? `, ${assumed} assumed` : "";
|
||||
// deriveSpecState() is the one rule for a documented spec's state,
|
||||
// shared with specs.mjs (status), so the two never disagree.
|
||||
const derived = deriveSpecState({
|
||||
overview: overview ? readText(path.join(dir, "overview.md")) : null,
|
||||
phases: [...picked.keys()].map((n) => ({ number: n, text: readText(path.join(dir, picked.get(n))) })),
|
||||
});
|
||||
// Documented, building and built specs all land here: each says whether a
|
||||
// Revise plan brief is waiting, and only when one is.
|
||||
// Revise plan brief is waiting, and only when one is. finalizeReady rides
|
||||
// along only when true (only blocked tasks left, each with a reason).
|
||||
const brief = planChangeWaiting(dir, phases) ? { planChange: true } : {};
|
||||
if (open === 0 && finished > 0) return { state: "built", detail: `all tasks done${suffix}`, ...brief };
|
||||
if (finished > 0) return { state: "building", detail: `${finished} of ${total} tasks done${suffix}`, ...brief };
|
||||
return {
|
||||
state: "documented",
|
||||
detail: `${phases.length} phase${phases.length === 1 ? "" : "s"}, ${total || "?"} tasks ready`,
|
||||
...brief,
|
||||
};
|
||||
return { state: derived.state, detail: derived.detail, ...(derived.finalizeReady ? { finalizeReady: true } : {}), ...brief };
|
||||
}
|
||||
// An overview with no phase files means Document was interrupted mid-write;
|
||||
// its next step is the same as a finished plan's.
|
||||
|
||||
+33
-10
@@ -33,7 +33,7 @@ import {
|
||||
readJson,
|
||||
writeJsonAtomic,
|
||||
} from "./files.mjs";
|
||||
import { LEDGER_FILE, handleFile, readLedger } from "./sessions.mjs";
|
||||
import { LEDGER_FILE, SERVER_MAX_LIFE_MS, handleFile, readLedger } from "./sessions.mjs";
|
||||
import {
|
||||
CHAT_CURSOR_FILE,
|
||||
CHAT_FILE,
|
||||
@@ -74,14 +74,32 @@ if (!DIR) {
|
||||
}
|
||||
|
||||
const SID = path.basename(DIR);
|
||||
// The session token. `open` leaves it in a one-shot file in the session
|
||||
// folder (`--token-file=<name>`, a bare name inside DIR) so it never appears
|
||||
// on this process's command line; it is read once and the file deleted at
|
||||
// once. `--token=<token>` is kept for a server started by hand or by a test.
|
||||
// No token, no server: authed() waves everything through on an empty one. A
|
||||
// bare `--token` (or one whose value parseArgs took for a flag) arrives as
|
||||
// `true`, so anything but a non-empty string is refused here, at boot.
|
||||
if (typeof args.token !== "string" || !args.token) {
|
||||
process.stderr.write("server: --token=<token> is required (a non-empty string)\n");
|
||||
const TOKEN = (() => {
|
||||
const name = args["token-file"];
|
||||
if (typeof name === "string" && name && path.basename(name) === name) {
|
||||
const file = path.join(DIR, name);
|
||||
let text = "";
|
||||
try {
|
||||
text = fs.readFileSync(file, "utf8").trim();
|
||||
} catch {}
|
||||
try {
|
||||
fs.rmSync(file, { force: true });
|
||||
} catch {}
|
||||
return text;
|
||||
}
|
||||
return typeof args.token === "string" ? args.token : "";
|
||||
})();
|
||||
if (!TOKEN) {
|
||||
process.stderr.write("server: a token is required: --token-file=<name in the session folder> or --token=<token> (a non-empty string)\n");
|
||||
process.exit(2);
|
||||
}
|
||||
const TOKEN = args.token;
|
||||
const PROJECT = args.project || process.cwd();
|
||||
// The checkout this session runs in, from `open`. PROJECT is the folder that
|
||||
// holds .git, which for a linked worktree is the MAIN checkout: the wrong
|
||||
@@ -90,7 +108,7 @@ const PROJECT = args.project || process.cwd();
|
||||
// there this is the only place the worktree can come from.
|
||||
const WORKTREE = typeof args.worktree === "string" ? args.worktree : "";
|
||||
const IDLE_MS = Number(args["idle-ms"] || 30 * 60 * 1000);
|
||||
const MAX_LIFE_MS = Number(args["max-life-ms"] || 4 * 60 * 60 * 1000);
|
||||
const MAX_LIFE_MS = Number(args["max-life-ms"] || SERVER_MAX_LIFE_MS);
|
||||
|
||||
const STATE_FILE = path.join(DIR, "state.json");
|
||||
const DRAFT_FILE = path.join(DIR, "draft.json");
|
||||
@@ -526,16 +544,18 @@ setInterval(() => {
|
||||
// the server deciding to stop. Do not "optimize" this away.
|
||||
setInterval(() => {
|
||||
const idle = Date.now() - lastContact;
|
||||
// Answers nobody has collected yet keep the server up (bounded by MAX_LIFE_MS):
|
||||
// exiting would strand the tab and the send it holds.
|
||||
if (idle > IDLE_MS && !resultFlags().pending) {
|
||||
// Answers nobody has collected yet keep the server up, past the idle limit
|
||||
// and past MAX_LIFE_MS alike: exiting would strand the tab and the send it
|
||||
// holds. Once a `wait` collects them (consumedAt) both limits apply again.
|
||||
const pending = resultFlags().pending;
|
||||
if (idle > IDLE_MS && !pending) {
|
||||
// The log is advisory: a failed append must never keep an orphan server alive.
|
||||
try {
|
||||
appendEvent(DIR, { type: "exit", reason: "idle", idleMs: idle });
|
||||
} catch {}
|
||||
process.exit(0);
|
||||
}
|
||||
if (Date.now() - STARTED > MAX_LIFE_MS) {
|
||||
if (Date.now() - STARTED > MAX_LIFE_MS && !pending) {
|
||||
try {
|
||||
appendEvent(DIR, { type: "exit", reason: "max-life" });
|
||||
} catch {}
|
||||
@@ -630,7 +650,10 @@ function onListening(port) {
|
||||
try {
|
||||
subagents.sync(readState());
|
||||
} catch {}
|
||||
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
||||
// stdout is server.log (`open` points it there), so the ready line names
|
||||
// the server without the token segment: the log is not a place for it. The
|
||||
// full link lives only in the handle file, which is private to this user.
|
||||
process.stdout.write(JSON.stringify({ type: "ready", url: `http://127.0.0.1:${port}/`, port, sid: SID }) + "\n");
|
||||
try {
|
||||
startUpdateCheck();
|
||||
} catch {}
|
||||
|
||||
@@ -6,7 +6,7 @@ import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
import { countPending } from "./git-repo.mjs";
|
||||
import { countPending, git } from "./git-repo.mjs";
|
||||
import { DOC_TYPES } from "./public/answers.js";
|
||||
import { appendJsonLine, HOME_DIR, newestMtime, nowIso, PLAN2CODE_DIR, readJson, readJsonLines, readText, RUNTIME_DIR, SESSIONS_DIR } from "./files.mjs";
|
||||
|
||||
@@ -210,6 +210,24 @@ export function attachmentName({ upload, name }) {
|
||||
// Sessions and their uploads age out on the same clock: a month untouched.
|
||||
export const SESSION_MAX_AGE_MS = UPLOAD_MAX_AGE_MS;
|
||||
|
||||
// A server's lifetime cap, one number for the server (MAX_LIFE_MS in
|
||||
// server.mjs) and for `stop`, which reasons about how old a server can be.
|
||||
// A server past it stays up only while answers nobody collected wait in its
|
||||
// session (resultWaiting below): exiting would strand them.
|
||||
export const SERVER_MAX_LIFE_MS = 4 * 60 * 60 * 1000;
|
||||
|
||||
// Answers the person sent that no agent has collected yet: a result.json with
|
||||
// no consumedAt. The server keeps its own cached reading of the same rule
|
||||
// (resultFlags in server.mjs); this one is for the CLI side.
|
||||
export function resultWaiting(dir) {
|
||||
try {
|
||||
const r = JSON.parse(fs.readFileSync(path.join(dir, "result.json"), "utf8"));
|
||||
return Boolean(r && !r.consumedAt);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const PDF_MAGIC = Buffer.from("%PDF-", "ascii");
|
||||
|
||||
/**
|
||||
@@ -351,6 +369,10 @@ export async function removeScratch(consoleDir, names) {
|
||||
// the desktop app (app/, which install.js fills, and app.json, its settings)
|
||||
// and the custom agents the person added (agents.json).
|
||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
||||
// The shared console install: install.js copies one folder per version here
|
||||
// (~/.plan2code/console/<version>/) and removes the old ones, so Cleanup never
|
||||
// offers it.
|
||||
export const CONSOLE_VERSION_DIR = /^\d+\.\d+\.\d+$/;
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs", "notepads", "app", "app.json", "agents.json"]);
|
||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
||||
// folders hold files that live for milliseconds -- a held
|
||||
@@ -384,7 +406,7 @@ function entryKind(entry) {
|
||||
return entry.isDirectory() ? "folder" : "file";
|
||||
}
|
||||
|
||||
function strayEntries(dir, kept, where, now) {
|
||||
function strayEntries(dir, kept, where, now, keptPattern = null) {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
@@ -393,14 +415,15 @@ function strayEntries(dir, kept, where, now) {
|
||||
}
|
||||
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
|
||||
return entries
|
||||
.filter((e) => !kept.has(e.name))
|
||||
.filter((e) => !kept.has(e.name) && !(keptPattern && e.isDirectory() && keptPattern.test(e.name)))
|
||||
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
||||
.filter((e) => settled(e.path));
|
||||
}
|
||||
|
||||
// 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.
|
||||
// file. Loose files at the top are not specs and stay. `tracked` says whether
|
||||
// git could give it back after a delete (removeCleanup refuses one it could not).
|
||||
function completedSpecs(project, now, maxAgeMs) {
|
||||
const dir = path.join(project, "specs--completed");
|
||||
let entries;
|
||||
@@ -412,7 +435,33 @@ function completedSpecs(project, now, maxAgeMs) {
|
||||
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);
|
||||
.filter((e) => now - newestMtime(e.path) > maxAgeMs)
|
||||
.map((e) => ({ ...e, tracked: trackedByGit(dir, e.name) }));
|
||||
}
|
||||
|
||||
// True only when git tracks `name` (under `dir`) and could give back every
|
||||
// file in it as it stands: `git ls-files` lists something, and `git status`
|
||||
// (untracked, ignored, modified and staged alike) lists nothing, since git can
|
||||
// restore only what was committed. Outside a repository, or when git fails, it
|
||||
// is not tracked. `specs--completed/` is gitignored by default, so most
|
||||
// archives answer false. Nothing records a backup copy yet, so tracked and
|
||||
// committed is the only way through.
|
||||
function trackedByGit(dir, name) {
|
||||
const run = (args) => git(["--literal-pathspecs", ...args, "--", name], dir, { raw: true });
|
||||
const cached = run(["ls-files", "-z"]);
|
||||
if (!cached.ok || !cached.out) return false;
|
||||
const changed = run(["status", "--porcelain=v1", "-z", "--ignored", "--untracked-files=all"]);
|
||||
return changed.ok && !changed.out;
|
||||
}
|
||||
|
||||
// The line the page shows for completed specs Cleanup kept because deleting
|
||||
// them would lose them for good. "" when none was refused.
|
||||
function refusalLine(names) {
|
||||
if (!names.length) return "";
|
||||
const list = names.map((n) => "specs--completed/" + n + "/").join(", ");
|
||||
return names.length === 1
|
||||
? `Kept ${list}: git does not track it as it stands, so deleting it would lose it for good. Commit it first, or delete it yourself once it is backed up.`
|
||||
: `Kept ${names.length} completed specs git does not track as they stand, so deleting them would lose them for good: ${list}. Commit them first, or delete them yourself once they are backed up.`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -444,7 +493,7 @@ export async function cleanupFindings({
|
||||
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
|
||||
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
|
||||
}
|
||||
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
|
||||
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now, CONSOLE_VERSION_DIR));
|
||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
||||
}
|
||||
@@ -463,6 +512,7 @@ export async function cleanupFindings({
|
||||
bytes += size;
|
||||
const item = { id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path };
|
||||
if (f.where === "notepad") item.folder = f.folder;
|
||||
if (f.where === "completed") item.tracked = f.tracked;
|
||||
items.push(item);
|
||||
}
|
||||
return { items, bytes };
|
||||
@@ -472,8 +522,10 @@ export async function cleanupFindings({
|
||||
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
|
||||
* worked out afresh first and only ids on it are touched, so a name from the
|
||||
* page is never a path, and anything that stopped qualifying since the scan
|
||||
* (a session touched again) stays. A link is unlinked, never followed.
|
||||
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
|
||||
* (a session touched again) stays. A link is unlinked, never followed. A
|
||||
* completed spec git does not track is refused, never deleted: it lands in
|
||||
* `refused`, and `refusal` is the line the page shows ("" when none was).
|
||||
* Resolves to `{ removed: [id], bytes, failed: [id], refused: [id], refusal }`.
|
||||
*/
|
||||
export async function removeCleanup(ids, opts = {}) {
|
||||
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
|
||||
@@ -481,9 +533,16 @@ export async function removeCleanup(ids, opts = {}) {
|
||||
const { removeNotepad } = await import("./notepads.mjs");
|
||||
const removed = [];
|
||||
const failed = [];
|
||||
const refused = [];
|
||||
const refusedNames = [];
|
||||
let bytes = 0;
|
||||
for (const item of items) {
|
||||
if (!wanted.has(item.id)) continue;
|
||||
if (item.where === "completed" && !item.tracked) {
|
||||
refused.push(item.id);
|
||||
refusedNames.push(item.name);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
if (item.where === "notepad") removeNotepad(item.name);
|
||||
else if (item.kind === "link") await fs.promises.unlink(item.path);
|
||||
@@ -494,7 +553,7 @@ export async function removeCleanup(ids, opts = {}) {
|
||||
failed.push(item.id);
|
||||
}
|
||||
}
|
||||
return { removed, bytes, failed };
|
||||
return { removed, bytes, failed, refused, refusal: refusalLine(refusedNames) };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//
|
||||
// The task markers and the task-line, checkbox and Status-line patterns, in
|
||||
// one place, so every reader of a spec counts and names its tasks the same
|
||||
// way. Imported by scan.mjs (the dashboard's spec states), patches.mjs (a doc
|
||||
// way, and deriveSpecState(), the one rule for a documented spec's state.
|
||||
// Imported by scan.mjs (the dashboard's spec states), patches.mjs (a doc
|
||||
// block's `select: "tasks"`) and src/skill-scripts/specs.mjs (through
|
||||
// consoleModule(), so the installed skill reads with this same copy). No
|
||||
// imports and nothing runs at load but building the patterns.
|
||||
@@ -72,24 +73,113 @@ export function phaseChecklist(overview) {
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* A spec folder's phase files by phase number, from its file names: the
|
||||
* `phase-<N>...md` files, one per number. When a number has several files
|
||||
* the exact `phase-<N>.md` wins, else the first by name; the rest are listed
|
||||
* in the map's `extra` (number -> names). The one rule for which files are a
|
||||
* spec's phases, shared by the dashboard scan and specs.mjs.
|
||||
*/
|
||||
export function pickPhaseFiles(names) {
|
||||
const files = new Map();
|
||||
const extra = new Map();
|
||||
for (const name of [...(names || [])].sort()) {
|
||||
const m = name.match(/^phase-(\d+)\b[^/]*\.md$/i);
|
||||
if (!m) continue;
|
||||
const n = Number(m[1]);
|
||||
const exact = new RegExp(`^phase-0*${n}\\.md$`, "i").test(name);
|
||||
if (!files.has(n)) files.set(n, name);
|
||||
else if (exact) {
|
||||
(extra.get(n) || extra.set(n, []).get(n)).push(files.get(n));
|
||||
files.set(n, name);
|
||||
} else (extra.get(n) || extra.set(n, []).get(n)).push(name);
|
||||
}
|
||||
files.extra = extra;
|
||||
return files;
|
||||
}
|
||||
|
||||
// A written reason on a blocked task: "BLOCKED: <why>" (Implementation
|
||||
// Mode's blocker format) or "Reason: <why>", on the task line or under it.
|
||||
export const BLOCK_REASON_RE = /\b(?:blocked|reason)\s*:\s*\S/i;
|
||||
|
||||
/**
|
||||
* A phase file's tasks by where they stand. The task lines when the file has
|
||||
* them, so an Acceptance Criteria checkbox is not counted as a task; every
|
||||
* checkbox in a file written before that format. `[?]` (assumed done) is
|
||||
* counted apart from `[x]`; an unknown marker is not counted at all.
|
||||
* counted apart from `[x]`, `[!]` (blocked) apart from the open ones, and an
|
||||
* unknown marker (`[~]`) is open: it is not done. `bare` counts the blocked
|
||||
* tasks with no written reason (BLOCK_REASON_RE) on their line or under it.
|
||||
*/
|
||||
export function countTasks(text) {
|
||||
const lines = (text || "").split(/\r?\n/);
|
||||
const tasks = lines.filter((l) => TASK_LINE_RE.test(l));
|
||||
const hasTasks = lines.some((l) => TASK_LINE_RE.test(l));
|
||||
let done = 0;
|
||||
let assumed = 0;
|
||||
let open = 0;
|
||||
for (const line of tasks.length ? tasks : lines) {
|
||||
let blocked = 0;
|
||||
let bare = 0;
|
||||
lines.forEach((line, i) => {
|
||||
if (hasTasks && !TASK_LINE_RE.test(line)) return;
|
||||
const m = line.match(CHECKBOX_RE);
|
||||
if (!m) continue;
|
||||
if (!m) return;
|
||||
if (m[1] === "x" || m[1] === "X") done++;
|
||||
else if (m[1] === "?") assumed++;
|
||||
else if (m[1] === " " || m[1] === "/" || m[1] === "!") open++;
|
||||
else if (m[1] === "!") {
|
||||
blocked++;
|
||||
// The task's body runs to the next heading or checkbox.
|
||||
let end = i + 1;
|
||||
while (end < lines.length && !/^#{1,6}\s/.test(lines[end]) && !CHECKBOX_RE.test(lines[end])) end++;
|
||||
if (!BLOCK_REASON_RE.test(line.replace(CHECKBOX_RE, "")) && !BLOCK_REASON_RE.test(lines.slice(i + 1, end).join("\n"))) bare++;
|
||||
} else open++;
|
||||
});
|
||||
return { done, assumed, open, blocked, bare, total: done + assumed + open + blocked };
|
||||
}
|
||||
|
||||
/**
|
||||
* A documented spec's state, from its overview.md text (or null) and its
|
||||
* phase files' texts (`[{ number, text }]`, one per phase number, as
|
||||
* pickPhaseFiles() picks them). The one derivation the dashboard scan and
|
||||
* specs.mjs both use, so they cannot drift:
|
||||
*
|
||||
* - `built`: no task is open or blocked, at least one is done, and every
|
||||
* phase the Phase Checklist lists as not yet approved has a phase file with
|
||||
* tasks in it.
|
||||
* - `building`: some task is done but the spec is not built. Blocked tasks
|
||||
* are named in `detail`; when they are all that is left and each carries a
|
||||
* written reason, `finalizeReady` is true (the dashboard lights Finalize).
|
||||
* - `documented`: nothing done yet.
|
||||
*
|
||||
* Returns { state, detail, done, assumed, open, blocked, bare, total,
|
||||
* unwritten, finalizeReady }, where `unwritten` lists the phase numbers the
|
||||
* checklist names as open with no phase file, or with a phase file holding
|
||||
* no tasks.
|
||||
*/
|
||||
export function deriveSpecState({ overview = null, phases = [] } = {}) {
|
||||
const rows = overview == null ? [] : phaseChecklist(overview);
|
||||
const approved = (n) => rows.some((r) => r.number === n && (r.marker === "x" || r.marker === "X" || r.marker === "?"));
|
||||
const sum = { done: 0, assumed: 0, open: 0, blocked: 0, bare: 0, total: 0 };
|
||||
const unwritten = [];
|
||||
const numbers = new Set();
|
||||
for (const p of phases) {
|
||||
numbers.add(p.number);
|
||||
const n = countTasks(p.text);
|
||||
for (const k of Object.keys(sum)) sum[k] += n[k];
|
||||
if (n.total === 0 && !approved(p.number)) unwritten.push(p.number);
|
||||
}
|
||||
return { done, assumed, open, total: done + assumed + open };
|
||||
for (const r of rows) if (!numbers.has(r.number) && !approved(r.number) && !unwritten.includes(r.number)) unwritten.push(r.number);
|
||||
unwritten.sort((a, b) => a - b);
|
||||
const finished = sum.done + sum.assumed;
|
||||
const assumedNote = sum.assumed > 0 ? `, ${sum.assumed} assumed` : "";
|
||||
const blockedNote = sum.blocked > 0 ? `, ${sum.blocked} blocked` : "";
|
||||
const unwrittenNote = unwritten.length ? `, Phase ${unwritten.join(", ")} not written up` : "";
|
||||
const base = { ...sum, unwritten, finalizeReady: false };
|
||||
if (finished > 0 && sum.open === 0 && sum.blocked === 0 && !unwritten.length) {
|
||||
return { ...base, state: "built", detail: `all tasks done${assumedNote}` };
|
||||
}
|
||||
if (finished > 0) {
|
||||
const finalizeReady = sum.open === 0 && sum.blocked > 0 && sum.bare === 0 && !unwritten.length;
|
||||
return { ...base, finalizeReady, state: "building", detail: `${finished} of ${sum.total} tasks done${assumedNote}${blockedNote}${unwrittenNote}` };
|
||||
}
|
||||
const count = phases.length;
|
||||
return { ...base, state: "documented", detail: `${count} phase${count === 1 ? "" : "s"}, ${sum.total || "?"} tasks ready` };
|
||||
}
|
||||
Reference in new issue
Block a user