mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-27 21:11:18 -08:00
Compare commits
90
Commits
v2.5.0
..
c0ea70e838
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0ea70e838 | ||
|
|
61f927466e | ||
|
|
42d220ce4c | ||
|
|
47c6129315 | ||
|
|
4a5f759173 | ||
|
|
8dc2f5d15d | ||
|
|
fa568a960d | ||
|
|
9a81b9cd24 | ||
|
|
340044664d | ||
|
|
06195cf692 | ||
|
|
2b247c9093 | ||
|
|
1085039110 | ||
|
|
e57dad052c | ||
|
|
32d1487dcf | ||
|
|
4cbf426df2 | ||
|
|
8a8cc14e0d | ||
|
|
1907281b40 | ||
|
|
cf9fe6d80f | ||
|
|
0c17ef1454 | ||
|
|
0767c6b4c7 | ||
|
|
b78b3cd6a3 | ||
|
|
474c76e564 | ||
|
|
161e424632 | ||
|
|
09aa565559 | ||
|
|
0501260098 | ||
|
|
48a7cf68bd | ||
|
|
30860a7654 | ||
|
|
fda0146969 | ||
|
|
75605e5e41 | ||
|
|
3b18b42e30 | ||
|
|
8e457fa6e4 | ||
|
|
6740e26261 | ||
|
|
aedfe944b2 | ||
|
|
9b3c06b498 | ||
|
|
8fe1bfa805 | ||
|
|
68542fd778 | ||
|
|
4656a6ebb7 | ||
|
|
7e9de755f1 | ||
|
|
4b20f93bb9 | ||
|
|
5b3b84f0a9 | ||
|
|
1015b99a6a | ||
|
|
20a9e2f040 | ||
|
|
28bda05cbf | ||
|
|
5274bdbd51 | ||
|
|
25d874d87d | ||
|
|
5e48e98293 | ||
|
|
8e0b1a2ab2 | ||
|
|
c2579a7b6a | ||
|
|
9d1104d105 | ||
|
|
72fed09aab | ||
|
|
37311a7e68 | ||
|
|
c92865c395 | ||
|
|
63656d339d | ||
|
|
628e688ab9 | ||
|
|
157e55ef2e | ||
|
|
02fd4efa40 | ||
|
|
348c8ed7b2 | ||
|
|
5c2f70a37c | ||
|
|
de46275b51 | ||
|
|
b7b2595fe1 | ||
|
|
6f98f6bd7f | ||
|
|
035cc680a7 | ||
|
|
34704eaf84 | ||
|
|
474e591f58 | ||
|
|
6a6b4c6fac | ||
|
|
b865b74cd0 | ||
|
|
f8c7a96bc7 | ||
|
|
edee3fc65e | ||
|
|
9d67de78c8 | ||
|
|
2409e8dbfb | ||
|
|
eaa9a633a0 | ||
|
|
9a49ba09fb | ||
|
|
7898ebf7ab | ||
|
|
e33a67e269 | ||
|
|
92acc99b71 | ||
|
|
50c281f11f | ||
|
|
5159b531ec | ||
|
|
0cee0f8962 | ||
|
|
b2fdab6814 | ||
|
|
f7da7d34c0 | ||
|
|
18321b62da | ||
|
|
495a5bb861 | ||
|
|
d9f87a7eb1 | ||
|
|
be41f3f1f8 | ||
|
|
87167f54f4 | ||
|
|
a4d15faba9 | ||
|
|
7a25084d25 | ||
|
|
d908a4d44c | ||
|
|
15911e970a | ||
|
|
4086c2e592 |
No files matched your search
@@ -51,15 +51,14 @@ plan2code/
|
|||||||
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
|
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
|
||||||
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
|
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
|
||||||
│ ├── test-web-console.mjs, test-launcher.mjs # node --test suites
|
│ ├── test-web-console.mjs, test-launcher.mjs # node --test suites
|
||||||
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, skill-script-helpers.mjs # Skill script suites and fixtures
|
|
||||||
│ └── validate-char-count.js # Pre-commit character count validator
|
│ └── validate-char-count.js # Pre-commit character count validator
|
||||||
├── skills/ # Committed build artifact — one Agent Skill per src/ prompt
|
├── skills/ # Committed build artifact — one Agent Skill per src/ prompt
|
||||||
│ └── plan2code-<name>/ # SKILL.md plus references/ and scripts/ where present
|
│ └── plan2code-<name>/ # SKILL.md plus references/ where present
|
||||||
│ # Generated by npm run build:skills; consumed by skills add
|
│ # Generated by npm run build:skills; consumed by skills add
|
||||||
├── .husky/ # Git hooks (husky)
|
├── .husky/ # Git hooks (husky)
|
||||||
│ └── pre-commit # Runs character count validation
|
│ └── pre-commit # Runs character count validation
|
||||||
├── .claude/ # Repo-local Claude Code config (NOT installed by install.js)
|
├── .claude/ # Repo-local Claude Code config (NOT installed by install.js)
|
||||||
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/, plan2code-model-update/
|
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/
|
||||||
├── .github/ISSUE_TEMPLATE/ # bug.yml, idea.yml, config.yml (target of the console's feedback button)
|
├── .github/ISSUE_TEMPLATE/ # bug.yml, idea.yml, config.yml (target of the console's feedback button)
|
||||||
├── .readme/ # User guides linked from README (web-console.md, web-console-design.md, walkthrough.md, autonomous-loop.md, metrics.md, status-line.md, test-bot.md)
|
├── .readme/ # User guides linked from README (web-console.md, web-console-design.md, walkthrough.md, autonomous-loop.md, metrics.md, status-line.md, test-bot.md)
|
||||||
├── docs/ # Landing page `index.html` served at plan2code.jparkerweb.com (GitHub Pages, `CNAME`) and assets
|
├── docs/ # Landing page `index.html` served at plan2code.jparkerweb.com (GitHub Pages, `CNAME`) and assets
|
||||||
@@ -81,7 +80,7 @@ plan2code/
|
|||||||
| `install.js` | Interactive installer — builds `skills/` from `src/`, then delegates installation to the skills CLI |
|
| `install.js` | Interactive installer — builds `skills/` from `src/`, then delegates installation to the skills CLI |
|
||||||
| `src/plan2code-*.md` | Source workflow prompts (the "source of truth") |
|
| `src/plan2code-*.md` | Source workflow prompts (the "source of truth") |
|
||||||
| `skills/` | Generated Agent Skills committed for installation and drift verification |
|
| `skills/` | Generated Agent Skills committed for installation and drift verification |
|
||||||
| `scripts/validate-char-count.js` | Pre-commit validator ensuring all source prompts ≤ 20,000 chars |
|
| `scripts/validate-char-count.js` | Pre-commit validator ensuring all source prompts ≤ 11,500 chars |
|
||||||
| `version.json` | Version metadata (name, version, description) |
|
| `version.json` | Version metadata (name, version, description) |
|
||||||
| `QUICK-REFERENCE.md` | User quick-reference card |
|
| `QUICK-REFERENCE.md` | User quick-reference card |
|
||||||
| `src/statusline-claude/` | Claude CLI status bar (see Status Line below) |
|
| `src/statusline-claude/` | Claude CLI status bar (see Status Line below) |
|
||||||
@@ -119,39 +118,13 @@ Examples:
|
|||||||
|
|
||||||
## Reference Files
|
## Reference Files
|
||||||
|
|
||||||
Some workflows use companion reference files for depth that does not need to load on every invocation. The orchestrator (main workflow file) loads them via `Read` directives during execution.
|
Some workflows use companion reference files for depth that exceeds the 11.5k char limit. The orchestrator (main workflow file) loads them via `Read` directives during execution.
|
||||||
|
|
||||||
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`)
|
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`)
|
||||||
|
|
||||||
**How the installer handles them:** the directory is copied verbatim to `skills/<skill-name>/references/`, so `Read references/<file>.md` resolves consistently for every agent. There is one output format, with no flat-file sibling directory or path rewrite.
|
**How the installer handles them:** the directory is copied verbatim to `skills/<skill-name>/references/`, so `Read references/<file>.md` resolves consistently for every agent. There is one output format, with no flat-file sibling directory or path rewrite.
|
||||||
|
|
||||||
Reference files are NOT subject to the 20,000 character limit. The review workflow pioneered this pattern (`verification-protocol`, `dimensions`, `false-positives`, `session-end`); the init-update workflow also uses it (`ai-agent-file-sync` for its Step 7), `plan2code-4-finalize.md` uses it for STEP 6.5 (`community-feedback-submission`), and `plan2code-0-pathfinder.md` leans on it hardest (`brief`, `chart`, `github-issues`, `grilling`, `questions`, `resolve`, `handoff`, `trail` — the orchestrator is a dispatcher, the depth lives in the references). Other workflows can adopt it when a source file carries detail that is only needed some of the time. The implement-review skill is a generated composition: `additionalReferences` in `SOURCE_PROMPTS` packages the canonical implement prompt, review prompt, and review reference directory into its own `references/` directory so those workflows are reused without source duplication.
|
The review workflow pioneered this pattern (`verification-protocol`, `dimensions`, `false-positives`, `session-end`); the init-update workflow also uses it (`ai-agent-file-sync` for its Step 7), `plan2code-4-finalize.md` uses it for STEP 6.5 (`community-feedback-submission`), and `plan2code-0-pathfinder.md` leans on it hardest (`brief`, `chart`, `github-issues`, `grilling`, `questions`, `resolve`, `handoff`, `trail` — the orchestrator is a dispatcher, the depth lives in the references). Other workflows can adopt it when a source file's detail exceeds the 11.5k limit. The implement-review skill is a generated composition: `additionalReferences` in `SOURCE_PROMPTS` packages the canonical implement prompt, review prompt, and review reference directory into its own `references/` directory so those workflows are reused without source duplication.
|
||||||
|
|
||||||
## Skill Scripts
|
|
||||||
|
|
||||||
Anything a workflow step decides with one correct answer (parsing a spec's checkboxes, rebuilding Pathfinder's map markers, the commit message, which AI config files exist) lives in a script the agent runs, not in prose it follows. Prose keeps the judgment.
|
|
||||||
|
|
||||||
| Source | Ships to | How |
|
|
||||||
|---|---|---|
|
|
||||||
| `src/skill-scripts/<name>.mjs` | `skills/<skill>/scripts/<name>.mjs` | Shared: a skill lists the ones it runs in `scripts: [...]` on its `SOURCE_PROMPTS` entry. Skills install independently, so each gets its own copy |
|
|
||||||
| `src/skill-scripts/common.mjs` | every skill that has scripts | `SHARED_SCRIPTS_ALWAYS` in `install.js` |
|
|
||||||
| `src/<source>-scripts/<name>.mjs` | `skills/<skill>/scripts/<name>.mjs` | A skill's own scripts, mirroring `-references/`. A name that collides with a shared script is a build error |
|
|
||||||
| `version.json` (repo root) | `skills/<skill>/scripts/version.json` | Copied at build, so an installed skill can report its version |
|
|
||||||
|
|
||||||
| Script | Skills | Does |
|
|
||||||
|---|---|---|
|
|
||||||
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff | `list` / `status` (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `metrics` / `mark` / `archive`. Imports `scanProject()` from the bundled `web-console/lib.mjs`, so the dashboard and the skills share one spec classifier |
|
|
||||||
| `commit-msg.mjs` | implement(-review), review, quick-task, finalize, init-update | The `<subject>` / ticket / `AI Assisted` command from the branch name |
|
|
||||||
| `review-scope.mjs` | review, implement(-review), quick-task | Review Mode's git fallback: files, lines, doc share, base branch |
|
|
||||||
| `agents-md.mjs` | init, init-update | AGENTS.md structure, budget, orphans, broken links, always-inline sections |
|
|
||||||
| `agent-files.mjs` | init, init-update | Detect and replace other agents' config files with AGENTS.md pointers |
|
|
||||||
| `pathfinder.mjs` (own) | 0-pathfinder | `reconcile`, `frontier`, `claim`, `resolve`, `rule-out`, `trail`, `gate`, `lint`, `brief-data` |
|
|
||||||
| `feedback-payload.mjs` (own) | 4-finalize | STEP 6.5's payload (real sha256 prompt hashes) and the gh / browser / print submission tiers |
|
|
||||||
| `handoff-path.mjs` (own) | handoff | Timestamped path, OS temp dir, git ignore check |
|
|
||||||
|
|
||||||
**Conventions** (`common.mjs`): Node 18+ built-ins only; one JSON object on stdout (`ok: false` plus `error`, `message`, `next` on a handled failure, the same line on stderr); exit 0 ok, 1 crash, 2 bad arguments, 3 not found, 4 invalid or check failed, 5 refused; `--help` documents commands and exit codes; writes take `--dry-run`; `PLAN2CODE_NOW` pins the clock for tests. A SKILL.md names a script as `node "<S>/<name>.mjs"`, where `<S>` is `scripts/` beside it.
|
|
||||||
|
|
||||||
**Tests:** `scripts/test-skill-scripts.mjs` (installer plumbing and the shared scripts), `scripts/test-script-<skill>.mjs` (a skill's own), with fixtures from `scripts/skill-script-helpers.mjs`. They run the built `skills/` tree, and one test fails if any SKILL.md or shipped reference names a `<S>/<name>.mjs` that skill does not ship. The per-skill scripts import `./common.mjs`, which only sits beside them in the built tree, so run them from `skills/`, not `src/`.
|
|
||||||
|
|
||||||
## Repo-Local Skills (`.claude/skills/`)
|
## Repo-Local Skills (`.claude/skills/`)
|
||||||
|
|
||||||
@@ -159,7 +132,6 @@ Maintainer-only skills committed to the repo but deliberately excluded from the
|
|||||||
|
|
||||||
- `plan2code-publish/` — publishes a GitHub Release after version files agree.
|
- `plan2code-publish/` — publishes a GitHub Release after version files agree.
|
||||||
- `plan2code-changelog/` — validates release classification and keeps version files synchronized.
|
- `plan2code-changelog/` — validates release classification and keeps version files synchronized.
|
||||||
- `plan2code-model-update/` — refreshes the launcher's curated model menu (`src/launcher/models.json`) from `devin models list` and Claude Code's documented model aliases: shows a diff, applies only the changes the maintainer approves, validates the file and runs `npm test`. Terminal only, and it never commits.
|
|
||||||
- `sync-repo/` — decrypts the protected upstream-sync workflow in memory.
|
- `sync-repo/` — decrypts the protected upstream-sync workflow in memory.
|
||||||
|
|
||||||
Do not run `skills add` against the repository root: recursive discovery also finds these maintainer skills. `install.js` targets `skills/` and passes explicit workflow names instead. Global install/uninstall cleanup removes `plan2code-*` workflow skills from user skill directories; it never operates on this repository's `.claude/skills/` directory, and `sync-repo` intentionally has no `plan2code-` prefix.
|
Do not run `skills add` against the repository root: recursive discovery also finds these maintainer skills. `install.js` targets `skills/` and passes explicit workflow names instead. Global install/uninstall cleanup removes `plan2code-*` workflow skills from user skill directories; it never operates on this repository's `.claude/skills/` directory, and `sync-repo` intentionally has no `plan2code-` prefix.
|
||||||
@@ -172,16 +144,14 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`) |
|
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`) |
|
||||||
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
|
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
|
||||||
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()`; plus `cleanupFindings()` / `removeCleanup()` for User Preferences → Cleanup |
|
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()` |
|
||||||
| `public/` | `index.html`, `app.js`, `answers.js`, `labels.js`, `boot.js`, `chat.js`, `help.js`, `starters.js`, `workspace.js`, `meter.js`, `subagents.js`, `mentions.js`, `favicon.js`, `app.css`, `render.js`, `palette.js`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server, `console.mjs`, `lib.mjs` and the tests import several `public/*.js` modules) parses them as ES modules without a reparse warning |
|
| `public/` | `index.html`, `app.js`, `answers.js`, `labels.js`, `boot.js`, `chat.js`, `help.js`, `starters.js`, `workspace.js`, `meter.js`, `mentions.js`, `favicon.js`, `app.css`, `render.js`, `palette.js`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server, `console.mjs`, `lib.mjs` and the tests import several `public/*.js` modules) parses them as ES modules without a reparse warning |
|
||||||
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (17 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
|
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (16 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
|
||||||
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `console.mjs`, `lib.mjs` and the page |
|
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `console.mjs`, `lib.mjs` and the page |
|
||||||
| `public/meter.js` | PURE, no imports: the session meter. `WEIGHTS` (the one place per-event points live; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
|
| `public/meter.js` | PURE, no imports: the session meter. `WEIGHTS` (the one place per-event points live; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), `pointsFrom()` (the count, folded from `ledger.ndjson` and deduplicated by id — never stored), `levelFor()` with `YELLOW_AT` 4 / `RED_AT` 6, `ringFraction()` (full at `RING_FULL` 8), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
|
||||||
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
|
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
|
||||||
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
|
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
|
||||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, `console.mjs`, `lib.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
|
||||||
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
|
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
|
||||||
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network |
|
|
||||||
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
|
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
|
||||||
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 13 starter templates and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by `app.js` and the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
|
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 13 starter templates and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by `app.js` and the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
|
||||||
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Split out of `app.js` because `app.js` cannot be imported outside a browser, so anything left in it is untestable. `scripts/test-web-console.mjs` imports this directly. |
|
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Split out of `app.js` because `app.js` cannot be imported outside a browser, so anything left in it is untestable. `scripts/test-web-console.mjs` imports this directly. |
|
||||||
@@ -202,7 +172,6 @@ Key design points:
|
|||||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `server.mjs`, which paints `data-width` on first load; `app.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `server.mjs`, which paints `data-width` on first load; `app.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||||
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
|
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
|
||||||
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
|
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
|
||||||
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes }], bytes }`, ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `models.json`). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
|
||||||
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
|
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
|
||||||
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `app.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `app.css`; `START_POSES`/`startPose()` in `answers.js` is the list, and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `app.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `app.css`; `START_POSES`/`startPose()` in `answers.js` is the list, and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
||||||
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
|
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
|
||||||
@@ -210,25 +179,15 @@ Key design points:
|
|||||||
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `lib.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
|
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `lib.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
|
||||||
- **The first paint needs no fetch.** `server.mjs` renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to `app.css`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
|
- **The first paint needs no fetch.** `server.mjs` renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to `app.css`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
|
||||||
- **Reads are stat-gated.** `fileStamp()` (mtime:size:ino) decides whether `state.json`, `result.json` and `looks.json` changed before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (`readState()` returns it; `/submit` clones before editing). `wait` stats `result.json` every 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
|
- **Reads are stat-gated.** `fileStamp()` (mtime:size:ino) decides whether `state.json`, `result.json` and `looks.json` changed before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (`readState()` returns it; `/submit` clones before editing). `wait` stats `result.json` every 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
|
||||||
- **The Workspace and the session meter live beside `state.json`, one writer each, and outlive every hop.** Three session files, none of which `switchWorkflow()` ever touches, so both survive dashboard → skill → dashboard (a new console session starts with a count of 0, and with the folders remembered for its folder and spec, below):
|
- **The Workspace and the session meter live beside `state.json`, one writer each, and outlive every hop.** Three session files, none of which `switchWorkflow()` ever touches, so both survive dashboard → skill → dashboard (a new console session starts with the original folder alone and a count of 0):
|
||||||
|
|
||||||
| File | Writer | Holds |
|
| File | Writer | Holds |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `workspace.json` | `server.mjs` | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()`, now in `lib.mjs`, computed by the server at boot) |
|
| `workspace.json` | `server.mjs` | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()`, now in `lib.mjs`, computed by the server at boot) |
|
||||||
| `ledger.ndjson` | `console.mjs` | append-only, one JSON line per entry. Meter events: `launch` (every fresh `open` and every resume into another workflow), `run` (a post's `run`, id scoped by launch, with `tasks` when a built phase reports one) and `answer` (one per item the person answered in a collected send, written by `ledgerAnswers()`, id `<launch>:answer:<send stamp>:<item>`). Also `folder-issue` reports |
|
| `ledger.ndjson` | `console.mjs` | append-only meter events — `launch` (every fresh `open` and every resume into another workflow), `run` (a post's `run`, id scoped by launch) — and `folder-issue` reports |
|
||||||
| `workspace-cursor.json` | `console.mjs` | the last workspace `version` handed to the agent; advanced after the print, never backwards |
|
| `workspace-cursor.json` | `console.mjs` | the last workspace `version` handed to the agent; advanced after the print, never backwards |
|
||||||
|
|
||||||
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `lib.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console.md` (Workspace; Posting an update → Session meter) and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
|
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. The contract is in `console.md` (Workspace; Posting an update → Session meter) and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
|
||||||
- **The Subagents switch is a standing instruction, injected only on change.** The page's icon button (`#btn-subagents`, after Write a brief) and `#subagents-modal` show only when the frame's `subagents` block says `offered && supported`. `offered` comes from `public/subagents.js`; `supported` means the latest `{ "type": "open" }` line in `events.ndjson` carries `caps: ["subagents"]` (`latestOpenCaps()`), so an older skill copy's `open` hides the button. Four places hold it, one writer each:
|
|
||||||
|
|
||||||
| File | Writer | Holds |
|
|
||||||
|---|---|---|
|
|
||||||
| `~/.plan2code/console/subagents.json` | `server.mjs` | per project folder → workflow: `{ on, instruction, max }`, `instruction: null` being the shipped default; on `PROTECTED_CONSOLE_FILES` |
|
|
||||||
| `<session>/subagents-setting.json` | `server.mjs` | `{ workflow, on, instruction, max, revision }`: synced from the store at boot and on any workflow change (`syncSubagentSetting()`), `revision` bumped only by a real change |
|
|
||||||
| `<session>/subagents-cursor.json` | `console.mjs` | `{ revision, state }`, the last block handed over; `open` resets it, and it moves only after the print |
|
|
||||||
| `state.json` → `helpers` | `console.mjs post` | the helpers the agent reports, merged by `id`, checked by `checkHelpers()` plus the prose scan; dropped by `switchWorkflow()` on a dashboard hop |
|
|
||||||
|
|
||||||
`POST /subagents` (origin-checked; `400` `not-offered` / `bad` / `too-long` / `max`) saves the store and bumps the session setting. `consume()`, `cmdChat()`, `deliverChat()` and `open` append `blockFor()`'s lines last in `reply` and the `subagents` field; a change alone never ends a `wait` slice. The page's Subagents tab (before Ask) draws `state.helpers` through `helperRows()`. Helpers never reach the meter ledger. Contract: `console.md` → Standing instructions.
|
|
||||||
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or the loop's marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
|
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or the loop's marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
|
||||||
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `server.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `lib.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
|
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `server.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `lib.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
|
||||||
- **Answers carry their terminal token.** Each item ships `fallbackText` and `token`, so a click resolves to the literal word the prompt already expects (`approved`, `a`, `skip`). No workflow needs a second code path, and declining the console degrades to prose with nothing lost.
|
- **Answers carry their terminal token.** Each item ships `fallbackText` and `token`, so a click resolves to the literal word the prompt already expects (`approved`, `a`, `skip`). No workflow needs a second code path, and declining the console degrades to prose with nothing lost.
|
||||||
@@ -239,10 +198,10 @@ Key design points:
|
|||||||
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `lib.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
|
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `lib.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
|
||||||
- **`validate()` in `lib.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
|
- **`validate()` in `lib.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
|
||||||
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
|
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
|
||||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 17 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed, so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `app.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 16 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed, so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `app.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
||||||
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
|
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
|
||||||
|
|
||||||
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --verify-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then `node --test scripts/test-web-console.mjs scripts/test-launcher.mjs scripts/test-skill-scripts.mjs scripts/test-script-pathfinder.mjs scripts/test-script-finalize.mjs scripts/test-script-handoff.mjs`. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --verify-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then `node --test scripts/test-web-console.mjs scripts/test-launcher.mjs`. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
||||||
|
|
||||||
**Adding a file under `public/` needs three edits, not one:** the file itself, the `SERVABLE` allow-list in `server.mjs`, and (for a module the page imports) a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a new module missing from it 404s and the page dies at import with no useful error (a test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint.
|
**Adding a file under `public/` needs three edits, not one:** the file itself, the `SERVABLE` allow-list in `server.mjs`, and (for a module the page imports) a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a new module missing from it 404s and the page dies at import with no useful error (a test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint.
|
||||||
|
|
||||||
@@ -279,7 +238,7 @@ Typing `plan2code` in any directory opens the dashboard skill against the curren
|
|||||||
| Claude Code | `claude /plan2code --permission-mode bypassPermissions [args]` |
|
| Claude Code | `claude /plan2code --permission-mode bypassPermissions [args]` |
|
||||||
| Devin | `devin --permission-mode bypass [args] -- /plan2code` |
|
| Devin | `devin --permission-mode bypass [args] -- /plan2code` |
|
||||||
|
|
||||||
On a terminal it first prints a Planny banner (`renderBanner()`). With both on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number, `claude` or `devin` also work); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with neither it exits 127 naming both. `--cli claude` / `--cli devin` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=`, it asks `Which model should <CLI> use?` from the curated `src/launcher/models.json` (copied to `~/.plan2code/bin/models.json`, overwritten by every install) merged with the user's additions in `~/.plan2code/models.json` (edited in the console's User Preferences → Models). Enter keeps the model the CLI last used; a pick appends `--model <id>`. Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin` commands and a temp home.
|
With both on `PATH` it asks `Which CLI should open Plan2Code?` as a numbered menu, the last pick pre-selected (Enter keeps it; a number, `claude` or `devin` also work); with one installed it uses that without asking; with neither it exits 127 naming both. `--cli claude` / `--cli devin` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=`, it asks `Which model should <CLI> use?` from the curated `src/launcher/models.json` (copied to `~/.plan2code/bin/models.json`, overwritten by every install) merged with the user's additions in `~/.plan2code/models.json` (edited in the console's User Preferences → Models). Enter keeps the model the CLI last used; a pick appends `--model <id>`. Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed), and it only prints which model will be used. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin` commands and a temp home.
|
||||||
|
|
||||||
**Design constraints:**
|
**Design constraints:**
|
||||||
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||||
|
|||||||
@@ -19,11 +19,11 @@
|
|||||||
- **PowerShell mangles the CHANGELOG emoji:** `Get-Content` / `Select-String` render the `###` heading emoji as `?` under the default Windows console encoding, so a heading audit done that way reports garbage. Read `CHANGELOG.md` with a file-read or grep tool instead.
|
- **PowerShell mangles the CHANGELOG emoji:** `Get-Content` / `Select-String` render the `###` heading emoji as `?` under the default Windows console encoding, so a heading audit done that way reports garbage. Read `CHANGELOG.md` with a file-read or grep tool instead.
|
||||||
- **`.claude/skills/` is tracked:** a new repo-local skill only needs `git add` (see Architecture → Repo-Local Skills). A correction that is a workflow belongs there as a skill, linked from AGENTS.md, not as a Failure log line.
|
- **`.claude/skills/` is tracked:** a new repo-local skill only needs `git add` (see Architecture → Repo-Local Skills). A correction that is a workflow belongs there as a skill, linked from AGENTS.md, not as a Failure log line.
|
||||||
- **Loop `.gitignore` setup:** `ensureGitignore()` runs at startup in `Controller.run()` as a pre-flight step, not just inside `createTaskCommit()`. This is critical for phase mode where the Node controller doesn't handle commits — without it, `git add -A` would stage spec files.
|
- **Loop `.gitignore` setup:** `ensureGitignore()` runs at startup in `Controller.run()` as a pre-flight step, not just inside `createTaskCommit()`. This is critical for phase mode where the Node controller doesn't handle commits — without it, `git add -A` would stage spec files.
|
||||||
- **Workflow file character limit:** All `src/plan2code-*.md` files (and the dashboard prompt `src/plan2code.md`) must be ≤ 20,000 characters (about 5k tokens, the usual Agent Skills guidance for a SKILL.md body). A husky pre-commit hook enforces this, and `plan2code-metrics` (`improver.ts`, `applier.ts`) applies the same number to proposed prompt edits, so change them together. History: 11,000 originally (headroom under Windsurf's old 12,000-char limit for platform-specific files, gone since 2.1.0's single-format build), 11,500 in 2.4.0, 20,000 in 2.4.1. The limit is now a prompt-size discipline only: the whole SKILL.md loads on every invocation while references load on demand, so situational detail still belongs in a reference file, and anything with one correct answer belongs in a script (see Skill scripts in the architecture doc).
|
- **Workflow file character limit:** All `src/plan2code-*.md` files (and the dashboard prompt `src/plan2code.md`) must be ≤ 11,500 characters. A husky pre-commit hook enforces this, and `plan2code-metrics` (`improver.ts`, `applier.ts`) applies the same number to proposed prompt edits, so change them together. When a prompt runs short of room, move detail into a reference file rather than compressing rules.
|
||||||
- **Keep LF line endings:** `.gitattributes` pins `eol=lf` because `validate-char-count.js` counts the characters on disk, and a CRLF checkout adds about one per line to every prompt. Measure with `node scripts/validate-char-count.js` before trusting a near-limit prompt.
|
- **Keep LF line endings:** `.gitattributes` pins `eol=lf` because `validate-char-count.js` counts the characters on disk, and a CRLF checkout adds about one per line, pushing near-limit prompts over 11,500. `plan2code-1-plan.md` has under 10 chars of headroom (11,492); measure before adding a word.
|
||||||
- **The pre-commit hook runs only the char-count check:** `.husky/pre-commit` is `node scripts/validate-char-count.js` alone. `skills/` drift, parse errors and test failures are caught only by `npm test`, so run it before committing. Sub-package tests are separate; see [Development Commands](./AGENTS-development-commands.md).
|
- **The pre-commit hook runs only the char-count check:** `.husky/pre-commit` is `node scripts/validate-char-count.js` alone. `skills/` drift, parse errors and test failures are caught only by `npm test`, so run it before committing. Sub-package tests are separate; see [Development Commands](./AGENTS-development-commands.md).
|
||||||
- **`skills/` is a committed build artifact:** edit `src/`, run `npm run build:skills`, and commit the regenerated skills in the same change. `npm test` runs `install.js --verify-skills` and fails on missing, unexpected, or stale files. Never edit `skills/` by hand.
|
- **`skills/` is a committed build artifact:** edit `src/`, run `npm run build:skills`, and commit the regenerated skills in the same change. `npm test` runs `install.js --verify-skills` and fails on missing, unexpected, or stale files. Never edit `skills/` by hand.
|
||||||
- **Metrics internal prompts have no char limit:** Files in `plan2code-metrics/src/prompts/` are NOT subject to the 20,000 char limit — only `src/plan2code-*.md` consumer-facing prompts are.
|
- **Metrics internal prompts have no char limit:** Files in `plan2code-metrics/src/prompts/` are NOT subject to the 11,500 char limit — only `src/plan2code-*.md` consumer-facing prompts are.
|
||||||
- **User Feedback table format:** The `## User Feedback` markdown table in `overview.md` has a strict format the collector regex depends on. Field names must be exactly `Rating`, `Reason`, `Went Well`, `Went Poorly`. Pipe characters in values must be escaped as `\|`.
|
- **User Feedback table format:** The `## User Feedback` markdown table in `overview.md` has a strict format the collector regex depends on. Field names must be exactly `Rating`, `Reason`, `Went Well`, `Went Poorly`. Pipe characters in values must be escaped as `\|`.
|
||||||
- **PLAN-DRAFT confidence numbers are scraped by regex:** `collector.ts` scrapes the latest `specs/<feature>/PLAN-DRAFT-*.md` prose. Overall confidence falls back to prose only when `<!-- METRICS_JSON ... -->` lacks `confidence` (`collector.ts:186-196`): `Confidence: 95%`, or a table row `| Confidence | 95` with no `%`. The four *breakdown* patterns (`collector.ts:200-203`) run on every draft, METRICS_JSON or not: `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep `Confidence` followed by a number (with `%`, or as a table row) **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class.
|
- **PLAN-DRAFT confidence numbers are scraped by regex:** `collector.ts` scrapes the latest `specs/<feature>/PLAN-DRAFT-*.md` prose. Overall confidence falls back to prose only when `<!-- METRICS_JSON ... -->` lacks `confidence` (`collector.ts:186-196`): `Confidence: 95%`, or a table row `| Confidence | 95` with no `%`. The four *breakdown* patterns (`collector.ts:200-203`) run on every draft, METRICS_JSON or not: `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep `Confidence` followed by a number (with `%`, or as a table row) **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class.
|
||||||
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console.mjs` guards it. Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `lib.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
|
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console.mjs` guards it. Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `lib.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
|
||||||
@@ -32,7 +32,7 @@
|
|||||||
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalises its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
|
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalises its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
|
||||||
- **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`.
|
- **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`.
|
||||||
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/app.css`. No test ties them together.
|
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/app.css`. No test ties them together.
|
||||||
- **Reference file sizing guideline:** Files in `src/plan2code-*-references/` directories target ~100-200 lines each (soft guideline; evaluate splitting above 300). They are NOT subject to the 20,000 character limit. The pre-commit hook (`validate-char-count.js`) only checks `src/plan2code-*.md` flat files — subdirectory contents are automatically excluded.
|
- **Reference file sizing guideline:** Files in `src/plan2code-*-references/` directories target ~100-200 lines each (soft guideline; evaluate splitting above 300). They are NOT subject to the 11,500 character limit. The pre-commit hook (`validate-char-count.js`) only checks `src/plan2code-*.md` flat files — subdirectory contents are automatically excluded.
|
||||||
- **The splitting guideline has a hard ceiling — reference files cannot always be split:** each new reference costs the orchestrator a `Read references/<file>.md` line plus its fallback blockquote (~150-200 chars), which adds up across a prompt's 20,000-char budget. When a reference legitimately exceeds 300 lines (e.g. `plan2code-0-pathfinder-references/chart.md`), that is an accepted trade-off, not an oversight. Nested folders under `-references/` work: `references/` is the real path on every agent.
|
- **The splitting guideline has a hard ceiling — reference files cannot always be split:** each new reference costs the orchestrator a `Read references/<file>.md` line plus its fallback blockquote (~150-200 chars), and orchestrators near the 11,500 limit have no room to spend. When a reference legitimately exceeds 300 lines (e.g. `plan2code-0-pathfinder-references/chart.md`), that is an accepted trade-off, not an oversight.
|
||||||
- **Windows global bins for loop, metrics and bot are wrappers, not `npm link`:** on win32 the installer writes `<name>.cmd` and `<name>.ps1` into `npm config get prefix`, each running `node <package>/dist/bin/<name>.js` (`install.js:1302-1323` for the loop; the metrics and bot installers do the same). After a source change, `npm run build` in the package is enough; no reinstall.
|
- **Windows global bins for loop, metrics and bot are wrappers, not `npm link`:** on win32 the installer writes `<name>.cmd` and `<name>.ps1` into `npm config get prefix`, each running `node <package>/dist/bin/<name>.js` (`install.js:1302-1323` for the loop; the metrics and bot installers do the same). After a source change, `npm run build` in the package is enough; no reinstall.
|
||||||
- **plan2code-metrics only runs from a repo checkout:** `analyzer.ts` and `improver.ts` load `src/prompts/analyze.md` / `improve.md` at runtime through `new URL('../src/prompts/...', import.meta.url)`, resolved relative to `dist/` (`analyzer.ts:11`, `improver.ts:13`). A packed or copied `dist/` without `src/prompts/` fails.
|
- **plan2code-metrics only runs from a repo checkout:** `analyzer.ts` and `improver.ts` load `src/prompts/analyze.md` / `improve.md` at runtime through `new URL('../src/prompts/...', import.meta.url)`, resolved relative to `dist/` (`analyzer.ts:11`, `improver.ts:13`). A packed or copied `dist/` without `src/prompts/` fails.
|
||||||
@@ -117,7 +117,6 @@ The skills CLI owns distribution from step 4 onward. It stores canonical skills
|
|||||||
| Skill name | `generateSkillName(prompt)`, such as `plan2code-1-plan` or `plan2code-init` |
|
| Skill name | `generateSkillName(prompt)`, such as `plan2code-1-plan` or `plan2code-init` |
|
||||||
| Frontmatter | `name`, `description`, `disable-model-invocation: true` |
|
| Frontmatter | `name`, `description`, `disable-model-invocation: true` |
|
||||||
| Reference files | `skills/<skill-name>/references/<path>`, copied from `src/<prompt>-references/` and `additionalReferences` (any file type; every skill bundles `web-console/` plus a copy of `version.json`) |
|
| Reference files | `skills/<skill-name>/references/<path>`, copied from `src/<prompt>-references/` and `additionalReferences` (any file type; every skill bundles `web-console/` plus a copy of `version.json`) |
|
||||||
| Scripts | `skills/<skill-name>/scripts/<file>.mjs`, plus `common.mjs` and a generated `version.json` (see Skill Scripts in the architecture doc) |
|
|
||||||
|
|
||||||
`disable-model-invocation: true` is unconditional because these workflows are user-initiated. Agents that do not recognize the field ignore it.
|
`disable-model-invocation: true` is unconditional because these workflows are user-initiated. Agents that do not recognize the field ignore it.
|
||||||
|
|
||||||
@@ -133,7 +132,7 @@ See the `skills/` build-artifact gotcha in [Code Style & Gotchas](./AGENTS-code-
|
|||||||
|
|
||||||
## Adding a New Workflow Prompt / Skill
|
## Adding a New Workflow Prompt / Skill
|
||||||
|
|
||||||
1. Create `src/plan2code-<name>.md` with body content only and keep it under 20,000 characters.
|
1. Create `src/plan2code-<name>.md` with body content only and keep it under 11,500 characters.
|
||||||
2. Register it in `SOURCE_PROMPTS` in `install.js` (with the web-console `additionalReferences` entry every skill carries); add a `generateStepLabel()` case when needed. List any shared scripts it runs in `scripts: [...]`, and put its own scripts in `src/plan2code-<name>-scripts/`. Add it to the skill/workflow table and the "What each skill reads and writes" table in `src/plan2code.md` (the latter is checked by `scripts/check-skill-table.mjs`), and to the workflow lists in `src/web-console/public/answers.js`, `public/meter.js` and the `console.mjs` usage text.
|
2. Register it in `SOURCE_PROMPTS` in `install.js` (with the web-console `additionalReferences` entry every skill carries); add a `generateStepLabel()` case when needed. Add it to the skill/workflow table and the "What each skill reads and writes" table in `src/plan2code.md` (the latter is checked by `scripts/check-skill-table.mjs`), and to the workflow lists in `src/web-console/public/answers.js`, `public/meter.js` and the `console.mjs` usage text.
|
||||||
3. Update command inventories in `README.md`, `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture.md`, and `CHANGELOG.md`. Update `docs/index.html` only for core pipeline steps.
|
3. Update command inventories in `README.md`, `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture.md`, and `CHANGELOG.md`. Update `docs/index.html` only for core pipeline steps.
|
||||||
4. Run `npm run build:skills` and `npm test`.
|
4. Run `npm run build:skills` and `npm test`.
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
---
|
|
||||||
name: plan2code-model-update
|
|
||||||
description: "Refresh the plan2code launcher's curated model menu in src/launcher/models.json from `devin models list` and Claude Code's documented model aliases, with the maintainer approving every change before anything is written. Use this skill when the user says 'update the models', 'refresh models.json', 'new Claude model', 'devin models changed', or otherwise asks to bring the launcher's model list up to date."
|
|
||||||
---
|
|
||||||
|
|
||||||
# Plan2Code Model Update
|
|
||||||
|
|
||||||
Bring the launcher's curated model menu (`src/launcher/models.json`) up to date with the models each CLI offers today. Discover what Devin and Claude Code currently offer, show the maintainer a diff against the shipped file, apply only the changes they approve, validate the file, and run `npm test`. This skill never commits.
|
|
||||||
|
|
||||||
**Repo-local by design.** This skill lives in the repo's `.claude/skills/` and is intentionally NOT wired into `install.js` — it is a maintainer dev tool, not part of the shipped product, so it is never installed to `~/.claude/skills/`. Do **not** copy it there: the uninstaller (`uninstallSkills()` in `install.js`) and every re-install (`install()`) both run `cleanLegacyPaths()`, which deletes every entry matching `/^plan2code-/` under `~/.claude/skills/` (the `LEGACY_PATHS` row for Claude Code skills), so a copy placed there would be silently removed.
|
|
||||||
|
|
||||||
**Terminal only.** This skill runs in the terminal, with no web console session. Ask every question here.
|
|
||||||
|
|
||||||
## Workflow
|
|
||||||
|
|
||||||
### Step 1 — Preflight
|
|
||||||
|
|
||||||
Run from the repo root (the folder holding `install.js` and `src/launcher/`). Run `git status --porcelain -- src/launcher/models.json`. If it prints anything, warn — do not stop:
|
|
||||||
|
|
||||||
> `src/launcher/models.json` already has uncommitted changes. The diff below compares against the file as it stands on disk, including those changes.
|
|
||||||
|
|
||||||
### Step 2 — Read the current file
|
|
||||||
|
|
||||||
Read `src/launcher/models.json`. It has three keys: `_note` (a string), `claude` and `devin` (each an array of `{ "id", "label" }`). Keep the `_note` text exactly as read — Step 7 writes it back verbatim and the Validation rules check it.
|
|
||||||
|
|
||||||
### Step 3 — Discover Devin's models
|
|
||||||
|
|
||||||
If `devin` is on PATH (`command -v devin` in bash, `Get-Command devin` in PowerShell), run:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
devin models list
|
|
||||||
```
|
|
||||||
|
|
||||||
Show its raw output to the maintainer before any interpretation — the format is not a stable contract. The output is long (hundreds of ids across about twenty families), so save it to a scratch file outside the repo, say where, and show the family headings in full. From it, take the explicit ids at Low, Medium and High effort only, plus `adaptive`. Skip every id the Validation rules forbid (`xhigh`, `max`, `fast`, `priority` endings), and also skip `none`-effort ids, ids with no effort suffix (such as `swe-1-7`, which is a Max model), and `fusion-*` combinations.
|
|
||||||
|
|
||||||
The 30-entry cap means the file can never hold every family at three efforts. Propose additions by family — newest and most-used first — and say how many entries that leaves.
|
|
||||||
|
|
||||||
If `devin` is not on PATH or the command fails, say so with the error, and switch to **guided manual edits** for Devin: ask the maintainer which ids to add, remove or relabel, one at a time, and carry those into Step 5 as the proposed list.
|
|
||||||
|
|
||||||
### Step 4 — Discover Claude Code's models
|
|
||||||
|
|
||||||
Look up Claude Code's current model documentation — the model configuration page in the Claude Code docs. Locate it on each run (search the Claude Code docs for model configuration) rather than using a remembered URL; docs move. List the documented model aliases (for example `default`, `sonnet`, `opus`, `haiku`, `opusplan`) and what each one means, and name the page you used. Keep `default` as the file's first entry even though the docs call it a special value rather than an alias. Bracketed aliases such as `opus[1m]` are valid ids; propose them only when the maintainer wants them in the menu.
|
|
||||||
|
|
||||||
If the lookup fails or the page does not list aliases, say so, and switch to **guided manual edits** for Claude, exactly as in Step 3.
|
|
||||||
|
|
||||||
### Step 5 — Show the diff
|
|
||||||
|
|
||||||
For each CLI, compare the discovered list with the current one by `id` and show one table:
|
|
||||||
|
|
||||||
| Change | id | Current label | Proposed label | Source |
|
|
||||||
| --- | --- | --- | --- | --- |
|
|
||||||
| added | `new-id` | — | New label | `devin models list` |
|
|
||||||
| gone | `old-id` | Old label | — | not in `devin models list` |
|
|
||||||
| relabelled | `same-id` | Old label | New label | Claude Code docs: <page> |
|
|
||||||
|
|
||||||
- **added:** offered by the CLI, not in the file.
|
|
||||||
- **gone:** in the file, no longer offered.
|
|
||||||
- **relabelled:** same `id`, a better or changed label. Propose a label in the file's existing style.
|
|
||||||
|
|
||||||
Summarise unchanged entries as a count under the table ("19 Devin entries unchanged") instead of listing them. If approving every **added** Devin row would take the list past 30 entries, say so above the table and by how many. Call out any likely rename before approval (see the rename warning under Validation rules). If both tables are empty, say the file is current and stop.
|
|
||||||
|
|
||||||
### Step 6 — Approve each change
|
|
||||||
|
|
||||||
Ask about each row, one at a time: **yes**, **no**, or **edit the label** (they type the label to use). Write nothing until every row has an answer. A "no" leaves that entry exactly as it is today.
|
|
||||||
|
|
||||||
### Step 7 — Edit `models.json`
|
|
||||||
|
|
||||||
Apply only the approved rows:
|
|
||||||
|
|
||||||
- Keep `_note` verbatim.
|
|
||||||
- Keep the existing order. Remove a **gone** entry where it stands, change a **relabelled** label in place, and append each **added** entry at the end of its list.
|
|
||||||
- Write two-space-indented JSON with a trailing newline, matching the file's current formatting.
|
|
||||||
|
|
||||||
### Step 8 — Validate
|
|
||||||
|
|
||||||
Check the edited file against every rule under Validation rules. On a failure, show the rule and the entry that broke it, and go back to Step 6 for the affected rows. Do not run tests on a file that fails validation.
|
|
||||||
|
|
||||||
### Step 9 — Test
|
|
||||||
|
|
||||||
Run `npm test` from the repo root and report the result honestly: pass, or the failing suite and its output. Never describe a failing run as passing.
|
|
||||||
|
|
||||||
### Step 10 — Remind about the release
|
|
||||||
|
|
||||||
A launcher model change reaches people only with the next release. Remind the maintainer to add a `CHANGELOG.md` line and keep `CHANGELOG.md`, `version.json` and `package.json` on the same version — `/plan2code-changelog` does both.
|
|
||||||
|
|
||||||
### Step 11 — Suggest a commit
|
|
||||||
|
|
||||||
Suggest a one-line commit message that says what changed, and do not run it:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git add src/launcher/models.json
|
|
||||||
git commit -m "Refresh the launcher's model menu"
|
|
||||||
```
|
|
||||||
|
|
||||||
Give `add` and `commit` as two separate commands (Windows PowerShell 5.1 has no `&&`).
|
|
||||||
|
|
||||||
## Validation rules
|
|
||||||
|
|
||||||
Check every rule before `npm test` (Step 8). They mirror the shipped-file test in `scripts/test-launcher.mjs` ("the shipped models.json is curated Devin at low/medium/high only") plus the menu's own needs:
|
|
||||||
|
|
||||||
- The file is valid JSON.
|
|
||||||
- `_note` is present and unchanged from what Step 2 read.
|
|
||||||
- `claude` and `devin` are both non-empty arrays.
|
|
||||||
- `devin` has at most 30 entries.
|
|
||||||
- Every entry has a non-empty string `id` and a non-empty string `label`.
|
|
||||||
- Ids are unique within each list, and labels are unique within each list.
|
|
||||||
- No Devin id ends in `xhigh`, `max`, `fast` or `priority`.
|
|
||||||
|
|
||||||
**Warn on renames.** When an entry is **gone** and a near-identical id is **added** in the same list (a changed version number or suffix, say `glm-5-3-high` → `glm-5-4-high`), call the pair out before approval as a likely rename. People's own lists in `~/.plan2code/models.json` merge with the shipped one by id (`mergeModels()` in `src/launcher/plan2code.js`), so a renamed id can bring back a user's old copy of the entry beside the new one. Approve the pair knowingly, or keep the old id.
|
|
||||||
|
|
||||||
## Rules
|
|
||||||
|
|
||||||
- **Never commit and never push** — Step 11 suggests the commit; the maintainer runs it.
|
|
||||||
- **Touch only `src/launcher/models.json`**, plus `CHANGELOG.md` only if the maintainer asks for the release line.
|
|
||||||
- **Nothing is written before every row is answered** (Step 6).
|
|
||||||
- **Never install this skill** — never add it to `install.js`, and never copy it to `~/.claude/skills/` (the uninstaller deletes `plan2code-*` entries there).
|
|
||||||
@@ -1 +1 @@
|
|||||||
U0VOQwGovNAVPqFDBN7eYOJY9w4zdSme1IrzeoWpGr74/61wgcKXcBdLKhgz5v9A4iFBOH90m/q36/c3xcd/+gsiMk7U8iGD/O4kK/99yyoscIj2AvtuHV16jFqjWQGo5H0imPwjYeDJKh22S4+jL3bidIt6A2LVSNK3cevIoQl4T8Bg8ts5dkSlTbcP9ztChqSgxuGfZsETKK+eAhvgHZ+rIIkvdjMTM0oufKScatRRW/gaKHGYMdaw6fHyLr9u+lY/XJ9b1LwQnpAT6Yjj4lEOJ84h9o85RY6jLmubDHEUl6fuCMi9HD0PTzPC2s/Pni5ksX0Pw+WX3ZzfBqywuLvdEruH5DKSgktekRirr+9bSBVRdhV2YIeKZ+wsJjGG/LXSTySktAUYT9FCgO+wXX/knTzQy2zZZ07j/jcWPOeXdQ4yhhS60qHhVtvZixJG/i0Q07Vv+hSdfo8Uv4/nPyWctf2nrFEyYBHPQhLT4xWTbL86VSCnB+sCca+5xs0NkKWy6SJLp0LYDS483Bi+gIa/ZSDE8soFepIyoprNmOsNFOMjScpdZAb8Gv/7/Sc1giCS4SaIq4o8QWNxqxdxaE68IiDbKdpOcMv80s73scf8gFzIBoXL+Ta5UnhRBcOwZvNEOCEoFy18LpCwzZc3xmfhUoevaZaMsPcr/yao3tWe36zSlroaiM3A4d5Dx6qDFAlkaHllaYsGnCVlEXxVx9yMBbiFNpmy+MX5NqVT2xRYQ+FUcMhLykvFgud7HbTlFlIW4N8PEmpNWvcmG5FhOipmSUAxawmmVaEnqnsSG3ygLFgWIl3giIApGRxgH1OAUSFBxRmq5fpvYCyBrgT+I+pqKAHaOlTFCwPdaceYBqQey3kEBHe0mfbpJjxnoYpJm42Zi8ecPqkohQZ0VGPscePZ+IpoiliaNmiyIXk1AqlD7Gh9EEscuti9DHfpDbgUpCEsfeChMKjwAW8yFOia8JaaX0pfD/POZ6RU4vcM6BJppn9LLlb+7gU5hGsl8ZjT29UUcuBoU5EF6DxhOXdWmto3BYsOm+vD803xDmKKgk2x/VeHsfBezV9cusZdsja4hyd9nPMwH6qaGnkKdEkArp1mq6XNlQLw331tqEHRWiX/gWtQ31nJUhZEWgt5ewwezRQgZAE+gRjaNy9Eia/df8HEV9VNyNeUmbd3FkryB0fI/HgpIppVPt4ZIAB6KU2JSShBL5Iow3qYEvTkfYzyYZcMAsC9EQ4CpKf9m63UMPtw+NPkzvsFM+5052BiL1qmKdpCxecIeelkOOtXOKUFUg5EVqQIgZXrEHPtvERUrAFitrbowrD9ZdWiGRGAS3uZ/33l0fN/c5raZeZFdW1dZbmqAURsZdocBC0fsTQQnn/0OraSzrDJgBzyi2YAEN6+lTPoronbddrBKEOEify1XS8MXyuuJTadbyo+/4YqiyaWLglmyFsl9GHN0WMH5WFi6rjyE7+0IIKJ3i/x+rf081QiA/i+AYY9NKwtzITYJL+EHHr3+G8MzMmAnhhBkXH7yCTMAlpWLo0kX3X7z0+ne/THieIaAAYfnvsUHwolJFCfcl+OTVFhBrHblgqYu7QHuWd5Gc6iOL0LsBwnYUCritFSsAepEeFENOLkunWK7xaXtl/fIxvWGrLgjHxyok1u4iQi3HQdMeTxu29zJiLCIbAJHkNXc93/A4D+zOkZAeRKw5Wg5DVfvU4E4soiPs0j65u99E7rZhi7vsn4usTCD76Ya+nha9it6/xgnWe6h0Xh3wgGXFnJ48OlVf63k2Qyz601KqF7wPJJuYsoKt6HIwqeVWHwdsFIDyrhwcPOaJgfuS27Id0pGCtrHQ0x2zg8cbnvzdcwgy84tw7G8wQZxorqHfwYmmMJTcwi63p/OqF8iBtV38cMBplCOfIA3GMX3vHeh7N2oFbF3jg/aVI92DYsja24YqUOcMawFZlSVZxh3mmM1IHoub9E6Hf/1A5JoxeOjgRg7qFnam2oSSaQhYltx3hvj/USvuoftwm8ZPJuZGgaRdOBkTe8guCNo6Jan1jT1e/M/mnEsz3/wIrh1i2VQJ0exO0I8F+YNikm3JQBVyzdMxzYqA+IwH2YVU9G3kZitgBV3FMAOZcWEW8BTZUjtaac4Op7KrI9Y74CKEKrQbQR0R+mi5dm6aI0iiXz/0Upq+Bd28vuQljG5mygL0/ODObBj2imOsVn7z0Q4oGA3PLvh7haXEVo9Dr2+9Ishu0dsGp4K5seu5ujjhykYpN9PCTGUIYnMGImH38hluI5Y8rFlJJLYbU+DjGcOQpCmvuwGbOmexwZ/xkH9d+6+C+q1wv/hpsCZGzHiLoT0/WjB06mayDxOIBP5PZV4tzx2hFK+IuPaub/d0LcCHmw2BzcJ85WajYl9G9pKCkDWg5sDIdnqP4QNWVVxIV6N75/gGDmpT3oOEx8c3eUGMT0usz9mlgPBIPP8ZkTD69P2T9t8BLCUtM+sgGWZDBPxzRkdVjcLWHI/7r3DwsWW8eovZuBrjGorzNYR9QIYlEpAYQRZdiz2JQ0mXlT0Si/KexXT8SPMywa0eEp5DqWAzZcYo5g5OAsB7xriOzoRBXcwkXPxx1V9V9aHMguAAQ+yHQohVjquQhL+dWIzR95hC/7vIctKm9UfrTWn1xdYRl7n3UHAXERKxGdMR96i4pJbrWLRbRkSvJZZ1fxvGCf2MaQCLOgTD33pVpxJWc65QW62ugnF2R4UdJcFiC/Lk6d2rrrsYZKzwy5j6Sv647V+oHAASlpB6/9lVRUQpgqKLKIixFCeuq5R78qFA5iA7PkEwK2gXJGrBO+Mcs1EPHj6f9sXgiAjhjYCOTdyHi0+9VP326TULJqEL5AxqUThYBqsMz0/rQoE58IxSJ45M8863sKuFkWHXvqJ/HutFv/7GfFSec7KIr0Mr8g5dkrfzSso766KpmSKDXgJM5L/7/GkDHcZIccA4/xD+eOzel8cnKztecp1+NwiablsGCJy/nXMFrhlAkvXoHWyEuAS13TM4omGrBWxgLRFsqL3V1d6sRrQfd4fUIeIr+VIdOblPRbVGqECMhfZVf1olh++wQT8Iy7Gniekz9YMejGFJmopIk04lFLHdxg85bGP51wVcb1xVAWxkp55/4nPmMJ/XpP/2qYDVGIqnuT0GxF/KHk/Ts9Ddo9IDDlw5kAeIDNVGBOVUlYK802MU8b33y+BBX8WlEfFxYhgh7u7Tzckc/NivJuPknMYTAPCxD7UzsdS80ZtOcmuwBP10/4M6xzV8ZTnK8Pb7Wmp2lCnvhrOElGcztEeN6he9Bxb1JftVPQ1QYkEOce9WZB/pKwBwkktKrsyMO0svFpUdMWDXYoNyqc9R+/4Woum7FB2H+6p2sqODSYfZqjnirrBjUOD1YV19Q4+ccTfk7ofmLaNGP+K/cZaZn0EOMSKLPh6exbc/QreoJdGWmCwMNk9W0T83m+iZXb69whaxPJNPJfOroXDrnc46YDr5Kt7+tjZUS1TpzeDL5h+pj1TelC3kW3e//wtuDYnvJIBXrxbeoZUrz6On1UoQDqcymNSZUQwPNE7nWXNFSuvniQ1M7ScnuMyheJvb18rkTzJhkPRGvkCb6ash4f58bmm9otN5TQucKldyzxsicMt1AORUvvFRrrGNZVNjAbXwNm67z8oyVmvxyhXmBrEdpnEUH+h+6W9wc4v88b45eagxTb60aF6ROz/LZPhEBdOKSy1Njk/i+NZ/axD2aKCqD2T3BUiz+1P1abrYemivzWiUFEv2/Djuc9+q/Zwp8rJbMuFkrn04Zk5L4i+PwfjPTSYLxePEKdlEqV+KPqnkGTFbXIUxfeKUoC0RUV5XIugjeAeQQk1HufY1v8hrPNP1+MB78QBEW5bIrlfIZGLx0gZTjky6/k9PJBxKij9J3iIpr7Lk1Qellat/Jr7PZzkknNhvrIw+xCfx2hWEdn0yXZRnPB86GPIrwJdBDrmYBB9w0BClrchACJnHSW722P/b8CFtvUQY9/51a60q4Vgvfcq6QXoEty8XNpvUSFRJqjww44zuYbdgID4sb3MlgPr4WqdfDpL7z2vhGkOYYL+4LCI/U+TazHMXVw4wQ2YI3/EXLJgN0PDKTehMSP/QPVsv4F52T1A1sCAAT3JVv3FGtSBMZxhujOdMqbleFrEHF4f0dBhB0GbaONFv0L3CjweUW40KxpxGTUizeBFWWz7UW+B6GFfkuS8D8n7hY0/K7yDTNLI263v918fm/ER36cmBHPR1GWcMe+yo8o7paC4UBN7PSxhuYK3DFElrGNUY4tV9NK1FWfm85TPB+eAJn4UtNzzzdS4j6TgFwu4kkojqhktczKUYccLfDT+THij7ju4SPeoF5yMXmOwNtsgcxtN+hu5Iq/WiJzBWfuulyCoL8mkXk9D1JivLC2MxxzJA5qOhFu9NHgCw3nB7KIGm4lnsVkiXPQYwQD5/eKG6Kw3MbcNYkJ0ZWxYn/iR8D1OcNw7X5T5GTumT4VWHxyShVdbc1iEzAk6HZ7baKZH0qejB7f2JhdnpwHxTKGRFJ9irxnvAqpxq1ezxT/7yl/8GRmBEH/NFvW+FeOJwjl15Syi46NDK1XZb4m1Z0XJ5tTpJaIj15KtJ0cDJQKzcENSIbitFtd8MFmv+EPIXHeZe+/9Nmhd84pZLlEygLNbywYNLQXmg3xBG/WtF8geQN7kEQJZn0yTGSssZYw+g/6gHgTPAW9CoACZZgGZ512gyXrIAI8q3e+5dBS6rwJ0xeb6eoDqBqiJVlpOWqV4LDpFt0gDuGtwZJNFREsL5Bs+FuXo6FE41OUwD91dcRq7OFaGQ+0rZybRkBiQqcelNRX//BkwLZBfx9Ts+gPxQjS0/7ahpI1a1taOeyTequCFL+C4p0xumh3Iqg1ijyG0X7cWIbAuFt2By/jrM5tvZilA490yITU23wRnmtpcZui4MEeRq1oRUCYVyRD2N4fL0Ld55tAh6estfA+8qTzKI+Line truncated
|
U0VOQwErJ48kORFACZSnsphnJIwkZvzfvDDm32pRub1X968+xmjPhFzBYj4CZgfvy+A4aoKW4RgsV97CEx0Xa6YqvBybBT/M7RykZpBSDWrTtgLi5op0Hxk2eI5TDer52ID4z55AgOPrOW4fT0bSv0RMdP/fh7N5Q65TG5fduMeAxlqiPyVfYldmX9OqV6xDhSPsatfWaJQhJ3/i3xfVRHP7q4ChHQiUx5DnwnkV/WEPYw1KXcMzxLBQHrn/0POxfzQwVWpji9ref8ZbG//HmOCxWNA6Z087LVHIT7gyt9TcBD+Lq2VF3FjMGoR/40agNrbXXDMgpAKJrRk88+Q5q8IPJmQXG9txDZay9+bGIqM7xpuowg6OZbsXD4r/FHUiuOEtn1uBWTBKZ71UEprzo6Ips20Xa2SBBM6+poOVOlNDVhEdem652awNlzRdqoWAYEOtmSKdbnwUlhfFhewV0nfjgB2lMs8PA/oGSjevaO+5R9JAOSU2r+y1Nnfa3fRNvzuls+1FHo4y7FOeKKHpSbWGERYLnWxD4wnfzE1FW8jtglk06lzf7mrJFCS0ApjMAj6acHg2It7YDD4yOoC7Qe/bCSouyu5Zy32bdKAwGeg1H19WsT51bkRrV5N5vpW+PVFdUsb5vdsctNDwkYlJK46FJkvv07HokzDRSeJdfWznnvxwQyjpP04b5YCzcOeRQngH9w7DmjC4bpShtSGnnXrG/DTJMqWLHztvyPwiYKngqyZ181nuRoUZzpQvYeko6SH33HVpvp39xlHJCt4s4iIqVY6g52rzVWa6YSDnMqcB/zrX2OByNanoYtZE2wiioywxakZLQ8N+0trB1rXheF9RfWzlSYYB+gBzt/3r2Y3Jff3VjdaAxgM6c/JFOaAIquOHDA/L89VV9wQVXT9cdsJT0KNVFK0OWhToTzrdVm52YBSYO4aNTX0XCLk8aevaMVh6Dcz3pINK5k9Y7leVm3vHyreUVn0MvS89DX4kMbS8RyIvSZi8TJsIhpdaTTme4A8GuwzOTNdQ04+Bxe7nmrOIZYUjwPl/UXN8y3zoYBFttlY6ucr5Uwk22TZgbpFZw4ZU5+6HZd26hgaWzy006s/lXM4J5jGNKHJd8vSyVwewHHfpqstAekyc6laaXoOd9t0a1Y1hsgl8b69w6KFuX2MQnalZ1fjlz//XvClpUAEJ9KmSUwe6kpbcVUKgd0B00HBrLdjmAws8Est6zIGkETLdPd9dtUyDeYSljhAzv4TyV9Y5bFnazZUBvXZMDPok1HLxfSK3CNbnLc3NcSgRiPCytajIF1sLuPzZwsaW4hExejHIOQZGJmC/gq4M/ikLdeDWUo7rRTybbglpJm6bN3PIx6t/A/RbDsF81OaJ6F3Wlxen+uqRsRSyv0LJ5FvAzaqP68clpifrIlB7/h6O4364ugIAveDyV8U5J6SS9JPuqS4SbFiKYi5W4E5ARF4U9TQEhLHe25lh0In7bTRWgJnadh8R6+j2voLRk33qrhueOH7i5GMbyDEG8DbBuXkHs09zpo7HuZmx+yUhmKm2yMbs53w1IsZ99Li+wJaTdvUQDxzR1IpsRDjO1U3mD9Rdri3IE/v64ciSV2lrlL3ge94n/jivBORmXmyKRZQtfnvyBJspi7xBtuvqqIwc7mcIqCLZmML5KHKEYesz6EOzGlOC5p1VW1xaxxh7wEOgXD8UthCaO0/qg4jWTWQDOKhwVolYDCw3KsRT4l4QM2PRkakBsue2ZBSj1PGmX2QjvoXLj0orv9o0WwPvCpQHh5yIwfSNhha8EJm00OPBe+hBW8ttpp2vRBBmUEcuUg+bF5ZjWsmDSiUohwqgI5RsNtw5rgPZVo3Ys8glkoi9dzzlIdp/vMUj1rX4JlfRhijTNIia3WqVhtEvycTOanHdj57YSDhRlyHARxVGmU+eANVj+8D+jJJYWu2UnhnzCsw4awkqP8jH4LRVJdqe2WKDaX361KwuvUWGcNa7dm7NhNAep+QDoRVgmkKjP1IU99xpkko+e+zcU18lnJtIZ5C2gUHm+ma17uT5/JisFuTtp9Lj5dnzcoCj2bC/5wZMmDvFoBr7C8cedeY5YmFs7lAUNEzAVweiYyQA80tf6lh58rA0X+NHKAH7kHw5BxqBSJAH1ewa/S0qZV2UrX6ASoAbahHhf0R5B+qk7yx4qXx3/wH4DKssj5OMvcRvjj1CmeVY/ErE/6UsYlhkHH5J4O3wfbo5Z1AbMD4JJ2H41KxoUn6VEA080xcXGWdOcJkfN2uVTFoVaBgxyl2ZhaZmnS94ig5Yf8TVhK2ligb0S1XezmKgqldNF68cPNad1uyP7fnbBbmW81SJWbklMkshhjCJvFt6H8l4VhsQh/wmS8nMmqDsK+d6OcHb4JoUgE1T+g03QmAY4kWFnKPKnXcanxDCGQNy/IpgMez+C3NN87pKBjcejTI63ld8xtrgORLeWTA+EBtwIUIbnDpCaR0uRo37L3azuAUyFpjksNqCK4IikJd1jmfNOz7x7uWADcRyoxlVNytHT+7SbEgNKybMDTKzByUHe7zraVii7Wh0d4cNNsLMoYut+a4riq8ivQsYMf1Mdt0Yo3CtC/AFS/+iW7s6LGYi6XGnZz2JDySxRDcqNvE4rl4QyyA5X4a8RmnDn5wx/mFUOZA7M1t6L1sfc4bcuZ0yFiV03VSzoguM9YeJIxvog889oXbH4ayuJo6NfkX3z9TJ+SQKrRqXPOPN9CuEvDB469nZtldoj0apg3LWtto08k2Y5PZghO3PWx2D370cukIYadw21CJmmDgSc44cr9RK7VnqVGhvPjlSx21sj+TjaFdWh7AqCStxt0PnCXCHKs6J4xaY8kVUG5rsq8gjn/3HnlRzeb0eAh5QF937xbXmo91g0EpGgoAM9mfheXY7EkaNXa26lJ6qXsuBCehlB7QL66ayzme7DHP1vYB4gCX0IMwUanfUIP0XKLC/SZvfmCNBuHxZZLerlVJdDlmOavmURYlMViy0HUY4m8ES/ACncMWkPsdmv/ZRo6v/q/4l+Y4zE2yEZ3DOlddHcTPNvFhFIQnIdQihrGY35fTGrILmQqlqM4QbAKiPT9oJsGqXuURyBdxQeJuJmT4V4b28mAbr0Nn+sKcfeVNd4wJ7VK4SGrdYG4KOFLmpKEI5i89OGApwxJqti1wrveyJLxF2P8XDVBA5US0vLz5WemKGDNM2NJOnvomOW30YN9CjmgM/qak9AZDZQ4x/uciOYuvPLMAzCjsMPjgUueVIcZw9eJUMIcFOwEthAeMZJ60pJT7bO34S65RvRL5co7CUzhvNlT3CFcC4VVyxKInhNt1B9IFnzI+sYZuhHW4OQnUG8atoL42J0MX39MeNEf/sAVOt1N8fC3RbylftLO9XuKGEqo+WD6755p3dC5kRy2AMZG1zMmmk8baeMSHPyM7v6lf1nXYQvFAy7IFHAg9/qTAp992IgHImsggX6ZdSQmxZpc4OhtZ14oGy+zgy7Fffi9Iidnc2O9qEBHxDiRRgkcgOs0Dg9bZWCrseaqruSKcYs/xgHt5wpLF+68RSDQ3LRau3guGQ+oQCcLKupF/4yeXFCSyd5Wd5Zcq6o/KdFfQqh4wnYsLnguDxi/qsUTxG9rUPDW94IC1w1zwImlLLqqmCYs1TRmkC7d8gRDJsRrhlK+2OAzNhRm5yL8RIBHyLJVZz69e488FQPxoHFnJG1H3sI3m3Sdt3Xq8H5xQ85UiNNQDyu3nteVzNH8Ri44x+4TVtZDrtTrwUUvW9r1eRywhGRj+pBcpxSD0VxzkMby2Z2z9cN5Ryg+SA9VW2IdFhEmQRW4ryrU2tTDlsd/EMPuoHx0sEOwyS7L/S5+ai1ZjOa3Ooi1R8Yzg97DBrVTYwSWKrNky2SRILVNiT9PYaNpreB+sWGQGk2Ji/UX13Zk2R9VSi5YBQhm5ELG4hXeHJPIU45yRg1ASi6BekyFN2GZe7QvslCzhJXZpgpxIBPVehnv6KDrk0iUu6LVI8lPaq7VbIt1vwn7xt2YS/P231EhtA5yvLFyfr1Y/Gf5NxFQhn8RSdFzTgt/pYsg5lqllS4MjeTQFziSdP5AeY3xYjmAvjqoWZ1DLAhLEO7wOMihk6rEA7+BRvSroZ3iBZp+sphk4ysi0QdTu4Jkf0L7YWkCCJksEGWCFrYFkqHSXIYKleN6bSW4K3adWo9F1V1UdoE960ghAxDMLtHPuDnKpsB3T5fgOJSxrGNUfylEgi9ya7pY/iEkhWbylCHA64N2ldWLLG0xjMw7HFUqKfLfvIKUniRWgqTue50WZYcwOqvrnvHiYxDHXPH23thAjzio/7dWuJ/j5sgSXlxhVHcZyozxIPUAw7Qsb3aUFaQqxQWxSkkkDiT1nfm3bT0IVDCr4VwYXsLqiF+TjkQlGfNqJPkjqWTut4ZA8YhSPpSUmLJcOrJPEnzCekZXmWlutT9CaFc9GEokr2HGHy6lhRg2OZRSlYcBRo3Ai6OK3nTM09O9r7zyHJR91baG/kzuK3XqXH87HXe5q+svysGL67nRb+qN+uddzPhRCkPhjT45ZeWGDX9idY+t4jMOFmP176XjMphJRPjUbCaqaN3FAGaHtM7AvFlWMvuJjaRQ7rM4hDhroCkwD5gMJ3GSzCA9FbHaPb68y8qqaVJlO+ZEHjaPluNIVcJmw19y2lFpuJXWWyc9RvFjgwVqC+XUm1M/iSUkieOnLkpgl825md9u7+fUhCVczrOrx2sjSu5t3VLG7meD7CkUa/37wbRFbX2l9kBdFOvIlBDvpuG+/ViOhsQnscux3eduWzFXT9ojWqy33ORMHzHjYJMGuCVQUckN6no1gRB3IEcAYIVcR3JhGwLOi5WMVncCBeeASRF7VfF27ib2mC9x1FvQLRDwN/9bsLoMmHajXjdiOwvaTybBQQSKy47kN3nlnIz5384VzGhdGLVPsZK4OFYXtC1vA4qBIykSWv9XQ0rltkEHLcWVbLine truncated
|
||||||
+2
-2
@@ -4,8 +4,8 @@
|
|||||||
# Git stores LF, and every text file is checked out as LF on all platforms.
|
# Git stores LF, and every text file is checked out as LF on all platforms.
|
||||||
# This is not cosmetic: scripts/validate-char-count.js measures the characters
|
# This is not cosmetic: scripts/validate-char-count.js measures the characters
|
||||||
# actually on disk, so a CRLF checkout adds ~1 character per line. The workflow
|
# actually on disk, so a CRLF checkout adds ~1 character per line. The workflow
|
||||||
# prompts in src/plan2code-*.md are counted against a 20,000 character budget,
|
# prompts in src/plan2code-*.md run close to their 11,500 character budget
|
||||||
# and a CRLF working tree inflates that count, turning
|
# (several sit above 10,800), and a CRLF working tree pushes them over — turning
|
||||||
# `npm test` into a check that passes or fails depending on how the repo was
|
# `npm test` into a check that passes or fails depending on how the repo was
|
||||||
# cloned. Pinning eol=lf makes the count reproducible everywhere.
|
# cloned. Pinning eol=lf makes the count reproducible everywhere.
|
||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ background processes.** Optional, and unrelated to the workflow itself.
|
|||||||
On Pro / Max / Teams accounts, where rate limits are available:
|
On Pro / Max / Teams accounts, where rate limits are available:
|
||||||
|
|
||||||
```
|
```
|
||||||
╭───╮ Opus 5 / high │ plan2code │ feature/pathfinder-github-iss │ +12 -3
|
╭───╮ Opus 5 / high │ plan2code │ feature/PCWEB-11702-pathfinder │ +12 -3
|
||||||
│ ★ │ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
|
│ ★ │ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
|
||||||
╰┬─┬╯ 3h 5m ($4.62) │ ▰▰▰▰▰▱▱▱▱▱▱▱ 42% (84K) │ 5h: 28% · 7d: 61%
|
╰┬─┬╯ 3h 5m ($4.62) │ ▰▰▰▰▰▱▱▱▱▱▱▱ 42% (84K) │ 5h: 28% · 7d: 61%
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ These are verified, not assumed. They shape everything below.
|
|||||||
|
|
||||||
### 2.1 The character limit is the binding constraint
|
### 2.1 The character limit is the binding constraint
|
||||||
|
|
||||||
`scripts/validate-char-count.js` caps every flat `src/plan2code-*.md` at 20,000 characters since 2.4.1 (11,000 when the numbers below were measured), enforced by a husky pre-commit hook. Measured today:
|
`scripts/validate-char-count.js` caps every flat `src/plan2code-*.md` at 11,500 characters (11,000 when the numbers below were measured), enforced by a husky pre-commit hook. Measured today:
|
||||||
|
|
||||||
```
|
```
|
||||||
10995 5 plan2code-0-pathfinder.md <- 5 characters of headroom
|
10995 5 plan2code-0-pathfinder.md <- 5 characters of headroom
|
||||||
|
|||||||
+4
-74
@@ -153,7 +153,7 @@ it opens on the page without asking.
|
|||||||
states differ by pattern, not only color). A finished session goes back to
|
states differ by pattern, not only color). A finished session goes back to
|
||||||
the plain icon, so a console left in a background tab can be checked at a
|
the plain icon, so a console left in a background tab can be checked at a
|
||||||
glance.
|
glance.
|
||||||
- **Help.** The **?** at the top right opens a Help dialog with 17 topics,
|
- **Help.** The **?** at the top right opens a Help dialog with 16 topics,
|
||||||
one per tab down the left (across the top on a narrow window), opening on
|
one per tab down the left (across the top on a narrow window), opening on
|
||||||
the one for where you are. It is part of the page itself, so it still reads
|
the one for where you are. It is part of the page itself, so it still reads
|
||||||
fully when the page has lost its program.
|
fully when the page has lost its program.
|
||||||
@@ -324,47 +324,8 @@ context for this console session.
|
|||||||
Code with a copyable `/add-dir <path>` to run); *Inside another folder in
|
Code with a copyable `/add-dir <path>` to run); *Inside another folder in
|
||||||
the list* for a nested one.
|
the list* for a nested one.
|
||||||
|
|
||||||
The workspace carries across skills you start from the dashboard and back, and
|
The workspace carries across skills you start from the dashboard and back. A
|
||||||
it is remembered for next time:
|
new console session starts with just the folder you started in.
|
||||||
|
|
||||||
- **Saved on every change**, in `~/.plan2code/console/workspaces.json` (beside
|
|
||||||
`looks.json`, never in the project, since the paths are your machine's),
|
|
||||||
keyed by the folder you started in.
|
|
||||||
- **One list per spec.** *Start from scratch* on the dashboard shows the
|
|
||||||
project's list. Picking a spec loads its own; the first time, it starts as a
|
|
||||||
copy of the project's, and after that the two are separate. A spec created
|
|
||||||
mid-run (Pathfinder, Plan) takes the list in force with it. The line under
|
|
||||||
the dialog's title says whose list it is.
|
|
||||||
- **Forgotten on archive.** Finalize's Spec Cleanup step says it will forget
|
|
||||||
the spec's list and runs `console.mjs forget --spec specs/<name>` after the
|
|
||||||
move.
|
|
||||||
|
|
||||||
### Subagents
|
|
||||||
|
|
||||||
On a build (Implement, Implement + review, Quick task), a review and
|
|
||||||
Pathfinder, the agent can hand independent pieces of work to helpers
|
|
||||||
(subagents) while it keeps the conversation with you.
|
|
||||||
|
|
||||||
- **The button.** An icon in the top bar, after Stop session (and Write a
|
|
||||||
brief on Pathfinder): one larger node linked to three smaller ones, lit in
|
|
||||||
your highlight color while helpers are on. It shows only on those skills,
|
|
||||||
and only when the skill's copy of the console can pass the setting on.
|
|
||||||
- **The dialog.** A click opens it; the button never switches anything by
|
|
||||||
itself. **Use helpers** or **Work alone**, the instruction the agent follows
|
|
||||||
(**Reset to default** puts the shipped one back), and how many helpers may
|
|
||||||
run at once (1 to 20; your agent's own limit still applies). **Save** sends
|
|
||||||
it; the agent hears of it at its next check-in, as a setting, not as
|
|
||||||
something you typed.
|
|
||||||
- **Saved per project and per skill**, off by default, in
|
|
||||||
`~/.plan2code/console/subagents.json`. The next session of the same skill
|
|
||||||
in the same folder starts the same way.
|
|
||||||
- **The Subagents tab.** With the first helper the agent reports, a tab
|
|
||||||
appears before Ask: one row per helper with what it was asked and whether it
|
|
||||||
is running, done or failed, plus a one-line result at the end. Rows change at
|
|
||||||
the agent's check-ins, not live. *Working alone* means your agent has no way
|
|
||||||
to start helpers here. The tab clears when you go back to the dashboard.
|
|
||||||
- **Pathfinder's research** always uses helpers, whatever the switch says, and
|
|
||||||
they show in the tab too.
|
|
||||||
|
|
||||||
### Session meter
|
### Session meter
|
||||||
|
|
||||||
@@ -379,10 +340,6 @@ Review, Init and Init update 2; Revise plan, Quick task and Finalize 1; a
|
|||||||
Pathfinder map 2 and each question its research subagents settle 1; a built phase by its size,
|
Pathfinder map 2 and each question its research subagents settle 1; a built phase by its size,
|
||||||
one point per 3 tasks it completed (rounded up), plus 1 for Implement + Review
|
one point per 3 tasks it completed (rounded up), plus 1 for Implement + Review
|
||||||
(a flat 2, or 3, if the agent did not report a task count); Handoff and the dashboard 0.
|
(a flat 2, or 3, if the agent did not report a task count); Handoff and the dashboard 0.
|
||||||
A build counts while it runs: each task the progress bar ticks off adds to the
|
|
||||||
build's row (*Implement + Review: 9 tasks built so far*), Implement + Review's
|
|
||||||
review stage adds its 1 as it starts, and the approved phase takes the row over
|
|
||||||
with its final score, so the meter never waits for the sign-off to catch up.
|
|
||||||
On top of that, every 2 questions you answer on the page add 1 point to the
|
On top of that, every 2 questions you answer on the page add 1 point to the
|
||||||
skill run you answered them in (`ANSWERS_PER_POINT`), so a long Pathfinder or a
|
skill run you answered them in (`ANSWERS_PER_POINT`), so a long Pathfinder or a
|
||||||
Plan with many clarifying questions weighs more than a short one. A review run on the
|
Plan with many clarifying questions weighs more than a short one. A review run on the
|
||||||
@@ -550,19 +507,6 @@ send never holds up a question.
|
|||||||
A reply that lands while you are on another tab puts a dot on **Ask** and
|
A reply that lands while you are on another tab puts a dot on **Ask** and
|
||||||
chimes once (if sounds are on).
|
chimes once (if sounds are on).
|
||||||
|
|
||||||
### When an update is out
|
|
||||||
|
|
||||||
When a newer Plan2Code release is out, the dashboard shows an **UPDATE
|
|
||||||
AVAILABLE** banner at the top. Click it for the details: the version you
|
|
||||||
have, the new one (linked to its Releases page) and the exact command that
|
|
||||||
updates you, with a Copy button. **×** hides the banner for this session; the
|
|
||||||
next dashboard shows it again until you update.
|
|
||||||
|
|
||||||
The check uses your own git login to read the repo's release tags, once an
|
|
||||||
hour at most. If git cannot reach the repo (no git, no access, offline), you
|
|
||||||
simply see no banner, and nothing waits on it. The version in Help always
|
|
||||||
links to the Releases page.
|
|
||||||
|
|
||||||
### Keyboard
|
### Keyboard
|
||||||
|
|
||||||
| Key | Does |
|
| Key | Does |
|
||||||
@@ -578,7 +522,7 @@ keyboard-only navigation work.
|
|||||||
|
|
||||||
## Models in User Preferences
|
## Models in User Preferences
|
||||||
|
|
||||||
The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. **User Preferences → Models** (Claude and Devin tabs) lets you add a model that came out before Plan2Code was updated; additions are kept in `~/.plan2code/models.json`, and **Reset to default** removes them. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused. Maintainers refresh the curated list with the repo-local `/plan2code-model-update` skill, which shows a diff and changes only what they approve.
|
The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. **User Preferences → Models** (Claude and Devin tabs) lets you add a model that came out before Plan2Code was updated; additions are kept in `~/.plan2code/models.json`, and **Reset to default** removes them. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -648,8 +592,6 @@ exception being the note attachments the agent keeps for a spec, above):
|
|||||||
| `~/.plan2code/console/sessions/<id>/workspace.json`, `ledger.ndjson`, `workspace-cursor.json` | the workspace's folders (paths, names, descriptions — never their contents), the session meter's events, and how far the agent has been told of workspace changes. Kept beside the session, so they outlive every dashboard hop | with the session |
|
| `~/.plan2code/console/sessions/<id>/workspace.json`, `ledger.ndjson`, `workspace-cursor.json` | the workspace's folders (paths, names, descriptions — never their contents), the session meter's events, and how far the agent has been told of workspace changes. Kept beside the session, so they outlive every dashboard hop | with the session |
|
||||||
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
|
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
|
||||||
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width | always |
|
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width | always |
|
||||||
| `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always |
|
|
||||||
| `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session |
|
|
||||||
| your system temp directory | the port, process id and session token | until reboot |
|
| your system temp directory | the port, process id and session token | until reboot |
|
||||||
|
|
||||||
Each of the workspace and meter files has exactly one writer: the server owns
|
Each of the workspace and meter files has exactly one writer: the server owns
|
||||||
@@ -671,17 +613,6 @@ Your `looks.json` and the `console-dir` pointer are never touched, and neither
|
|||||||
is the session being opened. Nothing of value goes with them: the page is
|
is the session being opened. Nothing of value goes with them: the page is
|
||||||
never the record, `specs/` in your project is.
|
never the record, `specs/` in your project is.
|
||||||
|
|
||||||
**Or clean up on demand.** *User Preferences → Cleanup* → **Find files to
|
|
||||||
clean up** lists, with sizes, everything in `~/.plan2code/` that is not
|
|
||||||
needed: sessions untouched for 30 days (never the one you are in), anything at
|
|
||||||
the top of `~/.plan2code/console/` other than `sessions/`, `looks.json`,
|
|
||||||
`workspaces.json`, `subagents.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` other than
|
|
||||||
`console/`, `bin/`, `launcher.json` and `models.json`. A stray is listed once
|
|
||||||
it has sat untouched for an hour, so a lock or temp file another session is
|
|
||||||
writing right now is never caught. **Delete these** removes
|
|
||||||
that list and nothing else. A console running from another home
|
|
||||||
(`PLAN2CODE_CONSOLE_HOME`) only ever looks inside that home.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Security
|
## Security
|
||||||
@@ -730,7 +661,6 @@ origin.
|
|||||||
| `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. |
|
| `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. |
|
||||||
| `POST /workspace/remove` | `{ id }`. 400 `original` for the folder the session started in, 404 `unknown`. |
|
| `POST /workspace/remove` | `{ id }`. 400 `original` for the folder the session started in, 404 `unknown`. |
|
||||||
| `POST /workspace/browse` | Opens the system folder picker and answers `{ path }` or `{ cancelled: true }`; never adds anything itself. 409 `busy` while one is open, 404 `no-picker` when the session looks remote or no picker exists. |
|
| `POST /workspace/browse` | Opens the system folder picker and answers `{ path }` or `{ cancelled: true }`; never adds anything itself. 409 `busy` while one is open, 404 `no-picker` when the session looks remote or no picker exists. |
|
||||||
| `POST /subagents` | `{ on, instruction, max }` (`instruction: null` for the shipped default). Saves the switch for this project and skill and answers `{ ok, setting }`; 400 `not-offered` on a skill without the switch, `bad`, `too-long` (over 2,000 characters) or `max` (outside 1 to 20). |
|
|
||||||
|
|
||||||
## For maintainers
|
## For maintainers
|
||||||
|
|
||||||
|
|||||||
@@ -40,16 +40,10 @@ Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line
|
|||||||
|
|
||||||
## Web Console
|
## Web Console
|
||||||
|
|
||||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a built-in 17-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) a **Subagents** button in the top bar turns helpers on or off per project and skill (off by default, saved in `~/.plan2code/console/subagents.json`); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console.md` → Standing instructions). The agent-facing contract is `console.md` / `building.md`; the server never writes into a project.
|
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders, a session meter, a built-in 16-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. The agent-facing contract is `console.md` / `building.md`; the server never writes into a project.
|
||||||
|
|
||||||
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
|
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
|
||||||
|
|
||||||
## Skill Scripts
|
|
||||||
|
|
||||||
Deterministic workflow steps run as Node scripts shipped in each skill's `scripts/` (shared ones in `src/skill-scripts/`, a skill's own in `src/<skill>-scripts/`, listed per skill in `SOURCE_PROMPTS` → `scripts`). Prose keeps the judgment. JSON on stdout, documented exit codes, tests run against the built `skills/` tree.
|
|
||||||
|
|
||||||
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Skill Scripts section)
|
|
||||||
|
|
||||||
## Development Commands
|
## Development Commands
|
||||||
|
|
||||||
Build commands, installer menu options, non-interactive skill-build verification, skills CLI delegation, skill format, and how to edit workflow prompts.
|
Build commands, installer menu options, non-interactive skill-build verification, skills CLI delegation, skill format, and how to edit workflow prompts.
|
||||||
@@ -92,4 +86,3 @@ When you make a mistake, get corrected, or discover something about this codebas
|
|||||||
- Sync upstream only through `/sync-repo`, and verify its baseline against the real tree before porting: an earlier sync silently skipped a whole upstream release (the `3-implement-review` skill) while the recorded version froze. Update the baseline with `.claude/skills/sync-repo/set-synced.mjs`, never with a shell pipe over the decrypted body.
|
- Sync upstream only through `/sync-repo`, and verify its baseline against the real tree before porting: an earlier sync silently skipped a whole upstream release (the `3-implement-review` skill) while the recorded version froze. Update the baseline with `.claude/skills/sync-repo/set-synced.mjs`, never with a shell pipe over the decrypted body.
|
||||||
- After a sync merge, run `npm test` before trusting a "clean" file: when upstream and plan2code fixed the same bug, `git merge-file` keeps both copies without a conflict (a sync once left `let pattern` declared twice in `app.js`, caught only by `parse-check`).
|
- After a sync merge, run `npm test` before trusting a "clean" file: when upstream and plan2code fixed the same bug, `git merge-file` keeps both copies without a conflict (a sync once left `let pattern` declared twice in `app.js`, caught only by `parse-check`).
|
||||||
- When extracting upstream files in Git Bash, run `git show <ref>:<path>` with `MSYS_NO_PATHCONV=1` and `C:/` style paths (never `/c/`): path conversion rewrites `origin/main:.readme/x.md` into `origin\main;.readme\x.md`, the show fails, and the merge silently runs against an empty "theirs". Check every extracted file is non-empty before merging.
|
- When extracting upstream files in Git Bash, run `git show <ref>:<path>` with `MSYS_NO_PATHCONV=1` and `C:/` style paths (never `/c/`): path conversion rewrites `origin/main:.readme/x.md` into `origin\main;.readme\x.md`, the show fails, and the merge silently runs against an empty "theirs". Check every extracted file is non-empty before merging.
|
||||||
- After a sync, grep the result for the upstream owner slug and company name in any case (the `/sync-repo` body lists them): the rebrand map only rewrites URLs, so a bare owner slug once slipped through into `feedback-payload.mjs` (and its test) until it was fixed by hand to `jparkerweb/plan2code`. No upstream name may appear in plain text anywhere in this repo.
|
|
||||||
@@ -2,56 +2,6 @@
|
|||||||
|
|
||||||
All notable changes to Plan2Code will be documented in this file.
|
All notable changes to Plan2Code will be documented in this file.
|
||||||
|
|
||||||
## v2.5.0
|
|
||||||
|
|
||||||
### ✨ Added
|
|
||||||
|
|
||||||
- **web-console**: a **Subagents** switch for the skills that can hand work to helpers (Implement, Implement + review, Quick task, Review, Pathfinder). An icon button after Write a brief, lit while helpers are on, opens a **Subagents** dialog: **Use helpers** or **Work alone**, an editable instruction with **Reset to default**, and an advisory "at most N at once" (1 to 20). It is off by default and saved per project folder and skill in `~/.plan2code/console/subagents.json` (`POST /subagents`, on Cleanup's keep-list). The button shows only when the skill opts in (`public/subagents.js`) and the agent's console copy reported support (`caps: ["subagents"]` on its `open` event), so an older skill copy never shows a switch it cannot serve.
|
|
||||||
- **web-console**: the switch reaches the agent as a standing instruction, and only when it changes. `wait` exit 0, `chat` and `open` carry a `subagents` field and `Subagents: on (revision N)` lines last in `reply`. A higher revision replaces a lower one, "off" goes only to an agent that was told "on", and a resume or dashboard launch with the switch on states it once. The per-session cursor moves only after the print, so a killed `wait` repeats a change rather than losing it. Contract: `console.md` → Standing instructions; `building.md` points at it.
|
|
||||||
- **web-console**: a **Subagents** tab before Ask, from the first helper the agent reports through `post` (`helpers: [{ id, title, ask, state, result? }]`, merged by `id`, or one `{ id: "alone", alone: true }` entry when it has no way to start helpers). One row per helper with its ask, a Running / Done / Failed pill and a one-line result. It clears on a dashboard hop, and helper reports add no session meter points. `validate()` refuses malformed entries with exit 3 (house rule 8). Help gains a 17th topic, **Helpers (subagents)**.
|
|
||||||
|
|
||||||
### 🔧 Changed
|
|
||||||
|
|
||||||
- **review**: run on its own with nothing named (no argument, no conversation work, not from a build's review button), `plan2code-review` no longer assumes the branch diff. It does a quick scan (branch changes, uncommitted changes, specs) and asks what to review, each option with its size; on the web console that is the first scope question, a `choice`. A build's review keeps its already-decided scope.
|
|
||||||
- **web-console**: `post` and `open --file` refuse a patch that sends a doc a lower `version` than the page already holds (exit 3, naming the doc and both versions; house rule 9). A version going back is almost always a stale or copied payload, which the page would otherwise show quietly under the new run's name. `building.md` now says a later phase in the same session continues `phase`, `phasefile`, `report` and `review` from the version the page holds instead of restarting at 1.
|
|
||||||
- **web-console**: the project name in the footer's `<project> · <branch>` label now shows in your highlight color, and the browser tab title starts with it (`<project> · <title> · #<sid> · Plan2Code`), so consoles for different projects are easy to tell apart.
|
|
||||||
|
|
||||||
## v2.4.2
|
|
||||||
|
|
||||||
### ✨ Added
|
|
||||||
|
|
||||||
- **web-console**: the Questions and Ask tabs show a small spinner left of their name while Plan2Code is on it. Questions (Dashboard on the dashboard) spins from Send until the answers are picked up, the same wait as *Sent. Waiting for Plan2Code.*; Ask spins while a question the agent picked up has no answer yet, exactly when the conversation's own ring does. Neither turns once the agent goes quiet or offline, so a dead session never reads as a slow one.
|
|
||||||
- **web-console**: **User Preferences → Cleanup**, above Models. **Find files to clean up** lists, with sizes, what `~/.plan2code` does not need: sessions untouched for 30 days (never the one serving the page), anything at the top of `~/.plan2code/console/` but `sessions/`, `looks.json`, `workspaces.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` but `console/`, `bin/`, `launcher.json` and `models.json`. A stray is listed only after an hour untouched (`STRAY_GRACE_MS`), so a held lock or a temp file mid-rename never is. **Delete these** removes exactly that list and reports what went and the space freed. The server builds the list (`POST /cleanup`, `cleanupFindings()` in `lib.mjs`), sends no paths to the page, and on delete re-scans and removes only ids still found (`removeCleanup()`), unlinking symlinks without following them. A console running from `PLAN2CODE_CONSOLE_HOME` never looks outside that home. Help's User Preferences topic describes it.
|
|
||||||
- **web-console**: the dashboard shows an **UPDATE AVAILABLE · v<latest>** banner when a newer release is out. The console server finds the newest `vX.Y.Z` tag with `git ls-remote --tags` when it starts (no shell, prompts off, a 10 s limit, never waited on), caches the answer for an hour in `~/.plan2code/console/update-check.json`, and adds `update` to the state frame only when that release is newer. The banner opens a dialog with both versions, a Releases link and the update command with Copy; × hides it for that session. `GET /version` also returns `latest`, and the version in Help links to the Releases page.
|
|
||||||
- **launcher**: `plan2code` opens with a colored Planny banner and a plain-English intro, then the agent menu with cyan numbers, a `(last used)` marker on the remembered pick and a green default. With one CLI installed, or a `--cli` pick, it prints `Opening with <CLI>…` instead. The model menu, the folder prompt and every `plan2code:` error get the same styling. Color is used only on a terminal with `NO_COLOR` unset, so piped runs print plain text and no banner.
|
|
||||||
- **maintainer**: a repo-local `/plan2code-model-update` skill (`.claude/skills/`, never installed) refreshes `src/launcher/models.json` from `devin models list` and Claude Code's documented model aliases. It shows a diff, applies only the changes the maintainer approves, checks the file against the launcher's rules, runs `npm test` and never commits.
|
|
||||||
- **tests**: `scripts/test-web-console.mjs` covers Cleanup, the update check and the note thread; `scripts/test-launcher.mjs` covers the banner and color handling.
|
|
||||||
|
|
||||||
### 🔧 Changed
|
|
||||||
|
|
||||||
- **document**: `overview.md` puts the Phase Checklist and Parallel Execution Groups directly under the Summary, ahead of the Tech Stack, Architecture, Risks and Success Criteria, so the phases are found without scrolling. Every script finds these sections by heading, so specs written in the old order keep working.
|
|
||||||
- **web-console**: while a build runs, the waiting screen's pointer to the tasks list is now clickable. **Task** and the tab's own name (say **Phase 6 tasks**) show bold in the highlight color, and either one opens that phase's tasks tab.
|
|
||||||
- **web-console**: the session meter counts a build while it runs instead of only once the phase is approved. `console.mjs` writes a `progress` ledger entry whenever an Implement or Implement + Review post raises `headline.cleared`, and the build's row (*Implement + Review: 9 tasks built so far*) scores one point per 3 tasks done. The phase's final `run` takes that row over in place, so nothing counts twice and the meter never drops. A second phase in the same run starts its own count once its headline is back at `cleared: 0`.
|
|
||||||
- **web-console**: the **UPDATE AVAILABLE** banner and **Send to Plan2Code** (while enabled) carry a soft glow in the picked highlight color; with reduced motion Send's pulse stops and the glow stays.
|
|
||||||
- **web-console**: a request body over the size cap now gets `413 too large` from every JSON route instead of a connection reset or a `400`.
|
|
||||||
|
|
||||||
### 🐛 Fixed
|
|
||||||
|
|
||||||
- **web-console**: Implement + Review's built-in review no longer scores twice on the session meter. Its `review` run now scores the phase's 1-point review bonus as the review starts (not a standalone Review's 2), and the phase's final `run` leaves that point out. A 17-task phase now ends at 7 points, not 9. The breakdown also stops repeating the unit in "Code review run: review".
|
|
||||||
- **web-console**: Send no longer stays disabled when an agent posts a question mid-build while still marked `working` (seen on Implement + Review, where the question said "I'm carrying on while you decide"). Once an open question has an answer or a note staged, Send unlocks at once with "Still working · it reads this next", instead of waiting out the agent's `quietMinutes` (up to an hour); the server holds the send until the agent next looks. `building.md` now says a question stops the build: set `waiting` in the same post as the question and wait, never keep working with a question open.
|
|
||||||
- **web-console**: **Notes on this** showed the agent's replies as empty "Plan2Code" bubbles and dropped the person's own notes once they were picked up. The server now writes every note into the item's `thread` as it arrives, `post` lifts `from` / `role` and `md` / `body` / `content` into `{ who, text }` (and drops an echoed copy of the person's note), and an entry with no text is rejected with exit 3. Older `{ from, md }` entries still render. `console.md` gains a **Replying to a note** section.
|
|
||||||
- **web-console**: dropped the `comments` list on docs, which `post` appended and time-stamped but nothing ever displayed.
|
|
||||||
- **web-console**: a dashboard launch could strand the hand-off when the agent called a skill-invocation tool on the picked skill instead of reading its `SKILL.md` (every skill below the dashboard ships `disable-model-invocation: true`). `plan2code.md` and `console.md` now say to open the next skill's file with a file-read tool.
|
|
||||||
- **web-console**: the waiting pane pointed Document and other skills with no task list at a tasks tab that never exists there. The pointer now appears only when a build's `phase` or a quick task's `tasks` tab is posted. The nav tab spinner also gets its 7px gap back from the tab's name.
|
|
||||||
- **web-console**: skipping a question dropped a note already typed for it; the note now goes with the skip as `skip; <note>`. Ticking a checklist step after a skip now ends the skip instead of still sending `skip`.
|
|
||||||
- **web-console**: reconnecting cleared every banner, including a warning that arrived while offline; it now clears only the *Lost contact* banner. An open Overview tab now refreshes during a build.
|
|
||||||
- **web-console**: a `409` on Home, Stop or **Write the brief** now marks the page busy the way Send does, and the brief dialog says why it could not go.
|
|
||||||
- **web-console**: arrowing through a menu question kept dropping keyboard focus to the page body; menu radios now carry stable ids, a `value` and an `aria-label`. `@` mentions typed with a capital letter now match, and the attachment-limit banner uses `MAX_ATTACHMENTS` / `CHAT_MAX_ATTACHMENTS` instead of a hard-coded 5.
|
|
||||||
|
|
||||||
### 📚 Documentation
|
|
||||||
|
|
||||||
- **web console guide**: new *When an update is out* section, Cleanup under the session cleanup notes, and a pointer to `/plan2code-model-update` for the curated model list.
|
|
||||||
|
|
||||||
## v2.4.1
|
## v2.4.1
|
||||||
|
|
||||||
### ✨ Added
|
### ✨ Added
|
||||||
@@ -62,31 +12,9 @@ All notable changes to Plan2Code will be documented in this file.
|
|||||||
- **Web console welcome**: the first dashboard a person sees opens a Welcome dialog with Planny waving, four tips and a **Start building** button. Closing it by any route saves `looks.welcomeSeen` in `looks.json`; Help's first tab has **Show the welcome again**.
|
- **Web console welcome**: the first dashboard a person sees opens a Welcome dialog with Planny waving, four tips and a **Start building** button. Closing it by any route saves `looks.welcomeSeen` in `looks.json`; Help's first tab has **Show the welcome again**.
|
||||||
- **Report a bug or idea from the console**: a megaphone button at the right of the top bar opens GitHub's new-issue chooser for `jparkerweb/plan2code`, with new **Bug** and **Idea** issue templates in `.github/ISSUE_TEMPLATE/` (blank issues off).
|
- **Report a bug or idea from the console**: a megaphone button at the right of the top bar opens GitHub's new-issue chooser for `jparkerweb/plan2code`, with new **Bug** and **Idea** issue templates in `.github/ISSUE_TEMPLATE/` (blank issues off).
|
||||||
- **Version in Help**: the Help dialog's footer shows the running Plan2Code version, served by a new `GET /version` route. The skill build copies `version.json` into each skill's `references/web-console/` so the console can find it.
|
- **Version in Help**: the Help dialog's footer shows the running Plan2Code version, served by a new `GET /version` route. The skill build copies `version.json` into each skill's `references/web-console/` so the console can find it.
|
||||||
- **skills**: skill scripts. Every step a workflow decides with one correct answer now runs as a script the agent calls instead of prose it follows: Node 18+ built-ins only, one JSON object on stdout, documented exit codes, `--help`, `--dry-run` on writes. They install beside each `SKILL.md` in `scripts/`: shared ones from `src/skill-scripts/` (named per skill in `SOURCE_PROMPTS` → `scripts`), a skill's own from `src/<skill>-scripts/`, plus `common.mjs` and the release's `version.json`.
|
|
||||||
- **specs.mjs** (plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff): `list`, `status`, `metrics`, `mark`, `archive`. It reads gitignored `specs/` directly, parses the Phase Checklist and Parallel Execution Groups in the formats real specs use, counts tasks by marker (including `3.6a` and named `1.T` tasks), applies Implementation Mode's phase-selection table, and flags drift such as a phase marked `[x]` with open tasks. It shares the dashboard's spec classifier by importing the bundled `web-console/lib.mjs`.
|
|
||||||
- **pathfinder.mjs**: `reconcile`, `frontier`, `claim`, `resolve`, `rule-out`, `trail`, `gate`, `lint`, `brief-data` for maps on the `local` backend. The map's markers, the Trail Footer, the Clearing Gate's mechanical checks and hard caps, the standing-rule lint (loop tokens, checkboxes, reserved names, schema lines, `Blocked by:` cycles, the metrics collector's own scrape patterns) and a brief's date filtering are computed from the question files. Reconcile keeps each map row's own wording and only changes what the files contradict. Maps on the `github` backend keep doing these steps with `gh`, as `github-issues.md` describes.
|
|
||||||
- **feedback-payload.mjs** (finalize STEP 6.5): builds the payload from the archive, with real 12-character sha256 prompt hashes (the prose admitted the agent could not compute them), renders the issue, checks the 8 KB URL limit with `--truncate`, and runs the gh / browser / print tiers against `jparkerweb/plan2code`.
|
|
||||||
- **commit-msg.mjs**, **review-scope.mjs**, **agents-md.mjs**, **agent-files.mjs**, **handoff-path.mjs**: the commit command from the branch's ticket, Review's git scope and doc share, AGENTS.md's structure and orphans, the AI agent file sync, and the handoff's timestamped path and git ignore check.
|
|
||||||
- **tests**: `scripts/test-skill-scripts.mjs` and `scripts/test-script-<skill>.mjs`, run by `npm test` against the built `skills/` tree. One test fails if a `SKILL.md` names a script its skill does not ship.
|
|
||||||
- **web console**: the Workspace dialog's folders are remembered across console sessions, in `~/.plan2code/console/workspaces.json` beside `looks.json` (never in the project), keyed by the folder a session runs in and then by spec. Every change is saved. *Start from scratch* on the dashboard shows the project's list; picking a spec loads its own, which starts as a copy of the project's and is separate after that, and a spec created mid-run takes the list in force with it. The dialog says whose list it is. New `console.mjs forget --spec specs/<name>`, which Finalize's Spec Cleanup runs after archiving a spec.
|
|
||||||
|
|
||||||
### 🔧 Changed
|
### 🔧 Changed
|
||||||
|
|
||||||
- **skills**: the character limit for `src/plan2code-*.md` rises from 11,500 to 20,000 (about 5k tokens). It no longer guards Windsurf's old limit; it is a size discipline, applied by `validate-char-count.js` and the metrics improver alike.
|
|
||||||
- **finalize**: a run at exactly 75% complete now finalizes with notice (the table said >75% and <75%). Assumed `[?]` tasks count as completed and are listed; started `[/]` tasks count as incomplete. `verification_items_added` and Step 7's two judgment counts are passed to the script, which computes the rest.
|
|
||||||
- **finalize**: the community feedback issue title reads `[Feedback] v<version> - rating N/10`; ingestion matches on the `[Feedback]` prefix and is unaffected.
|
|
||||||
- **init**, **init-update**: both write the same pointer templates, from `agent-files.mjs`. Replacing `.cursor/rules/` now also removes Cursor's own `.mdc` rule files, so AGENTS.md really is the single source there, and files that already point at AGENTS.md are no longer offered again.
|
|
||||||
- **revise-plan**: re-opening a phase (`specs.mjs mark --to open`) also sets its phase file's Status back to In Progress.
|
|
||||||
- **review**: the branch scope compares `base...HEAD` (what this branch added since it left the base) rather than `main..HEAD`, and a trunk other than `main` / `master` is passed with `--base`.
|
|
||||||
- **pathfinder**: the Trail Footer's named legend numbers stops by position (`(blocked:3)` points at stop 3), and a brief's range is given as `this-week`, `since:<date>` or `<date>..<date>`.
|
|
||||||
- **init**, **init-update**: a CLAUDE.md (or other agent file) that is a symlink or hard link to AGENTS.md is reported as `linkedToAgents` and never replaced, since writing the pointer through it would overwrite AGENTS.md. A pointer file checked out with CRLF line endings still counts as already pointing.
|
|
||||||
- **review**: with no `main` or `master` and no `--base`, `review-scope.mjs` now stops with `no-base` instead of quietly counting only uncommitted changes.
|
|
||||||
- **commit-msg.mjs**: the add step is `git add -- <paths>`, paths starting with `@` or `-` are quoted, and subjects with `\`, `!` or curly quotes are refused. The output also carries `add` and `commit` separately for Windows PowerShell 5.1, which has no `&&`.
|
|
||||||
- **specs.mjs**: `mark` reads a Status line written as `Status:` or `**Status**:` too, and warns when a phase file has none; a path that is not a folder directly under `specs/` is refused (`not-a-spec`).
|
|
||||||
- **pathfinder**: the map header carries `**Next NN:**`, so a deleted question's number is never handed out again. `claim`, `resolve` and `rule-out` honour `--dry-run`. Notes indented under a map row survive a marker change. Research questions are fired unclaimed; the one-claim rule is for the questions a person works through.
|
|
||||||
- **finalize**: `feedback-payload.mjs` counts the same phase files `specs.mjs` does, `submit` refuses an oversize URL when `gh` is unavailable (`oversize`), and a bare spec name present in both `specs/` and `specs--completed/` is refused as ambiguous.
|
|
||||||
- Every script was checked against real specs and Pathfinder maps in other repositories and by four independent reviews; each issue found has a regression test.
|
|
||||||
|
|
||||||
- **install.js**: the closing message beside Planny now names the dashboard first: `plan2code` from any project, or `/plan2code` in your agent when the command could not be installed. The docs link moves to the line under it.
|
- **install.js**: the closing message beside Planny now names the dashboard first: `plan2code` from any project, or `/plan2code` in your agent when the command could not be installed. The docs link moves to the line under it.
|
||||||
- **web-console**: User Preferences opens from a gear button instead of the three swatches, and the default highlight color is now ocean blue instead of rust.
|
- **web-console**: User Preferences opens from a gear button instead of the three swatches, and the default highlight color is now ocean blue instead of rust.
|
||||||
- **web-console**: the dashboard rail marks the suggested next step with a small dot, since the center pane's Suggested pill can scroll out of view. Send pulses only while it is the primary button.
|
- **web-console**: the dashboard rail marks the suggested next step with a small dot, since the center pane's Suggested pill can scroll out of view. Send pulses only while it is the primary button.
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
**A spec-driven workflow for AI coding agents.**
|
**A spec-driven workflow for AI coding agents.**
|
||||||
|
|
||||||
<img src="docs/banner.jpg" alt="banner" data="object-fit:contain;" style="max-width:1024px;">
|
<img src="docs/banner.jpg" alt="Plan2Code: plan and build with your AI agent, on one page. Planny, the mascot, acts out the five steps: Pathfinder, Plan, Document, Implement and Finalize." data="object-fit:contain;" style="max-width:1024px;">
|
||||||
|
|
||||||
You work through Plan2Code on a page in your browser. The dashboard lists every step as a card, and
|
You work through Plan2Code on a page in your browser. The dashboard lists every step as a card, and
|
||||||
each step's questions, progress and sign-offs arrive on that same page while your agent does the
|
each step's questions, progress and sign-offs arrive on that same page while your agent does the
|
||||||
@@ -13,7 +13,7 @@ the next engineer all start from the same specs.
|
|||||||
|
|
||||||
One command opens it, every step is a card, and the terminal is always there if you prefer it.
|
One command opens it, every step is a card, and the terminal is always there if you prefer it.
|
||||||
|
|
||||||
Version 2.5.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
Version 2.4.1 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -375,7 +375,7 @@ footer a { color: inherit; }
|
|||||||
<div class="wrap">
|
<div class="wrap">
|
||||||
<a href="https://github.com/jparkerweb/plan2code">Plan2Code on GitHub</a>
|
<a href="https://github.com/jparkerweb/plan2code">Plan2Code on GitHub</a>
|
||||||
<span>MIT license</span>
|
<span>MIT license</span>
|
||||||
<a href="https://github.com/jparkerweb/plan2code/releases">Releases</a>
|
<span>Version 2.4.1</span>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
|
|||||||
-64
@@ -112,11 +112,6 @@ const SKILLS_DIR = path.join(__dirname, SKILLS_DIR_NAME);
|
|||||||
// Source prompts directory
|
// Source prompts directory
|
||||||
const SRC_DIR = path.join(__dirname, 'src');
|
const SRC_DIR = path.join(__dirname, 'src');
|
||||||
|
|
||||||
// Shared skill scripts (src/skill-scripts/). A skill lists the ones it runs in its
|
|
||||||
// `scripts` field; SHARED_SCRIPTS_ALWAYS ride along with any skill that has scripts.
|
|
||||||
const SHARED_SCRIPTS_DIR = 'skill-scripts';
|
|
||||||
const SHARED_SCRIPTS_ALWAYS = ['common.mjs'];
|
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// SYNC PROMPTS CONFIGURATION (merged from sync-prompts.js)
|
// SYNC PROMPTS CONFIGURATION (merged from sync-prompts.js)
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -141,7 +136,6 @@ const SOURCE_PROMPTS = [
|
|||||||
displayName: 'Init Mode',
|
displayName: 'Init Mode',
|
||||||
description: 'Generate AGENTS.md file for project-specific guidance',
|
description: 'Generate AGENTS.md file for project-specific guidance',
|
||||||
isUtility: true,
|
isUtility: true,
|
||||||
scripts: ['agents-md.mjs', 'agent-files.mjs'],
|
|
||||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -151,7 +145,6 @@ const SOURCE_PROMPTS = [
|
|||||||
displayName: 'Init Update Mode',
|
displayName: 'Init Update Mode',
|
||||||
description: 'Update existing AGENTS.md with new learnings',
|
description: 'Update existing AGENTS.md with new learnings',
|
||||||
isUtility: true,
|
isUtility: true,
|
||||||
scripts: ['agents-md.mjs', 'agent-files.mjs', 'commit-msg.mjs'],
|
|
||||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -171,7 +164,6 @@ const SOURCE_PROMPTS = [
|
|||||||
isUtility: true,
|
isUtility: true,
|
||||||
// review.md rides along for the web console's "Review it now" button, which
|
// review.md rides along for the web console's "Review it now" button, which
|
||||||
// runs the review in the same session once the quick task is built.
|
// runs the review in the same session once the quick task is built.
|
||||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
|
|
||||||
additionalReferences: [
|
additionalReferences: [
|
||||||
{ source: 'web-console', target: 'web-console' },
|
{ source: 'web-console', target: 'web-console' },
|
||||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||||
@@ -184,7 +176,6 @@ const SOURCE_PROMPTS = [
|
|||||||
name: 'plan',
|
name: 'plan',
|
||||||
displayName: 'Planning Mode',
|
displayName: 'Planning Mode',
|
||||||
description: 'Requirements analysis and architecture design',
|
description: 'Requirements analysis and architecture design',
|
||||||
scripts: ['specs.mjs'],
|
|
||||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -193,7 +184,6 @@ const SOURCE_PROMPTS = [
|
|||||||
name: 'revise-plan',
|
name: 'revise-plan',
|
||||||
displayName: 'Revision Mode',
|
displayName: 'Revision Mode',
|
||||||
description: 'Modify specs mid-implementation when requirements change',
|
description: 'Modify specs mid-implementation when requirements change',
|
||||||
scripts: ['specs.mjs'],
|
|
||||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -202,7 +192,6 @@ const SOURCE_PROMPTS = [
|
|||||||
name: 'document',
|
name: 'document',
|
||||||
displayName: 'Documentation Mode',
|
displayName: 'Documentation Mode',
|
||||||
description: 'Transform planning output into structured implementation docs',
|
description: 'Transform planning output into structured implementation docs',
|
||||||
scripts: ['specs.mjs'],
|
|
||||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -213,7 +202,6 @@ const SOURCE_PROMPTS = [
|
|||||||
description: 'Execute implementation phase by phase',
|
description: 'Execute implementation phase by phase',
|
||||||
// review.md rides along for the web console's review offer on the sign-off
|
// review.md rides along for the web console's review offer on the sign-off
|
||||||
// card, which runs the review in the same session before the phase is approved.
|
// card, which runs the review in the same session before the phase is approved.
|
||||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
|
|
||||||
additionalReferences: [
|
additionalReferences: [
|
||||||
{ source: 'web-console', target: 'web-console' },
|
{ source: 'web-console', target: 'web-console' },
|
||||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||||
@@ -226,7 +214,6 @@ const SOURCE_PROMPTS = [
|
|||||||
name: 'implement-review',
|
name: 'implement-review',
|
||||||
displayName: 'Implementation + Review Mode',
|
displayName: 'Implementation + Review Mode',
|
||||||
description: 'Implement one phase, review it, then request sign-off',
|
description: 'Implement one phase, review it, then request sign-off',
|
||||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
|
|
||||||
additionalReferences: [
|
additionalReferences: [
|
||||||
{ source: 'web-console', target: 'web-console' },
|
{ source: 'web-console', target: 'web-console' },
|
||||||
{ source: 'plan2code-3-implement.md', target: 'implement.md' },
|
{ source: 'plan2code-3-implement.md', target: 'implement.md' },
|
||||||
@@ -241,7 +228,6 @@ const SOURCE_PROMPTS = [
|
|||||||
displayName: 'Review Mode',
|
displayName: 'Review Mode',
|
||||||
description: 'Comprehensive post-implementation review with spec compliance checking',
|
description: 'Comprehensive post-implementation review with spec compliance checking',
|
||||||
isUtility: true,
|
isUtility: true,
|
||||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
|
|
||||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -250,7 +236,6 @@ const SOURCE_PROMPTS = [
|
|||||||
name: 'finalize',
|
name: 'finalize',
|
||||||
displayName: 'Finalization Mode',
|
displayName: 'Finalization Mode',
|
||||||
description: 'Validate, summarize, and archive completed work',
|
description: 'Validate, summarize, and archive completed work',
|
||||||
scripts: ['specs.mjs', 'commit-msg.mjs'],
|
|
||||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -260,7 +245,6 @@ const SOURCE_PROMPTS = [
|
|||||||
displayName: 'Handoff Mode',
|
displayName: 'Handoff Mode',
|
||||||
description: 'Compact the conversation into a self-contained handoff document for a fresh session',
|
description: 'Compact the conversation into a self-contained handoff document for a fresh session',
|
||||||
isUtility: true,
|
isUtility: true,
|
||||||
scripts: ['specs.mjs'],
|
|
||||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
@@ -590,57 +574,11 @@ function computeExpectedSkills() {
|
|||||||
errors.push(`Could not include src/${reference.source} for ${skillName}: ${err.message}`);
|
errors.push(`Could not include src/${reference.source} for ${skillName}: ${err.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Scripts land flat in skills/<skill>/scripts/, beside the SKILL.md that runs them:
|
|
||||||
// the skill's own src/<source>-scripts/ plus the shared ones it names in `scripts`
|
|
||||||
// from src/skill-scripts/. Skills install independently, so shared code is copied
|
|
||||||
// into each skill rather than referenced across skill directories.
|
|
||||||
const scripts = new Map();
|
|
||||||
const ownScriptsDir = path.join(SRC_DIR, prompt.source.replace(/\.md$/, '-scripts'));
|
|
||||||
const sharedNames = prompt.scripts || [];
|
|
||||||
if (sharedNames.length || fs.existsSync(ownScriptsDir)) {
|
|
||||||
for (const name of [...SHARED_SCRIPTS_ALWAYS, ...sharedNames]) {
|
|
||||||
const abs = path.join(SRC_DIR, SHARED_SCRIPTS_DIR, name);
|
|
||||||
if (!fs.existsSync(abs)) {
|
|
||||||
errors.push(`src/${SHARED_SCRIPTS_DIR}/${name} (named by ${skillName}) does not exist`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
scripts.set(name, fs.readFileSync(abs));
|
|
||||||
}
|
|
||||||
if (fs.existsSync(ownScriptsDir)) {
|
|
||||||
for (const relPath of listFilesRecursive(ownScriptsDir)) {
|
|
||||||
const name = relPath.split(path.sep).join('/');
|
|
||||||
if (scripts.has(name) || name === 'version.json') {
|
|
||||||
errors.push(`src/${path.basename(ownScriptsDir)}/${name} collides with a ${name === 'version.json' ? 'generated file' : 'shared script'} of the same name`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
scripts.set(name, fs.readFileSync(path.join(ownScriptsDir, relPath)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// The version the scripts report (the finalize feedback payload needs it, and an
|
|
||||||
// installed skill has no repo version.json to read).
|
|
||||||
scripts.set('version.json', fs.readFileSync(path.join(__dirname, 'version.json')));
|
|
||||||
}
|
|
||||||
for (const [name, content] of scripts) {
|
|
||||||
expected.set(`${SKILLS_DIR_NAME}/${skillName}/scripts/${name}`, content);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { expected, errors };
|
return { expected, errors };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove empty directories below `dir` (never `dir` itself), deepest first.
|
|
||||||
*/
|
|
||||||
function removeEmptyDirs(dir) {
|
|
||||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
||||||
if (!entry.isDirectory()) continue;
|
|
||||||
const sub = path.join(dir, entry.name);
|
|
||||||
removeEmptyDirs(sub);
|
|
||||||
if (fs.readdirSync(sub).length === 0) fs.rmdirSync(sub);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildSkills(quiet = false) {
|
function buildSkills(quiet = false) {
|
||||||
const { expected, errors } = computeExpectedSkills();
|
const { expected, errors } = computeExpectedSkills();
|
||||||
const stats = { written: 0, unchanged: 0, pruned: 0, errors: errors.length };
|
const stats = { written: 0, unchanged: 0, pruned: 0, errors: errors.length };
|
||||||
@@ -668,8 +606,6 @@ function buildSkills(quiet = false) {
|
|||||||
stats.pruned++;
|
stats.pruned++;
|
||||||
if (!quiet) console.log(` ${COLORS.YELLOW}░░░${COLORS.RESET} Pruned: ${key}`);
|
if (!quiet) console.log(` ${COLORS.YELLOW}░░░${COLORS.RESET} Pruned: ${key}`);
|
||||||
}
|
}
|
||||||
// A folder the build no longer fills (a skill that lost all its scripts) goes too.
|
|
||||||
removeEmptyDirs(skillDir);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const [relPath, content] of expected) {
|
for (const [relPath, content] of expected) {
|
||||||
|
|||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "plan2code",
|
"name": "plan2code",
|
||||||
"version": "2.5.0",
|
"version": "2.4.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"bin": {
|
"bin": {
|
||||||
"plan2code-install": "./install.js"
|
"plan2code-install": "./install.js"
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"prepare": "husky",
|
"prepare": "husky",
|
||||||
"build:skills": "node install.js --build-skills",
|
"build:skills": "node install.js --build-skills",
|
||||||
"test": "node scripts/validate-char-count.js && node install.js --verify-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-web-console.mjs scripts/test-launcher.mjs scripts/test-skill-scripts.mjs scripts/test-script-pathfinder.mjs scripts/test-script-finalize.mjs scripts/test-script-handoff.mjs"
|
"test": "node scripts/validate-char-count.js && node install.js --verify-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-web-console.mjs scripts/test-launcher.mjs"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"husky": "^9.0.0"
|
"husky": "^9.0.0"
|
||||||
|
|||||||
@@ -226,7 +226,7 @@ Output: `.plan2code-metrics/proposals/<timestamp>-diagnosis.md`
|
|||||||
Sends the diagnosis plus current prompt file contents to an AI model. The AI proposes surgical `old_text -> new_text` edits, each validated against:
|
Sends the diagnosis plus current prompt file contents to an AI model. The AI proposes surgical `old_text -> new_text` edits, each validated against:
|
||||||
|
|
||||||
- The `old_text` actually exists in the target file
|
- The `old_text` actually exists in the target file
|
||||||
- The edited file stays under the 20,000 character limit
|
- The edited file stays under the 11,500 character limit
|
||||||
|
|
||||||
Output: `.plan2code-metrics/proposals/prop-<timestamp>.json`
|
Output: `.plan2code-metrics/proposals/prop-<timestamp>.json`
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import chalk from 'chalk';
|
|||||||
import type { PromptEdit, PromptProposal } from './types.js';
|
import type { PromptEdit, PromptProposal } from './types.js';
|
||||||
import { validateEdit } from './improver.js';
|
import { validateEdit } from './improver.js';
|
||||||
|
|
||||||
const CHAR_LIMIT = 20_000;
|
const CHAR_LIMIT = 11_500;
|
||||||
|
|
||||||
// ── Diff display ──────────────────────────────────────────────────────────────
|
// ── Diff display ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|||||||
@@ -69,12 +69,12 @@ describe('validateEdit', () => {
|
|||||||
expect(result.warnings.some(w => /appears.*times/i.test(w))).toBe(true);
|
expect(result.warnings.some(w => /appears.*times/i.test(w))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('errors when edit would exceed 20,000 char limit', () => {
|
it('errors when edit would exceed 11,500 char limit', () => {
|
||||||
const bigText = 'x'.repeat(21_000);
|
const bigText = 'x'.repeat(12_000);
|
||||||
const edit = makeEdit({ new_text: bigText });
|
const edit = makeEdit({ new_text: bigText });
|
||||||
const result = validateEdit(edit, PROMPT_CONTENTS);
|
const result = validateEdit(edit, PROMPT_CONTENTS);
|
||||||
expect(result.valid).toBe(false);
|
expect(result.valid).toBe(false);
|
||||||
expect(result.errors.some(e => /exceed.*20.?000/i.test(e))).toBe(true);
|
expect(result.errors.some(e => /exceed.*11.?500/i.test(e))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('warns when reported char counts diverge from actual (>10 chars off)', () => {
|
it('warns when reported char counts diverge from actual (>10 chars off)', () => {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import path from 'path';
|
|||||||
import type { PromptEdit, PromptProposal } from './types.js';
|
import type { PromptEdit, PromptProposal } from './types.js';
|
||||||
import { invokeLLM, type AgentType } from './invoke-llm.js';
|
import { invokeLLM, type AgentType } from './invoke-llm.js';
|
||||||
|
|
||||||
const CHAR_LIMIT = 20_000;
|
const CHAR_LIMIT = 11_500;
|
||||||
const IMPROVE_PROMPT_PATH = new URL('../src/prompts/improve.md', import.meta.url).pathname
|
const IMPROVE_PROMPT_PATH = new URL('../src/prompts/improve.md', import.meta.url).pathname
|
||||||
.replace(/^\/([A-Za-z]:)/, '$1'); // Fix Windows path
|
.replace(/^\/([A-Za-z]:)/, '$1'); // Fix Windows path
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ The following diagnosis was produced by the analysis step:
|
|||||||
|
|
||||||
## Hard Constraints — ALL must be satisfied:
|
## Hard Constraints — ALL must be satisfied:
|
||||||
|
|
||||||
1. **Char limit:** Each target file MUST stay under 20,000 characters after your edit is applied. This is enforced by code — edits that violate it will be automatically rejected.
|
1. **Char limit:** Each target file MUST stay under 11,500 characters after your edit is applied. This is enforced by code — edits that violate it will be automatically rejected.
|
||||||
2. **Maximum 5 edits per cycle.** Focus on the highest-impact changes only.
|
2. **Maximum 5 edits per cycle.** Focus on the highest-impact changes only.
|
||||||
3. **Each edit must cite a specific metric** in its `expected_metric_impact` field (e.g., "avg_task_completion_rate", "avg_blocker_count").
|
3. **Each edit must cite a specific metric** in its `expected_metric_impact` field (e.g., "avg_task_completion_rate", "avg_blocker_count").
|
||||||
4. **`old_text` must be verbatim** from the file. Copy-paste exactly — include surrounding whitespace/newlines as they appear. Edits with mismatched old_text will be automatically rejected.
|
4. **`old_text` must be verbatim** from the file. Copy-paste exactly — include surrounding whitespace/newlines as they appear. Edits with mismatched old_text will be automatically rejected.
|
||||||
@@ -85,7 +85,7 @@ Set `char_count_before`, `char_count_after`, and `char_count_delta` to your best
|
|||||||
|
|
||||||
A table with columns: File | Before | Projected After | Delta | Limit | Status (✓/✗)
|
A table with columns: File | Before | Projected After | Delta | Limit | Status (✓/✗)
|
||||||
|
|
||||||
Verify that NO file exceeds 20,000 characters after your proposed edits.
|
Verify that NO file exceeds 11,500 characters after your proposed edits.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -40,9 +40,6 @@ const CWD = path.resolve(args.cwd || ROOT);
|
|||||||
|
|
||||||
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-bench-"));
|
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-bench-"));
|
||||||
const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER: "1" };
|
const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER: "1" };
|
||||||
// A fresh cached failure: the boot-time release check stays off the network,
|
|
||||||
// so a slow GitHub never colours the timings.
|
|
||||||
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
|
|
||||||
|
|
||||||
function findBrowser() {
|
function findBrowser() {
|
||||||
if (args.browser === "none") return null;
|
if (args.browser === "none") return null;
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
// Shared helpers for the skill-script tests (scripts/test-*script*.mjs).
|
|
||||||
//
|
|
||||||
// The tests run the scripts the way an agent does: as `node <skill>/scripts/x.mjs`
|
|
||||||
// from the built skills/ tree, against throwaway fixtures in the OS temp dir,
|
|
||||||
// with the clock pinned by PLAN2CODE_NOW. They live in scripts/ so nothing
|
|
||||||
// here ships.
|
|
||||||
|
|
||||||
import fs from "node:fs";
|
|
||||||
import os from "node:os";
|
|
||||||
import path from "node:path";
|
|
||||||
import { spawnSync, execFileSync } from "node:child_process";
|
|
||||||
import { fileURLToPath } from "node:url";
|
|
||||||
|
|
||||||
export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
|
||||||
export const SKILLS = path.join(ROOT, "skills");
|
|
||||||
export const NOW = "2026-08-03 14:05";
|
|
||||||
|
|
||||||
// Rebuild skills/ on every import, not only when it is missing: a test file run
|
|
||||||
// directly after an edit to src/ must not test a stale tree. The build is
|
|
||||||
// idempotent and takes well under a second.
|
|
||||||
execFileSync(process.execPath, [path.join(ROOT, "install.js"), "--build-skills"], { stdio: "ignore" });
|
|
||||||
|
|
||||||
export function runScript(skill, script, args, { cwd, env } = {}) {
|
|
||||||
const r = spawnSync(process.execPath, [path.join(SKILLS, skill, "scripts", script), ...args], {
|
|
||||||
cwd: cwd || ROOT,
|
|
||||||
encoding: "utf8",
|
|
||||||
env: { ...process.env, PLAN2CODE_NOW: NOW, GIT_CONFIG_NOSYSTEM: "1", ...env },
|
|
||||||
});
|
|
||||||
let json = null;
|
|
||||||
try {
|
|
||||||
json = JSON.parse(r.stdout);
|
|
||||||
} catch {}
|
|
||||||
return { code: r.status, json, stdout: r.stdout, stderr: r.stderr };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function tmp(name) {
|
|
||||||
return fs.mkdtempSync(path.join(fs.realpathSync.native(os.tmpdir()), `p2c-${name}-`));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function write(root, rel, content) {
|
|
||||||
const p = path.join(root, rel);
|
|
||||||
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
||||||
fs.writeFileSync(p, content);
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const read = (root, rel) => fs.readFileSync(path.join(root, rel), "utf8");
|
|
||||||
|
|
||||||
export function gitInit(dir, branch = "main") {
|
|
||||||
const g = (...a) => execFileSync("git", a, { cwd: dir, stdio: "pipe", encoding: "utf8" });
|
|
||||||
g("init", "-q", "-b", branch);
|
|
||||||
g("config", "user.email", "t@example.com");
|
|
||||||
g("config", "user.name", "Test");
|
|
||||||
g("config", "commit.gpgsign", "false");
|
|
||||||
return g;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A phase-N.md in the Documentation template's shape. tasks: [[marker, id], ...] */
|
|
||||||
export function phase(n, status, tasks, extra = "") {
|
|
||||||
return `# Phase ${n}: Name ${n}\n\n**Status:** ${status}\n**Estimated Tasks:** ${tasks.length}\n\n## Overview\n\nPhase ${n} builds the thing. More words here.\n\n## Prerequisites\n\n- Something exists\n\n## Tasks\n\n${tasks.map(([m, id]) => `- [${m}] **Task ${id}:** Do ${id}`).join("\n")}\n${extra}\n## Acceptance Criteria\n\n- It works\n`;
|
|
||||||
}
|
|
||||||
@@ -174,35 +174,3 @@ test("launcher: the CLI's non-zero exit code is passed through", (t) => {
|
|||||||
assert.equal(result.status, 7, result.stderr);
|
assert.equal(result.status, 7, result.stderr);
|
||||||
assert.notEqual(box.argsOf("claude"), null);
|
assert.notEqual(box.argsOf("claude"), null);
|
||||||
});
|
});
|
||||||
test("launcher: renderBanner draws Planny and the name, colored only through paint", () => {
|
|
||||||
const { renderBanner, paint } = require(LAUNCHER);
|
|
||||||
const plain = renderBanner(paint(false));
|
|
||||||
assert.doesNotMatch(plain, /\x1b/);
|
|
||||||
for (const part of ["╭───╮", "╰┬─┬╯", "★", "Plan2Code"]) assert.ok(plain.includes(part), part);
|
|
||||||
assert.ok(plain.split("\n").length >= 4);
|
|
||||||
const colored = renderBanner(paint(true));
|
|
||||||
assert.ok(colored.includes("\x1b["));
|
|
||||||
assert.ok(colored.includes("\x1b[0m"));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("launcher: paint wraps text in the escape codes only when color is on", () => {
|
|
||||||
const { paint } = require(LAUNCHER);
|
|
||||||
assert.equal(paint(false).red("x"), "x");
|
|
||||||
assert.equal(paint(true).red("x"), "\x1b[31mx\x1b[0m");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("launcher: a piped run prints no escape codes, with or without NO_COLOR", (t) => {
|
|
||||||
const box = sandbox(["claude"]);
|
|
||||||
t.after(box.cleanup);
|
|
||||||
const none = sandbox([]);
|
|
||||||
t.after(none.cleanup);
|
|
||||||
for (const env of [{}, { NO_COLOR: "1" }]) {
|
|
||||||
const runs = [box.run([], env), box.run(["--cli", "bogus"], env), none.run([], env)];
|
|
||||||
assert.deepEqual(runs.map((r) => r.status), [0, 2, 127]);
|
|
||||||
for (const r of runs) {
|
|
||||||
assert.doesNotMatch(r.stdout, /\x1b/);
|
|
||||||
assert.doesNotMatch(r.stderr, /\x1b/);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
@@ -1,174 +0,0 @@
|
|||||||
// Tests for plan2code-4-finalize's scripts/feedback-payload.mjs.
|
|
||||||
//
|
|
||||||
// See skill-script-helpers.mjs for how these run.
|
|
||||||
|
|
||||||
import { test } from "node:test";
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { spawnSync } from "node:child_process";
|
|
||||||
import crypto from "node:crypto";
|
|
||||||
import { ROOT, SKILLS, NOW, runScript, tmp, write, read, gitInit, phase } from "./skill-script-helpers.mjs";
|
|
||||||
|
|
||||||
/* ========================================================= feedback-payload.mjs */
|
|
||||||
|
|
||||||
test("feedback-payload: payload from the archive, real prompt hashes, size and truncation", () => {
|
|
||||||
const root = tmp("fb");
|
|
||||||
const spec = "specs--completed/lunch-vote";
|
|
||||||
write(root, `${spec}/PLAN-DRAFT-20260801.md`, '# Plan\n\n<!-- METRICS_JSON {"confidence": 92, "clarification_rounds": 1, "functional_requirements_count": 5, "non_functional_requirements_count": 2, "risk_count": 3, "phase_count": 2, "verification_gaps_found": 0, "confidence_breakdown": {"requirements": 24, "feasibility": 23, "integration": 23, "risk": 22}} -->\n');
|
|
||||||
write(root, `${spec}/overview.md`, '# O\n\n<!-- METRICS_JSON {"step": "document", "total_tasks": 3, "tasks_per_phase": [2, 1], "phase_count": 2, "parallel_groups_identified": 0, "verification_items_added": 1} -->\n\n## User Feedback\n| Field | Value |\n|-------|-------|\n| Rating | 8 |\n| Reason | Good \\| fast |\n| Went Well | Specs |\n| Went Poorly | Review |\n');
|
|
||||||
write(root, `${spec}/phase-1.md`, phase(1, "Complete", [["x", "1.1"], ["x", "1.T"]]));
|
|
||||||
write(root, `${spec}/phase-2.md`, phase(2, "Complete", [["!", "2.1"]]));
|
|
||||||
const outDir = path.join(root, "out");
|
|
||||||
const F = (...a) => runScript("plan2code-4-finalize", "feedback-payload.mjs", [...a, "--root", root]);
|
|
||||||
assert.equal(F("build", "lunch-vote", "--out", outDir).code, 2, "the two judgment counts are required");
|
|
||||||
const b = F("build", "lunch-vote", "--out", outDir, "--set", "verification_failures_found=1", "--set", "documentation_updates_needed=2");
|
|
||||||
assert.equal(b.code, 0, b.stderr);
|
|
||||||
const p = b.json.payload;
|
|
||||||
assert.match(p.run_id, /^run-20260803-140500-[0-9a-f]{4}$/);
|
|
||||||
assert.equal(p.plan2code_version, JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version);
|
|
||||||
const srcHash = crypto.createHash("sha256").update(fs.readFileSync(path.join(ROOT, "src", "plan2code-1-plan.md"), "utf8")).digest("hex").slice(0, 12);
|
|
||||||
assert.equal(p.prompt_versions_short.plan, srcHash, "the hash is the src prompt's, recovered from the installed SKILL.md");
|
|
||||||
assert.ok(Object.values(p.prompt_versions_short).every((v) => /^[0-9a-f]{12}$/.test(v)));
|
|
||||||
assert.deepEqual(p.step1.confidence_breakdown, { requirements: 24, feasibility: 23, integration: 23, risk: 22 });
|
|
||||||
assert.equal(p.step1.final_confidence, 92);
|
|
||||||
assert.equal(p.step2.total_tasks, 3);
|
|
||||||
assert.deepEqual(p.step3, { task_completion_rate: 0.67, tasks_completed: 2, tasks_total: 3, blocker_count: 1 });
|
|
||||||
assert.deepEqual(p.step4, { completion_rate_at_audit: 0.67, verification_failures_found: 1, documentation_updates_needed: 2, archival_succeeded: true });
|
|
||||||
assert.deepEqual(p.user_feedback, { overall_rating: 8, rating_reason: "Good | fast", what_went_well: "Specs", what_went_poorly: "Review" });
|
|
||||||
assert.equal(b.json.title, `[Feedback] v${p.plan2code_version} - rating 8/10`);
|
|
||||||
assert.match(b.json.body, /<!-- METRICS_JSON \{"schema_version":"1\.0"/);
|
|
||||||
assert.ok(!/[—]/.test(b.json.title), "no em dash in the issue title");
|
|
||||||
assert.equal(b.json.oversize, false);
|
|
||||||
assert.ok(fs.existsSync(path.join(outDir, "body.md")));
|
|
||||||
// The ingest side parses the body back.
|
|
||||||
const parsed = JSON.parse(b.json.body.match(/<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/)[1]);
|
|
||||||
assert.equal(parsed.schema_version, "1.0");
|
|
||||||
// Oversize, then truncate.
|
|
||||||
const ov = path.join(root, spec, "overview.md");
|
|
||||||
fs.writeFileSync(ov, fs.readFileSync(ov, "utf8").replace("| Good \\| fast |", `| ${"long reason ".repeat(500)} |`));
|
|
||||||
const big = F("build", "lunch-vote", "--out", outDir, "--set", "verification_failures_found=1", "--set", "documentation_updates_needed=2");
|
|
||||||
assert.equal(big.json.oversize, true);
|
|
||||||
assert.match(big.json.next, /--truncate/);
|
|
||||||
const cut = F("build", "lunch-vote", "--out", outDir, "--set", "verification_failures_found=1", "--set", "documentation_updates_needed=2", "--truncate");
|
|
||||||
assert.equal(cut.json.oversize, false);
|
|
||||||
assert.deepEqual(cut.json.truncated, ["rating_reason"]);
|
|
||||||
const dry = runScript("plan2code-4-finalize", "feedback-payload.mjs", ["submit", "--from", outDir, "--dry-run"]);
|
|
||||||
assert.equal(dry.code, 0);
|
|
||||||
assert.match(dry.json.tiers[0], /^gh issue create --repo jparkerweb\/plan2code .*--label community-feedback$/);
|
|
||||||
assert.equal(dry.json.oversize, false);
|
|
||||||
assert.equal(dry.json.urlBytes, cut.json.urlBytes);
|
|
||||||
fs.writeFileSync(ov, "# O\n");
|
|
||||||
assert.equal(F("build", "lunch-vote", "--set", "verification_failures_found=1", "--set", "documentation_updates_needed=2").code, 3, "no feedback table, nothing to submit");
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ================================================= verification regressions */
|
|
||||||
|
|
||||||
test("feedback-payload: truncation always ends, '-->' survives ingest, lenient rating, absent steps are null", () => {
|
|
||||||
const root = tmp("fb2");
|
|
||||||
const spec = "specs--completed/x";
|
|
||||||
const long = (w) => `${w} `.repeat(400).trim();
|
|
||||||
// The visible answers carry markup that must stay text: a stray comment
|
|
||||||
// opener, and a fake payload comment an ingest regex could match first.
|
|
||||||
const fake = '<!-- METRICS_JSON {"schema_version":"1.0"} -->';
|
|
||||||
const inputs = { rating_reason: `see {a} --> b <!-- x ${long("reason")}`, what_went_well: `${fake} ${long("well")}`, what_went_poorly: long("poorly") };
|
|
||||||
write(root, `${spec}/overview.md`, `# O\n\n## User Feedback\n| field | value |\n|---|---|\n| rating | 8/10 |\n| reason | ${inputs.rating_reason} |\n| went well | ${inputs.what_went_well} |\n| went poorly | ${inputs.what_went_poorly} |\n`);
|
|
||||||
write(root, `${spec}/phase-1.md`, phase(1, "Complete", [["x", "1.1"]]));
|
|
||||||
const F = (...a) => runScript("plan2code-4-finalize", "feedback-payload.mjs", [...a, "--root", root]);
|
|
||||||
const sets = ["--set", "verification_failures_found=0", "--set", "documentation_updates_needed=0"];
|
|
||||||
assert.equal(F("build", "x", ...sets, "--set", "bogus=1").code, 2);
|
|
||||||
// Untruncated, the first METRICS_JSON match is the real payload: its answers
|
|
||||||
// come back exactly as typed, not the fake's bare schema_version.
|
|
||||||
const whole = F("build", "x", ...sets, "--out", path.join(root, "whole"));
|
|
||||||
assert.equal(whole.code, 0, whole.stderr);
|
|
||||||
const first = JSON.parse(whole.json.body.match(/<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/)[1]);
|
|
||||||
assert.deepEqual(first.user_feedback, { overall_rating: 8, ...inputs });
|
|
||||||
assert.equal(whole.json.body.split("<!--").length - 1, 1, "the payload's is the only comment that opens");
|
|
||||||
assert.ok(!/<!--(?! METRICS_JSON \{"schema_version":"1\.0","run_id")/.test(whole.json.body), "no comment opens before the payload's");
|
|
||||||
const r = spawnSync(process.execPath, [path.join(SKILLS, "plan2code-4-finalize", "scripts", "feedback-payload.mjs"), "build", "x", ...sets, "--truncate", "--out", path.join(root, "out"), "--root", root], { encoding: "utf8", timeout: 20000, env: { ...process.env, PLAN2CODE_NOW: NOW } });
|
|
||||||
assert.equal(r.status, 0, "build --truncate finishes with every field long");
|
|
||||||
const j = JSON.parse(r.stdout);
|
|
||||||
assert.equal(j.oversize, false);
|
|
||||||
assert.deepEqual(j.truncated, ["rating_reason", "what_went_well", "what_went_poorly"]);
|
|
||||||
assert.equal(j.payload.user_feedback.overall_rating, 8, "8/10 reads as 8, field names in any case");
|
|
||||||
assert.equal(j.payload.step1, null);
|
|
||||||
assert.equal(j.payload.step2, null);
|
|
||||||
// The ingest side's own extraction regex (plan2code-metrics collector.ts).
|
|
||||||
const m = j.body.match(/<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/);
|
|
||||||
const back = JSON.parse(m[1]);
|
|
||||||
assert.match(back.user_feedback.rating_reason, /^see \{a\} --> b <!-- x/);
|
|
||||||
assert.equal(back.user_feedback.what_went_well, j.payload.user_feedback.what_went_well);
|
|
||||||
assert.match(back.user_feedback.what_went_well, /^<!-- METRICS_JSON/, "the fake comment is still just text in the real payload");
|
|
||||||
assert.ok(!/<!--(?! METRICS_JSON \{"schema_version":"1\.0","run_id")/.test(j.body), "no comment opens before the payload's");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("feedback-payload: --truncate never splits an emoji", () => {
|
|
||||||
const root = tmp("fb3");
|
|
||||||
const spec = "specs--completed/x";
|
|
||||||
const reason = "a" + "\u{1F44D}".repeat(400);
|
|
||||||
write(root, `${spec}/overview.md`, `# O\n\n## User Feedback\n| Field | Value |\n|---|---|\n| Rating | 9 |\n| Reason | ${reason} |\n| Went Well | ok |\n| Went Poorly | none |\n`);
|
|
||||||
write(root, `${spec}/phase-1.md`, phase(1, "Complete", [["x", "1.1"]]));
|
|
||||||
const r = runScript("plan2code-4-finalize", "feedback-payload.mjs", ["build", "x", "--set", "verification_failures_found=0", "--set", "documentation_updates_needed=0", "--truncate", "--out", path.join(root, "out"), "--root", root]);
|
|
||||||
assert.equal(r.code, 0, r.stderr);
|
|
||||||
assert.equal(r.json.oversize, false);
|
|
||||||
assert.deepEqual(r.json.truncated, ["rating_reason"]);
|
|
||||||
const back = JSON.parse(r.json.body.match(/<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/)[1]);
|
|
||||||
assert.equal(back.user_feedback.rating_reason, r.json.payload.user_feedback.rating_reason);
|
|
||||||
assert.ok(!/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(back.user_feedback.rating_reason), "no lone high surrogate");
|
|
||||||
assert.match(back.user_feedback.rating_reason, /^a(\u{1F44D})+\.\.\.$/u);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("feedback-payload: task counts read the same phase files specs.mjs does, never a stale sibling", () => {
|
|
||||||
const root = tmp("fb5");
|
|
||||||
const spec = "specs--completed/x";
|
|
||||||
write(root, `${spec}/overview.md`, "# O\n\n## User Feedback\n| Field | Value |\n|---|---|\n| Rating | 7 |\n| Reason | r |\n| Went Well | w |\n| Went Poorly | p |\n");
|
|
||||||
write(root, `${spec}/phase-1.md`, phase(1, "Complete", [["x", "1.1"], ["x", "1.2"]]));
|
|
||||||
write(root, `${spec}/phase-1-old.md`, phase(1, "Not Started", [[" ", "1.1"], [" ", "1.2"], [" ", "1.3"]]));
|
|
||||||
const r = runScript("plan2code-4-finalize", "feedback-payload.mjs", ["build", "x", "--set", "verification_failures_found=0", "--set", "documentation_updates_needed=0", "--out", path.join(root, "out"), "--root", root]);
|
|
||||||
assert.equal(r.code, 0, r.stderr);
|
|
||||||
assert.deepEqual(r.json.payload.step3, { task_completion_rate: 1, tasks_completed: 2, tasks_total: 2, blocker_count: 0 });
|
|
||||||
const m = runScript("plan2code-4-finalize", "specs.mjs", ["metrics", spec, "--step", "finalize", "--set", "verification_failures_found=0", "--set", "documentation_updates_needed=0", "--root", root]);
|
|
||||||
assert.equal(m.code, 0, m.stderr);
|
|
||||||
assert.equal(m.json.metrics.tasks_total, r.json.payload.step3.tasks_total);
|
|
||||||
assert.equal(m.json.metrics.tasks_completed, r.json.payload.step3.tasks_completed);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("feedback-payload: a bare name in both specs/ and specs--completed/ is ambiguous", () => {
|
|
||||||
const root = tmp("fb4");
|
|
||||||
const table = (rating) => `# O\n\n## User Feedback\n| Field | Value |\n|---|---|\n| Rating | ${rating} |\n| Reason | r |\n| Went Well | w |\n| Went Poorly | p |\n`;
|
|
||||||
write(root, "specs--completed/x/overview.md", table(3));
|
|
||||||
write(root, "specs/x/overview.md", table(7));
|
|
||||||
const sets = ["--set", "verification_failures_found=0", "--set", "documentation_updates_needed=0"];
|
|
||||||
const F = (...a) => runScript("plan2code-4-finalize", "feedback-payload.mjs", [...a, ...sets, "--out", path.join(root, "out"), "--root", root]);
|
|
||||||
const bare = F("build", "x");
|
|
||||||
assert.equal(bare.code, 5);
|
|
||||||
assert.equal(bare.json.error, "ambiguous-spec");
|
|
||||||
assert.match(bare.json.next, /specs\/x/);
|
|
||||||
const live = F("build", "specs/x");
|
|
||||||
assert.equal(live.code, 0, live.stderr);
|
|
||||||
assert.equal(live.json.payload.user_feedback.overall_rating, 7, "the exact path reads this run, not the old archive");
|
|
||||||
assert.equal(live.json.payload.step4.archival_succeeded, false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("feedback-payload: submit refuses an oversize URL when gh fails, and dry-run says so", () => {
|
|
||||||
const root = tmp("fb5");
|
|
||||||
write(root, "specs--completed/x/overview.md", `# O\n\n## User Feedback\n| Field | Value |\n|---|---|\n| Rating | 6 |\n| Reason | ${"long reason ".repeat(800)} |\n| Went Well | w |\n| Went Poorly | p |\n`);
|
|
||||||
const outDir = path.join(root, "out");
|
|
||||||
const b = runScript("plan2code-4-finalize", "feedback-payload.mjs", ["build", "x", "--set", "verification_failures_found=0", "--set", "documentation_updates_needed=0", "--out", outDir, "--root", root]);
|
|
||||||
assert.equal(b.json.oversize, true);
|
|
||||||
const dry = runScript("plan2code-4-finalize", "feedback-payload.mjs", ["submit", "--from", outDir, "--dry-run"]);
|
|
||||||
assert.equal(dry.code, 0);
|
|
||||||
assert.equal(dry.json.oversize, true);
|
|
||||||
assert.equal(dry.json.urlBytes, b.json.urlBytes);
|
|
||||||
// gh must never succeed here: no PATH but node's own folder (so gh is not
|
|
||||||
// found), and should one turn up anyway, an empty config, no token and a
|
|
||||||
// host that does not resolve.
|
|
||||||
const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^(path|gh_|github_token$)/i.test(k)));
|
|
||||||
Object.assign(env, { PATH: path.dirname(process.execPath), GH_CONFIG_DIR: tmp("fb5-gh"), GH_HOST: "gh.invalid", PLAN2CODE_NOW: NOW });
|
|
||||||
const r = spawnSync(process.execPath, [path.join(SKILLS, "plan2code-4-finalize", "scripts", "feedback-payload.mjs"), "submit", "--from", outDir], { cwd: root, encoding: "utf8", timeout: 70000, env });
|
|
||||||
assert.equal(r.status, 4, r.stderr);
|
|
||||||
const j = JSON.parse(r.stdout);
|
|
||||||
assert.equal(j.error, "oversize");
|
|
||||||
assert.match(j.next, /--truncate/);
|
|
||||||
assert.match(j.next, /gh/);
|
|
||||||
});
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
// Tests for plan2code-handoff's scripts/handoff-path.mjs.
|
|
||||||
//
|
|
||||||
// See skill-script-helpers.mjs for how these run.
|
|
||||||
|
|
||||||
import { test } from "node:test";
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { ROOT, SKILLS, NOW, runScript, tmp, write, read, gitInit, phase } from "./skill-script-helpers.mjs";
|
|
||||||
|
|
||||||
/* =========================================================== handoff-path.mjs */
|
|
||||||
|
|
||||||
test("handoff-path: timestamped name, no overwrite, git ignore check", () => {
|
|
||||||
const repo = tmp("handoff");
|
|
||||||
gitInit(repo);
|
|
||||||
const H = (...a) => runScript("plan2code-handoff", "handoff-path.mjs", a, { cwd: repo });
|
|
||||||
const first = H("--dir", "handoffs");
|
|
||||||
assert.equal(first.code, 0, first.stderr);
|
|
||||||
assert.equal(path.basename(first.json.path), "2026-08-03-1405-handoff.md");
|
|
||||||
assert.equal(first.json.created, true);
|
|
||||||
assert.equal(first.json.git.inRepo, true);
|
|
||||||
assert.equal(first.json.git.ignored, false);
|
|
||||||
assert.match(first.json.warning, /handoffs\//);
|
|
||||||
fs.writeFileSync(first.json.path, "x");
|
|
||||||
assert.equal(path.basename(H("--dir", "handoffs").json.path), "2026-08-03-1405-2-handoff.md");
|
|
||||||
write(repo, ".gitignore", "handoffs/\n");
|
|
||||||
assert.equal(H("--dir", "handoffs").json.git.ignored, true);
|
|
||||||
const temp = H();
|
|
||||||
assert.equal(temp.json.git.inRepo, false);
|
|
||||||
assert.equal(temp.json.git.ignored, null);
|
|
||||||
const dry = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "later", "--dry-run"], { cwd: repo });
|
|
||||||
assert.equal(dry.json.created, false);
|
|
||||||
assert.ok(!fs.existsSync(path.join(repo, "later")));
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ================================================= verification regressions */
|
|
||||||
|
|
||||||
test("handoff-path: the repo root itself is never the line to ignore", () => {
|
|
||||||
const repo = tmp("handoff2");
|
|
||||||
gitInit(repo);
|
|
||||||
const j = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "."], { cwd: repo }).json;
|
|
||||||
assert.equal(j.git.inRepo, true);
|
|
||||||
assert.equal(j.git.ignoreLine, "*-handoff.md");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("handoff-path: --dir naming an existing file is refused", () => {
|
|
||||||
const repo = tmp("handoff3");
|
|
||||||
write(repo, "notes.txt", "x");
|
|
||||||
const r = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "notes.txt"], { cwd: repo });
|
|
||||||
assert.equal(r.code, 5);
|
|
||||||
assert.equal(r.json.ok, false);
|
|
||||||
assert.equal(r.json.error, "not-a-folder");
|
|
||||||
assert.match(r.json.next, /--dir temp/);
|
|
||||||
assert.equal(runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "notes.txt", "--dry-run"], { cwd: repo }).code, 5, "dry-run refuses it too");
|
|
||||||
});
|
|
||||||
@@ -1,545 +0,0 @@
|
|||||||
// Tests for plan2code-0-pathfinder's scripts/pathfinder.mjs.
|
|
||||||
//
|
|
||||||
// See skill-script-helpers.mjs for how these run.
|
|
||||||
|
|
||||||
import { test } from "node:test";
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { ROOT, SKILLS, NOW, runScript, tmp, write, read, gitInit, phase } from "./skill-script-helpers.mjs";
|
|
||||||
|
|
||||||
/* ============================================================ pathfinder.mjs */
|
|
||||||
|
|
||||||
const B = "> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.";
|
|
||||||
|
|
||||||
function q(name, { type = "grill · HITL", state = "open", blocked = "none", claimed = "none", resolved = "none", locked = "no", answer = null, evidence = null, skipResolved = false } = {}) {
|
|
||||||
return [
|
|
||||||
B, "", `# ${name}`, "", `Type: ${type}`, `State: ${state}`, `Blocked by: ${blocked}`, `Claimed: ${claimed}`,
|
|
||||||
...(skipResolved ? [] : [`Resolved: ${resolved}`]), `Locked: ${locked}`, "", "## Question", "", `What about ${name}?`, "",
|
|
||||||
...(answer ? ["## Answer", "", answer, ""] : []),
|
|
||||||
...(evidence ? ["## Evidence", "", evidence, ""] : []),
|
|
||||||
].join("\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
const MAP = `${B}
|
|
||||||
|
|
||||||
# Map: audit-export
|
|
||||||
|
|
||||||
*Decisions live in \`questions/\` — one file each. This file is just the index.*
|
|
||||||
|
|
||||||
**Status:** Working
|
|
||||||
**Updated:** 2026-08-01
|
|
||||||
**Confidence:** Requirements-clarity 19/25 · Feasibility-technical 14/25 · Integration-points 20/25 · Risk-assessment 18/25
|
|
||||||
|
|
||||||
## Destination
|
|
||||||
|
|
||||||
A locked plan for exporting audit events.
|
|
||||||
|
|
||||||
## Ground rules
|
|
||||||
|
|
||||||
- \`AGENTS.md\` exists and governs.
|
|
||||||
|
|
||||||
## Question Checklist
|
|
||||||
|
|
||||||
<!-- Rebuilt from questions/ every session. -->
|
|
||||||
|
|
||||||
- [x] [Codebase context](./questions/00-codebase-context.md) — Node and Postgres; a long gist
|
|
||||||
that wraps onto a second line. *(2026-08-01)*
|
|
||||||
- [ ] [Export format](./questions/01-export-format.md)
|
|
||||||
- [ ] [Row-count
|
|
||||||
ceiling](./questions/02-row-count-ceiling.md)
|
|
||||||
- [ ] [Testing posture](./questions/03-testing-posture.md)
|
|
||||||
- [ ] [Delivery channel](./questions/04-delivery-channel.md)
|
|
||||||
- [ ] [Gone question](./questions/09-gone.md)
|
|
||||||
|
|
||||||
## Not yet specified
|
|
||||||
|
|
||||||
- How far back an export may reach.
|
|
||||||
|
|
||||||
## Out of scope
|
|
||||||
|
|
||||||
- Redesign of the schema.
|
|
||||||
`;
|
|
||||||
|
|
||||||
function mapFixture() {
|
|
||||||
const root = tmp("pf");
|
|
||||||
write(root, "AGENTS.md", "# AGENTS.md\n");
|
|
||||||
const pf = "specs/audit-export/pathfinder";
|
|
||||||
write(root, `${pf}/map.md`, MAP);
|
|
||||||
write(root, `${pf}/questions/00-codebase-context.md`, q("Codebase context", { type: "legwork · AFK", state: "resolved", claimed: "2026-08-01 09:00", resolved: "2026-08-01", answer: "Node.\n\n**Gist:** Node and Postgres." }));
|
|
||||||
// An answer under State: open (a crash after writing the answer): reconcile resolves it and backfills the date.
|
|
||||||
write(root, `${pf}/questions/01-export-format.md`, q("Export format", { claimed: "2026-08-02 10:00", locked: "yes", answer: "**Decision.** CSV.\n\n**Rejected**\n\n- *JSONL* - recipients use Excel.\n\n**Gist:** CSV with a BOM.", skipResolved: true }));
|
|
||||||
// A stale claim with no answer: reset.
|
|
||||||
write(root, `${pf}/questions/02-row-count-ceiling.md`, q("Row-count ceiling", { type: "research · AFK", state: "claimed", claimed: "2026-08-02 11:00", evidence: "- half done" }));
|
|
||||||
write(root, `${pf}/questions/03-testing-posture.md`, q("Testing posture"));
|
|
||||||
write(root, `${pf}/questions/04-delivery-channel.md`, q("Delivery channel", { blocked: "02" }));
|
|
||||||
write(root, `${pf}/questions/05-siem-push.md`, q("SIEM push", { state: "out-of-scope" }));
|
|
||||||
return { root, pf };
|
|
||||||
}
|
|
||||||
|
|
||||||
test("pathfinder reconcile: files win, dates backfill, stale claims reset, rows keep their words", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
const dry = P("reconcile", "audit-export", "--dry-run");
|
|
||||||
assert.equal(dry.code, 0, dry.stderr);
|
|
||||||
assert.equal(read(root, `${pf}/map.md`), MAP, "dry-run writes nothing");
|
|
||||||
const r = P("reconcile", "audit-export");
|
|
||||||
assert.deepEqual(r.json.repairs.map((x) => [x.nn, x.repair]), [["01", "state-resolved"], ["01", "resolved-backfilled"], ["02", "stale-claim-reset"]]);
|
|
||||||
assert.match(r.json.repairs[1].detail, /2026-08-02 \(from Claimed:\)/);
|
|
||||||
assert.deepEqual(r.json.refire.map((x) => x.nn), ["02"], "research with no Research complete line is re-fired");
|
|
||||||
assert.equal(r.json.refire[0].partialEvidence, true);
|
|
||||||
const map = read(root, `${pf}/map.md`);
|
|
||||||
assert.match(map, /- \[x\] \[Codebase context\]\(\.\/questions\/00-codebase-context\.md\) — Node and Postgres; a long gist\n that wraps onto a second line\. \*\(2026-08-01\)\*/, "an unchanged row keeps its own wrapped text");
|
|
||||||
assert.match(map, /- \[x\] \[Export format\]\(\.\/questions\/01-export-format\.md\) — CSV with a BOM\. \*\(2026-08-02\)\*/);
|
|
||||||
assert.match(map, /- \[ \] \[Row-count\n ceiling\]\(\.\/questions\/02-row-count-ceiling\.md\)/, "a wrapped link is still one row");
|
|
||||||
assert.match(map, /- \[!\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\) — Blocked by 02/);
|
|
||||||
assert.match(map, /- \[-\] \[SIEM push\]\(\.\/questions\/05-siem-push\.md\) — out of scope, see below/);
|
|
||||||
assert.ok(!map.includes("09-gone"), "a row with no file is dropped");
|
|
||||||
assert.match(map, /<!-- Rebuilt from questions\/ every session\. -->/);
|
|
||||||
const q1 = read(root, `${pf}/questions/01-export-format.md`);
|
|
||||||
assert.match(q1, /State: resolved\nBlocked by: none\nClaimed: 2026-08-02 10:00\nResolved: 2026-08-02\nLocked: yes/, "Resolved: inserted in schema order");
|
|
||||||
assert.match(read(root, `${pf}/questions/02-row-count-ceiling.md`), /State: open\nBlocked by: none\nClaimed: none/);
|
|
||||||
const again = P("reconcile", "audit-export");
|
|
||||||
assert.deepEqual([again.json.repairs.length, again.json.mapChanges.length, again.json.mapWritten], [0, 0, false], "idempotent");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder frontier, claim, resolve, rule-out", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
let f = P("frontier", `${pf}`).json;
|
|
||||||
assert.deepEqual(f.frontier.map((x) => x.nn), ["02", "03"]);
|
|
||||||
assert.deepEqual(f.blocked.map((x) => [x.nn, x.blockedBy.map((b) => b.nn)]), [["04", ["02"]]]);
|
|
||||||
assert.equal(f.nextNN, "10", "09 was linked from the map before reconcile dropped its row: never reissued");
|
|
||||||
assert.match(read(root, `${pf}/map.md`), /^\*\*Confidence:\*\*.*\n\*\*Next NN:\*\* 10$/m, "reconcile keeps the high-water mark at the end of the header block");
|
|
||||||
assert.deepEqual(f.counts, { resolved: 2, total: 5, outOfScope: 1, fog: 1 });
|
|
||||||
assert.deepEqual(f.drift, []);
|
|
||||||
assert.equal(P("claim", "audit-export", "04").code, 5, "blocked");
|
|
||||||
assert.equal(P("claim", "audit-export", "05").code, 5, "out of scope");
|
|
||||||
assert.equal(P("claim", "audit-export", "77").code, 3);
|
|
||||||
const c = P("claim", "audit-export", "2");
|
|
||||||
assert.equal(c.code, 0, c.stderr);
|
|
||||||
assert.equal(c.json.claimed, NOW);
|
|
||||||
assert.match(read(root, `${pf}/questions/02-row-count-ceiling.md`), /State: claimed\nBlocked by: none\nClaimed: 2026-08-03 14:05/);
|
|
||||||
assert.match(read(root, `${pf}/map.md`), /- \[\/\] \[Row-count\n ceiling\]/);
|
|
||||||
assert.equal(P("claim", "audit-export", "03").json.error, "claim-open", "one claim at a time");
|
|
||||||
assert.equal(P("resolve", "audit-export", "02").json.error, "no-answer");
|
|
||||||
const qp = path.join(root, pf, "questions/02-row-count-ceiling.md");
|
|
||||||
fs.appendFileSync(qp, "\n## Answer\n\nFacts.\n");
|
|
||||||
assert.equal(P("resolve", "audit-export", "02").json.error, "no-gist");
|
|
||||||
fs.appendFileSync(qp, "\n**Gist:** 2M rows at the 99th percentile.\n");
|
|
||||||
const res = P("resolve", "audit-export", "02");
|
|
||||||
assert.equal(res.code, 0, res.stderr);
|
|
||||||
assert.deepEqual(res.json.unblocked, [{ nn: "04", name: "Delivery channel" }]);
|
|
||||||
const map = read(root, `${pf}/map.md`);
|
|
||||||
assert.match(map, /- \[x\] \[Row-count ceiling\]\(\.\/questions\/02-row-count-ceiling\.md\) — 2M rows at the 99th percentile\. \*\(2026-08-03\)\*/);
|
|
||||||
assert.match(map, /- \[ \] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\)\n/, "the Blocked by tail goes with the [!] marker");
|
|
||||||
assert.match(map, /^\*\*Updated:\*\* 2026-08-03$/m);
|
|
||||||
const ro = P("rule-out", "audit-export", "03", "--reason", "testing is owned elsewhere");
|
|
||||||
assert.equal(ro.code, 0, ro.stderr);
|
|
||||||
assert.match(read(root, `${pf}/questions/03-testing-posture.md`), /State: out-of-scope[\s\S]*## Question\n\nOut of scope: testing is owned elsewhere/);
|
|
||||||
assert.match(read(root, `${pf}/map.md`), /## Out of scope\n\n- Redesign of the schema\.\n- \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\) — testing is owned elsewhere/);
|
|
||||||
assert.equal(P("rule-out", "audit-export", "04").code, 2, "--reason is required");
|
|
||||||
assert.equal(P("rule-out", "audit-export", "00", "--reason", "x").code, 5, "a resolved decision is not ruled out");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder trail: exact footer for forms A, B and C", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
P("claim", "audit-export", "03");
|
|
||||||
const b = P("trail", "audit-export", "--form", "B", "--item", "Q1 Types", "--item", "Q2 Cadence", "--text");
|
|
||||||
assert.equal(b.code, 0, b.stderr);
|
|
||||||
assert.equal(b.stdout, [
|
|
||||||
"🧭 audit-export · Working · 2/5 cleared",
|
|
||||||
" START ●━●··○━◉··⊘··⊝ ····⚑",
|
|
||||||
" ● done · ◉ here · ○ open · ⊘ blocked · ⊝ out of scope · ⚑ destination · ~1 fog",
|
|
||||||
" 1 Codebase context ✔ · 2 Export format ✔ · 3 Row-count ceiling · 4 Testing posture ◀ here",
|
|
||||||
" 5 Delivery channel (blocked:3) · 6 SIEM push (out of scope)",
|
|
||||||
" Confidence: not yet — Feasibility still needs work.",
|
|
||||||
"",
|
|
||||||
"WAITING ON YOU · answer here, in this conversation:",
|
|
||||||
"Q1 Types · Q2 Cadence",
|
|
||||||
"",
|
|
||||||
].join("\n"));
|
|
||||||
assert.equal(P("trail", "audit-export", "--form", "B").code, 2, "Form B names its items");
|
|
||||||
assert.equal(P("trail", "audit-export", "--form", "B", "--item", "1", "--item", "2", "--item", "3", "--item", "4").code, 5, "three-probe cap");
|
|
||||||
assert.equal(P("trail", "audit-export", "--form", "C").json.error, "claim-open", "no menu while a claim is open");
|
|
||||||
const a = P("trail", "audit-export", "--form", "A", "--text").stdout;
|
|
||||||
assert.ok(a.endsWith("NEXT STEP · start a new conversation and run:\n`/plan2code-0-pathfinder specs/audit-export/pathfinder --web`\n"), a);
|
|
||||||
fs.appendFileSync(path.join(root, pf, "questions/03-testing-posture.md"), "\n## Answer\n\nUnit; `Run after each phase`; `Critical paths`.\n\n**Gist:** Unit tests, run after each phase.\n");
|
|
||||||
P("resolve", "audit-export", "03");
|
|
||||||
const c = P("trail", "audit-export", "--form", "C", "--resolved-this-session", "3");
|
|
||||||
assert.equal(c.code, 0, c.stderr);
|
|
||||||
assert.ok(c.json.text.endsWith("OR START FRESH · new conversation, paste:\n`/plan2code-0-pathfinder specs/audit-export/pathfinder --web`"));
|
|
||||||
assert.deepEqual(c.json.menu.options.map((o) => o.label), ["Row-count ceiling", "Start fresh"]);
|
|
||||||
assert.equal(c.json.menu.recommended, "Start fresh", "the checkpoint after ~3 decisions");
|
|
||||||
assert.equal(P("trail", "audit-export", "--form", "C").json.menu.recommended, "Row-count ceiling");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder trail: a cleared map arrives; init first only while AGENTS.md is still missing", () => {
|
|
||||||
const root = tmp("pfc");
|
|
||||||
const pf = "specs/done/pathfinder";
|
|
||||||
write(root, `${pf}/map.md`, MAP.replace("**Status:** Working", "**Status:** Cleared").replace("- `AGENTS.md` exists and governs.", "- `AGENTS.md` is absent; continued without it.").replace(/## Not yet specified\n\n- How far back an export may reach\.\n/, "## Not yet specified\n\n").replace("Feasibility-technical 14/25", "Feasibility-technical 22/25"));
|
|
||||||
write(root, `${pf}/questions/00-codebase-context.md`, q("Codebase context", { state: "resolved", resolved: "2026-08-01", answer: "**Gist:** Node." }));
|
|
||||||
write(root, `${pf}/questions/01-export-format.md`, q("Export format", { state: "resolved", resolved: "2026-08-02", answer: "**Gist:** CSV." }));
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
P("reconcile", "done");
|
|
||||||
assert.equal(P("trail", "done", "--form", "A", "--text").stdout, [
|
|
||||||
"🧭 done · Cleared · 2/2 cleared",
|
|
||||||
" START ●━●━⚑ arrived",
|
|
||||||
" Confidence: solid, but Requirements, Risk are borderline.",
|
|
||||||
"",
|
|
||||||
"NEXT STEP · start a new conversation and run:",
|
|
||||||
"`/plan2code-init`, then `/plan2code-1-plan --web`",
|
|
||||||
"",
|
|
||||||
].join("\n"));
|
|
||||||
write(root, "AGENTS.md", "# AGENTS.md\n");
|
|
||||||
assert.match(P("trail", "done", "--form", "A", "--text").stdout, /run:\n`\/plan2code-1-plan --web`\n$/);
|
|
||||||
assert.equal(P("trail", "done", "--form", "C").code, 5, "no menu on a cleared map");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder gate: mechanical checks and hard caps", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
let g = P("gate", "audit-export").json;
|
|
||||||
assert.equal(g.mechanicalPass, false);
|
|
||||||
const failed = g.checks.filter((c) => !c.pass).map((c) => c.id);
|
|
||||||
assert.deepEqual(failed, ["no-open-claimed-blocked", "fog-empty", "hard-caps", "scores-at-least-18"]);
|
|
||||||
assert.ok(g.caps.some((c) => c.dimension === "Requirements" && /not resolved/.test(c.why)));
|
|
||||||
assert.ok(g.caps.some((c) => c.dimension === "Risk" && /Export format records no consequences/.test(c.why)));
|
|
||||||
assert.equal(g.planDraftPath, "specs/audit-export/PLAN-DRAFT-20260803.md");
|
|
||||||
// Settle everything.
|
|
||||||
const qd = path.join(root, pf, "questions");
|
|
||||||
fs.writeFileSync(path.join(qd, "01-export-format.md"), q("Export format", { state: "resolved", resolved: "2026-08-02", locked: "yes", answer: "CSV.\n\n**Consequences**\n\n- Excel.\n\n**Gist:** CSV." }));
|
|
||||||
fs.writeFileSync(path.join(qd, "02-row-count-ceiling.md"), q("Row-count ceiling", { type: "research · AFK", state: "resolved", resolved: "2026-08-02", answer: "**Gist:** 2M." }));
|
|
||||||
fs.writeFileSync(path.join(qd, "03-testing-posture.md"), q("Testing posture", { state: "resolved", resolved: "2026-08-02", answer: "Unit and integration. `Dedicated phase only`. `Moderate (~60-80%)`.\n\n**Gist:** Unit." }));
|
|
||||||
fs.writeFileSync(path.join(qd, "04-delivery-channel.md"), q("Delivery channel", { state: "resolved", resolved: "2026-08-03", blocked: "02", answer: "**Gist:** Link." }));
|
|
||||||
const mp = path.join(root, pf, "map.md");
|
|
||||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- How far back an export may reach.\n", "").replace("Feasibility-technical 14/25", "Feasibility-technical 20/25"));
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
g = P("gate", "audit-export").json;
|
|
||||||
assert.deepEqual(g.checks.filter((c) => !c.pass).map((c) => c.id), ["hard-caps"]);
|
|
||||||
assert.match(g.caps[0].why, /research 02 Row-count ceiling is resolved with an empty ## Evidence/);
|
|
||||||
fs.appendFileSync(path.join(qd, "02-row-count-ceiling.md"), "\n## Evidence\n\n- Query plan.\n\n**Research complete:** 2026-08-02\n");
|
|
||||||
g = P("gate", "audit-export").json;
|
|
||||||
assert.equal(g.mechanicalPass, true, JSON.stringify(g.checks));
|
|
||||||
assert.ok(g.judgment.length >= 2, "the gate names what stays judgment");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder lint: loop tokens, checkboxes, reserved names, schema, cycles, scraper bait", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
let l = P("lint", "audit-export");
|
|
||||||
assert.equal(l.code, 0, JSON.stringify(l.json.problems));
|
|
||||||
const qd = path.join(root, pf, "questions");
|
|
||||||
fs.appendFileSync(path.join(qd, "03-testing-posture.md"), "\n- [ ] a checkbox\nTASK_COMPLETE\n");
|
|
||||||
fs.writeFileSync(path.join(qd, "06-loop-a.md"), q("Loop A", { blocked: "07" }));
|
|
||||||
fs.writeFileSync(path.join(qd, "07-loop-b.md"), q("Loop B", { blocked: "06", type: "chat · HITL" }));
|
|
||||||
write(root, `${pf}/overview.md`, "nope");
|
|
||||||
write(root, `${pf}/briefs/brief-20260803.md`, "Requirements 18 and 90%\n");
|
|
||||||
write(root, "specs/audit-export/PLAN-DRAFT-20260803.md", "**Charted by:** `/plan2code-0-pathfinder`\n**Confidence:** 85%\n| Requirements | 11 |\n");
|
|
||||||
l = P("lint", "audit-export");
|
|
||||||
assert.equal(l.code, 4);
|
|
||||||
const msgs = l.json.problems.map((p) => `${p.file}: ${p.message}`).join("\n");
|
|
||||||
for (const re of [/03-testing-posture\.md: has a checkbox/, /03-testing-posture\.md: contains the loop completion token TASK_COMPLETE/, /cycle 06 -> 07 -> 06|cycle 07 -> 06 -> 07/, /Type: "chat · HITL"/, /overview\.md is a reserved name/, /brief-20260803\.md: metrics-scraper bait \(bare Requirements/, /brief-20260803\.md: contains %/, /PLAN-DRAFT-20260803\.md: metrics-scraper bait \(overall confidence with %/, /PLAN-DRAFT-20260803\.md: metrics-scraper bait \(bare Requirements/]) {
|
|
||||||
assert.match(msgs, re);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder brief-data: range filtering, frontier notes, plain sections", () => {
|
|
||||||
const { root } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
const today = P("brief-data", "audit-export").json;
|
|
||||||
assert.equal(today.file, "specs/audit-export/pathfinder/briefs/brief-20260803.md");
|
|
||||||
assert.deepEqual(today.decided, []);
|
|
||||||
assert.equal(today.note, "No decisions were recorded in this period.");
|
|
||||||
const full = P("brief-data", "audit-export", "--range", "full").json;
|
|
||||||
assert.deepEqual(full.decided.map((d) => d.name), ["Codebase context", "Export format"]);
|
|
||||||
assert.deepEqual(full.decided[1].rejected, ["*JSONL* - recipients use Excel."]);
|
|
||||||
assert.equal(full.decided[1].hardToReverse, true);
|
|
||||||
assert.equal(full.progress, "2 of 5 decisions made");
|
|
||||||
assert.deepEqual(full.waiting, [{ name: "Delivery channel", waitingOn: ["Row-count ceiling"] }]);
|
|
||||||
assert.deepEqual(full.fog, ["How far back an export may reach."]);
|
|
||||||
assert.deepEqual(full.ruledOut, ["Redesign of the schema."]);
|
|
||||||
assert.equal(full.confidence, "Confidence: not yet — Feasibility still needs work.");
|
|
||||||
const since = P("brief-data", "audit-export", "--range", "since:2026-08-02").json;
|
|
||||||
assert.deepEqual(since.decided.map((d) => d.name), ["Export format"]);
|
|
||||||
assert.deepEqual(P("brief-data", "audit-export", "--range", "2026-08-01..2026-08-01").json.decided.map((d) => d.name), ["Codebase context"]);
|
|
||||||
assert.equal(P("brief-data", "audit-export", "--range", "2026-08-05..2026-08-01").code, 2);
|
|
||||||
assert.equal(P("brief-data", "audit-export", "--range", "yesterday").code, 2);
|
|
||||||
assert.equal(P("brief-data", "nope").code, 3);
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ================================================= verification regressions */
|
|
||||||
|
|
||||||
test("pathfinder: a ## Answer inside a fenced sketch is content, not an answer", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const qd = path.join(root, pf, "questions");
|
|
||||||
fs.writeFileSync(path.join(qd, "03-testing-posture.md"), q("Testing posture", { type: "sketch · HITL", evidence: "```markdown\n## Answer\n\n**Gist:** fake\n```" }));
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
const r = P("reconcile", "audit-export");
|
|
||||||
assert.ok(!r.json.repairs.some((x) => x.nn === "03"), JSON.stringify(r.json.repairs));
|
|
||||||
assert.match(read(root, `${pf}/questions/03-testing-posture.md`), /State: open/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder reconcile: an unrepairable file is skipped and named, nothing half-written, its row kept", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
write(root, `${pf}/questions/07-bare.md`, `${B}\n\n# Bare\n\n## Answer\n\nYes.\n`);
|
|
||||||
const mp = path.join(root, pf, "map.md");
|
|
||||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- [ ] [Gone question]", "- [ ] [Bare](./questions/07-bare.md)\n- [ ] [Gone question]"));
|
|
||||||
const r = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["reconcile", "audit-export", "--root", root]);
|
|
||||||
assert.equal(r.code, 0, r.stderr);
|
|
||||||
assert.deepEqual(r.json.findings.map((f) => [f.file, f.finding]), [["07-bare.md", "unrepairable"]]);
|
|
||||||
assert.match(read(root, `${pf}/questions/01-export-format.md`), /State: resolved/, "the other repairs still landed");
|
|
||||||
assert.equal(read(root, `${pf}/questions/07-bare.md`), `${B}\n\n# Bare\n\n## Answer\n\nYes.\n`, "left untouched");
|
|
||||||
assert.ok(!r.json.mapChanges.some((c) => c.file === "07-bare.md"), JSON.stringify(r.json.mapChanges));
|
|
||||||
assert.match(read(root, `${pf}/map.md`), /^- \[.\] \[Bare\]\(\.\/questions\/07-bare\.md\)$/m, "its row survives");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder reconcile: rows stay in place among grouping lines, a re-opened row loses its gist, stray claims clear", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const mp = path.join(root, pf, "map.md");
|
|
||||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- [ ] [Export format]", "### Group two\n\n- [x] [Export format]").replace("- [ ] [Export format](./questions/01-export-format.md)", "- [x] [Export format](./questions/01-export-format.md) — old gist *(2026-07-01)*"));
|
|
||||||
fs.writeFileSync(path.join(root, pf, "questions/01-export-format.md"), q("Export format", { claimed: "2026-08-02 10:00" }));
|
|
||||||
const r = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["reconcile", "audit-export", "--root", root]);
|
|
||||||
assert.ok(r.json.repairs.some((x) => x.nn === "01" && x.repair === "stray-claim-cleared"));
|
|
||||||
const map = read(root, `${pf}/map.md`);
|
|
||||||
assert.match(map, /### Group two\n\n- \[ \] \[Export format\]\(\.\/questions\/01-export-format\.md\)\n/, "the group heading keeps its place and the row its old tail is gone");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder gate: testing posture by keyword (never from Rejected), research-style consequences count", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const qd = path.join(root, pf, "questions");
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
fs.writeFileSync(path.join(qd, "03-testing-posture.md"), q("Testing posture", { state: "resolved", resolved: "2026-08-02", answer: "Unit + integration, run after each phase, moderate coverage.\n\n**Gist:** Unit." }));
|
|
||||||
fs.writeFileSync(path.join(qd, "01-export-format.md"), q("Export format", { state: "resolved", resolved: "2026-08-02", locked: "yes", answer: "### What this implies\n\n- Excel only.\n\n**Gist:** CSV." }));
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
let caps = P("gate", "audit-export").json.caps;
|
|
||||||
assert.ok(!caps.some((c) => c.dimension === "Requirements"), JSON.stringify(caps));
|
|
||||||
assert.ok(!caps.some((c) => c.dimension === "Risk"), JSON.stringify(caps));
|
|
||||||
fs.writeFileSync(path.join(qd, "03-testing-posture.md"), q("Testing posture", { state: "resolved", resolved: "2026-08-02", answer: "Unit tests.\n\n**Rejected**\n\n- Run after each phase with Moderate coverage: too slow.\n\n**Gist:** Unit." }));
|
|
||||||
caps = P("gate", "audit-export").json.caps;
|
|
||||||
assert.ok(caps.some((c) => c.dimension === "Requirements" && /cadence/.test(c.why)), "a cadence named only as rejected does not count");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder: Form C needs a frontier; names come from the rows; NN is never handed out twice", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
const mp = path.join(root, pf, "map.md");
|
|
||||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("[Testing posture](", "[How we test]("));
|
|
||||||
const c = P("trail", "audit-export", "--form", "C").json;
|
|
||||||
assert.deepEqual(c.menu.options.map((o) => o.label), ["Row-count ceiling", "How we test", "Start fresh"]);
|
|
||||||
fs.rmSync(path.join(root, pf, "questions/05-siem-push.md"));
|
|
||||||
// Without the high-water line (an older map), the links alone still count.
|
|
||||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace(/^\*\*Next NN:\*\*.*\n/m, ""));
|
|
||||||
assert.equal(P("frontier", "audit-export").json.nextNN, "06", "05 is still linked from the map");
|
|
||||||
const qd = path.join(root, pf, "questions");
|
|
||||||
fs.writeFileSync(path.join(qd, "02-row-count-ceiling.md"), q("Row-count ceiling", { blocked: "04" }));
|
|
||||||
fs.writeFileSync(path.join(qd, "03-testing-posture.md"), q("Testing posture", { blocked: "04 (needs the channel)" }));
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
const none = P("trail", "audit-export", "--form", "C");
|
|
||||||
assert.equal(none.code, 5);
|
|
||||||
assert.equal(none.json.error, "no-frontier");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder lint: map %, brief scores and checkboxes, Planning Metrics in a pathfinder draft", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["reconcile", "audit-export", "--root", root]);
|
|
||||||
const mp = path.join(root, pf, "map.md");
|
|
||||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8") + "\n80% sure.\n");
|
|
||||||
write(root, `${pf}/briefs/brief-20260803.md`, "Solid at 22/25.\n- [ ] todo\n");
|
|
||||||
write(root, "specs/audit-export/PLAN-DRAFT-20260803.md", "**Charted by:** `/plan2code-0-pathfinder`\n\n## Planning Metrics\n");
|
|
||||||
const l = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["lint", "audit-export", "--root", root]).json;
|
|
||||||
const msgs = l.problems.map((p) => `${p.level} ${p.message}`).join("\n");
|
|
||||||
assert.match(msgs, /warn contains %; the map/);
|
|
||||||
assert.match(msgs, /error contains a raw NN\/25 score/);
|
|
||||||
assert.match(msgs, /error has a checkbox line/);
|
|
||||||
assert.match(msgs, /error has a ## Planning Metrics section/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder brief-data: calendar dates only, no future since, no NNs or links in what a brief prints", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
assert.equal(P("brief-data", "audit-export", "--range", "since:2026-13-99").json.error, "bad-date");
|
|
||||||
assert.equal(P("brief-data", "audit-export", "--range", "since:2026-09-01").code, 2);
|
|
||||||
const mp = path.join(root, pf, "map.md");
|
|
||||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- Redesign of the schema.", "- [SIEM push](./questions/05-siem-push.md) — not ours.\n- Nothing yet."));
|
|
||||||
fs.writeFileSync(path.join(root, pf, "questions/04-delivery-channel.md"), q("Delivery channel", { blocked: "09" }));
|
|
||||||
const j = P("brief-data", "audit-export", "--range", "full").json;
|
|
||||||
assert.deepEqual(j.ruledOut, ["SIEM push — not ours."]);
|
|
||||||
assert.deepEqual(j.waiting.find((w) => w.name === "Delivery channel").waitingOn, ["a question that no longer exists"]);
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ===================================================== review-fix regressions */
|
|
||||||
|
|
||||||
test("pathfinder: claim, resolve and rule-out honour --dry-run", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
const snap = () => fs.readdirSync(path.join(root, pf, "questions")).map((n) => read(root, `${pf}/questions/${n}`)).concat(read(root, `${pf}/map.md`));
|
|
||||||
const before = snap();
|
|
||||||
const c = P("claim", "audit-export", "03", "--dry-run");
|
|
||||||
assert.equal(c.code, 0, c.stderr);
|
|
||||||
assert.deepEqual([c.json.dryRun, c.json.mapWritten], [true, false]);
|
|
||||||
assert.deepEqual(snap(), before, "claim --dry-run leaves every file unchanged");
|
|
||||||
fs.appendFileSync(path.join(root, pf, "questions/03-testing-posture.md"), "\n## Answer\n\nUnit.\n\n**Gist:** Unit.\n");
|
|
||||||
const withAnswer = snap();
|
|
||||||
const r = P("resolve", "audit-export", "03", "--dry-run");
|
|
||||||
assert.equal(r.code, 0, r.stderr);
|
|
||||||
assert.deepEqual([r.json.dryRun, r.json.mapWritten], [true, false]);
|
|
||||||
assert.deepEqual(snap(), withAnswer, "resolve --dry-run writes nothing");
|
|
||||||
const o = P("rule-out", "audit-export", "02", "--reason", "not ours", "--dry-run");
|
|
||||||
assert.equal(o.code, 0, o.stderr);
|
|
||||||
assert.deepEqual([o.json.dryRun, o.json.mapWritten], [true, false]);
|
|
||||||
assert.deepEqual(snap(), withAnswer, "rule-out --dry-run writes nothing");
|
|
||||||
const real = P("claim", "audit-export", "02");
|
|
||||||
assert.deepEqual([real.json.dryRun, real.json.mapWritten], [false, true]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder: a deleted top NN is never reissued, linked from an answer or not", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
const qd = path.join(root, pf, "questions");
|
|
||||||
const mp = path.join(root, pf, "map.md");
|
|
||||||
// Start from a map with no high-water line and no stale 09 link: reconcile adds the line.
|
|
||||||
fs.writeFileSync(mp, MAP.replace("- [ ] [Gone question](./questions/09-gone.md)\n", ""));
|
|
||||||
fs.writeFileSync(path.join(qd, "06-subsumed.md"), q("Subsumed"));
|
|
||||||
let r = P("reconcile", "audit-export");
|
|
||||||
assert.deepEqual(r.json.mapChanges.find((c) => c.change === "next-nn"), { change: "next-nn", from: null, to: "07" });
|
|
||||||
assert.match(read(root, `${pf}/map.md`), /^\*\*Next NN:\*\* 07$/m);
|
|
||||||
// resolve.md: delete the subsumed file, reconcile drops its row, the absorbing answer links to it.
|
|
||||||
fs.rmSync(path.join(qd, "06-subsumed.md"));
|
|
||||||
fs.appendFileSync(path.join(qd, "04-delivery-channel.md"), "\n## Answer\n\nAbsorbed [Subsumed](./questions/06-subsumed.md).\n\n**Gist:** Link.\n");
|
|
||||||
r = P("reconcile", "audit-export");
|
|
||||||
assert.ok(r.json.mapChanges.some((c) => c.change === "row-dropped" && c.file === "06-subsumed.md"));
|
|
||||||
assert.ok(!read(root, `${pf}/map.md`).includes("06-subsumed"), "the map no longer links it");
|
|
||||||
assert.equal(P("frontier", "audit-export").json.nextNN, "07", "linked from an answer");
|
|
||||||
// Even with the answer's link gone, the high-water mark holds.
|
|
||||||
fs.writeFileSync(path.join(qd, "04-delivery-channel.md"), q("Delivery channel", { blocked: "02" }));
|
|
||||||
assert.equal(P("frontier", "audit-export").json.nextNN, "07", "the **Next NN:** line");
|
|
||||||
assert.equal(P("reconcile", "audit-export").json.nextNN, "07", "reconcile never lowers it");
|
|
||||||
assert.equal(P("lint", "audit-export").code, 0, "lint accepts the line");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder: a name with brackets round-trips; reconcile is stable", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
write(root, `${pf}/questions/06-retention.md`, q("Retention [legal] hold"));
|
|
||||||
for (let i = 0; i < 3; i++) assert.equal(P("reconcile", "audit-export").code, 0);
|
|
||||||
const map = read(root, `${pf}/map.md`);
|
|
||||||
assert.equal(map.split("\n").filter((l) => l.includes("06-retention.md")).length, 1, map);
|
|
||||||
assert.match(map, /^- \[ \] \[Retention \[legal\] hold\]\(\.\/questions\/06-retention\.md\)$/m);
|
|
||||||
assert.deepEqual(P("frontier", "audit-export").json.drift, []);
|
|
||||||
assert.equal(P("reconcile", "audit-export").json.mapWritten, false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder: an author's sub-bullet under a row survives resolve, rule-out and a marker change", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
const mp = path.join(root, pf, "map.md");
|
|
||||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8")
|
|
||||||
.replace("- [ ] [Testing posture](./questions/03-testing-posture.md)", "- [ ] [Testing posture](./questions/03-testing-posture.md)\n - note: ask Dana first")
|
|
||||||
.replace("- [ ] [Delivery channel](./questions/04-delivery-channel.md)", "- [ ] [Delivery channel](./questions/04-delivery-channel.md)\n - note: depends on the volume\n and wraps"));
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
let map = read(root, `${pf}/map.md`);
|
|
||||||
assert.match(map, /- \[!\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\) — Blocked by 02\n - note: depends on the volume\n and wraps\n/, "kept under a regenerated [!] row");
|
|
||||||
P("claim", "audit-export", "03");
|
|
||||||
fs.appendFileSync(path.join(root, pf, "questions/03-testing-posture.md"), "\n## Answer\n\nUnit.\n\n**Gist:** Unit tests only.\n");
|
|
||||||
assert.equal(P("resolve", "audit-export", "03").code, 0);
|
|
||||||
map = read(root, `${pf}/map.md`);
|
|
||||||
assert.match(map, /- \[x\] \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\) — Unit tests only\. \*\(2026-08-03\)\*\n - note: ask Dana first\n/, "kept on resolve");
|
|
||||||
assert.equal(P("rule-out", "audit-export", "04", "--reason", "not ours").code, 0);
|
|
||||||
map = read(root, `${pf}/map.md`);
|
|
||||||
assert.match(map, /- \[-\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\) — out of scope, see below\n - note: depends on the volume\n and wraps\n/, "kept on rule-out");
|
|
||||||
assert.deepEqual(P("frontier", "audit-export").json.drift, []);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder: AGENTS.md absent reads in the canonical and the skill's own wording", () => {
|
|
||||||
for (const line of ["- `AGENTS.md` is absent.", "- No `AGENTS.md`.", "- No AGENTS.md; init skipped."]) {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
fs.rmSync(path.join(root, "AGENTS.md"));
|
|
||||||
const mp = path.join(root, pf, "map.md");
|
|
||||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- `AGENTS.md` exists and governs.", line));
|
|
||||||
const g = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["gate", "audit-export", "--root", root]).json;
|
|
||||||
assert.deepEqual([g.agentsAbsent, g.initFirst], [true, true], line);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder lint: a failure carries error, message and next, on stderr too", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["reconcile", "audit-export", "--root", root]);
|
|
||||||
fs.appendFileSync(path.join(root, pf, "questions/03-testing-posture.md"), "\n- [ ] a checkbox\n");
|
|
||||||
const l = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["lint", "audit-export", "--root", root]);
|
|
||||||
assert.equal(l.code, 4);
|
|
||||||
assert.deepEqual([l.json.ok, l.json.error, l.json.message, l.json.next], [false, "lint-failed", "lint found 1 error.", "Fix each error in problems, then rerun lint."]);
|
|
||||||
assert.equal(l.json.errors, 1);
|
|
||||||
assert.equal(l.json.problems.filter((p) => p.level === "error").length, 1);
|
|
||||||
assert.match(l.stderr, /^error: lint found 1 error\.\nnext: Fix each error in problems, then rerun lint\.\n$/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder lint: densely blocked questions check in linear time", () => {
|
|
||||||
const root = tmp("pfd");
|
|
||||||
const pf = "specs/dense/pathfinder";
|
|
||||||
write(root, `${pf}/map.md`, MAP);
|
|
||||||
write(root, `${pf}/questions/00-codebase-context.md`, q("Codebase context", { type: "legwork · AFK", state: "resolved", resolved: "2026-08-01", answer: "**Gist:** Node." }));
|
|
||||||
for (let i = 1; i < 40; i++) {
|
|
||||||
const nn = String(i).padStart(2, "0");
|
|
||||||
const blocked = i === 1 ? "00" : [i - 1, i - 2].map((n) => String(n).padStart(2, "0")).join(", ");
|
|
||||||
write(root, `${pf}/questions/${nn}-q${nn}.md`, q(`Q ${nn}`, { blocked }));
|
|
||||||
}
|
|
||||||
const t0 = Date.now();
|
|
||||||
const l = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["lint", "dense", "--root", root]);
|
|
||||||
const ms = Date.now() - t0;
|
|
||||||
assert.ok(!(l.json.problems || []).some((p) => /cycle/.test(p.message)), JSON.stringify(l.json.problems));
|
|
||||||
assert.ok(ms < 2000, `lint took ${ms} ms`);
|
|
||||||
// A cycle is still found, once, in the same format.
|
|
||||||
write(root, `${pf}/questions/01-q01.md`, q("Q 01", { blocked: "39" }));
|
|
||||||
const c = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["lint", "dense", "--root", root]).json;
|
|
||||||
const cycles = c.problems.filter((p) => /cycle/.test(p.message));
|
|
||||||
assert.ok(cycles.length >= 1, JSON.stringify(c.problems));
|
|
||||||
assert.match(cycles[0].message, /^Blocked by: cycle (\d\d)( -> \d\d)+ -> \1;/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder: a one-digit NN is question 0N everywhere, and lint asks for the rename", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
write(root, `${pf}/questions/6-short.md`, q("Short"));
|
|
||||||
write(root, `${pf}/questions/07-after.md`, q("After", { blocked: "06" }));
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
const f = P("frontier", "audit-export").json;
|
|
||||||
assert.ok(f.frontier.some((x) => x.nn === "06" && x.name === "Short"), JSON.stringify(f.frontier));
|
|
||||||
assert.deepEqual(f.blocked.find((x) => x.nn === "07").blockedBy, [{ nn: "06", name: "Short", state: "open" }]);
|
|
||||||
assert.equal(P("claim", "audit-export", "6").json.nn, "06");
|
|
||||||
const l = P("lint", "audit-export").json;
|
|
||||||
assert.ok(l.problems.some((p) => p.level === "error" && /6-short\.md$/.test(p.file) && /rename it to 06-short\.md/.test(p.message)), JSON.stringify(l.problems));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder: a duplicate map row is reported as drift and dropped by name", () => {
|
|
||||||
const { root, pf } = mapFixture();
|
|
||||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
|
||||||
P("reconcile", "audit-export");
|
|
||||||
const mp = path.join(root, pf, "map.md");
|
|
||||||
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- [ ] [Testing posture](./questions/03-testing-posture.md)", "- [ ] [Testing posture](./questions/03-testing-posture.md)\n- [ ] [Testing again](./questions/03-testing-posture.md)"));
|
|
||||||
assert.ok(P("frontier", "audit-export").json.drift.includes("map row 03-testing-posture.md appears 2 times"));
|
|
||||||
const r = P("reconcile", "audit-export");
|
|
||||||
assert.deepEqual(r.json.mapChanges, [{ change: "row-dropped", file: "03-testing-posture.md", name: "Testing again", why: "duplicate row" }]);
|
|
||||||
assert.equal(read(root, `${pf}/map.md`).split("\n").filter((l) => l.includes("03-testing-posture.md")).length, 1);
|
|
||||||
assert.deepEqual(P("frontier", "audit-export").json.drift, []);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("pathfinder lint: the chart.md map template lints clean", () => {
|
|
||||||
const chart = fs.readFileSync(path.join(SKILLS, "plan2code-0-pathfinder", "references", "chart.md"), "utf8");
|
|
||||||
const template = chart.split("## The `map.md` template")[1].match(/```markdown\r?\n([\s\S]*?)\r?\n```/)[1];
|
|
||||||
assert.match(template, /^\*\*Next NN:\*\* \d+$/m, "the template carries the high-water line");
|
|
||||||
const root = tmp("pft");
|
|
||||||
write(root, "specs/audit-log-export/pathfinder/map.md", template + "\n");
|
|
||||||
const l = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["lint", "audit-log-export", "--root", root]);
|
|
||||||
assert.equal(l.code, 0, JSON.stringify(l.json.problems));
|
|
||||||
assert.deepEqual([l.json.errors, l.json.warnings], [0, 0], JSON.stringify(l.json.problems));
|
|
||||||
});
|
|
||||||
@@ -1,625 +0,0 @@
|
|||||||
// Tests for the skill-script plumbing (installer) and the shared scripts in src/skill-scripts/.
|
|
||||||
//
|
|
||||||
// See skill-script-helpers.mjs for how these run.
|
|
||||||
|
|
||||||
import { test } from "node:test";
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { spawnSync } from "node:child_process";
|
|
||||||
import { ROOT, SKILLS, NOW, runScript, tmp, write, read, gitInit, phase } from "./skill-script-helpers.mjs";
|
|
||||||
|
|
||||||
/* ================================================================ install */
|
|
||||||
|
|
||||||
test("every skill with scripts ships common.mjs and version.json; dashboard ships none", () => {
|
|
||||||
const withScripts = fs.readdirSync(SKILLS).filter((s) => fs.existsSync(path.join(SKILLS, s, "scripts")));
|
|
||||||
assert.ok(withScripts.length >= 11, `expected most skills to carry scripts, got ${withScripts.join(", ")}`);
|
|
||||||
for (const s of withScripts) {
|
|
||||||
for (const f of ["common.mjs", "version.json"]) assert.ok(fs.existsSync(path.join(SKILLS, s, "scripts", f)), `${s}/scripts/${f}`);
|
|
||||||
}
|
|
||||||
assert.ok(!fs.existsSync(path.join(SKILLS, "plan2code", "scripts")), "the dashboard needs no scripts");
|
|
||||||
const v = JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version;
|
|
||||||
assert.equal(JSON.parse(fs.readFileSync(path.join(SKILLS, "plan2code-4-finalize", "scripts", "version.json"), "utf8")).version, v);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("every script a SKILL.md (or a reference it ships) runs exists beside it, and answers --help", () => {
|
|
||||||
for (const skill of fs.readdirSync(SKILLS)) {
|
|
||||||
const dir = path.join(SKILLS, skill);
|
|
||||||
const texts = [];
|
|
||||||
const walk = (d) => {
|
|
||||||
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
|
||||||
const p = path.join(d, e.name);
|
|
||||||
if (e.isDirectory()) {
|
|
||||||
if (e.name !== "web-console" && e.name !== "scripts") walk(p);
|
|
||||||
} else if (e.name.endsWith(".md")) texts.push(fs.readFileSync(p, "utf8"));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
walk(dir);
|
|
||||||
const named = new Set();
|
|
||||||
for (const t of texts) for (const m of t.matchAll(/<S>\/([a-z-]+\.mjs)/g)) named.add(m[1]);
|
|
||||||
for (const script of named) {
|
|
||||||
const p = path.join(dir, "scripts", script);
|
|
||||||
assert.ok(fs.existsSync(p), `${skill} names <S>/${script} but scripts/${script} is not shipped`);
|
|
||||||
const r = spawnSync(process.execPath, [p, "--help"], { encoding: "utf8" });
|
|
||||||
assert.equal(r.status, 0, `${skill}/${script} --help`);
|
|
||||||
assert.match(r.stdout, /Exit:/, `${skill}/${script} --help documents its exit codes`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test("scripts are self-contained: built-ins and siblings only", () => {
|
|
||||||
for (const dir of [path.join(ROOT, "src", "skill-scripts"), ...fs.readdirSync(path.join(ROOT, "src")).filter((n) => n.endsWith("-scripts")).map((n) => path.join(ROOT, "src", n))]) {
|
|
||||||
for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".mjs"))) {
|
|
||||||
const t = fs.readFileSync(path.join(dir, f), "utf8");
|
|
||||||
for (const m of t.matchAll(/^import .* from "([^"]+)";$/gm)) {
|
|
||||||
assert.ok(m[1].startsWith("node:") || m[1] === "./common.mjs", `${f} imports ${m[1]}`);
|
|
||||||
}
|
|
||||||
assert.ok(!/[\u0000-\u0008]/.test(t), `${f} contains a control character (an escape lost in an edit?)`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ================================================================ specs.mjs */
|
|
||||||
|
|
||||||
const OVERVIEW = `# Lunch vote
|
|
||||||
|
|
||||||
## Phase Checklist
|
|
||||||
|
|
||||||
- [x] **[Phase 1: Data model](./phase-1.md)** - 3 tasks.
|
|
||||||
- [/] [Phase 2: API](./phase-2.md) _(2 tasks)_
|
|
||||||
- [ ] **Phase 3 — Web UI** — see [phase-3.md](./phase-3.md)
|
|
||||||
- [ ] [Phase 4: Docs](./phase-4.md): readme **[Milestone 1]**
|
|
||||||
|
|
||||||
## Parallel Execution Groups
|
|
||||||
|
|
||||||
| Group | Phases | Reason |
|
|
||||||
|-------|--------|--------|
|
|
||||||
| A | 3, 4 | Separate files |
|
|
||||||
| B (sequential) | 1, 2 | Not parallel |
|
|
||||||
|
|
||||||
## Quick Reference
|
|
||||||
`;
|
|
||||||
|
|
||||||
function specFixture() {
|
|
||||||
const root = tmp("specs");
|
|
||||||
write(root, "AGENTS.md", "# AGENTS.md\n");
|
|
||||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW);
|
|
||||||
write(root, "specs/lunch-vote/PLAN-DRAFT-20260801.md", "# Plan\n\n**Status:** Complete\n");
|
|
||||||
write(root, "specs/lunch-vote/phase-1.md", phase(1, "Complete", [["x", "1.1"], ["x", "1.2"], ["x", "1.T"]]));
|
|
||||||
write(root, "specs/lunch-vote/phase-2.md", phase(2, "In Progress", [["x", "2.1"], [" ", "2.2"]]));
|
|
||||||
write(root, "specs/lunch-vote/phase-3.md", phase(3, "Not Started", [[" ", "3.1"], [" ", "3.2"], [" ", "3.2a"], [" ", "3.4"]], "\n## Phase Testing\n\n- [ ] Run unit tests\n"));
|
|
||||||
write(root, "specs/lunch-vote/phase-4.md", phase(4, "Not Started", [["!", "4.1"], ["?", "4.2"]]));
|
|
||||||
write(root, "specs/idea-only/pathfinder/map.md", "# Map\n\n**Status:** Working\n");
|
|
||||||
write(root, "specs--completed/old-one/overview.md", "# Old\n");
|
|
||||||
return root;
|
|
||||||
}
|
|
||||||
|
|
||||||
test("specs list: active specs with state, drafts and archives, never specs--completed", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
const r = runScript("plan2code-1-plan", "specs.mjs", ["list", "--root", root]);
|
|
||||||
assert.equal(r.code, 0, r.stderr);
|
|
||||||
const names = r.json.specs.map((s) => s.name).sort();
|
|
||||||
assert.deepEqual(names, ["idea-only", "lunch-vote"]);
|
|
||||||
const lv = r.json.specs.find((s) => s.name === "lunch-vote");
|
|
||||||
assert.equal(lv.state, "building");
|
|
||||||
assert.deepEqual(lv.planDrafts, [{ file: "PLAN-DRAFT-20260801.md", archived: false, status: "Complete" }]);
|
|
||||||
assert.equal(lv.phaseFiles, 4);
|
|
||||||
assert.deepEqual(r.json.completed, ["old-one"]);
|
|
||||||
assert.equal(r.json.hasAgents, true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs status: checklist formats, groups, task markers, numbering, totals, checks", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
const r = runScript("plan2code-3-implement", "specs.mjs", ["status", "specs/lunch-vote/overview.md", "--root", root]);
|
|
||||||
assert.equal(r.code, 0, r.stderr);
|
|
||||||
const j = r.json;
|
|
||||||
assert.deepEqual(j.phases.map((p) => [p.number, p.name, p.checklist]), [
|
|
||||||
[1, "Data model", "complete"],
|
|
||||||
[2, "API", "in-progress"],
|
|
||||||
[3, "Web UI", "pending"],
|
|
||||||
[4, "Docs", "pending"],
|
|
||||||
]);
|
|
||||||
assert.deepEqual(j.parallelGroups.map((g) => [g.id, g.phases]), [["A", [3, 4]]], "a group labelled sequential is not a parallel group");
|
|
||||||
assert.deepEqual(j.totals, { total: 11, complete: 4, assumed: 1, pending: 5, "in-progress": 0, blocked: 1, unknown: 0, completed: 5, incomplete: 5 });
|
|
||||||
assert.equal(j.completionPercent, 45);
|
|
||||||
assert.equal(j.phases[0].tasks.total, 3, "a named testing task (1.T) counts");
|
|
||||||
assert.equal(j.phases[0].goal, "Phase 1 builds the thing.");
|
|
||||||
const codes = j.checks.map((c) => c.code);
|
|
||||||
assert.ok(j.checks.some((c) => c.code === "task-numbering" && /expected 3\.3, found 3\.4/.test(c.message)), JSON.stringify(j.checks));
|
|
||||||
assert.ok(!codes.includes("criteria-checkbox"), "a Phase Testing checkbox block is the template's own");
|
|
||||||
assert.ok(j.checks.some((c) => c.code === "unchecked-with-done-tasks" && /Phase 4/.test(c.message)), "an assumed [?] task counts as done, so a [ ] phase holding one is flagged");
|
|
||||||
assert.equal(j.next.action, "ask-resume");
|
|
||||||
assert.equal(j.next.phase.number, 2);
|
|
||||||
assert.deepEqual(j.pending.map((p) => p.number), [2, 3, 4]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs status: the implement selection table", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
const ov = (m1, m2, m3, m4) => OVERVIEW.replace("- [x] **[Phase 1", `- [${m1}] **[Phase 1`).replace("- [/] [Phase 2", `- [${m2}] [Phase 2`).replace("- [ ] **Phase 3", `- [${m3}] **Phase 3`).replace("- [ ] [Phase 4", `- [${m4}] [Phase 4`);
|
|
||||||
const next = (...m) => {
|
|
||||||
write(root, "specs/lunch-vote/overview.md", ov(...m));
|
|
||||||
return runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json.next;
|
|
||||||
};
|
|
||||||
assert.deepEqual(next("x", "x", " ", " ").action, "choose");
|
|
||||||
assert.deepEqual(next("x", "x", " ", " ").options.map((o) => o.number), [3, 4]);
|
|
||||||
assert.ok(next("x", "x", "/", "/").warning, "all options already [/] warns about duplicated work");
|
|
||||||
assert.equal(next("x", " ", " ", " ").action, "auto-start");
|
|
||||||
assert.equal(next("x", "x", "x", " ").action, "auto-start");
|
|
||||||
assert.equal(next("x", "x", "x", "x").action, "none");
|
|
||||||
assert.equal(next("x", "x", "x", "x").reason, "every phase is complete");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs status: drift between the checklist and the phase files is an error", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("- [/] [Phase 2", "- [x] [Phase 2"));
|
|
||||||
write(root, "specs/lunch-vote/phase-5.md", phase(5, "Not Started", [[" ", "5.1"]]));
|
|
||||||
const j = runScript("plan2code-1b-revise-plan", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
|
||||||
assert.ok(j.checks.some((c) => c.code === "checked-with-open-tasks" && /Phase 2/.test(c.message)));
|
|
||||||
assert.ok(j.checks.some((c) => c.code === "missing-checklist-row" && /phase-5/.test(c.message)));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs status: errors are actionable and exit-coded", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
const miss = runScript("plan2code-1-plan", "specs.mjs", ["status", "nope", "--root", root]);
|
|
||||||
assert.equal(miss.code, 3);
|
|
||||||
assert.equal(miss.json.error, "spec-not-found");
|
|
||||||
assert.match(miss.json.next, /specs\.mjs list/);
|
|
||||||
assert.equal(runScript("plan2code-1-plan", "specs.mjs", ["frobnicate"]).code, 2);
|
|
||||||
assert.equal(runScript("plan2code-1-plan", "specs.mjs", ["status", "lunch-vote", "--bogus"]).code, 2);
|
|
||||||
const archived = runScript("plan2code-4-finalize", "specs.mjs", ["mark", "specs--completed/old-one", "--phase", "1", "--to", "done", "--root", root]);
|
|
||||||
assert.equal(archived.code, 5);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs mark: transitions, the no-reset rule, dry-run and idempotence", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
const S = (...a) => runScript("plan2code-3-implement", "specs.mjs", [...a, "--root", root]);
|
|
||||||
const dry = S("mark", "lunch-vote", "--phase", "3", "--to", "in-progress", "--dry-run");
|
|
||||||
assert.equal(dry.code, 0);
|
|
||||||
assert.equal(dry.json.changed, true);
|
|
||||||
assert.match(read(root, "specs/lunch-vote/overview.md"), /- \[ \] \*\*Phase 3/, "dry-run writes nothing");
|
|
||||||
assert.equal(S("mark", "lunch-vote", "--phase", "3", "--to", "in-progress").code, 0);
|
|
||||||
assert.match(read(root, "specs/lunch-vote/overview.md"), /- \[\/\] \*\*Phase 3 — Web UI\*\* — see/, "only the marker changes");
|
|
||||||
assert.equal(S("mark", "lunch-vote", "--phase", "3", "--to", "in-progress").json.changed, false);
|
|
||||||
const reset = S("mark", "lunch-vote", "--phase", "3", "--to", "open");
|
|
||||||
assert.equal(reset.code, 5);
|
|
||||||
assert.equal(reset.json.error, "no-reset");
|
|
||||||
const done = S("mark", "lunch-vote", "--phase", "2", "--to", "done");
|
|
||||||
assert.equal(done.code, 0);
|
|
||||||
assert.match(read(root, "specs/lunch-vote/overview.md"), /- \[x\] \[Phase 2: API\]/);
|
|
||||||
assert.match(read(root, "specs/lunch-vote/phase-2.md"), /^\*\*Status:\*\* Complete$/m);
|
|
||||||
assert.equal(S("mark", "lunch-vote", "--phase", "9", "--to", "done").code, 3);
|
|
||||||
assert.equal(S("mark", "lunch-vote", "--phase", "1", "--to", "open").code, 0, "re-opening a complete phase (revise-plan) is allowed");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs metrics: document and finalize comments, judgment fields from --set", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
const S = (...a) => runScript("plan2code-2-document", "specs.mjs", [...a, "--root", root]);
|
|
||||||
assert.equal(S("metrics", "lunch-vote", "--step", "document").code, 2, "verification_items_added is the agent's number");
|
|
||||||
write(root, "specs/lunch-vote/phase-3.md", read(root, "specs/lunch-vote/phase-3.md") + "\n<!-- VERIFICATION: Added (FR-2) -->\n");
|
|
||||||
const doc = S("metrics", "lunch-vote", "--step", "document", "--set", "verification_items_added=1");
|
|
||||||
assert.equal(doc.code, 0, doc.stderr);
|
|
||||||
assert.equal(doc.json.comment, '<!-- METRICS_JSON {"step": "document", "total_tasks": 11, "tasks_per_phase": [3, 2, 4, 2], "phase_count": 4, "parallel_groups_identified": 1, "verification_items_added": 1} -->');
|
|
||||||
assert.equal(doc.json.verificationCommentsFound, 1);
|
|
||||||
assert.equal(S("metrics", "lunch-vote", "--step", "finalize").code, 2);
|
|
||||||
const fin = S("metrics", "lunch-vote", "--step", "finalize", "--set", "verification_failures_found=1", "--set", "documentation_updates_needed=2");
|
|
||||||
assert.equal(fin.json.comment, '<!-- METRICS_JSON {"step": "finalize", "completion_rate_at_audit": 0.45, "tasks_completed": 5, "tasks_total": 11, "verification_failures_found": 1, "documentation_updates_needed": 2} -->');
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs archive: dry-run, move, refuse to clobber", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
const S = (...a) => runScript("plan2code-4-finalize", "specs.mjs", [...a, "--root", root]);
|
|
||||||
const dry = S("archive", "lunch-vote", "--dry-run");
|
|
||||||
assert.equal(dry.code, 0);
|
|
||||||
assert.ok(dry.json.files.includes("overview.md"));
|
|
||||||
assert.ok(fs.existsSync(path.join(root, "specs/lunch-vote")));
|
|
||||||
const moved = S("archive", "lunch-vote");
|
|
||||||
assert.equal(moved.code, 0, moved.stdout);
|
|
||||||
assert.equal(moved.json.sourceRemoved, true);
|
|
||||||
assert.equal(moved.json.filesAtTarget, dry.json.files.length);
|
|
||||||
assert.ok(fs.existsSync(path.join(root, "specs--completed/lunch-vote/phase-4.md")));
|
|
||||||
write(root, "specs/idea-only/x.md", "x");
|
|
||||||
fs.mkdirSync(path.join(root, "specs--completed/idea-only"));
|
|
||||||
const clash = S("archive", "idea-only");
|
|
||||||
assert.equal(clash.code, 5);
|
|
||||||
assert.ok(fs.existsSync(path.join(root, "specs/idea-only/x.md")), "nothing moved on refusal");
|
|
||||||
const after = S("status", "specs--completed/lunch-vote");
|
|
||||||
assert.equal(after.code, 0, "status reads an archived spec (Finalize after Step 6)");
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ============================================================ commit-msg.mjs */
|
|
||||||
|
|
||||||
test("commit-msg: ticket from the branch, the three -m flags, subject rules", () => {
|
|
||||||
const repo = tmp("commit");
|
|
||||||
const g = gitInit(repo, "feature/ABC-10968-export-csv");
|
|
||||||
write(repo, "a.txt", "a");
|
|
||||||
g("add", "-A");
|
|
||||||
g("commit", "-q", "-m", "init");
|
|
||||||
const C = (...a) => runScript("plan2code-review", "commit-msg.mjs", a, { cwd: repo });
|
|
||||||
const ok = C("--subject", "Add the export endpoint", "--add-all");
|
|
||||||
assert.equal(ok.code, 0, ok.stderr);
|
|
||||||
assert.equal(ok.json.ticket, "ABC-10968");
|
|
||||||
assert.equal(ok.json.command, 'git add -A && git commit -m "Add the export endpoint" -m "ABC-10968" -m "AI Assisted"');
|
|
||||||
assert.equal(ok.json.message, "Add the export endpoint\n\nABC-10968\nAI Assisted");
|
|
||||||
assert.equal(C("--subject", "x".repeat(101)).code, 4);
|
|
||||||
assert.equal(C("--subject", 'say "hi"').code, 4);
|
|
||||||
assert.equal(C("--subject", "costs $5").code, 4);
|
|
||||||
assert.equal(C().code, 2);
|
|
||||||
assert.match(C("--subject", "Fix it", "--files", "src/a.ts", "--files", "my file.md").json.command, /^git add -- src\/a\.ts 'my file\.md' && git commit/);
|
|
||||||
g("checkout", "-q", "-b", "chore/no-ticket-here");
|
|
||||||
const none = C("--subject", "Fix it");
|
|
||||||
assert.equal(none.code, 4);
|
|
||||||
assert.equal(none.json.error, "no-ticket");
|
|
||||||
assert.equal(C("--subject", "Fix it", "--ticket", "ABC-1").json.ticket, "ABC-1");
|
|
||||||
assert.equal(C("--subject", "Fix it", "--ticket", "abc-1").code, 4);
|
|
||||||
g("checkout", "-q", "-b", "PROJ2-7_underscore");
|
|
||||||
assert.equal(C("--subject", "Fix it").json.ticket, "PROJ2-7");
|
|
||||||
const notRepo = runScript("plan2code-review", "commit-msg.mjs", ["--subject", "x"], { cwd: tmp("norepo") });
|
|
||||||
assert.equal(notRepo.code, 3);
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ============================================================ agent-files.mjs */
|
|
||||||
|
|
||||||
test("agent-files: detect, apply only what was chosen, rules folders, idempotent", () => {
|
|
||||||
const root = tmp("agentfiles");
|
|
||||||
write(root, "AGENTS.md", "# AGENTS.md\n");
|
|
||||||
write(root, "CLAUDE.md", Array.from({ length: 12 }, (_, i) => `line ${i}`).join("\n") + "\n");
|
|
||||||
write(root, "GEMINI.md", "# Gemini\nshort\n");
|
|
||||||
write(root, ".github/copilot-instructions.md", "copilot\n");
|
|
||||||
write(root, ".cursor/rules/a.md", "a\n");
|
|
||||||
write(root, ".cursor/rules/b.md", "b\n");
|
|
||||||
const A = (...a) => runScript("plan2code-init", "agent-files.mjs", [...a, "--root", root]);
|
|
||||||
const d = A("detect");
|
|
||||||
assert.equal(d.code, 0);
|
|
||||||
assert.deepEqual(d.json.found.map((f) => f.id), ["CLAUDE.md", "GEMINI.md", ".github/copilot-instructions.md", ".cursor/rules"]);
|
|
||||||
assert.equal(d.json.found[0].lines, 12);
|
|
||||||
assert.equal(d.json.found[0].custom, true);
|
|
||||||
assert.equal(d.json.found[1].custom, false);
|
|
||||||
assert.match(d.json.warnings[0], /CLAUDE\.md has custom content/);
|
|
||||||
const dry = A("apply", "CLAUDE.md", "--dry-run");
|
|
||||||
assert.equal(dry.code, 0);
|
|
||||||
assert.match(read(root, "CLAUDE.md"), /^line 0/, "dry-run writes nothing");
|
|
||||||
assert.equal(A("apply", "CLAUDE.md", ".cursor/rules/", ".github/copilot-instructions.md").code, 0);
|
|
||||||
assert.match(read(root, "CLAUDE.md"), /CRITICAL — MANDATORY FIRST STEP: You MUST read \[AGENTS\.md\]\(\.\/AGENTS\.md\)/);
|
|
||||||
assert.match(read(root, ".github/copilot-instructions.md"), /^# Copilot Instructions\n\nSee \[AGENTS\.md\]\(\.\.\/AGENTS\.md\)/);
|
|
||||||
for (const f of ["CLAUDE.md", ".github/copilot-instructions.md"]) {
|
|
||||||
assert.match(read(root, f), /for complete project documentation including:\n- Development commands and setup\n[\s\S]*- Keeping this file current \/ Failure log\n- Section details in \.agents-docs\//, `${f} uses the bullet-list pointer`);
|
|
||||||
}
|
|
||||||
assert.deepEqual(fs.readdirSync(path.join(root, ".cursor/rules")), ["reference.md"]);
|
|
||||||
assert.match(read(root, ".cursor/rules/reference.md"), /\]\(\.\.\/\.\.\/AGENTS\.md\)/);
|
|
||||||
assert.match(read(root, "GEMINI.md"), /^# Gemini/, "unchosen files are untouched");
|
|
||||||
const again = A("apply", "CLAUDE.md");
|
|
||||||
assert.deepEqual(again.json.actions, [{ action: "unchanged", path: "CLAUDE.md" }]);
|
|
||||||
assert.equal(A("detect").json.found.find((f) => f.id === "CLAUDE.md").alreadyPointer, true);
|
|
||||||
fs.writeFileSync(path.join(root, "CLAUDE.md"), read(root, "CLAUDE.md").replace(/\n/g, "\r\n"));
|
|
||||||
assert.equal(A("detect").json.found.find((f) => f.id === "CLAUDE.md").alreadyPointer, true, "a CRLF copy of the pointer still counts");
|
|
||||||
assert.equal(A("apply", "GEMINI.md", "nope.md").code, 3);
|
|
||||||
fs.rmSync(path.join(root, "AGENTS.md"));
|
|
||||||
assert.equal(A("apply", "--all").code, 3);
|
|
||||||
const empty = runScript("plan2code-init", "agent-files.mjs", ["detect", "--root", tmp("none")]);
|
|
||||||
assert.deepEqual(empty.json.found, []);
|
|
||||||
assert.match(empty.json.note, /skip this step silently/);
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ============================================================== agents-md.mjs */
|
|
||||||
|
|
||||||
test("agents-md: structure, budget, orphans, broken links, inline rules", () => {
|
|
||||||
const root = tmp("agentsmd");
|
|
||||||
write(root, "AGENTS.md", [
|
|
||||||
"# AGENTS.md", "", "## Project Overview", "", "Thing.", "",
|
|
||||||
"## Architecture", "", "Summary.", "", "Details: [Architecture](./.agents-docs/AGENTS-architecture.md)", "",
|
|
||||||
"## Testing", "", "Details: [Testing](./.agents-docs/AGENTS-testing.md)", "",
|
|
||||||
"## Failure log", "", "Details: [Git](./.agents-docs/AGENTS-git.md)", "",
|
|
||||||
"```", "## not a heading inside a fence", "```", "",
|
|
||||||
].join("\n"));
|
|
||||||
write(root, ".agents-docs/AGENTS-architecture.md", "# Architecture\n> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.\n");
|
|
||||||
write(root, ".agents-docs/AGENTS-git.md", "# Git\nno breadcrumb\n");
|
|
||||||
write(root, ".agents-docs/AGENTS-orphan.md", "# Orphan\n> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.\n");
|
|
||||||
const r = runScript("plan2code-init-update", "agents-md.mjs", ["inspect", "--root", root]);
|
|
||||||
assert.equal(r.code, 0, r.stderr);
|
|
||||||
const j = r.json;
|
|
||||||
assert.equal(j.structure, "progressive");
|
|
||||||
assert.equal(j.budget, `${j.lines}/500`);
|
|
||||||
assert.deepEqual(j.sections.map((s) => s.name), ["Project Overview", "Architecture", "Testing", "Failure log"]);
|
|
||||||
assert.deepEqual(j.brokenLinks, [".agents-docs/AGENTS-testing.md"]);
|
|
||||||
assert.deepEqual(j.orphans, [".agents-docs/AGENTS-orphan.md"]);
|
|
||||||
assert.ok(j.problems.some((p) => /Failure log must stay inline/.test(p)));
|
|
||||||
assert.ok(j.problems.some((p) => /AGENTS-git\.md lacks the/.test(p)));
|
|
||||||
const missing = runScript("plan2code-init", "agents-md.mjs", ["inspect", "--root", tmp("noagents")]);
|
|
||||||
assert.equal(missing.json.exists, false);
|
|
||||||
const fn = runScript("plan2code-init", "agents-md.mjs", ["filename", "Development Commands"]);
|
|
||||||
assert.equal(fn.json.file, ".agents-docs/AGENTS-development-commands.md");
|
|
||||||
assert.equal(fn.json.link, "Details: [Development Commands](./.agents-docs/AGENTS-development-commands.md)");
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ============================================================ review-scope.mjs */
|
|
||||||
|
|
||||||
test("review-scope: base detection, committed + staged + untracked, doc share", () => {
|
|
||||||
const repo = tmp("scope");
|
|
||||||
const g = gitInit(repo, "main");
|
|
||||||
write(repo, "src/a.js", "1\n2\n");
|
|
||||||
g("add", "-A");
|
|
||||||
g("commit", "-q", "-m", "init");
|
|
||||||
g("checkout", "-q", "-b", "feature/X-1-thing");
|
|
||||||
write(repo, "src/a.js", "1\n2\n3\n");
|
|
||||||
write(repo, "README.md", "# r\n");
|
|
||||||
g("add", "-A");
|
|
||||||
g("commit", "-q", "-m", "work");
|
|
||||||
write(repo, "docs/new.md", "a\nb\n");
|
|
||||||
write(repo, "src/b.js", "x\n");
|
|
||||||
g("add", "src/b.js");
|
|
||||||
const r = runScript("plan2code-review", "review-scope.mjs", [], { cwd: repo });
|
|
||||||
assert.equal(r.code, 0, r.stderr);
|
|
||||||
const j = r.json;
|
|
||||||
assert.equal(j.base, "main");
|
|
||||||
assert.equal(j.branch, "feature/X-1-thing");
|
|
||||||
assert.deepEqual(j.files.map((f) => [f.path, f.status.join("+")]), [["docs/new.md", "untracked"], ["README.md", "committed"], ["src/a.js", "committed"], ["src/b.js", "staged"]]);
|
|
||||||
assert.deepEqual(j.counts, { files: 4, lines: 5, added: 5, deleted: 0, docs: 2, code: 2 });
|
|
||||||
assert.equal(j.mix, "mixed");
|
|
||||||
assert.equal(j.commits.length, 1);
|
|
||||||
assert.equal(j.empty, false);
|
|
||||||
assert.equal(runScript("plan2code-review", "review-scope.mjs", ["--base", "nope"], { cwd: repo }).code, 3);
|
|
||||||
assert.equal(runScript("plan2code-review", "review-scope.mjs", [], { cwd: tmp("plain") }).code, 3);
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ================================================= verification regressions */
|
|
||||||
|
|
||||||
test("specs: duplicate phase files and checklist rows are reported, and mark will not guess", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
write(root, "specs/lunch-vote/phase-1-old.md", "# Old\n");
|
|
||||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("- [/] [Phase 2: API](./phase-2.md) _(2 tasks)_", "- [/] [Phase 2: API](./phase-2.md) _(2 tasks)_\n- [ ] Phase 2 again"));
|
|
||||||
const j = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
|
||||||
assert.equal(j.phases[0].file, "phase-1.md", "the exact phase-N.md wins over phase-1-old.md");
|
|
||||||
assert.ok(j.checks.some((c) => c.code === "duplicate-phase-file" && /phase-1-old\.md/.test(c.message)));
|
|
||||||
assert.ok(j.checks.some((c) => c.code === "duplicate-checklist-row" && /Phase 2/.test(c.message)));
|
|
||||||
const m = runScript("plan2code-3-implement", "specs.mjs", ["mark", "lunch-vote", "--phase", "2", "--to", "done", "--root", root]);
|
|
||||||
assert.equal(m.code, 5);
|
|
||||||
assert.equal(m.json.error, "duplicate-row");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs: group ranges expand, chains are not parallel, [?] phases count as done, a blocked phase is skipped aloud", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
const groups = (cells) => OVERVIEW.replace("| A | 3, 4 | Separate files |", cells);
|
|
||||||
write(root, "specs/lunch-vote/overview.md", groups("| A | 2-4 | Separate files |"));
|
|
||||||
assert.deepEqual(runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json.parallelGroups[0].phases, [2, 3, 4]);
|
|
||||||
write(root, "specs/lunch-vote/overview.md", groups("| A | 3 → 4 | 4 needs 3 |"));
|
|
||||||
assert.deepEqual(runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json.parallelGroups, []);
|
|
||||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("- [/] [Phase 2", "- [?] [Phase 2").replace("- [ ] **Phase 3", "- [?] **Phase 3").replace("- [ ] [Phase 4", "- [?] [Phase 4"));
|
|
||||||
const done = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
|
||||||
assert.equal(done.next.reason, "every phase is complete");
|
|
||||||
assert.deepEqual(done.pending, []);
|
|
||||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("- [/] [Phase 2", "- [!] [Phase 2"));
|
|
||||||
const skip = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json.next;
|
|
||||||
assert.equal(skip.action, "choose");
|
|
||||||
assert.deepEqual(skip.skipped.map((p) => p.number), [2]);
|
|
||||||
assert.match(skip.warning, /skipping Phase 2 \[blocked\]/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs: blocked tasks may stand at approval; a re-opened phase is normal; done warns on unfinished work", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
write(root, "specs/lunch-vote/phase-1.md", phase(1, "Complete", [["x", "1.1"], ["!", "1.2"]]));
|
|
||||||
let j = runScript("plan2code-1b-revise-plan", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
|
||||||
assert.ok(!j.checks.some((c) => c.code === "checked-with-open-tasks"), JSON.stringify(j.checks));
|
|
||||||
assert.ok(j.checks.some((c) => c.code === "approved-with-blocked"));
|
|
||||||
write(root, "specs/lunch-vote/phase-1.md", phase(1, "Complete", [["x", "1.1"], ["x", "1.2"], [" ", "1.3"]]));
|
|
||||||
const reopen = runScript("plan2code-1b-revise-plan", "specs.mjs", ["mark", "lunch-vote", "--phase", "1", "--to", "open", "--root", root]);
|
|
||||||
assert.deepEqual(reopen.json.changes.map((c) => c.to), ["[ ]", "In Progress"]);
|
|
||||||
j = runScript("plan2code-1b-revise-plan", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
|
||||||
assert.ok(j.checks.some((c) => c.code === "partly-done-unchecked" && c.level === "info"));
|
|
||||||
const done = runScript("plan2code-3-implement", "specs.mjs", ["mark", "lunch-vote", "--phase", "2", "--to", "done", "--root", root]);
|
|
||||||
assert.deepEqual(done.json.unfinished, ["2.2"]);
|
|
||||||
assert.match(done.json.warning, /unfinished/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs: --set cannot override computed fields; empty overview exists; uncounted task lines are flagged", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
assert.equal(runScript("plan2code-2-document", "specs.mjs", ["metrics", "lunch-vote", "--step", "document", "--set", "verification_items_added=1", "--set", "total_tasks=99", "--root", root]).code, 2);
|
|
||||||
write(root, "specs/lunch-vote/phase-2.md", read(root, "specs/lunch-vote/phase-2.md") + "- [ ] **Task 2.4A:** odd\n1. [ ] **Task 2.5:** numbered\n");
|
|
||||||
const j = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
|
||||||
assert.equal(j.checks.filter((c) => c.code === "uncounted-task").length, 2);
|
|
||||||
write(root, "specs/lunch-vote/overview.md", "");
|
|
||||||
const e = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
|
||||||
assert.equal(e.overview, "overview.md");
|
|
||||||
assert.ok(e.checks.some((c) => c.code === "no-checklist"));
|
|
||||||
assert.ok(!e.checks.some((c) => c.code === "no-overview"));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("commit-msg: a repo with no commits, stray arguments, and paths quoted for every shell", () => {
|
|
||||||
const repo = tmp("commit2");
|
|
||||||
gitInit(repo, "feature/ABC-12-x");
|
|
||||||
const C = (...a) => runScript("plan2code-review", "commit-msg.mjs", a, { cwd: repo });
|
|
||||||
assert.equal(C("--subject", "Add x").json.ticket, "ABC-12", "no commits yet");
|
|
||||||
const stray = C("--subject", "Fix", "--files", "a.js", "b.js");
|
|
||||||
assert.equal(stray.code, 2);
|
|
||||||
assert.equal(stray.json.error, "stray-argument");
|
|
||||||
assert.equal(C("--subject", "Fix", "--files", "src\\a.js", "--files", "my $file.md").json.command.split(" && ")[0], "git add -- src/a.js 'my $file.md'");
|
|
||||||
assert.equal(C("--subject", "Fix", "--files", "it's.md").code, 4);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("review-scope: non-ASCII paths, empty untracked files, .txt is not a doc", () => {
|
|
||||||
const repo = tmp("scope2");
|
|
||||||
const g = gitInit(repo, "main");
|
|
||||||
write(repo, "a.js", "1\n");
|
|
||||||
g("add", "-A");
|
|
||||||
g("commit", "-q", "-m", "init");
|
|
||||||
write(repo, "café.md", "a\nb\n");
|
|
||||||
write(repo, "empty.js", "");
|
|
||||||
write(repo, "requirements.txt", "x\n");
|
|
||||||
const j = runScript("plan2code-review", "review-scope.mjs", [], { cwd: repo }).json;
|
|
||||||
const byPath = Object.fromEntries(j.files.map((f) => [f.path, f]));
|
|
||||||
assert.equal(byPath["café.md"].added, 2);
|
|
||||||
assert.equal(byPath["empty.js"].added, 0);
|
|
||||||
assert.equal(j.counts.docs, 1, "only café.md is a doc");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("agents-md and agent-files: indirect links are not orphans, accents fold, Cursor .mdc rules are replaced", () => {
|
|
||||||
const root = tmp("agents2");
|
|
||||||
write(root, "AGENTS.md", "# AGENTS.md\n\n## Architecture\n\nDetails: [A](./.agents-docs/AGENTS-architecture.md)\n");
|
|
||||||
write(root, ".agents-docs/AGENTS-architecture.md", "# Architecture\n> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.\n\nSee [deep](./AGENTS-deep.md).\n");
|
|
||||||
write(root, ".agents-docs/AGENTS-deep.md", "# Deep\n> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.\n");
|
|
||||||
const j = runScript("plan2code-init-update", "agents-md.mjs", ["inspect", "--root", root]).json;
|
|
||||||
assert.deepEqual(j.orphans, []);
|
|
||||||
assert.deepEqual(j.indirect, [".agents-docs/AGENTS-deep.md"]);
|
|
||||||
assert.equal(runScript("plan2code-init", "agents-md.mjs", ["filename", "Café Ünïcode"]).json.file, ".agents-docs/AGENTS-cafe-unicode.md");
|
|
||||||
write(root, ".cursor/rules/style.mdc", "---\nalwaysApply: true\n---\nrule\n");
|
|
||||||
const d = runScript("plan2code-init", "agent-files.mjs", ["detect", "--root", root]).json;
|
|
||||||
assert.deepEqual(d.found.find((f) => f.id === ".cursor/rules").files.map((f) => f.path), [".cursor/rules/style.mdc"]);
|
|
||||||
runScript("plan2code-init", "agent-files.mjs", ["apply", ".cursor/rules", "--root", root]);
|
|
||||||
assert.deepEqual(fs.readdirSync(path.join(root, ".cursor/rules")), ["reference.md"]);
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ================================================== code-review regressions */
|
|
||||||
|
|
||||||
test("agent-files: an entry that is AGENTS.md through a link is never written through", () => {
|
|
||||||
const root = tmp("agentlink");
|
|
||||||
const agents = "# AGENTS.md\n\nThe real instructions.\n";
|
|
||||||
write(root, "AGENTS.md", agents);
|
|
||||||
fs.linkSync(path.join(root, "AGENTS.md"), path.join(root, "CLAUDE.md"));
|
|
||||||
write(root, "GEMINI.md", Array.from({ length: 12 }, (_, i) => `line ${i}`).join("\n") + "\n");
|
|
||||||
const A = (...a) => runScript("plan2code-init", "agent-files.mjs", [...a, "--root", root]);
|
|
||||||
const d = A("detect").json;
|
|
||||||
assert.equal(d.found.find((f) => f.id === "CLAUDE.md").linkedToAgents, true, "a hard link to AGENTS.md is AGENTS.md");
|
|
||||||
assert.equal(d.found.find((f) => f.id === "GEMINI.md").linkedToAgents, false);
|
|
||||||
assert.ok(!d.warnings.some((w) => /CLAUDE\.md/.test(w)), "a linked entry is not warned as custom content");
|
|
||||||
const refused = A("apply", "CLAUDE.md", "GEMINI.md");
|
|
||||||
assert.equal(refused.code, 5);
|
|
||||||
assert.equal(refused.json.error, "linked-to-agents");
|
|
||||||
assert.match(refused.json.next, /already serves AGENTS\.md/);
|
|
||||||
assert.equal(read(root, "AGENTS.md"), agents, "refused before anything was written");
|
|
||||||
assert.match(read(root, "GEMINI.md"), /^line 0/, "a refusal writes nothing at all");
|
|
||||||
const all = A("apply", "--all");
|
|
||||||
assert.equal(all.code, 0, all.stderr);
|
|
||||||
assert.ok(all.json.actions.some((a) => a.action === "skipped-linked" && a.path === "CLAUDE.md"));
|
|
||||||
assert.deepEqual(all.json.updated, ["GEMINI.md"]);
|
|
||||||
assert.equal(read(root, "AGENTS.md"), agents, "--all skips the linked entry");
|
|
||||||
assert.match(read(root, "GEMINI.md"), /^# GEMINI\.md\n\nSee \[AGENTS\.md\]/);
|
|
||||||
|
|
||||||
// Symlinks need admin (or Developer Mode) on Windows: run this part only where they work.
|
|
||||||
const sroot = tmp("agentsym");
|
|
||||||
write(sroot, "AGENTS.md", agents);
|
|
||||||
write(sroot, "shared/other.md", "someone else's file\n");
|
|
||||||
try {
|
|
||||||
fs.symlinkSync(path.join(sroot, "AGENTS.md"), path.join(sroot, "CLAUDE.md"));
|
|
||||||
fs.symlinkSync(path.join(sroot, "shared/other.md"), path.join(sroot, "GEMINI.md"));
|
|
||||||
} catch (err) {
|
|
||||||
if (err.code === "EPERM" || err.code === "EACCES") return;
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
const S = (...a) => runScript("plan2code-init", "agent-files.mjs", [...a, "--root", sroot]);
|
|
||||||
assert.equal(S("detect").json.found.find((f) => f.id === "CLAUDE.md").linkedToAgents, true);
|
|
||||||
assert.equal(S("apply", "CLAUDE.md").code, 5);
|
|
||||||
assert.equal(S("apply", "GEMINI.md").code, 0);
|
|
||||||
assert.equal(read(sroot, "shared/other.md"), "someone else's file\n", "a symlink to another file is replaced, not written through");
|
|
||||||
assert.equal(fs.lstatSync(path.join(sroot, "GEMINI.md")).isSymbolicLink(), false);
|
|
||||||
assert.equal(read(sroot, "AGENTS.md"), agents);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("agent-files: a CRLF checkout of a pointer is still the pointer", () => {
|
|
||||||
const root = tmp("agentcrlf");
|
|
||||||
write(root, "AGENTS.md", "# AGENTS.md\n");
|
|
||||||
write(root, "GEMINI.md", "x\n");
|
|
||||||
write(root, ".windsurf/rules/a.md", "a\n");
|
|
||||||
const A = (...a) => runScript("plan2code-init", "agent-files.mjs", [...a, "--root", root]);
|
|
||||||
assert.equal(A("apply", "--all").code, 0);
|
|
||||||
for (const f of ["GEMINI.md", ".windsurf/rules/reference.md"]) write(root, f, read(root, f).replace(/\n/g, "\r\n"));
|
|
||||||
const d = A("detect").json;
|
|
||||||
assert.equal(d.found.find((f) => f.id === "GEMINI.md").alreadyPointer, true);
|
|
||||||
assert.equal(d.found.find((f) => f.id === ".windsurf/rules").alreadyPointer, true);
|
|
||||||
assert.deepEqual(A("apply", "GEMINI.md", ".windsurf/rules").json.actions.map((a) => a.action), ["unchanged", "unchanged"]);
|
|
||||||
assert.match(read(root, "GEMINI.md"), /\r\n/, "an unchanged CRLF pointer is left as it is");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs mark: a plain or bold Status: line is updated; a missing one is reported", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
const S = (...a) => runScript("plan2code-3-implement", "specs.mjs", [...a, "--root", root]);
|
|
||||||
write(root, "specs/lunch-vote/phase-3.md", phase(3, "x", [["x", "3.1"]]).replace("**Status:** x", "Status: In Progress"));
|
|
||||||
const plain = S("mark", "lunch-vote", "--phase", "3", "--to", "done");
|
|
||||||
assert.equal(plain.code, 0, plain.stderr);
|
|
||||||
assert.match(read(root, "specs/lunch-vote/phase-3.md"), /^Status: Complete$/m, "the plain form is kept as written");
|
|
||||||
assert.ok(!plain.json.warning);
|
|
||||||
write(root, "specs/lunch-vote/phase-4.md", phase(4, "x", [["x", "4.1"]]).replace("**Status:** x", "- **Status**: Not Started"));
|
|
||||||
assert.equal(S("status", "lunch-vote").json.phases[3].status, "Not Started");
|
|
||||||
assert.equal(S("mark", "lunch-vote", "--phase", "4", "--to", "done").code, 0);
|
|
||||||
assert.match(read(root, "specs/lunch-vote/phase-4.md"), /^- \*\*Status\*\*: Complete$/m);
|
|
||||||
write(root, "specs/lunch-vote/phase-2.md", phase(2, "x", [["x", "2.1"]]).replace("**Status:** x\n", ""));
|
|
||||||
const none = S("mark", "lunch-vote", "--phase", "2", "--to", "done");
|
|
||||||
assert.equal(none.code, 0);
|
|
||||||
assert.match(none.json.warning, /phase-2\.md has no Status line, so only the Phase Checklist checkbox changed/);
|
|
||||||
assert.match(read(root, "specs/lunch-vote/overview.md"), /- \[x\] \[Phase 2: API\]/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs: only a folder directly under specs/ is a spec; archive verification fails loudly", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
write(root, "src/app.js", "x\n");
|
|
||||||
const S = (...a) => runScript("plan2code-4-finalize", "specs.mjs", [...a, "--root", root]);
|
|
||||||
for (const arg of [".", "./src", "./specs", "specs/lunch-vote/.."]) {
|
|
||||||
const r = S("archive", arg, "--dry-run");
|
|
||||||
assert.equal(r.code, 5, `archive ${arg}: ${r.stdout}`);
|
|
||||||
assert.equal(r.json.error, "not-a-spec");
|
|
||||||
assert.match(r.json.next, /specs\/<name>/);
|
|
||||||
}
|
|
||||||
assert.ok(fs.existsSync(path.join(root, "specs/lunch-vote/overview.md")));
|
|
||||||
assert.equal(S("archive", "./specs/lunch-vote", "--dry-run").code, 0);
|
|
||||||
assert.equal(S("archive", path.join(root, "specs", "lunch-vote"), "--dry-run").code, 0, "an absolute path under specs/ is fine");
|
|
||||||
assert.equal(S("status", "specs--completed/old-one").code, 0, "a read may name an archived spec");
|
|
||||||
assert.equal(S("status", "./src").json.error, "not-a-spec");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("specs: an em dash in a group range expands like a hyphen", () => {
|
|
||||||
const root = specFixture();
|
|
||||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("| A | 3, 4 | Separate files |", "| A | 2\u20144 | Separate files |"));
|
|
||||||
assert.deepEqual(runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json.parallelGroups[0].phases, [2, 3, 4]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("commit-msg: @ and - paths are quoted, git add ends its options, risky subjects are refused, add and commit apart", () => {
|
|
||||||
const repo = tmp("commit3");
|
|
||||||
gitInit(repo, "feature/ABC-12-x");
|
|
||||||
const C = (...a) => runScript("plan2code-review", "commit-msg.mjs", a, { cwd: repo });
|
|
||||||
const files = C("--subject", "Fix", "--files", "@types/x.d.ts", "--files", "-weird.md", "--files", "src/a@b.js");
|
|
||||||
assert.equal(files.code, 0, files.stderr);
|
|
||||||
assert.equal(files.json.add, "git add -- '@types/x.d.ts' '-weird.md' src/a@b.js");
|
|
||||||
assert.equal(files.json.commit, 'git commit -m "Fix" -m "ABC-12" -m "AI Assisted"');
|
|
||||||
assert.equal(files.json.command, `${files.json.add} && ${files.json.commit}`);
|
|
||||||
assert.equal(C("--subject", "Fix", "--add-all").json.add, "git add -A");
|
|
||||||
const bare = C("--subject", "Fix").json;
|
|
||||||
assert.equal(bare.add, null);
|
|
||||||
assert.equal(bare.command, bare.commit);
|
|
||||||
for (const bad of ["back\\slash", "wow!", "a\rb", "say \u201Chi\u201D"]) {
|
|
||||||
assert.equal(C("--subject", bad).code, 4, JSON.stringify(bad));
|
|
||||||
}
|
|
||||||
assert.equal(C("--subject", "wow!").json.error, "unsafe-subject");
|
|
||||||
assert.equal(C("--subject", "Fix", "--files", "it\u2019s.md").json.error, "unsafe-path");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("review-scope: no main or master is no-base unless the repo has no commits; a move up a level keeps one slash", () => {
|
|
||||||
const repo = tmp("scope3");
|
|
||||||
const g = gitInit(repo, "develop");
|
|
||||||
write(repo, "d/sub/f.txt", "1\n");
|
|
||||||
write(repo, "top/h.txt", "3\n");
|
|
||||||
g("add", "-A");
|
|
||||||
g("commit", "-q", "-m", "init");
|
|
||||||
g("checkout", "-q", "-b", "feature/X-2-thing");
|
|
||||||
write(repo, "src/new.js", "x\n");
|
|
||||||
g("add", "-A");
|
|
||||||
g("commit", "-q", "-m", "feature work");
|
|
||||||
const R = (...a) => runScript("plan2code-review", "review-scope.mjs", a, { cwd: repo });
|
|
||||||
const none = R();
|
|
||||||
assert.equal(none.code, 3);
|
|
||||||
assert.equal(none.json.error, "no-base");
|
|
||||||
assert.match(none.json.next, /--base <trunk>/);
|
|
||||||
const dev = R("--base", "develop");
|
|
||||||
assert.equal(dev.code, 0, dev.stderr);
|
|
||||||
assert.deepEqual(dev.json.files.map((f) => f.path), ["src/new.js"]);
|
|
||||||
g("mv", "d/sub/f.txt", "d/f.txt");
|
|
||||||
g("mv", "top/h.txt", "h.txt");
|
|
||||||
const moved = R("--base", "develop").json.files.map((f) => f.path);
|
|
||||||
assert.ok(moved.includes("d/f.txt") && moved.includes("h.txt"), JSON.stringify(moved));
|
|
||||||
assert.ok(!moved.some((p) => p.includes("//") || p.startsWith("/")), JSON.stringify(moved));
|
|
||||||
const fresh = tmp("scope4");
|
|
||||||
gitInit(fresh, "develop");
|
|
||||||
write(fresh, "a.js", "1\n");
|
|
||||||
const unborn = runScript("plan2code-review", "review-scope.mjs", [], { cwd: fresh });
|
|
||||||
assert.equal(unborn.code, 0, unborn.stderr);
|
|
||||||
assert.equal(unborn.json.base, null);
|
|
||||||
assert.match(unborn.json.note, /No commits yet/);
|
|
||||||
assert.deepEqual(unborn.json.files.map((f) => f.path), ["a.js"]);
|
|
||||||
});
|
|
||||||
+12
-1138
File diff suppressed because it is too large.
Load diff
@@ -3,7 +3,7 @@
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
const CHAR_LIMIT = 20000;
|
const CHAR_LIMIT = 11500;
|
||||||
const srcDir = path.join(__dirname, '..', 'src');
|
const srcDir = path.join(__dirname, '..', 'src');
|
||||||
|
|
||||||
// Note: readdirSync is non-recursive, so files in subdirectories like
|
// Note: readdirSync is non-recursive, so files in subdirectories like
|
||||||
|
|||||||
@@ -33,13 +33,9 @@ Read references/github-issues.md — REQUIRED on `github`, skip on `local`.
|
|||||||
|
|
||||||
Recorded as the first `## Ground rules` bullet (`**Backend:** local|github`), never re-asked or switched. Either way the PLAN-DRAFT lands in local `specs/<idea>/` — downstream steps read files, not issues.
|
Recorded as the first `## Ground rules` bullet (`**Backend:** local|github`), never re-asked or switched. Either way the PLAN-DRAFT lands in local `specs/<idea>/` — downstream steps read files, not issues.
|
||||||
|
|
||||||
## Scripts
|
|
||||||
|
|
||||||
On `local`, the map's bookkeeping is a script; the decisions are yours. `node "<S>/pathfinder.mjs" <command> specs/<idea>/pathfinder`, run from the project root, where `<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-0-pathfinder/scripts/` globally). It prints one JSON object. Exit 0 is success; anything else carries `message` and `next`, so do what `next` says. Exit 5 (refused) means a rule would break: never work around it by editing the files by hand. `--help` lists every command; they are named at the steps below. It reads local files only: on `github`, the backend playbook does each step with `gh` (except `lint`, which checks the local briefs and PLAN-DRAFT once one exists), and a `no-map` result there is expected, never a cue to chart.
|
|
||||||
|
|
||||||
## Project Context
|
## Project Context
|
||||||
|
|
||||||
Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it answers. If missing, fold it into the Step 0 gate batch: *"No `AGENTS.md`. Pathfinder can chart without it. Continue, or run `plan2code-init` first?"* Record the outcome as the first line of `## Ground rules`: ``- `AGENTS.md` exists and governs.`` or, when missing, exactly ``- `AGENTS.md` is absent.`` (the handoff reads it).
|
Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it answers. If missing, fold it into the Step 0 gate batch: *"No `AGENTS.md`. Pathfinder can chart without it. Continue, or run `plan2code-init` first?"* Record it in `## Ground rules`.
|
||||||
|
|
||||||
## Rules
|
## Rules
|
||||||
|
|
||||||
@@ -53,13 +49,12 @@ Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it
|
|||||||
- **Reserved names — never create inside `pathfinder/`:** `overview.md`, `phase-<N>.md`, `PLAN-DRAFT-*.md`, `PLAN-CONVERSATION-*.md`.
|
- **Reserved names — never create inside `pathfinder/`:** `overview.md`, `phase-<N>.md`, `PLAN-DRAFT-*.md`, `PLAN-CONVERSATION-*.md`.
|
||||||
- **Never emit the loop's completion tokens under `specs/`** — `TASK_COMPLETE`, `PHASE_COMPLETE`, `ALL_TASKS_COMPLETE`, `IMPLEMENTATION_COMPLETE`, `SPEC_COMPLETE`, `WORK_COMPLETE`. It scans for them.
|
- **Never emit the loop's completion tokens under `specs/`** — `TASK_COMPLETE`, `PHASE_COMPLETE`, `ALL_TASKS_COMPLETE`, `IMPLEMENTATION_COMPLETE`, `SPEC_COMPLETE`, `WORK_COMPLETE`. It scans for them.
|
||||||
- **No `- [ ]` checkboxes inside question files**, and no `METRICS_JSON` anywhere.
|
- **No `- [ ]` checkboxes inside question files**, and no `METRICS_JSON` anywhere.
|
||||||
- **Lint before every Session End** (on `github`, once a brief or PLAN-DRAFT is on local disk; it checks those): `lint` checks the rules above, the schema lines, `Blocked by:` targets and cycles, and metrics-scraper bait. Fix every error it lists (exit 4) before you stop.
|
|
||||||
|
|
||||||
## Auto-Discovery and Mode Selection
|
## Auto-Discovery and Mode Selection
|
||||||
|
|
||||||
⚠️ `specs/` is gitignored — NEVER use Glob. Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
|
⚠️ `specs/` is gitignored — NEVER use Glob. Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
|
||||||
|
|
||||||
**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.
|
**Brief/recap/minutes asked?** → read references/brief.md: reconcile, write plain-English `briefs/brief-<YYYYMMDD>.md` (decisions in range, still open, next step), STOP. Never resolves.
|
||||||
|
|
||||||
**Identify the idea FIRST** (from the argument, or ask), then evaluate for THAT idea — first match wins. An issue URL or number means `github`; else look for a local map, then `gh issue list --label pathfinder:map` for `Map: <idea>`.
|
**Identify the idea FIRST** (from the argument, or ask), then evaluate for THAT idea — first match wins. An issue URL or number means `github`; else look for a local map, then `gh issue list --label pathfinder:map` for `Map: <idea>`.
|
||||||
|
|
||||||
@@ -86,15 +81,15 @@ 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.
|
> 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. `[Step 0: Intent Gate]` **Before creating anything**, use AskUserQuestion for the outcome and WAIT: **chart a map** (foggy — Step 1), **`/plan2code-1-plan`** (clear — STOP), **`/plan2code-quick-task`** (tiny — STOP). HITL, never self-select "chart".
|
||||||
1. `[Chart - Step 1: Name and backend]` Only after the gate says "chart." Confirm the kebab-case idea name, then ask — HITL, never self-picked — **local files or GitHub Issues?** Recommend `local` for solo work; offer `github` only if preflight passes, naming the repo's visibility. THEN the first write.
|
1. `[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.
|
2. `[Step 2: Destination]` Grill until it is one or two lines. It fixes scope — settle it first.
|
||||||
3. `[Chart - Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK`. On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter.
|
3. `[Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK`. On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter.
|
||||||
4. `[Chart - Step 4: Map the frontier]` Grill again **breadth-first**: fan out, never deep on one thread. Surface the open decisions and what is takeable now.
|
4. `[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.
|
5. `[Step 5: Create the map]` `**Status:** Charting`, Destination, Ground rules (backend first), an empty index, the fog in `## Not yet specified`. Say once where it lives and who sees it.
|
||||||
6. `[Chart - Step 6: Write the questions]` One per decision you can phrase sharply NOW, dependency order, `Blocked by:` filled the same pass — on `github`, create all first, wire edges second. The rest stays fog. Include a `grill · HITL` testing-posture question; `/plan2code-1-plan` Phase 1 needs it.
|
6. `[Step 6: Write the questions]` One per decision you can phrase sharply NOW, dependency order, `Blocked by:` filled the same pass — on `github`, create all first, wire edges second. The rest stays fog. Include a `grill · HITL` testing-posture question; `/plan2code-1-plan` Phase 1 needs it.
|
||||||
7. `[Chart - Step 7: Index]` `local`: `reconcile` fills `## Question Checklist` from the files (every missing row, with its marker). Either backend: set `**Status:** Working`. `local`: then `lint`.
|
7. `[Step 7: Index]` Fill `## Question Checklist` from the files (`local` only). Set `**Status:** Working`.
|
||||||
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.
|
8. `[Step 8: Fire research]` One subagent per `research` question, in parallel. Each writes only its `## Evidence`, never decides. **Wait for all** (they die with the terminal), then Session End.
|
||||||
|
|
||||||
**No fog at Step 4?** Small enough to plan directly: create no map, keep the recon as a local file, attach it to `/plan2code-1-plan`, STOP. Charting resolves nothing by hand — stop at Step 8.
|
**No fog at Step 4?** Small enough to plan directly: create no map, keep the recon as a local file, attach it to `/plan2code-1-plan`, STOP. Charting resolves nothing by hand — stop at Step 8.
|
||||||
|
|
||||||
@@ -106,18 +101,15 @@ Read references/resolve.md
|
|||||||
|
|
||||||
Assume NO memory of any prior session.
|
Assume NO memory of any prior session.
|
||||||
|
|
||||||
1. `[Work - Step 1: Load]` Read the map whole. No question yet.
|
1. `[Step 1: Load]` Read the map whole. No question yet.
|
||||||
2. `[Work - Step 2: Reconcile]` **Always.** `local`: run `reconcile`. The answer wins: a question whose `## Answer` its state contradicts is resolved, a missing `Resolved:` is backfilled from the claim (today if none), a claim with no `## Answer` (a crash) is released, and every marker is rebuilt from the questions. Tell the human each `repairs` entry in one line. Re-fire every question in `refire` (research cut off before its `Research complete:` line; resolve.md → Interrupted research). `--dry-run` first if the map looks badly off. `github`: the reconcile checks in the backend playbook.
|
2. `[Step 2: Reconcile]` **Always.** Read every question. `## Answer` written but the state disagrees? The answer wins. Claimed with no `## Answer`? A crash: release it, say so. Rebuild every marker from the questions; backfill a missing `Resolved:` date from the claim. Research without `Research complete:`? Re-fire it.
|
||||||
3. `[Work - Step 3: Frontier]` Every question open, unclaimed, and unblocked, first in order. `local`: run `frontier` (`frontier`, `blocked` with each blocker, `stranded`, `nextNN`, `counts`).
|
3. `[Step 3: Frontier]` Every question open, unclaimed, and unblocked. First in order.
|
||||||
4. `[Work - Step 4: Choose and claim]` The one the user named, else first on the frontier. Mark it claimed on the question and the map, **saved before any work** (`local`: `claim <NN>`, which refuses a blocked or non-open question and a second open claim). A `research` pick fires unclaimed instead (resolve.md); then claim the next one.
|
4. `[Step 4: Choose and claim]` The one the user named, else first on the frontier. Mark it claimed on the question and the map, **saved before any work.** Frontier empty but questions remain? All blocked — report the chain, STOP. Stranded on an `out-of-scope` blocker? Re-frame or rule out, re-run Step 3. Nothing open? The Clearing Gate.
|
||||||
- Stranded on an `out-of-scope` blocker? Check this first: re-frame or rule out, re-run Step 3.
|
5. `[Step 5: Zoom]` Read the claimed question in full, plus any closed question it references. Obey `## Ground rules`.
|
||||||
- Frontier empty but questions remain (`allBlocked`)? Report the chain, STOP.
|
6. `[Step 6: Resolve]` Route by type per the resolve playbook. HITL needs the human's own words.
|
||||||
- Nothing open (`nothingOpen`)? The Clearing Gate.
|
7. `[Step 7: Record]` Write `## Answer`: the decision, what was rejected and why, consequences, a one-line `**Gist:**`. Sources under `## Evidence`. Mark it resolved, dated today, index the gist + date on the map, bump `**Updated:**`.
|
||||||
5. `[Work - Step 5: Zoom]` Read the claimed question in full, plus any closed question it references. Obey `## Ground rules`.
|
8. `[Step 8: Graduate]` Fog now sharp? Write those questions, delete the graduated bullets. Past the destination? Rule it out of scope, one line in `## Out of scope`. Invalidated? Re-frame or rule out.
|
||||||
6. `[Work - Step 6: Resolve]` Route by type per the resolve playbook. HITL needs the human's own words.
|
9. `[Step 9: Menu]` Run The Clearing Gate. Not cleared: fork-menu (Form C) — pick → Step 4, stop → Session End.
|
||||||
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.
|
|
||||||
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
|
## The Clearing Gate
|
||||||
|
|
||||||
@@ -132,7 +124,7 @@ The map clears only when ALL hold:
|
|||||||
3. The destination is reachable with nothing left to decide
|
3. The destination is reachable with nothing left to decide
|
||||||
4. All four confidence dimensions score ≥ 18/25
|
4. All four confidence dimensions score ≥ 18/25
|
||||||
|
|
||||||
Score the four dimensions (handoff.md rubric) and write them to the map's `**Confidence:**` line. `local`: run `gate`; it checks 1, 2 and 4 against the files, plus the handoff preflight and the Requirements, Feasibility and Risk caps; condition 3, the Integration cap and the scores stay yours (its `judgment` list). Any failing: name it, keep working. All passing: follow the handoff playbook, set `**Status:** Cleared`, run `lint`, stop. The PLAN-DRAFT is always local — `/plan2code-1-plan` cannot read a tracker.
|
Any failing: name it, keep working. All passing: follow the handoff playbook, set `**Status:** Cleared`, stop. The PLAN-DRAFT is always local — `/plan2code-1-plan` cannot read a tracker.
|
||||||
|
|
||||||
## Trail Footer
|
## Trail Footer
|
||||||
|
|
||||||
@@ -140,8 +132,6 @@ Read references/trail.md
|
|||||||
|
|
||||||
> Fallback: once the map exists, end every response with a marker path (`●` done · `◉` here · `○` open · `⊘` blocked · `⊝` out of scope) `START`→`⚑`, a named legend, a plain-English confidence note, then ONE closer: asking → Form B, `WAITING ON YOU`, no command; menu → Form C, `NEXT UP` + `OR START FRESH`; session end → Form A, `NEXT STEP` + resume command with `--web` (map issue URL on `github`).
|
> Fallback: once the map exists, end every response with a marker path (`●` done · `◉` here · `○` open · `⊘` blocked · `⊝` out of scope) `START`→`⚑`, a named legend, a plain-English confidence note, then ONE closer: asking → Form B, `WAITING ON YOU`, no command; menu → Form C, `NEXT UP` + `OR START FRESH`; session end → Form A, `NEXT STEP` + resume command with `--web` (map issue URL on `github`).
|
||||||
|
|
||||||
Close EVERY response with the trail once the map exists. You pick the form by what the turn does. `local`: `trail` draws it from the files, so paste its output verbatim. Asking → Form B, `trail --form B --item "<probe>" ... --text` (one `--item` per open probe, up to three). Menu after a decision → Form C, `trail --form C` WITHOUT `--text`: paste its `text`, then build the question tool from its `menu`. Session end → Form A, `trail --form A --text`. `github`: draw it by hand per the backend playbook.
|
|
||||||
|
|
||||||
## Session End
|
## Session End
|
||||||
|
|
||||||
Report each question resolved (name + gist), what graduated, what's still open; offer a brief for today. Nothing to commit — `local` is gitignored, `github` already on the tracker. Then the mascot, then the Trail Footer.
|
Report each question resolved (name + gist), what graduated, what's still open; offer a brief for today. Nothing to commit — `local` is gitignored, `github` already on the tracker. Then the mascot, then the Trail Footer.
|
||||||
@@ -162,8 +152,7 @@ Report each question resolved (name + gist), what graduated, what's still open;
|
|||||||
|
|
||||||
| Issue | Action |
|
| Issue | Action |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Session stops mid-question, or map drift | Release the claim, note why (or leave it: the next reconcile releases a claim with no answer). Work Step 2 repairs both; questions win. Never reconcile mid-question: it would release your own live claim. |
|
| Session stops mid-question, or map drift | Release the claim, note why. Work Step 2 repairs both; questions win. |
|
||||||
| A script cannot run (no `node`) | Say so once; do the step by hand from questions.md (markers, blocking, schema) and the reference that names the step. Footer by hand: the trail's glyph path, then Form A `NEXT STEP · start a new conversation and run:` + the command, Form B `WAITING ON YOU · answer here, in this conversation:` + the items, or Form C `OR START FRESH · new conversation, paste:` + the command. |
|
|
||||||
| Frontier empty, fog remains | Not sharp yet. Grill it into a question, or clear the map |
|
| Frontier empty, fog remains | Not sharp yet. Grill it into a question, or clear the map |
|
||||||
| Reference file missing | Use the fallback blockquote under its `Read` line |
|
| Reference file missing | Use the fallback blockquote under its `Read` line |
|
||||||
| `gh` fails mid-session on a `github` map | Report and STOP. Falling back to local forks the map |
|
| `gh` fails mid-session on a `github` map | Report and STOP. Falling back to local forks the map |
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
> Loaded when the user's argument asks for a brief. Produces one plain-English report file for a date range — the artifact a PM pastes into Slack or reads aloud in a meeting. The only mutation BRIEF mode ever performs is the Work Step 2 reconcile; it never claims, resolves, or answers a question.
|
> Loaded when the user's argument asks for a brief. Produces one plain-English report file for a date range — the artifact a PM pastes into Slack or reads aloud in a meeting. The only mutation BRIEF mode ever performs is the Work Step 2 reconcile; it never claims, resolves, or answers a question.
|
||||||
|
|
||||||
> **Backend note.** The report is IDENTICAL either way — same sections, same plain-English rules — and the brief file always lands on **local disk** under `specs/<idea>/pathfinder/briefs/`, even on `**Backend:** github`. What differs is where the inputs come from: on `github` the range filter reads each question issue's close date instead of a `Resolved:` line, and the open / blocked / out-of-scope sections come from the frontier query rather than the checklist — see `github-issues.md`. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes.
|
> **Backend note.** The report is IDENTICAL either way — same sections, same plain-English rules — and the brief file always lands on **local disk** under `specs/<idea>/pathfinder/briefs/`, even on `**Backend:** github`. What differs is where the inputs come from: on `github` the range filter reads each question issue's close date instead of a `Resolved:` line, and the open / blocked / out-of-scope sections come from the frontier query rather than the checklist — see `github-issues.md`.
|
||||||
|
|
||||||
## When it fires
|
## When it fires
|
||||||
|
|
||||||
@@ -14,17 +14,17 @@ The argument (or message) asks for a `brief`, `summary`, `recap`, or `minutes` f
|
|||||||
/plan2code-0-pathfinder full brief for specs/<idea>/pathfinder
|
/plan2code-0-pathfinder full brief for specs/<idea>/pathfinder
|
||||||
```
|
```
|
||||||
|
|
||||||
Translate the person's words into the script's range: `today` (the default when unstated) · `this-week` (Monday through today) · `since:<YYYY-MM-DD>` · `<YYYY-MM-DD>..<YYYY-MM-DD>` · `full` (everything since the map was created). Resolve a relative phrase ("since Tuesday") to a date yourself; the script takes dates only and reads today from the clock.
|
Range grammar is deliberately loose: `today` (the default when unstated) · `this week` · `since <date>` · an explicit `<date>..<date>` · `full` (everything since the map was created). Get today's date from the shell — never guess it.
|
||||||
|
|
||||||
No `map.md` for the idea? There is nothing to brief — say so and route to charting. `**Status:** Cleared`? A brief is still legitimate: cover the full history and point at the PLAN-DRAFT in `## Next step`.
|
No `map.md` for the idea? There is nothing to brief — say so and route to charting. `**Status:** Cleared`? A brief is still legitimate: cover the full history and point at the PLAN-DRAFT in `## Next step`.
|
||||||
|
|
||||||
## Procedure
|
## Procedure
|
||||||
|
|
||||||
1. **Resolve the idea** exactly as Auto-Discovery does.
|
1. **Resolve the idea** exactly as Auto-Discovery does (shell only — `specs/` is gitignored, Glob silently fails).
|
||||||
2. **Reconcile first**: `node "<S>/pathfinder.mjs" reconcile specs/<idea>/pathfinder`. A brief must never disagree with the map it summarizes, which is why BRIEF mode repairs drift rather than reporting it. Keep its `repairs` for step 5.
|
2. **Reconcile first, in full** (Work Step 2): files win over markers, stale claims reset to `open`, absent `Resolved:` dates backfilled from `Claimed:`. Save the repaired map. A brief must never disagree with the map it summarizes — this is why BRIEF mode reconciles rather than reporting drift.
|
||||||
3. **Gather**: `node "<S>/pathfinder.mjs" brief-data specs/<idea>/pathfinder --range <range>`. It filters resolved questions by `Resolved:` date and returns every section's source (below), the file to write, and `drift` / `undatedResolved` (both empty after step 2; if not, rerun step 2). Out-of-scope rulings are never date-filtered: standing scope boundaries appear in every brief.
|
3. **Filter**: resolved questions whose `Resolved:` date falls in the range. Out-of-scope rulings are NOT date-filtered — they are standing scope boundaries and appear in every brief.
|
||||||
4. **Write** the file at its `file` path (create `briefs/` if absent). The name carries today's date regardless of range; the `**Covers:**` line disambiguates. Same-day re-runs overwrite (`exists: true`): a brief is a report, not a record; the question files remain the record.
|
4. **Write** `specs/<idea>/pathfinder/briefs/brief-<YYYYMMDD>.md` (create `briefs/` if absent). The filename carries today's date regardless of range — the `**Covers:**` line disambiguates. Same-day re-runs overwrite: a brief is a report, not a record; the question files remain the record.
|
||||||
5. **Report** in chat: the file path, the range, one line on any reconcile repairs. Then the Trail Footer, Form A (the session is over; the command routes by map status as usual). Run `lint` first: it checks the brief for percent signs and scraper bait.
|
5. **Report** in chat: the file path, the range, one line on any reconcile repairs. Then the Trail Footer, Form A (the session is over; the command routes by map status as usual).
|
||||||
|
|
||||||
## The template
|
## The template
|
||||||
|
|
||||||
@@ -78,17 +78,17 @@ Run: `/plan2code-0-pathfinder specs/audit-log-export/pathfinder`
|
|||||||
|
|
||||||
**How each section is built:**
|
**How each section is built:**
|
||||||
|
|
||||||
| Section | `brief-data` field | Rendering rule |
|
| Section | Source | Rendering rule |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Heading + `**Covers:**` | `title`, `covers`, `progress` | `progress` already uses the trail's counting rule (out-of-scope excluded from the total) |
|
| Heading + `**Covers:**` | Idea name in words; the range; `<resolved>/<total>` using the trail's counting rule (out-of-scope rows excluded from the total) | |
|
||||||
| Where this is headed | `destination` | Verbatim. Never paraphrase it |
|
| Where this is headed | `## Destination`, verbatim | Never paraphrase it |
|
||||||
| Decided `<in range>` | `decidedHeading`, `decided` (`name`, `gist`, `rejected`, `hardToReverse`) | Question name bold, gist as the first line, each `rejected` entry compressed to ONE line with the why in parentheses. `hardToReverse` renders as *Recorded as hard to reverse.* — never the word "locked". Empty → `note` |
|
| Decided `<in range>` | Resolved files with `Resolved:` in range | Question name bold, gist as the first line, rejected alternatives compressed to ONE line each with the why in parentheses. `Locked: yes` renders as *Recorded as hard to reverse.* — never the word "locked" |
|
||||||
| Ruled out | `ruledOut` | One line each: name + why, link markup dropped |
|
| Ruled out | `## Out of scope`, all of it | One line each: name + why |
|
||||||
| Open - ready to decide next | `ready` | Flag each `justUnblockedBy`: "can now be decided; X landed <day>" |
|
| Open - ready to decide next | The frontier (open, unclaimed, unblocked) | Flag anything a resolution in range just unblocked: "can now be decided; X landed <day>" |
|
||||||
| Open - waiting on something first | `waiting` | Name the blocker in plain words ("waiting on the export format decision"), never `Blocked by: 02` |
|
| Open - waiting on something first | `[!]` blocked rows | Name the blocker in plain words ("waiting on the export format decision"), never `Blocked by: 02` |
|
||||||
| Still taking shape | `fog` | Lightly rephrase each bullet into one plain sentence |
|
| Still taking shape | `## Not yet specified` | Lightly rephrase each bullet into one plain sentence |
|
||||||
| How solid is this? | `confidence` | Already the plain-English line. Omit the section when it is null |
|
| How solid is this? | The map's `**Confidence:**` line | ONLY via trail.md's plain-English mapping (solid / solid-but-borderline / not yet). Omit the section if the map has no confidence line |
|
||||||
| Next step | `nextStep` | `command` as given; with a `plan`, point at that PLAN-DRAFT too |
|
| Next step | Map status | `Working`/`Charting` → the pathed resume command; `Cleared` → point at the PLAN-DRAFT and `/plan2code-1-plan` |
|
||||||
|
|
||||||
Nothing decided in the range? Keep the file honest: "No decisions were recorded in this period." under Decided, and render the open sections as usual — a meeting that only surfaced questions still gets minutes.
|
Nothing decided in the range? Keep the file honest: "No decisions were recorded in this period." under Decided, and render the open sections as usual — a meeting that only surfaced questions still gets minutes.
|
||||||
|
|
||||||
|
|||||||
@@ -351,7 +351,7 @@ Fog gathers **only toward the destination**. The destination fixes the scope, so
|
|||||||
| Reopening | Automatic, as answers land | Only if the destination is redrawn — and then as a fresh effort, not a resumption |
|
| Reopening | Automatic, as answers land | Only if the destination is redrawn — and then as a fresh effort, not a resumption |
|
||||||
| The act | An admission of ignorance | A scoping decision |
|
| The act | An admission of ignorance | A scoping decision |
|
||||||
|
|
||||||
Ruling something out of scope is a **scoping act, not a step on the route**. When a question you already created turns out to sit past the destination — mis-scoped in during charting, or exposed by a later answer — run `rule-out <NN> --reason "<why>"` (resolve.md, Ruling a question out of scope mid-work): it sets `State: out-of-scope`, marks its row `[-]` and leaves one linked line in `## Out of scope` with the reason. Then handle anything it reports `stranded`. It does not get an `## Answer` and it is not a decision the route walked.
|
Ruling something out of scope is a **scoping act, not a step on the route**. When a question you already created turns out to sit past the destination — mis-scoped in during charting, or exposed by a later answer — set `State: out-of-scope`, mark its row `[-]`, and leave one line in `## Out of scope` giving the gist and the reason, linking the question by name. It does not get an `## Answer` and it is not a decision the route walked.
|
||||||
|
|
||||||
Watch for **stranded** questions: a live question whose `Blocked by:` names something now out of scope will never unblock. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
|
Watch for **stranded** questions: a live question whose `Blocked by:` names something now out of scope will never unblock. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
|
||||||
|
|
||||||
@@ -369,7 +369,7 @@ The rules:
|
|||||||
2. **Blockers get lower numbers.** If *Row-count ceiling* blocks *Delivery channel*, the ceiling is `02` and delivery is `05`. This makes `Blocked by: 02` readable at a glance and makes "lowest `NN` first" on the frontier a sane traversal order.
|
2. **Blockers get lower numbers.** If *Row-count ceiling* blocks *Delivery channel*, the ceiling is `02` and delivery is `05`. This makes `Blocked by: 02` readable at a glance and makes "lowest `NN` first" on the frontier a sane traversal order.
|
||||||
3. **`00` is always the codebase context.** Never anything else.
|
3. **`00` is always the codebase context.** Never anything else.
|
||||||
4. **`NN` is never reused and never renumbered.** Not when a question is ruled out of scope, not when one is deleted, not to close a gap in the sequence. Links and `Blocked by:` lines would rot silently. Gaps in the numbering are normal and harmless.
|
4. **`NN` is never reused and never renumbered.** Not when a question is ruled out of scope, not when one is deleted, not to close a gap in the sequence. Links and `Blocked by:` lines would rot silently. Gaps in the numbering are normal and harmless.
|
||||||
5. **The next number is max + 1**, and `frontier` reports it as `nextNN`: one past the highest `NN` in the directory listing, on any `Blocked by:` line, or in any `questions/NN-` link in the map or a question file, and never below the map's `**Next NN:**` line. That line is a high-water mark the script keeps (every write command updates it, and it only rises), so even a deleted question that nothing links to any more never has its number handed out again. Never edit it by hand.
|
5. **The next number is max + 1**, computed from the directory listing, not from the map.
|
||||||
6. **Only depend on what genuinely gates the question.** A `Blocked by:` chain that is really a preference for reading order strangles the frontier. Ask: could this question be answered — badly but honestly — without the blocker? If yes, it is not blocked.
|
6. **Only depend on what genuinely gates the question.** A `Blocked by:` chain that is really a preference for reading order strangles the frontier. Ask: could this question be answered — badly but honestly — without the blocker? If yes, it is not blocked.
|
||||||
7. **Cycles are a phrasing bug.** If A blocks B and B blocks A, the two are one decision. Merge them or re-frame one to drop the edge.
|
7. **Cycles are a phrasing bug.** If A blocks B and B blocks A, the two are one decision. Merge them or re-frame one to drop the edge.
|
||||||
8. **Refer by name in prose.** Bare numbers appear only on `Blocked by:` lines.
|
8. **Refer by name in prose.** Bare numbers appear only on `Blocked by:` lines.
|
||||||
@@ -410,16 +410,11 @@ Say once, at Step 5: *"This map lives in gitignored `specs/` — local to you, n
|
|||||||
**Status:** Working
|
**Status:** Working
|
||||||
**Updated:** 2026-08-03
|
**Updated:** 2026-08-03
|
||||||
**Confidence:** Requirements-clarity 18/25 · Feasibility-technical 14/25 · Integration-points 16/25 · Risk-assessment 14/25
|
**Confidence:** Requirements-clarity 18/25 · Feasibility-technical 14/25 · Integration-points 16/25 · Risk-assessment 14/25
|
||||||
**Next NN:** 07
|
|
||||||
|
|
||||||
<!-- Status: Charting while the map is being built (Chart Steps 1-6) -> Working once the
|
<!-- 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.
|
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. -->
|
A fresh session routes on this line, so it must be correct before the session ends. -->
|
||||||
|
|
||||||
<!-- 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. Leave it out at Step 5; never edit it. -->
|
|
||||||
|
|
||||||
<!-- Confidence: four dimensions, each scored out of 25, re-scored at every resolution.
|
<!-- 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. -->
|
The Clearing Gate requires all four at 18/25 or better. Score against evidence. -->
|
||||||
|
|
||||||
@@ -436,9 +431,7 @@ plan, not at shipped code. Continuous streaming to external systems is not on th
|
|||||||
## Ground rules
|
## Ground rules
|
||||||
|
|
||||||
<!-- Standing constraints for every session on this map. Read before choosing a question,
|
<!-- Standing constraints for every session on this map. Read before choosing a question,
|
||||||
obeyed while resolving it. Nothing here is re-asked. The first line records AGENTS.md:
|
obeyed while resolving it. Nothing here is re-asked. -->
|
||||||
"- `AGENTS.md` exists and governs." or, when it is missing, exactly
|
|
||||||
"- `AGENTS.md` is absent." (the handoff then routes to /plan2code-init first). -->
|
|
||||||
|
|
||||||
- `AGENTS.md` exists and governs. Its conventions are not re-litigated by any question here.
|
- `AGENTS.md` exists and governs. Its conventions are not re-litigated by any question here.
|
||||||
- One question _file_ at a time; the fork-menu between decisions; a fresh session recommended after ~3. `research` questions may run as parallel subagents.
|
- One question _file_ at a time; the fork-menu between decisions; a fresh session recommended after ~3. `research` questions may run as parallel subagents.
|
||||||
|
|||||||
@@ -401,8 +401,6 @@ Form B is unchanged — a turn that asks the human something still says `WAITING
|
|||||||
|
|
||||||
Form C — the fork-menu after a recorded decision — is unchanged in shape, with two substitutions: the takeable options come from the frontier query rather than the checklist rows, and the `OR START FRESH` command carries the map issue URL. The `RECOMMENDED` marker and the ~3-decision checkpoint work exactly as `trail.md` describes.
|
Form C — the fork-menu after a recorded decision — is unchanged in shape, with two substitutions: the takeable options come from the frontier query rather than the checklist rows, and the `OR START FRESH` command carries the map issue URL. The `RECOMMENDED` marker and the ~3-decision checkpoint work exactly as `trail.md` describes.
|
||||||
|
|
||||||
With no script to draw them, the labels are exact: Form A `NEXT STEP · start a new conversation and run:`, Form B `WAITING ON YOU · answer here, in this conversation:`, Form C `OR START FRESH · new conversation, paste:`. The Form C question tool uses the header `Next step` and the question "Continue here, or start fresh? Everything is saved." (add "I recommend starting fresh, to keep me sharp." at the ~3-decision checkpoint). Its options are up to three takeable question names plus `Start fresh`, one marked `RECOMMENDED`.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## BRIEF mode
|
## BRIEF mode
|
||||||
|
|||||||
@@ -2,28 +2,22 @@
|
|||||||
|
|
||||||
Loaded at The Clearing Gate. Turns a cleared map into `specs/<idea>/PLAN-DRAFT-<YYYYMMDD>.md` that `/plan2code-1-plan` resumes from at Phase 4, then freezes `pathfinder/` as the rationale record.
|
Loaded at The Clearing Gate. Turns a cleared map into `specs/<idea>/PLAN-DRAFT-<YYYYMMDD>.md` that `/plan2code-1-plan` resumes from at Phase 4, then freezes `pathfinder/` as the rationale record.
|
||||||
|
|
||||||
**Backend note.** The scoring rubric, the hard caps, the honesty rules, the template, and the mapping table are the same either way — and the draft is written to local disk either way, because `/plan2code-1-plan` reads a file, not a tracker. On `**Backend:** github`, `github-issues.md` replaces only the preflight table, the question links (issue URLs, already absolute), and the freeze steps. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes.
|
**Backend note.** The scoring rubric, the hard caps, the honesty rules, the template, and the mapping table are the same either way — and the draft is written to local disk either way, because `/plan2code-1-plan` reads a file, not a tracker. On `**Backend:** github`, `github-issues.md` replaces only the preflight table, the question links (issue URLs, already absolute), and the freeze steps.
|
||||||
|
|
||||||
Nothing here is creative. The gate is scored, the mapping is fixed, the template is literal. Follow it exactly or the resuming plan session silently loses work.
|
Nothing here is creative. The gate is scored, the mapping is fixed, the template is literal. Follow it exactly or the resuming plan session silently loses work.
|
||||||
|
|
||||||
## Preflight — before scoring anything
|
## Preflight — before scoring anything
|
||||||
|
|
||||||
Run `reconcile`, then `node "<S>/pathfinder.mjs" gate specs/<idea>/pathfinder`. Its `checks` cover the mechanical preflight, read from the files:
|
| # | Check | If it fails |
|
||||||
|
|
||||||
| `checks` id | Means | If it fails |
|
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `markers-match-files` | The map's markers are the files' (reconcile ran) | Run `reconcile`. Markers are derived, never authored. |
|
| 1 | Re-run the reconcile pass: read every file in `questions/`, rebuild every map marker from the files | Fix the map first. Markers are derived, never authored. |
|
||||||
| `no-open-claimed-blocked` | Zero `[ ]`, `[/]`, `[!]` | Not cleared. Return to the frontier. |
|
| 2 | Zero `[ ]`, zero `[/]`, zero `[!]` rows in `## Question Checklist` | Not cleared. Return to the frontier. |
|
||||||
| `fog-empty` | `## Not yet specified` is empty | Not cleared. Graduate the fog into questions, or admit it is out of scope. |
|
| 3 | `## Not yet specified` is empty | Not cleared. Graduate the fog into questions, or admit it is out of scope. |
|
||||||
| `every-resolved-has-gist` | Every resolved file has a real `## Answer` with a `**Gist:**` | The file wins over the marker. Repair, then re-check. |
|
| 4 | Every `[x]` row's file has a real `## Answer` with a `**Gist:**` | The file wins over the marker. Repair, then re-check. |
|
||||||
| `hard-caps` | None of the Requirements, Feasibility or Risk caps below holds (the Integration cap is yours to check) | That dimension cannot exceed 17: fix the record first. |
|
| 5 | `ls specs/<idea>/` shows no existing `PLAN-DRAFT-*.md` | One already exists — read it. Update it in place; never add a second dated draft. |
|
||||||
| `scores-at-least-18` | The map's `**Confidence:**` line has all four at 18 or better | Not cleared. Keep working the weak dimension. |
|
| 6 | The destination is reachable with nothing left to decide — no `## Answer` defers a choice to "whoever implements this" | Not cleared. Name the open decision and graduate it into a question. |
|
||||||
|
|
||||||
`existingPlanDraft` lists a `PLAN-DRAFT-*.md` already in `specs/<idea>/`: read it and update it in place, never add a second dated draft. `planDraftPath` is the file to write either way.
|
Only after all six pass do you score the four dimensions.
|
||||||
|
|
||||||
One preflight item stays yours: **the destination is reachable with nothing left to decide**: no `## Answer` defers a choice to "whoever implements this". If one does, the map is not cleared: name the open decision and graduate it into a question.
|
|
||||||
|
|
||||||
Score the four dimensions (below), write them to the map's `**Confidence:**` line, and rerun `gate` until `mechanicalPass` is true.
|
|
||||||
|
|
||||||
## The clearing-gate scoring rubric
|
## The clearing-gate scoring rubric
|
||||||
|
|
||||||
@@ -51,7 +45,7 @@ The 18-boundary is the honest line between *"needs designing"* and *"needs decid
|
|||||||
|
|
||||||
### Hard caps
|
### Hard caps
|
||||||
|
|
||||||
A cap overrides your judgment. While a cap condition holds, the dimension **cannot** exceed 17, so the gate cannot pass. `gate` reports the Requirements, Feasibility and Risk caps from the files (`caps`); the Integration cap needs you to match the destination's systems to questions.
|
A cap overrides your judgment. While a cap condition holds, the dimension **cannot** exceed 17, so the gate cannot pass.
|
||||||
|
|
||||||
| Cap | Condition |
|
| Cap | Condition |
|
||||||
|---|---|
|
|---|---|
|
||||||
@@ -113,7 +107,7 @@ Consequences of that being a literal string match:
|
|||||||
- Copy it byte for byte. Plain ASCII hyphen-minus surrounded by single spaces. An en dash, a colon, or "Phase 3 complete" in lower case breaks the match and 1-plan starts over at Phase 1 — throwing away every decision the map holds.
|
- Copy it byte for byte. Plain ASCII hyphen-minus surrounded by single spaces. An en dash, a colon, or "Phase 3 complete" in lower case breaks the match and 1-plan starts over at Phase 1 — throwing away every decision the map holds.
|
||||||
- It goes on its own `**Status:**` line in the header block, not buried in prose.
|
- It goes on its own `**Status:**` line in the header block, not buried in prose.
|
||||||
- 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.
|
- 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.
|
- Get the date from the shell (`date +%Y%m%d` in Bash, `Get-Date -Format yyyyMMdd` in PowerShell). Do not guess it.
|
||||||
|
|
||||||
**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 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.
|
||||||
|
|
||||||
@@ -344,8 +338,6 @@ The reason is exact. When a PLAN-DRAFT carries no `METRICS_JSON` comment, the me
|
|||||||
|
|
||||||
Never drop the footer to make the file tidier. It is load-bearing.
|
Never drop the footer to make the file tidier. It is load-bearing.
|
||||||
|
|
||||||
After writing the draft, run `lint`: it scans a pathfinder-written PLAN-DRAFT with the metrics collector's own patterns and names any bait that reached the page.
|
|
||||||
|
|
||||||
## System Context and Scope Assessment — why they buy you Phase 4
|
## System Context and Scope Assessment — why they buy you Phase 4
|
||||||
|
|
||||||
These two named, unnumbered sections are what make "Resume at Phase 4" legitimate rather than a shortcut. They stand in for the phases pathfinder already did the work of:
|
These two named, unnumbered sections are what make "Resume at Phase 4" legitimate rather than a shortcut. They stand in for the phases pathfinder already did the work of:
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ specs/<idea>/
|
|||||||
|
|
||||||
## Numbering
|
## Numbering
|
||||||
|
|
||||||
`NN` is zero-padded from `00`, assigned in dependency order (blockers lower), **never reused or renumbered** — links and `Blocked by:` would rot silently. Next = max + 1 (`frontier`'s `nextNN`), never below the map's `**Next NN:**` high-water line, which the script keeps so a deleted question's number stays retired (chart.md, Step 6 rule 5). A one-digit file name (`1-export.md`) still reads as `01`, but `lint` asks for the rename. `00` is always `00-codebase-context.md`, never anything else. Gaps in the sequence are normal and harmless.
|
`NN` is zero-padded from `00`, assigned in dependency order (blockers lower), **never reused or renumbered** — links and `Blocked by:` would rot silently. Next = max + 1. `00` is always `00-codebase-context.md`, never anything else. Gaps in the sequence are normal and harmless.
|
||||||
|
|
||||||
## The six schema lines
|
## The six schema lines
|
||||||
|
|
||||||
@@ -42,6 +42,4 @@ Each question file carries six contiguous `Key: value` lines after its H1 — NO
|
|||||||
|
|
||||||
**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: `— <gist> *(YYYY-MM-DD)*`.
|
||||||
|
|
||||||
`scripts/pathfinder.mjs` implements exactly these rules (`reconcile` rebuilds the markers, `frontier` computes blocking, `lint` checks the schema), so this file is the reference for reading its output and for writing a question file. Apply the rules by hand only when the script cannot run.
|
|
||||||
|
|
||||||
**Unblocked** ⟺ every `NN` in `Blocked by:` is `resolved`. **Stranded:** a blocker gone `out-of-scope` never resolves — the question is not merely blocked. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
|
**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.
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
> Loaded at the top of MODE B. Work Step 6 routes here by `Type:`; Work Step 8 uses the fog procedure at the end.
|
> Loaded at the top of MODE B. Work Step 6 routes here by `Type:`; Work Step 8 uses the fog procedure at the end.
|
||||||
>
|
>
|
||||||
> **Backend note.** Every resolution technique here is backend-independent — the type table, the primary-source rule, the sketch tiers, the checklist discipline, the `## Answer` anatomy. On `**Backend:** github`, `Type:` is a `pathfinder:<type>-<mode>` label, `## Answer` and `## Evidence` are comments rather than file sections, and a research subagent gets an issue URL instead of a path; see `github-issues.md`. Sketches stay on local disk regardless. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes.
|
> **Backend note.** Every resolution technique here is backend-independent — the type table, the primary-source rule, the sketch tiers, the checklist discipline, the `## Answer` anatomy. On `**Backend:** github`, `Type:` is a `pathfinder:<type>-<mode>` label, `## Answer` and `## Evidence` are comments rather than file sections, and a research subagent gets an issue URL instead of a path; see `github-issues.md`. Sketches stay on local disk regardless.
|
||||||
|
|
||||||
Every question resolves into the SAME shape — a filled `## Answer` plus whatever `## Evidence` backs it. The type only decides how you get there.
|
Every question resolves into the SAME shape — a filled `## Answer` plus whatever `## Evidence` backs it. The type only decides how you get there.
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ Every question resolves into the SAME shape — a filled `## Answer` plus whatev
|
|||||||
| `legwork · HITL` | Human does, agent waits | No | The human confirmed it is done |
|
| `legwork · HITL` | Human does, agent waits | No | The human confirmed it is done |
|
||||||
| `grill · HITL` | Human decides, agent interrogates | No — but probes batch, up to 3 per turn | The human said it in their own words |
|
| `grill · HITL` | Human decides, agent interrogates | No — but probes batch, up to 3 per turn | The human said it in their own words |
|
||||||
|
|
||||||
**One question _file_ at a time** holds for every row except `research` — several may resolve in one session, but strictly in sequence, per the Cadence below. `research` is also the one type that is **never claimed**: its subagents fire unclaimed (the file stays `State: open`), so `claim` and its one-claim rule govern grill, sketch and legwork only, and a grill can be claimed while research runs. A research question is finished with `## Answer` plus `resolve` once its subagent is back, or re-fired from `reconcile`'s `refire` if it was cut off. HITL rows are never self-answered — an agent that writes its own `## Answer` on a `grill` has broken the skill.
|
**One question _file_ at a time** holds for every row except `research` — several may resolve in one session, but strictly in sequence, per the Cadence below. HITL rows are never self-answered — an agent that writes its own `## Answer` on a `grill` has broken the skill.
|
||||||
|
|
||||||
Every file you create along the way — question files, sketch READMEs — opens with the banner:
|
Every file you create along the way — question files, sketch READMEs — opens with the banner:
|
||||||
|
|
||||||
@@ -42,7 +42,7 @@ The restart costs one paste and loses nothing: every claim, answer, and map upda
|
|||||||
|
|
||||||
- Read only what the cycle needs: the claimed question file plus resolved neighbors' *gists* (Work Step 5). Never re-read the whole `questions/` directory between cycles — reconcile ran once at session start, and this session is the only writer.
|
- Read only what the cycle needs: the claimed question file plus resolved neighbors' *gists* (Work Step 5). Never re-read the whole `questions/` directory between cycles — reconcile ran once at session start, and this session is the only writer.
|
||||||
- The menu renders from the map's checklist rows, never from re-reading question files.
|
- The menu renders from the map's checklist rows, never from re-reading question files.
|
||||||
- Strictly one claim open at any moment. Claim → record → release, then the menu. Never two. (Research subagents run unclaimed beside it; see the top of this file.)
|
- Strictly one claim open at any moment. Claim → record → release, then the menu. Never two.
|
||||||
|
|
||||||
**Group sessions.** When Product and Engineering (or any room) work the map together, the grilling playbook's group-session rules apply: probes address the room, the recap captures the decision in the room's words, and a contested pick is never recorded as decided — both positions go under `## Evidence`, the question stays `open`, and the menu moves on (or offer to convert it to `sketch`; reacting to something concrete resolves more standoffs than argument). At Session End, offer `write a brief for today` — the brief doubles as the meeting minutes.
|
**Group sessions.** When Product and Engineering (or any room) work the map together, the grilling playbook's group-session rules apply: probes address the room, the recap captures the decision in the room's words, and a contested pick is never recorded as decided — both positions go under `## Evidence`, the question stays `open`, and the menu moves on (or offer to convert it to `sketch`; reacting to something concrete resolves more standoffs than argument). At Session End, offer `write a brief for today` — the brief doubles as the meeting minutes.
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ The restart costs one paste and loses nothing: every claim, answer, and map upda
|
|||||||
|
|
||||||
## `research · AFK`
|
## `research · AFK`
|
||||||
|
|
||||||
The only type an agent resolves alone, and the only type that may run several at once. Charting fires them in a batch at Chart Step 8; MODE B fires any that appear later the same way, unclaimed: never run `claim` on a research question. When one tops the frontier at Work Step 4, fire it, then claim the first non-research question.
|
The only type an agent resolves alone, and the only type that may run several at once. Charting fires them in a batch at Chart Step 8; MODE B fires any that appear later the same way.
|
||||||
|
|
||||||
### Spin up a subagent
|
### Spin up a subagent
|
||||||
|
|
||||||
@@ -78,7 +78,7 @@ Subagents run inside this session's process, even when the harness runs them in
|
|||||||
|
|
||||||
### Interrupted research
|
### Interrupted research
|
||||||
|
|
||||||
At Work Step 2, `reconcile` lists in `refire` every research question that is not resolved and whose `## Evidence` lacks the `**Research complete:**` line (with its path and `## Question` text for the brief): it was never finished, by a closed terminal, a crash, a rate limit. Re-fire its subagent with the same brief, plus one instruction: keep what is already in `## Evidence`, verify it, fill the gaps, then write the line. Say so in one line to the human. A map written before this line existed shows the same symptom; re-firing it costs a little time and nothing else.
|
At Work Step 2 (Reconcile), any research question that is not resolved and whose `## Evidence` lacks the `**Research complete:**` line was never finished: a closed terminal, a crash, a rate limit. Re-fire its subagent with the same brief, plus one instruction: keep what is already in `## Evidence`, verify it, fill the gaps, then write the line. Say so in one line to the human. A map written before this line existed shows the same symptom; re-firing it costs a little time and nothing else.
|
||||||
|
|
||||||
### Primary sources only
|
### Primary sources only
|
||||||
|
|
||||||
@@ -421,7 +421,7 @@ If the legwork turns out to BE the deliverable rather than an unblocker — you
|
|||||||
|
|
||||||
> "This has stopped being legwork that unblocks a decision and become the work itself. Pathfinder plans; it doesn't build. I'm ruling this out of scope and it belongs in planning."
|
> "This has stopped being legwork that unblocks a decision and become the work itself. Pathfinder plans; it doesn't build. I'm ruling this out of scope and it belongs in planning."
|
||||||
|
|
||||||
Rule the question out with `rule-out <NN> --reason "<what it turned into>"` (it marks the row `[-]` and adds the `## Out of scope` line), and hand off to `/plan2code-1-plan` for that piece. Never let pathfinder quietly become the implementation.
|
Rule the question `out-of-scope`, mark the map row `[-]`, add one line to `## Out of scope` naming what it turned into, and hand off to `/plan2code-1-plan` for that piece. Never let pathfinder quietly become the implementation.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -446,7 +446,7 @@ A good grill `## Answer` contains four things:
|
|||||||
|
|
||||||
## Writing the `## Answer`
|
## Writing the `## Answer`
|
||||||
|
|
||||||
Same anatomy for every type. Append it at Work Step 7; never edit `## Question` to match the answer. Then run `node "<S>/pathfinder.mjs" resolve specs/<idea>/pathfinder <NN>`: it sets `State: resolved` **and** `Resolved:` to today (from the clock; the date is what lets a brief report "decided on <day>"), and writes the map row from your `**Gist:**`. It refuses an Answer with no Gist line.
|
Same anatomy for every type. Append it at Work Step 7; never edit `## Question` to match the answer. In the same write, set `State: resolved` **and** `Resolved:` to today's date (`YYYY-MM-DD`, from the shell, never guessed) — the date is what lets a brief report "decided on <day>", so a resolution without it is incomplete.
|
||||||
|
|
||||||
| Part | Required | Content |
|
| Part | Required | Content |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
@@ -519,7 +519,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.
|
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?
|
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. Next `NN` = max existing + 1, never reused. Fill all five metadata lines, with `Blocked by:` wired in the same pass. Add its `[ ]` or `[!]` row to `## Question Checklist`.
|
||||||
4. **DELETE the bullet from `## Not yet specified`.** Immediately, in the same edit as writing the file.
|
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.
|
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. **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.
|
||||||
@@ -538,9 +538,10 @@ Detection is cheap: after writing any graduated question file, re-read `## Not y
|
|||||||
|
|
||||||
The destination fixes the scope. When a resolution reveals that a question — the one you just claimed, or another on the map — sits past the destination:
|
The destination fixes the scope. When a resolution reveals that a question — the one you just claimed, or another on the map — sits past the destination:
|
||||||
|
|
||||||
1. Decide the one-line reason. Do NOT write a `## Answer`; there is no decision, only a scope boundary.
|
1. Set that file's `State: out-of-scope`. Do NOT write a `## Answer`; there is no decision, only a scope boundary. Add one line under `## Question` saying why it is out.
|
||||||
2. Run `node "<S>/pathfinder.mjs" rule-out specs/<idea>/pathfinder <NN> --reason "<why>"`. It sets `State: out-of-scope`, adds the reason under `## Question`, marks the row `[-]` and adds the linked line to `## Out of scope`.
|
2. Set its map row to `[-]`.
|
||||||
3. Handle its `stranded` list: questions whose `Blocked by:` names it. A blocker that is `out-of-scope` will never be `resolved`, so the dependent is permanently blocked. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
|
3. Add one line to `## Out of scope`: the name as a link, plus the reason.
|
||||||
|
4. Check for **stranded** questions — anything whose `Blocked by:` names it. A blocker that is `out-of-scope` will never be `resolved`, so the dependent is permanently blocked. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
|
||||||
|
|
||||||
Out-of-scope work never graduates back. The frontier stops at the destination. It returns only if the destination is redrawn, and then as a fresh effort with a fresh map.
|
Out-of-scope work never graduates back. The frontier stops at the destination. It returns only if the destination is redrawn, and then as a fresh effort with a fresh map.
|
||||||
|
|
||||||
@@ -558,9 +559,9 @@ An answer can also break questions that already exist. Three cases:
|
|||||||
| What happened | Do this |
|
| What happened | Do this |
|
||||||
|---|---|
|
|---|---|
|
||||||
| The question still matters but is asked wrong | **Re-frame.** Rewrite `## Question` in place. Keep `NN`, keep the file, keep the links. Add one line noting which answer forced the re-frame. |
|
| The question still matters but is asked wrong | **Re-frame.** Rewrite `## Question` in place. Keep `NN`, keep the file, keep the links. Add one line noting which answer forced the re-frame. |
|
||||||
| The question no longer exists — the answer subsumed it | **Delete the file, then run `reconcile`** (it drops the map row). Add one line to the answering question's `## Answer` consequences saying what it absorbed. Do not renumber anything. |
|
| The question no longer exists — the answer subsumed it | **Delete the file and its map row.** Add one line to the answering question's `## Answer` consequences saying what it absorbed. Do not renumber anything. |
|
||||||
| The question is now two questions | **Re-frame the original to the narrower half; write a new file at max+1 for the other.** Wire `Blocked by:` between them if one gates the other. |
|
| The question is now two questions | **Re-frame the original to the narrower half; write a new file at max+1 for the other.** Wire `Blocked by:` between them if one gates the other. |
|
||||||
|
|
||||||
Never leave a question standing that you know is wrong on the theory that a later session will notice. It will not — it assumes no memory, and a well-formed `## Question` reads as intentional.
|
Never leave a question standing that you know is wrong on the theory that a later session will notice. It will not — it assumes no memory, and a well-formed `## Question` reads as intentional.
|
||||||
|
|
||||||
Two hard constraints on all three cases: **`NN` is never reused and never renumbered** — links and `Blocked by:` lines would rot silently. And run `reconcile` straight after any re-frame or deletion, so the index never disagrees with the files (it drops the row of a deleted file and adds one for a new file).
|
Two hard constraints on all three cases: **`NN` is never reused and never renumbered** — links and `Blocked by:` lines would rot silently. And every re-frame or deletion is reflected in the map's `## Question Checklist` in the same edit, so the index never disagrees with the files.
|
||||||
@@ -2,85 +2,193 @@
|
|||||||
|
|
||||||
> Loaded at the top of the skill. Read once; it applies to EVERY response in both modes. Defines the map visual and the pathed resume command that close each turn.
|
> Loaded at the top of the skill. Read once; it applies to EVERY response in both modes. Defines the map visual and the pathed resume command that close each turn.
|
||||||
>
|
>
|
||||||
> **Backend note.** The glyphs, the two forms, and the discipline are identical either way. On `**Backend:** github` the inputs come from the sub-issue query rather than the checklist, and Form A's command is the map issue URL — see `github-issues.md`. `pathfinder.mjs` reads local files only, so on `github` do each script step below except `lint` by hand with `gh`, as `github-issues.md` describes.
|
> **Backend note.** The glyphs, the two forms, and the discipline are identical either way. On `**Backend:** github` the inputs come from the sub-issue query rather than the checklist, and Form A's command is the map issue URL — see `github-issues.md`.
|
||||||
|
|
||||||
The trail is how a human with no memory of the last session sees, at a glance, how far the map has come and what is left — and copies the exact command to resume without hunting for a path that lives in gitignored `specs/`. It closes every response once a map exists.
|
The trail is how a human with no memory of the last session sees, at a glance, how far the map has come and what is left — and copies the exact command to resume without hunting for a path that lives in gitignored `specs/`. It closes every response once a map exists.
|
||||||
|
|
||||||
It is **presentation only**, rebuilt fresh from the files every response and never written to disk. The script draws it; you choose its form.
|
It is **presentation only**. Rebuild it fresh from `map.md` each response; never write it to disk, and never let it emit a loop token (`TASK_COMPLETE`, `PHASE_COMPLETE`, and the rest). It is an index of an index — the question files remain ground truth.
|
||||||
|
|
||||||
```
|
|
||||||
node "<S>/pathfinder.mjs" trail specs/<idea>/pathfinder --form A|B|C [--item "<probe>" ...] --text
|
|
||||||
```
|
|
||||||
|
|
||||||
`--text` prints the footer itself: paste it verbatim as the last thing in the response. Use it for Forms A and B. For Form C leave `--text` off: the JSON carries the same `text` plus the `menu` the question tool needs. Run `reconcile` first in a session (Work Step 2) so the files it reads are settled.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## When it renders, and which form
|
## When it renders
|
||||||
|
|
||||||
The **turn type** picks the form, never the map's status. This is the one decision the script cannot make for you.
|
| Situation | Footer? |
|
||||||
|
|
||||||
| Situation | Footer |
|
|
||||||
|---|---|
|
|---|---|
|
||||||
| `map.md` exists and the turn **ends the session** — Session End, a cleared map, a fully blocked frontier, a parked grill | **Form A**: the trail, then the resume command |
|
| `map.md` exists and the turn **ends the session** — Session End, a cleared map, a fully blocked frontier | **Yes**, both parts: the trail, then the resume command (Form A) |
|
||||||
| `map.md` exists and the turn **asks the human something** — a probe batch, a sketch put up for reaction, a `legwork · HITL` checklist, the Chart Step 2 destination grill, the Chart Step 4 frontier grill | **Form B**: the trail, then the waiting notice. Never a resume command |
|
| `map.md` exists and the turn **asks the human something** — a probe batch, a sketch put up for reaction, a `legwork · HITL` checklist | **Yes**, but with the waiting form of Part 2 (Form B). Never a resume command — see below |
|
||||||
| `map.md` exists and the turn **offers the menu after a recorded decision** — the continue-or-stop fork of the Work cadence | **Form C**: the trail, the `OR START FRESH` command, then the question tool |
|
| `map.md` exists and the turn **offers the menu after a recorded decision** — the continue-or-stop fork of the Work cadence | **Yes**, the fork form of Part 2 (Form C): the takeable questions AND the resume command as the stop branch |
|
||||||
| Intent Gate (Step 0), the no-fog off-ramp, or any route-and-stop before Step 5 | **None** — no map on disk yet, and no path to resume |
|
| Intent Gate (Step 0), the no-fog off-ramp, or any route-and-stop before Step 5 | **No** — no map on disk yet, and no path to resume. There is nothing to draw. |
|
||||||
|
|
||||||
One idea per session, so there is only ever one trail.
|
One idea per session, so there is only ever one trail. Draw the trail for the active idea and no other.
|
||||||
|
|
||||||
### What the script draws (so you can read it, not build it)
|
---
|
||||||
|
|
||||||
|
## The two parts
|
||||||
|
|
||||||
|
Always in this order, after everything else in the response:
|
||||||
|
|
||||||
|
1. **The trail** — the horizontal path plus its legend and confidence line. Identical on every turn.
|
||||||
|
2. **The next line** — either the pathed resume command or the waiting notice, chosen by turn type.
|
||||||
|
|
||||||
|
### Part 1 — the trail
|
||||||
|
|
||||||
```
|
```
|
||||||
🧭 audit-log-export · Working · 2/6 cleared
|
🧭 audit-log-export · Working · 2/7 cleared
|
||||||
START ●━●━◉··○··○··⊘··⊝ ····⚑
|
START ●━●━◉··○··○··⊘··⊝ ····⚑
|
||||||
● done · ◉ here · ○ open · ⊘ blocked · ⊝ out of scope · ⚑ destination · ~4 fog
|
● done · ◉ here · ○ open · ⊘ blocked · ⊝ out of scope · ⚑ destination · ~4 fog
|
||||||
1 Codebase context ✔ · 2 Export format ✔ · 3 Row-count ceiling ◀ here · 4 Export authorization
|
1 Codebase context ✔ · 2 Export format ✔ · 3 Row-count ceiling ◀ here
|
||||||
5 Testing posture · 6 Delivery channel (blocked:3) · 7 SIEM push (out of scope)
|
4 Export authorization · 5 Testing posture · 6 Delivery channel (blocked:3) · 7 SIEM push (out of scope)
|
||||||
Confidence: solid, but Risk is borderline.
|
Confidence: solid, but Risk is borderline.
|
||||||
|
|
||||||
WAITING ON YOU · answer here, in this conversation:
|
|
||||||
Q2 Ceiling behaviour past the cap (re-ask) · Q3 Who sees the truncation warning
|
|
||||||
```
|
```
|
||||||
|
|
||||||
- The heading counts resolved questions over every question except out-of-scope ones.
|
How each line is built, top to bottom:
|
||||||
- One glyph per question in `NN` order: `●` resolved, `◉` claimed, `○` open, `⊘` blocked, `⊝` out of scope. A solid `━` leads into a walked stop (`●`, `◉`); `··` leads into one still ahead. `····⚑` stands for the fog; with no fog the path ends `━⚑` once every stop is walked (or ruled out) and `··⚑` while any is still ahead. A cleared map ends `━⚑ arrived` and drops both legend lines.
|
|
||||||
- The named legend numbers stops by position, and `(blocked:3)` points at stop 3.
|
|
||||||
- The confidence line is the map's four internal scores reduced to plain English: `solid` (all ≥ 20), `solid, but <Dimension> is borderline` (all ≥ 18, some at 18-19), `not yet — <Dimension(s)> still need work` (any < 18). The raw numbers never reach the human. No `**Confidence:**` line on the map, no confidence line in the trail.
|
|
||||||
|
|
||||||
---
|
- **Heading** — `🧭 <idea> · <Status> · <resolved>/<total> cleared`. `<Status>` is the map's `**Status:**` verbatim (`Charting` / `Working` / `Cleared`). `<resolved>` counts `[x]` rows; `<total>` counts every question row **except** out-of-scope `[-]` rows (a ruled-out question is off the route, not an unfinished stop).
|
||||||
|
- **The path** — one glyph per question row in `NN` order, left to right, from `START` to the `⚑` destination. Connectors carry meaning: solid `━` joins stops already walked (everything up to and including `◉ here`); dashed `··` joins stops still ahead. After the last question glyph, a fog stretch `····` then `⚑` — drop both if there is no fog and join straight to `⚑` with `━`.
|
||||||
|
- **The legend** — only the glyphs actually on this path, so a map with no blocked question does not advertise `⊘`. Append `~N fog` when `## Not yet specified` holds N bullets.
|
||||||
|
- **The named legend** — the same `NN` order, `<NN> <Name>` each, `·`-separated, wrapping across lines as needed. Tag each: `✔` resolved, `◀ here` the claimed one, `(blocked:NN)` with its blocker, `(out of scope)`. Names come straight from the checklist rows.
|
||||||
|
- **Confidence** — the map's four internal scores (Requirements / Feasibility / Integration / Risk, each out of 25) exist for the Clearing Gate, not the human. Never print the raw numbers or the `R·F·I·K` letters. Instead, reduce them to one plain-English line:
|
||||||
|
|
||||||
## Form A — the turn ends the session
|
| Scores | Line |
|
||||||
|
|---|---|
|
||||||
|
| All four ≥ 20 | `Confidence: solid.` |
|
||||||
|
| All four ≥ 18, one or more sitting at 18-19 | `Confidence: solid, but <Dimension> is borderline.` (name every dimension in that range, comma-separated) |
|
||||||
|
| Any dimension < 18 | `Confidence: not yet — <Dimension(s)> still need work.` |
|
||||||
|
|
||||||
The command follows the map's status: `/plan2code-0-pathfinder specs/<idea>/pathfinder --web` while `Charting` / `Working`; `/plan2code-1-plan --web` once `Cleared`; and `/plan2code-init` first when `## Ground rules` records `AGENTS.md` absent and it still is. The path is the exact argument Auto-Discovery resolves an idea from, so the human pastes it back with zero edits.
|
Omit the whole line if the map has no `**Confidence:**` line yet.
|
||||||
|
|
||||||
## Form B — the turn asks the human something
|
### Glyph reference
|
||||||
|
|
||||||
Pass every outstanding item as `--item`, at its stable number (`--item "Q1 Duration model"`), so a partial reply is cheap and a dropped probe is visible to both of you. The script refuses more than three: the three-probe cap.
|
| Glyph | Map marker | Meaning |
|
||||||
|
|---|---|---|
|
||||||
|
| `●` | `[x]` | resolved — a stop already walked |
|
||||||
|
| `◉` | `[/]` | the claimed question — you are here |
|
||||||
|
| `○` | `[ ]` | open, on the frontier |
|
||||||
|
| `⊘` | `[!]` | open but blocked |
|
||||||
|
| `⊝` | `[-]` | ruled out of scope |
|
||||||
|
| `⚑` | — | the destination |
|
||||||
|
| `····` | — | the fog still between the last question and the destination |
|
||||||
|
|
||||||
|
### Part 2 — the next line
|
||||||
|
|
||||||
|
Part 2 answers exactly one question for the human: **is this turn over, or is it my move?** It has three forms, and the **turn type** picks between them — not the map's status.
|
||||||
|
|
||||||
|
#### Form A — the turn ends the session
|
||||||
|
|
||||||
|
```
|
||||||
|
NEXT STEP · start a new conversation and run:
|
||||||
|
`/plan2code-0-pathfinder specs/audit-log-export/pathfinder --web`
|
||||||
|
```
|
||||||
|
|
||||||
|
The path is always relative and always ends `/pathfinder` — that is exactly the argument this skill's Auto-Discovery resolves an idea from, so the human pastes it back with zero edits. Fill `<idea>` from the active map's directory; never leave the `<spec-folder>` placeholder in a rendered footer.
|
||||||
|
|
||||||
|
The command target follows the map's status, but the sentence is always the same shape — `start a new conversation and run:` followed by the command on its own line:
|
||||||
|
|
||||||
|
| Status | Command |
|
||||||
|
|---|---|
|
||||||
|
| `Charting` / `Working` | `/plan2code-0-pathfinder specs/<idea>/pathfinder --web` |
|
||||||
|
| `Cleared` | `/plan2code-1-plan --web` — point at the PLAN-DRAFT the Clearing Gate wrote |
|
||||||
|
| `Cleared`, but `## Ground rules` records `AGENTS.md` **absent** | `/plan2code-init` FIRST (offer `questions/00-codebase-context.md`), then `/plan2code-1-plan --web` |
|
||||||
|
|
||||||
|
#### Form B — the turn asks the human something
|
||||||
|
|
||||||
|
Any turn whose next move is theirs and happens **in this same conversation**: a batch of grill probes, a sketch put up for reaction, a `legwork · HITL` checklist, the Chart Step 2 destination grill, the Chart Step 4 frontier grill.
|
||||||
|
|
||||||
|
```
|
||||||
|
WAITING ON YOU · answer here, in this conversation:
|
||||||
|
Q1 Duration model · Q2 Contract while held · Q3 Placement & restore
|
||||||
|
```
|
||||||
|
|
||||||
|
Name every outstanding item at its stable number so a partial reply is cheap to give and a dropped probe is visible to both of you. `·`-separated on one line; one per line if the names run long. Never more items than the three-probe cap allows.
|
||||||
|
|
||||||
**Emit no resume command on a Form B turn.** There is nothing to resume — the session is alive and holding a claim. A resume command here reads as *we're done*, and the human either walks away mid-decision or burns the next turn asking what you meant. This is the single most common way the footer misfires, and it costs the batch the round trips batching was introduced to save.
|
**Emit no resume command on a Form B turn.** There is nothing to resume — the session is alive and holding a claim. A resume command here reads as *we're done*, and the human either walks away mid-decision or burns the next turn asking what you meant. This is the single most common way the footer misfires, and it costs the batch the round trips batching was introduced to save.
|
||||||
|
|
||||||
One exception: `grilling.md`'s unreachable-human procedure. Parking a mid-grill question and stopping IS a session end — use Form A, and say in the body that the question is parked mid-grill with its batch outstanding.
|
One exception: `grilling.md`'s unreachable-human procedure. Parking a mid-grill question and stopping IS a session end — use Form A, and say in the body that the question is parked mid-grill with its batch outstanding.
|
||||||
|
|
||||||
## Form C — the menu after a recorded decision
|
#### Form C — the menu after a recorded decision
|
||||||
|
|
||||||
Used ONLY on the Work cadence's fork-menu turn (resolve.md §Cadence), immediately after `resolve` recorded an `## Answer`. The script refuses it while a question is claimed or once the map is `Cleared`. Pass `--resolved-this-session <N>`, and `--heavy` when the decision just recorded was heavy, contested, or `Locked: yes`.
|
Used ONLY on the Work cadence's fork-menu turn (resolve.md §Cadence), immediately after an `## Answer` landed and the map row flipped `[x]`. It is the one legitimate hybrid: an *explicit* continue-or-stop fork where the resume command IS the stop branch, not a farewell.
|
||||||
|
|
||||||
It prints the stop branch, labeled `OR START FRESH · new conversation, paste:`, and returns `menu`: the header, the question text, up to three takeable questions plus `Start fresh`, and which option to mark `RECOMMENDED` (a question early in the session; `Start fresh` after ~3 resolved or a heavy decision, with the reason in the question text, "to keep me sharp").
|
First print the stop branch, clearly labeled:
|
||||||
|
|
||||||
Then invoke the structured question tool with that menu. Put each question's gist or newly-unblocked note (from `resolve`'s `unblocked`) in its description. The automatic `Other` path lets the human name a frontier question not shown (`menu.more`).
|
```
|
||||||
|
OR START FRESH · new conversation, paste:
|
||||||
|
`/plan2code-0-pathfinder specs/audit-log-export/pathfinder --web`
|
||||||
|
```
|
||||||
|
|
||||||
|
Then invoke the structured question tool (header `Next step`) asking: "Continue here, or start fresh? Everything is saved." Options: up to three takeable question names, then `Start fresh`. Put each question's gist / newly-unblocked note in its description. The automatic `Other` path lets the human name another frontier question not shown. Mark one option's description `RECOMMENDED` — early in the session that is a question; at the checkpoint it is `Start fresh`.
|
||||||
|
|
||||||
Rules for Form C:
|
Rules for Form C:
|
||||||
|
|
||||||
- **The command label is mandatory and exact.** It makes the command the stop branch, not a farewell. Never render a bare command on a menu turn.
|
- **The command label is mandatory and exact:** `OR START FRESH · new conversation, paste:`. It makes the command the stop branch, not a farewell. Never render a bare command on a menu turn.
|
||||||
- **The choice itself always uses the structured tool.** Never print `NEXT UP` as a prose menu when the tool exists.
|
- **The choice itself always uses the structured tool.** Never print `NEXT UP` as a prose menu when the tool exists.
|
||||||
|
- Options come from the map's checklist rows (names + gists), takeable questions only. Flag anything the decision just recorded unblocked. The fourth slot is `Start fresh`; `Other` covers a frontier question omitted from the top three.
|
||||||
|
- **The recommendation carries the checkpoint** (resolve.md §Cadence): early in a session recommend a question; after ~3 resolved this session — or after a heavy, contested, or `Locked: yes` decision — recommend `Start fresh`, with the reason said in the question text ("to keep me sharp").
|
||||||
- **Form C never replaces Form B.** A turn that asks probes, shows a sketch, or hands over a checklist is Form B, no command. Form C fires only between decisions, when nothing is claimed.
|
- **Form C never replaces Form B.** A turn that asks probes, shows a sketch, or hands over a checklist is Form B, no command. Form C fires only between decisions, when nothing is claimed.
|
||||||
- If the human walks away mid-menu, nothing is stranded: no claim is open, and the command to come back is already on screen.
|
- If the human walks away mid-menu, nothing is stranded: no claim is open, and the command to come back is already on screen.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## State-by-state examples
|
||||||
|
|
||||||
|
**Charting, mid-grill, no question claimed yet** (`◉` is omitted; the frontier head is the first `○`). The Chart Step 4 frontier grill is a Form B turn — the batch is above, so the footer says stay:
|
||||||
|
|
||||||
|
```
|
||||||
|
🧭 audit-log-export · Charting · 1/5 cleared
|
||||||
|
START ●··○··○··○··○ ····⚑
|
||||||
|
● done · ○ open · ⚑ destination · ~6 fog
|
||||||
|
1 Codebase context ✔ · 2 Export format · 3 Export authorization · 4 Testing posture · 5 Row-count ceiling
|
||||||
|
Confidence: not yet — Requirements, Feasibility, Integration, Risk still need work.
|
||||||
|
|
||||||
|
WAITING ON YOU · answer here, in this conversation:
|
||||||
|
Q1 Data · Q2 Surface · Q3 Permissions
|
||||||
|
```
|
||||||
|
|
||||||
|
**Working, a claimed question mid-grill** — probes are out, the claim is held, nothing is resolved yet. Same trail, Form B again. Note that Q2 is a re-ask carried over at its original number from a batch that came back partial:
|
||||||
|
|
||||||
|
```
|
||||||
|
🧭 audit-log-export · Working · 2/7 cleared
|
||||||
|
START ●━●━◉··○··○··⊘··⊝ ····⚑
|
||||||
|
● done · ◉ here · ○ open · ⊘ blocked · ⊝ out of scope · ⚑ destination · ~4 fog
|
||||||
|
1 Codebase context ✔ · 2 Export format ✔ · 3 Row-count ceiling ◀ here
|
||||||
|
4 Export authorization · 5 Testing posture · 6 Delivery channel (blocked:3) · 7 SIEM push (out of scope)
|
||||||
|
Confidence: not yet — Feasibility, Integration, Risk still need work.
|
||||||
|
|
||||||
|
WAITING ON YOU · answer here, in this conversation:
|
||||||
|
Q2 Ceiling behaviour past the cap (re-ask) · Q3 Who sees the truncation warning
|
||||||
|
```
|
||||||
|
|
||||||
|
**Frontier fully blocked** — report the chain in the body; the trail shows why nothing is takeable. Work Step 4 stops the session here, so Form A:
|
||||||
|
|
||||||
|
```
|
||||||
|
🧭 audit-log-export · Working · 5/7 cleared
|
||||||
|
START ●━●━●━●━●━⊘··⊘ ⚑
|
||||||
|
● done · ⊘ blocked · ⚑ destination
|
||||||
|
6 Delivery channel (blocked:2) · 7 Notification (blocked:6)
|
||||||
|
Confidence: not yet — Feasibility, Risk still need work.
|
||||||
|
|
||||||
|
NEXT STEP · start a new conversation and run:
|
||||||
|
`/plan2code-0-pathfinder specs/audit-log-export/pathfinder --web`
|
||||||
|
```
|
||||||
|
|
||||||
|
**Cleared** — every stop walked, fog empty, command hands off:
|
||||||
|
|
||||||
|
```
|
||||||
|
🧭 audit-log-export · Cleared · 8/8 cleared
|
||||||
|
START ●━●━●━●━●━●━●━●━⚑ arrived
|
||||||
|
Confidence: solid.
|
||||||
|
|
||||||
|
NEXT STEP · start a new conversation and run:
|
||||||
|
`/plan2code-1-plan --web`
|
||||||
|
```
|
||||||
|
|
||||||
|
At `Cleared` the named legend is optional — the destination is reached and the PLAN-DRAFT is the thing to point at. Keep the confidence line; the Clearing Gate leaned on it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Discipline
|
## Discipline
|
||||||
|
|
||||||
- **Never print a bare resume command on a turn that asks a question.** Before you choose the form, ask whether the response above it ends with something for them to answer: mid-question (probes, sketch, checklist) → Form B, no exceptions but the parked-grill one; between decisions at the fork-menu → Form C.
|
- **Never print a bare resume command on a turn that asks a question.** The footer must not tell the human to leave a conversation you are still waiting in. Before you write Part 2, ask whether the response above it ends with something for them to answer: mid-question (probes, sketch, checklist) → Form B, no command, no exceptions but the parked-grill one; between decisions at the fork-menu → Form C, where the command appears ONLY under its `OR START FRESH` label as the explicit stop branch.
|
||||||
- **Draw it, never type it.** A hand-built trail drifts from the files; the script reads them every time. If the trail disagrees with the checklist above it, run `reconcile`, but only at session start or while nothing is claimed: `reconcile` resets a claim with no answer to `open`, so mid-question it would drop your own live claim. With a claim open, finish that question instead; `resolve` rebuilds the checklist, and the next trail is drawn from it. On `github` (the script cannot read the tracker), build it by hand from the sub-issue query, following "What the script draws" exactly.
|
- **Alignment is not the point.** Glyphs sit in `NN` order and the legend names them in the same order; do not burn effort column-aligning numbers under waypoints across variable-width glyphs. Legibility over pixels.
|
||||||
|
- **Rebuild, never cache.** The markers come from the current `map.md`, which Work Step 2 has already reconciled against the question files this session. A footer that disagrees with the checklist above it means you drew from memory.
|
||||||
- **One trail.** Never render two ideas' trails, and never invent a stop the map does not list.
|
- **One trail.** Never render two ideas' trails, and never invent a stop the map does not list.
|
||||||
@@ -60,16 +60,7 @@ The first payload for a phase you are about to build:
|
|||||||
```
|
```
|
||||||
|
|
||||||
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
|
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
|
||||||
progress bar is the first thing someone watching a build looks at. The session
|
progress bar is the first thing someone watching a build looks at.
|
||||||
meter counts the build's tasks from `cleared` as it rises, so keep it current,
|
|
||||||
and start every phase (a second one in the same run too) at `"cleared": 0`.
|
|
||||||
|
|
||||||
`"version": 1` is for the first phase of a session only. A doc's version
|
|
||||||
never goes back (console.md → House rules, rule 9), so a later phase in the
|
|
||||||
same session reposts `phase` and `phasefile` at one more than the version the
|
|
||||||
page holds, with the new phase's title and content. The same goes for
|
|
||||||
`report` at sign-off and `review` in a mid-session review: version 1 the
|
|
||||||
first time, then up from wherever the page has it.
|
|
||||||
|
|
||||||
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
||||||
the person can read the prerequisites and task specs while you build. Re-post
|
the person can read the prerequisites and task specs while you build. Re-post
|
||||||
@@ -118,12 +109,6 @@ printed), never into the project or into `~/.plan2code/console/` directly:
|
|||||||
- Do not call `wait` while building. There is nothing to collect, and the page
|
- Do not call `wait` while building. There is nothing to collect, and the page
|
||||||
holds anything the person sends until you next look.
|
holds anything the person sends until you next look.
|
||||||
|
|
||||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
|
||||||
`chat` check between tasks. Follow console.md → Standing instructions for
|
|
||||||
handing independent tasks to helpers and reporting them as `helpers`. Keep the
|
|
||||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
|
||||||
with you.
|
|
||||||
|
|
||||||
### Quick questions between tasks
|
### Quick questions between tasks
|
||||||
|
|
||||||
The person can ask a Quick question on the Ask tab at any point in a build
|
The person can ask a Quick question on the Ask tab at any point in a build
|
||||||
@@ -150,15 +135,8 @@ not questions. Put them in the phase doc as they happen, and in the report.
|
|||||||
|
|
||||||
### When the workflow asks something
|
### When the workflow asks something
|
||||||
|
|
||||||
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }` in
|
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }`, and
|
||||||
the SAME post, and go into the wait loop. When the answer lands, set `working`
|
go into the wait loop. When the answer lands, set `working` again and carry on.
|
||||||
again and carry on.
|
|
||||||
|
|
||||||
A question stops the build. Never leave yourself `working` with a question
|
|
||||||
open, and never "carry on while you decide": the page reads `working` as "not
|
|
||||||
your turn", and the person is left looking at a question they cannot answer.
|
|
||||||
If there is other work the answer does not touch, finish it before you ask,
|
|
||||||
then ask and wait.
|
|
||||||
|
|
||||||
| Moment | `kind` | Notes |
|
| Moment | `kind` | Notes |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -208,8 +186,7 @@ only ever be offered once nothing could come of it:
|
|||||||
`reply` carries `Approve this phase: approved`, which is the terminal's
|
`reply` carries `Approve this phase: approved`, which is the terminal's
|
||||||
`approved`. If the note that came with an approval asks for a change, treat it
|
`approved`. If the note that came with an approval asks for a change, treat it
|
||||||
as "describe any issues": do the change first and ask again. `changes` means
|
as "describe any issues": do the change first and ask again. `changes` means
|
||||||
exactly what it says: address it, bump the report's version (a later phase's
|
exactly what it says: address it, bump the report's version, and reopen the
|
||||||
report starts above the last one's, too), and reopen the
|
|
||||||
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||||
person asking for the code review before they approve anything — see "The
|
person asking for the code review before they approve anything — see "The
|
||||||
review, mid-session" below.
|
review, mid-session" below.
|
||||||
@@ -249,9 +226,8 @@ sign-off card, and approving past it was the answer. `implement-review` ends
|
|||||||
the same way; that phase was reviewed already. Only a finished `quick-task`
|
the same way; that phase was reviewed already. Only a finished `quick-task`
|
||||||
still offers the review on its finish — see below.
|
still offers the review on its finish — see below.
|
||||||
|
|
||||||
`run` gives the approved phase its final score on the session meter (console.md →
|
`run` scores the approved phase on the session meter (console.md → Posting an
|
||||||
Posting an update → Session meter), in the same post that records the approval;
|
update → Session meter), in the same post that records the approval:
|
||||||
it takes over what the build already counted from `cleared`, never adds to it:
|
|
||||||
`implement-phase` for Implement, `implement-review-phase` for Implement +
|
`implement-phase` for Implement, `implement-review-phase` for Implement +
|
||||||
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
|
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
|
||||||
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
|
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
|
||||||
@@ -409,10 +385,7 @@ a question still owed, above the ending itself:
|
|||||||
|
|
||||||
The same build, then Stage 2 publishes the findings exactly as above (the
|
The same build, then Stage 2 publishes the findings exactly as above (the
|
||||||
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
|
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
|
||||||
item: Stage 4 is the only gate. The post that starts Stage 2's review carries
|
item: Stage 4 is the only gate. Stage 4 is the sign-off above **without the
|
||||||
`"run": { "event": "review", "id": "review" }`, as above: in this workflow it
|
|
||||||
scores the review stage's 1 point on the meter as it begins, and the phase's
|
|
||||||
final `run` leaves that point out. Stage 4 is the sign-off above **without the
|
|
||||||
review verdict** — the phase was already reviewed — with the review results
|
review verdict** — the phase was already reviewed — with the review results
|
||||||
and unresolved findings in the report doc, header "Reviewed and ready for
|
and unresolved findings in the report doc, header "Reviewed and ready for
|
||||||
sign-off" in the item's `body`. The finish never carries `review`, and its
|
sign-off" in the item's `body`. The finish never carries `review`, and its
|
||||||
|
|||||||
@@ -170,7 +170,7 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
|
|||||||
|
|
||||||
| Exit | Meaning | What you do |
|
| Exit | Meaning | What you do |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace) and `subagents` (the helpers switch, see Standing instructions). | Handle the cards (if any), the chat (if any), any `workspace` changes and any `subagents` block, then post once (below, Quick questions, Workspace and Standing instructions). |
|
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace). | Handle the cards (if any), the chat (if any) and any `workspace` changes, then post once (below, Quick questions and Workspace). |
|
||||||
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
||||||
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
||||||
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
||||||
@@ -243,7 +243,7 @@ summarise it back.
|
|||||||
Then, in ONE `post`, do all of:
|
Then, in ONE `post`, do all of:
|
||||||
|
|
||||||
- mark each answered item `"status": "answered"` and record its `answer`
|
- mark each answered item `"status": "answered"` and record its `answer`
|
||||||
- reply to every note in that item's `thread` (shape below)
|
- add your replies to any comment threads
|
||||||
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
||||||
questions)
|
questions)
|
||||||
- publish the next batch of questions
|
- publish the next batch of questions
|
||||||
@@ -251,26 +251,6 @@ Then, in ONE `post`, do all of:
|
|||||||
|
|
||||||
One post is one atomic update, so the page never shows a half-changed state.
|
One post is one atomic update, so the page never shows a half-changed state.
|
||||||
|
|
||||||
### Replying to a note
|
|
||||||
|
|
||||||
A `comment` is the person talking to you about that card, often asking
|
|
||||||
something. It shows in the card's **Notes on this** panel, and so does your
|
|
||||||
answer:
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{ "items": [{ "id": "p4", "thread": [
|
|
||||||
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
|
|
||||||
] }] }
|
|
||||||
```
|
|
||||||
|
|
||||||
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
|
|
||||||
`md`: the page reads nothing else. An entry with no `text` is rejected.
|
|
||||||
- The server writes their note into the thread as it arrives. Do not repeat
|
|
||||||
it, and send only your new entries: `thread` appends.
|
|
||||||
- Answer what they asked, in the thread, even when you also change a doc or
|
|
||||||
re-ask the question. "I've updated the doc" alone leaves the question in the
|
|
||||||
panel with no answer under it.
|
|
||||||
|
|
||||||
### Recording the answer
|
### Recording the answer
|
||||||
|
|
||||||
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
||||||
@@ -576,15 +556,8 @@ enforces it, so never tell someone to keep asking past it.
|
|||||||
The person can add folders beside the one the session started in (a shared
|
The person can add folders beside the one the session started in (a shared
|
||||||
library, a design folder), from the footer's folder label. Together they are
|
library, a design folder), from the footer's folder label. Together they are
|
||||||
the session's **workspace**: context for every skill run in this console
|
the session's **workspace**: context for every skill run in this console
|
||||||
session, each folder addressed by a short `@name`. It outlives dashboard hops,
|
session, each folder addressed by a short `@name`. It outlives dashboard hops;
|
||||||
and it is remembered: every change is saved to `workspaces.json` beside
|
a new console session starts with the original folder alone.
|
||||||
`looks.json` (never into the project), keyed by the folder the session runs
|
|
||||||
in and then by spec. A session with a spec opens on that spec's list, one with
|
|
||||||
none on the project's; a spec with nothing saved starts as a copy of the
|
|
||||||
project's list. The dashboard's picker swaps the list as the selection moves,
|
|
||||||
and a `specDir` you post mid-run takes the current list with it. There is
|
|
||||||
nothing for you to load: `open` prints the list, and a switch of spec on a
|
|
||||||
resume reaches you as ordinary workspace changes on your next `wait`.
|
|
||||||
|
|
||||||
### What you are told
|
### What you are told
|
||||||
|
|
||||||
@@ -647,84 +620,6 @@ for permission is not a failure; report only a read that failed after it.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Standing instructions
|
|
||||||
|
|
||||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
|
||||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
|
||||||
from the top bar's Subagents button. Their pick is saved per project and per
|
|
||||||
skill, off by default, and reaches you as a standing instruction, only when it
|
|
||||||
changes.
|
|
||||||
|
|
||||||
### What arrives
|
|
||||||
|
|
||||||
A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`,
|
|
||||||
after the card lines, the `Quick question:` blocks and the `Workspace:` lines.
|
|
||||||
It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting
|
|
||||||
change alone never ends a `wait` slice: it waits for the next send, or for
|
|
||||||
your next `chat` check.
|
|
||||||
|
|
||||||
```
|
|
||||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
|
||||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
|
||||||
Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.
|
|
||||||
With no way to start helpers, report one "working alone" entry for this skill run instead.
|
|
||||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.
|
|
||||||
At most 3 helpers at once.
|
|
||||||
```
|
|
||||||
|
|
||||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
|
||||||
An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …`
|
|
||||||
with the whole block again; switching off arrives as one line:
|
|
||||||
`Subagents: off (revision 4) — don't start new helpers for the rest of this session.`
|
|
||||||
|
|
||||||
It is a console setting, not something the person typed. It never answers a
|
|
||||||
card, and it is never recorded under `specs/`.
|
|
||||||
|
|
||||||
### Obeying it
|
|
||||||
|
|
||||||
- **On:** hand independent work to helpers if your tools allow it, at most
|
|
||||||
`max` at once, following the instruction lines. `max` is advisory: your
|
|
||||||
harness's own limit still applies.
|
|
||||||
- **A higher revision replaces a lower one.** Follow the latest block only.
|
|
||||||
- **Off:** start no new helpers for the rest of the session. Let running ones
|
|
||||||
finish and report them.
|
|
||||||
- **Nothing arrives:** keep doing what the skill says.
|
|
||||||
- **Scope is the skill run it arrived in.** After a dashboard launch, no block
|
|
||||||
means the switch is off for this skill, even if an earlier skill in the same
|
|
||||||
conversation was told "on": `open` starts the count again, and a launch with
|
|
||||||
the switch off sends nothing.
|
|
||||||
|
|
||||||
### Reporting helpers
|
|
||||||
|
|
||||||
Post them, at your check-ins, so the page's Subagents tab can show them. The
|
|
||||||
page never hears from a helper directly:
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{ "helpers": [
|
|
||||||
{ "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" },
|
|
||||||
{ "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." }
|
|
||||||
] }
|
|
||||||
```
|
|
||||||
|
|
||||||
- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and
|
|
||||||
`state` (`running`, `done` or `failed`) are required; `result` (at most 200)
|
|
||||||
is the one line you add once a helper ends.
|
|
||||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
|
||||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
|
||||||
too; a resume into the same skill keeps it.
|
|
||||||
- One post per change worth seeing, not a stream.
|
|
||||||
- Questions for the person stay with you, never with a helper: most harnesses
|
|
||||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
|
||||||
session.
|
|
||||||
- **No way to start helpers?** Post one `{ "id": "alone", "alone": true }`
|
|
||||||
entry for the skill run instead. The tab then says you are working alone.
|
|
||||||
- **Pathfinder:** research questions always use helpers and are always
|
|
||||||
reported, whatever the switch says. The switch governs recon, sketches and
|
|
||||||
lookups beside the conversation.
|
|
||||||
- Helpers add no session meter points. Post no `run` for them.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Launches (dashboard only)
|
## Launches (dashboard only)
|
||||||
|
|
||||||
A `dashboard` session is not a conversation: the page draws a menu of every
|
A `dashboard` session is not a conversation: the page draws a menu of every
|
||||||
@@ -759,17 +654,9 @@ finish are dropped, so you start on a blank page and post your own. A skill
|
|||||||
run inline from another (a quick task's review) keeps the page it was
|
run inline from another (a quick task's review) keeps the page it was
|
||||||
handed. A
|
handed. A
|
||||||
fresh `open` would strand the page the person is watching on the dashboard's
|
fresh `open` would strand the page the person is watching on the dashboard's
|
||||||
session while your questions went to a page nobody has open.
|
session while your questions went to a page nobody has open. Then run the
|
||||||
|
skill normally: its Interface question was already answered by being
|
||||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
launched, so start where its real work starts.
|
||||||
> own file-read tool and follow it from the top instead.** Every Plan2Code
|
|
||||||
> skill below the dashboard ships `disable-model-invocation: true` on
|
|
||||||
> purpose — it exists to be read and followed inline, not launched as a
|
|
||||||
> sub-skill — and calling one through a skill-invocation tool errors out and
|
|
||||||
> strands the hand-off mid-launch.
|
|
||||||
|
|
||||||
Its Interface step is already answered by having been launched, so start
|
|
||||||
where its real work starts.
|
|
||||||
|
|
||||||
The menu itself is the page's own list — you never send it. The page knows
|
The menu itself is the page's own list — you never send it. The page knows
|
||||||
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
||||||
@@ -841,10 +728,7 @@ commands follow the pipeline: the sign-off's is
|
|||||||
|
|
||||||
### Review (`review`)
|
### Review (`review`)
|
||||||
|
|
||||||
Scope questions up front — run standalone with nothing named, the first is
|
Scope questions up front, then the findings report as a doc (`id: "report"`),
|
||||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
|
||||||
uncommitted changes, specs, files you name; each option with its size),
|
|
||||||
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
|
|
||||||
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
||||||
id, carrying `"doc": "report"` so the card links straight to the findings.
|
id, carrying `"doc": "report"` so the card links straight to the findings.
|
||||||
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
||||||
@@ -878,14 +762,12 @@ that is what the person is there to download. The finish carries no
|
|||||||
- Chart Step 8's research subagents must all report back before the
|
- Chart Step 8's research subagents must all report back before the
|
||||||
finish (Finishing → Nothing of yours may still be running); the finish
|
finish (Finishing → Nothing of yours may still be running); the finish
|
||||||
body then names what each one found.
|
body then names what each one found.
|
||||||
- Report every research subagent as a helper, whatever the Subagents switch
|
|
||||||
says (Standing instructions → Reporting helpers).
|
|
||||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||||
sees the Trail Footer, and without this their last screen promises a question
|
sees the Trail Footer, and without this their last screen promises a question
|
||||||
that is never coming.
|
that is never coming.
|
||||||
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
|
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
|
||||||
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
|
and `pathfinder-research` (id = the question's file slug) as each research
|
||||||
subagent reports back, or when you resolve a `research` question yourself
|
subagent reports back, or when you resolve a `research` question yourself
|
||||||
(Posting an update → Session meter). Other questions score through their
|
(Posting an update → Session meter). Other questions score through their
|
||||||
answers, so there is nothing to post for them.
|
answers, so there is nothing to post for them.
|
||||||
@@ -938,13 +820,7 @@ know:
|
|||||||
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) so the page reader sees it land. |
|
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) so the page reader sees it land. |
|
||||||
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
|
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
|
||||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
|
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`. |
|
||||||
|
|
||||||
Post `activity` as each step starts, before its doc or question lands — reading
|
|
||||||
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
|
|
||||||
implementation — the same way Review does. A step with no card of its own
|
|
||||||
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
|
|
||||||
Finalize".
|
|
||||||
|
|
||||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||||
Stopping mid-finalize loses nothing
|
Stopping mid-finalize loses nothing
|
||||||
@@ -976,7 +852,7 @@ question or doc lands:
|
|||||||
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
||||||
|
|
||||||
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
||||||
merge by `id` (an unknown id is added), and `thread` appends. Send only
|
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
|
||||||
what changed. A whole-file rewrite would put the entire session back into your
|
what changed. A whole-file rewrite would put the entire session back into your
|
||||||
context on every turn.
|
context on every turn.
|
||||||
|
|
||||||
@@ -1018,9 +894,7 @@ Per-unit work is yours to report, with `run` in any post:
|
|||||||
not count), a whole number from 1 to 999. A built phase scores by its size,
|
not count), a whole number from 1 to 999. A built phase scores by its size,
|
||||||
one point per 3 tasks rounded up, and Implement + Review one more for the
|
one point per 3 tasks rounded up, and Implement + Review one more for the
|
||||||
review. Always send it: without it a phase scores a flat 2 (or 3), however
|
review. Always send it: without it a phase scores a flat 2 (or 3), however
|
||||||
big it was. On any other event it is exit `3`. The console already counts a
|
big it was. On any other event it is exit `3`.
|
||||||
build's tasks from `headline.cleared` as they are ticked off; the phase's
|
|
||||||
`run` takes that count over with the final score, so it never counts twice.
|
|
||||||
- One `run` per post. Which events a workflow reports is in its own notes
|
- One `run` per post. Which events a workflow reports is in its own notes
|
||||||
(Workflow notes → Pathfinder; `building.md` for Implement and for the
|
(Workflow notes → Pathfinder; `building.md` for Implement and for the
|
||||||
review run on the page after a build).
|
review run on the page after a build).
|
||||||
@@ -1229,16 +1103,6 @@ A patch that breaks one of these is rejected with exit `3` and a message:
|
|||||||
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
||||||
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
||||||
and 5 cover `reason` and `hint`.
|
and 5 cover `reason` and `hint`.
|
||||||
8. **`helpers` entries are well formed** (Standing instructions → Reporting
|
|
||||||
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
|
|
||||||
and a known `state` within their limits, plus at most one `alone` entry.
|
|
||||||
Rules 4 and 5 cover `title`, `ask` and `result`.
|
|
||||||
9. **A doc's `version` never goes back.** Sending a known doc a lower
|
|
||||||
`version` than the page holds is refused: it is almost always a stale or
|
|
||||||
copied payload. The same version again is fine, and a dashboard hop starts
|
|
||||||
every doc fresh. Anything else reusing a doc id in the same session (a
|
|
||||||
build's second phase, a second report or review) continues from the
|
|
||||||
version the page holds.
|
|
||||||
|
|
||||||
These are workflow rules you already follow. The server just makes them checkable.
|
These are workflow rules you already follow. The server just makes them checkable.
|
||||||
|
|
||||||
@@ -1260,9 +1124,7 @@ cannot see them, and the moment it says the session ended, the person is
|
|||||||
free to close that terminal and kill them mid-write. While you wait, post
|
free to close that terminal and kill them mid-write. While you wait, post
|
||||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||||
and update the count as each returns. Never write a `finish.body` that says
|
and update the count as each returns. Never write a `finish.body` that says
|
||||||
work "is running in the background" or "will finish on its own". Mark every
|
work "is running in the background" or "will finish on its own".
|
||||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
|
||||||
never ends on a row still running.
|
|
||||||
|
|
||||||
### 1. Post the finish
|
### 1. Post the finish
|
||||||
|
|
||||||
@@ -1368,7 +1230,7 @@ answers were submitted but never picked up.
|
|||||||
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
||||||
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
||||||
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
||||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||||
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
||||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||||
|
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ import {
|
|||||||
die,
|
die,
|
||||||
ensureDir,
|
ensureDir,
|
||||||
fileStamp,
|
fileStamp,
|
||||||
forgetWorkspace,
|
|
||||||
handOff,
|
handOff,
|
||||||
handleFile,
|
handleFile,
|
||||||
healthOk,
|
healthOk,
|
||||||
@@ -64,21 +63,16 @@ import {
|
|||||||
readChat,
|
readChat,
|
||||||
readJson,
|
readJson,
|
||||||
readLedger,
|
readLedger,
|
||||||
readSubagentCursor,
|
|
||||||
readSubagentSetting,
|
|
||||||
readWorkspace,
|
readWorkspace,
|
||||||
reapHandles,
|
reapHandles,
|
||||||
rememberedWorkspace,
|
|
||||||
remoteWarning,
|
remoteWarning,
|
||||||
removeScratch,
|
removeScratch,
|
||||||
removeSessions,
|
removeSessions,
|
||||||
repoRoots,
|
repoRoots,
|
||||||
resetSubagentCursor,
|
|
||||||
scanProject,
|
scanProject,
|
||||||
SESSION_MAX_AGE_MS,
|
SESSION_MAX_AGE_MS,
|
||||||
sessionDir,
|
sessionDir,
|
||||||
sleepSync,
|
sleepSync,
|
||||||
specKey,
|
|
||||||
staleScratch,
|
staleScratch,
|
||||||
staleSessions,
|
staleSessions,
|
||||||
sweepUploads,
|
sweepUploads,
|
||||||
@@ -91,11 +85,9 @@ import {
|
|||||||
workspaceForAgent,
|
workspaceForAgent,
|
||||||
writeCursor,
|
writeCursor,
|
||||||
writeJsonAtomic,
|
writeJsonAtomic,
|
||||||
writeSubagentCursor,
|
|
||||||
writeWorkspaceCursor,
|
writeWorkspaceCursor,
|
||||||
} from "./lib.mjs";
|
} from "./lib.mjs";
|
||||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount } from "./public/meter.js";
|
||||||
import { blockFor, offered } from "./public/subagents.js";
|
|
||||||
import { changeLine } from "./public/workspace.js";
|
import { changeLine } from "./public/workspace.js";
|
||||||
|
|
||||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||||
@@ -315,11 +307,7 @@ async function cmdOpen() {
|
|||||||
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
||||||
}
|
}
|
||||||
state = written.state;
|
state = written.state;
|
||||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
|
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
|
||||||
// A new agent conversation has been told nothing yet (FR-6).
|
|
||||||
try {
|
|
||||||
resetSubagentCursor(dir);
|
|
||||||
} catch {}
|
|
||||||
trace("open: state written");
|
trace("open: state written");
|
||||||
|
|
||||||
// Dashboard launches are recorded too (they score nothing), so the folder
|
// Dashboard launches are recorded too (they score nothing), so the folder
|
||||||
@@ -329,7 +317,7 @@ async function cmdOpen() {
|
|||||||
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
|
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
|
||||||
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
|
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
|
||||||
} catch {}
|
} catch {}
|
||||||
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
|
const workspace = workspaceOnOpen(dir, worktree);
|
||||||
|
|
||||||
// Month-old sessions and scratch files: listed before the print so the
|
// Month-old sessions and scratch files: listed before the print so the
|
||||||
// agent can see what went, removed after it so the page waits for nothing.
|
// agent can see what went, removed after it so the page waits for nothing.
|
||||||
@@ -346,18 +334,9 @@ async function cmdOpen() {
|
|||||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||||
};
|
};
|
||||||
|
|
||||||
// A standing instruction the new agent is owed, as `subagents` and a
|
|
||||||
// `reply` holding only its lines; neither key when nothing is owed.
|
|
||||||
const subagentsOwed = () => {
|
|
||||||
awaitSubagentSync(dir, state.workflow);
|
|
||||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
|
||||||
return [out.subagents ? out : {}, cursor];
|
|
||||||
};
|
|
||||||
|
|
||||||
// Reuse a live server if one is already serving this session.
|
// Reuse a live server if one is already serving this session.
|
||||||
if (existing && (await reusable)) {
|
if (existing && (await reusable)) {
|
||||||
if (!args["no-open"]) openBrowser(existing.url);
|
if (!args["no-open"]) openBrowser(existing.url);
|
||||||
const [owed, subCursor] = subagentsOwed();
|
|
||||||
print({
|
print({
|
||||||
ok: true,
|
ok: true,
|
||||||
sid,
|
sid,
|
||||||
@@ -367,11 +346,9 @@ async function cmdOpen() {
|
|||||||
pendingResult: carried,
|
pendingResult: carried,
|
||||||
terminalLine: terminalLine(existing.url),
|
terminalLine: terminalLine(existing.url),
|
||||||
workspace,
|
workspace,
|
||||||
...owed,
|
|
||||||
...swept,
|
...swept,
|
||||||
...remoteWarning(),
|
...remoteWarning(),
|
||||||
});
|
});
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
sweep();
|
sweep();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -404,7 +381,6 @@ async function cmdOpen() {
|
|||||||
const notes = [];
|
const notes = [];
|
||||||
if (remote.note) notes.push(remote.note);
|
if (remote.note) notes.push(remote.note);
|
||||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||||
const [owed, subCursor] = subagentsOwed();
|
|
||||||
print({
|
print({
|
||||||
ok: true,
|
ok: true,
|
||||||
sid,
|
sid,
|
||||||
@@ -415,12 +391,10 @@ async function cmdOpen() {
|
|||||||
pendingResult: carried,
|
pendingResult: carried,
|
||||||
terminalLine: terminalLine(handle.url),
|
terminalLine: terminalLine(handle.url),
|
||||||
workspace,
|
workspace,
|
||||||
...owed,
|
|
||||||
...swept,
|
...swept,
|
||||||
...(remote.remote ? { remote: remote.remote } : {}),
|
...(remote.remote ? { remote: remote.remote } : {}),
|
||||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||||
});
|
});
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
// After the print, never before it: the page and the link wait for nothing.
|
// After the print, never before it: the page and the link wait for nothing.
|
||||||
sweep();
|
sweep();
|
||||||
}
|
}
|
||||||
@@ -429,11 +403,10 @@ async function cmdOpen() {
|
|||||||
* The workspace as `open` hands it to the agent, and the cursor seeded to
|
* The workspace as `open` hands it to the agent, and the cursor seeded to
|
||||||
* match: the agent now has the whole list, so no change up to here is owed.
|
* match: the agent now has the whole list, so no change up to here is owed.
|
||||||
* Read-only on workspace.json, which only the server writes; on a fresh
|
* Read-only on workspace.json, which only the server writes; on a fresh
|
||||||
* session the server has not made it yet, so what was remembered for this
|
* session the server has not made it yet, so the original folder stands in.
|
||||||
* folder and spec stands in, the same list the server is about to make.
|
|
||||||
*/
|
*/
|
||||||
function workspaceOnOpen(dir, worktree, specDir) {
|
function workspaceOnOpen(dir, worktree) {
|
||||||
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
|
const ws = readWorkspace(dir) || initialWorkspace(worktree);
|
||||||
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
|
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
|
||||||
try {
|
try {
|
||||||
writeWorkspaceCursor(dir, ws.version || 0);
|
writeWorkspaceCursor(dir, ws.version || 0);
|
||||||
@@ -616,13 +589,6 @@ function cmdPost() {
|
|||||||
const next = written.state;
|
const next = written.state;
|
||||||
|
|
||||||
for (const line of ledgerLines) appendLedger(dir, line);
|
for (const line of ledgerLines) appendLedger(dir, line);
|
||||||
// A build scores its tasks as it clears them (meter.js, PROGRESS_WORKFLOWS),
|
|
||||||
// after any `run` in the same post, so a phase finished here ends its count.
|
|
||||||
if (patch.headline && typeof patch.headline === "object") {
|
|
||||||
const ledger = readLedger(dir);
|
|
||||||
const progress = progressEntry(ledger, lastLaunchId(ledger), next.workflow, patch.headline.cleared);
|
|
||||||
if (progress) appendLedger(dir, progress);
|
|
||||||
}
|
|
||||||
appendEvent(dir, { type: "post", items: (patch.items || []).length });
|
appendEvent(dir, { type: "post", items: (patch.items || []).length });
|
||||||
|
|
||||||
const open = next.items.filter((i) => isOpen(i) && i.required !== false).length;
|
const open = next.items.filter((i) => isOpen(i) && i.required !== false).length;
|
||||||
@@ -797,7 +763,7 @@ function serverGone(sid) {
|
|||||||
|
|
||||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||||
function deliverChat(dir, sid, entries, url) {
|
function deliverChat(dir, sid, entries, url) {
|
||||||
const [withWs, changes] = withWorkspace(dir, {
|
const [out, changes] = withWorkspace(dir, {
|
||||||
type: "chat",
|
type: "chat",
|
||||||
at: nowIso(),
|
at: nowIso(),
|
||||||
sid,
|
sid,
|
||||||
@@ -805,11 +771,9 @@ function deliverChat(dir, sid, entries, url) {
|
|||||||
chat: entries,
|
chat: entries,
|
||||||
reply: chatReplyLines(entries),
|
reply: chatReplyLines(entries),
|
||||||
});
|
});
|
||||||
const [out, subCursor] = withSubagents(dir, withWs);
|
|
||||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||||
advanceCursor(dir, entries);
|
advanceCursor(dir, entries);
|
||||||
advanceWorkspace(dir, changes);
|
advanceWorkspace(dir, changes);
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
process.exitCode = 0;
|
process.exitCode = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -831,52 +795,6 @@ function advanceWorkspace(dir, changes) {
|
|||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The server rewrites the session's setting for a new workflow only once its
|
|
||||||
// watcher sees the state `open` just wrote, so a launch or hop that read the
|
|
||||||
// file at once would find the old workflow's and owe the agent nothing until
|
|
||||||
// its next pickup. Give the server a moment to catch up instead, never
|
|
||||||
// writing the file ourselves (FR-7). A session with no setting file at all is
|
|
||||||
// an older server, which never writes one: a short look, not the full wait.
|
|
||||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
|
||||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
|
||||||
function awaitSubagentSync(dir, workflow) {
|
|
||||||
if (!offered(workflow)) return;
|
|
||||||
const start = Date.now();
|
|
||||||
for (;;) {
|
|
||||||
const setting = readSubagentSetting(dir);
|
|
||||||
if (setting && setting.workflow === workflow) return;
|
|
||||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
|
||||||
if (Date.now() - start >= budget) return;
|
|
||||||
sleepSync(25);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Subagents switch the agent is owed, added to what it is about to read:
|
|
||||||
// the setting as `subagents`, and its lines last in `reply`, after card lines,
|
|
||||||
// Quick questions and Workspace lines (FR-9). Read from the session's own
|
|
||||||
// setting file only, which only the server writes (FR-7). A setting for
|
|
||||||
// another workflow is the server not having caught up with a hop yet: it
|
|
||||||
// rides on the next pickup instead.
|
|
||||||
function withSubagents(dir, out) {
|
|
||||||
const setting = readSubagentSetting(dir);
|
|
||||||
if (!setting) return [out, null];
|
|
||||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
|
||||||
if (setting.workflow !== workflow) return [out, null];
|
|
||||||
const block = blockFor(setting, readSubagentCursor(dir));
|
|
||||||
if (!block) return [out, null];
|
|
||||||
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
|
|
||||||
return [{ ...out, subagents: block.field, reply }, block.cursor];
|
|
||||||
}
|
|
||||||
|
|
||||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
|
||||||
// block at the next pickup, never loses it.
|
|
||||||
function advanceSubagents(dir, cursor) {
|
|
||||||
if (!cursor) return;
|
|
||||||
try {
|
|
||||||
writeSubagentCursor(dir, cursor);
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Print first, then this, exactly as consume() stamps a result: a kill in
|
// Print first, then this, exactly as consume() stamps a result: a kill in
|
||||||
// between can only hand the same chat over again, and collectChat() drops
|
// between can only hand the same chat over again, and collectChat() drops
|
||||||
// anything that already has a reply.
|
// anything that already has a reply.
|
||||||
@@ -903,17 +821,15 @@ async function cmdChat() {
|
|||||||
}
|
}
|
||||||
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||||
const changes = pendingWorkspaceChanges(dir);
|
const changes = pendingWorkspaceChanges(dir);
|
||||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
if (!entries.length && !changes.length) {
|
||||||
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
|
|
||||||
if (!entries.length && !changes.length && !subCursor) {
|
|
||||||
print({ chat: [] });
|
print({ chat: [] });
|
||||||
process.exitCode = 10;
|
process.exitCode = 10;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||||
|
print({ chat: entries, workspace: changes, reply, terminalLine: terminalLine(handle.url) });
|
||||||
advanceCursor(dir, entries);
|
advanceCursor(dir, entries);
|
||||||
advanceWorkspace(dir, changes);
|
advanceWorkspace(dir, changes);
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
process.exitCode = 0;
|
process.exitCode = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -938,8 +854,7 @@ function consume(dir, resultPath, result, url, chat = []) {
|
|||||||
// never on result.json itself.
|
// never on result.json itself.
|
||||||
const withChat = { ...collected, chat };
|
const withChat = { ...collected, chat };
|
||||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
const [out, changes] = withWorkspace(dir, withChat);
|
||||||
const [out, subCursor] = withSubagents(dir, withWs);
|
|
||||||
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
||||||
try {
|
try {
|
||||||
writeJsonAtomic(resultPath, collected);
|
writeJsonAtomic(resultPath, collected);
|
||||||
@@ -948,7 +863,6 @@ function consume(dir, resultPath, result, url, chat = []) {
|
|||||||
ledgerAnswers(dir, result);
|
ledgerAnswers(dir, result);
|
||||||
advanceCursor(dir, chat);
|
advanceCursor(dir, chat);
|
||||||
advanceWorkspace(dir, changes);
|
advanceWorkspace(dir, changes);
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1032,18 +946,6 @@ function realNearest(p) {
|
|||||||
return path.join(fs.realpathSync(existing), path.relative(existing, p));
|
return path.join(fs.realpathSync(existing), path.relative(existing, p));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------------- forget */
|
|
||||||
|
|
||||||
// Drop the folder list remembered for one spec (Finalize, once the spec is
|
|
||||||
// archived). The project's own list and every other spec's are untouched.
|
|
||||||
function cmdForget() {
|
|
||||||
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
|
|
||||||
let spec = specKey(args.spec);
|
|
||||||
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
|
|
||||||
const worktree = repoRoots().worktree;
|
|
||||||
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ----------------------------------------------------------------- help */
|
/* ----------------------------------------------------------------- help */
|
||||||
|
|
||||||
function cmdHelp() {
|
function cmdHelp() {
|
||||||
@@ -1059,20 +961,13 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
|||||||
first post. --file is optional, and --title defaults to the
|
first post. --file is optional, and --title defaults to the
|
||||||
project's folder name. Also prints workspace: { folders: [{ name,
|
project's folder name. Also prints workspace: { folders: [{ name,
|
||||||
path, description?, original? }], missing? }, the folders this
|
path, description?, original? }], missing? }, the folders this
|
||||||
console session reads as context, addressed as @name. The list is
|
console session reads as context, addressed as @name.
|
||||||
remembered per folder and spec in workspaces.json beside looks.json.
|
|
||||||
May also print subagents: { state, revision, max, instruction } and
|
|
||||||
a reply holding only its "Subagents: ..." lines, when a standing
|
|
||||||
instruction (the page's Subagents switch) is owed to you.
|
|
||||||
post --session <sid> --file <patch.json>
|
post --session <sid> --file <patch.json>
|
||||||
Merge a patch into the session. Prints terminalLine while the
|
Merge a patch into the session. Prints terminalLine while the
|
||||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||||
{ name, reason, hint? } (a workspace folder you could not read);
|
{ name, reason, hint? } (a workspace folder you could not read);
|
||||||
both go to the ledger, never into the state. A patch may also
|
both go to the ledger, never into the state.
|
||||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
|
||||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
|
||||||
(see console.md → Standing instructions).
|
|
||||||
wait --session <sid> [--seconds <N>]
|
wait --session <sid> [--seconds <N>]
|
||||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||||
@@ -1083,24 +978,16 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
|||||||
"workspace" (changes since you last heard, each once, with a
|
"workspace" (changes since you last heard, each once, with a
|
||||||
"Workspace: ..." line in reply); exit 10 counts them as
|
"Workspace: ..." line in reply); exit 10 counts them as
|
||||||
pendingWorkspace, and a change alone never ends a slice.
|
pendingWorkspace, and a change alone never ends a slice.
|
||||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
|
||||||
by the person, with its "Subagents: ..." lines last in reply); a
|
|
||||||
setting change alone never ends a slice either.
|
|
||||||
chat --session <sid>
|
chat --session <sid>
|
||||||
Collect Quick questions, workspace changes and a Subagents
|
Collect Quick questions and workspace changes now, never waiting,
|
||||||
setting change now, never waiting, never touching card sends.
|
never touching card sends. Exit 0 = { chat, workspace, reply,
|
||||||
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
|
terminalLine }, 10 = none, 20 = server gone.
|
||||||
10 = none, 20 = server gone.
|
|
||||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||||
messages with it during a console session.
|
messages with it during a console session.
|
||||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||||
Copy a cited note attachment into specs/<idea>/attachments/. Prints
|
Copy a cited note attachment into specs/<idea>/attachments/. Prints
|
||||||
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
|
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
|
||||||
missing. Paste link as it is.
|
missing. Paste link as it is.
|
||||||
forget --spec specs/<idea>
|
|
||||||
Drop the workspace folders remembered for that spec, in this
|
|
||||||
folder (Finalize, after archiving it). Prints { ok, spec, forgot };
|
|
||||||
forgot is false when nothing was saved. Exit 2 = bad usage.
|
|
||||||
status [--session <sid>] [--all]
|
status [--session <sid>] [--all]
|
||||||
One session, or every session belonging to this project.
|
One session, or every session belonging to this project.
|
||||||
stop --session <sid> | --all
|
stop --session <sid> | --all
|
||||||
@@ -1319,7 +1206,6 @@ const COMMANDS = {
|
|||||||
wait: cmdWait,
|
wait: cmdWait,
|
||||||
chat: cmdChat,
|
chat: cmdChat,
|
||||||
keep: cmdKeep,
|
keep: cmdKeep,
|
||||||
forget: cmdForget,
|
|
||||||
status: cmdStatus,
|
status: cmdStatus,
|
||||||
stop: cmdStop,
|
stop: cmdStop,
|
||||||
help: cmdHelp,
|
help: cmdHelp,
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ import { fileURLToPath } from "node:url";
|
|||||||
import { CHAT_LIMIT } from "./public/chat.js";
|
import { CHAT_LIMIT } from "./public/chat.js";
|
||||||
import { DOC_TYPES } from "./public/answers.js";
|
import { DOC_TYPES } from "./public/answers.js";
|
||||||
import { defaultName } from "./public/workspace.js";
|
import { defaultName } from "./public/workspace.js";
|
||||||
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
|
||||||
|
|
||||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
export const PUBLIC_DIR = path.join(HERE, "public");
|
export const PUBLIC_DIR = path.join(HERE, "public");
|
||||||
@@ -49,10 +48,6 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
|
|||||||
|
|
||||||
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
||||||
|
|
||||||
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
|
|
||||||
// so every session within the hour reuses one lookup.
|
|
||||||
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
|
|
||||||
|
|
||||||
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
||||||
// test run (or a second sandboxed instance) shares one handle directory with
|
// test run (or a second sandboxed instance) shares one handle directory with
|
||||||
// the real thing, and `stop --all` reaches outside its own world and kills a
|
// the real thing, and `stop --all` reaches outside its own world and kills a
|
||||||
@@ -183,8 +178,8 @@ function lockStale(lock) {
|
|||||||
// Run fn while holding the session's state lock, and release it however fn
|
// Run fn while holding the session's state lock, and release it however fn
|
||||||
// ends. fn must not call process.exit(): the release would never run, and the
|
// ends. fn must not call process.exit(): the release would never run, and the
|
||||||
// next writer would wait out the stale age.
|
// next writer would wait out the stale age.
|
||||||
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
|
export function withStateLock(dir, fn) {
|
||||||
const lock = path.join(dir, lockName);
|
const lock = path.join(dir, STATE_LOCK_FILE);
|
||||||
const deadline = Date.now() + LOCK_WAIT_MS;
|
const deadline = Date.now() + LOCK_WAIT_MS;
|
||||||
let fd = null;
|
let fd = null;
|
||||||
for (let attempt = 0; fd === null; attempt++) {
|
for (let attempt = 0; fd === null; attempt++) {
|
||||||
@@ -193,7 +188,7 @@ export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
|
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
|
||||||
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
|
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
|
||||||
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
|
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
|
||||||
if (err.code === "EEXIST" && lockStale(lock)) {
|
if (err.code === "EEXIST" && lockStale(lock)) {
|
||||||
try {
|
try {
|
||||||
fs.rmSync(lock, { force: true });
|
fs.rmSync(lock, { force: true });
|
||||||
@@ -492,16 +487,8 @@ export async function removeSessions(sessionsDir, sids) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The console folder's own files that no sweep may ever remove: the person's
|
// The console folder's own files that no sweep may ever remove: the person's
|
||||||
// looks, the folders remembered per project and spec, the Subagents switch
|
// looks and the pointer to this console's directory.
|
||||||
// saved per project and workflow, the pointer to this console's directory,
|
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "console-dir"]);
|
||||||
// and the cached release check.
|
|
||||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
|
||||||
"looks.json",
|
|
||||||
"workspaces.json",
|
|
||||||
"subagents.json",
|
|
||||||
"console-dir",
|
|
||||||
"update-check.json",
|
|
||||||
]);
|
|
||||||
|
|
||||||
function isScratchName(name) {
|
function isScratchName(name) {
|
||||||
return (
|
return (
|
||||||
@@ -548,148 +535,6 @@ export async function removeScratch(consoleDir, names) {
|
|||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------- cleanup */
|
|
||||||
|
|
||||||
// What User Preferences -> Cleanup never removes. The console folder keeps its
|
|
||||||
// protected files, its sessions dir (old sessions go one by one, by age) and,
|
|
||||||
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
|
|
||||||
// console, the launcher (bin/, launcher.json) and the models the person added.
|
|
||||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
|
||||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
|
|
||||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
|
||||||
// folders hold files that live for milliseconds -- a held
|
|
||||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
|
||||||
// rename -- and removing one mid-write loses another session's change.
|
|
||||||
export const STRAY_GRACE_MS = 60 * 60 * 1000;
|
|
||||||
|
|
||||||
// Bytes under `p`, never following a symlink: a link counts as itself.
|
|
||||||
async function diskBytes(p) {
|
|
||||||
let st;
|
|
||||||
try {
|
|
||||||
st = await fs.promises.lstat(p);
|
|
||||||
} catch {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
if (!st.isDirectory()) return st.size;
|
|
||||||
let entries;
|
|
||||||
try {
|
|
||||||
entries = await fs.promises.readdir(p);
|
|
||||||
} catch {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
let total = 0;
|
|
||||||
for (const name of entries) total += await diskBytes(path.join(p, name));
|
|
||||||
return total;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The newest mtime of anything under `p`, never following a symlink. A folder
|
|
||||||
// counts by its files, since rewriting a file never touches its folder's
|
|
||||||
// mtime; an empty folder counts by its own. Anything unreadable on the way
|
|
||||||
// down answers Infinity, so it reads as just touched and stays.
|
|
||||||
function newestMtime(p) {
|
|
||||||
let st;
|
|
||||||
try {
|
|
||||||
st = fs.lstatSync(p);
|
|
||||||
} catch {
|
|
||||||
return Infinity;
|
|
||||||
}
|
|
||||||
if (!st.isDirectory()) return st.mtimeMs;
|
|
||||||
let entries;
|
|
||||||
try {
|
|
||||||
entries = fs.readdirSync(p);
|
|
||||||
} catch {
|
|
||||||
return Infinity;
|
|
||||||
}
|
|
||||||
if (!entries.length) return st.mtimeMs;
|
|
||||||
let newest = 0;
|
|
||||||
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
|
|
||||||
return newest;
|
|
||||||
}
|
|
||||||
|
|
||||||
function entryKind(entry) {
|
|
||||||
if (entry.isSymbolicLink()) return "link";
|
|
||||||
return entry.isDirectory() ? "folder" : "file";
|
|
||||||
}
|
|
||||||
|
|
||||||
function strayEntries(dir, kept, where, now) {
|
|
||||||
let entries;
|
|
||||||
try {
|
|
||||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
||||||
} catch {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
|
|
||||||
return entries
|
|
||||||
.filter((e) => !kept.has(e.name))
|
|
||||||
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
|
||||||
.filter((e) => settled(e.path));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Everything Cleanup would remove, worked out on the server and never taken
|
|
||||||
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
|
|
||||||
* `open` sweeps by, plus every file in the folder that old, so a resumed
|
|
||||||
* session or a saved draft keeps it), anything at the top of the console folder that is
|
|
||||||
* not kept, and -- only when the console runs from its default home inside
|
|
||||||
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
|
|
||||||
* touched within `STRAY_GRACE_MS` are left for a later scan. A
|
|
||||||
* console running from another home (tests, dev) never reaches ~/.plan2code.
|
|
||||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
|
||||||
*/
|
|
||||||
export async function cleanupFindings({
|
|
||||||
consoleDir = HOME_DIR,
|
|
||||||
plan2codeDir = PLAN2CODE_DIR,
|
|
||||||
now = Date.now(),
|
|
||||||
maxAgeMs = SESSION_MAX_AGE_MS,
|
|
||||||
skipSid,
|
|
||||||
} = {}) {
|
|
||||||
const found = [];
|
|
||||||
const sessionsDir = path.join(consoleDir, "sessions");
|
|
||||||
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
|
|
||||||
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
|
|
||||||
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
|
|
||||||
}
|
|
||||||
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
|
|
||||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
|
||||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
|
||||||
}
|
|
||||||
const items = [];
|
|
||||||
let bytes = 0;
|
|
||||||
for (const f of found) {
|
|
||||||
const size = await diskBytes(f.path);
|
|
||||||
bytes += size;
|
|
||||||
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
|
|
||||||
}
|
|
||||||
return { items, bytes };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
|
|
||||||
* worked out afresh first and only ids on it are touched, so a name from the
|
|
||||||
* page is never a path, and anything that stopped qualifying since the scan
|
|
||||||
* (a session touched again) stays. A link is unlinked, never followed.
|
|
||||||
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
|
|
||||||
*/
|
|
||||||
export async function removeCleanup(ids, opts = {}) {
|
|
||||||
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
|
|
||||||
const { items } = await cleanupFindings(opts);
|
|
||||||
const removed = [];
|
|
||||||
const failed = [];
|
|
||||||
let bytes = 0;
|
|
||||||
for (const item of items) {
|
|
||||||
if (!wanted.has(item.id)) continue;
|
|
||||||
try {
|
|
||||||
if (item.kind === "link") await fs.promises.unlink(item.path);
|
|
||||||
else await fs.promises.rm(item.path, { recursive: true, force: true });
|
|
||||||
removed.push(item.id);
|
|
||||||
bytes += item.bytes;
|
|
||||||
} catch {
|
|
||||||
failed.push(item.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { removed, bytes, failed };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
||||||
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
||||||
@@ -1025,7 +870,7 @@ export function handOff(child, pre) {
|
|||||||
|
|
||||||
/* ----------------------------------------------------------- patch merge */
|
/* ----------------------------------------------------------- patch merge */
|
||||||
|
|
||||||
const APPEND_KEYS = new Set(["thread"]);
|
const APPEND_KEYS = new Set(["thread", "comments"]);
|
||||||
|
|
||||||
function isPlainObject(v) {
|
function isPlainObject(v) {
|
||||||
return v !== null && typeof v === "object" && !Array.isArray(v);
|
return v !== null && typeof v === "object" && !Array.isArray(v);
|
||||||
@@ -1050,7 +895,7 @@ function mergeOne(target, patch, where) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
||||||
// Named fields are replaced whole; thread appends.
|
// Named fields are replaced whole; thread/comments append.
|
||||||
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||||
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
||||||
for (const entry of patchList) {
|
for (const entry of patchList) {
|
||||||
@@ -1109,60 +954,11 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
|||||||
return merged;
|
return merged;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
|
|
||||||
// borrow the shape of the replies and doc blocks they also write, so `from` /
|
|
||||||
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
|
|
||||||
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
|
|
||||||
// at all is refused. The person's own notes are recorded by the server when
|
|
||||||
// they send, so an agent that echoes one back is not shown it twice.
|
|
||||||
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
|
|
||||||
|
|
||||||
function normalizeThreads(patchList, currentItems) {
|
|
||||||
return patchList.map((entry) => {
|
|
||||||
if (!isPlainObject(entry) || entry.thread == null) return entry;
|
|
||||||
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
|
|
||||||
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
|
|
||||||
const said = new Set(
|
|
||||||
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
|
|
||||||
);
|
|
||||||
const thread = [];
|
|
||||||
for (const m of entry.thread) {
|
|
||||||
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
|
|
||||||
guard(m, "thread");
|
|
||||||
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
|
|
||||||
if (!key) {
|
|
||||||
throw new Error(
|
|
||||||
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const { from, role, md, body, content, ...rest } = m;
|
|
||||||
const who = (m.who || from || role) === "user" ? "user" : "agent";
|
|
||||||
const text = m[key];
|
|
||||||
if (who === "user" && said.has(text.trim())) continue;
|
|
||||||
thread.push({ ...rest, who, text });
|
|
||||||
}
|
|
||||||
return { ...entry, thread };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
||||||
|
|
||||||
// Blocks merge by id like docs do, so a patch that only settles a block's
|
// Blocks merge by id like docs do, so a patch that only settles a block's
|
||||||
// state keeps its text. Blocks left out of the patch stay as they are.
|
// state keeps its text. Blocks left out of the patch stay as they are.
|
||||||
function mergeDocs(current, patchList) {
|
function mergeDocs(current, patchList) {
|
||||||
// A doc's version only moves forward. One going back is a stale or copied
|
|
||||||
// payload (last phase's progress script, say), and the page would quietly
|
|
||||||
// show the old content under the new run's name.
|
|
||||||
for (const entry of patchList) {
|
|
||||||
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
|
|
||||||
const prev = (current || []).find((d) => d && d.id === entry.id);
|
|
||||||
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
|
|
||||||
throw new Error(
|
|
||||||
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
|
|
||||||
"Versions only go up: bump it, and check the payload is the current one."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
||||||
for (const entry of patchList) {
|
for (const entry of patchList) {
|
||||||
if (!Array.isArray(entry.blocks)) continue;
|
if (!Array.isArray(entry.blocks)) continue;
|
||||||
@@ -1199,19 +995,12 @@ export function applyPatch(state, patch) {
|
|||||||
break;
|
break;
|
||||||
case "items":
|
case "items":
|
||||||
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
||||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
|
next.items = dropStaleSubmissions(next.items, state.items, v);
|
||||||
break;
|
break;
|
||||||
case "topics":
|
case "topics":
|
||||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||||
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
||||||
break;
|
break;
|
||||||
case "helpers":
|
|
||||||
// The agent's report of its helpers, for the page's Subagents tab.
|
|
||||||
// Only `post` writes it; the server's /submit never touches it.
|
|
||||||
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
|
|
||||||
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
|
|
||||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
|
||||||
break;
|
|
||||||
case "docs":
|
case "docs":
|
||||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||||
next.docs = mergeDocs(next.docs, v);
|
next.docs = mergeDocs(next.docs, v);
|
||||||
@@ -1258,11 +1047,15 @@ function stampTimes(before, next) {
|
|||||||
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
||||||
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
||||||
}
|
}
|
||||||
if (Array.isArray(next.items)) {
|
for (const list of [next.items, next.docs]) {
|
||||||
for (const entry of next.items) {
|
if (!Array.isArray(list)) continue;
|
||||||
|
for (const entry of list) {
|
||||||
if (Array.isArray(entry.thread)) {
|
if (Array.isArray(entry.thread)) {
|
||||||
for (const m of entry.thread) if (!m.at) m.at = now;
|
for (const m of entry.thread) if (!m.at) m.at = now;
|
||||||
}
|
}
|
||||||
|
if (Array.isArray(entry.comments)) {
|
||||||
|
for (const m of entry.comments) if (!m.at) m.at = now;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Array.isArray(next.docs)) {
|
if (Array.isArray(next.docs)) {
|
||||||
@@ -1495,10 +1288,7 @@ export function validate(state) {
|
|||||||
// server's record of an answer someone pressed Send on; if their own words
|
// server's record of an answer someone pressed Send on; if their own words
|
||||||
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
||||||
// would be rejected and the session would wedge with no way out.
|
// would be rejected and the session would wedge with no way out.
|
||||||
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
|
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
|
||||||
...rest,
|
|
||||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
|
||||||
}));
|
|
||||||
const prose =
|
const prose =
|
||||||
JSON.stringify(authored) +
|
JSON.stringify(authored) +
|
||||||
JSON.stringify(state.docs || []) +
|
JSON.stringify(state.docs || []) +
|
||||||
@@ -1506,20 +1296,6 @@ export function validate(state) {
|
|||||||
JSON.stringify(state.menu || {});
|
JSON.stringify(state.menu || {});
|
||||||
problems.push(...proseProblems(prose));
|
problems.push(...proseProblems(prose));
|
||||||
|
|
||||||
// The agent's report of its helpers: the shape the page draws from
|
|
||||||
// (subagents.js), then the same prose scan as everything else it writes.
|
|
||||||
if (state.helpers != null) {
|
|
||||||
problems.push(...checkHelpers(state.helpers));
|
|
||||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
|
||||||
if (!isPlainObject(helper)) continue;
|
|
||||||
for (const field of ["title", "ask", "result"]) {
|
|
||||||
if (typeof helper[field] === "string") {
|
|
||||||
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return problems;
|
return problems;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1549,8 +1325,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
|||||||
* A resume that passes through the dashboard (a finished skill going back to
|
* A resume that passes through the dashboard (a finished skill going back to
|
||||||
* it, or a launch from its menu) is a new skill taking the page over, so it
|
* it, or a launch from its menu) is a new skill taking the page over, so it
|
||||||
* starts from a blank page: the last skill's questions, sections, docs,
|
* starts from a blank page: the last skill's questions, sections, docs,
|
||||||
* helpers, headline and ending are its record on disk, not the next skill's
|
* headline and ending are its record on disk, not the next skill's opening.
|
||||||
* opening.
|
|
||||||
* Only the session's identity carries across. `workspace.json`,
|
* Only the session's identity carries across. `workspace.json`,
|
||||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||||
* and the meter outlive every hop.
|
* and the meter outlive every hop.
|
||||||
@@ -1577,8 +1352,6 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
|
|||||||
// workspace.json the server. Folders, version, change log, missing, remote.
|
// workspace.json the server. Folders, version, change log, missing, remote.
|
||||||
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
||||||
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
||||||
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
|
|
||||||
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
|
|
||||||
export const CHAT_FILE = "chat.ndjson";
|
export const CHAT_FILE = "chat.ndjson";
|
||||||
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
||||||
export const WORKSPACE_FILE = "workspace.json";
|
export const WORKSPACE_FILE = "workspace.json";
|
||||||
@@ -1846,125 +1619,17 @@ export function readWorkspace(dir) {
|
|||||||
return readJson(path.join(dir, WORKSPACE_FILE), null);
|
return readJson(path.join(dir, WORKSPACE_FILE), null);
|
||||||
}
|
}
|
||||||
|
|
||||||
// A fresh workspace: the original folder, named after itself, plus whatever
|
// A fresh workspace: just the original folder, named after itself.
|
||||||
// was remembered for this folder and spec (rememberedWorkspace() below).
|
export function initialWorkspace(worktree) {
|
||||||
export function initialWorkspace(worktree, remembered = null) {
|
|
||||||
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
|
|
||||||
if (remembered && remembered.original) {
|
|
||||||
if (remembered.original.name) original.name = remembered.original.name;
|
|
||||||
if (remembered.original.description) original.description = remembered.original.description;
|
|
||||||
}
|
|
||||||
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
|
|
||||||
id: "f" + (i + 1),
|
|
||||||
path: f.path,
|
|
||||||
name: f.name,
|
|
||||||
description: f.description || "",
|
|
||||||
...(f.nested ? { nested: true } : {}),
|
|
||||||
}));
|
|
||||||
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------ remembered workspaces */
|
|
||||||
|
|
||||||
// The folder list outlives the console session: one file for the person,
|
|
||||||
// beside looks.json, keyed by the folder a session runs in and then by spec.
|
|
||||||
// Never under specs/: the paths are this machine's, and the server never
|
|
||||||
// writes into a project.
|
|
||||||
//
|
|
||||||
// { "projects": { "<folded worktree>": {
|
|
||||||
// "path": "<worktree>",
|
|
||||||
// "project": { original, folders, at }, // no spec picked
|
|
||||||
// "specs": { "specs/<name>": { original, folders, at } } } } }
|
|
||||||
//
|
|
||||||
// `original` holds the first folder's name and description only (its path is
|
|
||||||
// always the session's own); `folders` the added ones as { path, name,
|
|
||||||
// description, nested? }. Two writers, the server on every change and
|
|
||||||
// `console.mjs forget`, each a read-modify-write of one key.
|
|
||||||
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
|
|
||||||
|
|
||||||
const foldKey = (p) => {
|
|
||||||
const resolved = path.resolve(String(p || ""));
|
|
||||||
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
|
|
||||||
};
|
|
||||||
|
|
||||||
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
|
|
||||||
export function specKey(specDir) {
|
|
||||||
return String(specDir || "")
|
|
||||||
.trim()
|
|
||||||
.replace(/\\/g, "/")
|
|
||||||
.replace(/^\.\//, "")
|
|
||||||
.replace(/\/+$/, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function readStore() {
|
|
||||||
const saved = readJson(WORKSPACES_FILE, null);
|
|
||||||
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What was remembered for this folder and spec: `{ entry, from }`, where
|
|
||||||
* `from` is "spec" when the spec has its own list, "project" when it falls
|
|
||||||
* back to the project's (a spec's list starts as a copy of it), and null
|
|
||||||
* when nothing was ever saved.
|
|
||||||
*/
|
|
||||||
export function rememberedWorkspace(worktree, specDir) {
|
|
||||||
const project = readStore().projects[foldKey(worktree)];
|
|
||||||
if (!project) return { entry: null, from: null };
|
|
||||||
const spec = specKey(specDir);
|
|
||||||
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
|
|
||||||
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
|
|
||||||
}
|
|
||||||
|
|
||||||
// The workspace's folders as the store keeps them.
|
|
||||||
export function rememberable(ws) {
|
|
||||||
const folders = (ws && ws.folders) || [];
|
|
||||||
const first = folders.find((f) => f.original) || {};
|
|
||||||
return {
|
return {
|
||||||
original: { name: first.name || "", description: first.description || "" },
|
version: 0,
|
||||||
folders: folders
|
folders: [{ id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }],
|
||||||
.filter((f) => !f.original)
|
missing: [],
|
||||||
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
|
changes: [],
|
||||||
at: nowIso(),
|
remote: "",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Every server and `console.mjs forget` writes the one file, so each
|
|
||||||
// read-modify-write holds this lock beside it.
|
|
||||||
const WORKSPACES_LOCK = "workspaces.json.lock";
|
|
||||||
|
|
||||||
// Save the list for this folder and spec ("" for the project's own).
|
|
||||||
export function rememberWorkspace(worktree, specDir, ws) {
|
|
||||||
ensureDir(path.dirname(WORKSPACES_FILE));
|
|
||||||
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveRemembered(worktree, specDir, ws) {
|
|
||||||
const store = readStore();
|
|
||||||
const key = foldKey(worktree);
|
|
||||||
const project = store.projects[key] || { path: path.resolve(worktree) };
|
|
||||||
const spec = specKey(specDir);
|
|
||||||
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
|
|
||||||
else project.project = rememberable(ws);
|
|
||||||
store.projects[key] = project;
|
|
||||||
writeJsonAtomic(WORKSPACES_FILE, store);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
|
|
||||||
export function forgetWorkspace(worktree, specDir) {
|
|
||||||
const spec = specKey(specDir);
|
|
||||||
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
|
|
||||||
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
|
|
||||||
}
|
|
||||||
|
|
||||||
function dropRemembered(worktree, spec) {
|
|
||||||
const store = readStore();
|
|
||||||
const project = store.projects[foldKey(worktree)];
|
|
||||||
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
|
|
||||||
delete project.specs[spec];
|
|
||||||
writeJsonAtomic(WORKSPACES_FILE, store);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only server.mjs may call this.
|
// Single-writer rule: only server.mjs may call this.
|
||||||
export function writeWorkspace(dir, ws) {
|
export function writeWorkspace(dir, ws) {
|
||||||
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
|
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
|
||||||
@@ -2034,98 +1699,6 @@ export function pendingWorkspaceChanges(dir) {
|
|||||||
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------ the Subagents switch */
|
|
||||||
|
|
||||||
// The person's Subagents switch, remembered per project folder and workflow:
|
|
||||||
//
|
|
||||||
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
|
|
||||||
//
|
|
||||||
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
|
|
||||||
// workflow's shipped default.
|
|
||||||
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
|
|
||||||
const SUBAGENTS_LOCK = "subagents.json.lock";
|
|
||||||
|
|
||||||
function readSubagentStore() {
|
|
||||||
const saved = readJson(SUBAGENTS_FILE, null);
|
|
||||||
return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
|
||||||
}
|
|
||||||
|
|
||||||
// The saved `{ on, instruction, max }` for this folder and workflow, or the
|
|
||||||
// default's when nothing (or something malformed) is saved.
|
|
||||||
export function subagentStoreEntry(worktree, workflow) {
|
|
||||||
const { on, instruction, max } = defaultSetting(workflow);
|
|
||||||
const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null;
|
|
||||||
const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null;
|
|
||||||
return saved && !saved.error ? saved : { on, instruction, max };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only server.mjs may call this.
|
|
||||||
export function saveSubagentStoreEntry(worktree, workflow, value) {
|
|
||||||
ensureDir(path.dirname(SUBAGENTS_FILE));
|
|
||||||
withStateLock(
|
|
||||||
path.dirname(SUBAGENTS_FILE),
|
|
||||||
() => {
|
|
||||||
const store = readSubagentStore();
|
|
||||||
const key = foldKey(worktree);
|
|
||||||
const project = store[key] && typeof store[key] === "object" ? store[key] : {};
|
|
||||||
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } };
|
|
||||||
writeJsonAtomic(SUBAGENTS_FILE, store);
|
|
||||||
},
|
|
||||||
SUBAGENTS_LOCK
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
|
||||||
|
|
||||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
|
||||||
|
|
||||||
// This session's switch, `{ workflow, on, instruction, max, revision }`, or
|
|
||||||
// null when there is none or it is malformed.
|
|
||||||
export function readSubagentSetting(dir) {
|
|
||||||
const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null);
|
|
||||||
if (!s || typeof s !== "object") return null;
|
|
||||||
if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null;
|
|
||||||
return s;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only server.mjs may call this. The revision never goes
|
|
||||||
// backwards within a session.
|
|
||||||
export function writeSubagentSetting(dir, setting) {
|
|
||||||
const previous = readSubagentSetting(dir);
|
|
||||||
const revision = Math.max(previous ? previous.revision : 0, setting.revision);
|
|
||||||
return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision });
|
|
||||||
}
|
|
||||||
|
|
||||||
export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json";
|
|
||||||
const CURSOR_STATES = new Set(["none", "on", "off"]);
|
|
||||||
|
|
||||||
// What the agent was last told: `{ revision, state }`.
|
|
||||||
export function readSubagentCursor(dir) {
|
|
||||||
const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null);
|
|
||||||
if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" };
|
|
||||||
return { revision: saved.revision, state: saved.state };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only console.mjs may call this. Never backwards, like
|
|
||||||
// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one.
|
|
||||||
export function writeSubagentCursor(dir, cursor) {
|
|
||||||
const old = readSubagentCursor(dir);
|
|
||||||
const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state };
|
|
||||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The one place the cursor may go back: `open`, which starts a fresh agent.
|
|
||||||
export function resetSubagentCursor(dir) {
|
|
||||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// The `caps` of the last `open` event: what the agent's console copy can do.
|
|
||||||
export function latestOpenCaps(dir) {
|
|
||||||
const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open");
|
|
||||||
const last = opens[opens.length - 1];
|
|
||||||
return last && Array.isArray(last.caps) ? last.caps : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flag the case where the link cannot be opened by the person it is for.
|
* Flag the case where the link cannot be opened by the person it is for.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
|
|||||||
if (!s || typeof s !== "object") return null;
|
if (!s || typeof s !== "object") return null;
|
||||||
if (item.answer && typeof item.answer === "object") return null;
|
if (item.answer && typeof item.answer === "object") return null;
|
||||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||||
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
|
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||||
return replied ? null : s;
|
return replied ? null : s;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,33 +74,17 @@ export function submittedAwaiting(item) {
|
|||||||
* agent has yet to say anything after it. The server records it as `sentNote`
|
* agent has yet to say anything after it. The server records it as `sentNote`
|
||||||
* on every send, so the page can show it in the Notes pane and in the Sent
|
* on every send, so the page can show it in the Notes pane and in the Sent
|
||||||
* box instead of letting it vanish into a send that shows no sign of arriving.
|
* box instead of letting it vanish into a send that shows no sign of arriving.
|
||||||
* Any agent message from the send onwards, or one with no clock to compare,
|
* Any thread message from the send onwards, or none with a clock to compare,
|
||||||
* means it has been picked up. The person's own entries never count: the
|
* means it has been picked up.
|
||||||
* server writes their note into the thread as it arrives.
|
|
||||||
*/
|
*/
|
||||||
export function noteAwaiting(item) {
|
export function noteAwaiting(item) {
|
||||||
const n = item && item.sentNote;
|
const n = item && item.sentNote;
|
||||||
if (!n || typeof n !== "object") return null;
|
if (!n || typeof n !== "object") return null;
|
||||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||||
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
|
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
|
||||||
return picked ? null : n;
|
return picked ? null : n;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Who said a thread entry and what they said. The contract is `{ who, text }`
|
|
||||||
* and the server lifts anything else into it, but sessions written before that
|
|
||||||
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
|
|
||||||
*/
|
|
||||||
export function threadWho(m) {
|
|
||||||
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
|
|
||||||
}
|
|
||||||
|
|
||||||
export function threadText(m) {
|
|
||||||
if (!m) return "";
|
|
||||||
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/* -------------------------------------------------------------- labels */
|
/* -------------------------------------------------------------- labels */
|
||||||
|
|
||||||
export function optionLabel(item, k) {
|
export function optionLabel(item, k) {
|
||||||
|
|||||||
@@ -23,9 +23,6 @@
|
|||||||
--warn-soft: #fbe7e3;
|
--warn-soft: #fbe7e3;
|
||||||
--focus: #1f6feb;
|
--focus: #1f6feb;
|
||||||
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
||||||
/* A soft accent halo for the things that want noticing: the update banner
|
|
||||||
and an enabled Send. Built from --accent, so a picked accent glows too. */
|
|
||||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
|
|
||||||
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||||
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
||||||
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
||||||
@@ -64,7 +61,6 @@
|
|||||||
--warn-soft: #34201d;
|
--warn-soft: #34201d;
|
||||||
--focus: #6aa3ff;
|
--focus: #6aa3ff;
|
||||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +85,6 @@
|
|||||||
--warn-soft: #34201d;
|
--warn-soft: #34201d;
|
||||||
--focus: #6aa3ff;
|
--focus: #6aa3ff;
|
||||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
* { box-sizing: border-box; }
|
* { box-sizing: border-box; }
|
||||||
@@ -208,26 +203,6 @@ body {
|
|||||||
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
||||||
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||||
|
|
||||||
/* Subagents: an orchestrator and its helpers. Unlit is a hollow outline in
|
|
||||||
the quiet ink; lit fills the nodes with the highlight color. */
|
|
||||||
.subagents-btn { border-color: var(--rule-2); color: var(--ink-2); display: inline-flex; align-items: center; justify-content: center; }
|
|
||||||
.btn.subagents-btn { padding: 0 6px; align-self: stretch; }
|
|
||||||
.subagents-btn[hidden] { display: none; }
|
|
||||||
.subagents-btn svg { width: 16px; height: 16px; display: block; }
|
|
||||||
.subagents-btn .sa-link { fill: none; stroke: var(--ink-2); stroke-width: 1.2; stroke-linecap: round; }
|
|
||||||
.subagents-btn .sa-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
|
|
||||||
.subagents-btn .sa-node { fill: none; stroke: var(--ink-2); stroke-width: 1.2; }
|
|
||||||
.subagents-btn[aria-pressed="true"] .sa-hub,
|
|
||||||
.subagents-btn[aria-pressed="true"] .sa-node { fill: var(--accent); stroke: var(--accent); }
|
|
||||||
.subagents-btn[aria-pressed="true"] .sa-link { stroke: var(--accent); }
|
|
||||||
.subagents-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
|
||||||
.subagents-btn:hover:not(:disabled) .sa-link,
|
|
||||||
.subagents-btn:hover:not(:disabled) .sa-hub,
|
|
||||||
.subagents-btn:hover:not(:disabled) .sa-node { stroke: var(--accent); }
|
|
||||||
.subagents-btn:disabled .sa-link,
|
|
||||||
.subagents-btn:disabled .sa-hub,
|
|
||||||
.subagents-btn:disabled .sa-node { stroke: var(--ink-3); fill: none; }
|
|
||||||
|
|
||||||
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
||||||
|
|
||||||
/* The session meter: a ring that fills with the points and a few words, in
|
/* The session meter: a ring that fills with the points and a few words, in
|
||||||
@@ -1121,15 +1096,6 @@ h1 {
|
|||||||
.ask-disabled-note.is-limit, .ask-disabled-note.is-waiting { color: var(--ink-2); background: var(--panel-2); border: 1px solid var(--rule); }
|
.ask-disabled-note.is-limit, .ask-disabled-note.is-waiting { color: var(--ink-2); background: var(--panel-2); border: 1px solid var(--rule); }
|
||||||
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
||||||
|
|
||||||
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
|
|
||||||
the tiny ring, left of the label. The extra .spinner is for specificity:
|
|
||||||
.spinner.tiny comes later and zeroes the margin otherwise. */
|
|
||||||
.view-tab .spinner.tab-spin {
|
|
||||||
display: inline-block;
|
|
||||||
margin-right: 7px;
|
|
||||||
vertical-align: -1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* A reply landed while another tab was open. */
|
/* A reply landed while another tab was open. */
|
||||||
.view-tab .tab-dot {
|
.view-tab .tab-dot {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
@@ -1450,30 +1416,6 @@ h1 {
|
|||||||
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
||||||
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
||||||
|
|
||||||
/* The Subagents tab: one row per reported helper, newest state in a pill. */
|
|
||||||
.sa-card h2 { margin: 0 0 6px; }
|
|
||||||
.sa-card > .help { margin: 0 0 16px; }
|
|
||||||
.sa-alone { margin: 0; color: var(--ink-2); }
|
|
||||||
.sa-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
|
|
||||||
.sa-row { border: 1px solid var(--rule); border-radius: 8px; background: var(--panel-2); padding: 12px 14px; }
|
|
||||||
.sa-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
|
||||||
.sa-title { min-width: 0; overflow-wrap: anywhere; }
|
|
||||||
.sa-ask {
|
|
||||||
margin: 4px 0 0; color: var(--ink-2); font-size: 13.5px;
|
|
||||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
|
|
||||||
}
|
|
||||||
.sa-result { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
|
||||||
.sa-pill { display: inline-flex; align-items: center; gap: 6px; flex: none; }
|
|
||||||
.sa-pill.is-running { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
|
|
||||||
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
|
|
||||||
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
|
|
||||||
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
|
|
||||||
/* The dialog's number box, themed like the page's other inputs. */
|
|
||||||
.subagents input[type="number"] {
|
|
||||||
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
|
|
||||||
border: 1px solid var(--rule-2); border-radius: 6px; padding: 4px 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------ settled answer */
|
/* ------------------------------------------------------ settled answer */
|
||||||
|
|
||||||
.answered {
|
.answered {
|
||||||
@@ -1707,13 +1649,11 @@ input[type="text"].invalid { border-color: var(--warn); }
|
|||||||
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||||
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
||||||
/* Send glows and breathes while there is something to send: the steady
|
/* Send breathes while there is something to send: a soft accent ring that
|
||||||
--glow, plus a soft accent ring that spreads and fades. The ring is off
|
spreads and fades. Off under reduced motion, below. */
|
||||||
under reduced motion, below; the glow stays. */
|
|
||||||
#btn-send:not(:disabled) { box-shadow: var(--glow); }
|
|
||||||
@keyframes send-pulse {
|
@keyframes send-pulse {
|
||||||
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
|
0% { box-shadow: 0 0 0 0 var(--accent-line); }
|
||||||
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
|
100% { box-shadow: 0 0 0 6px transparent; }
|
||||||
}
|
}
|
||||||
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
||||||
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
||||||
@@ -2015,8 +1955,6 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.footer-where:hover { text-decoration: underline; }
|
.footer-where:hover { text-decoration: underline; }
|
||||||
/* The project name, in the person's highlight color. */
|
|
||||||
.where-project { color: var(--accent); font-weight: 600; }
|
|
||||||
/* A folder is missing or the agent could not read one: the dialog says which. */
|
/* A folder is missing or the agent could not read one: the dialog says which. */
|
||||||
.where-alert {
|
.where-alert {
|
||||||
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
||||||
@@ -2059,18 +1997,6 @@ kbd {
|
|||||||
}
|
}
|
||||||
.waiting-pane h2 { font: 600 23px/1.3 var(--serif); color: var(--ink); margin: 0; }
|
.waiting-pane h2 { font: 600 23px/1.3 var(--serif); color: var(--ink); margin: 0; }
|
||||||
.waiting-pane p { margin: 0; }
|
.waiting-pane p { margin: 0; }
|
||||||
/* The words that open the tasks tab: bold in the highlight color, a button
|
|
||||||
that reads as part of the sentence. */
|
|
||||||
.waiting-jump {
|
|
||||||
font: inherit;
|
|
||||||
font-weight: 700;
|
|
||||||
color: var(--accent);
|
|
||||||
background: none;
|
|
||||||
border: 0;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
button.waiting-jump { cursor: pointer; text-decoration: underline; text-decoration-color: var(--accent-line); text-underline-offset: 3px; }
|
|
||||||
button.waiting-jump:hover { text-decoration-color: var(--accent); }
|
|
||||||
/* Once the work is under way Planny steps back a size, and the ring in
|
/* Once the work is under way Planny steps back a size, and the ring in
|
||||||
front of the stage name carries the "still going" signal instead. */
|
front of the stage name carries the "still going" signal instead. */
|
||||||
.waiting-pane .pose-stage { height: 130px; transition: height 0.35s ease; }
|
.waiting-pane .pose-stage { height: 130px; transition: height 0.35s ease; }
|
||||||
@@ -2273,7 +2199,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
.modal.help[open] { display: flex; }
|
.modal.help[open] { display: flex; }
|
||||||
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
||||||
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
||||||
.help-version a { color: inherit; }
|
|
||||||
|
|
||||||
.help-layout {
|
.help-layout {
|
||||||
display: grid;
|
display: grid;
|
||||||
@@ -2580,9 +2505,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
actions stay put. */
|
actions stay put. */
|
||||||
.modal.workspace { max-width: 680px; }
|
.modal.workspace { max-width: 680px; }
|
||||||
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
||||||
.workspace .modal-blurb { margin-bottom: 6px; }
|
|
||||||
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
|
|
||||||
|
|
||||||
.workspace-list {
|
.workspace-list {
|
||||||
list-style: none; margin: 0; padding: 0;
|
list-style: none; margin: 0; padding: 0;
|
||||||
display: grid; gap: 12px;
|
display: grid; gap: 12px;
|
||||||
@@ -2723,74 +2645,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
border-left-width: 4px;
|
border-left-width: 4px;
|
||||||
color: var(--ink);
|
color: var(--ink);
|
||||||
}
|
}
|
||||||
/* A newer release: the same slot, in the accent, with the label as the way
|
|
||||||
into the update modal and a small × that hides it for this session. */
|
|
||||||
.dash-nudge.update-banner {
|
|
||||||
position: relative;
|
|
||||||
padding-left: 40px;
|
|
||||||
padding-right: 40px;
|
|
||||||
border-left-width: 4px;
|
|
||||||
border-left-color: var(--accent-line);
|
|
||||||
color: var(--ink);
|
|
||||||
box-shadow: var(--glow);
|
|
||||||
}
|
|
||||||
.update-banner-open {
|
|
||||||
flex: 1 1 16em;
|
|
||||||
padding: 0;
|
|
||||||
border: 0;
|
|
||||||
background: none;
|
|
||||||
color: inherit;
|
|
||||||
font: inherit;
|
|
||||||
font-weight: 600;
|
|
||||||
letter-spacing: 0.02em;
|
|
||||||
text-align: center;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.update-banner-open:hover { text-decoration: underline; }
|
|
||||||
/* Pinned to the right edge, out of the flow, so the label centres on the
|
|
||||||
whole banner rather than on what the × leaves of it. */
|
|
||||||
.update-banner-dismiss {
|
|
||||||
position: absolute;
|
|
||||||
top: 50%;
|
|
||||||
right: 10px;
|
|
||||||
transform: translateY(-50%);
|
|
||||||
padding: 0 6px;
|
|
||||||
border: 0;
|
|
||||||
border-radius: var(--radius);
|
|
||||||
background: none;
|
|
||||||
color: inherit;
|
|
||||||
font: inherit;
|
|
||||||
font-size: 16px;
|
|
||||||
line-height: 1;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.update-banner-dismiss:hover { background: var(--accent-line); }
|
|
||||||
/* Wide enough that the update command sits on one line beside Copy; a
|
|
||||||
narrow window still wraps it rather than overflowing. */
|
|
||||||
#update-modal { max-width: 720px; }
|
|
||||||
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
|
|
||||||
.update-steps li { margin: 4px 0; }
|
|
||||||
/* The hand-off copy row, in the modal's first step: the command and its Copy
|
|
||||||
side by side. */
|
|
||||||
.update-command {
|
|
||||||
margin: 6px 0 4px;
|
|
||||||
display: flex;
|
|
||||||
align-items: stretch;
|
|
||||||
gap: 10px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
}
|
|
||||||
.update-command code {
|
|
||||||
flex: 1 1 260px;
|
|
||||||
min-width: 0;
|
|
||||||
font: 13px/1.5 var(--mono);
|
|
||||||
color: var(--ink);
|
|
||||||
background: var(--panel);
|
|
||||||
border: 1px solid var(--rule-2);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 10px 12px;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
||||||
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
||||||
.dash-working {
|
.dash-working {
|
||||||
@@ -3275,6 +3129,11 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
0%, 15%, 75%, 100% { transform: scale(1); opacity: 0.16; }
|
0%, 15%, 75%, 100% { transform: scale(1); opacity: 0.16; }
|
||||||
45% { transform: scale(0.7); opacity: 0.08; }
|
45% { transform: scale(0.7); opacity: 0.08; }
|
||||||
}
|
}
|
||||||
|
.pose .fz-halo { opacity: 0.25; animation: fz-halo 1.6s ease-in-out infinite; }
|
||||||
|
@keyframes fz-halo {
|
||||||
|
0%, 100% { transform: scale(1); opacity: 0.2; }
|
||||||
|
45% { transform: scale(1.3); opacity: 0.4; }
|
||||||
|
}
|
||||||
.pose .fz-tick { stroke: var(--accent-ink); }
|
.pose .fz-tick { stroke: var(--accent-ink); }
|
||||||
.pose .fz-flag { transform-origin: 0% 50%; animation: fz-wave 1.2s ease-in-out infinite; }
|
.pose .fz-flag { transform-origin: 0% 50%; animation: fz-wave 1.2s ease-in-out infinite; }
|
||||||
@keyframes fz-wave {
|
@keyframes fz-wave {
|
||||||
@@ -3517,18 +3376,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||||
.models-actions .help.error { color: var(--danger, #d64545); }
|
.models-actions .help.error { color: var(--danger, #d64545); }
|
||||||
|
|
||||||
/* User Preferences: Cleanup's list of what would go, shown before anything
|
|
||||||
is deleted. */
|
|
||||||
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
|
|
||||||
.cleanup-list:empty { display: none; }
|
|
||||||
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
|
|
||||||
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
|
|
||||||
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
|
|
||||||
.cleanup-size { flex: none; color: var(--ink-3); }
|
|
||||||
.cleanup-more { display: grid; gap: 4px; }
|
|
||||||
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
|
|
||||||
#cleanup-delete[hidden] { display: none; }
|
|
||||||
|
|
||||||
/* A word the person has to type, bold and in their highlight color so it
|
/* A word the person has to type, bold and in their highlight color so it
|
||||||
does not get lost in the status sentence. */
|
does not get lost in the status sentence. */
|
||||||
.agent-key {
|
.agent-key {
|
||||||
|
|||||||
@@ -66,8 +66,6 @@ import {
|
|||||||
submittedAwaiting,
|
submittedAwaiting,
|
||||||
noteAwaiting,
|
noteAwaiting,
|
||||||
suggestionFrom,
|
suggestionFrom,
|
||||||
threadText,
|
|
||||||
threadWho,
|
|
||||||
THUMB_EDGE,
|
THUMB_EDGE,
|
||||||
turnGate,
|
turnGate,
|
||||||
verdictText,
|
verdictText,
|
||||||
@@ -103,15 +101,6 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
|
|||||||
import { RED_BANNER } from "./meter.js";
|
import { RED_BANNER } from "./meter.js";
|
||||||
import { applyMention, matchNames, mentionAt } from "./mentions.js";
|
import { applyMention, matchNames, mentionAt } from "./mentions.js";
|
||||||
import { faviconState, setFavicon } from "./favicon.js";
|
import { faviconState, setFavicon } from "./favicon.js";
|
||||||
import {
|
|
||||||
CHECKIN_LINE,
|
|
||||||
PATHFINDER_RESEARCH_LINE,
|
|
||||||
defaultInstruction,
|
|
||||||
helperRows,
|
|
||||||
showSwitch,
|
|
||||||
showTab,
|
|
||||||
switchLabel,
|
|
||||||
} from "./subagents.js";
|
|
||||||
|
|
||||||
const $ = (id) => document.getElementById(id);
|
const $ = (id) => document.getElementById(id);
|
||||||
|
|
||||||
@@ -457,10 +446,6 @@ document.addEventListener("click", (e) => {
|
|||||||
|
|
||||||
|
|
||||||
const GONE_AFTER_MS = 8000;
|
const GONE_AFTER_MS = 8000;
|
||||||
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
|
|
||||||
// wipe an unrelated warning that landed while the page was gone (an upload
|
|
||||||
// failure, a refused send).
|
|
||||||
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
|
|
||||||
const WORKING_GRACE_MS = 5 * 60 * 1000;
|
const WORKING_GRACE_MS = 5 * 60 * 1000;
|
||||||
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
||||||
// listening. The difference is the cost of being wrong: a working agent that
|
// listening. The difference is the cost of being wrong: a working agent that
|
||||||
@@ -536,12 +521,6 @@ let chatFrame = null;
|
|||||||
// sends them.
|
// sends them.
|
||||||
let wsFrame = null;
|
let wsFrame = null;
|
||||||
let meterFrame = null;
|
let meterFrame = null;
|
||||||
// The frame's update ({ installed, latest }), present only when a newer
|
|
||||||
// release is out; null otherwise.
|
|
||||||
let updateFrame = null;
|
|
||||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
|
||||||
// revision }), or null before a server that sends it.
|
|
||||||
let subagentsFrame = null;
|
|
||||||
let chatDot = false;
|
let chatDot = false;
|
||||||
let chatSending = false;
|
let chatSending = false;
|
||||||
let chatResetting = false;
|
let chatResetting = false;
|
||||||
@@ -587,6 +566,7 @@ function fresh() {
|
|||||||
drafts: {},
|
drafts: {},
|
||||||
images: {},
|
images: {},
|
||||||
sent: {},
|
sent: {},
|
||||||
|
sentAt: null,
|
||||||
stopping: null,
|
stopping: null,
|
||||||
afterBuild: null,
|
afterBuild: null,
|
||||||
homeward: null,
|
homeward: null,
|
||||||
@@ -890,14 +870,10 @@ function adopt(body) {
|
|||||||
chatFrame = body.chat || null;
|
chatFrame = body.chat || null;
|
||||||
if (body.workspace) wsFrame = body.workspace;
|
if (body.workspace) wsFrame = body.workspace;
|
||||||
if (body.meter) meterFrame = body.meter;
|
if (body.meter) meterFrame = body.meter;
|
||||||
// Always replaced: an absent key means no update.
|
|
||||||
updateFrame = body.update || null;
|
|
||||||
// Always replaced too: an older server sends none, and then there is no switch.
|
|
||||||
subagentsFrame = body.subagents || null;
|
|
||||||
lastContact = Date.now();
|
lastContact = Date.now();
|
||||||
if (gone) {
|
if (gone) {
|
||||||
gone = false;
|
gone = false;
|
||||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
banner(null);
|
||||||
}
|
}
|
||||||
if (firstLoad) {
|
if (firstLoad) {
|
||||||
load();
|
load();
|
||||||
@@ -1040,9 +1016,7 @@ function adopt(body) {
|
|||||||
render();
|
render();
|
||||||
if ($("workspace-modal").open) renderWorkspace();
|
if ($("workspace-modal").open) renderWorkspace();
|
||||||
tellFolderIssues();
|
tellFolderIssues();
|
||||||
// The Overview tab's file changes under a build, so a tab you are watching
|
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
|
||||||
// refetches on every new frame too, not only on the click that opened it.
|
|
||||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
|
|
||||||
if (announce) showArrival(announce);
|
if (announce) showArrival(announce);
|
||||||
// New entries land at the bottom of the rail. Gliding down to them beats
|
// New entries land at the bottom of the rail. Gliding down to them beats
|
||||||
// leaving the list parked where it was while it grew underneath.
|
// leaving the list parked where it was while it grew underneath.
|
||||||
@@ -1175,12 +1149,15 @@ function markGone() {
|
|||||||
// of the server means there, and a banner promising a reconnect would
|
// of the server means there, and a banner promising a reconnect would
|
||||||
// argue with it.
|
// argue with it.
|
||||||
if (!finish() && !stopInProgress()) {
|
if (!finish() && !stopInProgress()) {
|
||||||
banner(GONE_BANNER, "warn");
|
banner(
|
||||||
|
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
|
||||||
|
"warn"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
render();
|
render();
|
||||||
} else if (!bad && gone) {
|
} else if (!bad && gone) {
|
||||||
gone = false;
|
gone = false;
|
||||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
banner(null);
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1205,6 +1182,7 @@ function connect() {
|
|||||||
} catch {}
|
} catch {}
|
||||||
});
|
});
|
||||||
es.addEventListener("submitted", (e) => {
|
es.addEventListener("submitted", (e) => {
|
||||||
|
local.sentAt = Date.now();
|
||||||
// Drop only what was actually sent.
|
// Drop only what was actually sent.
|
||||||
//
|
//
|
||||||
// This event fires for a send from ANY tab of this session, which is why it
|
// This event fires for a send from ANY tab of this session, which is why it
|
||||||
@@ -1315,7 +1293,6 @@ function render() {
|
|||||||
renderChrome();
|
renderChrome();
|
||||||
renderStatus();
|
renderStatus();
|
||||||
renderBriefButton();
|
renderBriefButton();
|
||||||
renderSubagentsButton();
|
|
||||||
renderStopButton();
|
renderStopButton();
|
||||||
renderHomeButton();
|
renderHomeButton();
|
||||||
tabAdded = renderViews();
|
tabAdded = renderViews();
|
||||||
@@ -1581,7 +1558,7 @@ function renderChrome() {
|
|||||||
renderMeter();
|
renderMeter();
|
||||||
$("title").textContent = S.title || "Session";
|
$("title").textContent = S.title || "Session";
|
||||||
$("badge").textContent = workflowLabel(S.workflow);
|
$("badge").textContent = workflowLabel(S.workflow);
|
||||||
renderTabTitle();
|
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||||
|
|
||||||
const h = S.headline || {};
|
const h = S.headline || {};
|
||||||
// On a finished session an open item is frozen: the send on it counts as
|
// On a finished session an open item is frozen: the send on it counts as
|
||||||
@@ -1822,19 +1799,14 @@ async function sendBrief() {
|
|||||||
reply: briefPhrase(choice.range),
|
reply: briefPhrase(choice.range),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
|
||||||
if (!res.ok) throw new Error(String(res.status));
|
if (!res.ok) throw new Error(String(res.status));
|
||||||
$("brief-modal").close();
|
$("brief-modal").close();
|
||||||
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
||||||
setTimeout(() => banner(null), 5000);
|
setTimeout(() => banner(null), 5000);
|
||||||
pendingResult = true;
|
pendingResult = true;
|
||||||
render();
|
render();
|
||||||
} catch (err) {
|
} catch {
|
||||||
if (err && err.pending) pendingResult = true;
|
why.textContent = "That did not go through. Try again in a moment.";
|
||||||
why.textContent =
|
|
||||||
err && err.pending
|
|
||||||
? "Your last answers are still being picked up. Try again in a moment."
|
|
||||||
: "That did not go through. Try again in a moment.";
|
|
||||||
} finally {
|
} finally {
|
||||||
go.disabled = false;
|
go.disabled = false;
|
||||||
go.textContent = "Write the brief";
|
go.textContent = "Write the brief";
|
||||||
@@ -1850,77 +1822,11 @@ function renderBriefButton() {
|
|||||||
if (offer) btn.disabled = gone || pendingResult;
|
if (offer) btn.disabled = gone || pendingResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shown only where the skill opts in and the agent's console copy can deliver
|
|
||||||
// it. Lit while helpers are on; a click opens the dialog, never toggles.
|
|
||||||
function renderSubagentsButton() {
|
|
||||||
const btn = $("btn-subagents");
|
|
||||||
const offer = showSwitch(subagentsFrame);
|
|
||||||
btn.hidden = !offer;
|
|
||||||
if (!offer) return;
|
|
||||||
const label = switchLabel(subagentsFrame);
|
|
||||||
btn.setAttribute("aria-pressed", String(Boolean(subagentsFrame.on)));
|
|
||||||
btn.title = label;
|
|
||||||
btn.setAttribute("aria-label", label);
|
|
||||||
btn.disabled = gone;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
|
||||||
// instruction is the shipped default, shown as its text so it can be edited.
|
|
||||||
function openSubagents() {
|
|
||||||
if (!showSwitch(subagentsFrame)) return;
|
|
||||||
const on = Boolean(subagentsFrame.on);
|
|
||||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
|
|
||||||
radio.checked = radio.value === (on ? "on" : "off");
|
|
||||||
}
|
|
||||||
$("subagents-instruction").value = subagentsFrame.instruction ?? defaultInstruction(S.workflow);
|
|
||||||
$("subagents-max").value = String(subagentsFrame.max);
|
|
||||||
$("subagents-checkin").textContent = CHECKIN_LINE;
|
|
||||||
const research = $("subagents-research");
|
|
||||||
research.textContent = PATHFINDER_RESEARCH_LINE;
|
|
||||||
research.hidden = S.workflow !== "pathfinder";
|
|
||||||
$("subagents-status").textContent = "";
|
|
||||||
$("subagents-save").disabled = false;
|
|
||||||
$("subagents-modal").showModal();
|
|
||||||
const checked = document.querySelector('input[name="subagents-on"]:checked');
|
|
||||||
if (checked) checked.focus();
|
|
||||||
}
|
|
||||||
|
|
||||||
const SUBAGENTS_ERRORS = {
|
|
||||||
max: "Pick a number from 1 to 20.",
|
|
||||||
"too-long": "The instruction is over 2,000 characters.",
|
|
||||||
"not-offered": "This skill doesn't use helpers.",
|
|
||||||
bad: "That didn't save. Try again.",
|
|
||||||
};
|
|
||||||
const SUBAGENTS_LOST = "Lost contact with Plan2Code. Try again once it's back.";
|
|
||||||
|
|
||||||
async function saveSubagents() {
|
|
||||||
const save = $("subagents-save");
|
|
||||||
const status = $("subagents-status");
|
|
||||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
|
||||||
const text = $("subagents-instruction").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(S.workflow) ? null : text;
|
|
||||||
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
|
|
||||||
save.disabled = true;
|
|
||||||
status.textContent = "";
|
|
||||||
const res = await postJson("/subagents", body);
|
|
||||||
save.disabled = false;
|
|
||||||
// The next state frame redraws the button.
|
|
||||||
if (res.status === 200) return $("subagents-modal").close();
|
|
||||||
if (res.status === 400) status.textContent = SUBAGENTS_ERRORS[res.body && res.body.error] || SUBAGENTS_ERRORS.bad;
|
|
||||||
else if (res.status === 403 || res.status === 0) status.textContent = SUBAGENTS_LOST;
|
|
||||||
else status.textContent = SUBAGENTS_ERRORS.bad;
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderViews() {
|
function renderViews() {
|
||||||
const nav = $("views");
|
const nav = $("views");
|
||||||
nav.replaceChildren();
|
nav.replaceChildren();
|
||||||
// Sent and not yet picked up: the same ring as Ask, until Plan2Code moves on
|
|
||||||
// or goes quiet (a turning ring would pass a dead session for a slow one).
|
|
||||||
const sentBusy = pendingResult && !gone && !agentAdrift();
|
|
||||||
const tabs = [
|
const tabs = [
|
||||||
{ id: "questions", label: isDashboard() ? "Dashboard" : "Questions", count: myTurn().length, busy: sentBusy },
|
{ id: "questions", label: isDashboard() ? "Dashboard" : "Questions", count: myTurn().length },
|
||||||
];
|
];
|
||||||
// Built in rather than posted: present exactly while the spec in view has
|
// Built in rather than posted: present exactly while the spec in view has
|
||||||
// an overview.md. A tab that vanishes under the person sends them home.
|
// an overview.md. A tab that vanishes under the person sends them home.
|
||||||
@@ -1928,30 +1834,12 @@ function renderViews() {
|
|||||||
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
||||||
else if (view === "overview") view = "questions";
|
else if (view === "overview") view = "questions";
|
||||||
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
||||||
// The helpers the agent reported, from the first one on; cleared by a
|
|
||||||
// dashboard hop, which sends the person home like the Overview tab does.
|
|
||||||
if (showTab(subagentsFrame, S.helpers)) {
|
|
||||||
// From the rows the tab draws, so the badge never counts helpers the
|
|
||||||
// working-alone note hides.
|
|
||||||
const running = helperRows(S.helpers).rows.filter((r) => r.state === "running").length;
|
|
||||||
tabs.push({ id: "subagents", label: "Subagents", count: running });
|
|
||||||
} else if (view === "subagents") view = "questions";
|
|
||||||
// Always last, on every workflow and after a finish: the Quick question chat.
|
// Always last, on every workflow and after a finish: the Quick question chat.
|
||||||
// The ring left of "Ask" shows exactly when the conversation's own ring does:
|
tabs.push({ id: "ask", label: "Ask", count: 0, dot: chatDot });
|
||||||
// a question the agent picked up and has not answered yet.
|
|
||||||
const ask = askState();
|
|
||||||
const askBusy = ask.view.rows.some((r) => r.working) && ask.send.state !== "offline" && !agentAdrift();
|
|
||||||
tabs.push({ id: "ask", label: "Ask", count: 0, dot: chatDot, busy: askBusy });
|
|
||||||
|
|
||||||
for (const t of tabs) {
|
for (const t of tabs) {
|
||||||
const b = el("button", "view-tab", t.label);
|
const b = el("button", "view-tab", t.label);
|
||||||
b.type = "button";
|
b.type = "button";
|
||||||
if (t.busy) {
|
|
||||||
const spin = el("span", "spinner tiny tab-spin");
|
|
||||||
spin.setAttribute("aria-hidden", "true");
|
|
||||||
b.prepend(spin);
|
|
||||||
b.title = t.id === "ask" ? "Plan2Code is working on an answer" : "Sent. Waiting for Plan2Code";
|
|
||||||
}
|
|
||||||
b.setAttribute("aria-current", String(view === t.id || (t.id === "questions" && view === "end")));
|
b.setAttribute("aria-current", String(view === t.id || (t.id === "questions" && view === "end")));
|
||||||
if (t.count) {
|
if (t.count) {
|
||||||
const c = el("span", "tab-count", String(t.count));
|
const c = el("span", "tab-count", String(t.count));
|
||||||
@@ -2216,7 +2104,6 @@ function paintMain(main) {
|
|||||||
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
|
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
|
||||||
if (view === "overview") return renderOverview(main);
|
if (view === "overview") return renderOverview(main);
|
||||||
if (view === "ask") return renderAsk(main);
|
if (view === "ask") return renderAsk(main);
|
||||||
if (view === "subagents") return renderSubagents(main);
|
|
||||||
|
|
||||||
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
||||||
// the top of the rail. The hand-off lives here alone now, rather than
|
// the top of the rail. The hand-off lives here alone now, rather than
|
||||||
@@ -2615,51 +2502,6 @@ function roleNudge() {
|
|||||||
return nudge;
|
return nudge;
|
||||||
}
|
}
|
||||||
|
|
||||||
// × on the update banner hides it for this console session only, and only
|
|
||||||
// for the release it named. Blocked storage means "not dismissed".
|
|
||||||
function updateDismissKey() {
|
|
||||||
try {
|
|
||||||
return "p2c-update-dismissed:" + S.sid;
|
|
||||||
} catch {
|
|
||||||
return "p2c-update-dismissed:";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateDismissed() {
|
|
||||||
try {
|
|
||||||
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
|
||||||
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
|
|
||||||
|
|
||||||
function releasesLink(text) {
|
|
||||||
const a = el("a", null, text);
|
|
||||||
a.href = RELEASES_URL;
|
|
||||||
a.target = "_blank";
|
|
||||||
a.rel = "noopener noreferrer";
|
|
||||||
return a;
|
|
||||||
}
|
|
||||||
|
|
||||||
function openUpdateModal() {
|
|
||||||
if (!updateFrame) return;
|
|
||||||
const versions = $("update-versions");
|
|
||||||
versions.replaceChildren(
|
|
||||||
document.createTextNode("Version "),
|
|
||||||
releasesLink("v" + updateFrame.latest),
|
|
||||||
document.createTextNode(" is out — you have "),
|
|
||||||
el("code", null, updateFrame.installed),
|
|
||||||
document.createTextNode(".")
|
|
||||||
);
|
|
||||||
const row = $("update-command");
|
|
||||||
const code = el("code", null, UPDATE_COMMAND);
|
|
||||||
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
|
|
||||||
$("update-modal").showModal();
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderDashboard(main) {
|
function renderDashboard(main) {
|
||||||
maybeWake();
|
maybeWake();
|
||||||
const menu = (S && S.menu) || {};
|
const menu = (S && S.menu) || {};
|
||||||
@@ -2671,25 +2513,6 @@ function renderDashboard(main) {
|
|||||||
warn.setAttribute("role", "status");
|
warn.setAttribute("role", "status");
|
||||||
wrap.appendChild(warn);
|
wrap.appendChild(warn);
|
||||||
}
|
}
|
||||||
// Built here only, so no other workflow's page ever shows it.
|
|
||||||
if (updateFrame && !updateDismissed()) {
|
|
||||||
const notice = el("div", "dash-nudge update-banner");
|
|
||||||
notice.setAttribute("role", "status");
|
|
||||||
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
|
|
||||||
open.type = "button";
|
|
||||||
open.addEventListener("click", openUpdateModal);
|
|
||||||
const dismiss = el("button", "update-banner-dismiss", "×");
|
|
||||||
dismiss.type = "button";
|
|
||||||
dismiss.setAttribute("aria-label", "Dismiss until next time");
|
|
||||||
dismiss.addEventListener("click", () => {
|
|
||||||
try {
|
|
||||||
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
|
|
||||||
} catch {}
|
|
||||||
render();
|
|
||||||
});
|
|
||||||
notice.append(open, dismiss);
|
|
||||||
wrap.appendChild(notice);
|
|
||||||
}
|
|
||||||
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
||||||
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
||||||
if (typeof menu.note === "string" && menu.note.trim()) {
|
if (typeof menu.note === "string" && menu.note.trim()) {
|
||||||
@@ -2719,7 +2542,6 @@ function renderDashboard(main) {
|
|||||||
const specs = specList();
|
const specs = specList();
|
||||||
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
|
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
|
||||||
wrap.appendChild(hideUnavailableToggle());
|
wrap.appendChild(hideUnavailableToggle());
|
||||||
if (!local.launching && !launchScoping) syncWorkspaceScope();
|
|
||||||
|
|
||||||
// "Unavailable" is the scan's verdict for the selected spec, not the
|
// "Unavailable" is the scan's verdict for the selected spec, not the
|
||||||
// momentary greying while a launch is in flight or the server is away, so
|
// momentary greying while a launch is in flight or the server is away, so
|
||||||
@@ -3141,11 +2963,6 @@ async function launchSkill(entry) {
|
|||||||
// cards that take no spec (utilities, setup) launch untargeted even while
|
// cards that take no spec (utilities, setup) launch untargeted even while
|
||||||
// a spec is selected.
|
// a spec is selected.
|
||||||
if (target) action.spec = target.dir;
|
if (target) action.spec = target.dir;
|
||||||
// The skill opens on the folders remembered for what it was launched for.
|
|
||||||
// Held until the launch is in flight: the swap's own frame re-renders the
|
|
||||||
// dashboard, which would otherwise sync back to the picker's spec.
|
|
||||||
launchScoping = true;
|
|
||||||
await syncWorkspaceScope(target ? target.dir : "");
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/submit", {
|
const res = await fetch("/submit", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -3156,7 +2973,6 @@ async function launchSkill(entry) {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (res.status === 409) {
|
if (res.status === 409) {
|
||||||
launchScoping = false;
|
|
||||||
pendingResult = true;
|
pendingResult = true;
|
||||||
banner("Your last pick is still being picked up. One moment.", "info");
|
banner("Your last pick is still being picked up. One moment.", "info");
|
||||||
return;
|
return;
|
||||||
@@ -3164,12 +2980,10 @@ async function launchSkill(entry) {
|
|||||||
if (!res.ok) throw new Error(String(res.status));
|
if (!res.ok) throw new Error(String(res.status));
|
||||||
sound("startSkill");
|
sound("startSkill");
|
||||||
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
|
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
|
||||||
launchScoping = false;
|
|
||||||
pendingResult = true;
|
pendingResult = true;
|
||||||
save();
|
save();
|
||||||
render();
|
render();
|
||||||
} catch {
|
} catch {
|
||||||
launchScoping = false;
|
|
||||||
banner("That did not go through. Nothing was lost; try again.", "warn");
|
banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3387,11 +3201,7 @@ document.addEventListener("keydown", cancelSkipMove, true);
|
|||||||
function skipAndMoveOn(id) {
|
function skipAndMoveOn(id) {
|
||||||
cancelSkipMove();
|
cancelSkipMove();
|
||||||
local.skipFlash = id;
|
local.skipFlash = id;
|
||||||
// A note already typed goes along: skipping the question is not retracting
|
stage(id, { type: "skip", skipped: true });
|
||||||
// the comment. Dropping it would leave the text in the box but out of the
|
|
||||||
// send, which looks kept and is not.
|
|
||||||
const cur = local.staged[id];
|
|
||||||
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
|
|
||||||
skipTimer = setTimeout(() => {
|
skipTimer = setTimeout(() => {
|
||||||
skipTimer = null;
|
skipTimer = null;
|
||||||
local.skipFlash = null;
|
local.skipFlash = null;
|
||||||
@@ -3508,41 +3318,15 @@ function renderWaiting(main) {
|
|||||||
}
|
}
|
||||||
pane.appendChild(title);
|
pane.appendChild(title);
|
||||||
pane.appendChild(el("p", null, doing));
|
pane.appendChild(el("p", null, doing));
|
||||||
const ask = "If Plan2Code needs you, the question appears here on its own.";
|
pane.appendChild(
|
||||||
if (!docs().length) {
|
el(
|
||||||
pane.appendChild(el("p", null, ask));
|
"p",
|
||||||
return;
|
null,
|
||||||
}
|
docs().length
|
||||||
// "Task" and the tasks tab's own name both open that tab, so the pointer is
|
? "The tabs above fill in as it goes. You can follow along with live `Task` updates in the `Phase tasks` tab. If Plan2Code needs you, the question appears here on its own."
|
||||||
// one click from what it points at. A build posts it as `phase` ("Phase N
|
: "If Plan2Code needs you, the question appears here on its own."
|
||||||
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
|
)
|
||||||
// Plan) has nothing live to follow, so it gets no pointer at all.
|
|
||||||
const list =
|
|
||||||
docs().find((d) => d.id === "phase") ||
|
|
||||||
docs().find((d) => d.id === "tasks") ||
|
|
||||||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
|
|
||||||
if (!list) {
|
|
||||||
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const jump = (word) => {
|
|
||||||
const b = el("button", "waiting-jump", word);
|
|
||||||
b.type = "button";
|
|
||||||
b.addEventListener("click", () => {
|
|
||||||
view = "doc:" + list.id;
|
|
||||||
render();
|
|
||||||
});
|
|
||||||
return b;
|
|
||||||
};
|
|
||||||
const p = el("p");
|
|
||||||
p.append(
|
|
||||||
"The tabs above fill in as it goes. You can follow along with live ",
|
|
||||||
jump("Task"),
|
|
||||||
" updates in the ",
|
|
||||||
jump(list.title || "Phase tasks"),
|
|
||||||
" tab. " + ask
|
|
||||||
);
|
);
|
||||||
pane.appendChild(p);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// A notice is context for the question it sits beside, so it lives inside the
|
// A notice is context for the question it sits beside, so it lives inside the
|
||||||
@@ -3678,8 +3462,8 @@ function renderSettled(card, item) {
|
|||||||
// would misreport which of the two was the answer.
|
// would misreport which of the two was the answer.
|
||||||
let prose = text;
|
let prose = text;
|
||||||
if (!prose && !lines.length) {
|
if (!prose && !lines.length) {
|
||||||
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
|
const mine = (item.thread || []).filter((m) => m.who === "user");
|
||||||
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
|
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
const nothing = !lines.length && !prose;
|
const nothing = !lines.length && !prose;
|
||||||
@@ -4495,10 +4279,6 @@ function buildChecklist(card, item, staged) {
|
|||||||
const commitList = (change) => {
|
const commitList = (change) => {
|
||||||
const cur = local.staged[item.id];
|
const cur = local.staged[item.id];
|
||||||
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
|
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
|
||||||
// A tick or a state IS the answer, so it ends a skip staged earlier:
|
|
||||||
// left in place, `skipped` would collapse the reply to "skip" while the
|
|
||||||
// card showed ticked steps on their way.
|
|
||||||
delete next.skipped;
|
|
||||||
const empty = !(next.done && next.done.length) && !next.state && !next.text;
|
const empty = !(next.done && next.done.length) && !next.state && !next.text;
|
||||||
stage(item.id, empty ? null : next);
|
stage(item.id, empty ? null : next);
|
||||||
};
|
};
|
||||||
@@ -4548,7 +4328,7 @@ function buildChecklist(card, item, staged) {
|
|||||||
function buildMenu(card, item, staged) {
|
function buildMenu(card, item, staged) {
|
||||||
const list = el("ul", "options");
|
const list = el("ul", "options");
|
||||||
const name = "menu-" + item.id;
|
const name = "menu-" + item.id;
|
||||||
for (const [i, o] of (item.options || []).entries()) {
|
for (const o of item.options || []) {
|
||||||
const picked = staged && staged.k === o.k;
|
const picked = staged && staged.k === o.k;
|
||||||
const li = el("li", "option" + (picked ? " is-picked" : ""));
|
const li = el("li", "option" + (picked ? " is-picked" : ""));
|
||||||
const label = el("label");
|
const label = el("label");
|
||||||
@@ -4556,13 +4336,7 @@ function buildMenu(card, item, staged) {
|
|||||||
const radio = el("input");
|
const radio = el("input");
|
||||||
radio.type = "radio";
|
radio.type = "radio";
|
||||||
radio.name = name;
|
radio.name = name;
|
||||||
// The same id buildChoice gives its radios: withFocus finds the focused
|
|
||||||
// input by id after the render this change() sets off, and without one a
|
|
||||||
// keyboard user arrowing through the menu lands on <body> every time.
|
|
||||||
radio.id = optionId(item, o, i);
|
|
||||||
radio.value = o.k;
|
|
||||||
radio.checked = Boolean(picked);
|
radio.checked = Boolean(picked);
|
||||||
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
|
|
||||||
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
|
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
|
||||||
const body = el("div", "option-body");
|
const body = el("div", "option-body");
|
||||||
const head = el("div", "option-label");
|
const head = el("div", "option-label");
|
||||||
@@ -4861,42 +4635,6 @@ function renderOverview(main) {
|
|||||||
main.appendChild(box);
|
main.appendChild(box);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The helpers the agent reported, as it last posted them. Everything here is
|
|
||||||
// the agent's text, so it goes in as text, never as markup.
|
|
||||||
function renderSubagents(main) {
|
|
||||||
const card = el("section", "card sa-card");
|
|
||||||
card.appendChild(el("h2", null, "Subagents"));
|
|
||||||
card.appendChild(el("p", "help", CHECKIN_LINE));
|
|
||||||
const { alone, rows } = helperRows(S.helpers);
|
|
||||||
if (alone) {
|
|
||||||
card.appendChild(
|
|
||||||
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
|
|
||||||
);
|
|
||||||
main.appendChild(card);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const list = el("ul", "sa-list");
|
|
||||||
for (const row of rows) {
|
|
||||||
const item = el("li", "sa-row");
|
|
||||||
const head = el("div", "sa-head");
|
|
||||||
head.appendChild(el("strong", "sa-title", row.title));
|
|
||||||
const pill = el("span", "pill sa-pill is-" + row.state);
|
|
||||||
if (row.state === "running") {
|
|
||||||
const spin = el("span", "spinner tiny");
|
|
||||||
spin.setAttribute("aria-hidden", "true");
|
|
||||||
pill.appendChild(spin);
|
|
||||||
}
|
|
||||||
pill.appendChild(document.createTextNode(row.stateLabel));
|
|
||||||
head.appendChild(pill);
|
|
||||||
item.appendChild(head);
|
|
||||||
item.appendChild(el("p", "sa-ask", row.ask));
|
|
||||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
|
||||||
list.appendChild(item);
|
|
||||||
}
|
|
||||||
card.appendChild(list);
|
|
||||||
main.appendChild(card);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---------------------------------------------------------------- ask */
|
/* ---------------------------------------------------------------- ask */
|
||||||
|
|
||||||
// The frame's chat block, with `offline` worked out now rather than when the
|
// The frame's chat block, with `offline` worked out now rather than when the
|
||||||
@@ -5495,30 +5233,20 @@ function renderAside() {
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// A note that has been sent but not yet picked up: marked as waiting, so the
|
|
||||||
// send is seen to have gone, until the agent replies. The server writes the
|
|
||||||
// note into the thread as it arrives; a session from before that has only
|
|
||||||
// `sentNote`, which gets a box of its own below.
|
|
||||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
|
||||||
let waitingShown = false;
|
|
||||||
for (const m of thread) {
|
for (const m of thread) {
|
||||||
const mine = threadWho(m) === "user";
|
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
|
||||||
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
|
|
||||||
if (pending) waitingShown = true;
|
|
||||||
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
|
|
||||||
const who = el("div", "msg-who");
|
const who = el("div", "msg-who");
|
||||||
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
|
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
|
||||||
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
|
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||||
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
|
||||||
box.appendChild(who);
|
box.appendChild(who);
|
||||||
const text = threadText(m);
|
box.appendChild(md(m.text, "md"));
|
||||||
if (text) box.appendChild(md(text, "md"));
|
|
||||||
const tray = mine ? sentAttachments(m) : null;
|
|
||||||
if (tray) box.appendChild(tray);
|
|
||||||
aside.appendChild(box);
|
aside.appendChild(box);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (waiting && !waitingShown) {
|
// A note that has been sent but not yet picked up: shown at once, so the
|
||||||
|
// send is seen to have gone, and gone when the agent replies.
|
||||||
|
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||||
|
if (waiting) {
|
||||||
const box = el("div", "msg you pending");
|
const box = el("div", "msg you pending");
|
||||||
const who = el("div", "msg-who");
|
const who = el("div", "msg-who");
|
||||||
who.appendChild(el("span", null, "You"));
|
who.appendChild(el("span", null, "You"));
|
||||||
@@ -5818,10 +5546,7 @@ async function attachFiles(itemId, files) {
|
|||||||
const taken = wanted.slice(0, room);
|
const taken = wanted.slice(0, room);
|
||||||
// One banner at a time, so every refusal goes into it, each by name.
|
// One banner at a time, so every refusal goes into it, each by name.
|
||||||
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
|
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
|
||||||
if (taken.length < wanted.length)
|
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
|
||||||
said.push(
|
|
||||||
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
|
|
||||||
);
|
|
||||||
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
|
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
taken.map(async (file) => {
|
taken.map(async (file) => {
|
||||||
@@ -5924,19 +5649,6 @@ function sendState() {
|
|||||||
: { disabled: true, why: "Your last answers are on their way. One moment.", short: "" };
|
: { disabled: true, why: "Your last answers are on their way. One moment.", short: "" };
|
||||||
}
|
}
|
||||||
if (agentWorking()) {
|
if (agentWorking()) {
|
||||||
// A question the agent left open while still working is still a question,
|
|
||||||
// and its answer has nowhere better to wait than the server, which holds
|
|
||||||
// a send until the agent next looks. The contract says to switch to
|
|
||||||
// "waiting" before asking, but an agent that asks and carries on ("while
|
|
||||||
// you decide") must not lock the person out of answering for up to an
|
|
||||||
// hour of quietMinutes.
|
|
||||||
if (myTurn().length && (stagedCount() || pendingNotes().length)) {
|
|
||||||
return {
|
|
||||||
disabled: false,
|
|
||||||
why: "Plan2Code is still working. Your answers wait for it to look.",
|
|
||||||
short: "Still working · it reads this next",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const ms = workingMs();
|
const ms = workingMs();
|
||||||
if (ms > patience(WORKING_GRACE_MS)) {
|
if (ms > patience(WORKING_GRACE_MS)) {
|
||||||
// A stuck agent must not lock someone out of their own session, so the
|
// A stuck agent must not lock someone out of their own session, so the
|
||||||
@@ -6079,30 +5791,10 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
|
|||||||
// session opened before the server wrote `worktree` has nothing to show, so
|
// session opened before the server wrote `worktree` has nothing to show, so
|
||||||
// the slot stays hidden. The footer renders on every tick, so the DOM is only
|
// the slot stays hidden. The footer renders on every tick, so the DOM is only
|
||||||
// touched when the labels change, or when a resize clears the key.
|
// touched when the labels change, or when a resize clears the key.
|
||||||
// The project's name: the workspace's original folder, or the session's
|
|
||||||
// worktree folder before a frame carries the workspace.
|
|
||||||
function projectName() {
|
|
||||||
const folders = workspaceFolders();
|
|
||||||
if (folders.length && folders[0].name) return folders[0].name;
|
|
||||||
const path = (S && S.worktree) || "";
|
|
||||||
return path ? path.split(/[\\/]/).filter(Boolean).pop() || path : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// The browser tab's title, led by the project so tabs from different
|
|
||||||
// projects are told apart. Called from the chrome and the footer, since the
|
|
||||||
// workspace frame can arrive after either.
|
|
||||||
function renderTabTitle() {
|
|
||||||
if (!S) return;
|
|
||||||
const name = projectName();
|
|
||||||
document.title =
|
|
||||||
(name ? name + " · " : "") + (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderWhere() {
|
function renderWhere() {
|
||||||
const b = $("footer-where");
|
const b = $("footer-where");
|
||||||
const folders = workspaceFolders();
|
const folders = workspaceFolders();
|
||||||
const path = S.worktree || "";
|
const path = S.worktree || "";
|
||||||
renderTabTitle();
|
|
||||||
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
|
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
|
||||||
const labels = folders.length
|
const labels = folders.length
|
||||||
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
|
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
|
||||||
@@ -6115,16 +5807,7 @@ function renderWhere() {
|
|||||||
let label = labels[0];
|
let label = labels[0];
|
||||||
for (const text of labels) {
|
for (const text of labels) {
|
||||||
label = text;
|
label = text;
|
||||||
// The project name takes the highlight color, so several consoles side by
|
|
||||||
// side tell apart at a glance; the rest of the label stays quiet.
|
|
||||||
const name = projectName();
|
|
||||||
b.textContent = "";
|
|
||||||
if (name && text.startsWith(name)) {
|
|
||||||
b.appendChild(el("span", "where-project", name));
|
|
||||||
b.appendChild(document.createTextNode(text.slice(name.length)));
|
|
||||||
} else {
|
|
||||||
b.textContent = text;
|
b.textContent = text;
|
||||||
}
|
|
||||||
if (alert) {
|
if (alert) {
|
||||||
const dot = el("span", "where-alert");
|
const dot = el("span", "where-alert");
|
||||||
dot.setAttribute("aria-hidden", "true");
|
dot.setAttribute("aria-hidden", "true");
|
||||||
@@ -6171,32 +5854,6 @@ async function postJson(url, body) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The workspace follows the dashboard's picker: the folders remembered for
|
|
||||||
the selected spec, or the project's own under "Start from scratch". The
|
|
||||||
server swaps the list and remembers every change after it. */
|
|
||||||
let scopeAsked = null;
|
|
||||||
// True from a launch's scope sync until its send has gone (or failed).
|
|
||||||
let launchScoping = false;
|
|
||||||
async function syncWorkspaceScope(spec) {
|
|
||||||
if (!S || S.workflow !== "dashboard" || gone || !wsFrame) return;
|
|
||||||
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
|
|
||||||
if ((wsFrame.scope || "") === want || scopeAsked === want) return;
|
|
||||||
scopeAsked = want;
|
|
||||||
const { status, body } = await postJson("/workspace/scope", { spec: want });
|
|
||||||
if (status === 200 && body && Array.isArray(body.folders)) wsFrame = { ...wsFrame, ...body };
|
|
||||||
scopeAsked = null;
|
|
||||||
if ($("workspace-modal").open) renderWorkspace();
|
|
||||||
}
|
|
||||||
|
|
||||||
// The dialog's "Remembered for" line: whose list this is.
|
|
||||||
function workspaceScopeText() {
|
|
||||||
const scope = (wsFrame && wsFrame.scope) || "";
|
|
||||||
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
|
|
||||||
const spec = specList().find((s) => s.dir === scope);
|
|
||||||
const name = spec ? spec.name : scope.split("/").pop();
|
|
||||||
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
|
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
|
||||||
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
|
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
|
||||||
// The folder whose Remove is waiting on its inline confirm, by id.
|
// The folder whose Remove is waiting on its inline confirm, by id.
|
||||||
@@ -6236,7 +5893,6 @@ function renderWorkspace() {
|
|||||||
}
|
}
|
||||||
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
|
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
|
||||||
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
|
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
|
||||||
$("workspace-scope").textContent = workspaceScopeText();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function workspaceRow(f) {
|
function workspaceRow(f) {
|
||||||
@@ -6700,10 +6356,6 @@ async function goHome() {
|
|||||||
$("home-modal").close();
|
$("home-modal").close();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
$("home-modal").close();
|
$("home-modal").close();
|
||||||
// The server is holding an uncollected result: Send, Home and Stop all
|
|
||||||
// need to read as busy until the frame or the ping says otherwise, same
|
|
||||||
// as send() and sendAfterBuild() do on a 409.
|
|
||||||
if (err && err.pending) pendingResult = true;
|
|
||||||
banner(
|
banner(
|
||||||
err && err.pending
|
err && err.pending
|
||||||
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
||||||
@@ -6764,7 +6416,6 @@ async function stopSession() {
|
|||||||
stoppingHidden = false;
|
stoppingHidden = false;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
$("stop-modal").close();
|
$("stop-modal").close();
|
||||||
if (err && err.pending) pendingResult = true;
|
|
||||||
banner(
|
banner(
|
||||||
err && err.pending
|
err && err.pending
|
||||||
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
||||||
@@ -6919,6 +6570,7 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
|
|||||||
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
|
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
|
||||||
}
|
}
|
||||||
local.staged = {};
|
local.staged = {};
|
||||||
|
local.sentAt = Date.now();
|
||||||
save();
|
save();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6971,7 +6623,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
|
|||||||
// something the agent never hears.
|
// something the agent never hears.
|
||||||
function tokenFor(item, v) {
|
function tokenFor(item, v) {
|
||||||
const map = item.token || {};
|
const map = item.token || {};
|
||||||
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
|
if (v.skipped) return "skip";
|
||||||
const parts = [];
|
const parts = [];
|
||||||
if (v.k) parts.push(map[v.k] || v.k);
|
if (v.k) parts.push(map[v.k] || v.k);
|
||||||
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
|
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
|
||||||
@@ -7203,14 +6855,14 @@ function renderAbout() {
|
|||||||
let helpBuilt = false;
|
let helpBuilt = false;
|
||||||
|
|
||||||
async function renderHelpVersion() {
|
async function renderHelpVersion() {
|
||||||
const slot = $("help-version");
|
const el = $("help-version");
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/version", { cache: "no-store" });
|
const res = await fetch("/version", { cache: "no-store" });
|
||||||
const { version } = res.ok ? await res.json() : {};
|
const { version } = res.ok ? await res.json() : {};
|
||||||
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
|
el.textContent = version ? "Plan2Code v" + version : "";
|
||||||
slot.hidden = !version;
|
el.hidden = !version;
|
||||||
} catch {
|
} catch {
|
||||||
slot.hidden = true;
|
el.hidden = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -7318,7 +6970,6 @@ function openHelpOn(id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$("btn-home").addEventListener("click", openHomeConfirm);
|
$("btn-home").addEventListener("click", openHomeConfirm);
|
||||||
$("update-done").addEventListener("click", () => $("update-modal").close());
|
|
||||||
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
||||||
$("home-go").addEventListener("click", goHome);
|
$("home-go").addEventListener("click", goHome);
|
||||||
$("btn-stop").addEventListener("click", openStopConfirm);
|
$("btn-stop").addEventListener("click", openStopConfirm);
|
||||||
@@ -7349,7 +7000,6 @@ function lightDismiss(dlg) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
lightDismiss($("looks-modal"));
|
lightDismiss($("looks-modal"));
|
||||||
lightDismiss($("subagents-modal"));
|
|
||||||
lightDismiss($("help-modal"));
|
lightDismiss($("help-modal"));
|
||||||
lightDismiss($("workspace-modal"));
|
lightDismiss($("workspace-modal"));
|
||||||
lightDismiss($("welcome-modal"));
|
lightDismiss($("welcome-modal"));
|
||||||
@@ -7399,7 +7049,6 @@ $("btn-looks").addEventListener("click", () => {
|
|||||||
});
|
});
|
||||||
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
||||||
$("looks-modal").addEventListener("close", () => {
|
$("looks-modal").addEventListener("close", () => {
|
||||||
resetCleanup();
|
|
||||||
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
|
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
|
||||||
});
|
});
|
||||||
$("looks-reset").addEventListener("click", () => {
|
$("looks-reset").addEventListener("click", () => {
|
||||||
@@ -7546,119 +7195,7 @@ $("models-reset").addEventListener("click", () => {
|
|||||||
renderModels();
|
renderModels();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Cleanup: the server works out what in ~/.plan2code is not needed and
|
|
||||||
// shows it first; Delete these sends back only the ids it was shown, and the
|
|
||||||
// server re-checks every one before removing it.
|
|
||||||
let cleanupFound = null;
|
|
||||||
// Bumped by every scan, delete and reset: a response from an older one is
|
|
||||||
// dropped, so a scan still in flight when Preferences closes cannot refill it.
|
|
||||||
let cleanupGen = 0;
|
|
||||||
const CLEANUP_SHOWN = 8;
|
|
||||||
|
|
||||||
function setCleanupStatus(text, isError) {
|
|
||||||
const status = $("cleanup-status");
|
|
||||||
status.textContent = text;
|
|
||||||
status.classList.toggle("error", Boolean(isError));
|
|
||||||
}
|
|
||||||
|
|
||||||
function cleanupLabel(item) {
|
|
||||||
if (item.where === "session") return "Session " + item.name;
|
|
||||||
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
|
|
||||||
return where + item.name + (item.kind === "folder" ? "/" : "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function cleanupSummary(items, bytes) {
|
|
||||||
const sessions = items.filter((i) => i.where === "session").length;
|
|
||||||
const strays = items.length - sessions;
|
|
||||||
const parts = [];
|
|
||||||
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
|
|
||||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
|
||||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resetCleanup() {
|
|
||||||
cleanupGen++;
|
|
||||||
cleanupFound = null;
|
|
||||||
$("cleanup-list").replaceChildren();
|
|
||||||
$("cleanup-delete").hidden = true;
|
|
||||||
$("cleanup-delete").disabled = false;
|
|
||||||
$("cleanup-scan").disabled = false;
|
|
||||||
setCleanupStatus("", false);
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderCleanup() {
|
|
||||||
const list = $("cleanup-list");
|
|
||||||
list.replaceChildren();
|
|
||||||
const items = (cleanupFound && cleanupFound.items) || [];
|
|
||||||
$("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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function scanCleanup() {
|
|
||||||
const gen = ++cleanupGen;
|
|
||||||
$("cleanup-scan").disabled = true;
|
|
||||||
$("cleanup-delete").disabled = true;
|
|
||||||
setCleanupStatus("Looking…", false);
|
|
||||||
const { status, body } = await postJson("/cleanup", { scan: true });
|
|
||||||
if (gen !== cleanupGen) return;
|
|
||||||
$("cleanup-scan").disabled = false;
|
|
||||||
$("cleanup-delete").disabled = false;
|
|
||||||
if (status !== 200 || !body.ok) {
|
|
||||||
cleanupFound = null;
|
|
||||||
renderCleanup();
|
|
||||||
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
|
|
||||||
}
|
|
||||||
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function deleteCleanup() {
|
|
||||||
if (!cleanupFound || !cleanupFound.items.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) });
|
|
||||||
if (gen !== cleanupGen) return;
|
|
||||||
$("cleanup-delete").disabled = false;
|
|
||||||
$("cleanup-scan").disabled = false;
|
|
||||||
if (status !== 200 || !body.ok) {
|
|
||||||
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
|
|
||||||
}
|
|
||||||
const removed = (body.removed || []).length;
|
|
||||||
const failed = (body.failed || []).length;
|
|
||||||
cleanupFound = null;
|
|
||||||
renderCleanup();
|
|
||||||
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
|
|
||||||
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
|
|
||||||
}
|
|
||||||
|
|
||||||
$("cleanup-scan").addEventListener("click", scanCleanup);
|
|
||||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
|
||||||
|
|
||||||
$("btn-brief").addEventListener("click", openBrief);
|
$("btn-brief").addEventListener("click", openBrief);
|
||||||
$("btn-subagents").addEventListener("click", openSubagents);
|
|
||||||
$("subagents-default").addEventListener("click", () => {
|
|
||||||
$("subagents-instruction").value = defaultInstruction(S.workflow);
|
|
||||||
});
|
|
||||||
$("subagents-save").addEventListener("click", saveSubagents);
|
|
||||||
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
|
|
||||||
$("subagents-modal").addEventListener("close", () => $("btn-subagents").focus());
|
|
||||||
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
||||||
$("brief-go").addEventListener("click", sendBrief);
|
$("brief-go").addEventListener("click", sendBrief);
|
||||||
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ export const HELP_TABS = Object.freeze([
|
|||||||
tab("dashboard", "The dashboard", true),
|
tab("dashboard", "The dashboard", true),
|
||||||
tab("meter", "Session meter", false),
|
tab("meter", "Session meter", false),
|
||||||
tab("build", "Watching a build", false),
|
tab("build", "Watching a build", false),
|
||||||
tab("subagents", "Helpers (subagents)", false),
|
|
||||||
tab("ask", "Ask a quick question", false),
|
tab("ask", "Ask a quick question", false),
|
||||||
tab("finishing", "Stopping and finishing", false),
|
tab("finishing", "Stopping and finishing", false),
|
||||||
tab("stuck", "When something looks stuck", true),
|
tab("stuck", "When something looks stuck", true),
|
||||||
@@ -40,7 +39,6 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
|||||||
if (gone || adrift) return "stuck";
|
if (gone || adrift) return "stuck";
|
||||||
if (workspace) return "workspace";
|
if (workspace) return "workspace";
|
||||||
if (v === "ask") return "ask";
|
if (v === "ask") return "ask";
|
||||||
if (v === "subagents") return "subagents";
|
|
||||||
if (dashboard && meterRed) return "meter";
|
if (dashboard && meterRed) return "meter";
|
||||||
if (dashboard) return "dashboard";
|
if (dashboard) return "dashboard";
|
||||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||||
|
|||||||
@@ -21,7 +21,6 @@
|
|||||||
<link rel="modulepreload" href="/starters.js" />
|
<link rel="modulepreload" href="/starters.js" />
|
||||||
<link rel="modulepreload" href="/workspace.js" />
|
<link rel="modulepreload" href="/workspace.js" />
|
||||||
<link rel="modulepreload" href="/meter.js" />
|
<link rel="modulepreload" href="/meter.js" />
|
||||||
<link rel="modulepreload" href="/subagents.js" />
|
|
||||||
<link rel="modulepreload" href="/mentions.js" />
|
<link rel="modulepreload" href="/mentions.js" />
|
||||||
<link rel="modulepreload" href="/favicon.js" />
|
<link rel="modulepreload" href="/favicon.js" />
|
||||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||||
@@ -173,18 +172,6 @@
|
|||||||
<button type="button" class="btn ghost small brief-btn" id="btn-brief" hidden>
|
<button type="button" class="btn ghost small brief-btn" id="btn-brief" hidden>
|
||||||
Write a brief
|
Write a brief
|
||||||
</button>
|
</button>
|
||||||
<!-- Subagents: opted-in skills only. Lit while helpers are on; a click
|
|
||||||
opens the Subagents dialog and never toggles them itself. -->
|
|
||||||
<button type="button" class="btn ghost small subagents-btn" id="btn-subagents" aria-pressed="false" hidden>
|
|
||||||
<!-- An orchestrator and its helpers: one larger node linked to three smaller ones. -->
|
|
||||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
||||||
<path class="sa-link" d="M6.9 6.6L10.9 3.9M7.4 8h3.5M6.9 9.4l4 2.7" />
|
|
||||||
<circle cx="4.6" cy="8" r="2.6" class="sa-hub" />
|
|
||||||
<circle cx="12.4" cy="3" r="1.5" class="sa-node" />
|
|
||||||
<circle cx="12.4" cy="8" r="1.5" class="sa-node" />
|
|
||||||
<circle cx="12.4" cy="13" r="1.5" class="sa-node" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="views-group">
|
<div class="views-group">
|
||||||
<span class="views-arrow" aria-hidden="true">
|
<span class="views-arrow" aria-hidden="true">
|
||||||
@@ -418,7 +405,7 @@
|
|||||||
</svg>
|
</svg>
|
||||||
|
|
||||||
<!-- 4 Finalize: hopping for joy, both arms up, beside the checkmark
|
<!-- 4 Finalize: hopping for joy, both arms up, beside the checkmark
|
||||||
flag, confetti drifting down. -->
|
flag, confetti drifting down and his star glowing. -->
|
||||||
<svg class="pose pose-finalize" data-pose="finalize" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
|
<svg class="pose pose-finalize" data-pose="finalize" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
|
||||||
<ellipse class="shadow fz-shadow" cx="120" cy="198" rx="34" ry="5" />
|
<ellipse class="shadow fz-shadow" cx="120" cy="198" rx="34" ry="5" />
|
||||||
<g class="fz-hop">
|
<g class="fz-hop">
|
||||||
@@ -428,6 +415,7 @@
|
|||||||
<rect class="sh" x="80" y="72" width="80" height="108" rx="16" />
|
<rect class="sh" x="80" y="72" width="80" height="108" rx="16" />
|
||||||
<path class="ln" d="M80 116 L60 90" /><circle class="fl" cx="60" cy="90" r="5.5" />
|
<path class="ln" d="M80 116 L60 90" /><circle class="fl" cx="60" cy="90" r="5.5" />
|
||||||
<path class="ln" d="M160 116 L180 90" /><circle class="fl" cx="180" cy="90" r="5.5" />
|
<path class="ln" d="M160 116 L180 90" /><circle class="fl" cx="180" cy="90" r="5.5" />
|
||||||
|
<circle class="ac fz-halo" cx="120" cy="98" r="23" />
|
||||||
<path class="ey blink" d="M120 84 L123.64 92.98 L133.31 93.67 L125.9 99.92 L128.23 109.33 L120 104.2 L111.77 109.33 L114.1 99.92 L106.69 93.67 L116.36 92.98 Z" />
|
<path class="ey blink" d="M120 84 L123.64 92.98 L133.31 93.67 L125.9 99.92 L128.23 109.33 L120 104.2 L111.77 109.33 L114.1 99.92 L106.69 93.67 L116.36 92.98 Z" />
|
||||||
<path class="ey" d="M106 118 Q120 134 134 118 Z" />
|
<path class="ey" d="M106 118 Q120 134 134 118 Z" />
|
||||||
</g>
|
</g>
|
||||||
@@ -593,13 +581,6 @@
|
|||||||
<rect x="3" y="9" width="18" height="6" rx="3" />
|
<rect x="3" y="9" width="18" height="6" rx="3" />
|
||||||
<path d="M6 12h7" />
|
<path d="M6 12h7" />
|
||||||
</symbol>
|
</symbol>
|
||||||
<symbol id="hi-subagents" viewBox="0 0 24 24" fill="none">
|
|
||||||
<circle cx="7" cy="12" r="3.5" />
|
|
||||||
<circle cx="18" cy="5" r="2" />
|
|
||||||
<circle cx="18" cy="12" r="2" />
|
|
||||||
<circle cx="18" cy="19" r="2" />
|
|
||||||
<path d="M10 10l6-4M10.5 12H16M10 14l6 4" />
|
|
||||||
</symbol>
|
|
||||||
<symbol id="hi-ask" viewBox="0 0 24 24" fill="none">
|
<symbol id="hi-ask" viewBox="0 0 24 24" fill="none">
|
||||||
<path d="M4 5h16v11H10l-4 4v-4H4z" />
|
<path d="M4 5h16v11H10l-4 4v-4H4z" />
|
||||||
<path d="M8 9.5h8M8 12.5h5" />
|
<path d="M8 9.5h8M8 12.5h5" />
|
||||||
@@ -852,28 +833,10 @@
|
|||||||
Click the folder name in the middle of the bottom bar. It shows your
|
Click the folder name in the middle of the bottom bar. It shows your
|
||||||
folder's name and branch, such as <strong>shop · main</strong>, and
|
folder's name and branch, such as <strong>shop · main</strong>, and
|
||||||
<strong>shop + 2 folders · main</strong> once you have added some.
|
<strong>shop + 2 folders · main</strong> once you have added some.
|
||||||
It carries across steps you start from the dashboard.
|
The workspace lasts for this console session only: it carries across
|
||||||
|
steps you start from the dashboard, and a new console session starts
|
||||||
|
with just the folder you started in.
|
||||||
</p>
|
</p>
|
||||||
<h4>Remembered for next time</h4>
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
Every change is saved as you make it, so the next console session in
|
|
||||||
this folder starts with the same folders.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
Each spec keeps its own list. The first time you pick a spec on the
|
|
||||||
dashboard it starts as a copy of the project's list (the one shown
|
|
||||||
under <strong>Start from scratch</strong>), and after that the two
|
|
||||||
are separate. Picking a spec loads its list; the line under the
|
|
||||||
dialog's title says whose list you are looking at.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
The lists live in <code>workspaces.json</code> in your own
|
|
||||||
Plan2Code settings folder, beside your look and feel, never in the
|
|
||||||
project. Finalize offers to forget a spec's list when it archives the
|
|
||||||
spec.
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
<h4>Adding a folder</h4>
|
<h4>Adding a folder</h4>
|
||||||
<ul>
|
<ul>
|
||||||
<li>
|
<li>
|
||||||
@@ -1311,14 +1274,6 @@
|
|||||||
come back, and you can change your role any time from the swatch
|
come back, and you can change your role any time from the swatch
|
||||||
button.
|
button.
|
||||||
</p>
|
</p>
|
||||||
<h4>When an update is out</h4>
|
|
||||||
<p>
|
|
||||||
When a newer Plan2Code release is out, the dashboard shows
|
|
||||||
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
|
|
||||||
to run in your terminal; × hides it until the next
|
|
||||||
<code>/plan2code</code>. The version at the bottom of Help links to
|
|
||||||
the Releases page.
|
|
||||||
</p>
|
|
||||||
<h4>The cards</h4>
|
<h4>The cards</h4>
|
||||||
<p>They come in three groups.</p>
|
<p>They come in three groups.</p>
|
||||||
<p><strong>First, the project</strong></p>
|
<p><strong>First, the project</strong></p>
|
||||||
@@ -1408,10 +1363,9 @@
|
|||||||
<h4>What it counts</h4>
|
<h4>What it counts</h4>
|
||||||
<p>
|
<p>
|
||||||
Each step you run here adds points: a plan or a set of documents
|
Each step you run here adds points: a plan or a set of documents
|
||||||
weighs more than a quick task, and a built phase more still, by how
|
weighs more than a single answered question, and a built phase more
|
||||||
many tasks it completed: a big phase adds more than a small one.
|
still, by how many tasks it completed: a big phase adds more than a
|
||||||
Every two questions you answer within one step add a point too
|
small one. Every two questions you answer add a point too, so a long
|
||||||
(rounded down, so a single answer adds nothing), so a long
|
|
||||||
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
|
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
|
||||||
points, with what it added. It is a rule of thumb, not a
|
points, with what it added. It is a rule of thumb, not a
|
||||||
reading of Plan2Code's real memory: long sessions tend to make it
|
reading of Plan2Code's real memory: long sessions tend to make it
|
||||||
@@ -1497,61 +1451,7 @@
|
|||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 12: Helpers (subagents) -->
|
<!-- Tab 12: Ask a quick question -->
|
||||||
<section class="help-panel" data-tab="subagents">
|
|
||||||
<h3>Helpers (subagents)</h3>
|
|
||||||
<p>
|
|
||||||
On a build, a review and Pathfinder, Plan2Code can hand independent
|
|
||||||
pieces of work to helpers (subagents) while it keeps the conversation
|
|
||||||
with you. The <strong>Subagents</strong> button in the top bar, after
|
|
||||||
Stop session, is lit while helpers are on.
|
|
||||||
</p>
|
|
||||||
<h4>The switch</h4>
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
Clicking the button opens the <strong>Subagents</strong> dialog; it
|
|
||||||
never switches helpers on or off by itself. Pick <strong>Use
|
|
||||||
helpers</strong> or <strong>Work alone</strong>, edit the instruction
|
|
||||||
Plan2Code follows (<strong>Reset to default</strong> puts the
|
|
||||||
shipped one back), and say how many may run at once.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
It is off by default and saved for this project and this skill, so
|
|
||||||
the next session of the same skill here starts the same way.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
The change reaches Plan2Code at its next check-in, as a setting,
|
|
||||||
not as something you typed. How many helpers it can really start is
|
|
||||||
up to your agent; some have no helpers at all.
|
|
||||||
</li>
|
|
||||||
<li>The button only appears on skills that use helpers, and only when Plan2Code can pass the setting on.</li>
|
|
||||||
</ul>
|
|
||||||
<h4>The Subagents tab</h4>
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
With the first helper, a <strong>Subagents</strong> tab appears before
|
|
||||||
Ask: one row each, with what it was asked, whether it is running, done
|
|
||||||
or failed, and a one-line result at the end. The number on the tab is
|
|
||||||
how many are still running.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
Helpers report through Plan2Code, so the rows change at its
|
|
||||||
check-ins, not live. The page cannot stop a helper; ask Plan2Code
|
|
||||||
on the Ask tab if one should stop.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
<strong>Working alone</strong> means your agent has no way to start
|
|
||||||
helpers here, so it is doing the work itself.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
Pathfinder always uses helpers for its research questions, whatever
|
|
||||||
the switch says, and they show here too.
|
|
||||||
</li>
|
|
||||||
<li>The tab clears when you go back to the dashboard.</li>
|
|
||||||
</ul>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<!-- Tab 13: Ask a quick question -->
|
|
||||||
<section class="help-panel" data-tab="ask">
|
<section class="help-panel" data-tab="ask">
|
||||||
<h3>Ask a quick question</h3>
|
<h3>Ask a quick question</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1642,7 +1542,7 @@
|
|||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 14: Stopping and finishing -->
|
<!-- Tab 13: Stopping and finishing -->
|
||||||
<section class="help-panel" data-tab="finishing">
|
<section class="help-panel" data-tab="finishing">
|
||||||
<h3>Stopping and finishing</h3>
|
<h3>Stopping and finishing</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1724,7 +1624,7 @@
|
|||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 15: When something looks stuck -->
|
<!-- Tab 14: When something looks stuck -->
|
||||||
<section class="help-panel" data-tab="stuck">
|
<section class="help-panel" data-tab="stuck">
|
||||||
<h3>When something looks stuck</h3>
|
<h3>When something looks stuck</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1846,7 +1746,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 16: Keyboard and preferences -->
|
<!-- Tab 15: Keyboard and preferences -->
|
||||||
<section class="help-panel" data-tab="prefs">
|
<section class="help-panel" data-tab="prefs">
|
||||||
<h3>Keyboard and preferences</h3>
|
<h3>Keyboard and preferences</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1927,15 +1827,6 @@
|
|||||||
joining the strip. Keep only the ones you want; ticking a box plays
|
joining the strip. Keep only the ones you want; ticking a box plays
|
||||||
its sound.
|
its sound.
|
||||||
</li>
|
</li>
|
||||||
<li>
|
|
||||||
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
|
|
||||||
lists what Plan2Code doesn't need in your
|
|
||||||
<code>~/.plan2code</code> folder: sessions nobody has opened for
|
|
||||||
30 days, and files or folders that ended up there by mistake. It
|
|
||||||
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.
|
|
||||||
</li>
|
|
||||||
<li>
|
<li>
|
||||||
<strong>Back to default</strong> puts everything back as it was, and
|
<strong>Back to default</strong> puts everything back as it was, and
|
||||||
sets Role back to Not set.
|
sets Role back to Not set.
|
||||||
@@ -1962,7 +1853,7 @@
|
|||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 17: Privacy and where things are saved -->
|
<!-- Tab 16: Privacy and where things are saved -->
|
||||||
<section class="help-panel" data-tab="privacy">
|
<section class="help-panel" data-tab="privacy">
|
||||||
<h3>Privacy and where things are saved</h3>
|
<h3>Privacy and where things are saved</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1999,11 +1890,7 @@
|
|||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
your role, theme, colors, card width and sounds, in
|
your role, theme, colors, card width and sounds, in
|
||||||
<code>looks.json</code>;
|
<code>looks.json</code>.
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
your Subagents switch for each project and skill, in
|
|
||||||
<code>subagents.json</code>.
|
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
<p>
|
<p>
|
||||||
@@ -2078,16 +1965,6 @@
|
|||||||
</div>
|
</div>
|
||||||
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<fieldset class="modal-ranges looks-cleanup">
|
|
||||||
<legend>Cleanup</legend>
|
|
||||||
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
|
|
||||||
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
|
|
||||||
<div class="models-actions">
|
|
||||||
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
|
|
||||||
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
|
|
||||||
<span class="help" id="cleanup-status" role="status"></span>
|
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset class="modal-ranges looks-models">
|
<fieldset class="modal-ranges looks-models">
|
||||||
<legend>Models</legend>
|
<legend>Models</legend>
|
||||||
<div class="models-tabs" role="group" aria-label="Which agent">
|
<div class="models-tabs" role="group" aria-label="Which agent">
|
||||||
@@ -2117,46 +1994,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
<!-- Subagents: the switch for this skill, filled from the frame's
|
|
||||||
`subagents` by app.js and saved through POST /subagents. It borrows
|
|
||||||
the User Preferences dialog's classes, so it needs no dialog styles of
|
|
||||||
its own, only a themed number box. -->
|
|
||||||
<dialog class="modal looks subagents" id="subagents-modal" aria-labelledby="subagents-title">
|
|
||||||
<h2 id="subagents-title">Subagents</h2>
|
|
||||||
<p class="modal-blurb">
|
|
||||||
Let Plan2Code hand independent work to helpers in this skill. Saved for this
|
|
||||||
project and this skill.
|
|
||||||
</p>
|
|
||||||
<fieldset class="modal-ranges looks-row">
|
|
||||||
<legend>Helpers</legend>
|
|
||||||
<label><input type="radio" name="subagents-on" value="on" /> <span>Use helpers</span></label>
|
|
||||||
<label><input type="radio" name="subagents-on" value="off" checked /> <span>Work alone</span></label>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset class="modal-ranges">
|
|
||||||
<legend>Instruction</legend>
|
|
||||||
<textarea id="subagents-instruction" rows="4" maxlength="2000" aria-label="Instruction"></textarea>
|
|
||||||
<div class="models-actions">
|
|
||||||
<button type="button" class="btn small ghost" id="subagents-default">Reset to default</button>
|
|
||||||
<span class="help">Passed to the agent as written, at its next check-in.</span>
|
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset class="modal-ranges">
|
|
||||||
<legend>At most</legend>
|
|
||||||
<label>
|
|
||||||
<input type="number" id="subagents-max" min="1" max="20" step="1" aria-label="At most this many helpers at once" />
|
|
||||||
<span>helpers at once</span>
|
|
||||||
</label>
|
|
||||||
<p class="help">Advisory: your agent's own limit still applies.</p>
|
|
||||||
</fieldset>
|
|
||||||
<p class="help" id="subagents-checkin"></p>
|
|
||||||
<p class="help" id="subagents-research" hidden></p>
|
|
||||||
<p class="help" id="subagents-status" role="status"></p>
|
|
||||||
<div class="modal-actions">
|
|
||||||
<button type="button" class="btn ghost" id="subagents-cancel">Cancel</button>
|
|
||||||
<button type="button" class="btn primary" id="subagents-save">Save</button>
|
|
||||||
</div>
|
|
||||||
</dialog>
|
|
||||||
|
|
||||||
<!-- The Workspace: the folder this session started in plus any added as
|
<!-- The Workspace: the folder this session started in plus any added as
|
||||||
context. The list is drawn by app.js from the frame's `workspace`;
|
context. The list is drawn by app.js from the frame's `workspace`;
|
||||||
every change goes through the server's /workspace routes. -->
|
every change goes through the server's /workspace routes. -->
|
||||||
@@ -2166,7 +2003,6 @@
|
|||||||
The folders the agent uses as context this session. It reads the extra ones for
|
The folders the agent uses as context this session. It reads the extra ones for
|
||||||
reference and only changes them if you ask.
|
reference and only changes them if you ask.
|
||||||
</p>
|
</p>
|
||||||
<p class="workspace-scope" id="workspace-scope"></p>
|
|
||||||
<ul class="workspace-list" id="workspace-list"></ul>
|
<ul class="workspace-list" id="workspace-list"></ul>
|
||||||
<div class="workspace-add">
|
<div class="workspace-add">
|
||||||
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
|
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
|
||||||
@@ -2326,24 +2162,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
|
|
||||||
the copy row are filled by app.js; the update itself runs in a
|
|
||||||
terminal, never from this page. -->
|
|
||||||
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
|
|
||||||
<h2 id="update-title">A new Plan2Code is available</h2>
|
|
||||||
<p class="modal-blurb" id="update-versions"></p>
|
|
||||||
<ol class="update-steps">
|
|
||||||
<li>
|
|
||||||
Run this in your terminal (not in this page or your agent):
|
|
||||||
<div class="update-command" id="update-command"></div>
|
|
||||||
</li>
|
|
||||||
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
|
|
||||||
</ol>
|
|
||||||
<div class="modal-actions">
|
|
||||||
<button type="button" class="btn primary" id="update-done">Close</button>
|
|
||||||
</div>
|
|
||||||
</dialog>
|
|
||||||
|
|
||||||
<footer class="footer">
|
<footer class="footer">
|
||||||
<div class="footer-summary" id="footer-summary" aria-live="polite">
|
<div class="footer-summary" id="footer-summary" aria-live="polite">
|
||||||
Nothing to send yet.
|
Nothing to send yet.
|
||||||
|
|||||||
@@ -5,10 +5,7 @@
|
|||||||
// popover; this file owns the rules. No DOM access at module scope and no
|
// popover; this file owns the rules. No DOM access at module scope and no
|
||||||
// imports: the page and `node --test` both import this file.
|
// imports: the page and `node --test` both import this file.
|
||||||
|
|
||||||
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
|
const NAME_CHAR = /[a-z0-9-]/;
|
||||||
// by the workspace rules, and a query typed with a capital otherwise matches
|
|
||||||
// nothing and opens no suggestions at all.
|
|
||||||
const NAME_CHAR = /[a-z0-9-]/i;
|
|
||||||
const MAX_MATCHES = 6;
|
const MAX_MATCHES = 6;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -26,13 +23,11 @@ export function mentionAt(text, caret) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Names starting with the query first, then names containing it, in the
|
// Names starting with the query first, then names containing it, in the
|
||||||
// order given, at most six. Case-folded: folder names are lowercase by rule,
|
// order given, at most six.
|
||||||
// and "@Repo" should still find @repo rather than claim nothing matches.
|
|
||||||
export function matchNames(names, query) {
|
export function matchNames(names, query) {
|
||||||
const q = String(query || "").toLowerCase();
|
const q = String(query || "");
|
||||||
const fold = (n) => String(n).toLowerCase();
|
const prefix = names.filter((n) => n.startsWith(q));
|
||||||
const prefix = names.filter((n) => fold(n).startsWith(q));
|
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
|
||||||
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
|
|
||||||
return [...prefix, ...inside].slice(0, MAX_MATCHES);
|
return [...prefix, ...inside].slice(0, MAX_MATCHES);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -53,55 +53,16 @@ export const TASK_EVENTS = Object.freeze(new Set(Object.keys(TASK_BONUS)));
|
|||||||
// The most tasks one run may report: past this it is a typo, not a phase.
|
// The most tasks one run may report: past this it is a typo, not a phase.
|
||||||
export const MAX_TASKS = 999;
|
export const MAX_TASKS = 999;
|
||||||
|
|
||||||
// A build scores while it runs, not only once it is approved: console.mjs
|
|
||||||
// writes a `progress` ledger entry whenever a build's `headline.cleared`
|
|
||||||
// rises, and the build's row scores those tasks at TASKS_PER_POINT with no
|
|
||||||
// bonus. The phase's `run` then takes the row over with its final score, so
|
|
||||||
// the total only ever climbs. Workflows whose headline counts tasks:
|
|
||||||
export const PROGRESS_WORKFLOWS = Object.freeze(new Set(["implement", "implement-review"]));
|
|
||||||
|
|
||||||
// Implement + Review reviews every phase as a stage of the build. A `review`
|
|
||||||
// run inside it is that stage, so it scores the phase's TASK_BONUS when it
|
|
||||||
// starts, and the phase's own run leaves the bonus out after it.
|
|
||||||
const BUILT_IN_REVIEW = Object.freeze({ "implement-review": "implement-review-phase" });
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The ledger entry a build's progress post stands for, or null when it adds
|
|
||||||
* nothing: not a task-counting workflow, no whole `cleared`, or no more tasks
|
|
||||||
* than this build already has. `seg` is how many phases this skill run has
|
|
||||||
* finished, so a second phase in the same run starts its own count, but only
|
|
||||||
* once its headline is back at 0: until then a `cleared` is the finished
|
|
||||||
* phase's, posted again, and opening a build on it would count it twice.
|
|
||||||
*/
|
|
||||||
export function progressEntry(entries, launch, workflow, cleared) {
|
|
||||||
if (!PROGRESS_WORKFLOWS.has(workflow)) return null;
|
|
||||||
if (cleared !== 0 && !isTaskCount(cleared)) return null;
|
|
||||||
const list = Array.isArray(entries) ? entries : [];
|
|
||||||
const seg = list.filter((e) => e && e.kind === "run" && TASK_EVENTS.has(e.event) && launchOf(e.id) === launch).length;
|
|
||||||
const build = `${launch}:b${seg}`;
|
|
||||||
const mine = list.filter((e) => e && e.kind === "progress" && e.build === build);
|
|
||||||
const entry = (tasks) => ({ kind: "progress", id: `${build}:${tasks}`, build, workflow, tasks });
|
|
||||||
if (cleared === 0) return seg > 0 && !mine.length ? entry(0) : null;
|
|
||||||
if (seg > 0 && !mine.length) return null;
|
|
||||||
const most = mine.reduce((n, e) => Math.max(n, e.tasks), 0);
|
|
||||||
return cleared > most ? entry(cleared) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A valid `run.tasks`: a whole number from 1 to MAX_TASKS. */
|
/** A valid `run.tasks`: a whole number from 1 to MAX_TASKS. */
|
||||||
export function isTaskCount(tasks) {
|
export function isTaskCount(tasks) {
|
||||||
return Number.isInteger(tasks) && tasks >= 1 && tasks <= MAX_TASKS;
|
return Number.isInteger(tasks) && tasks >= 1 && tasks <= MAX_TASKS;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** What one `run` scores, from its event and (for a built phase) its tasks. */
|
||||||
* What one `run` scores, from its event and (for a built phase) its tasks.
|
export function runPoints(event, tasks) {
|
||||||
* `bonus: false` leaves the review bonus out, for a phase whose review
|
|
||||||
* already scored.
|
|
||||||
*/
|
|
||||||
export function runPoints(event, tasks, { bonus = true } = {}) {
|
|
||||||
if (TASK_EVENTS.has(event) && isTaskCount(tasks)) {
|
if (TASK_EVENTS.has(event) && isTaskCount(tasks)) {
|
||||||
return Math.ceil(tasks / TASKS_PER_POINT) + (bonus ? TASK_BONUS[event] : 0);
|
return Math.ceil(tasks / TASKS_PER_POINT) + TASK_BONUS[event];
|
||||||
}
|
}
|
||||||
if (TASK_EVENTS.has(event) && !bonus) return weightOf(event) - TASK_BONUS[event];
|
|
||||||
return weightOf(event);
|
return weightOf(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,8 +133,6 @@ export function breakdownFrom(entries) {
|
|||||||
const seen = new Set();
|
const seen = new Set();
|
||||||
const rows = [];
|
const rows = [];
|
||||||
const answers = new Map(); // launch id -> { row, count, workflow }
|
const answers = new Map(); // launch id -> { row, count, workflow }
|
||||||
const builds = new Map(); // launch id -> the row of the build in progress
|
|
||||||
const reviewed = new Set(); // launch ids whose built-in review has scored
|
|
||||||
for (const entry of Array.isArray(entries) ? entries : []) {
|
for (const entry of Array.isArray(entries) ? entries : []) {
|
||||||
if (!entry || typeof entry !== "object") continue;
|
if (!entry || typeof entry !== "object") continue;
|
||||||
if (entry.id !== undefined) {
|
if (entry.id !== undefined) {
|
||||||
@@ -191,54 +150,17 @@ export function breakdownFrom(entries) {
|
|||||||
tally.count += 1;
|
tally.count += 1;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (entry.kind === "progress") {
|
|
||||||
if (!isTaskCount(entry.tasks)) continue;
|
|
||||||
const launch = launchOf(entry.id);
|
|
||||||
let row = builds.get(launch);
|
|
||||||
if (!row || row.build !== entry.build) {
|
|
||||||
row = { label: "", points: 0, build: entry.build, tasks: 0 };
|
|
||||||
builds.set(launch, row);
|
|
||||||
rows.push(row);
|
|
||||||
}
|
|
||||||
if (entry.tasks > row.tasks) {
|
|
||||||
row.tasks = entry.tasks;
|
|
||||||
row.points = Math.ceil(entry.tasks / TASKS_PER_POINT);
|
|
||||||
const where = WORKFLOW_NAMES[entry.workflow] || "Build";
|
|
||||||
row.label = `${where}: ${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"} built so far`;
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let points = 0;
|
let points = 0;
|
||||||
let label = "";
|
let label = "";
|
||||||
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) {
|
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) {
|
||||||
points = weightOf(entry.workflow);
|
points = weightOf(entry.workflow);
|
||||||
label = LAUNCH_LABELS[entry.workflow] || entry.workflow;
|
label = LAUNCH_LABELS[entry.workflow] || entry.workflow;
|
||||||
} else if (entry.kind === "run") {
|
} else if (entry.kind === "run") {
|
||||||
const launch = launchOf(entry.id);
|
points = runPoints(entry.event, entry.tasks);
|
||||||
const builtIn = BUILT_IN_REVIEW[entry.workflow];
|
|
||||||
if (entry.event === "review" && builtIn) {
|
|
||||||
// The review stage of Implement + Review: it scores the bonus its
|
|
||||||
// phase would otherwise carry, once per skill run.
|
|
||||||
if (reviewed.has(launch)) continue;
|
|
||||||
reviewed.add(launch);
|
|
||||||
points = TASK_BONUS[builtIn];
|
|
||||||
label = `${WORKFLOW_NAMES[entry.workflow]}: code review run`;
|
|
||||||
} else {
|
|
||||||
const bonus = !(TASK_EVENTS.has(entry.event) && reviewed.has(launch));
|
|
||||||
points = runPoints(entry.event, entry.tasks, { bonus });
|
|
||||||
const unit = unitOf(entry.id);
|
const unit = unitOf(entry.id);
|
||||||
const counted = TASK_EVENTS.has(entry.event) && isTaskCount(entry.tasks);
|
const counted = TASK_EVENTS.has(entry.event) && isTaskCount(entry.tasks);
|
||||||
const size = counted ? ` (${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"})` : "";
|
const size = counted ? ` (${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"})` : "";
|
||||||
label = (RUN_LABELS[entry.event] || entry.event) + (unit && unit !== entry.event ? `: ${unit}` : "") + size;
|
label = (RUN_LABELS[entry.event] || entry.event) + (unit ? `: ${unit}` : "") + size;
|
||||||
}
|
|
||||||
// A finished phase takes over its build's progress row, in place.
|
|
||||||
if (TASK_EVENTS.has(entry.event) && builds.has(launch)) {
|
|
||||||
const row = builds.get(launch);
|
|
||||||
builds.delete(launch);
|
|
||||||
row.label = label;
|
|
||||||
row.points = Math.max(points, row.points);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (points > 0) rows.push({ label, points });
|
if (points > 0) rows.push({ label, points });
|
||||||
}
|
}
|
||||||
@@ -247,7 +169,7 @@ export function breakdownFrom(entries) {
|
|||||||
const where = WORKFLOW_NAMES[workflow] ? ` in ${WORKFLOW_NAMES[workflow]}` : "";
|
const where = WORKFLOW_NAMES[workflow] ? ` in ${WORKFLOW_NAMES[workflow]}` : "";
|
||||||
row.label = `${count} ${count === 1 ? "answer" : "answers"}${where}`;
|
row.label = `${count} ${count === 1 ? "answer" : "answers"}${where}`;
|
||||||
}
|
}
|
||||||
return rows.filter((row) => row.points > 0).map(({ label, points }) => ({ label, points }));
|
return rows.filter((row) => row.points > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The session's points, folded from ledger entries in order. */
|
/** The session's points, folded from ledger entries in order. */
|
||||||
|
|||||||
@@ -1,223 +0,0 @@
|
|||||||
// Plan2Code Web Console - the Subagents switch's opt-in table, wording and checks.
|
|
||||||
//
|
|
||||||
// The source of truth for which workflows offer the switch, the instruction
|
|
||||||
// each one ships with, the fixed frame every "on" block carries, the exact
|
|
||||||
// lines the agent reads at a pickup (blockFor()), and the house rules for the
|
|
||||||
// helpers an agent reports back (checkHelper()). No DOM access at module scope
|
|
||||||
// and no imports: the server, console.mjs, the page and `node --test` all
|
|
||||||
// import this file.
|
|
||||||
|
|
||||||
// The one place a skill opts in (FR-1). Wording is behaviour-level and names
|
|
||||||
// no harness tool, so any agent can follow it or harmlessly ignore it.
|
|
||||||
export const SUBAGENT_WORKFLOWS = Object.freeze({
|
|
||||||
implement: Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
|
||||||
}),
|
|
||||||
"implement-review": Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
|
||||||
}),
|
|
||||||
"quick-task": Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
|
||||||
}),
|
|
||||||
review: Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Split the review across helpers by area (for example correctness, tests and security), then merge and de-duplicate their findings yourself before you report.",
|
|
||||||
}),
|
|
||||||
pathfinder: Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
export function offered(workflow) {
|
|
||||||
return typeof workflow === "string" && Object.prototype.hasOwnProperty.call(SUBAGENT_WORKFLOWS, workflow);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const MAX_MIN = 1;
|
|
||||||
export const MAX_MAX = 20;
|
|
||||||
export const DEFAULT_MAX = 3;
|
|
||||||
export const INSTRUCTION_MAX_CHARS = 2000;
|
|
||||||
export const HELPER_TITLE_MAX = 80;
|
|
||||||
export const HELPER_ASK_MAX = 400;
|
|
||||||
export const HELPER_RESULT_MAX = 200;
|
|
||||||
export const HELPER_STATES = Object.freeze(["running", "done", "failed"]);
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------- settings */
|
|
||||||
|
|
||||||
export function defaultInstruction(workflow) {
|
|
||||||
return offered(workflow) ? SUBAGENT_WORKFLOWS[workflow].instruction : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// The person's own text when they wrote some, else the workflow's default.
|
|
||||||
export function effectiveInstruction(setting) {
|
|
||||||
const own = setting && typeof setting.instruction === "string" ? setting.instruction.trim() : "";
|
|
||||||
return own || defaultInstruction(setting && setting.workflow);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function defaultSetting(workflow) {
|
|
||||||
return { workflow, on: false, instruction: null, max: DEFAULT_MAX };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* `{ on, instruction, max }` from untrusted input, or `{ error }` naming the
|
|
||||||
* field that failed: "bad" (wrong type), "too-long" (instruction) or "max".
|
|
||||||
* Returns an error object rather than throwing, so the route and the store
|
|
||||||
* reader share one validator. An empty instruction means the default: null.
|
|
||||||
*/
|
|
||||||
export function cleanSetting(input) {
|
|
||||||
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "bad" };
|
|
||||||
if (typeof input.on !== "boolean") return { error: "bad" };
|
|
||||||
let instruction = null;
|
|
||||||
if (input.instruction !== null && input.instruction !== undefined) {
|
|
||||||
if (typeof input.instruction !== "string") return { error: "bad" };
|
|
||||||
const trimmed = input.instruction.trim();
|
|
||||||
if (trimmed.length > INSTRUCTION_MAX_CHARS) return { error: "too-long" };
|
|
||||||
instruction = trimmed || null;
|
|
||||||
}
|
|
||||||
const max = input.max;
|
|
||||||
if (!Number.isInteger(max) || max < MAX_MIN || max > MAX_MAX) return { error: "max" };
|
|
||||||
return { on: input.on, instruction, max };
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------ the lines */
|
|
||||||
|
|
||||||
// The non-editable part of every "on" block (FR-8).
|
|
||||||
export const FRAME_LINES = Object.freeze([
|
|
||||||
"Hand independent work to helpers if your tools allow it; otherwise carry on alone.",
|
|
||||||
"Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.",
|
|
||||||
'With no way to start helpers, report one "working alone" entry for this skill run instead.',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
|
|
||||||
|
|
||||||
// Only the first line of a block starts at column 0, so no line inside it can
|
|
||||||
// be read as an entry of its own (NFR-5).
|
|
||||||
export function onLines({ revision, replaces, max, instruction }) {
|
|
||||||
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
|
|
||||||
const own = String(instruction || "")
|
|
||||||
.split("\n")
|
|
||||||
.map((line) => line.trimEnd())
|
|
||||||
.filter((line) => line.trim());
|
|
||||||
return [
|
|
||||||
`Subagents: on (${label}) — a console setting, not typed by the person.`,
|
|
||||||
...[...FRAME_LINES, ...own, `At most ${max} helpers at once.`].map((line) => " " + line),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function offLine(revision) {
|
|
||||||
return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What the agent is owed at a pickup, given the session setting and the
|
|
||||||
* cursor of what it was last told: `null`, or `{ field, lines, cursor }`
|
|
||||||
* where `cursor` is what to write once the lines are printed. Never says
|
|
||||||
* "off" to an agent that was not told "on" (FR-6). Pure: no clock, no I/O.
|
|
||||||
*/
|
|
||||||
export function blockFor(setting, told) {
|
|
||||||
const last = told || { revision: 0, state: "none" };
|
|
||||||
if (!setting || !offered(setting.workflow) || !(setting.revision > last.revision)) return null;
|
|
||||||
const { revision, max } = setting;
|
|
||||||
const instruction = effectiveInstruction(setting);
|
|
||||||
if (setting.on) {
|
|
||||||
const replaces = last.state === "on" ? last.revision : undefined;
|
|
||||||
return {
|
|
||||||
field: { state: "on", revision, max, instruction },
|
|
||||||
lines: onLines({ revision, replaces, max, instruction }),
|
|
||||||
cursor: { revision, state: "on" },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (last.state !== "on") return null;
|
|
||||||
return {
|
|
||||||
field: { state: "off", revision, max, instruction },
|
|
||||||
lines: [offLine(revision)],
|
|
||||||
cursor: { revision, state: "off" },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------ helpers */
|
|
||||||
|
|
||||||
const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
||||||
const nonEmpty = (v) => typeof v === "string" && v.trim() !== "";
|
|
||||||
|
|
||||||
// The problems with one reported helper, [] when it is fine.
|
|
||||||
export function checkHelper(entry) {
|
|
||||||
if (!isPlainObject(entry)) return ["helper: each entry must be an object"];
|
|
||||||
if (!nonEmpty(entry.id)) return ["helper: id must be a non-empty string"];
|
|
||||||
const who = `helper "${entry.id}"`;
|
|
||||||
if (entry.alone === true) return entry.id === "alone" ? [] : [`${who}: the working-alone entry must have id "alone"`];
|
|
||||||
const problems = [];
|
|
||||||
if (!nonEmpty(entry.title)) problems.push(`${who}: title must be a non-empty string`);
|
|
||||||
else if (entry.title.length > HELPER_TITLE_MAX) problems.push(`${who}: title must be at most ${HELPER_TITLE_MAX} characters`);
|
|
||||||
if (!nonEmpty(entry.ask)) problems.push(`${who}: ask must be a non-empty string`);
|
|
||||||
else if (entry.ask.length > HELPER_ASK_MAX) problems.push(`${who}: ask must be at most ${HELPER_ASK_MAX} characters`);
|
|
||||||
if (!HELPER_STATES.includes(entry.state)) problems.push(`${who}: state must be running, done or failed`);
|
|
||||||
if (entry.result !== undefined) {
|
|
||||||
if (typeof entry.result !== "string") problems.push(`${who}: result must be a string`);
|
|
||||||
else if (entry.result.length > HELPER_RESULT_MAX) problems.push(`${who}: result must be at most ${HELPER_RESULT_MAX} characters`);
|
|
||||||
}
|
|
||||||
return problems;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The problems with a whole merged list.
|
|
||||||
export function checkHelpers(list) {
|
|
||||||
if (!Array.isArray(list)) return ["helpers must be an array"];
|
|
||||||
const problems = [];
|
|
||||||
const seen = new Set();
|
|
||||||
let alone = 0;
|
|
||||||
for (const entry of list) {
|
|
||||||
if (isPlainObject(entry) && nonEmpty(entry.id)) {
|
|
||||||
if (seen.has(entry.id)) problems.push(`helper "${entry.id}": duplicate id`);
|
|
||||||
seen.add(entry.id);
|
|
||||||
if (entry.alone === true && ++alone === 2) problems.push(`helper "${entry.id}": only one working-alone entry is allowed`);
|
|
||||||
}
|
|
||||||
problems.push(...checkHelper(entry));
|
|
||||||
}
|
|
||||||
return problems;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------ the page */
|
|
||||||
|
|
||||||
// The page's rules for the button, the modal and the tab, kept here so they
|
|
||||||
// are tested without a browser. `frame` is the state frame's `subagents`
|
|
||||||
// block; app.js only renders what these say.
|
|
||||||
|
|
||||||
export const CHECKIN_LINE = "Helpers report through Plan2Code, so their progress shows here at its check-ins, not live.";
|
|
||||||
|
|
||||||
const STATE_LABELS = Object.freeze({ running: "Running", done: "Done", failed: "Failed" });
|
|
||||||
|
|
||||||
// The switch shows only where the skill opts in AND the agent's console copy
|
|
||||||
// said it can deliver it (FR-3).
|
|
||||||
export function showSwitch(frame) {
|
|
||||||
return Boolean(frame && frame.offered && frame.supported);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The button's tooltip and accessible name (FR-2).
|
|
||||||
export function switchLabel(frame) {
|
|
||||||
return frame && frame.on ? "Subagents: on" : "Subagents: off";
|
|
||||||
}
|
|
||||||
|
|
||||||
// What the Subagents tab draws: the working-alone note, or one row per helper
|
|
||||||
// in the order the agent reported them. A result shows once the helper ended.
|
|
||||||
export function helperRows(helpers) {
|
|
||||||
const list = Array.isArray(helpers) ? helpers.filter(isPlainObject) : [];
|
|
||||||
if (list.some((h) => h.alone === true)) return { alone: true, rows: [] };
|
|
||||||
const rows = list.map(({ id, title, ask, state, result }) => ({
|
|
||||||
id,
|
|
||||||
title,
|
|
||||||
ask,
|
|
||||||
state,
|
|
||||||
stateLabel: STATE_LABELS[state] || STATE_LABELS.running,
|
|
||||||
...((state === "done" || state === "failed") && typeof result === "string" && result ? { result } : {}),
|
|
||||||
}));
|
|
||||||
return { alone: false, rows };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Never an empty tab. Independent of on / off, so Pathfinder's research
|
|
||||||
// helpers show even with the switch off (FR-11, FR-12).
|
|
||||||
export function showTab(frame, helpers) {
|
|
||||||
return showSwitch(frame) && Array.isArray(helpers) && helpers.length > 0;
|
|
||||||
}
|
|
||||||
@@ -25,21 +25,17 @@ import {
|
|||||||
LOOKS_FILE,
|
LOOKS_FILE,
|
||||||
PUBLIC_DIR,
|
PUBLIC_DIR,
|
||||||
SHIPPED_MODELS_FILE,
|
SHIPPED_MODELS_FILE,
|
||||||
SUBAGENTS_SETTING_FILE,
|
|
||||||
UPDATE_CHECK_FILE,
|
|
||||||
USER_MODELS_FILE,
|
USER_MODELS_FILE,
|
||||||
WORKSPACE_FILE,
|
WORKSPACE_FILE,
|
||||||
appendChat,
|
appendChat,
|
||||||
appendEvent,
|
appendEvent,
|
||||||
chatForFrame,
|
chatForFrame,
|
||||||
checkDocument,
|
checkDocument,
|
||||||
cleanupFindings,
|
|
||||||
currentConversation,
|
currentConversation,
|
||||||
ensureDir,
|
ensureDir,
|
||||||
fileStamp,
|
fileStamp,
|
||||||
handleFile,
|
handleFile,
|
||||||
initialWorkspace,
|
initialWorkspace,
|
||||||
latestOpenCaps,
|
|
||||||
nowIso,
|
nowIso,
|
||||||
parseArgs,
|
parseArgs,
|
||||||
pendingChatCount,
|
pendingChatCount,
|
||||||
@@ -48,28 +44,18 @@ import {
|
|||||||
readJson,
|
readJson,
|
||||||
readLedger,
|
readLedger,
|
||||||
readOverview,
|
readOverview,
|
||||||
readSubagentSetting,
|
|
||||||
readWorkspace,
|
readWorkspace,
|
||||||
rememberWorkspace,
|
|
||||||
rememberedWorkspace,
|
|
||||||
removeCleanup,
|
|
||||||
remoteWarning,
|
remoteWarning,
|
||||||
saveSubagentStoreEntry,
|
|
||||||
specKey,
|
|
||||||
subagentStoreEntry,
|
|
||||||
typedCount,
|
typedCount,
|
||||||
withStateLock,
|
withStateLock,
|
||||||
writeJsonAtomic,
|
writeJsonAtomic,
|
||||||
writeSubagentSetting,
|
|
||||||
writeWorkspace,
|
writeWorkspace,
|
||||||
} from "./lib.mjs";
|
} from "./lib.mjs";
|
||||||
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
|
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
|
||||||
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
|
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
|
||||||
import { meterView } from "./public/meter.js";
|
import { meterView } from "./public/meter.js";
|
||||||
import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
|
||||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||||
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
||||||
import { checkForUpdate } from "./update-check.mjs";
|
|
||||||
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
|
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
|
||||||
|
|
||||||
const args = parseArgs(process.argv.slice(2));
|
const args = parseArgs(process.argv.slice(2));
|
||||||
@@ -219,7 +205,6 @@ const SERVABLE = new Set([
|
|||||||
"starters.js",
|
"starters.js",
|
||||||
"workspace.js",
|
"workspace.js",
|
||||||
"meter.js",
|
"meter.js",
|
||||||
"subagents.js",
|
|
||||||
"mentions.js",
|
"mentions.js",
|
||||||
"favicon.js",
|
"favicon.js",
|
||||||
"start-stop.mp3",
|
"start-stop.mp3",
|
||||||
@@ -341,9 +326,7 @@ function workspaceNow() {
|
|||||||
return ws;
|
return ws;
|
||||||
}
|
}
|
||||||
const root = sessionWorktree();
|
const root = sessionWorktree();
|
||||||
const scope = specKey(stateNow?.specDir);
|
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
|
||||||
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
|
|
||||||
const fresh = { ...initialWorkspace(root || PROJECT, remembered), scope, remote: remoteWarning().remote || "" };
|
|
||||||
// There but unreadable for now (a scanner's lock): never written over, and
|
// There but unreadable for now (a scanner's lock): never written over, and
|
||||||
// never cached, so the next call reads it again.
|
// never cached, so the next call reads it again.
|
||||||
if (stamp) return workspaceSeen.ws || fresh;
|
if (stamp) return workspaceSeen.ws || fresh;
|
||||||
@@ -364,87 +347,13 @@ function saveWorkspace(ws) {
|
|||||||
|
|
||||||
// One change: a new version, an entry in the change log the agent is handed,
|
// One change: a new version, an entry in the change log the agent is handed,
|
||||||
// the file, and every open page.
|
// the file, and every open page.
|
||||||
function bumpWorkspace(ws, change, { remember = true } = {}) {
|
function bumpWorkspace(ws, change) {
|
||||||
ws.version = (ws.version || 0) + 1;
|
ws.version = (ws.version || 0) + 1;
|
||||||
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
|
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
|
||||||
saveWorkspace(ws);
|
saveWorkspace(ws);
|
||||||
// Remembered for the next console session too. A folder gone missing or
|
|
||||||
// found again is not a change of mind, so it is not saved.
|
|
||||||
if (remember) rememberNow(ws);
|
|
||||||
pushState();
|
pushState();
|
||||||
}
|
}
|
||||||
|
|
||||||
function rememberNow(ws) {
|
|
||||||
const root = sessionWorktree();
|
|
||||||
if (!root) return;
|
|
||||||
try {
|
|
||||||
rememberWorkspace(root, ws.scope || "", ws);
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Point the workspace at another spec ("" for the project's own list) and
|
|
||||||
* swap in what was remembered there, logging each difference as a change so
|
|
||||||
* the agent's cursor stays truthful. A spec with nothing saved starts from
|
|
||||||
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
|
|
||||||
* list it has and saves it as the spec's (`seed: "current"`, a spec created
|
|
||||||
* mid-run). Folders keep their ids when their path stays.
|
|
||||||
*/
|
|
||||||
function setScope(ws, spec, seed = "project") {
|
|
||||||
const root = sessionWorktree();
|
|
||||||
const next = specKey(spec);
|
|
||||||
if (!root || (ws.scope || "") === next) return false;
|
|
||||||
const found = rememberedWorkspace(root, next);
|
|
||||||
ws.scope = next;
|
|
||||||
if (next && found.from !== "spec" && seed === "current") {
|
|
||||||
saveWorkspace(ws);
|
|
||||||
rememberNow(ws);
|
|
||||||
pushState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
const want = initialWorkspace(root, found.entry).folders;
|
|
||||||
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
|
|
||||||
const kept = new Set();
|
|
||||||
const folders = [];
|
|
||||||
const changes = [];
|
|
||||||
for (const w of want) {
|
|
||||||
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
|
|
||||||
if (!have) {
|
|
||||||
folders.push({ ...w, id: "pending" });
|
|
||||||
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
kept.add(have);
|
|
||||||
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
|
|
||||||
if ((have.description || "") !== (w.description || "")) {
|
|
||||||
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
|
|
||||||
}
|
|
||||||
folders.push({ ...have, name: w.name, description: w.description || "" });
|
|
||||||
}
|
|
||||||
for (const f of ws.folders) {
|
|
||||||
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
|
|
||||||
}
|
|
||||||
ws.folders = folders.filter((f) => f.id !== "pending");
|
|
||||||
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
|
|
||||||
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
|
|
||||||
if (!changes.length) {
|
|
||||||
saveWorkspace(ws);
|
|
||||||
pushState();
|
|
||||||
}
|
|
||||||
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
|
|
||||||
checkFolders(ws);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
|
|
||||||
// learns its spec late) takes the workspace with it.
|
|
||||||
function followSpecDir(state) {
|
|
||||||
const spec = specKey(state && state.specDir);
|
|
||||||
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
|
|
||||||
const ws = workspaceNow();
|
|
||||||
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
|
|
||||||
}
|
|
||||||
|
|
||||||
function isFolder(p) {
|
function isFolder(p) {
|
||||||
try {
|
try {
|
||||||
return fs.statSync(p).isDirectory();
|
return fs.statSync(p).isDirectory();
|
||||||
@@ -461,10 +370,10 @@ function checkFolders(ws) {
|
|||||||
const marked = ws.missing.includes(f.id);
|
const marked = ws.missing.includes(f.id);
|
||||||
if (!there && !marked) {
|
if (!there && !marked) {
|
||||||
ws.missing = [...ws.missing, f.id];
|
ws.missing = [...ws.missing, f.id];
|
||||||
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
|
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path });
|
||||||
} else if (there && marked) {
|
} else if (there && marked) {
|
||||||
ws.missing = ws.missing.filter((id) => id !== f.id);
|
ws.missing = ws.missing.filter((id) => id !== f.id);
|
||||||
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
|
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -493,8 +402,8 @@ function folderIssues(entries) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function workspaceView() {
|
function workspaceView() {
|
||||||
const { folders, missing, remote, scope } = workspaceNow();
|
const { folders, missing, remote } = workspaceNow();
|
||||||
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ledgerEntries()) };
|
return { folders, missing: missing || [], remote: remote || "", issues: folderIssues(ledgerEntries()) };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Whether child sits strictly under parent.
|
// Whether child sits strictly under parent.
|
||||||
@@ -583,7 +492,6 @@ function bootWorkspace() {
|
|||||||
saveWorkspace(ws);
|
saveWorkspace(ws);
|
||||||
}
|
}
|
||||||
checkFolders(ws);
|
checkFolders(ws);
|
||||||
followSpecDir(stateNow);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -609,48 +517,6 @@ function ensureConversation(state) {
|
|||||||
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------ subagents */
|
|
||||||
|
|
||||||
// subagents-setting.json has one writer, this server, and the agent hears of
|
|
||||||
// it only through what console.mjs reads there; events.ndjson's latest `open`
|
|
||||||
// says whether the agent's console copy can carry it. Both re-read only when
|
|
||||||
// their file has moved.
|
|
||||||
const SUBAGENTS_SETTING_PATH = path.join(DIR, SUBAGENTS_SETTING_FILE);
|
|
||||||
const EVENTS_PATH = path.join(DIR, "events.ndjson");
|
|
||||||
|
|
||||||
let subagentSettingSeen = { stamp: null, setting: null };
|
|
||||||
function subagentSettingNow() {
|
|
||||||
const stamp = fileStamp(SUBAGENTS_SETTING_PATH);
|
|
||||||
if (stamp !== subagentSettingSeen.stamp) subagentSettingSeen = { stamp, setting: readSubagentSetting(DIR) };
|
|
||||||
return subagentSettingSeen.setting;
|
|
||||||
}
|
|
||||||
|
|
||||||
let capsSeen = { stamp: null, caps: [] };
|
|
||||||
function openCapsNow() {
|
|
||||||
const stamp = fileStamp(EVENTS_PATH);
|
|
||||||
if (stamp !== capsSeen.stamp) capsSeen = { stamp, caps: latestOpenCaps(DIR) };
|
|
||||||
return capsSeen.caps;
|
|
||||||
}
|
|
||||||
|
|
||||||
const sameSetting = (a, b) => a.workflow === b.workflow && a.on === b.on && a.instruction === b.instruction && a.max === b.max;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Turn the per-project store into this session's setting, for the workflow
|
|
||||||
* the session is in now. The only place that happens (FR-7): a session an
|
|
||||||
* older server ran has no setting file, so nothing is ever injected into it.
|
|
||||||
* A record that already matches is left alone, revision and all, so a
|
|
||||||
* restart alone never re-tells the agent anything.
|
|
||||||
*/
|
|
||||||
function syncSubagentSetting(state) {
|
|
||||||
if (!state || typeof state.workflow !== "string") return;
|
|
||||||
const { workflow } = state;
|
|
||||||
const { on, instruction, max } = offered(workflow) ? subagentStoreEntry(sessionWorktree(), workflow) : defaultSetting(workflow);
|
|
||||||
const target = { workflow, on, instruction, max };
|
|
||||||
const current = readSubagentSetting(DIR);
|
|
||||||
if (current && sameSetting(current, target)) return;
|
|
||||||
writeSubagentSetting(DIR, { ...target, revision: (current ? current.revision : 0) + 1 });
|
|
||||||
}
|
|
||||||
|
|
||||||
// What the page needs to draw itself, in the shape of the SSE state frame.
|
// What the page needs to draw itself, in the shape of the SSE state frame.
|
||||||
// `have` names that exact view, for the page to hand back when it opens its
|
// `have` names that exact view, for the page to hand back when it opens its
|
||||||
// stream (see /events).
|
// stream (see /events).
|
||||||
@@ -665,33 +531,19 @@ function stateFrame(state) {
|
|||||||
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
||||||
workspace: workspaceView(),
|
workspace: workspaceView(),
|
||||||
meter: meterView(ledgerEntries()),
|
meter: meterView(ledgerEntries()),
|
||||||
subagents: subagentsView(state),
|
|
||||||
...(updateInfo ? { update: updateInfo } : {}),
|
|
||||||
have: haveKey(),
|
have: haveKey(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// The page shows the switch only when `offered && supported` (FR-3); the
|
|
||||||
// frame says both and leaves combining them to the page. `instruction: null`
|
|
||||||
// is the shipped default, which the page reads from subagents.js itself.
|
|
||||||
function subagentsView(state) {
|
|
||||||
const workflow = state && state.workflow;
|
|
||||||
const { on, instruction, max, revision } = subagentSettingNow() || { ...defaultSetting(workflow), revision: 0 };
|
|
||||||
return { offered: offered(workflow), supported: openCapsNow().includes("subagents"), on, instruction, max, revision };
|
|
||||||
}
|
|
||||||
|
|
||||||
function haveKey() {
|
function haveKey() {
|
||||||
const { pending, stop } = resultFlags();
|
const { pending, stop } = resultFlags();
|
||||||
chatEntries();
|
chatEntries();
|
||||||
chatPickedUp();
|
chatPickedUp();
|
||||||
workspaceNow();
|
workspaceNow();
|
||||||
ledgerEntries();
|
ledgerEntries();
|
||||||
subagentSettingNow();
|
|
||||||
openCapsNow();
|
|
||||||
return (
|
return (
|
||||||
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
|
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
|
||||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
|
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
|
||||||
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -716,12 +568,6 @@ function recordSubmitted(state, actions) {
|
|||||||
if (action.type === "comment") {
|
if (action.type === "comment") {
|
||||||
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
|
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
|
||||||
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
|
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
|
||||||
// The person's side of the Notes thread. Left to the agent it was never
|
|
||||||
// written, so a question asked in a note vanished once it was picked up
|
|
||||||
// and the reply under it answered nothing on the page.
|
|
||||||
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
|
|
||||||
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
|
|
||||||
}
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const { i, type, ...rest } = action;
|
const { i, type, ...rest } = action;
|
||||||
@@ -1007,38 +853,6 @@ function pushState() {
|
|||||||
if (stateNow) broadcast("state", stateFrame(stateNow));
|
if (stateNow) broadcast("state", stateFrame(stateNow));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------- update check */
|
|
||||||
|
|
||||||
// The version this console was installed as: install.js writes version.json
|
|
||||||
// beside console.mjs; a dev checkout falls back to the repo root's.
|
|
||||||
function installedVersion() {
|
|
||||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
|
||||||
const version = readJson(file, {}).version;
|
|
||||||
if (typeof version === "string" && version) return version;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filled in once the boot-time check answers; until then, and whenever it
|
|
||||||
// fails, the frame carries no `update` and the page shows no banner.
|
|
||||||
let updateInfo = null;
|
|
||||||
let updateLatest = null;
|
|
||||||
|
|
||||||
// Started at boot and never awaited: git may take up to its 10 s limit, and
|
|
||||||
// nothing the person sees waits on it. The catch is not optional: a throw in
|
|
||||||
// pushState() would otherwise be an unhandled rejection, which ends the server.
|
|
||||||
function startUpdateCheck() {
|
|
||||||
const installed = installedVersion();
|
|
||||||
if (!installed) return;
|
|
||||||
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
|
|
||||||
.then((result) => {
|
|
||||||
updateLatest = result?.latest ?? null;
|
|
||||||
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
|
|
||||||
if (updateInfo) pushState();
|
|
||||||
})
|
|
||||||
.catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
let agentSeenAt = Date.now();
|
let agentSeenAt = Date.now();
|
||||||
function agentLastSeen() {
|
function agentLastSeen() {
|
||||||
return new Date(agentSeenAt).toISOString();
|
return new Date(agentSeenAt).toISOString();
|
||||||
@@ -1145,8 +959,10 @@ const server = http.createServer((req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (pathname === "/version" && req.method === "GET") {
|
if (pathname === "/version" && req.method === "GET") {
|
||||||
const version = installedVersion();
|
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||||
if (version) return json(res, 200, { version, latest: updateLatest });
|
const version = readJson(file, {}).version;
|
||||||
|
if (typeof version === "string" && version) return json(res, 200, { version });
|
||||||
|
}
|
||||||
return json(res, 404, { error: "no version" });
|
return json(res, 404, { error: "no version" });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1194,7 +1010,7 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/draft" && req.method === "POST") {
|
if (pathname === "/draft" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (err, body) => {
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||||
// Debounced client-side; this is just the durable mirror. Twenty minutes
|
// Debounced client-side; this is just the durable mirror. Twenty minutes
|
||||||
// of someone's structured answers must not die with a closed tab.
|
// of someone's structured answers must not die with a closed tab.
|
||||||
try {
|
try {
|
||||||
@@ -1219,7 +1035,7 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/looks" && req.method === "POST") {
|
if (pathname === "/looks" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (err, body) => {
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||||
// `set` carries only the keys one tab changed, merged onto what is on
|
// `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.
|
// disk, so a tab holding stale settings cannot undo another tab's change.
|
||||||
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
|
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
|
||||||
@@ -1235,39 +1051,6 @@ const server = http.createServer((req, res) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Subagents switch for the session's workflow. Saved per project folder
|
|
||||||
// for the next session, and applied to this one with a bumped revision, which
|
|
||||||
// is what console.mjs hands the agent at its next pickup. Never blocked by,
|
|
||||||
// and never blocking, a card send.
|
|
||||||
if (pathname === "/subagents" && req.method === "POST") {
|
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
|
||||||
return readBody(req, (err, body) => {
|
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
|
||||||
const state = readState();
|
|
||||||
if (!state || !offered(state.workflow)) return json(res, 400, { error: "not-offered" });
|
|
||||||
const clean = cleanSetting(body);
|
|
||||||
if (clean.error) return json(res, 400, { error: clean.error });
|
|
||||||
const { on, instruction, max } = clean;
|
|
||||||
const current = readSubagentSetting(DIR);
|
|
||||||
const next = { workflow: state.workflow, on, instruction, max };
|
|
||||||
// The store is per project, so another session may have moved it since
|
|
||||||
// this one synced: it always takes the person's latest pick. Only a
|
|
||||||
// real change to this session's setting bumps what the agent hears.
|
|
||||||
const unchanged = Boolean(current && sameSetting(current, next));
|
|
||||||
try {
|
|
||||||
saveSubagentStoreEntry(sessionWorktree(), state.workflow, { on, instruction, max });
|
|
||||||
if (!unchanged) writeSubagentSetting(DIR, { ...next, revision: (current ? current.revision : 0) + 1 });
|
|
||||||
} catch (e) {
|
|
||||||
return json(res, 500, { error: String(e.message) });
|
|
||||||
}
|
|
||||||
if (unchanged) return json(res, 200, { ok: true, setting: current });
|
|
||||||
const setting = readSubagentSetting(DIR);
|
|
||||||
appendEvent(DIR, { type: "subagents", on, revision: setting.revision });
|
|
||||||
pushState();
|
|
||||||
return json(res, 200, { ok: true, setting });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// The launcher's model menu: what ships (read-only here) and what the user added.
|
// The launcher's model menu: what ships (read-only here) and what the user added.
|
||||||
if (pathname === "/models" && req.method === "GET") {
|
if (pathname === "/models" && req.method === "GET") {
|
||||||
const saved = readJson(USER_MODELS_FILE, null) || {};
|
const saved = readJson(USER_MODELS_FILE, null) || {};
|
||||||
@@ -1278,7 +1061,7 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/models" && req.method === "POST") {
|
if (pathname === "/models" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (err, body) => {
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||||
const { models, error } = cleanModels(body && body.models);
|
const { models, error } = cleanModels(body && body.models);
|
||||||
if (error) return json(res, 400, { error });
|
if (error) return json(res, 400, { error });
|
||||||
try {
|
try {
|
||||||
@@ -1291,24 +1074,6 @@ const server = http.createServer((req, res) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
|
|
||||||
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
|
|
||||||
// still finds. Never this session, never a path the page sent.
|
|
||||||
if (pathname === "/cleanup" && req.method === "POST") {
|
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
|
||||||
return readBody(req, (err, body) => {
|
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
|
||||||
if (body && Array.isArray(body.delete)) {
|
|
||||||
return removeCleanup(body.delete, { skipSid: SID })
|
|
||||||
.then((done) => json(res, 200, { ok: true, ...done }))
|
|
||||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
|
||||||
}
|
|
||||||
return cleanupFindings({ skipSid: SID })
|
|
||||||
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
|
|
||||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pathname === "/upload" && req.method === "POST") {
|
if (pathname === "/upload" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
const contentType = String(req.headers["content-type"] || "");
|
const contentType = String(req.headers["content-type"] || "");
|
||||||
@@ -1415,7 +1180,7 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/submit" && req.method === "POST") {
|
if (pathname === "/submit" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (err, body) => {
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||||
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
|
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
|
||||||
return json(res, 400, { error: "actions must be a non-empty array" });
|
return json(res, 400, { error: "actions must be a non-empty array" });
|
||||||
}
|
}
|
||||||
@@ -1496,9 +1261,6 @@ const server = http.createServer((req, res) => {
|
|||||||
try {
|
try {
|
||||||
ensureConversation(written.state);
|
ensureConversation(written.state);
|
||||||
} catch {}
|
} catch {}
|
||||||
try {
|
|
||||||
syncSubagentSetting(written.state);
|
|
||||||
} catch {}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Name the items that went. A page with OTHER answers staged should drop
|
// Name the items that went. A page with OTHER answers staged should drop
|
||||||
@@ -1519,7 +1281,6 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/chat" && req.method === "POST") {
|
if (pathname === "/chat" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (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 (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||||
const state = readState() || {};
|
const state = readState() || {};
|
||||||
const current = currentConversation(chatEntries()).conversation;
|
const current = currentConversation(chatEntries()).conversation;
|
||||||
@@ -1583,7 +1344,6 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/chat/decision" && req.method === "POST") {
|
if (pathname === "/chat/decision" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (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 (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" });
|
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
|
||||||
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
|
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
|
||||||
@@ -1632,7 +1392,6 @@ const server = http.createServer((req, res) => {
|
|||||||
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
|
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (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 (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||||
let answer;
|
let answer;
|
||||||
try {
|
try {
|
||||||
@@ -1644,25 +1403,6 @@ const server = http.createServer((req, res) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Which list the workspace is: a spec's, or the project's (`spec` empty).
|
|
||||||
// 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.
|
|
||||||
if (pathname === "/workspace/scope" && req.method === "POST") {
|
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
|
||||||
return readBody(req, (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 : "";
|
|
||||||
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
|
|
||||||
try {
|
|
||||||
setScope(workspaceNow(), spec, "project");
|
|
||||||
} catch (e) {
|
|
||||||
return json(res, 500, { error: String(e.message) });
|
|
||||||
}
|
|
||||||
return json(res, 200, workspaceView());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only ever returns a path: the page then adds it through /workspace/add.
|
// Only ever returns a path: the page then adds it through /workspace/add.
|
||||||
if (pathname === "/workspace/browse" && req.method === "POST") {
|
if (pathname === "/workspace/browse" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
@@ -1751,19 +1491,15 @@ function readBody(req, cb) {
|
|||||||
let tooBig = false;
|
let tooBig = false;
|
||||||
req.on("data", (c) => {
|
req.on("data", (c) => {
|
||||||
size += c.length;
|
size += c.length;
|
||||||
// Drain past the cap rather than destroy, exactly like readRaw: a
|
|
||||||
// destroyed request emits 'close', never 'end' or 'error', so cb would
|
|
||||||
// never run and the page would see a reset instead of the 413 that names
|
|
||||||
// the problem.
|
|
||||||
if (size > MAX_BODY) {
|
if (size > MAX_BODY) {
|
||||||
tooBig = true;
|
tooBig = true;
|
||||||
chunks.length = 0;
|
req.destroy();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
chunks.push(c);
|
chunks.push(c);
|
||||||
});
|
});
|
||||||
req.on("end", () => {
|
req.on("end", () => {
|
||||||
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
|
if (tooBig) return cb(new Error("too large"));
|
||||||
try {
|
try {
|
||||||
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -1825,12 +1561,6 @@ function checkState() {
|
|||||||
try {
|
try {
|
||||||
ensureConversation(parsed);
|
ensureConversation(parsed);
|
||||||
} catch {}
|
} catch {}
|
||||||
try {
|
|
||||||
syncSubagentSetting(parsed);
|
|
||||||
} catch {}
|
|
||||||
try {
|
|
||||||
followSpecDir(parsed);
|
|
||||||
} catch {}
|
|
||||||
pushState();
|
pushState();
|
||||||
}
|
}
|
||||||
lastStateStamp = stamp;
|
lastStateStamp = stamp;
|
||||||
@@ -2002,13 +1732,7 @@ function onListening(port) {
|
|||||||
try {
|
try {
|
||||||
bootWorkspace();
|
bootWorkspace();
|
||||||
} catch {}
|
} catch {}
|
||||||
try {
|
|
||||||
syncSubagentSetting(readState());
|
|
||||||
} catch {}
|
|
||||||
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
||||||
try {
|
|
||||||
startUpdateCheck();
|
|
||||||
} catch {}
|
|
||||||
try {
|
try {
|
||||||
process.send?.({ type: "listening", port });
|
process.send?.({ type: "listening", port });
|
||||||
} catch {}
|
} catch {}
|
||||||
|
|||||||
@@ -1,138 +0,0 @@
|
|||||||
// Plan2Code Web Console - is a newer Plan2Code release out?
|
|
||||||
//
|
|
||||||
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
|
|
||||||
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
|
|
||||||
// release tag is "latest". The server
|
|
||||||
// starts this at boot and never waits on it; the answer, failures included, is
|
|
||||||
// cached for an hour so a burst of sessions asks GitHub once.
|
|
||||||
//
|
|
||||||
// Nothing here reads, stores or sends a credential: git authenticates itself,
|
|
||||||
// with every prompt turned off so a missing login fails fast instead of
|
|
||||||
// opening a window nobody asked for.
|
|
||||||
//
|
|
||||||
// Node built-ins only.
|
|
||||||
|
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { spawn } from "node:child_process";
|
|
||||||
|
|
||||||
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
|
|
||||||
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
|
||||||
export const CACHE_MS = 60 * 60 * 1000;
|
|
||||||
|
|
||||||
const SEMVER = /^\d+\.\d+\.\d+$/;
|
|
||||||
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
|
|
||||||
|
|
||||||
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
|
|
||||||
export function compareVersions(a, b) {
|
|
||||||
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
|
|
||||||
const x = a.split(".").map(Number);
|
|
||||||
const y = b.split(".").map(Number);
|
|
||||||
for (let i = 0; i < 3; i++) {
|
|
||||||
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
|
|
||||||
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
|
|
||||||
* pre-releases or other tag names are ignored. Null when nothing matches.
|
|
||||||
*/
|
|
||||||
export function latestTag(text) {
|
|
||||||
if (typeof text !== "string") return null;
|
|
||||||
let best = null;
|
|
||||||
for (const line of text.split(/\r?\n/)) {
|
|
||||||
const m = TAG_REF.exec(line.trim());
|
|
||||||
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
|
|
||||||
}
|
|
||||||
return best;
|
|
||||||
}
|
|
||||||
|
|
||||||
function readCache(cacheFile, now) {
|
|
||||||
try {
|
|
||||||
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
|
|
||||||
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
|
|
||||||
return typeof cached.latest === "string" ? cached.latest : null;
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function writeCache(cacheFile, data) {
|
|
||||||
const tmp = cacheFile + "." + process.pid + ".tmp";
|
|
||||||
try {
|
|
||||||
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
|
|
||||||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
|
|
||||||
fs.renameSync(tmp, cacheFile);
|
|
||||||
} catch {
|
|
||||||
try {
|
|
||||||
fs.rmSync(tmp, { force: true });
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
|
|
||||||
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
|
|
||||||
* window, no prompt.
|
|
||||||
*/
|
|
||||||
export function runLsRemote({ timeoutMs = 10000 } = {}) {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
let settled = false;
|
|
||||||
const done = (value) => {
|
|
||||||
if (settled) return;
|
|
||||||
settled = true;
|
|
||||||
clearTimeout(timer);
|
|
||||||
resolve(value);
|
|
||||||
};
|
|
||||||
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
|
|
||||||
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
|
|
||||||
let child;
|
|
||||||
try {
|
|
||||||
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
|
|
||||||
shell: false,
|
|
||||||
windowsHide: true,
|
|
||||||
stdio: ["ignore", "pipe", "ignore"],
|
|
||||||
env,
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
return resolve(null);
|
|
||||||
}
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
try {
|
|
||||||
child.kill();
|
|
||||||
} catch {}
|
|
||||||
done(null);
|
|
||||||
}, timeoutMs);
|
|
||||||
timer.unref?.();
|
|
||||||
let out = "";
|
|
||||||
child.stdout.setEncoding("utf8");
|
|
||||||
child.stdout.on("data", (chunk) => {
|
|
||||||
out += chunk;
|
|
||||||
});
|
|
||||||
child.on("error", () => done(null));
|
|
||||||
child.on("close", (code) => done(code === 0 ? out : null));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether `installed` is behind the newest release: `{ installed, latest,
|
|
||||||
* updateAvailable }`, or null when either version is unknown. Reuses a cache
|
|
||||||
* under an hour old, and caches a failed lookup as `latest: null` so it is
|
|
||||||
* not retried until the hour is up. Never throws.
|
|
||||||
*/
|
|
||||||
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
|
|
||||||
try {
|
|
||||||
let latest = readCache(cacheFile, now);
|
|
||||||
if (latest === undefined) {
|
|
||||||
latest = latestTag(await run());
|
|
||||||
writeCache(cacheFile, { checkedAt: now, latest });
|
|
||||||
}
|
|
||||||
const order = compareVersions(installed, latest);
|
|
||||||
if (latest === null || order === null) return null;
|
|
||||||
return { installed, latest, updateAvailable: order < 0 };
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "Plan2Code",
|
"name": "Plan2Code",
|
||||||
"version": "2.5.0",
|
"version": "2.4.1",
|
||||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"ai",
|
"ai",
|
||||||
@@ -17,6 +17,6 @@
|
|||||||
"url": "https://github.com/jparkerweb/plan2code"
|
"url": "https://github.com/jparkerweb/plan2code"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||||
"releaseDate": "2026-10-06",
|
"releaseDate": "2026-10-02",
|
||||||
"mode": "utility"
|
"mode": "utility"
|
||||||
}
|
}
|
||||||
@@ -1,247 +0,0 @@
|
|||||||
// Plan2Code skill scripts: shared plumbing.
|
|
||||||
//
|
|
||||||
// Every script in a skill's scripts/ directory imports this file. It owns the
|
|
||||||
// conventions the SKILL.md prompts rely on, so they are identical everywhere:
|
|
||||||
//
|
|
||||||
// stdout one JSON object, always. `{ "ok": true, ... }` on success,
|
|
||||||
// `{ "ok": false, "error": "<code>", "message": "...", "next": "..." }`
|
|
||||||
// on a handled failure.
|
|
||||||
// stderr a one-line human diagnostic on failure (the same message + next).
|
|
||||||
// exit 0 ok · 1 unexpected crash · 2 bad arguments · 3 not found ·
|
|
||||||
// 4 invalid input or a check that failed · 5 refused (would clobber
|
|
||||||
// or break a rule).
|
|
||||||
//
|
|
||||||
// Node 18+ built-ins only, no build step: this ships inside every skill.
|
|
||||||
|
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
||||||
|
|
||||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
||||||
|
|
||||||
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
|
|
||||||
|
|
||||||
export class CliError extends Error {
|
|
||||||
constructor(exit, error, message, next) {
|
|
||||||
super(message);
|
|
||||||
this.exit = exit;
|
|
||||||
this.error = error;
|
|
||||||
this.next = next;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
|
|
||||||
export function fail(exit, error, message, next) {
|
|
||||||
throw new CliError(exit, error, message, next);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function out(obj) {
|
|
||||||
process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse argv into { _: positionals, <flag>: value }.
|
|
||||||
* `booleans` names flags that take no value; every other `--flag` takes the
|
|
||||||
* next argument, and repeats of a flag listed in `lists` collect into an array.
|
|
||||||
* `--flag=value` works too. Unknown flags are a usage error, so a typo never
|
|
||||||
* silently changes behavior.
|
|
||||||
*/
|
|
||||||
export function parseArgs(argv, { booleans = [], values = [], lists = [] } = {}) {
|
|
||||||
const known = new Set([...booleans, ...values, ...lists, "help"]);
|
|
||||||
const args = { _: [] };
|
|
||||||
for (let i = 0; i < argv.length; i++) {
|
|
||||||
const a = argv[i];
|
|
||||||
if (!a.startsWith("--")) {
|
|
||||||
args._.push(a);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let name = a.slice(2);
|
|
||||||
let value;
|
|
||||||
const eq = name.indexOf("=");
|
|
||||||
if (eq !== -1) {
|
|
||||||
value = name.slice(eq + 1);
|
|
||||||
name = name.slice(0, eq);
|
|
||||||
}
|
|
||||||
if (!known.has(name)) {
|
|
||||||
fail(EXIT.USAGE, "unknown-flag", `Unknown flag --${name}.`, "Run with --help for the flags this script takes.");
|
|
||||||
}
|
|
||||||
if (name === "help" || booleans.includes(name)) {
|
|
||||||
args[name] = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (value === undefined) {
|
|
||||||
if (i + 1 >= argv.length) {
|
|
||||||
fail(EXIT.USAGE, "missing-value", `--${name} needs a value.`, "Run with --help for usage.");
|
|
||||||
}
|
|
||||||
value = argv[++i];
|
|
||||||
}
|
|
||||||
if (lists.includes(name)) (args[name] ||= []).push(value);
|
|
||||||
else args[name] = value;
|
|
||||||
}
|
|
||||||
return args;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Run a script's main(). Prints usage on --help, turns CliError into the JSON
|
|
||||||
* failure shape plus an exit code, and anything else into exit 1 with the stack
|
|
||||||
* on stderr. Sets process.exitCode rather than calling process.exit(), so
|
|
||||||
* stdout is never cut off mid-write.
|
|
||||||
*/
|
|
||||||
export async function run(usage, main) {
|
|
||||||
try {
|
|
||||||
const argv = process.argv.slice(2);
|
|
||||||
if (argv.includes("--help") || argv.includes("-h")) {
|
|
||||||
process.stdout.write(usage.trim() + "\n");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await main(argv);
|
|
||||||
} catch (err) {
|
|
||||||
if (err instanceof CliError) {
|
|
||||||
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
|
|
||||||
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
|
|
||||||
process.exitCode = err.exit;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
process.stderr.write(`unexpected error: ${err && err.stack ? err.stack : err}\n`);
|
|
||||||
out({ ok: false, error: "crash", message: String(err && err.message ? err.message : err) });
|
|
||||||
process.exitCode = EXIT.CRASH;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ time */
|
|
||||||
|
|
||||||
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
|
|
||||||
// clock, for tests and for reproducing a run. Otherwise: the local clock, which
|
|
||||||
// is what "today" means to the person reading the date in their files.
|
|
||||||
export function now() {
|
|
||||||
const pinned = process.env.PLAN2CODE_NOW;
|
|
||||||
if (pinned) {
|
|
||||||
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
|
|
||||||
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
|
|
||||||
const d = new Date(pinned);
|
|
||||||
if (!Number.isNaN(d.getTime())) return d;
|
|
||||||
}
|
|
||||||
return new Date();
|
|
||||||
}
|
|
||||||
|
|
||||||
const pad = (n) => String(n).padStart(2, "0");
|
|
||||||
|
|
||||||
/** YYYY-MM-DD */
|
|
||||||
export function isoDate(d = now()) {
|
|
||||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** YYYYMMDD */
|
|
||||||
export function compactDate(d = now()) {
|
|
||||||
return isoDate(d).replace(/-/g, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
/** YYYY-MM-DD HH:mm */
|
|
||||||
export function stamp(d = now()) {
|
|
||||||
return `${isoDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** HHMMSS */
|
|
||||||
export function clock(d = now()) {
|
|
||||||
return `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ----------------------------------------------------------------- files */
|
|
||||||
|
|
||||||
export function readText(file) {
|
|
||||||
try {
|
|
||||||
return fs.readFileSync(file, "utf8");
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isDir(p) {
|
|
||||||
try {
|
|
||||||
return fs.statSync(p).isDirectory();
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Write a file only when its content changes. Returns true when it wrote. */
|
|
||||||
export function writeIfChanged(file, content) {
|
|
||||||
const current = readText(file);
|
|
||||||
if (current === content) return false;
|
|
||||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
||||||
fs.writeFileSync(file, content);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Normalise line endings for parsing; keep the original for writing back. */
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
|
|
||||||
export function rel(root, p) {
|
|
||||||
return path.relative(root, p).split(path.sep).join("/") || ".";
|
|
||||||
}
|
|
||||||
|
|
||||||
/* --------------------------------------------------------- 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
|
|
||||||
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
|
|
||||||
// metrics-bait scan, so the scripts import it rather than keep a second copy.
|
|
||||||
const CONSOLE_LIB_CANDIDATES = [
|
|
||||||
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
|
|
||||||
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
|
|
||||||
];
|
|
||||||
|
|
||||||
let consoleLibPromise;
|
|
||||||
export function consoleLib() {
|
|
||||||
consoleLibPromise ||= (async () => {
|
|
||||||
for (const candidate of CONSOLE_LIB_CANDIDATES) {
|
|
||||||
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
|
|
||||||
}
|
|
||||||
fail(
|
|
||||||
EXIT.NOT_FOUND,
|
|
||||||
"console-lib-missing",
|
|
||||||
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
|
|
||||||
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
|
|
||||||
);
|
|
||||||
})();
|
|
||||||
return consoleLibPromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
|
|
||||||
export function version() {
|
|
||||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
|
||||||
const text = readText(file);
|
|
||||||
if (!text) continue;
|
|
||||||
try {
|
|
||||||
const v = JSON.parse(text).version;
|
|
||||||
if (typeof v === "string") return v;
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,22 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "Plan2Code",
|
|
||||||
"version": "2.5.0",
|
|
||||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
|
||||||
"keywords": [
|
|
||||||
"ai",
|
|
||||||
"workflow",
|
|
||||||
"development",
|
|
||||||
"planning",
|
|
||||||
"implementation",
|
|
||||||
"plan"
|
|
||||||
],
|
|
||||||
"author": "Justin Parker",
|
|
||||||
"license": "MIT",
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "https://github.com/jparkerweb/plan2code"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
|
||||||
"releaseDate": "2026-10-06",
|
|
||||||
"mode": "utility"
|
|
||||||
}
|
|
||||||
@@ -54,7 +54,7 @@ Check if `./AGENTS.md` exists:
|
|||||||
|
|
||||||
### Check for Existing Progress
|
### 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, check for existing `PLAN-DRAFT-*.md` under `specs/` (`ls specs/` via shell — never Glob; it is gitignored):
|
||||||
- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4
|
- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4
|
||||||
- Status "Escalated from Quick Task - Resume at Phase 2": Acknowledge, verify requirements, skip to Phase 2
|
- Status "Escalated from Quick Task - Resume at Phase 2": Acknowledge, verify requirements, skip to Phase 2
|
||||||
- Status "Draft" or "Complete": Ask user how to proceed
|
- Status "Draft" or "Complete": Ask user how to proceed
|
||||||
|
|||||||
@@ -60,16 +60,7 @@ The first payload for a phase you are about to build:
|
|||||||
```
|
```
|
||||||
|
|
||||||
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
|
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
|
||||||
progress bar is the first thing someone watching a build looks at. The session
|
progress bar is the first thing someone watching a build looks at.
|
||||||
meter counts the build's tasks from `cleared` as it rises, so keep it current,
|
|
||||||
and start every phase (a second one in the same run too) at `"cleared": 0`.
|
|
||||||
|
|
||||||
`"version": 1` is for the first phase of a session only. A doc's version
|
|
||||||
never goes back (console.md → House rules, rule 9), so a later phase in the
|
|
||||||
same session reposts `phase` and `phasefile` at one more than the version the
|
|
||||||
page holds, with the new phase's title and content. The same goes for
|
|
||||||
`report` at sign-off and `review` in a mid-session review: version 1 the
|
|
||||||
first time, then up from wherever the page has it.
|
|
||||||
|
|
||||||
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
||||||
the person can read the prerequisites and task specs while you build. Re-post
|
the person can read the prerequisites and task specs while you build. Re-post
|
||||||
@@ -118,12 +109,6 @@ printed), never into the project or into `~/.plan2code/console/` directly:
|
|||||||
- Do not call `wait` while building. There is nothing to collect, and the page
|
- Do not call `wait` while building. There is nothing to collect, and the page
|
||||||
holds anything the person sends until you next look.
|
holds anything the person sends until you next look.
|
||||||
|
|
||||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
|
||||||
`chat` check between tasks. Follow console.md → Standing instructions for
|
|
||||||
handing independent tasks to helpers and reporting them as `helpers`. Keep the
|
|
||||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
|
||||||
with you.
|
|
||||||
|
|
||||||
### Quick questions between tasks
|
### Quick questions between tasks
|
||||||
|
|
||||||
The person can ask a Quick question on the Ask tab at any point in a build
|
The person can ask a Quick question on the Ask tab at any point in a build
|
||||||
@@ -150,15 +135,8 @@ not questions. Put them in the phase doc as they happen, and in the report.
|
|||||||
|
|
||||||
### When the workflow asks something
|
### When the workflow asks something
|
||||||
|
|
||||||
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }` in
|
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }`, and
|
||||||
the SAME post, and go into the wait loop. When the answer lands, set `working`
|
go into the wait loop. When the answer lands, set `working` again and carry on.
|
||||||
again and carry on.
|
|
||||||
|
|
||||||
A question stops the build. Never leave yourself `working` with a question
|
|
||||||
open, and never "carry on while you decide": the page reads `working` as "not
|
|
||||||
your turn", and the person is left looking at a question they cannot answer.
|
|
||||||
If there is other work the answer does not touch, finish it before you ask,
|
|
||||||
then ask and wait.
|
|
||||||
|
|
||||||
| Moment | `kind` | Notes |
|
| Moment | `kind` | Notes |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -208,8 +186,7 @@ only ever be offered once nothing could come of it:
|
|||||||
`reply` carries `Approve this phase: approved`, which is the terminal's
|
`reply` carries `Approve this phase: approved`, which is the terminal's
|
||||||
`approved`. If the note that came with an approval asks for a change, treat it
|
`approved`. If the note that came with an approval asks for a change, treat it
|
||||||
as "describe any issues": do the change first and ask again. `changes` means
|
as "describe any issues": do the change first and ask again. `changes` means
|
||||||
exactly what it says: address it, bump the report's version (a later phase's
|
exactly what it says: address it, bump the report's version, and reopen the
|
||||||
report starts above the last one's, too), and reopen the
|
|
||||||
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||||
person asking for the code review before they approve anything — see "The
|
person asking for the code review before they approve anything — see "The
|
||||||
review, mid-session" below.
|
review, mid-session" below.
|
||||||
@@ -249,9 +226,8 @@ sign-off card, and approving past it was the answer. `implement-review` ends
|
|||||||
the same way; that phase was reviewed already. Only a finished `quick-task`
|
the same way; that phase was reviewed already. Only a finished `quick-task`
|
||||||
still offers the review on its finish — see below.
|
still offers the review on its finish — see below.
|
||||||
|
|
||||||
`run` gives the approved phase its final score on the session meter (console.md →
|
`run` scores the approved phase on the session meter (console.md → Posting an
|
||||||
Posting an update → Session meter), in the same post that records the approval;
|
update → Session meter), in the same post that records the approval:
|
||||||
it takes over what the build already counted from `cleared`, never adds to it:
|
|
||||||
`implement-phase` for Implement, `implement-review-phase` for Implement +
|
`implement-phase` for Implement, `implement-review-phase` for Implement +
|
||||||
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
|
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
|
||||||
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
|
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
|
||||||
@@ -409,10 +385,7 @@ a question still owed, above the ending itself:
|
|||||||
|
|
||||||
The same build, then Stage 2 publishes the findings exactly as above (the
|
The same build, then Stage 2 publishes the findings exactly as above (the
|
||||||
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
|
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
|
||||||
item: Stage 4 is the only gate. The post that starts Stage 2's review carries
|
item: Stage 4 is the only gate. Stage 4 is the sign-off above **without the
|
||||||
`"run": { "event": "review", "id": "review" }`, as above: in this workflow it
|
|
||||||
scores the review stage's 1 point on the meter as it begins, and the phase's
|
|
||||||
final `run` leaves that point out. Stage 4 is the sign-off above **without the
|
|
||||||
review verdict** — the phase was already reviewed — with the review results
|
review verdict** — the phase was already reviewed — with the review results
|
||||||
and unresolved findings in the report doc, header "Reviewed and ready for
|
and unresolved findings in the report doc, header "Reviewed and ready for
|
||||||
sign-off" in the item's `body`. The finish never carries `review`, and its
|
sign-off" in the item's `body`. The finish never carries `review`, and its
|
||||||
|
|||||||
@@ -170,7 +170,7 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
|
|||||||
|
|
||||||
| Exit | Meaning | What you do |
|
| Exit | Meaning | What you do |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace) and `subagents` (the helpers switch, see Standing instructions). | Handle the cards (if any), the chat (if any), any `workspace` changes and any `subagents` block, then post once (below, Quick questions, Workspace and Standing instructions). |
|
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace). | Handle the cards (if any), the chat (if any) and any `workspace` changes, then post once (below, Quick questions and Workspace). |
|
||||||
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
||||||
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
||||||
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
||||||
@@ -243,7 +243,7 @@ summarise it back.
|
|||||||
Then, in ONE `post`, do all of:
|
Then, in ONE `post`, do all of:
|
||||||
|
|
||||||
- mark each answered item `"status": "answered"` and record its `answer`
|
- mark each answered item `"status": "answered"` and record its `answer`
|
||||||
- reply to every note in that item's `thread` (shape below)
|
- add your replies to any comment threads
|
||||||
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
||||||
questions)
|
questions)
|
||||||
- publish the next batch of questions
|
- publish the next batch of questions
|
||||||
@@ -251,26 +251,6 @@ Then, in ONE `post`, do all of:
|
|||||||
|
|
||||||
One post is one atomic update, so the page never shows a half-changed state.
|
One post is one atomic update, so the page never shows a half-changed state.
|
||||||
|
|
||||||
### Replying to a note
|
|
||||||
|
|
||||||
A `comment` is the person talking to you about that card, often asking
|
|
||||||
something. It shows in the card's **Notes on this** panel, and so does your
|
|
||||||
answer:
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{ "items": [{ "id": "p4", "thread": [
|
|
||||||
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
|
|
||||||
] }] }
|
|
||||||
```
|
|
||||||
|
|
||||||
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
|
|
||||||
`md`: the page reads nothing else. An entry with no `text` is rejected.
|
|
||||||
- The server writes their note into the thread as it arrives. Do not repeat
|
|
||||||
it, and send only your new entries: `thread` appends.
|
|
||||||
- Answer what they asked, in the thread, even when you also change a doc or
|
|
||||||
re-ask the question. "I've updated the doc" alone leaves the question in the
|
|
||||||
panel with no answer under it.
|
|
||||||
|
|
||||||
### Recording the answer
|
### Recording the answer
|
||||||
|
|
||||||
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
||||||
@@ -576,15 +556,8 @@ enforces it, so never tell someone to keep asking past it.
|
|||||||
The person can add folders beside the one the session started in (a shared
|
The person can add folders beside the one the session started in (a shared
|
||||||
library, a design folder), from the footer's folder label. Together they are
|
library, a design folder), from the footer's folder label. Together they are
|
||||||
the session's **workspace**: context for every skill run in this console
|
the session's **workspace**: context for every skill run in this console
|
||||||
session, each folder addressed by a short `@name`. It outlives dashboard hops,
|
session, each folder addressed by a short `@name`. It outlives dashboard hops;
|
||||||
and it is remembered: every change is saved to `workspaces.json` beside
|
a new console session starts with the original folder alone.
|
||||||
`looks.json` (never into the project), keyed by the folder the session runs
|
|
||||||
in and then by spec. A session with a spec opens on that spec's list, one with
|
|
||||||
none on the project's; a spec with nothing saved starts as a copy of the
|
|
||||||
project's list. The dashboard's picker swaps the list as the selection moves,
|
|
||||||
and a `specDir` you post mid-run takes the current list with it. There is
|
|
||||||
nothing for you to load: `open` prints the list, and a switch of spec on a
|
|
||||||
resume reaches you as ordinary workspace changes on your next `wait`.
|
|
||||||
|
|
||||||
### What you are told
|
### What you are told
|
||||||
|
|
||||||
@@ -647,84 +620,6 @@ for permission is not a failure; report only a read that failed after it.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Standing instructions
|
|
||||||
|
|
||||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
|
||||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
|
||||||
from the top bar's Subagents button. Their pick is saved per project and per
|
|
||||||
skill, off by default, and reaches you as a standing instruction, only when it
|
|
||||||
changes.
|
|
||||||
|
|
||||||
### What arrives
|
|
||||||
|
|
||||||
A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`,
|
|
||||||
after the card lines, the `Quick question:` blocks and the `Workspace:` lines.
|
|
||||||
It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting
|
|
||||||
change alone never ends a `wait` slice: it waits for the next send, or for
|
|
||||||
your next `chat` check.
|
|
||||||
|
|
||||||
```
|
|
||||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
|
||||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
|
||||||
Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.
|
|
||||||
With no way to start helpers, report one "working alone" entry for this skill run instead.
|
|
||||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.
|
|
||||||
At most 3 helpers at once.
|
|
||||||
```
|
|
||||||
|
|
||||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
|
||||||
An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …`
|
|
||||||
with the whole block again; switching off arrives as one line:
|
|
||||||
`Subagents: off (revision 4) — don't start new helpers for the rest of this session.`
|
|
||||||
|
|
||||||
It is a console setting, not something the person typed. It never answers a
|
|
||||||
card, and it is never recorded under `specs/`.
|
|
||||||
|
|
||||||
### Obeying it
|
|
||||||
|
|
||||||
- **On:** hand independent work to helpers if your tools allow it, at most
|
|
||||||
`max` at once, following the instruction lines. `max` is advisory: your
|
|
||||||
harness's own limit still applies.
|
|
||||||
- **A higher revision replaces a lower one.** Follow the latest block only.
|
|
||||||
- **Off:** start no new helpers for the rest of the session. Let running ones
|
|
||||||
finish and report them.
|
|
||||||
- **Nothing arrives:** keep doing what the skill says.
|
|
||||||
- **Scope is the skill run it arrived in.** After a dashboard launch, no block
|
|
||||||
means the switch is off for this skill, even if an earlier skill in the same
|
|
||||||
conversation was told "on": `open` starts the count again, and a launch with
|
|
||||||
the switch off sends nothing.
|
|
||||||
|
|
||||||
### Reporting helpers
|
|
||||||
|
|
||||||
Post them, at your check-ins, so the page's Subagents tab can show them. The
|
|
||||||
page never hears from a helper directly:
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{ "helpers": [
|
|
||||||
{ "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" },
|
|
||||||
{ "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." }
|
|
||||||
] }
|
|
||||||
```
|
|
||||||
|
|
||||||
- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and
|
|
||||||
`state` (`running`, `done` or `failed`) are required; `result` (at most 200)
|
|
||||||
is the one line you add once a helper ends.
|
|
||||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
|
||||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
|
||||||
too; a resume into the same skill keeps it.
|
|
||||||
- One post per change worth seeing, not a stream.
|
|
||||||
- Questions for the person stay with you, never with a helper: most harnesses
|
|
||||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
|
||||||
session.
|
|
||||||
- **No way to start helpers?** Post one `{ "id": "alone", "alone": true }`
|
|
||||||
entry for the skill run instead. The tab then says you are working alone.
|
|
||||||
- **Pathfinder:** research questions always use helpers and are always
|
|
||||||
reported, whatever the switch says. The switch governs recon, sketches and
|
|
||||||
lookups beside the conversation.
|
|
||||||
- Helpers add no session meter points. Post no `run` for them.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Launches (dashboard only)
|
## Launches (dashboard only)
|
||||||
|
|
||||||
A `dashboard` session is not a conversation: the page draws a menu of every
|
A `dashboard` session is not a conversation: the page draws a menu of every
|
||||||
@@ -759,17 +654,9 @@ finish are dropped, so you start on a blank page and post your own. A skill
|
|||||||
run inline from another (a quick task's review) keeps the page it was
|
run inline from another (a quick task's review) keeps the page it was
|
||||||
handed. A
|
handed. A
|
||||||
fresh `open` would strand the page the person is watching on the dashboard's
|
fresh `open` would strand the page the person is watching on the dashboard's
|
||||||
session while your questions went to a page nobody has open.
|
session while your questions went to a page nobody has open. Then run the
|
||||||
|
skill normally: its Interface question was already answered by being
|
||||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
launched, so start where its real work starts.
|
||||||
> own file-read tool and follow it from the top instead.** Every Plan2Code
|
|
||||||
> skill below the dashboard ships `disable-model-invocation: true` on
|
|
||||||
> purpose — it exists to be read and followed inline, not launched as a
|
|
||||||
> sub-skill — and calling one through a skill-invocation tool errors out and
|
|
||||||
> strands the hand-off mid-launch.
|
|
||||||
|
|
||||||
Its Interface step is already answered by having been launched, so start
|
|
||||||
where its real work starts.
|
|
||||||
|
|
||||||
The menu itself is the page's own list — you never send it. The page knows
|
The menu itself is the page's own list — you never send it. The page knows
|
||||||
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
||||||
@@ -841,10 +728,7 @@ commands follow the pipeline: the sign-off's is
|
|||||||
|
|
||||||
### Review (`review`)
|
### Review (`review`)
|
||||||
|
|
||||||
Scope questions up front — run standalone with nothing named, the first is
|
Scope questions up front, then the findings report as a doc (`id: "report"`),
|
||||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
|
||||||
uncommitted changes, specs, files you name; each option with its size),
|
|
||||||
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
|
|
||||||
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
||||||
id, carrying `"doc": "report"` so the card links straight to the findings.
|
id, carrying `"doc": "report"` so the card links straight to the findings.
|
||||||
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
||||||
@@ -878,14 +762,12 @@ that is what the person is there to download. The finish carries no
|
|||||||
- Chart Step 8's research subagents must all report back before the
|
- Chart Step 8's research subagents must all report back before the
|
||||||
finish (Finishing → Nothing of yours may still be running); the finish
|
finish (Finishing → Nothing of yours may still be running); the finish
|
||||||
body then names what each one found.
|
body then names what each one found.
|
||||||
- Report every research subagent as a helper, whatever the Subagents switch
|
|
||||||
says (Standing instructions → Reporting helpers).
|
|
||||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||||
sees the Trail Footer, and without this their last screen promises a question
|
sees the Trail Footer, and without this their last screen promises a question
|
||||||
that is never coming.
|
that is never coming.
|
||||||
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
|
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
|
||||||
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
|
and `pathfinder-research` (id = the question's file slug) as each research
|
||||||
subagent reports back, or when you resolve a `research` question yourself
|
subagent reports back, or when you resolve a `research` question yourself
|
||||||
(Posting an update → Session meter). Other questions score through their
|
(Posting an update → Session meter). Other questions score through their
|
||||||
answers, so there is nothing to post for them.
|
answers, so there is nothing to post for them.
|
||||||
@@ -938,13 +820,7 @@ know:
|
|||||||
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) so the page reader sees it land. |
|
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) so the page reader sees it land. |
|
||||||
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
|
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
|
||||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
|
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`. |
|
||||||
|
|
||||||
Post `activity` as each step starts, before its doc or question lands — reading
|
|
||||||
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
|
|
||||||
implementation — the same way Review does. A step with no card of its own
|
|
||||||
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
|
|
||||||
Finalize".
|
|
||||||
|
|
||||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||||
Stopping mid-finalize loses nothing
|
Stopping mid-finalize loses nothing
|
||||||
@@ -976,7 +852,7 @@ question or doc lands:
|
|||||||
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
||||||
|
|
||||||
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
||||||
merge by `id` (an unknown id is added), and `thread` appends. Send only
|
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
|
||||||
what changed. A whole-file rewrite would put the entire session back into your
|
what changed. A whole-file rewrite would put the entire session back into your
|
||||||
context on every turn.
|
context on every turn.
|
||||||
|
|
||||||
@@ -1018,9 +894,7 @@ Per-unit work is yours to report, with `run` in any post:
|
|||||||
not count), a whole number from 1 to 999. A built phase scores by its size,
|
not count), a whole number from 1 to 999. A built phase scores by its size,
|
||||||
one point per 3 tasks rounded up, and Implement + Review one more for the
|
one point per 3 tasks rounded up, and Implement + Review one more for the
|
||||||
review. Always send it: without it a phase scores a flat 2 (or 3), however
|
review. Always send it: without it a phase scores a flat 2 (or 3), however
|
||||||
big it was. On any other event it is exit `3`. The console already counts a
|
big it was. On any other event it is exit `3`.
|
||||||
build's tasks from `headline.cleared` as they are ticked off; the phase's
|
|
||||||
`run` takes that count over with the final score, so it never counts twice.
|
|
||||||
- One `run` per post. Which events a workflow reports is in its own notes
|
- One `run` per post. Which events a workflow reports is in its own notes
|
||||||
(Workflow notes → Pathfinder; `building.md` for Implement and for the
|
(Workflow notes → Pathfinder; `building.md` for Implement and for the
|
||||||
review run on the page after a build).
|
review run on the page after a build).
|
||||||
@@ -1229,16 +1103,6 @@ A patch that breaks one of these is rejected with exit `3` and a message:
|
|||||||
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
||||||
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
||||||
and 5 cover `reason` and `hint`.
|
and 5 cover `reason` and `hint`.
|
||||||
8. **`helpers` entries are well formed** (Standing instructions → Reporting
|
|
||||||
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
|
|
||||||
and a known `state` within their limits, plus at most one `alone` entry.
|
|
||||||
Rules 4 and 5 cover `title`, `ask` and `result`.
|
|
||||||
9. **A doc's `version` never goes back.** Sending a known doc a lower
|
|
||||||
`version` than the page holds is refused: it is almost always a stale or
|
|
||||||
copied payload. The same version again is fine, and a dashboard hop starts
|
|
||||||
every doc fresh. Anything else reusing a doc id in the same session (a
|
|
||||||
build's second phase, a second report or review) continues from the
|
|
||||||
version the page holds.
|
|
||||||
|
|
||||||
These are workflow rules you already follow. The server just makes them checkable.
|
These are workflow rules you already follow. The server just makes them checkable.
|
||||||
|
|
||||||
@@ -1260,9 +1124,7 @@ cannot see them, and the moment it says the session ended, the person is
|
|||||||
free to close that terminal and kill them mid-write. While you wait, post
|
free to close that terminal and kill them mid-write. While you wait, post
|
||||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||||
and update the count as each returns. Never write a `finish.body` that says
|
and update the count as each returns. Never write a `finish.body` that says
|
||||||
work "is running in the background" or "will finish on its own". Mark every
|
work "is running in the background" or "will finish on its own".
|
||||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
|
||||||
never ends on a row still running.
|
|
||||||
|
|
||||||
### 1. Post the finish
|
### 1. Post the finish
|
||||||
|
|
||||||
@@ -1368,7 +1230,7 @@ answers were submitted but never picked up.
|
|||||||
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
||||||
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
||||||
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
||||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||||
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
||||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||||
|
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ import {
|
|||||||
die,
|
die,
|
||||||
ensureDir,
|
ensureDir,
|
||||||
fileStamp,
|
fileStamp,
|
||||||
forgetWorkspace,
|
|
||||||
handOff,
|
handOff,
|
||||||
handleFile,
|
handleFile,
|
||||||
healthOk,
|
healthOk,
|
||||||
@@ -64,21 +63,16 @@ import {
|
|||||||
readChat,
|
readChat,
|
||||||
readJson,
|
readJson,
|
||||||
readLedger,
|
readLedger,
|
||||||
readSubagentCursor,
|
|
||||||
readSubagentSetting,
|
|
||||||
readWorkspace,
|
readWorkspace,
|
||||||
reapHandles,
|
reapHandles,
|
||||||
rememberedWorkspace,
|
|
||||||
remoteWarning,
|
remoteWarning,
|
||||||
removeScratch,
|
removeScratch,
|
||||||
removeSessions,
|
removeSessions,
|
||||||
repoRoots,
|
repoRoots,
|
||||||
resetSubagentCursor,
|
|
||||||
scanProject,
|
scanProject,
|
||||||
SESSION_MAX_AGE_MS,
|
SESSION_MAX_AGE_MS,
|
||||||
sessionDir,
|
sessionDir,
|
||||||
sleepSync,
|
sleepSync,
|
||||||
specKey,
|
|
||||||
staleScratch,
|
staleScratch,
|
||||||
staleSessions,
|
staleSessions,
|
||||||
sweepUploads,
|
sweepUploads,
|
||||||
@@ -91,11 +85,9 @@ import {
|
|||||||
workspaceForAgent,
|
workspaceForAgent,
|
||||||
writeCursor,
|
writeCursor,
|
||||||
writeJsonAtomic,
|
writeJsonAtomic,
|
||||||
writeSubagentCursor,
|
|
||||||
writeWorkspaceCursor,
|
writeWorkspaceCursor,
|
||||||
} from "./lib.mjs";
|
} from "./lib.mjs";
|
||||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount } from "./public/meter.js";
|
||||||
import { blockFor, offered } from "./public/subagents.js";
|
|
||||||
import { changeLine } from "./public/workspace.js";
|
import { changeLine } from "./public/workspace.js";
|
||||||
|
|
||||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||||
@@ -315,11 +307,7 @@ async function cmdOpen() {
|
|||||||
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
||||||
}
|
}
|
||||||
state = written.state;
|
state = written.state;
|
||||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
|
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
|
||||||
// A new agent conversation has been told nothing yet (FR-6).
|
|
||||||
try {
|
|
||||||
resetSubagentCursor(dir);
|
|
||||||
} catch {}
|
|
||||||
trace("open: state written");
|
trace("open: state written");
|
||||||
|
|
||||||
// Dashboard launches are recorded too (they score nothing), so the folder
|
// Dashboard launches are recorded too (they score nothing), so the folder
|
||||||
@@ -329,7 +317,7 @@ async function cmdOpen() {
|
|||||||
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
|
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
|
||||||
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
|
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
|
||||||
} catch {}
|
} catch {}
|
||||||
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
|
const workspace = workspaceOnOpen(dir, worktree);
|
||||||
|
|
||||||
// Month-old sessions and scratch files: listed before the print so the
|
// Month-old sessions and scratch files: listed before the print so the
|
||||||
// agent can see what went, removed after it so the page waits for nothing.
|
// agent can see what went, removed after it so the page waits for nothing.
|
||||||
@@ -346,18 +334,9 @@ async function cmdOpen() {
|
|||||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||||
};
|
};
|
||||||
|
|
||||||
// A standing instruction the new agent is owed, as `subagents` and a
|
|
||||||
// `reply` holding only its lines; neither key when nothing is owed.
|
|
||||||
const subagentsOwed = () => {
|
|
||||||
awaitSubagentSync(dir, state.workflow);
|
|
||||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
|
||||||
return [out.subagents ? out : {}, cursor];
|
|
||||||
};
|
|
||||||
|
|
||||||
// Reuse a live server if one is already serving this session.
|
// Reuse a live server if one is already serving this session.
|
||||||
if (existing && (await reusable)) {
|
if (existing && (await reusable)) {
|
||||||
if (!args["no-open"]) openBrowser(existing.url);
|
if (!args["no-open"]) openBrowser(existing.url);
|
||||||
const [owed, subCursor] = subagentsOwed();
|
|
||||||
print({
|
print({
|
||||||
ok: true,
|
ok: true,
|
||||||
sid,
|
sid,
|
||||||
@@ -367,11 +346,9 @@ async function cmdOpen() {
|
|||||||
pendingResult: carried,
|
pendingResult: carried,
|
||||||
terminalLine: terminalLine(existing.url),
|
terminalLine: terminalLine(existing.url),
|
||||||
workspace,
|
workspace,
|
||||||
...owed,
|
|
||||||
...swept,
|
...swept,
|
||||||
...remoteWarning(),
|
...remoteWarning(),
|
||||||
});
|
});
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
sweep();
|
sweep();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -404,7 +381,6 @@ async function cmdOpen() {
|
|||||||
const notes = [];
|
const notes = [];
|
||||||
if (remote.note) notes.push(remote.note);
|
if (remote.note) notes.push(remote.note);
|
||||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||||
const [owed, subCursor] = subagentsOwed();
|
|
||||||
print({
|
print({
|
||||||
ok: true,
|
ok: true,
|
||||||
sid,
|
sid,
|
||||||
@@ -415,12 +391,10 @@ async function cmdOpen() {
|
|||||||
pendingResult: carried,
|
pendingResult: carried,
|
||||||
terminalLine: terminalLine(handle.url),
|
terminalLine: terminalLine(handle.url),
|
||||||
workspace,
|
workspace,
|
||||||
...owed,
|
|
||||||
...swept,
|
...swept,
|
||||||
...(remote.remote ? { remote: remote.remote } : {}),
|
...(remote.remote ? { remote: remote.remote } : {}),
|
||||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||||
});
|
});
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
// After the print, never before it: the page and the link wait for nothing.
|
// After the print, never before it: the page and the link wait for nothing.
|
||||||
sweep();
|
sweep();
|
||||||
}
|
}
|
||||||
@@ -429,11 +403,10 @@ async function cmdOpen() {
|
|||||||
* The workspace as `open` hands it to the agent, and the cursor seeded to
|
* The workspace as `open` hands it to the agent, and the cursor seeded to
|
||||||
* match: the agent now has the whole list, so no change up to here is owed.
|
* match: the agent now has the whole list, so no change up to here is owed.
|
||||||
* Read-only on workspace.json, which only the server writes; on a fresh
|
* Read-only on workspace.json, which only the server writes; on a fresh
|
||||||
* session the server has not made it yet, so what was remembered for this
|
* session the server has not made it yet, so the original folder stands in.
|
||||||
* folder and spec stands in, the same list the server is about to make.
|
|
||||||
*/
|
*/
|
||||||
function workspaceOnOpen(dir, worktree, specDir) {
|
function workspaceOnOpen(dir, worktree) {
|
||||||
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
|
const ws = readWorkspace(dir) || initialWorkspace(worktree);
|
||||||
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
|
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
|
||||||
try {
|
try {
|
||||||
writeWorkspaceCursor(dir, ws.version || 0);
|
writeWorkspaceCursor(dir, ws.version || 0);
|
||||||
@@ -616,13 +589,6 @@ function cmdPost() {
|
|||||||
const next = written.state;
|
const next = written.state;
|
||||||
|
|
||||||
for (const line of ledgerLines) appendLedger(dir, line);
|
for (const line of ledgerLines) appendLedger(dir, line);
|
||||||
// A build scores its tasks as it clears them (meter.js, PROGRESS_WORKFLOWS),
|
|
||||||
// after any `run` in the same post, so a phase finished here ends its count.
|
|
||||||
if (patch.headline && typeof patch.headline === "object") {
|
|
||||||
const ledger = readLedger(dir);
|
|
||||||
const progress = progressEntry(ledger, lastLaunchId(ledger), next.workflow, patch.headline.cleared);
|
|
||||||
if (progress) appendLedger(dir, progress);
|
|
||||||
}
|
|
||||||
appendEvent(dir, { type: "post", items: (patch.items || []).length });
|
appendEvent(dir, { type: "post", items: (patch.items || []).length });
|
||||||
|
|
||||||
const open = next.items.filter((i) => isOpen(i) && i.required !== false).length;
|
const open = next.items.filter((i) => isOpen(i) && i.required !== false).length;
|
||||||
@@ -797,7 +763,7 @@ function serverGone(sid) {
|
|||||||
|
|
||||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||||
function deliverChat(dir, sid, entries, url) {
|
function deliverChat(dir, sid, entries, url) {
|
||||||
const [withWs, changes] = withWorkspace(dir, {
|
const [out, changes] = withWorkspace(dir, {
|
||||||
type: "chat",
|
type: "chat",
|
||||||
at: nowIso(),
|
at: nowIso(),
|
||||||
sid,
|
sid,
|
||||||
@@ -805,11 +771,9 @@ function deliverChat(dir, sid, entries, url) {
|
|||||||
chat: entries,
|
chat: entries,
|
||||||
reply: chatReplyLines(entries),
|
reply: chatReplyLines(entries),
|
||||||
});
|
});
|
||||||
const [out, subCursor] = withSubagents(dir, withWs);
|
|
||||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||||
advanceCursor(dir, entries);
|
advanceCursor(dir, entries);
|
||||||
advanceWorkspace(dir, changes);
|
advanceWorkspace(dir, changes);
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
process.exitCode = 0;
|
process.exitCode = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -831,52 +795,6 @@ function advanceWorkspace(dir, changes) {
|
|||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The server rewrites the session's setting for a new workflow only once its
|
|
||||||
// watcher sees the state `open` just wrote, so a launch or hop that read the
|
|
||||||
// file at once would find the old workflow's and owe the agent nothing until
|
|
||||||
// its next pickup. Give the server a moment to catch up instead, never
|
|
||||||
// writing the file ourselves (FR-7). A session with no setting file at all is
|
|
||||||
// an older server, which never writes one: a short look, not the full wait.
|
|
||||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
|
||||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
|
||||||
function awaitSubagentSync(dir, workflow) {
|
|
||||||
if (!offered(workflow)) return;
|
|
||||||
const start = Date.now();
|
|
||||||
for (;;) {
|
|
||||||
const setting = readSubagentSetting(dir);
|
|
||||||
if (setting && setting.workflow === workflow) return;
|
|
||||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
|
||||||
if (Date.now() - start >= budget) return;
|
|
||||||
sleepSync(25);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Subagents switch the agent is owed, added to what it is about to read:
|
|
||||||
// the setting as `subagents`, and its lines last in `reply`, after card lines,
|
|
||||||
// Quick questions and Workspace lines (FR-9). Read from the session's own
|
|
||||||
// setting file only, which only the server writes (FR-7). A setting for
|
|
||||||
// another workflow is the server not having caught up with a hop yet: it
|
|
||||||
// rides on the next pickup instead.
|
|
||||||
function withSubagents(dir, out) {
|
|
||||||
const setting = readSubagentSetting(dir);
|
|
||||||
if (!setting) return [out, null];
|
|
||||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
|
||||||
if (setting.workflow !== workflow) return [out, null];
|
|
||||||
const block = blockFor(setting, readSubagentCursor(dir));
|
|
||||||
if (!block) return [out, null];
|
|
||||||
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
|
|
||||||
return [{ ...out, subagents: block.field, reply }, block.cursor];
|
|
||||||
}
|
|
||||||
|
|
||||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
|
||||||
// block at the next pickup, never loses it.
|
|
||||||
function advanceSubagents(dir, cursor) {
|
|
||||||
if (!cursor) return;
|
|
||||||
try {
|
|
||||||
writeSubagentCursor(dir, cursor);
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Print first, then this, exactly as consume() stamps a result: a kill in
|
// Print first, then this, exactly as consume() stamps a result: a kill in
|
||||||
// between can only hand the same chat over again, and collectChat() drops
|
// between can only hand the same chat over again, and collectChat() drops
|
||||||
// anything that already has a reply.
|
// anything that already has a reply.
|
||||||
@@ -903,17 +821,15 @@ async function cmdChat() {
|
|||||||
}
|
}
|
||||||
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||||
const changes = pendingWorkspaceChanges(dir);
|
const changes = pendingWorkspaceChanges(dir);
|
||||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
if (!entries.length && !changes.length) {
|
||||||
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
|
|
||||||
if (!entries.length && !changes.length && !subCursor) {
|
|
||||||
print({ chat: [] });
|
print({ chat: [] });
|
||||||
process.exitCode = 10;
|
process.exitCode = 10;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||||
|
print({ chat: entries, workspace: changes, reply, terminalLine: terminalLine(handle.url) });
|
||||||
advanceCursor(dir, entries);
|
advanceCursor(dir, entries);
|
||||||
advanceWorkspace(dir, changes);
|
advanceWorkspace(dir, changes);
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
process.exitCode = 0;
|
process.exitCode = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -938,8 +854,7 @@ function consume(dir, resultPath, result, url, chat = []) {
|
|||||||
// never on result.json itself.
|
// never on result.json itself.
|
||||||
const withChat = { ...collected, chat };
|
const withChat = { ...collected, chat };
|
||||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
const [out, changes] = withWorkspace(dir, withChat);
|
||||||
const [out, subCursor] = withSubagents(dir, withWs);
|
|
||||||
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
||||||
try {
|
try {
|
||||||
writeJsonAtomic(resultPath, collected);
|
writeJsonAtomic(resultPath, collected);
|
||||||
@@ -948,7 +863,6 @@ function consume(dir, resultPath, result, url, chat = []) {
|
|||||||
ledgerAnswers(dir, result);
|
ledgerAnswers(dir, result);
|
||||||
advanceCursor(dir, chat);
|
advanceCursor(dir, chat);
|
||||||
advanceWorkspace(dir, changes);
|
advanceWorkspace(dir, changes);
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1032,18 +946,6 @@ function realNearest(p) {
|
|||||||
return path.join(fs.realpathSync(existing), path.relative(existing, p));
|
return path.join(fs.realpathSync(existing), path.relative(existing, p));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------------- forget */
|
|
||||||
|
|
||||||
// Drop the folder list remembered for one spec (Finalize, once the spec is
|
|
||||||
// archived). The project's own list and every other spec's are untouched.
|
|
||||||
function cmdForget() {
|
|
||||||
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
|
|
||||||
let spec = specKey(args.spec);
|
|
||||||
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
|
|
||||||
const worktree = repoRoots().worktree;
|
|
||||||
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ----------------------------------------------------------------- help */
|
/* ----------------------------------------------------------------- help */
|
||||||
|
|
||||||
function cmdHelp() {
|
function cmdHelp() {
|
||||||
@@ -1059,20 +961,13 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
|||||||
first post. --file is optional, and --title defaults to the
|
first post. --file is optional, and --title defaults to the
|
||||||
project's folder name. Also prints workspace: { folders: [{ name,
|
project's folder name. Also prints workspace: { folders: [{ name,
|
||||||
path, description?, original? }], missing? }, the folders this
|
path, description?, original? }], missing? }, the folders this
|
||||||
console session reads as context, addressed as @name. The list is
|
console session reads as context, addressed as @name.
|
||||||
remembered per folder and spec in workspaces.json beside looks.json.
|
|
||||||
May also print subagents: { state, revision, max, instruction } and
|
|
||||||
a reply holding only its "Subagents: ..." lines, when a standing
|
|
||||||
instruction (the page's Subagents switch) is owed to you.
|
|
||||||
post --session <sid> --file <patch.json>
|
post --session <sid> --file <patch.json>
|
||||||
Merge a patch into the session. Prints terminalLine while the
|
Merge a patch into the session. Prints terminalLine while the
|
||||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||||
{ name, reason, hint? } (a workspace folder you could not read);
|
{ name, reason, hint? } (a workspace folder you could not read);
|
||||||
both go to the ledger, never into the state. A patch may also
|
both go to the ledger, never into the state.
|
||||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
|
||||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
|
||||||
(see console.md → Standing instructions).
|
|
||||||
wait --session <sid> [--seconds <N>]
|
wait --session <sid> [--seconds <N>]
|
||||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||||
@@ -1083,24 +978,16 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
|||||||
"workspace" (changes since you last heard, each once, with a
|
"workspace" (changes since you last heard, each once, with a
|
||||||
"Workspace: ..." line in reply); exit 10 counts them as
|
"Workspace: ..." line in reply); exit 10 counts them as
|
||||||
pendingWorkspace, and a change alone never ends a slice.
|
pendingWorkspace, and a change alone never ends a slice.
|
||||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
|
||||||
by the person, with its "Subagents: ..." lines last in reply); a
|
|
||||||
setting change alone never ends a slice either.
|
|
||||||
chat --session <sid>
|
chat --session <sid>
|
||||||
Collect Quick questions, workspace changes and a Subagents
|
Collect Quick questions and workspace changes now, never waiting,
|
||||||
setting change now, never waiting, never touching card sends.
|
never touching card sends. Exit 0 = { chat, workspace, reply,
|
||||||
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
|
terminalLine }, 10 = none, 20 = server gone.
|
||||||
10 = none, 20 = server gone.
|
|
||||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||||
messages with it during a console session.
|
messages with it during a console session.
|
||||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||||
Copy a cited note attachment into specs/<idea>/attachments/. Prints
|
Copy a cited note attachment into specs/<idea>/attachments/. Prints
|
||||||
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
|
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
|
||||||
missing. Paste link as it is.
|
missing. Paste link as it is.
|
||||||
forget --spec specs/<idea>
|
|
||||||
Drop the workspace folders remembered for that spec, in this
|
|
||||||
folder (Finalize, after archiving it). Prints { ok, spec, forgot };
|
|
||||||
forgot is false when nothing was saved. Exit 2 = bad usage.
|
|
||||||
status [--session <sid>] [--all]
|
status [--session <sid>] [--all]
|
||||||
One session, or every session belonging to this project.
|
One session, or every session belonging to this project.
|
||||||
stop --session <sid> | --all
|
stop --session <sid> | --all
|
||||||
@@ -1319,7 +1206,6 @@ const COMMANDS = {
|
|||||||
wait: cmdWait,
|
wait: cmdWait,
|
||||||
chat: cmdChat,
|
chat: cmdChat,
|
||||||
keep: cmdKeep,
|
keep: cmdKeep,
|
||||||
forget: cmdForget,
|
|
||||||
status: cmdStatus,
|
status: cmdStatus,
|
||||||
stop: cmdStop,
|
stop: cmdStop,
|
||||||
help: cmdHelp,
|
help: cmdHelp,
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ import { fileURLToPath } from "node:url";
|
|||||||
import { CHAT_LIMIT } from "./public/chat.js";
|
import { CHAT_LIMIT } from "./public/chat.js";
|
||||||
import { DOC_TYPES } from "./public/answers.js";
|
import { DOC_TYPES } from "./public/answers.js";
|
||||||
import { defaultName } from "./public/workspace.js";
|
import { defaultName } from "./public/workspace.js";
|
||||||
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
|
||||||
|
|
||||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
export const PUBLIC_DIR = path.join(HERE, "public");
|
export const PUBLIC_DIR = path.join(HERE, "public");
|
||||||
@@ -49,10 +48,6 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
|
|||||||
|
|
||||||
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
||||||
|
|
||||||
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
|
|
||||||
// so every session within the hour reuses one lookup.
|
|
||||||
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
|
|
||||||
|
|
||||||
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
||||||
// test run (or a second sandboxed instance) shares one handle directory with
|
// test run (or a second sandboxed instance) shares one handle directory with
|
||||||
// the real thing, and `stop --all` reaches outside its own world and kills a
|
// the real thing, and `stop --all` reaches outside its own world and kills a
|
||||||
@@ -183,8 +178,8 @@ function lockStale(lock) {
|
|||||||
// Run fn while holding the session's state lock, and release it however fn
|
// Run fn while holding the session's state lock, and release it however fn
|
||||||
// ends. fn must not call process.exit(): the release would never run, and the
|
// ends. fn must not call process.exit(): the release would never run, and the
|
||||||
// next writer would wait out the stale age.
|
// next writer would wait out the stale age.
|
||||||
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
|
export function withStateLock(dir, fn) {
|
||||||
const lock = path.join(dir, lockName);
|
const lock = path.join(dir, STATE_LOCK_FILE);
|
||||||
const deadline = Date.now() + LOCK_WAIT_MS;
|
const deadline = Date.now() + LOCK_WAIT_MS;
|
||||||
let fd = null;
|
let fd = null;
|
||||||
for (let attempt = 0; fd === null; attempt++) {
|
for (let attempt = 0; fd === null; attempt++) {
|
||||||
@@ -193,7 +188,7 @@ export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
|
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
|
||||||
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
|
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
|
||||||
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
|
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
|
||||||
if (err.code === "EEXIST" && lockStale(lock)) {
|
if (err.code === "EEXIST" && lockStale(lock)) {
|
||||||
try {
|
try {
|
||||||
fs.rmSync(lock, { force: true });
|
fs.rmSync(lock, { force: true });
|
||||||
@@ -492,16 +487,8 @@ export async function removeSessions(sessionsDir, sids) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The console folder's own files that no sweep may ever remove: the person's
|
// The console folder's own files that no sweep may ever remove: the person's
|
||||||
// looks, the folders remembered per project and spec, the Subagents switch
|
// looks and the pointer to this console's directory.
|
||||||
// saved per project and workflow, the pointer to this console's directory,
|
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "console-dir"]);
|
||||||
// and the cached release check.
|
|
||||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
|
||||||
"looks.json",
|
|
||||||
"workspaces.json",
|
|
||||||
"subagents.json",
|
|
||||||
"console-dir",
|
|
||||||
"update-check.json",
|
|
||||||
]);
|
|
||||||
|
|
||||||
function isScratchName(name) {
|
function isScratchName(name) {
|
||||||
return (
|
return (
|
||||||
@@ -548,148 +535,6 @@ export async function removeScratch(consoleDir, names) {
|
|||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------- cleanup */
|
|
||||||
|
|
||||||
// What User Preferences -> Cleanup never removes. The console folder keeps its
|
|
||||||
// protected files, its sessions dir (old sessions go one by one, by age) and,
|
|
||||||
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
|
|
||||||
// console, the launcher (bin/, launcher.json) and the models the person added.
|
|
||||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
|
||||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
|
|
||||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
|
||||||
// folders hold files that live for milliseconds -- a held
|
|
||||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
|
||||||
// rename -- and removing one mid-write loses another session's change.
|
|
||||||
export const STRAY_GRACE_MS = 60 * 60 * 1000;
|
|
||||||
|
|
||||||
// Bytes under `p`, never following a symlink: a link counts as itself.
|
|
||||||
async function diskBytes(p) {
|
|
||||||
let st;
|
|
||||||
try {
|
|
||||||
st = await fs.promises.lstat(p);
|
|
||||||
} catch {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
if (!st.isDirectory()) return st.size;
|
|
||||||
let entries;
|
|
||||||
try {
|
|
||||||
entries = await fs.promises.readdir(p);
|
|
||||||
} catch {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
let total = 0;
|
|
||||||
for (const name of entries) total += await diskBytes(path.join(p, name));
|
|
||||||
return total;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The newest mtime of anything under `p`, never following a symlink. A folder
|
|
||||||
// counts by its files, since rewriting a file never touches its folder's
|
|
||||||
// mtime; an empty folder counts by its own. Anything unreadable on the way
|
|
||||||
// down answers Infinity, so it reads as just touched and stays.
|
|
||||||
function newestMtime(p) {
|
|
||||||
let st;
|
|
||||||
try {
|
|
||||||
st = fs.lstatSync(p);
|
|
||||||
} catch {
|
|
||||||
return Infinity;
|
|
||||||
}
|
|
||||||
if (!st.isDirectory()) return st.mtimeMs;
|
|
||||||
let entries;
|
|
||||||
try {
|
|
||||||
entries = fs.readdirSync(p);
|
|
||||||
} catch {
|
|
||||||
return Infinity;
|
|
||||||
}
|
|
||||||
if (!entries.length) return st.mtimeMs;
|
|
||||||
let newest = 0;
|
|
||||||
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
|
|
||||||
return newest;
|
|
||||||
}
|
|
||||||
|
|
||||||
function entryKind(entry) {
|
|
||||||
if (entry.isSymbolicLink()) return "link";
|
|
||||||
return entry.isDirectory() ? "folder" : "file";
|
|
||||||
}
|
|
||||||
|
|
||||||
function strayEntries(dir, kept, where, now) {
|
|
||||||
let entries;
|
|
||||||
try {
|
|
||||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
||||||
} catch {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
|
|
||||||
return entries
|
|
||||||
.filter((e) => !kept.has(e.name))
|
|
||||||
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
|
||||||
.filter((e) => settled(e.path));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Everything Cleanup would remove, worked out on the server and never taken
|
|
||||||
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
|
|
||||||
* `open` sweeps by, plus every file in the folder that old, so a resumed
|
|
||||||
* session or a saved draft keeps it), anything at the top of the console folder that is
|
|
||||||
* not kept, and -- only when the console runs from its default home inside
|
|
||||||
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
|
|
||||||
* touched within `STRAY_GRACE_MS` are left for a later scan. A
|
|
||||||
* console running from another home (tests, dev) never reaches ~/.plan2code.
|
|
||||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
|
||||||
*/
|
|
||||||
export async function cleanupFindings({
|
|
||||||
consoleDir = HOME_DIR,
|
|
||||||
plan2codeDir = PLAN2CODE_DIR,
|
|
||||||
now = Date.now(),
|
|
||||||
maxAgeMs = SESSION_MAX_AGE_MS,
|
|
||||||
skipSid,
|
|
||||||
} = {}) {
|
|
||||||
const found = [];
|
|
||||||
const sessionsDir = path.join(consoleDir, "sessions");
|
|
||||||
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
|
|
||||||
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
|
|
||||||
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
|
|
||||||
}
|
|
||||||
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
|
|
||||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
|
||||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
|
||||||
}
|
|
||||||
const items = [];
|
|
||||||
let bytes = 0;
|
|
||||||
for (const f of found) {
|
|
||||||
const size = await diskBytes(f.path);
|
|
||||||
bytes += size;
|
|
||||||
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
|
|
||||||
}
|
|
||||||
return { items, bytes };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
|
|
||||||
* worked out afresh first and only ids on it are touched, so a name from the
|
|
||||||
* page is never a path, and anything that stopped qualifying since the scan
|
|
||||||
* (a session touched again) stays. A link is unlinked, never followed.
|
|
||||||
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
|
|
||||||
*/
|
|
||||||
export async function removeCleanup(ids, opts = {}) {
|
|
||||||
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
|
|
||||||
const { items } = await cleanupFindings(opts);
|
|
||||||
const removed = [];
|
|
||||||
const failed = [];
|
|
||||||
let bytes = 0;
|
|
||||||
for (const item of items) {
|
|
||||||
if (!wanted.has(item.id)) continue;
|
|
||||||
try {
|
|
||||||
if (item.kind === "link") await fs.promises.unlink(item.path);
|
|
||||||
else await fs.promises.rm(item.path, { recursive: true, force: true });
|
|
||||||
removed.push(item.id);
|
|
||||||
bytes += item.bytes;
|
|
||||||
} catch {
|
|
||||||
failed.push(item.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { removed, bytes, failed };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
||||||
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
||||||
@@ -1025,7 +870,7 @@ export function handOff(child, pre) {
|
|||||||
|
|
||||||
/* ----------------------------------------------------------- patch merge */
|
/* ----------------------------------------------------------- patch merge */
|
||||||
|
|
||||||
const APPEND_KEYS = new Set(["thread"]);
|
const APPEND_KEYS = new Set(["thread", "comments"]);
|
||||||
|
|
||||||
function isPlainObject(v) {
|
function isPlainObject(v) {
|
||||||
return v !== null && typeof v === "object" && !Array.isArray(v);
|
return v !== null && typeof v === "object" && !Array.isArray(v);
|
||||||
@@ -1050,7 +895,7 @@ function mergeOne(target, patch, where) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
||||||
// Named fields are replaced whole; thread appends.
|
// Named fields are replaced whole; thread/comments append.
|
||||||
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||||
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
||||||
for (const entry of patchList) {
|
for (const entry of patchList) {
|
||||||
@@ -1109,60 +954,11 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
|||||||
return merged;
|
return merged;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
|
|
||||||
// borrow the shape of the replies and doc blocks they also write, so `from` /
|
|
||||||
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
|
|
||||||
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
|
|
||||||
// at all is refused. The person's own notes are recorded by the server when
|
|
||||||
// they send, so an agent that echoes one back is not shown it twice.
|
|
||||||
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
|
|
||||||
|
|
||||||
function normalizeThreads(patchList, currentItems) {
|
|
||||||
return patchList.map((entry) => {
|
|
||||||
if (!isPlainObject(entry) || entry.thread == null) return entry;
|
|
||||||
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
|
|
||||||
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
|
|
||||||
const said = new Set(
|
|
||||||
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
|
|
||||||
);
|
|
||||||
const thread = [];
|
|
||||||
for (const m of entry.thread) {
|
|
||||||
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
|
|
||||||
guard(m, "thread");
|
|
||||||
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
|
|
||||||
if (!key) {
|
|
||||||
throw new Error(
|
|
||||||
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const { from, role, md, body, content, ...rest } = m;
|
|
||||||
const who = (m.who || from || role) === "user" ? "user" : "agent";
|
|
||||||
const text = m[key];
|
|
||||||
if (who === "user" && said.has(text.trim())) continue;
|
|
||||||
thread.push({ ...rest, who, text });
|
|
||||||
}
|
|
||||||
return { ...entry, thread };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
||||||
|
|
||||||
// Blocks merge by id like docs do, so a patch that only settles a block's
|
// Blocks merge by id like docs do, so a patch that only settles a block's
|
||||||
// state keeps its text. Blocks left out of the patch stay as they are.
|
// state keeps its text. Blocks left out of the patch stay as they are.
|
||||||
function mergeDocs(current, patchList) {
|
function mergeDocs(current, patchList) {
|
||||||
// A doc's version only moves forward. One going back is a stale or copied
|
|
||||||
// payload (last phase's progress script, say), and the page would quietly
|
|
||||||
// show the old content under the new run's name.
|
|
||||||
for (const entry of patchList) {
|
|
||||||
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
|
|
||||||
const prev = (current || []).find((d) => d && d.id === entry.id);
|
|
||||||
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
|
|
||||||
throw new Error(
|
|
||||||
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
|
|
||||||
"Versions only go up: bump it, and check the payload is the current one."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
||||||
for (const entry of patchList) {
|
for (const entry of patchList) {
|
||||||
if (!Array.isArray(entry.blocks)) continue;
|
if (!Array.isArray(entry.blocks)) continue;
|
||||||
@@ -1199,19 +995,12 @@ export function applyPatch(state, patch) {
|
|||||||
break;
|
break;
|
||||||
case "items":
|
case "items":
|
||||||
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
||||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
|
next.items = dropStaleSubmissions(next.items, state.items, v);
|
||||||
break;
|
break;
|
||||||
case "topics":
|
case "topics":
|
||||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||||
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
||||||
break;
|
break;
|
||||||
case "helpers":
|
|
||||||
// The agent's report of its helpers, for the page's Subagents tab.
|
|
||||||
// Only `post` writes it; the server's /submit never touches it.
|
|
||||||
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
|
|
||||||
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
|
|
||||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
|
||||||
break;
|
|
||||||
case "docs":
|
case "docs":
|
||||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||||
next.docs = mergeDocs(next.docs, v);
|
next.docs = mergeDocs(next.docs, v);
|
||||||
@@ -1258,11 +1047,15 @@ function stampTimes(before, next) {
|
|||||||
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
||||||
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
||||||
}
|
}
|
||||||
if (Array.isArray(next.items)) {
|
for (const list of [next.items, next.docs]) {
|
||||||
for (const entry of next.items) {
|
if (!Array.isArray(list)) continue;
|
||||||
|
for (const entry of list) {
|
||||||
if (Array.isArray(entry.thread)) {
|
if (Array.isArray(entry.thread)) {
|
||||||
for (const m of entry.thread) if (!m.at) m.at = now;
|
for (const m of entry.thread) if (!m.at) m.at = now;
|
||||||
}
|
}
|
||||||
|
if (Array.isArray(entry.comments)) {
|
||||||
|
for (const m of entry.comments) if (!m.at) m.at = now;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Array.isArray(next.docs)) {
|
if (Array.isArray(next.docs)) {
|
||||||
@@ -1495,10 +1288,7 @@ export function validate(state) {
|
|||||||
// server's record of an answer someone pressed Send on; if their own words
|
// server's record of an answer someone pressed Send on; if their own words
|
||||||
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
||||||
// would be rejected and the session would wedge with no way out.
|
// would be rejected and the session would wedge with no way out.
|
||||||
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
|
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
|
||||||
...rest,
|
|
||||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
|
||||||
}));
|
|
||||||
const prose =
|
const prose =
|
||||||
JSON.stringify(authored) +
|
JSON.stringify(authored) +
|
||||||
JSON.stringify(state.docs || []) +
|
JSON.stringify(state.docs || []) +
|
||||||
@@ -1506,20 +1296,6 @@ export function validate(state) {
|
|||||||
JSON.stringify(state.menu || {});
|
JSON.stringify(state.menu || {});
|
||||||
problems.push(...proseProblems(prose));
|
problems.push(...proseProblems(prose));
|
||||||
|
|
||||||
// The agent's report of its helpers: the shape the page draws from
|
|
||||||
// (subagents.js), then the same prose scan as everything else it writes.
|
|
||||||
if (state.helpers != null) {
|
|
||||||
problems.push(...checkHelpers(state.helpers));
|
|
||||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
|
||||||
if (!isPlainObject(helper)) continue;
|
|
||||||
for (const field of ["title", "ask", "result"]) {
|
|
||||||
if (typeof helper[field] === "string") {
|
|
||||||
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return problems;
|
return problems;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1549,8 +1325,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
|||||||
* A resume that passes through the dashboard (a finished skill going back to
|
* A resume that passes through the dashboard (a finished skill going back to
|
||||||
* it, or a launch from its menu) is a new skill taking the page over, so it
|
* it, or a launch from its menu) is a new skill taking the page over, so it
|
||||||
* starts from a blank page: the last skill's questions, sections, docs,
|
* starts from a blank page: the last skill's questions, sections, docs,
|
||||||
* helpers, headline and ending are its record on disk, not the next skill's
|
* headline and ending are its record on disk, not the next skill's opening.
|
||||||
* opening.
|
|
||||||
* Only the session's identity carries across. `workspace.json`,
|
* Only the session's identity carries across. `workspace.json`,
|
||||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||||
* and the meter outlive every hop.
|
* and the meter outlive every hop.
|
||||||
@@ -1577,8 +1352,6 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
|
|||||||
// workspace.json the server. Folders, version, change log, missing, remote.
|
// workspace.json the server. Folders, version, change log, missing, remote.
|
||||||
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
||||||
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
||||||
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
|
|
||||||
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
|
|
||||||
export const CHAT_FILE = "chat.ndjson";
|
export const CHAT_FILE = "chat.ndjson";
|
||||||
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
||||||
export const WORKSPACE_FILE = "workspace.json";
|
export const WORKSPACE_FILE = "workspace.json";
|
||||||
@@ -1846,125 +1619,17 @@ export function readWorkspace(dir) {
|
|||||||
return readJson(path.join(dir, WORKSPACE_FILE), null);
|
return readJson(path.join(dir, WORKSPACE_FILE), null);
|
||||||
}
|
}
|
||||||
|
|
||||||
// A fresh workspace: the original folder, named after itself, plus whatever
|
// A fresh workspace: just the original folder, named after itself.
|
||||||
// was remembered for this folder and spec (rememberedWorkspace() below).
|
export function initialWorkspace(worktree) {
|
||||||
export function initialWorkspace(worktree, remembered = null) {
|
|
||||||
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
|
|
||||||
if (remembered && remembered.original) {
|
|
||||||
if (remembered.original.name) original.name = remembered.original.name;
|
|
||||||
if (remembered.original.description) original.description = remembered.original.description;
|
|
||||||
}
|
|
||||||
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
|
|
||||||
id: "f" + (i + 1),
|
|
||||||
path: f.path,
|
|
||||||
name: f.name,
|
|
||||||
description: f.description || "",
|
|
||||||
...(f.nested ? { nested: true } : {}),
|
|
||||||
}));
|
|
||||||
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------ remembered workspaces */
|
|
||||||
|
|
||||||
// The folder list outlives the console session: one file for the person,
|
|
||||||
// beside looks.json, keyed by the folder a session runs in and then by spec.
|
|
||||||
// Never under specs/: the paths are this machine's, and the server never
|
|
||||||
// writes into a project.
|
|
||||||
//
|
|
||||||
// { "projects": { "<folded worktree>": {
|
|
||||||
// "path": "<worktree>",
|
|
||||||
// "project": { original, folders, at }, // no spec picked
|
|
||||||
// "specs": { "specs/<name>": { original, folders, at } } } } }
|
|
||||||
//
|
|
||||||
// `original` holds the first folder's name and description only (its path is
|
|
||||||
// always the session's own); `folders` the added ones as { path, name,
|
|
||||||
// description, nested? }. Two writers, the server on every change and
|
|
||||||
// `console.mjs forget`, each a read-modify-write of one key.
|
|
||||||
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
|
|
||||||
|
|
||||||
const foldKey = (p) => {
|
|
||||||
const resolved = path.resolve(String(p || ""));
|
|
||||||
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
|
|
||||||
};
|
|
||||||
|
|
||||||
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
|
|
||||||
export function specKey(specDir) {
|
|
||||||
return String(specDir || "")
|
|
||||||
.trim()
|
|
||||||
.replace(/\\/g, "/")
|
|
||||||
.replace(/^\.\//, "")
|
|
||||||
.replace(/\/+$/, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function readStore() {
|
|
||||||
const saved = readJson(WORKSPACES_FILE, null);
|
|
||||||
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What was remembered for this folder and spec: `{ entry, from }`, where
|
|
||||||
* `from` is "spec" when the spec has its own list, "project" when it falls
|
|
||||||
* back to the project's (a spec's list starts as a copy of it), and null
|
|
||||||
* when nothing was ever saved.
|
|
||||||
*/
|
|
||||||
export function rememberedWorkspace(worktree, specDir) {
|
|
||||||
const project = readStore().projects[foldKey(worktree)];
|
|
||||||
if (!project) return { entry: null, from: null };
|
|
||||||
const spec = specKey(specDir);
|
|
||||||
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
|
|
||||||
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
|
|
||||||
}
|
|
||||||
|
|
||||||
// The workspace's folders as the store keeps them.
|
|
||||||
export function rememberable(ws) {
|
|
||||||
const folders = (ws && ws.folders) || [];
|
|
||||||
const first = folders.find((f) => f.original) || {};
|
|
||||||
return {
|
return {
|
||||||
original: { name: first.name || "", description: first.description || "" },
|
version: 0,
|
||||||
folders: folders
|
folders: [{ id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }],
|
||||||
.filter((f) => !f.original)
|
missing: [],
|
||||||
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
|
changes: [],
|
||||||
at: nowIso(),
|
remote: "",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Every server and `console.mjs forget` writes the one file, so each
|
|
||||||
// read-modify-write holds this lock beside it.
|
|
||||||
const WORKSPACES_LOCK = "workspaces.json.lock";
|
|
||||||
|
|
||||||
// Save the list for this folder and spec ("" for the project's own).
|
|
||||||
export function rememberWorkspace(worktree, specDir, ws) {
|
|
||||||
ensureDir(path.dirname(WORKSPACES_FILE));
|
|
||||||
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveRemembered(worktree, specDir, ws) {
|
|
||||||
const store = readStore();
|
|
||||||
const key = foldKey(worktree);
|
|
||||||
const project = store.projects[key] || { path: path.resolve(worktree) };
|
|
||||||
const spec = specKey(specDir);
|
|
||||||
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
|
|
||||||
else project.project = rememberable(ws);
|
|
||||||
store.projects[key] = project;
|
|
||||||
writeJsonAtomic(WORKSPACES_FILE, store);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
|
|
||||||
export function forgetWorkspace(worktree, specDir) {
|
|
||||||
const spec = specKey(specDir);
|
|
||||||
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
|
|
||||||
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
|
|
||||||
}
|
|
||||||
|
|
||||||
function dropRemembered(worktree, spec) {
|
|
||||||
const store = readStore();
|
|
||||||
const project = store.projects[foldKey(worktree)];
|
|
||||||
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
|
|
||||||
delete project.specs[spec];
|
|
||||||
writeJsonAtomic(WORKSPACES_FILE, store);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only server.mjs may call this.
|
// Single-writer rule: only server.mjs may call this.
|
||||||
export function writeWorkspace(dir, ws) {
|
export function writeWorkspace(dir, ws) {
|
||||||
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
|
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
|
||||||
@@ -2034,98 +1699,6 @@ export function pendingWorkspaceChanges(dir) {
|
|||||||
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------ the Subagents switch */
|
|
||||||
|
|
||||||
// The person's Subagents switch, remembered per project folder and workflow:
|
|
||||||
//
|
|
||||||
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
|
|
||||||
//
|
|
||||||
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
|
|
||||||
// workflow's shipped default.
|
|
||||||
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
|
|
||||||
const SUBAGENTS_LOCK = "subagents.json.lock";
|
|
||||||
|
|
||||||
function readSubagentStore() {
|
|
||||||
const saved = readJson(SUBAGENTS_FILE, null);
|
|
||||||
return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
|
||||||
}
|
|
||||||
|
|
||||||
// The saved `{ on, instruction, max }` for this folder and workflow, or the
|
|
||||||
// default's when nothing (or something malformed) is saved.
|
|
||||||
export function subagentStoreEntry(worktree, workflow) {
|
|
||||||
const { on, instruction, max } = defaultSetting(workflow);
|
|
||||||
const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null;
|
|
||||||
const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null;
|
|
||||||
return saved && !saved.error ? saved : { on, instruction, max };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only server.mjs may call this.
|
|
||||||
export function saveSubagentStoreEntry(worktree, workflow, value) {
|
|
||||||
ensureDir(path.dirname(SUBAGENTS_FILE));
|
|
||||||
withStateLock(
|
|
||||||
path.dirname(SUBAGENTS_FILE),
|
|
||||||
() => {
|
|
||||||
const store = readSubagentStore();
|
|
||||||
const key = foldKey(worktree);
|
|
||||||
const project = store[key] && typeof store[key] === "object" ? store[key] : {};
|
|
||||||
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } };
|
|
||||||
writeJsonAtomic(SUBAGENTS_FILE, store);
|
|
||||||
},
|
|
||||||
SUBAGENTS_LOCK
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
|
||||||
|
|
||||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
|
||||||
|
|
||||||
// This session's switch, `{ workflow, on, instruction, max, revision }`, or
|
|
||||||
// null when there is none or it is malformed.
|
|
||||||
export function readSubagentSetting(dir) {
|
|
||||||
const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null);
|
|
||||||
if (!s || typeof s !== "object") return null;
|
|
||||||
if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null;
|
|
||||||
return s;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only server.mjs may call this. The revision never goes
|
|
||||||
// backwards within a session.
|
|
||||||
export function writeSubagentSetting(dir, setting) {
|
|
||||||
const previous = readSubagentSetting(dir);
|
|
||||||
const revision = Math.max(previous ? previous.revision : 0, setting.revision);
|
|
||||||
return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision });
|
|
||||||
}
|
|
||||||
|
|
||||||
export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json";
|
|
||||||
const CURSOR_STATES = new Set(["none", "on", "off"]);
|
|
||||||
|
|
||||||
// What the agent was last told: `{ revision, state }`.
|
|
||||||
export function readSubagentCursor(dir) {
|
|
||||||
const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null);
|
|
||||||
if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" };
|
|
||||||
return { revision: saved.revision, state: saved.state };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only console.mjs may call this. Never backwards, like
|
|
||||||
// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one.
|
|
||||||
export function writeSubagentCursor(dir, cursor) {
|
|
||||||
const old = readSubagentCursor(dir);
|
|
||||||
const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state };
|
|
||||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The one place the cursor may go back: `open`, which starts a fresh agent.
|
|
||||||
export function resetSubagentCursor(dir) {
|
|
||||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// The `caps` of the last `open` event: what the agent's console copy can do.
|
|
||||||
export function latestOpenCaps(dir) {
|
|
||||||
const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open");
|
|
||||||
const last = opens[opens.length - 1];
|
|
||||||
return last && Array.isArray(last.caps) ? last.caps : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flag the case where the link cannot be opened by the person it is for.
|
* Flag the case where the link cannot be opened by the person it is for.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
|
|||||||
if (!s || typeof s !== "object") return null;
|
if (!s || typeof s !== "object") return null;
|
||||||
if (item.answer && typeof item.answer === "object") return null;
|
if (item.answer && typeof item.answer === "object") return null;
|
||||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||||
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
|
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||||
return replied ? null : s;
|
return replied ? null : s;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,33 +74,17 @@ export function submittedAwaiting(item) {
|
|||||||
* agent has yet to say anything after it. The server records it as `sentNote`
|
* agent has yet to say anything after it. The server records it as `sentNote`
|
||||||
* on every send, so the page can show it in the Notes pane and in the Sent
|
* on every send, so the page can show it in the Notes pane and in the Sent
|
||||||
* box instead of letting it vanish into a send that shows no sign of arriving.
|
* box instead of letting it vanish into a send that shows no sign of arriving.
|
||||||
* Any agent message from the send onwards, or one with no clock to compare,
|
* Any thread message from the send onwards, or none with a clock to compare,
|
||||||
* means it has been picked up. The person's own entries never count: the
|
* means it has been picked up.
|
||||||
* server writes their note into the thread as it arrives.
|
|
||||||
*/
|
*/
|
||||||
export function noteAwaiting(item) {
|
export function noteAwaiting(item) {
|
||||||
const n = item && item.sentNote;
|
const n = item && item.sentNote;
|
||||||
if (!n || typeof n !== "object") return null;
|
if (!n || typeof n !== "object") return null;
|
||||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||||
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
|
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
|
||||||
return picked ? null : n;
|
return picked ? null : n;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Who said a thread entry and what they said. The contract is `{ who, text }`
|
|
||||||
* and the server lifts anything else into it, but sessions written before that
|
|
||||||
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
|
|
||||||
*/
|
|
||||||
export function threadWho(m) {
|
|
||||||
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
|
|
||||||
}
|
|
||||||
|
|
||||||
export function threadText(m) {
|
|
||||||
if (!m) return "";
|
|
||||||
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/* -------------------------------------------------------------- labels */
|
/* -------------------------------------------------------------- labels */
|
||||||
|
|
||||||
export function optionLabel(item, k) {
|
export function optionLabel(item, k) {
|
||||||
|
|||||||
@@ -23,9 +23,6 @@
|
|||||||
--warn-soft: #fbe7e3;
|
--warn-soft: #fbe7e3;
|
||||||
--focus: #1f6feb;
|
--focus: #1f6feb;
|
||||||
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
||||||
/* A soft accent halo for the things that want noticing: the update banner
|
|
||||||
and an enabled Send. Built from --accent, so a picked accent glows too. */
|
|
||||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
|
|
||||||
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||||
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
||||||
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
||||||
@@ -64,7 +61,6 @@
|
|||||||
--warn-soft: #34201d;
|
--warn-soft: #34201d;
|
||||||
--focus: #6aa3ff;
|
--focus: #6aa3ff;
|
||||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +85,6 @@
|
|||||||
--warn-soft: #34201d;
|
--warn-soft: #34201d;
|
||||||
--focus: #6aa3ff;
|
--focus: #6aa3ff;
|
||||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
* { box-sizing: border-box; }
|
* { box-sizing: border-box; }
|
||||||
@@ -208,26 +203,6 @@ body {
|
|||||||
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
||||||
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||||
|
|
||||||
/* Subagents: an orchestrator and its helpers. Unlit is a hollow outline in
|
|
||||||
the quiet ink; lit fills the nodes with the highlight color. */
|
|
||||||
.subagents-btn { border-color: var(--rule-2); color: var(--ink-2); display: inline-flex; align-items: center; justify-content: center; }
|
|
||||||
.btn.subagents-btn { padding: 0 6px; align-self: stretch; }
|
|
||||||
.subagents-btn[hidden] { display: none; }
|
|
||||||
.subagents-btn svg { width: 16px; height: 16px; display: block; }
|
|
||||||
.subagents-btn .sa-link { fill: none; stroke: var(--ink-2); stroke-width: 1.2; stroke-linecap: round; }
|
|
||||||
.subagents-btn .sa-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
|
|
||||||
.subagents-btn .sa-node { fill: none; stroke: var(--ink-2); stroke-width: 1.2; }
|
|
||||||
.subagents-btn[aria-pressed="true"] .sa-hub,
|
|
||||||
.subagents-btn[aria-pressed="true"] .sa-node { fill: var(--accent); stroke: var(--accent); }
|
|
||||||
.subagents-btn[aria-pressed="true"] .sa-link { stroke: var(--accent); }
|
|
||||||
.subagents-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
|
||||||
.subagents-btn:hover:not(:disabled) .sa-link,
|
|
||||||
.subagents-btn:hover:not(:disabled) .sa-hub,
|
|
||||||
.subagents-btn:hover:not(:disabled) .sa-node { stroke: var(--accent); }
|
|
||||||
.subagents-btn:disabled .sa-link,
|
|
||||||
.subagents-btn:disabled .sa-hub,
|
|
||||||
.subagents-btn:disabled .sa-node { stroke: var(--ink-3); fill: none; }
|
|
||||||
|
|
||||||
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
||||||
|
|
||||||
/* The session meter: a ring that fills with the points and a few words, in
|
/* The session meter: a ring that fills with the points and a few words, in
|
||||||
@@ -1121,15 +1096,6 @@ h1 {
|
|||||||
.ask-disabled-note.is-limit, .ask-disabled-note.is-waiting { color: var(--ink-2); background: var(--panel-2); border: 1px solid var(--rule); }
|
.ask-disabled-note.is-limit, .ask-disabled-note.is-waiting { color: var(--ink-2); background: var(--panel-2); border: 1px solid var(--rule); }
|
||||||
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
||||||
|
|
||||||
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
|
|
||||||
the tiny ring, left of the label. The extra .spinner is for specificity:
|
|
||||||
.spinner.tiny comes later and zeroes the margin otherwise. */
|
|
||||||
.view-tab .spinner.tab-spin {
|
|
||||||
display: inline-block;
|
|
||||||
margin-right: 7px;
|
|
||||||
vertical-align: -1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* A reply landed while another tab was open. */
|
/* A reply landed while another tab was open. */
|
||||||
.view-tab .tab-dot {
|
.view-tab .tab-dot {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
@@ -1450,30 +1416,6 @@ h1 {
|
|||||||
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
||||||
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
||||||
|
|
||||||
/* The Subagents tab: one row per reported helper, newest state in a pill. */
|
|
||||||
.sa-card h2 { margin: 0 0 6px; }
|
|
||||||
.sa-card > .help { margin: 0 0 16px; }
|
|
||||||
.sa-alone { margin: 0; color: var(--ink-2); }
|
|
||||||
.sa-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
|
|
||||||
.sa-row { border: 1px solid var(--rule); border-radius: 8px; background: var(--panel-2); padding: 12px 14px; }
|
|
||||||
.sa-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
|
||||||
.sa-title { min-width: 0; overflow-wrap: anywhere; }
|
|
||||||
.sa-ask {
|
|
||||||
margin: 4px 0 0; color: var(--ink-2); font-size: 13.5px;
|
|
||||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
|
|
||||||
}
|
|
||||||
.sa-result { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
|
||||||
.sa-pill { display: inline-flex; align-items: center; gap: 6px; flex: none; }
|
|
||||||
.sa-pill.is-running { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
|
|
||||||
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
|
|
||||||
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
|
|
||||||
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
|
|
||||||
/* The dialog's number box, themed like the page's other inputs. */
|
|
||||||
.subagents input[type="number"] {
|
|
||||||
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
|
|
||||||
border: 1px solid var(--rule-2); border-radius: 6px; padding: 4px 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------ settled answer */
|
/* ------------------------------------------------------ settled answer */
|
||||||
|
|
||||||
.answered {
|
.answered {
|
||||||
@@ -1707,13 +1649,11 @@ input[type="text"].invalid { border-color: var(--warn); }
|
|||||||
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||||
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
||||||
/* Send glows and breathes while there is something to send: the steady
|
/* Send breathes while there is something to send: a soft accent ring that
|
||||||
--glow, plus a soft accent ring that spreads and fades. The ring is off
|
spreads and fades. Off under reduced motion, below. */
|
||||||
under reduced motion, below; the glow stays. */
|
|
||||||
#btn-send:not(:disabled) { box-shadow: var(--glow); }
|
|
||||||
@keyframes send-pulse {
|
@keyframes send-pulse {
|
||||||
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
|
0% { box-shadow: 0 0 0 0 var(--accent-line); }
|
||||||
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
|
100% { box-shadow: 0 0 0 6px transparent; }
|
||||||
}
|
}
|
||||||
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
||||||
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
||||||
@@ -2015,8 +1955,6 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.footer-where:hover { text-decoration: underline; }
|
.footer-where:hover { text-decoration: underline; }
|
||||||
/* The project name, in the person's highlight color. */
|
|
||||||
.where-project { color: var(--accent); font-weight: 600; }
|
|
||||||
/* A folder is missing or the agent could not read one: the dialog says which. */
|
/* A folder is missing or the agent could not read one: the dialog says which. */
|
||||||
.where-alert {
|
.where-alert {
|
||||||
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
||||||
@@ -2059,18 +1997,6 @@ kbd {
|
|||||||
}
|
}
|
||||||
.waiting-pane h2 { font: 600 23px/1.3 var(--serif); color: var(--ink); margin: 0; }
|
.waiting-pane h2 { font: 600 23px/1.3 var(--serif); color: var(--ink); margin: 0; }
|
||||||
.waiting-pane p { margin: 0; }
|
.waiting-pane p { margin: 0; }
|
||||||
/* The words that open the tasks tab: bold in the highlight color, a button
|
|
||||||
that reads as part of the sentence. */
|
|
||||||
.waiting-jump {
|
|
||||||
font: inherit;
|
|
||||||
font-weight: 700;
|
|
||||||
color: var(--accent);
|
|
||||||
background: none;
|
|
||||||
border: 0;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
button.waiting-jump { cursor: pointer; text-decoration: underline; text-decoration-color: var(--accent-line); text-underline-offset: 3px; }
|
|
||||||
button.waiting-jump:hover { text-decoration-color: var(--accent); }
|
|
||||||
/* Once the work is under way Planny steps back a size, and the ring in
|
/* Once the work is under way Planny steps back a size, and the ring in
|
||||||
front of the stage name carries the "still going" signal instead. */
|
front of the stage name carries the "still going" signal instead. */
|
||||||
.waiting-pane .pose-stage { height: 130px; transition: height 0.35s ease; }
|
.waiting-pane .pose-stage { height: 130px; transition: height 0.35s ease; }
|
||||||
@@ -2273,7 +2199,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
.modal.help[open] { display: flex; }
|
.modal.help[open] { display: flex; }
|
||||||
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
||||||
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
||||||
.help-version a { color: inherit; }
|
|
||||||
|
|
||||||
.help-layout {
|
.help-layout {
|
||||||
display: grid;
|
display: grid;
|
||||||
@@ -2580,9 +2505,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
actions stay put. */
|
actions stay put. */
|
||||||
.modal.workspace { max-width: 680px; }
|
.modal.workspace { max-width: 680px; }
|
||||||
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
||||||
.workspace .modal-blurb { margin-bottom: 6px; }
|
|
||||||
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
|
|
||||||
|
|
||||||
.workspace-list {
|
.workspace-list {
|
||||||
list-style: none; margin: 0; padding: 0;
|
list-style: none; margin: 0; padding: 0;
|
||||||
display: grid; gap: 12px;
|
display: grid; gap: 12px;
|
||||||
@@ -2723,74 +2645,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
border-left-width: 4px;
|
border-left-width: 4px;
|
||||||
color: var(--ink);
|
color: var(--ink);
|
||||||
}
|
}
|
||||||
/* A newer release: the same slot, in the accent, with the label as the way
|
|
||||||
into the update modal and a small × that hides it for this session. */
|
|
||||||
.dash-nudge.update-banner {
|
|
||||||
position: relative;
|
|
||||||
padding-left: 40px;
|
|
||||||
padding-right: 40px;
|
|
||||||
border-left-width: 4px;
|
|
||||||
border-left-color: var(--accent-line);
|
|
||||||
color: var(--ink);
|
|
||||||
box-shadow: var(--glow);
|
|
||||||
}
|
|
||||||
.update-banner-open {
|
|
||||||
flex: 1 1 16em;
|
|
||||||
padding: 0;
|
|
||||||
border: 0;
|
|
||||||
background: none;
|
|
||||||
color: inherit;
|
|
||||||
font: inherit;
|
|
||||||
font-weight: 600;
|
|
||||||
letter-spacing: 0.02em;
|
|
||||||
text-align: center;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.update-banner-open:hover { text-decoration: underline; }
|
|
||||||
/* Pinned to the right edge, out of the flow, so the label centres on the
|
|
||||||
whole banner rather than on what the × leaves of it. */
|
|
||||||
.update-banner-dismiss {
|
|
||||||
position: absolute;
|
|
||||||
top: 50%;
|
|
||||||
right: 10px;
|
|
||||||
transform: translateY(-50%);
|
|
||||||
padding: 0 6px;
|
|
||||||
border: 0;
|
|
||||||
border-radius: var(--radius);
|
|
||||||
background: none;
|
|
||||||
color: inherit;
|
|
||||||
font: inherit;
|
|
||||||
font-size: 16px;
|
|
||||||
line-height: 1;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.update-banner-dismiss:hover { background: var(--accent-line); }
|
|
||||||
/* Wide enough that the update command sits on one line beside Copy; a
|
|
||||||
narrow window still wraps it rather than overflowing. */
|
|
||||||
#update-modal { max-width: 720px; }
|
|
||||||
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
|
|
||||||
.update-steps li { margin: 4px 0; }
|
|
||||||
/* The hand-off copy row, in the modal's first step: the command and its Copy
|
|
||||||
side by side. */
|
|
||||||
.update-command {
|
|
||||||
margin: 6px 0 4px;
|
|
||||||
display: flex;
|
|
||||||
align-items: stretch;
|
|
||||||
gap: 10px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
}
|
|
||||||
.update-command code {
|
|
||||||
flex: 1 1 260px;
|
|
||||||
min-width: 0;
|
|
||||||
font: 13px/1.5 var(--mono);
|
|
||||||
color: var(--ink);
|
|
||||||
background: var(--panel);
|
|
||||||
border: 1px solid var(--rule-2);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 10px 12px;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
||||||
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
||||||
.dash-working {
|
.dash-working {
|
||||||
@@ -3275,6 +3129,11 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
0%, 15%, 75%, 100% { transform: scale(1); opacity: 0.16; }
|
0%, 15%, 75%, 100% { transform: scale(1); opacity: 0.16; }
|
||||||
45% { transform: scale(0.7); opacity: 0.08; }
|
45% { transform: scale(0.7); opacity: 0.08; }
|
||||||
}
|
}
|
||||||
|
.pose .fz-halo { opacity: 0.25; animation: fz-halo 1.6s ease-in-out infinite; }
|
||||||
|
@keyframes fz-halo {
|
||||||
|
0%, 100% { transform: scale(1); opacity: 0.2; }
|
||||||
|
45% { transform: scale(1.3); opacity: 0.4; }
|
||||||
|
}
|
||||||
.pose .fz-tick { stroke: var(--accent-ink); }
|
.pose .fz-tick { stroke: var(--accent-ink); }
|
||||||
.pose .fz-flag { transform-origin: 0% 50%; animation: fz-wave 1.2s ease-in-out infinite; }
|
.pose .fz-flag { transform-origin: 0% 50%; animation: fz-wave 1.2s ease-in-out infinite; }
|
||||||
@keyframes fz-wave {
|
@keyframes fz-wave {
|
||||||
@@ -3517,18 +3376,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||||
.models-actions .help.error { color: var(--danger, #d64545); }
|
.models-actions .help.error { color: var(--danger, #d64545); }
|
||||||
|
|
||||||
/* User Preferences: Cleanup's list of what would go, shown before anything
|
|
||||||
is deleted. */
|
|
||||||
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
|
|
||||||
.cleanup-list:empty { display: none; }
|
|
||||||
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
|
|
||||||
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
|
|
||||||
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
|
|
||||||
.cleanup-size { flex: none; color: var(--ink-3); }
|
|
||||||
.cleanup-more { display: grid; gap: 4px; }
|
|
||||||
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
|
|
||||||
#cleanup-delete[hidden] { display: none; }
|
|
||||||
|
|
||||||
/* A word the person has to type, bold and in their highlight color so it
|
/* A word the person has to type, bold and in their highlight color so it
|
||||||
does not get lost in the status sentence. */
|
does not get lost in the status sentence. */
|
||||||
.agent-key {
|
.agent-key {
|
||||||
|
|||||||
@@ -66,8 +66,6 @@ import {
|
|||||||
submittedAwaiting,
|
submittedAwaiting,
|
||||||
noteAwaiting,
|
noteAwaiting,
|
||||||
suggestionFrom,
|
suggestionFrom,
|
||||||
threadText,
|
|
||||||
threadWho,
|
|
||||||
THUMB_EDGE,
|
THUMB_EDGE,
|
||||||
turnGate,
|
turnGate,
|
||||||
verdictText,
|
verdictText,
|
||||||
@@ -103,15 +101,6 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
|
|||||||
import { RED_BANNER } from "./meter.js";
|
import { RED_BANNER } from "./meter.js";
|
||||||
import { applyMention, matchNames, mentionAt } from "./mentions.js";
|
import { applyMention, matchNames, mentionAt } from "./mentions.js";
|
||||||
import { faviconState, setFavicon } from "./favicon.js";
|
import { faviconState, setFavicon } from "./favicon.js";
|
||||||
import {
|
|
||||||
CHECKIN_LINE,
|
|
||||||
PATHFINDER_RESEARCH_LINE,
|
|
||||||
defaultInstruction,
|
|
||||||
helperRows,
|
|
||||||
showSwitch,
|
|
||||||
showTab,
|
|
||||||
switchLabel,
|
|
||||||
} from "./subagents.js";
|
|
||||||
|
|
||||||
const $ = (id) => document.getElementById(id);
|
const $ = (id) => document.getElementById(id);
|
||||||
|
|
||||||
@@ -457,10 +446,6 @@ document.addEventListener("click", (e) => {
|
|||||||
|
|
||||||
|
|
||||||
const GONE_AFTER_MS = 8000;
|
const GONE_AFTER_MS = 8000;
|
||||||
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
|
|
||||||
// wipe an unrelated warning that landed while the page was gone (an upload
|
|
||||||
// failure, a refused send).
|
|
||||||
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
|
|
||||||
const WORKING_GRACE_MS = 5 * 60 * 1000;
|
const WORKING_GRACE_MS = 5 * 60 * 1000;
|
||||||
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
||||||
// listening. The difference is the cost of being wrong: a working agent that
|
// listening. The difference is the cost of being wrong: a working agent that
|
||||||
@@ -536,12 +521,6 @@ let chatFrame = null;
|
|||||||
// sends them.
|
// sends them.
|
||||||
let wsFrame = null;
|
let wsFrame = null;
|
||||||
let meterFrame = null;
|
let meterFrame = null;
|
||||||
// The frame's update ({ installed, latest }), present only when a newer
|
|
||||||
// release is out; null otherwise.
|
|
||||||
let updateFrame = null;
|
|
||||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
|
||||||
// revision }), or null before a server that sends it.
|
|
||||||
let subagentsFrame = null;
|
|
||||||
let chatDot = false;
|
let chatDot = false;
|
||||||
let chatSending = false;
|
let chatSending = false;
|
||||||
let chatResetting = false;
|
let chatResetting = false;
|
||||||
@@ -587,6 +566,7 @@ function fresh() {
|
|||||||
drafts: {},
|
drafts: {},
|
||||||
images: {},
|
images: {},
|
||||||
sent: {},
|
sent: {},
|
||||||
|
sentAt: null,
|
||||||
stopping: null,
|
stopping: null,
|
||||||
afterBuild: null,
|
afterBuild: null,
|
||||||
homeward: null,
|
homeward: null,
|
||||||
@@ -890,14 +870,10 @@ function adopt(body) {
|
|||||||
chatFrame = body.chat || null;
|
chatFrame = body.chat || null;
|
||||||
if (body.workspace) wsFrame = body.workspace;
|
if (body.workspace) wsFrame = body.workspace;
|
||||||
if (body.meter) meterFrame = body.meter;
|
if (body.meter) meterFrame = body.meter;
|
||||||
// Always replaced: an absent key means no update.
|
|
||||||
updateFrame = body.update || null;
|
|
||||||
// Always replaced too: an older server sends none, and then there is no switch.
|
|
||||||
subagentsFrame = body.subagents || null;
|
|
||||||
lastContact = Date.now();
|
lastContact = Date.now();
|
||||||
if (gone) {
|
if (gone) {
|
||||||
gone = false;
|
gone = false;
|
||||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
banner(null);
|
||||||
}
|
}
|
||||||
if (firstLoad) {
|
if (firstLoad) {
|
||||||
load();
|
load();
|
||||||
@@ -1040,9 +1016,7 @@ function adopt(body) {
|
|||||||
render();
|
render();
|
||||||
if ($("workspace-modal").open) renderWorkspace();
|
if ($("workspace-modal").open) renderWorkspace();
|
||||||
tellFolderIssues();
|
tellFolderIssues();
|
||||||
// The Overview tab's file changes under a build, so a tab you are watching
|
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
|
||||||
// refetches on every new frame too, not only on the click that opened it.
|
|
||||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
|
|
||||||
if (announce) showArrival(announce);
|
if (announce) showArrival(announce);
|
||||||
// New entries land at the bottom of the rail. Gliding down to them beats
|
// New entries land at the bottom of the rail. Gliding down to them beats
|
||||||
// leaving the list parked where it was while it grew underneath.
|
// leaving the list parked where it was while it grew underneath.
|
||||||
@@ -1175,12 +1149,15 @@ function markGone() {
|
|||||||
// of the server means there, and a banner promising a reconnect would
|
// of the server means there, and a banner promising a reconnect would
|
||||||
// argue with it.
|
// argue with it.
|
||||||
if (!finish() && !stopInProgress()) {
|
if (!finish() && !stopInProgress()) {
|
||||||
banner(GONE_BANNER, "warn");
|
banner(
|
||||||
|
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
|
||||||
|
"warn"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
render();
|
render();
|
||||||
} else if (!bad && gone) {
|
} else if (!bad && gone) {
|
||||||
gone = false;
|
gone = false;
|
||||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
banner(null);
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1205,6 +1182,7 @@ function connect() {
|
|||||||
} catch {}
|
} catch {}
|
||||||
});
|
});
|
||||||
es.addEventListener("submitted", (e) => {
|
es.addEventListener("submitted", (e) => {
|
||||||
|
local.sentAt = Date.now();
|
||||||
// Drop only what was actually sent.
|
// Drop only what was actually sent.
|
||||||
//
|
//
|
||||||
// This event fires for a send from ANY tab of this session, which is why it
|
// This event fires for a send from ANY tab of this session, which is why it
|
||||||
@@ -1315,7 +1293,6 @@ function render() {
|
|||||||
renderChrome();
|
renderChrome();
|
||||||
renderStatus();
|
renderStatus();
|
||||||
renderBriefButton();
|
renderBriefButton();
|
||||||
renderSubagentsButton();
|
|
||||||
renderStopButton();
|
renderStopButton();
|
||||||
renderHomeButton();
|
renderHomeButton();
|
||||||
tabAdded = renderViews();
|
tabAdded = renderViews();
|
||||||
@@ -1581,7 +1558,7 @@ function renderChrome() {
|
|||||||
renderMeter();
|
renderMeter();
|
||||||
$("title").textContent = S.title || "Session";
|
$("title").textContent = S.title || "Session";
|
||||||
$("badge").textContent = workflowLabel(S.workflow);
|
$("badge").textContent = workflowLabel(S.workflow);
|
||||||
renderTabTitle();
|
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||||
|
|
||||||
const h = S.headline || {};
|
const h = S.headline || {};
|
||||||
// On a finished session an open item is frozen: the send on it counts as
|
// On a finished session an open item is frozen: the send on it counts as
|
||||||
@@ -1822,19 +1799,14 @@ async function sendBrief() {
|
|||||||
reply: briefPhrase(choice.range),
|
reply: briefPhrase(choice.range),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
|
||||||
if (!res.ok) throw new Error(String(res.status));
|
if (!res.ok) throw new Error(String(res.status));
|
||||||
$("brief-modal").close();
|
$("brief-modal").close();
|
||||||
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
||||||
setTimeout(() => banner(null), 5000);
|
setTimeout(() => banner(null), 5000);
|
||||||
pendingResult = true;
|
pendingResult = true;
|
||||||
render();
|
render();
|
||||||
} catch (err) {
|
} catch {
|
||||||
if (err && err.pending) pendingResult = true;
|
why.textContent = "That did not go through. Try again in a moment.";
|
||||||
why.textContent =
|
|
||||||
err && err.pending
|
|
||||||
? "Your last answers are still being picked up. Try again in a moment."
|
|
||||||
: "That did not go through. Try again in a moment.";
|
|
||||||
} finally {
|
} finally {
|
||||||
go.disabled = false;
|
go.disabled = false;
|
||||||
go.textContent = "Write the brief";
|
go.textContent = "Write the brief";
|
||||||
@@ -1850,77 +1822,11 @@ function renderBriefButton() {
|
|||||||
if (offer) btn.disabled = gone || pendingResult;
|
if (offer) btn.disabled = gone || pendingResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shown only where the skill opts in and the agent's console copy can deliver
|
|
||||||
// it. Lit while helpers are on; a click opens the dialog, never toggles.
|
|
||||||
function renderSubagentsButton() {
|
|
||||||
const btn = $("btn-subagents");
|
|
||||||
const offer = showSwitch(subagentsFrame);
|
|
||||||
btn.hidden = !offer;
|
|
||||||
if (!offer) return;
|
|
||||||
const label = switchLabel(subagentsFrame);
|
|
||||||
btn.setAttribute("aria-pressed", String(Boolean(subagentsFrame.on)));
|
|
||||||
btn.title = label;
|
|
||||||
btn.setAttribute("aria-label", label);
|
|
||||||
btn.disabled = gone;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
|
||||||
// instruction is the shipped default, shown as its text so it can be edited.
|
|
||||||
function openSubagents() {
|
|
||||||
if (!showSwitch(subagentsFrame)) return;
|
|
||||||
const on = Boolean(subagentsFrame.on);
|
|
||||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
|
|
||||||
radio.checked = radio.value === (on ? "on" : "off");
|
|
||||||
}
|
|
||||||
$("subagents-instruction").value = subagentsFrame.instruction ?? defaultInstruction(S.workflow);
|
|
||||||
$("subagents-max").value = String(subagentsFrame.max);
|
|
||||||
$("subagents-checkin").textContent = CHECKIN_LINE;
|
|
||||||
const research = $("subagents-research");
|
|
||||||
research.textContent = PATHFINDER_RESEARCH_LINE;
|
|
||||||
research.hidden = S.workflow !== "pathfinder";
|
|
||||||
$("subagents-status").textContent = "";
|
|
||||||
$("subagents-save").disabled = false;
|
|
||||||
$("subagents-modal").showModal();
|
|
||||||
const checked = document.querySelector('input[name="subagents-on"]:checked');
|
|
||||||
if (checked) checked.focus();
|
|
||||||
}
|
|
||||||
|
|
||||||
const SUBAGENTS_ERRORS = {
|
|
||||||
max: "Pick a number from 1 to 20.",
|
|
||||||
"too-long": "The instruction is over 2,000 characters.",
|
|
||||||
"not-offered": "This skill doesn't use helpers.",
|
|
||||||
bad: "That didn't save. Try again.",
|
|
||||||
};
|
|
||||||
const SUBAGENTS_LOST = "Lost contact with Plan2Code. Try again once it's back.";
|
|
||||||
|
|
||||||
async function saveSubagents() {
|
|
||||||
const save = $("subagents-save");
|
|
||||||
const status = $("subagents-status");
|
|
||||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
|
||||||
const text = $("subagents-instruction").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(S.workflow) ? null : text;
|
|
||||||
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
|
|
||||||
save.disabled = true;
|
|
||||||
status.textContent = "";
|
|
||||||
const res = await postJson("/subagents", body);
|
|
||||||
save.disabled = false;
|
|
||||||
// The next state frame redraws the button.
|
|
||||||
if (res.status === 200) return $("subagents-modal").close();
|
|
||||||
if (res.status === 400) status.textContent = SUBAGENTS_ERRORS[res.body && res.body.error] || SUBAGENTS_ERRORS.bad;
|
|
||||||
else if (res.status === 403 || res.status === 0) status.textContent = SUBAGENTS_LOST;
|
|
||||||
else status.textContent = SUBAGENTS_ERRORS.bad;
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderViews() {
|
function renderViews() {
|
||||||
const nav = $("views");
|
const nav = $("views");
|
||||||
nav.replaceChildren();
|
nav.replaceChildren();
|
||||||
// Sent and not yet picked up: the same ring as Ask, until Plan2Code moves on
|
|
||||||
// or goes quiet (a turning ring would pass a dead session for a slow one).
|
|
||||||
const sentBusy = pendingResult && !gone && !agentAdrift();
|
|
||||||
const tabs = [
|
const tabs = [
|
||||||
{ id: "questions", label: isDashboard() ? "Dashboard" : "Questions", count: myTurn().length, busy: sentBusy },
|
{ id: "questions", label: isDashboard() ? "Dashboard" : "Questions", count: myTurn().length },
|
||||||
];
|
];
|
||||||
// Built in rather than posted: present exactly while the spec in view has
|
// Built in rather than posted: present exactly while the spec in view has
|
||||||
// an overview.md. A tab that vanishes under the person sends them home.
|
// an overview.md. A tab that vanishes under the person sends them home.
|
||||||
@@ -1928,30 +1834,12 @@ function renderViews() {
|
|||||||
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
||||||
else if (view === "overview") view = "questions";
|
else if (view === "overview") view = "questions";
|
||||||
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
||||||
// The helpers the agent reported, from the first one on; cleared by a
|
|
||||||
// dashboard hop, which sends the person home like the Overview tab does.
|
|
||||||
if (showTab(subagentsFrame, S.helpers)) {
|
|
||||||
// From the rows the tab draws, so the badge never counts helpers the
|
|
||||||
// working-alone note hides.
|
|
||||||
const running = helperRows(S.helpers).rows.filter((r) => r.state === "running").length;
|
|
||||||
tabs.push({ id: "subagents", label: "Subagents", count: running });
|
|
||||||
} else if (view === "subagents") view = "questions";
|
|
||||||
// Always last, on every workflow and after a finish: the Quick question chat.
|
// Always last, on every workflow and after a finish: the Quick question chat.
|
||||||
// The ring left of "Ask" shows exactly when the conversation's own ring does:
|
tabs.push({ id: "ask", label: "Ask", count: 0, dot: chatDot });
|
||||||
// a question the agent picked up and has not answered yet.
|
|
||||||
const ask = askState();
|
|
||||||
const askBusy = ask.view.rows.some((r) => r.working) && ask.send.state !== "offline" && !agentAdrift();
|
|
||||||
tabs.push({ id: "ask", label: "Ask", count: 0, dot: chatDot, busy: askBusy });
|
|
||||||
|
|
||||||
for (const t of tabs) {
|
for (const t of tabs) {
|
||||||
const b = el("button", "view-tab", t.label);
|
const b = el("button", "view-tab", t.label);
|
||||||
b.type = "button";
|
b.type = "button";
|
||||||
if (t.busy) {
|
|
||||||
const spin = el("span", "spinner tiny tab-spin");
|
|
||||||
spin.setAttribute("aria-hidden", "true");
|
|
||||||
b.prepend(spin);
|
|
||||||
b.title = t.id === "ask" ? "Plan2Code is working on an answer" : "Sent. Waiting for Plan2Code";
|
|
||||||
}
|
|
||||||
b.setAttribute("aria-current", String(view === t.id || (t.id === "questions" && view === "end")));
|
b.setAttribute("aria-current", String(view === t.id || (t.id === "questions" && view === "end")));
|
||||||
if (t.count) {
|
if (t.count) {
|
||||||
const c = el("span", "tab-count", String(t.count));
|
const c = el("span", "tab-count", String(t.count));
|
||||||
@@ -2216,7 +2104,6 @@ function paintMain(main) {
|
|||||||
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
|
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
|
||||||
if (view === "overview") return renderOverview(main);
|
if (view === "overview") return renderOverview(main);
|
||||||
if (view === "ask") return renderAsk(main);
|
if (view === "ask") return renderAsk(main);
|
||||||
if (view === "subagents") return renderSubagents(main);
|
|
||||||
|
|
||||||
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
||||||
// the top of the rail. The hand-off lives here alone now, rather than
|
// the top of the rail. The hand-off lives here alone now, rather than
|
||||||
@@ -2615,51 +2502,6 @@ function roleNudge() {
|
|||||||
return nudge;
|
return nudge;
|
||||||
}
|
}
|
||||||
|
|
||||||
// × on the update banner hides it for this console session only, and only
|
|
||||||
// for the release it named. Blocked storage means "not dismissed".
|
|
||||||
function updateDismissKey() {
|
|
||||||
try {
|
|
||||||
return "p2c-update-dismissed:" + S.sid;
|
|
||||||
} catch {
|
|
||||||
return "p2c-update-dismissed:";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateDismissed() {
|
|
||||||
try {
|
|
||||||
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
|
||||||
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
|
|
||||||
|
|
||||||
function releasesLink(text) {
|
|
||||||
const a = el("a", null, text);
|
|
||||||
a.href = RELEASES_URL;
|
|
||||||
a.target = "_blank";
|
|
||||||
a.rel = "noopener noreferrer";
|
|
||||||
return a;
|
|
||||||
}
|
|
||||||
|
|
||||||
function openUpdateModal() {
|
|
||||||
if (!updateFrame) return;
|
|
||||||
const versions = $("update-versions");
|
|
||||||
versions.replaceChildren(
|
|
||||||
document.createTextNode("Version "),
|
|
||||||
releasesLink("v" + updateFrame.latest),
|
|
||||||
document.createTextNode(" is out — you have "),
|
|
||||||
el("code", null, updateFrame.installed),
|
|
||||||
document.createTextNode(".")
|
|
||||||
);
|
|
||||||
const row = $("update-command");
|
|
||||||
const code = el("code", null, UPDATE_COMMAND);
|
|
||||||
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
|
|
||||||
$("update-modal").showModal();
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderDashboard(main) {
|
function renderDashboard(main) {
|
||||||
maybeWake();
|
maybeWake();
|
||||||
const menu = (S && S.menu) || {};
|
const menu = (S && S.menu) || {};
|
||||||
@@ -2671,25 +2513,6 @@ function renderDashboard(main) {
|
|||||||
warn.setAttribute("role", "status");
|
warn.setAttribute("role", "status");
|
||||||
wrap.appendChild(warn);
|
wrap.appendChild(warn);
|
||||||
}
|
}
|
||||||
// Built here only, so no other workflow's page ever shows it.
|
|
||||||
if (updateFrame && !updateDismissed()) {
|
|
||||||
const notice = el("div", "dash-nudge update-banner");
|
|
||||||
notice.setAttribute("role", "status");
|
|
||||||
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
|
|
||||||
open.type = "button";
|
|
||||||
open.addEventListener("click", openUpdateModal);
|
|
||||||
const dismiss = el("button", "update-banner-dismiss", "×");
|
|
||||||
dismiss.type = "button";
|
|
||||||
dismiss.setAttribute("aria-label", "Dismiss until next time");
|
|
||||||
dismiss.addEventListener("click", () => {
|
|
||||||
try {
|
|
||||||
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
|
|
||||||
} catch {}
|
|
||||||
render();
|
|
||||||
});
|
|
||||||
notice.append(open, dismiss);
|
|
||||||
wrap.appendChild(notice);
|
|
||||||
}
|
|
||||||
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
||||||
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
||||||
if (typeof menu.note === "string" && menu.note.trim()) {
|
if (typeof menu.note === "string" && menu.note.trim()) {
|
||||||
@@ -2719,7 +2542,6 @@ function renderDashboard(main) {
|
|||||||
const specs = specList();
|
const specs = specList();
|
||||||
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
|
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
|
||||||
wrap.appendChild(hideUnavailableToggle());
|
wrap.appendChild(hideUnavailableToggle());
|
||||||
if (!local.launching && !launchScoping) syncWorkspaceScope();
|
|
||||||
|
|
||||||
// "Unavailable" is the scan's verdict for the selected spec, not the
|
// "Unavailable" is the scan's verdict for the selected spec, not the
|
||||||
// momentary greying while a launch is in flight or the server is away, so
|
// momentary greying while a launch is in flight or the server is away, so
|
||||||
@@ -3141,11 +2963,6 @@ async function launchSkill(entry) {
|
|||||||
// cards that take no spec (utilities, setup) launch untargeted even while
|
// cards that take no spec (utilities, setup) launch untargeted even while
|
||||||
// a spec is selected.
|
// a spec is selected.
|
||||||
if (target) action.spec = target.dir;
|
if (target) action.spec = target.dir;
|
||||||
// The skill opens on the folders remembered for what it was launched for.
|
|
||||||
// Held until the launch is in flight: the swap's own frame re-renders the
|
|
||||||
// dashboard, which would otherwise sync back to the picker's spec.
|
|
||||||
launchScoping = true;
|
|
||||||
await syncWorkspaceScope(target ? target.dir : "");
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/submit", {
|
const res = await fetch("/submit", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -3156,7 +2973,6 @@ async function launchSkill(entry) {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (res.status === 409) {
|
if (res.status === 409) {
|
||||||
launchScoping = false;
|
|
||||||
pendingResult = true;
|
pendingResult = true;
|
||||||
banner("Your last pick is still being picked up. One moment.", "info");
|
banner("Your last pick is still being picked up. One moment.", "info");
|
||||||
return;
|
return;
|
||||||
@@ -3164,12 +2980,10 @@ async function launchSkill(entry) {
|
|||||||
if (!res.ok) throw new Error(String(res.status));
|
if (!res.ok) throw new Error(String(res.status));
|
||||||
sound("startSkill");
|
sound("startSkill");
|
||||||
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
|
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
|
||||||
launchScoping = false;
|
|
||||||
pendingResult = true;
|
pendingResult = true;
|
||||||
save();
|
save();
|
||||||
render();
|
render();
|
||||||
} catch {
|
} catch {
|
||||||
launchScoping = false;
|
|
||||||
banner("That did not go through. Nothing was lost; try again.", "warn");
|
banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3387,11 +3201,7 @@ document.addEventListener("keydown", cancelSkipMove, true);
|
|||||||
function skipAndMoveOn(id) {
|
function skipAndMoveOn(id) {
|
||||||
cancelSkipMove();
|
cancelSkipMove();
|
||||||
local.skipFlash = id;
|
local.skipFlash = id;
|
||||||
// A note already typed goes along: skipping the question is not retracting
|
stage(id, { type: "skip", skipped: true });
|
||||||
// the comment. Dropping it would leave the text in the box but out of the
|
|
||||||
// send, which looks kept and is not.
|
|
||||||
const cur = local.staged[id];
|
|
||||||
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
|
|
||||||
skipTimer = setTimeout(() => {
|
skipTimer = setTimeout(() => {
|
||||||
skipTimer = null;
|
skipTimer = null;
|
||||||
local.skipFlash = null;
|
local.skipFlash = null;
|
||||||
@@ -3508,41 +3318,15 @@ function renderWaiting(main) {
|
|||||||
}
|
}
|
||||||
pane.appendChild(title);
|
pane.appendChild(title);
|
||||||
pane.appendChild(el("p", null, doing));
|
pane.appendChild(el("p", null, doing));
|
||||||
const ask = "If Plan2Code needs you, the question appears here on its own.";
|
pane.appendChild(
|
||||||
if (!docs().length) {
|
el(
|
||||||
pane.appendChild(el("p", null, ask));
|
"p",
|
||||||
return;
|
null,
|
||||||
}
|
docs().length
|
||||||
// "Task" and the tasks tab's own name both open that tab, so the pointer is
|
? "The tabs above fill in as it goes. You can follow along with live `Task` updates in the `Phase tasks` tab. If Plan2Code needs you, the question appears here on its own."
|
||||||
// one click from what it points at. A build posts it as `phase` ("Phase N
|
: "If Plan2Code needs you, the question appears here on its own."
|
||||||
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
|
)
|
||||||
// Plan) has nothing live to follow, so it gets no pointer at all.
|
|
||||||
const list =
|
|
||||||
docs().find((d) => d.id === "phase") ||
|
|
||||||
docs().find((d) => d.id === "tasks") ||
|
|
||||||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
|
|
||||||
if (!list) {
|
|
||||||
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const jump = (word) => {
|
|
||||||
const b = el("button", "waiting-jump", word);
|
|
||||||
b.type = "button";
|
|
||||||
b.addEventListener("click", () => {
|
|
||||||
view = "doc:" + list.id;
|
|
||||||
render();
|
|
||||||
});
|
|
||||||
return b;
|
|
||||||
};
|
|
||||||
const p = el("p");
|
|
||||||
p.append(
|
|
||||||
"The tabs above fill in as it goes. You can follow along with live ",
|
|
||||||
jump("Task"),
|
|
||||||
" updates in the ",
|
|
||||||
jump(list.title || "Phase tasks"),
|
|
||||||
" tab. " + ask
|
|
||||||
);
|
);
|
||||||
pane.appendChild(p);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// A notice is context for the question it sits beside, so it lives inside the
|
// A notice is context for the question it sits beside, so it lives inside the
|
||||||
@@ -3678,8 +3462,8 @@ function renderSettled(card, item) {
|
|||||||
// would misreport which of the two was the answer.
|
// would misreport which of the two was the answer.
|
||||||
let prose = text;
|
let prose = text;
|
||||||
if (!prose && !lines.length) {
|
if (!prose && !lines.length) {
|
||||||
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
|
const mine = (item.thread || []).filter((m) => m.who === "user");
|
||||||
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
|
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
const nothing = !lines.length && !prose;
|
const nothing = !lines.length && !prose;
|
||||||
@@ -4495,10 +4279,6 @@ function buildChecklist(card, item, staged) {
|
|||||||
const commitList = (change) => {
|
const commitList = (change) => {
|
||||||
const cur = local.staged[item.id];
|
const cur = local.staged[item.id];
|
||||||
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
|
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
|
||||||
// A tick or a state IS the answer, so it ends a skip staged earlier:
|
|
||||||
// left in place, `skipped` would collapse the reply to "skip" while the
|
|
||||||
// card showed ticked steps on their way.
|
|
||||||
delete next.skipped;
|
|
||||||
const empty = !(next.done && next.done.length) && !next.state && !next.text;
|
const empty = !(next.done && next.done.length) && !next.state && !next.text;
|
||||||
stage(item.id, empty ? null : next);
|
stage(item.id, empty ? null : next);
|
||||||
};
|
};
|
||||||
@@ -4548,7 +4328,7 @@ function buildChecklist(card, item, staged) {
|
|||||||
function buildMenu(card, item, staged) {
|
function buildMenu(card, item, staged) {
|
||||||
const list = el("ul", "options");
|
const list = el("ul", "options");
|
||||||
const name = "menu-" + item.id;
|
const name = "menu-" + item.id;
|
||||||
for (const [i, o] of (item.options || []).entries()) {
|
for (const o of item.options || []) {
|
||||||
const picked = staged && staged.k === o.k;
|
const picked = staged && staged.k === o.k;
|
||||||
const li = el("li", "option" + (picked ? " is-picked" : ""));
|
const li = el("li", "option" + (picked ? " is-picked" : ""));
|
||||||
const label = el("label");
|
const label = el("label");
|
||||||
@@ -4556,13 +4336,7 @@ function buildMenu(card, item, staged) {
|
|||||||
const radio = el("input");
|
const radio = el("input");
|
||||||
radio.type = "radio";
|
radio.type = "radio";
|
||||||
radio.name = name;
|
radio.name = name;
|
||||||
// The same id buildChoice gives its radios: withFocus finds the focused
|
|
||||||
// input by id after the render this change() sets off, and without one a
|
|
||||||
// keyboard user arrowing through the menu lands on <body> every time.
|
|
||||||
radio.id = optionId(item, o, i);
|
|
||||||
radio.value = o.k;
|
|
||||||
radio.checked = Boolean(picked);
|
radio.checked = Boolean(picked);
|
||||||
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
|
|
||||||
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
|
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
|
||||||
const body = el("div", "option-body");
|
const body = el("div", "option-body");
|
||||||
const head = el("div", "option-label");
|
const head = el("div", "option-label");
|
||||||
@@ -4861,42 +4635,6 @@ function renderOverview(main) {
|
|||||||
main.appendChild(box);
|
main.appendChild(box);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The helpers the agent reported, as it last posted them. Everything here is
|
|
||||||
// the agent's text, so it goes in as text, never as markup.
|
|
||||||
function renderSubagents(main) {
|
|
||||||
const card = el("section", "card sa-card");
|
|
||||||
card.appendChild(el("h2", null, "Subagents"));
|
|
||||||
card.appendChild(el("p", "help", CHECKIN_LINE));
|
|
||||||
const { alone, rows } = helperRows(S.helpers);
|
|
||||||
if (alone) {
|
|
||||||
card.appendChild(
|
|
||||||
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
|
|
||||||
);
|
|
||||||
main.appendChild(card);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const list = el("ul", "sa-list");
|
|
||||||
for (const row of rows) {
|
|
||||||
const item = el("li", "sa-row");
|
|
||||||
const head = el("div", "sa-head");
|
|
||||||
head.appendChild(el("strong", "sa-title", row.title));
|
|
||||||
const pill = el("span", "pill sa-pill is-" + row.state);
|
|
||||||
if (row.state === "running") {
|
|
||||||
const spin = el("span", "spinner tiny");
|
|
||||||
spin.setAttribute("aria-hidden", "true");
|
|
||||||
pill.appendChild(spin);
|
|
||||||
}
|
|
||||||
pill.appendChild(document.createTextNode(row.stateLabel));
|
|
||||||
head.appendChild(pill);
|
|
||||||
item.appendChild(head);
|
|
||||||
item.appendChild(el("p", "sa-ask", row.ask));
|
|
||||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
|
||||||
list.appendChild(item);
|
|
||||||
}
|
|
||||||
card.appendChild(list);
|
|
||||||
main.appendChild(card);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---------------------------------------------------------------- ask */
|
/* ---------------------------------------------------------------- ask */
|
||||||
|
|
||||||
// The frame's chat block, with `offline` worked out now rather than when the
|
// The frame's chat block, with `offline` worked out now rather than when the
|
||||||
@@ -5495,30 +5233,20 @@ function renderAside() {
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// A note that has been sent but not yet picked up: marked as waiting, so the
|
|
||||||
// send is seen to have gone, until the agent replies. The server writes the
|
|
||||||
// note into the thread as it arrives; a session from before that has only
|
|
||||||
// `sentNote`, which gets a box of its own below.
|
|
||||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
|
||||||
let waitingShown = false;
|
|
||||||
for (const m of thread) {
|
for (const m of thread) {
|
||||||
const mine = threadWho(m) === "user";
|
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
|
||||||
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
|
|
||||||
if (pending) waitingShown = true;
|
|
||||||
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
|
|
||||||
const who = el("div", "msg-who");
|
const who = el("div", "msg-who");
|
||||||
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
|
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
|
||||||
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
|
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||||
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
|
||||||
box.appendChild(who);
|
box.appendChild(who);
|
||||||
const text = threadText(m);
|
box.appendChild(md(m.text, "md"));
|
||||||
if (text) box.appendChild(md(text, "md"));
|
|
||||||
const tray = mine ? sentAttachments(m) : null;
|
|
||||||
if (tray) box.appendChild(tray);
|
|
||||||
aside.appendChild(box);
|
aside.appendChild(box);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (waiting && !waitingShown) {
|
// A note that has been sent but not yet picked up: shown at once, so the
|
||||||
|
// send is seen to have gone, and gone when the agent replies.
|
||||||
|
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||||
|
if (waiting) {
|
||||||
const box = el("div", "msg you pending");
|
const box = el("div", "msg you pending");
|
||||||
const who = el("div", "msg-who");
|
const who = el("div", "msg-who");
|
||||||
who.appendChild(el("span", null, "You"));
|
who.appendChild(el("span", null, "You"));
|
||||||
@@ -5818,10 +5546,7 @@ async function attachFiles(itemId, files) {
|
|||||||
const taken = wanted.slice(0, room);
|
const taken = wanted.slice(0, room);
|
||||||
// One banner at a time, so every refusal goes into it, each by name.
|
// One banner at a time, so every refusal goes into it, each by name.
|
||||||
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
|
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
|
||||||
if (taken.length < wanted.length)
|
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
|
||||||
said.push(
|
|
||||||
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
|
|
||||||
);
|
|
||||||
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
|
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
taken.map(async (file) => {
|
taken.map(async (file) => {
|
||||||
@@ -5924,19 +5649,6 @@ function sendState() {
|
|||||||
: { disabled: true, why: "Your last answers are on their way. One moment.", short: "" };
|
: { disabled: true, why: "Your last answers are on their way. One moment.", short: "" };
|
||||||
}
|
}
|
||||||
if (agentWorking()) {
|
if (agentWorking()) {
|
||||||
// A question the agent left open while still working is still a question,
|
|
||||||
// and its answer has nowhere better to wait than the server, which holds
|
|
||||||
// a send until the agent next looks. The contract says to switch to
|
|
||||||
// "waiting" before asking, but an agent that asks and carries on ("while
|
|
||||||
// you decide") must not lock the person out of answering for up to an
|
|
||||||
// hour of quietMinutes.
|
|
||||||
if (myTurn().length && (stagedCount() || pendingNotes().length)) {
|
|
||||||
return {
|
|
||||||
disabled: false,
|
|
||||||
why: "Plan2Code is still working. Your answers wait for it to look.",
|
|
||||||
short: "Still working · it reads this next",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const ms = workingMs();
|
const ms = workingMs();
|
||||||
if (ms > patience(WORKING_GRACE_MS)) {
|
if (ms > patience(WORKING_GRACE_MS)) {
|
||||||
// A stuck agent must not lock someone out of their own session, so the
|
// A stuck agent must not lock someone out of their own session, so the
|
||||||
@@ -6079,30 +5791,10 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
|
|||||||
// session opened before the server wrote `worktree` has nothing to show, so
|
// session opened before the server wrote `worktree` has nothing to show, so
|
||||||
// the slot stays hidden. The footer renders on every tick, so the DOM is only
|
// the slot stays hidden. The footer renders on every tick, so the DOM is only
|
||||||
// touched when the labels change, or when a resize clears the key.
|
// touched when the labels change, or when a resize clears the key.
|
||||||
// The project's name: the workspace's original folder, or the session's
|
|
||||||
// worktree folder before a frame carries the workspace.
|
|
||||||
function projectName() {
|
|
||||||
const folders = workspaceFolders();
|
|
||||||
if (folders.length && folders[0].name) return folders[0].name;
|
|
||||||
const path = (S && S.worktree) || "";
|
|
||||||
return path ? path.split(/[\\/]/).filter(Boolean).pop() || path : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// The browser tab's title, led by the project so tabs from different
|
|
||||||
// projects are told apart. Called from the chrome and the footer, since the
|
|
||||||
// workspace frame can arrive after either.
|
|
||||||
function renderTabTitle() {
|
|
||||||
if (!S) return;
|
|
||||||
const name = projectName();
|
|
||||||
document.title =
|
|
||||||
(name ? name + " · " : "") + (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderWhere() {
|
function renderWhere() {
|
||||||
const b = $("footer-where");
|
const b = $("footer-where");
|
||||||
const folders = workspaceFolders();
|
const folders = workspaceFolders();
|
||||||
const path = S.worktree || "";
|
const path = S.worktree || "";
|
||||||
renderTabTitle();
|
|
||||||
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
|
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
|
||||||
const labels = folders.length
|
const labels = folders.length
|
||||||
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
|
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
|
||||||
@@ -6115,16 +5807,7 @@ function renderWhere() {
|
|||||||
let label = labels[0];
|
let label = labels[0];
|
||||||
for (const text of labels) {
|
for (const text of labels) {
|
||||||
label = text;
|
label = text;
|
||||||
// The project name takes the highlight color, so several consoles side by
|
|
||||||
// side tell apart at a glance; the rest of the label stays quiet.
|
|
||||||
const name = projectName();
|
|
||||||
b.textContent = "";
|
|
||||||
if (name && text.startsWith(name)) {
|
|
||||||
b.appendChild(el("span", "where-project", name));
|
|
||||||
b.appendChild(document.createTextNode(text.slice(name.length)));
|
|
||||||
} else {
|
|
||||||
b.textContent = text;
|
b.textContent = text;
|
||||||
}
|
|
||||||
if (alert) {
|
if (alert) {
|
||||||
const dot = el("span", "where-alert");
|
const dot = el("span", "where-alert");
|
||||||
dot.setAttribute("aria-hidden", "true");
|
dot.setAttribute("aria-hidden", "true");
|
||||||
@@ -6171,32 +5854,6 @@ async function postJson(url, body) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The workspace follows the dashboard's picker: the folders remembered for
|
|
||||||
the selected spec, or the project's own under "Start from scratch". The
|
|
||||||
server swaps the list and remembers every change after it. */
|
|
||||||
let scopeAsked = null;
|
|
||||||
// True from a launch's scope sync until its send has gone (or failed).
|
|
||||||
let launchScoping = false;
|
|
||||||
async function syncWorkspaceScope(spec) {
|
|
||||||
if (!S || S.workflow !== "dashboard" || gone || !wsFrame) return;
|
|
||||||
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
|
|
||||||
if ((wsFrame.scope || "") === want || scopeAsked === want) return;
|
|
||||||
scopeAsked = want;
|
|
||||||
const { status, body } = await postJson("/workspace/scope", { spec: want });
|
|
||||||
if (status === 200 && body && Array.isArray(body.folders)) wsFrame = { ...wsFrame, ...body };
|
|
||||||
scopeAsked = null;
|
|
||||||
if ($("workspace-modal").open) renderWorkspace();
|
|
||||||
}
|
|
||||||
|
|
||||||
// The dialog's "Remembered for" line: whose list this is.
|
|
||||||
function workspaceScopeText() {
|
|
||||||
const scope = (wsFrame && wsFrame.scope) || "";
|
|
||||||
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
|
|
||||||
const spec = specList().find((s) => s.dir === scope);
|
|
||||||
const name = spec ? spec.name : scope.split("/").pop();
|
|
||||||
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
|
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
|
||||||
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
|
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
|
||||||
// The folder whose Remove is waiting on its inline confirm, by id.
|
// The folder whose Remove is waiting on its inline confirm, by id.
|
||||||
@@ -6236,7 +5893,6 @@ function renderWorkspace() {
|
|||||||
}
|
}
|
||||||
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
|
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
|
||||||
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
|
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
|
||||||
$("workspace-scope").textContent = workspaceScopeText();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function workspaceRow(f) {
|
function workspaceRow(f) {
|
||||||
@@ -6700,10 +6356,6 @@ async function goHome() {
|
|||||||
$("home-modal").close();
|
$("home-modal").close();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
$("home-modal").close();
|
$("home-modal").close();
|
||||||
// The server is holding an uncollected result: Send, Home and Stop all
|
|
||||||
// need to read as busy until the frame or the ping says otherwise, same
|
|
||||||
// as send() and sendAfterBuild() do on a 409.
|
|
||||||
if (err && err.pending) pendingResult = true;
|
|
||||||
banner(
|
banner(
|
||||||
err && err.pending
|
err && err.pending
|
||||||
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
||||||
@@ -6764,7 +6416,6 @@ async function stopSession() {
|
|||||||
stoppingHidden = false;
|
stoppingHidden = false;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
$("stop-modal").close();
|
$("stop-modal").close();
|
||||||
if (err && err.pending) pendingResult = true;
|
|
||||||
banner(
|
banner(
|
||||||
err && err.pending
|
err && err.pending
|
||||||
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
||||||
@@ -6919,6 +6570,7 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
|
|||||||
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
|
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
|
||||||
}
|
}
|
||||||
local.staged = {};
|
local.staged = {};
|
||||||
|
local.sentAt = Date.now();
|
||||||
save();
|
save();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6971,7 +6623,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
|
|||||||
// something the agent never hears.
|
// something the agent never hears.
|
||||||
function tokenFor(item, v) {
|
function tokenFor(item, v) {
|
||||||
const map = item.token || {};
|
const map = item.token || {};
|
||||||
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
|
if (v.skipped) return "skip";
|
||||||
const parts = [];
|
const parts = [];
|
||||||
if (v.k) parts.push(map[v.k] || v.k);
|
if (v.k) parts.push(map[v.k] || v.k);
|
||||||
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
|
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
|
||||||
@@ -7203,14 +6855,14 @@ function renderAbout() {
|
|||||||
let helpBuilt = false;
|
let helpBuilt = false;
|
||||||
|
|
||||||
async function renderHelpVersion() {
|
async function renderHelpVersion() {
|
||||||
const slot = $("help-version");
|
const el = $("help-version");
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/version", { cache: "no-store" });
|
const res = await fetch("/version", { cache: "no-store" });
|
||||||
const { version } = res.ok ? await res.json() : {};
|
const { version } = res.ok ? await res.json() : {};
|
||||||
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
|
el.textContent = version ? "Plan2Code v" + version : "";
|
||||||
slot.hidden = !version;
|
el.hidden = !version;
|
||||||
} catch {
|
} catch {
|
||||||
slot.hidden = true;
|
el.hidden = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -7318,7 +6970,6 @@ function openHelpOn(id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$("btn-home").addEventListener("click", openHomeConfirm);
|
$("btn-home").addEventListener("click", openHomeConfirm);
|
||||||
$("update-done").addEventListener("click", () => $("update-modal").close());
|
|
||||||
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
||||||
$("home-go").addEventListener("click", goHome);
|
$("home-go").addEventListener("click", goHome);
|
||||||
$("btn-stop").addEventListener("click", openStopConfirm);
|
$("btn-stop").addEventListener("click", openStopConfirm);
|
||||||
@@ -7349,7 +7000,6 @@ function lightDismiss(dlg) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
lightDismiss($("looks-modal"));
|
lightDismiss($("looks-modal"));
|
||||||
lightDismiss($("subagents-modal"));
|
|
||||||
lightDismiss($("help-modal"));
|
lightDismiss($("help-modal"));
|
||||||
lightDismiss($("workspace-modal"));
|
lightDismiss($("workspace-modal"));
|
||||||
lightDismiss($("welcome-modal"));
|
lightDismiss($("welcome-modal"));
|
||||||
@@ -7399,7 +7049,6 @@ $("btn-looks").addEventListener("click", () => {
|
|||||||
});
|
});
|
||||||
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
||||||
$("looks-modal").addEventListener("close", () => {
|
$("looks-modal").addEventListener("close", () => {
|
||||||
resetCleanup();
|
|
||||||
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
|
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
|
||||||
});
|
});
|
||||||
$("looks-reset").addEventListener("click", () => {
|
$("looks-reset").addEventListener("click", () => {
|
||||||
@@ -7546,119 +7195,7 @@ $("models-reset").addEventListener("click", () => {
|
|||||||
renderModels();
|
renderModels();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Cleanup: the server works out what in ~/.plan2code is not needed and
|
|
||||||
// shows it first; Delete these sends back only the ids it was shown, and the
|
|
||||||
// server re-checks every one before removing it.
|
|
||||||
let cleanupFound = null;
|
|
||||||
// Bumped by every scan, delete and reset: a response from an older one is
|
|
||||||
// dropped, so a scan still in flight when Preferences closes cannot refill it.
|
|
||||||
let cleanupGen = 0;
|
|
||||||
const CLEANUP_SHOWN = 8;
|
|
||||||
|
|
||||||
function setCleanupStatus(text, isError) {
|
|
||||||
const status = $("cleanup-status");
|
|
||||||
status.textContent = text;
|
|
||||||
status.classList.toggle("error", Boolean(isError));
|
|
||||||
}
|
|
||||||
|
|
||||||
function cleanupLabel(item) {
|
|
||||||
if (item.where === "session") return "Session " + item.name;
|
|
||||||
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
|
|
||||||
return where + item.name + (item.kind === "folder" ? "/" : "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function cleanupSummary(items, bytes) {
|
|
||||||
const sessions = items.filter((i) => i.where === "session").length;
|
|
||||||
const strays = items.length - sessions;
|
|
||||||
const parts = [];
|
|
||||||
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
|
|
||||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
|
||||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resetCleanup() {
|
|
||||||
cleanupGen++;
|
|
||||||
cleanupFound = null;
|
|
||||||
$("cleanup-list").replaceChildren();
|
|
||||||
$("cleanup-delete").hidden = true;
|
|
||||||
$("cleanup-delete").disabled = false;
|
|
||||||
$("cleanup-scan").disabled = false;
|
|
||||||
setCleanupStatus("", false);
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderCleanup() {
|
|
||||||
const list = $("cleanup-list");
|
|
||||||
list.replaceChildren();
|
|
||||||
const items = (cleanupFound && cleanupFound.items) || [];
|
|
||||||
$("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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function scanCleanup() {
|
|
||||||
const gen = ++cleanupGen;
|
|
||||||
$("cleanup-scan").disabled = true;
|
|
||||||
$("cleanup-delete").disabled = true;
|
|
||||||
setCleanupStatus("Looking…", false);
|
|
||||||
const { status, body } = await postJson("/cleanup", { scan: true });
|
|
||||||
if (gen !== cleanupGen) return;
|
|
||||||
$("cleanup-scan").disabled = false;
|
|
||||||
$("cleanup-delete").disabled = false;
|
|
||||||
if (status !== 200 || !body.ok) {
|
|
||||||
cleanupFound = null;
|
|
||||||
renderCleanup();
|
|
||||||
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
|
|
||||||
}
|
|
||||||
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function deleteCleanup() {
|
|
||||||
if (!cleanupFound || !cleanupFound.items.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) });
|
|
||||||
if (gen !== cleanupGen) return;
|
|
||||||
$("cleanup-delete").disabled = false;
|
|
||||||
$("cleanup-scan").disabled = false;
|
|
||||||
if (status !== 200 || !body.ok) {
|
|
||||||
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
|
|
||||||
}
|
|
||||||
const removed = (body.removed || []).length;
|
|
||||||
const failed = (body.failed || []).length;
|
|
||||||
cleanupFound = null;
|
|
||||||
renderCleanup();
|
|
||||||
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
|
|
||||||
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
|
|
||||||
}
|
|
||||||
|
|
||||||
$("cleanup-scan").addEventListener("click", scanCleanup);
|
|
||||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
|
||||||
|
|
||||||
$("btn-brief").addEventListener("click", openBrief);
|
$("btn-brief").addEventListener("click", openBrief);
|
||||||
$("btn-subagents").addEventListener("click", openSubagents);
|
|
||||||
$("subagents-default").addEventListener("click", () => {
|
|
||||||
$("subagents-instruction").value = defaultInstruction(S.workflow);
|
|
||||||
});
|
|
||||||
$("subagents-save").addEventListener("click", saveSubagents);
|
|
||||||
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
|
|
||||||
$("subagents-modal").addEventListener("close", () => $("btn-subagents").focus());
|
|
||||||
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
||||||
$("brief-go").addEventListener("click", sendBrief);
|
$("brief-go").addEventListener("click", sendBrief);
|
||||||
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ export const HELP_TABS = Object.freeze([
|
|||||||
tab("dashboard", "The dashboard", true),
|
tab("dashboard", "The dashboard", true),
|
||||||
tab("meter", "Session meter", false),
|
tab("meter", "Session meter", false),
|
||||||
tab("build", "Watching a build", false),
|
tab("build", "Watching a build", false),
|
||||||
tab("subagents", "Helpers (subagents)", false),
|
|
||||||
tab("ask", "Ask a quick question", false),
|
tab("ask", "Ask a quick question", false),
|
||||||
tab("finishing", "Stopping and finishing", false),
|
tab("finishing", "Stopping and finishing", false),
|
||||||
tab("stuck", "When something looks stuck", true),
|
tab("stuck", "When something looks stuck", true),
|
||||||
@@ -40,7 +39,6 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
|||||||
if (gone || adrift) return "stuck";
|
if (gone || adrift) return "stuck";
|
||||||
if (workspace) return "workspace";
|
if (workspace) return "workspace";
|
||||||
if (v === "ask") return "ask";
|
if (v === "ask") return "ask";
|
||||||
if (v === "subagents") return "subagents";
|
|
||||||
if (dashboard && meterRed) return "meter";
|
if (dashboard && meterRed) return "meter";
|
||||||
if (dashboard) return "dashboard";
|
if (dashboard) return "dashboard";
|
||||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||||
|
|||||||
@@ -21,7 +21,6 @@
|
|||||||
<link rel="modulepreload" href="/starters.js" />
|
<link rel="modulepreload" href="/starters.js" />
|
||||||
<link rel="modulepreload" href="/workspace.js" />
|
<link rel="modulepreload" href="/workspace.js" />
|
||||||
<link rel="modulepreload" href="/meter.js" />
|
<link rel="modulepreload" href="/meter.js" />
|
||||||
<link rel="modulepreload" href="/subagents.js" />
|
|
||||||
<link rel="modulepreload" href="/mentions.js" />
|
<link rel="modulepreload" href="/mentions.js" />
|
||||||
<link rel="modulepreload" href="/favicon.js" />
|
<link rel="modulepreload" href="/favicon.js" />
|
||||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||||
@@ -173,18 +172,6 @@
|
|||||||
<button type="button" class="btn ghost small brief-btn" id="btn-brief" hidden>
|
<button type="button" class="btn ghost small brief-btn" id="btn-brief" hidden>
|
||||||
Write a brief
|
Write a brief
|
||||||
</button>
|
</button>
|
||||||
<!-- Subagents: opted-in skills only. Lit while helpers are on; a click
|
|
||||||
opens the Subagents dialog and never toggles them itself. -->
|
|
||||||
<button type="button" class="btn ghost small subagents-btn" id="btn-subagents" aria-pressed="false" hidden>
|
|
||||||
<!-- An orchestrator and its helpers: one larger node linked to three smaller ones. -->
|
|
||||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
||||||
<path class="sa-link" d="M6.9 6.6L10.9 3.9M7.4 8h3.5M6.9 9.4l4 2.7" />
|
|
||||||
<circle cx="4.6" cy="8" r="2.6" class="sa-hub" />
|
|
||||||
<circle cx="12.4" cy="3" r="1.5" class="sa-node" />
|
|
||||||
<circle cx="12.4" cy="8" r="1.5" class="sa-node" />
|
|
||||||
<circle cx="12.4" cy="13" r="1.5" class="sa-node" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="views-group">
|
<div class="views-group">
|
||||||
<span class="views-arrow" aria-hidden="true">
|
<span class="views-arrow" aria-hidden="true">
|
||||||
@@ -418,7 +405,7 @@
|
|||||||
</svg>
|
</svg>
|
||||||
|
|
||||||
<!-- 4 Finalize: hopping for joy, both arms up, beside the checkmark
|
<!-- 4 Finalize: hopping for joy, both arms up, beside the checkmark
|
||||||
flag, confetti drifting down. -->
|
flag, confetti drifting down and his star glowing. -->
|
||||||
<svg class="pose pose-finalize" data-pose="finalize" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
|
<svg class="pose pose-finalize" data-pose="finalize" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
|
||||||
<ellipse class="shadow fz-shadow" cx="120" cy="198" rx="34" ry="5" />
|
<ellipse class="shadow fz-shadow" cx="120" cy="198" rx="34" ry="5" />
|
||||||
<g class="fz-hop">
|
<g class="fz-hop">
|
||||||
@@ -428,6 +415,7 @@
|
|||||||
<rect class="sh" x="80" y="72" width="80" height="108" rx="16" />
|
<rect class="sh" x="80" y="72" width="80" height="108" rx="16" />
|
||||||
<path class="ln" d="M80 116 L60 90" /><circle class="fl" cx="60" cy="90" r="5.5" />
|
<path class="ln" d="M80 116 L60 90" /><circle class="fl" cx="60" cy="90" r="5.5" />
|
||||||
<path class="ln" d="M160 116 L180 90" /><circle class="fl" cx="180" cy="90" r="5.5" />
|
<path class="ln" d="M160 116 L180 90" /><circle class="fl" cx="180" cy="90" r="5.5" />
|
||||||
|
<circle class="ac fz-halo" cx="120" cy="98" r="23" />
|
||||||
<path class="ey blink" d="M120 84 L123.64 92.98 L133.31 93.67 L125.9 99.92 L128.23 109.33 L120 104.2 L111.77 109.33 L114.1 99.92 L106.69 93.67 L116.36 92.98 Z" />
|
<path class="ey blink" d="M120 84 L123.64 92.98 L133.31 93.67 L125.9 99.92 L128.23 109.33 L120 104.2 L111.77 109.33 L114.1 99.92 L106.69 93.67 L116.36 92.98 Z" />
|
||||||
<path class="ey" d="M106 118 Q120 134 134 118 Z" />
|
<path class="ey" d="M106 118 Q120 134 134 118 Z" />
|
||||||
</g>
|
</g>
|
||||||
@@ -593,13 +581,6 @@
|
|||||||
<rect x="3" y="9" width="18" height="6" rx="3" />
|
<rect x="3" y="9" width="18" height="6" rx="3" />
|
||||||
<path d="M6 12h7" />
|
<path d="M6 12h7" />
|
||||||
</symbol>
|
</symbol>
|
||||||
<symbol id="hi-subagents" viewBox="0 0 24 24" fill="none">
|
|
||||||
<circle cx="7" cy="12" r="3.5" />
|
|
||||||
<circle cx="18" cy="5" r="2" />
|
|
||||||
<circle cx="18" cy="12" r="2" />
|
|
||||||
<circle cx="18" cy="19" r="2" />
|
|
||||||
<path d="M10 10l6-4M10.5 12H16M10 14l6 4" />
|
|
||||||
</symbol>
|
|
||||||
<symbol id="hi-ask" viewBox="0 0 24 24" fill="none">
|
<symbol id="hi-ask" viewBox="0 0 24 24" fill="none">
|
||||||
<path d="M4 5h16v11H10l-4 4v-4H4z" />
|
<path d="M4 5h16v11H10l-4 4v-4H4z" />
|
||||||
<path d="M8 9.5h8M8 12.5h5" />
|
<path d="M8 9.5h8M8 12.5h5" />
|
||||||
@@ -852,28 +833,10 @@
|
|||||||
Click the folder name in the middle of the bottom bar. It shows your
|
Click the folder name in the middle of the bottom bar. It shows your
|
||||||
folder's name and branch, such as <strong>shop · main</strong>, and
|
folder's name and branch, such as <strong>shop · main</strong>, and
|
||||||
<strong>shop + 2 folders · main</strong> once you have added some.
|
<strong>shop + 2 folders · main</strong> once you have added some.
|
||||||
It carries across steps you start from the dashboard.
|
The workspace lasts for this console session only: it carries across
|
||||||
|
steps you start from the dashboard, and a new console session starts
|
||||||
|
with just the folder you started in.
|
||||||
</p>
|
</p>
|
||||||
<h4>Remembered for next time</h4>
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
Every change is saved as you make it, so the next console session in
|
|
||||||
this folder starts with the same folders.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
Each spec keeps its own list. The first time you pick a spec on the
|
|
||||||
dashboard it starts as a copy of the project's list (the one shown
|
|
||||||
under <strong>Start from scratch</strong>), and after that the two
|
|
||||||
are separate. Picking a spec loads its list; the line under the
|
|
||||||
dialog's title says whose list you are looking at.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
The lists live in <code>workspaces.json</code> in your own
|
|
||||||
Plan2Code settings folder, beside your look and feel, never in the
|
|
||||||
project. Finalize offers to forget a spec's list when it archives the
|
|
||||||
spec.
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
<h4>Adding a folder</h4>
|
<h4>Adding a folder</h4>
|
||||||
<ul>
|
<ul>
|
||||||
<li>
|
<li>
|
||||||
@@ -1311,14 +1274,6 @@
|
|||||||
come back, and you can change your role any time from the swatch
|
come back, and you can change your role any time from the swatch
|
||||||
button.
|
button.
|
||||||
</p>
|
</p>
|
||||||
<h4>When an update is out</h4>
|
|
||||||
<p>
|
|
||||||
When a newer Plan2Code release is out, the dashboard shows
|
|
||||||
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
|
|
||||||
to run in your terminal; × hides it until the next
|
|
||||||
<code>/plan2code</code>. The version at the bottom of Help links to
|
|
||||||
the Releases page.
|
|
||||||
</p>
|
|
||||||
<h4>The cards</h4>
|
<h4>The cards</h4>
|
||||||
<p>They come in three groups.</p>
|
<p>They come in three groups.</p>
|
||||||
<p><strong>First, the project</strong></p>
|
<p><strong>First, the project</strong></p>
|
||||||
@@ -1408,10 +1363,9 @@
|
|||||||
<h4>What it counts</h4>
|
<h4>What it counts</h4>
|
||||||
<p>
|
<p>
|
||||||
Each step you run here adds points: a plan or a set of documents
|
Each step you run here adds points: a plan or a set of documents
|
||||||
weighs more than a quick task, and a built phase more still, by how
|
weighs more than a single answered question, and a built phase more
|
||||||
many tasks it completed: a big phase adds more than a small one.
|
still, by how many tasks it completed: a big phase adds more than a
|
||||||
Every two questions you answer within one step add a point too
|
small one. Every two questions you answer add a point too, so a long
|
||||||
(rounded down, so a single answer adds nothing), so a long
|
|
||||||
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
|
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
|
||||||
points, with what it added. It is a rule of thumb, not a
|
points, with what it added. It is a rule of thumb, not a
|
||||||
reading of Plan2Code's real memory: long sessions tend to make it
|
reading of Plan2Code's real memory: long sessions tend to make it
|
||||||
@@ -1497,61 +1451,7 @@
|
|||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 12: Helpers (subagents) -->
|
<!-- Tab 12: Ask a quick question -->
|
||||||
<section class="help-panel" data-tab="subagents">
|
|
||||||
<h3>Helpers (subagents)</h3>
|
|
||||||
<p>
|
|
||||||
On a build, a review and Pathfinder, Plan2Code can hand independent
|
|
||||||
pieces of work to helpers (subagents) while it keeps the conversation
|
|
||||||
with you. The <strong>Subagents</strong> button in the top bar, after
|
|
||||||
Stop session, is lit while helpers are on.
|
|
||||||
</p>
|
|
||||||
<h4>The switch</h4>
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
Clicking the button opens the <strong>Subagents</strong> dialog; it
|
|
||||||
never switches helpers on or off by itself. Pick <strong>Use
|
|
||||||
helpers</strong> or <strong>Work alone</strong>, edit the instruction
|
|
||||||
Plan2Code follows (<strong>Reset to default</strong> puts the
|
|
||||||
shipped one back), and say how many may run at once.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
It is off by default and saved for this project and this skill, so
|
|
||||||
the next session of the same skill here starts the same way.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
The change reaches Plan2Code at its next check-in, as a setting,
|
|
||||||
not as something you typed. How many helpers it can really start is
|
|
||||||
up to your agent; some have no helpers at all.
|
|
||||||
</li>
|
|
||||||
<li>The button only appears on skills that use helpers, and only when Plan2Code can pass the setting on.</li>
|
|
||||||
</ul>
|
|
||||||
<h4>The Subagents tab</h4>
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
With the first helper, a <strong>Subagents</strong> tab appears before
|
|
||||||
Ask: one row each, with what it was asked, whether it is running, done
|
|
||||||
or failed, and a one-line result at the end. The number on the tab is
|
|
||||||
how many are still running.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
Helpers report through Plan2Code, so the rows change at its
|
|
||||||
check-ins, not live. The page cannot stop a helper; ask Plan2Code
|
|
||||||
on the Ask tab if one should stop.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
<strong>Working alone</strong> means your agent has no way to start
|
|
||||||
helpers here, so it is doing the work itself.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
Pathfinder always uses helpers for its research questions, whatever
|
|
||||||
the switch says, and they show here too.
|
|
||||||
</li>
|
|
||||||
<li>The tab clears when you go back to the dashboard.</li>
|
|
||||||
</ul>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<!-- Tab 13: Ask a quick question -->
|
|
||||||
<section class="help-panel" data-tab="ask">
|
<section class="help-panel" data-tab="ask">
|
||||||
<h3>Ask a quick question</h3>
|
<h3>Ask a quick question</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1642,7 +1542,7 @@
|
|||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 14: Stopping and finishing -->
|
<!-- Tab 13: Stopping and finishing -->
|
||||||
<section class="help-panel" data-tab="finishing">
|
<section class="help-panel" data-tab="finishing">
|
||||||
<h3>Stopping and finishing</h3>
|
<h3>Stopping and finishing</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1724,7 +1624,7 @@
|
|||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 15: When something looks stuck -->
|
<!-- Tab 14: When something looks stuck -->
|
||||||
<section class="help-panel" data-tab="stuck">
|
<section class="help-panel" data-tab="stuck">
|
||||||
<h3>When something looks stuck</h3>
|
<h3>When something looks stuck</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1846,7 +1746,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 16: Keyboard and preferences -->
|
<!-- Tab 15: Keyboard and preferences -->
|
||||||
<section class="help-panel" data-tab="prefs">
|
<section class="help-panel" data-tab="prefs">
|
||||||
<h3>Keyboard and preferences</h3>
|
<h3>Keyboard and preferences</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1927,15 +1827,6 @@
|
|||||||
joining the strip. Keep only the ones you want; ticking a box plays
|
joining the strip. Keep only the ones you want; ticking a box plays
|
||||||
its sound.
|
its sound.
|
||||||
</li>
|
</li>
|
||||||
<li>
|
|
||||||
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
|
|
||||||
lists what Plan2Code doesn't need in your
|
|
||||||
<code>~/.plan2code</code> folder: sessions nobody has opened for
|
|
||||||
30 days, and files or folders that ended up there by mistake. It
|
|
||||||
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.
|
|
||||||
</li>
|
|
||||||
<li>
|
<li>
|
||||||
<strong>Back to default</strong> puts everything back as it was, and
|
<strong>Back to default</strong> puts everything back as it was, and
|
||||||
sets Role back to Not set.
|
sets Role back to Not set.
|
||||||
@@ -1962,7 +1853,7 @@
|
|||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 17: Privacy and where things are saved -->
|
<!-- Tab 16: Privacy and where things are saved -->
|
||||||
<section class="help-panel" data-tab="privacy">
|
<section class="help-panel" data-tab="privacy">
|
||||||
<h3>Privacy and where things are saved</h3>
|
<h3>Privacy and where things are saved</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1999,11 +1890,7 @@
|
|||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
your role, theme, colors, card width and sounds, in
|
your role, theme, colors, card width and sounds, in
|
||||||
<code>looks.json</code>;
|
<code>looks.json</code>.
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
your Subagents switch for each project and skill, in
|
|
||||||
<code>subagents.json</code>.
|
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
<p>
|
<p>
|
||||||
@@ -2078,16 +1965,6 @@
|
|||||||
</div>
|
</div>
|
||||||
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<fieldset class="modal-ranges looks-cleanup">
|
|
||||||
<legend>Cleanup</legend>
|
|
||||||
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
|
|
||||||
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
|
|
||||||
<div class="models-actions">
|
|
||||||
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
|
|
||||||
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
|
|
||||||
<span class="help" id="cleanup-status" role="status"></span>
|
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset class="modal-ranges looks-models">
|
<fieldset class="modal-ranges looks-models">
|
||||||
<legend>Models</legend>
|
<legend>Models</legend>
|
||||||
<div class="models-tabs" role="group" aria-label="Which agent">
|
<div class="models-tabs" role="group" aria-label="Which agent">
|
||||||
@@ -2117,46 +1994,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
<!-- Subagents: the switch for this skill, filled from the frame's
|
|
||||||
`subagents` by app.js and saved through POST /subagents. It borrows
|
|
||||||
the User Preferences dialog's classes, so it needs no dialog styles of
|
|
||||||
its own, only a themed number box. -->
|
|
||||||
<dialog class="modal looks subagents" id="subagents-modal" aria-labelledby="subagents-title">
|
|
||||||
<h2 id="subagents-title">Subagents</h2>
|
|
||||||
<p class="modal-blurb">
|
|
||||||
Let Plan2Code hand independent work to helpers in this skill. Saved for this
|
|
||||||
project and this skill.
|
|
||||||
</p>
|
|
||||||
<fieldset class="modal-ranges looks-row">
|
|
||||||
<legend>Helpers</legend>
|
|
||||||
<label><input type="radio" name="subagents-on" value="on" /> <span>Use helpers</span></label>
|
|
||||||
<label><input type="radio" name="subagents-on" value="off" checked /> <span>Work alone</span></label>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset class="modal-ranges">
|
|
||||||
<legend>Instruction</legend>
|
|
||||||
<textarea id="subagents-instruction" rows="4" maxlength="2000" aria-label="Instruction"></textarea>
|
|
||||||
<div class="models-actions">
|
|
||||||
<button type="button" class="btn small ghost" id="subagents-default">Reset to default</button>
|
|
||||||
<span class="help">Passed to the agent as written, at its next check-in.</span>
|
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset class="modal-ranges">
|
|
||||||
<legend>At most</legend>
|
|
||||||
<label>
|
|
||||||
<input type="number" id="subagents-max" min="1" max="20" step="1" aria-label="At most this many helpers at once" />
|
|
||||||
<span>helpers at once</span>
|
|
||||||
</label>
|
|
||||||
<p class="help">Advisory: your agent's own limit still applies.</p>
|
|
||||||
</fieldset>
|
|
||||||
<p class="help" id="subagents-checkin"></p>
|
|
||||||
<p class="help" id="subagents-research" hidden></p>
|
|
||||||
<p class="help" id="subagents-status" role="status"></p>
|
|
||||||
<div class="modal-actions">
|
|
||||||
<button type="button" class="btn ghost" id="subagents-cancel">Cancel</button>
|
|
||||||
<button type="button" class="btn primary" id="subagents-save">Save</button>
|
|
||||||
</div>
|
|
||||||
</dialog>
|
|
||||||
|
|
||||||
<!-- The Workspace: the folder this session started in plus any added as
|
<!-- The Workspace: the folder this session started in plus any added as
|
||||||
context. The list is drawn by app.js from the frame's `workspace`;
|
context. The list is drawn by app.js from the frame's `workspace`;
|
||||||
every change goes through the server's /workspace routes. -->
|
every change goes through the server's /workspace routes. -->
|
||||||
@@ -2166,7 +2003,6 @@
|
|||||||
The folders the agent uses as context this session. It reads the extra ones for
|
The folders the agent uses as context this session. It reads the extra ones for
|
||||||
reference and only changes them if you ask.
|
reference and only changes them if you ask.
|
||||||
</p>
|
</p>
|
||||||
<p class="workspace-scope" id="workspace-scope"></p>
|
|
||||||
<ul class="workspace-list" id="workspace-list"></ul>
|
<ul class="workspace-list" id="workspace-list"></ul>
|
||||||
<div class="workspace-add">
|
<div class="workspace-add">
|
||||||
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
|
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
|
||||||
@@ -2326,24 +2162,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
|
|
||||||
the copy row are filled by app.js; the update itself runs in a
|
|
||||||
terminal, never from this page. -->
|
|
||||||
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
|
|
||||||
<h2 id="update-title">A new Plan2Code is available</h2>
|
|
||||||
<p class="modal-blurb" id="update-versions"></p>
|
|
||||||
<ol class="update-steps">
|
|
||||||
<li>
|
|
||||||
Run this in your terminal (not in this page or your agent):
|
|
||||||
<div class="update-command" id="update-command"></div>
|
|
||||||
</li>
|
|
||||||
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
|
|
||||||
</ol>
|
|
||||||
<div class="modal-actions">
|
|
||||||
<button type="button" class="btn primary" id="update-done">Close</button>
|
|
||||||
</div>
|
|
||||||
</dialog>
|
|
||||||
|
|
||||||
<footer class="footer">
|
<footer class="footer">
|
||||||
<div class="footer-summary" id="footer-summary" aria-live="polite">
|
<div class="footer-summary" id="footer-summary" aria-live="polite">
|
||||||
Nothing to send yet.
|
Nothing to send yet.
|
||||||
|
|||||||
@@ -5,10 +5,7 @@
|
|||||||
// popover; this file owns the rules. No DOM access at module scope and no
|
// popover; this file owns the rules. No DOM access at module scope and no
|
||||||
// imports: the page and `node --test` both import this file.
|
// imports: the page and `node --test` both import this file.
|
||||||
|
|
||||||
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
|
const NAME_CHAR = /[a-z0-9-]/;
|
||||||
// by the workspace rules, and a query typed with a capital otherwise matches
|
|
||||||
// nothing and opens no suggestions at all.
|
|
||||||
const NAME_CHAR = /[a-z0-9-]/i;
|
|
||||||
const MAX_MATCHES = 6;
|
const MAX_MATCHES = 6;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -26,13 +23,11 @@ export function mentionAt(text, caret) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Names starting with the query first, then names containing it, in the
|
// Names starting with the query first, then names containing it, in the
|
||||||
// order given, at most six. Case-folded: folder names are lowercase by rule,
|
// order given, at most six.
|
||||||
// and "@Repo" should still find @repo rather than claim nothing matches.
|
|
||||||
export function matchNames(names, query) {
|
export function matchNames(names, query) {
|
||||||
const q = String(query || "").toLowerCase();
|
const q = String(query || "");
|
||||||
const fold = (n) => String(n).toLowerCase();
|
const prefix = names.filter((n) => n.startsWith(q));
|
||||||
const prefix = names.filter((n) => fold(n).startsWith(q));
|
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
|
||||||
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
|
|
||||||
return [...prefix, ...inside].slice(0, MAX_MATCHES);
|
return [...prefix, ...inside].slice(0, MAX_MATCHES);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -53,55 +53,16 @@ export const TASK_EVENTS = Object.freeze(new Set(Object.keys(TASK_BONUS)));
|
|||||||
// The most tasks one run may report: past this it is a typo, not a phase.
|
// The most tasks one run may report: past this it is a typo, not a phase.
|
||||||
export const MAX_TASKS = 999;
|
export const MAX_TASKS = 999;
|
||||||
|
|
||||||
// A build scores while it runs, not only once it is approved: console.mjs
|
|
||||||
// writes a `progress` ledger entry whenever a build's `headline.cleared`
|
|
||||||
// rises, and the build's row scores those tasks at TASKS_PER_POINT with no
|
|
||||||
// bonus. The phase's `run` then takes the row over with its final score, so
|
|
||||||
// the total only ever climbs. Workflows whose headline counts tasks:
|
|
||||||
export const PROGRESS_WORKFLOWS = Object.freeze(new Set(["implement", "implement-review"]));
|
|
||||||
|
|
||||||
// Implement + Review reviews every phase as a stage of the build. A `review`
|
|
||||||
// run inside it is that stage, so it scores the phase's TASK_BONUS when it
|
|
||||||
// starts, and the phase's own run leaves the bonus out after it.
|
|
||||||
const BUILT_IN_REVIEW = Object.freeze({ "implement-review": "implement-review-phase" });
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The ledger entry a build's progress post stands for, or null when it adds
|
|
||||||
* nothing: not a task-counting workflow, no whole `cleared`, or no more tasks
|
|
||||||
* than this build already has. `seg` is how many phases this skill run has
|
|
||||||
* finished, so a second phase in the same run starts its own count, but only
|
|
||||||
* once its headline is back at 0: until then a `cleared` is the finished
|
|
||||||
* phase's, posted again, and opening a build on it would count it twice.
|
|
||||||
*/
|
|
||||||
export function progressEntry(entries, launch, workflow, cleared) {
|
|
||||||
if (!PROGRESS_WORKFLOWS.has(workflow)) return null;
|
|
||||||
if (cleared !== 0 && !isTaskCount(cleared)) return null;
|
|
||||||
const list = Array.isArray(entries) ? entries : [];
|
|
||||||
const seg = list.filter((e) => e && e.kind === "run" && TASK_EVENTS.has(e.event) && launchOf(e.id) === launch).length;
|
|
||||||
const build = `${launch}:b${seg}`;
|
|
||||||
const mine = list.filter((e) => e && e.kind === "progress" && e.build === build);
|
|
||||||
const entry = (tasks) => ({ kind: "progress", id: `${build}:${tasks}`, build, workflow, tasks });
|
|
||||||
if (cleared === 0) return seg > 0 && !mine.length ? entry(0) : null;
|
|
||||||
if (seg > 0 && !mine.length) return null;
|
|
||||||
const most = mine.reduce((n, e) => Math.max(n, e.tasks), 0);
|
|
||||||
return cleared > most ? entry(cleared) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A valid `run.tasks`: a whole number from 1 to MAX_TASKS. */
|
/** A valid `run.tasks`: a whole number from 1 to MAX_TASKS. */
|
||||||
export function isTaskCount(tasks) {
|
export function isTaskCount(tasks) {
|
||||||
return Number.isInteger(tasks) && tasks >= 1 && tasks <= MAX_TASKS;
|
return Number.isInteger(tasks) && tasks >= 1 && tasks <= MAX_TASKS;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** What one `run` scores, from its event and (for a built phase) its tasks. */
|
||||||
* What one `run` scores, from its event and (for a built phase) its tasks.
|
export function runPoints(event, tasks) {
|
||||||
* `bonus: false` leaves the review bonus out, for a phase whose review
|
|
||||||
* already scored.
|
|
||||||
*/
|
|
||||||
export function runPoints(event, tasks, { bonus = true } = {}) {
|
|
||||||
if (TASK_EVENTS.has(event) && isTaskCount(tasks)) {
|
if (TASK_EVENTS.has(event) && isTaskCount(tasks)) {
|
||||||
return Math.ceil(tasks / TASKS_PER_POINT) + (bonus ? TASK_BONUS[event] : 0);
|
return Math.ceil(tasks / TASKS_PER_POINT) + TASK_BONUS[event];
|
||||||
}
|
}
|
||||||
if (TASK_EVENTS.has(event) && !bonus) return weightOf(event) - TASK_BONUS[event];
|
|
||||||
return weightOf(event);
|
return weightOf(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,8 +133,6 @@ export function breakdownFrom(entries) {
|
|||||||
const seen = new Set();
|
const seen = new Set();
|
||||||
const rows = [];
|
const rows = [];
|
||||||
const answers = new Map(); // launch id -> { row, count, workflow }
|
const answers = new Map(); // launch id -> { row, count, workflow }
|
||||||
const builds = new Map(); // launch id -> the row of the build in progress
|
|
||||||
const reviewed = new Set(); // launch ids whose built-in review has scored
|
|
||||||
for (const entry of Array.isArray(entries) ? entries : []) {
|
for (const entry of Array.isArray(entries) ? entries : []) {
|
||||||
if (!entry || typeof entry !== "object") continue;
|
if (!entry || typeof entry !== "object") continue;
|
||||||
if (entry.id !== undefined) {
|
if (entry.id !== undefined) {
|
||||||
@@ -191,54 +150,17 @@ export function breakdownFrom(entries) {
|
|||||||
tally.count += 1;
|
tally.count += 1;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (entry.kind === "progress") {
|
|
||||||
if (!isTaskCount(entry.tasks)) continue;
|
|
||||||
const launch = launchOf(entry.id);
|
|
||||||
let row = builds.get(launch);
|
|
||||||
if (!row || row.build !== entry.build) {
|
|
||||||
row = { label: "", points: 0, build: entry.build, tasks: 0 };
|
|
||||||
builds.set(launch, row);
|
|
||||||
rows.push(row);
|
|
||||||
}
|
|
||||||
if (entry.tasks > row.tasks) {
|
|
||||||
row.tasks = entry.tasks;
|
|
||||||
row.points = Math.ceil(entry.tasks / TASKS_PER_POINT);
|
|
||||||
const where = WORKFLOW_NAMES[entry.workflow] || "Build";
|
|
||||||
row.label = `${where}: ${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"} built so far`;
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let points = 0;
|
let points = 0;
|
||||||
let label = "";
|
let label = "";
|
||||||
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) {
|
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) {
|
||||||
points = weightOf(entry.workflow);
|
points = weightOf(entry.workflow);
|
||||||
label = LAUNCH_LABELS[entry.workflow] || entry.workflow;
|
label = LAUNCH_LABELS[entry.workflow] || entry.workflow;
|
||||||
} else if (entry.kind === "run") {
|
} else if (entry.kind === "run") {
|
||||||
const launch = launchOf(entry.id);
|
points = runPoints(entry.event, entry.tasks);
|
||||||
const builtIn = BUILT_IN_REVIEW[entry.workflow];
|
|
||||||
if (entry.event === "review" && builtIn) {
|
|
||||||
// The review stage of Implement + Review: it scores the bonus its
|
|
||||||
// phase would otherwise carry, once per skill run.
|
|
||||||
if (reviewed.has(launch)) continue;
|
|
||||||
reviewed.add(launch);
|
|
||||||
points = TASK_BONUS[builtIn];
|
|
||||||
label = `${WORKFLOW_NAMES[entry.workflow]}: code review run`;
|
|
||||||
} else {
|
|
||||||
const bonus = !(TASK_EVENTS.has(entry.event) && reviewed.has(launch));
|
|
||||||
points = runPoints(entry.event, entry.tasks, { bonus });
|
|
||||||
const unit = unitOf(entry.id);
|
const unit = unitOf(entry.id);
|
||||||
const counted = TASK_EVENTS.has(entry.event) && isTaskCount(entry.tasks);
|
const counted = TASK_EVENTS.has(entry.event) && isTaskCount(entry.tasks);
|
||||||
const size = counted ? ` (${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"})` : "";
|
const size = counted ? ` (${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"})` : "";
|
||||||
label = (RUN_LABELS[entry.event] || entry.event) + (unit && unit !== entry.event ? `: ${unit}` : "") + size;
|
label = (RUN_LABELS[entry.event] || entry.event) + (unit ? `: ${unit}` : "") + size;
|
||||||
}
|
|
||||||
// A finished phase takes over its build's progress row, in place.
|
|
||||||
if (TASK_EVENTS.has(entry.event) && builds.has(launch)) {
|
|
||||||
const row = builds.get(launch);
|
|
||||||
builds.delete(launch);
|
|
||||||
row.label = label;
|
|
||||||
row.points = Math.max(points, row.points);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (points > 0) rows.push({ label, points });
|
if (points > 0) rows.push({ label, points });
|
||||||
}
|
}
|
||||||
@@ -247,7 +169,7 @@ export function breakdownFrom(entries) {
|
|||||||
const where = WORKFLOW_NAMES[workflow] ? ` in ${WORKFLOW_NAMES[workflow]}` : "";
|
const where = WORKFLOW_NAMES[workflow] ? ` in ${WORKFLOW_NAMES[workflow]}` : "";
|
||||||
row.label = `${count} ${count === 1 ? "answer" : "answers"}${where}`;
|
row.label = `${count} ${count === 1 ? "answer" : "answers"}${where}`;
|
||||||
}
|
}
|
||||||
return rows.filter((row) => row.points > 0).map(({ label, points }) => ({ label, points }));
|
return rows.filter((row) => row.points > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The session's points, folded from ledger entries in order. */
|
/** The session's points, folded from ledger entries in order. */
|
||||||
|
|||||||
@@ -1,223 +0,0 @@
|
|||||||
// Plan2Code Web Console - the Subagents switch's opt-in table, wording and checks.
|
|
||||||
//
|
|
||||||
// The source of truth for which workflows offer the switch, the instruction
|
|
||||||
// each one ships with, the fixed frame every "on" block carries, the exact
|
|
||||||
// lines the agent reads at a pickup (blockFor()), and the house rules for the
|
|
||||||
// helpers an agent reports back (checkHelper()). No DOM access at module scope
|
|
||||||
// and no imports: the server, console.mjs, the page and `node --test` all
|
|
||||||
// import this file.
|
|
||||||
|
|
||||||
// The one place a skill opts in (FR-1). Wording is behaviour-level and names
|
|
||||||
// no harness tool, so any agent can follow it or harmlessly ignore it.
|
|
||||||
export const SUBAGENT_WORKFLOWS = Object.freeze({
|
|
||||||
implement: Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
|
||||||
}),
|
|
||||||
"implement-review": Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
|
||||||
}),
|
|
||||||
"quick-task": Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
|
||||||
}),
|
|
||||||
review: Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Split the review across helpers by area (for example correctness, tests and security), then merge and de-duplicate their findings yourself before you report.",
|
|
||||||
}),
|
|
||||||
pathfinder: Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
export function offered(workflow) {
|
|
||||||
return typeof workflow === "string" && Object.prototype.hasOwnProperty.call(SUBAGENT_WORKFLOWS, workflow);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const MAX_MIN = 1;
|
|
||||||
export const MAX_MAX = 20;
|
|
||||||
export const DEFAULT_MAX = 3;
|
|
||||||
export const INSTRUCTION_MAX_CHARS = 2000;
|
|
||||||
export const HELPER_TITLE_MAX = 80;
|
|
||||||
export const HELPER_ASK_MAX = 400;
|
|
||||||
export const HELPER_RESULT_MAX = 200;
|
|
||||||
export const HELPER_STATES = Object.freeze(["running", "done", "failed"]);
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------- settings */
|
|
||||||
|
|
||||||
export function defaultInstruction(workflow) {
|
|
||||||
return offered(workflow) ? SUBAGENT_WORKFLOWS[workflow].instruction : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// The person's own text when they wrote some, else the workflow's default.
|
|
||||||
export function effectiveInstruction(setting) {
|
|
||||||
const own = setting && typeof setting.instruction === "string" ? setting.instruction.trim() : "";
|
|
||||||
return own || defaultInstruction(setting && setting.workflow);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function defaultSetting(workflow) {
|
|
||||||
return { workflow, on: false, instruction: null, max: DEFAULT_MAX };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* `{ on, instruction, max }` from untrusted input, or `{ error }` naming the
|
|
||||||
* field that failed: "bad" (wrong type), "too-long" (instruction) or "max".
|
|
||||||
* Returns an error object rather than throwing, so the route and the store
|
|
||||||
* reader share one validator. An empty instruction means the default: null.
|
|
||||||
*/
|
|
||||||
export function cleanSetting(input) {
|
|
||||||
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "bad" };
|
|
||||||
if (typeof input.on !== "boolean") return { error: "bad" };
|
|
||||||
let instruction = null;
|
|
||||||
if (input.instruction !== null && input.instruction !== undefined) {
|
|
||||||
if (typeof input.instruction !== "string") return { error: "bad" };
|
|
||||||
const trimmed = input.instruction.trim();
|
|
||||||
if (trimmed.length > INSTRUCTION_MAX_CHARS) return { error: "too-long" };
|
|
||||||
instruction = trimmed || null;
|
|
||||||
}
|
|
||||||
const max = input.max;
|
|
||||||
if (!Number.isInteger(max) || max < MAX_MIN || max > MAX_MAX) return { error: "max" };
|
|
||||||
return { on: input.on, instruction, max };
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------ the lines */
|
|
||||||
|
|
||||||
// The non-editable part of every "on" block (FR-8).
|
|
||||||
export const FRAME_LINES = Object.freeze([
|
|
||||||
"Hand independent work to helpers if your tools allow it; otherwise carry on alone.",
|
|
||||||
"Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.",
|
|
||||||
'With no way to start helpers, report one "working alone" entry for this skill run instead.',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
|
|
||||||
|
|
||||||
// Only the first line of a block starts at column 0, so no line inside it can
|
|
||||||
// be read as an entry of its own (NFR-5).
|
|
||||||
export function onLines({ revision, replaces, max, instruction }) {
|
|
||||||
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
|
|
||||||
const own = String(instruction || "")
|
|
||||||
.split("\n")
|
|
||||||
.map((line) => line.trimEnd())
|
|
||||||
.filter((line) => line.trim());
|
|
||||||
return [
|
|
||||||
`Subagents: on (${label}) — a console setting, not typed by the person.`,
|
|
||||||
...[...FRAME_LINES, ...own, `At most ${max} helpers at once.`].map((line) => " " + line),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function offLine(revision) {
|
|
||||||
return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What the agent is owed at a pickup, given the session setting and the
|
|
||||||
* cursor of what it was last told: `null`, or `{ field, lines, cursor }`
|
|
||||||
* where `cursor` is what to write once the lines are printed. Never says
|
|
||||||
* "off" to an agent that was not told "on" (FR-6). Pure: no clock, no I/O.
|
|
||||||
*/
|
|
||||||
export function blockFor(setting, told) {
|
|
||||||
const last = told || { revision: 0, state: "none" };
|
|
||||||
if (!setting || !offered(setting.workflow) || !(setting.revision > last.revision)) return null;
|
|
||||||
const { revision, max } = setting;
|
|
||||||
const instruction = effectiveInstruction(setting);
|
|
||||||
if (setting.on) {
|
|
||||||
const replaces = last.state === "on" ? last.revision : undefined;
|
|
||||||
return {
|
|
||||||
field: { state: "on", revision, max, instruction },
|
|
||||||
lines: onLines({ revision, replaces, max, instruction }),
|
|
||||||
cursor: { revision, state: "on" },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (last.state !== "on") return null;
|
|
||||||
return {
|
|
||||||
field: { state: "off", revision, max, instruction },
|
|
||||||
lines: [offLine(revision)],
|
|
||||||
cursor: { revision, state: "off" },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------ helpers */
|
|
||||||
|
|
||||||
const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
||||||
const nonEmpty = (v) => typeof v === "string" && v.trim() !== "";
|
|
||||||
|
|
||||||
// The problems with one reported helper, [] when it is fine.
|
|
||||||
export function checkHelper(entry) {
|
|
||||||
if (!isPlainObject(entry)) return ["helper: each entry must be an object"];
|
|
||||||
if (!nonEmpty(entry.id)) return ["helper: id must be a non-empty string"];
|
|
||||||
const who = `helper "${entry.id}"`;
|
|
||||||
if (entry.alone === true) return entry.id === "alone" ? [] : [`${who}: the working-alone entry must have id "alone"`];
|
|
||||||
const problems = [];
|
|
||||||
if (!nonEmpty(entry.title)) problems.push(`${who}: title must be a non-empty string`);
|
|
||||||
else if (entry.title.length > HELPER_TITLE_MAX) problems.push(`${who}: title must be at most ${HELPER_TITLE_MAX} characters`);
|
|
||||||
if (!nonEmpty(entry.ask)) problems.push(`${who}: ask must be a non-empty string`);
|
|
||||||
else if (entry.ask.length > HELPER_ASK_MAX) problems.push(`${who}: ask must be at most ${HELPER_ASK_MAX} characters`);
|
|
||||||
if (!HELPER_STATES.includes(entry.state)) problems.push(`${who}: state must be running, done or failed`);
|
|
||||||
if (entry.result !== undefined) {
|
|
||||||
if (typeof entry.result !== "string") problems.push(`${who}: result must be a string`);
|
|
||||||
else if (entry.result.length > HELPER_RESULT_MAX) problems.push(`${who}: result must be at most ${HELPER_RESULT_MAX} characters`);
|
|
||||||
}
|
|
||||||
return problems;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The problems with a whole merged list.
|
|
||||||
export function checkHelpers(list) {
|
|
||||||
if (!Array.isArray(list)) return ["helpers must be an array"];
|
|
||||||
const problems = [];
|
|
||||||
const seen = new Set();
|
|
||||||
let alone = 0;
|
|
||||||
for (const entry of list) {
|
|
||||||
if (isPlainObject(entry) && nonEmpty(entry.id)) {
|
|
||||||
if (seen.has(entry.id)) problems.push(`helper "${entry.id}": duplicate id`);
|
|
||||||
seen.add(entry.id);
|
|
||||||
if (entry.alone === true && ++alone === 2) problems.push(`helper "${entry.id}": only one working-alone entry is allowed`);
|
|
||||||
}
|
|
||||||
problems.push(...checkHelper(entry));
|
|
||||||
}
|
|
||||||
return problems;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------ the page */
|
|
||||||
|
|
||||||
// The page's rules for the button, the modal and the tab, kept here so they
|
|
||||||
// are tested without a browser. `frame` is the state frame's `subagents`
|
|
||||||
// block; app.js only renders what these say.
|
|
||||||
|
|
||||||
export const CHECKIN_LINE = "Helpers report through Plan2Code, so their progress shows here at its check-ins, not live.";
|
|
||||||
|
|
||||||
const STATE_LABELS = Object.freeze({ running: "Running", done: "Done", failed: "Failed" });
|
|
||||||
|
|
||||||
// The switch shows only where the skill opts in AND the agent's console copy
|
|
||||||
// said it can deliver it (FR-3).
|
|
||||||
export function showSwitch(frame) {
|
|
||||||
return Boolean(frame && frame.offered && frame.supported);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The button's tooltip and accessible name (FR-2).
|
|
||||||
export function switchLabel(frame) {
|
|
||||||
return frame && frame.on ? "Subagents: on" : "Subagents: off";
|
|
||||||
}
|
|
||||||
|
|
||||||
// What the Subagents tab draws: the working-alone note, or one row per helper
|
|
||||||
// in the order the agent reported them. A result shows once the helper ended.
|
|
||||||
export function helperRows(helpers) {
|
|
||||||
const list = Array.isArray(helpers) ? helpers.filter(isPlainObject) : [];
|
|
||||||
if (list.some((h) => h.alone === true)) return { alone: true, rows: [] };
|
|
||||||
const rows = list.map(({ id, title, ask, state, result }) => ({
|
|
||||||
id,
|
|
||||||
title,
|
|
||||||
ask,
|
|
||||||
state,
|
|
||||||
stateLabel: STATE_LABELS[state] || STATE_LABELS.running,
|
|
||||||
...((state === "done" || state === "failed") && typeof result === "string" && result ? { result } : {}),
|
|
||||||
}));
|
|
||||||
return { alone: false, rows };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Never an empty tab. Independent of on / off, so Pathfinder's research
|
|
||||||
// helpers show even with the switch off (FR-11, FR-12).
|
|
||||||
export function showTab(frame, helpers) {
|
|
||||||
return showSwitch(frame) && Array.isArray(helpers) && helpers.length > 0;
|
|
||||||
}
|
|
||||||
@@ -25,21 +25,17 @@ import {
|
|||||||
LOOKS_FILE,
|
LOOKS_FILE,
|
||||||
PUBLIC_DIR,
|
PUBLIC_DIR,
|
||||||
SHIPPED_MODELS_FILE,
|
SHIPPED_MODELS_FILE,
|
||||||
SUBAGENTS_SETTING_FILE,
|
|
||||||
UPDATE_CHECK_FILE,
|
|
||||||
USER_MODELS_FILE,
|
USER_MODELS_FILE,
|
||||||
WORKSPACE_FILE,
|
WORKSPACE_FILE,
|
||||||
appendChat,
|
appendChat,
|
||||||
appendEvent,
|
appendEvent,
|
||||||
chatForFrame,
|
chatForFrame,
|
||||||
checkDocument,
|
checkDocument,
|
||||||
cleanupFindings,
|
|
||||||
currentConversation,
|
currentConversation,
|
||||||
ensureDir,
|
ensureDir,
|
||||||
fileStamp,
|
fileStamp,
|
||||||
handleFile,
|
handleFile,
|
||||||
initialWorkspace,
|
initialWorkspace,
|
||||||
latestOpenCaps,
|
|
||||||
nowIso,
|
nowIso,
|
||||||
parseArgs,
|
parseArgs,
|
||||||
pendingChatCount,
|
pendingChatCount,
|
||||||
@@ -48,28 +44,18 @@ import {
|
|||||||
readJson,
|
readJson,
|
||||||
readLedger,
|
readLedger,
|
||||||
readOverview,
|
readOverview,
|
||||||
readSubagentSetting,
|
|
||||||
readWorkspace,
|
readWorkspace,
|
||||||
rememberWorkspace,
|
|
||||||
rememberedWorkspace,
|
|
||||||
removeCleanup,
|
|
||||||
remoteWarning,
|
remoteWarning,
|
||||||
saveSubagentStoreEntry,
|
|
||||||
specKey,
|
|
||||||
subagentStoreEntry,
|
|
||||||
typedCount,
|
typedCount,
|
||||||
withStateLock,
|
withStateLock,
|
||||||
writeJsonAtomic,
|
writeJsonAtomic,
|
||||||
writeSubagentSetting,
|
|
||||||
writeWorkspace,
|
writeWorkspace,
|
||||||
} from "./lib.mjs";
|
} from "./lib.mjs";
|
||||||
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
|
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
|
||||||
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
|
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
|
||||||
import { meterView } from "./public/meter.js";
|
import { meterView } from "./public/meter.js";
|
||||||
import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
|
||||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||||
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
||||||
import { checkForUpdate } from "./update-check.mjs";
|
|
||||||
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
|
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
|
||||||
|
|
||||||
const args = parseArgs(process.argv.slice(2));
|
const args = parseArgs(process.argv.slice(2));
|
||||||
@@ -219,7 +205,6 @@ const SERVABLE = new Set([
|
|||||||
"starters.js",
|
"starters.js",
|
||||||
"workspace.js",
|
"workspace.js",
|
||||||
"meter.js",
|
"meter.js",
|
||||||
"subagents.js",
|
|
||||||
"mentions.js",
|
"mentions.js",
|
||||||
"favicon.js",
|
"favicon.js",
|
||||||
"start-stop.mp3",
|
"start-stop.mp3",
|
||||||
@@ -341,9 +326,7 @@ function workspaceNow() {
|
|||||||
return ws;
|
return ws;
|
||||||
}
|
}
|
||||||
const root = sessionWorktree();
|
const root = sessionWorktree();
|
||||||
const scope = specKey(stateNow?.specDir);
|
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
|
||||||
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
|
|
||||||
const fresh = { ...initialWorkspace(root || PROJECT, remembered), scope, remote: remoteWarning().remote || "" };
|
|
||||||
// There but unreadable for now (a scanner's lock): never written over, and
|
// There but unreadable for now (a scanner's lock): never written over, and
|
||||||
// never cached, so the next call reads it again.
|
// never cached, so the next call reads it again.
|
||||||
if (stamp) return workspaceSeen.ws || fresh;
|
if (stamp) return workspaceSeen.ws || fresh;
|
||||||
@@ -364,87 +347,13 @@ function saveWorkspace(ws) {
|
|||||||
|
|
||||||
// One change: a new version, an entry in the change log the agent is handed,
|
// One change: a new version, an entry in the change log the agent is handed,
|
||||||
// the file, and every open page.
|
// the file, and every open page.
|
||||||
function bumpWorkspace(ws, change, { remember = true } = {}) {
|
function bumpWorkspace(ws, change) {
|
||||||
ws.version = (ws.version || 0) + 1;
|
ws.version = (ws.version || 0) + 1;
|
||||||
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
|
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
|
||||||
saveWorkspace(ws);
|
saveWorkspace(ws);
|
||||||
// Remembered for the next console session too. A folder gone missing or
|
|
||||||
// found again is not a change of mind, so it is not saved.
|
|
||||||
if (remember) rememberNow(ws);
|
|
||||||
pushState();
|
pushState();
|
||||||
}
|
}
|
||||||
|
|
||||||
function rememberNow(ws) {
|
|
||||||
const root = sessionWorktree();
|
|
||||||
if (!root) return;
|
|
||||||
try {
|
|
||||||
rememberWorkspace(root, ws.scope || "", ws);
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Point the workspace at another spec ("" for the project's own list) and
|
|
||||||
* swap in what was remembered there, logging each difference as a change so
|
|
||||||
* the agent's cursor stays truthful. A spec with nothing saved starts from
|
|
||||||
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
|
|
||||||
* list it has and saves it as the spec's (`seed: "current"`, a spec created
|
|
||||||
* mid-run). Folders keep their ids when their path stays.
|
|
||||||
*/
|
|
||||||
function setScope(ws, spec, seed = "project") {
|
|
||||||
const root = sessionWorktree();
|
|
||||||
const next = specKey(spec);
|
|
||||||
if (!root || (ws.scope || "") === next) return false;
|
|
||||||
const found = rememberedWorkspace(root, next);
|
|
||||||
ws.scope = next;
|
|
||||||
if (next && found.from !== "spec" && seed === "current") {
|
|
||||||
saveWorkspace(ws);
|
|
||||||
rememberNow(ws);
|
|
||||||
pushState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
const want = initialWorkspace(root, found.entry).folders;
|
|
||||||
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
|
|
||||||
const kept = new Set();
|
|
||||||
const folders = [];
|
|
||||||
const changes = [];
|
|
||||||
for (const w of want) {
|
|
||||||
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
|
|
||||||
if (!have) {
|
|
||||||
folders.push({ ...w, id: "pending" });
|
|
||||||
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
kept.add(have);
|
|
||||||
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
|
|
||||||
if ((have.description || "") !== (w.description || "")) {
|
|
||||||
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
|
|
||||||
}
|
|
||||||
folders.push({ ...have, name: w.name, description: w.description || "" });
|
|
||||||
}
|
|
||||||
for (const f of ws.folders) {
|
|
||||||
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
|
|
||||||
}
|
|
||||||
ws.folders = folders.filter((f) => f.id !== "pending");
|
|
||||||
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
|
|
||||||
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
|
|
||||||
if (!changes.length) {
|
|
||||||
saveWorkspace(ws);
|
|
||||||
pushState();
|
|
||||||
}
|
|
||||||
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
|
|
||||||
checkFolders(ws);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
|
|
||||||
// learns its spec late) takes the workspace with it.
|
|
||||||
function followSpecDir(state) {
|
|
||||||
const spec = specKey(state && state.specDir);
|
|
||||||
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
|
|
||||||
const ws = workspaceNow();
|
|
||||||
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
|
|
||||||
}
|
|
||||||
|
|
||||||
function isFolder(p) {
|
function isFolder(p) {
|
||||||
try {
|
try {
|
||||||
return fs.statSync(p).isDirectory();
|
return fs.statSync(p).isDirectory();
|
||||||
@@ -461,10 +370,10 @@ function checkFolders(ws) {
|
|||||||
const marked = ws.missing.includes(f.id);
|
const marked = ws.missing.includes(f.id);
|
||||||
if (!there && !marked) {
|
if (!there && !marked) {
|
||||||
ws.missing = [...ws.missing, f.id];
|
ws.missing = [...ws.missing, f.id];
|
||||||
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
|
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path });
|
||||||
} else if (there && marked) {
|
} else if (there && marked) {
|
||||||
ws.missing = ws.missing.filter((id) => id !== f.id);
|
ws.missing = ws.missing.filter((id) => id !== f.id);
|
||||||
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
|
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -493,8 +402,8 @@ function folderIssues(entries) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function workspaceView() {
|
function workspaceView() {
|
||||||
const { folders, missing, remote, scope } = workspaceNow();
|
const { folders, missing, remote } = workspaceNow();
|
||||||
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ledgerEntries()) };
|
return { folders, missing: missing || [], remote: remote || "", issues: folderIssues(ledgerEntries()) };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Whether child sits strictly under parent.
|
// Whether child sits strictly under parent.
|
||||||
@@ -583,7 +492,6 @@ function bootWorkspace() {
|
|||||||
saveWorkspace(ws);
|
saveWorkspace(ws);
|
||||||
}
|
}
|
||||||
checkFolders(ws);
|
checkFolders(ws);
|
||||||
followSpecDir(stateNow);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -609,48 +517,6 @@ function ensureConversation(state) {
|
|||||||
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------ subagents */
|
|
||||||
|
|
||||||
// subagents-setting.json has one writer, this server, and the agent hears of
|
|
||||||
// it only through what console.mjs reads there; events.ndjson's latest `open`
|
|
||||||
// says whether the agent's console copy can carry it. Both re-read only when
|
|
||||||
// their file has moved.
|
|
||||||
const SUBAGENTS_SETTING_PATH = path.join(DIR, SUBAGENTS_SETTING_FILE);
|
|
||||||
const EVENTS_PATH = path.join(DIR, "events.ndjson");
|
|
||||||
|
|
||||||
let subagentSettingSeen = { stamp: null, setting: null };
|
|
||||||
function subagentSettingNow() {
|
|
||||||
const stamp = fileStamp(SUBAGENTS_SETTING_PATH);
|
|
||||||
if (stamp !== subagentSettingSeen.stamp) subagentSettingSeen = { stamp, setting: readSubagentSetting(DIR) };
|
|
||||||
return subagentSettingSeen.setting;
|
|
||||||
}
|
|
||||||
|
|
||||||
let capsSeen = { stamp: null, caps: [] };
|
|
||||||
function openCapsNow() {
|
|
||||||
const stamp = fileStamp(EVENTS_PATH);
|
|
||||||
if (stamp !== capsSeen.stamp) capsSeen = { stamp, caps: latestOpenCaps(DIR) };
|
|
||||||
return capsSeen.caps;
|
|
||||||
}
|
|
||||||
|
|
||||||
const sameSetting = (a, b) => a.workflow === b.workflow && a.on === b.on && a.instruction === b.instruction && a.max === b.max;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Turn the per-project store into this session's setting, for the workflow
|
|
||||||
* the session is in now. The only place that happens (FR-7): a session an
|
|
||||||
* older server ran has no setting file, so nothing is ever injected into it.
|
|
||||||
* A record that already matches is left alone, revision and all, so a
|
|
||||||
* restart alone never re-tells the agent anything.
|
|
||||||
*/
|
|
||||||
function syncSubagentSetting(state) {
|
|
||||||
if (!state || typeof state.workflow !== "string") return;
|
|
||||||
const { workflow } = state;
|
|
||||||
const { on, instruction, max } = offered(workflow) ? subagentStoreEntry(sessionWorktree(), workflow) : defaultSetting(workflow);
|
|
||||||
const target = { workflow, on, instruction, max };
|
|
||||||
const current = readSubagentSetting(DIR);
|
|
||||||
if (current && sameSetting(current, target)) return;
|
|
||||||
writeSubagentSetting(DIR, { ...target, revision: (current ? current.revision : 0) + 1 });
|
|
||||||
}
|
|
||||||
|
|
||||||
// What the page needs to draw itself, in the shape of the SSE state frame.
|
// What the page needs to draw itself, in the shape of the SSE state frame.
|
||||||
// `have` names that exact view, for the page to hand back when it opens its
|
// `have` names that exact view, for the page to hand back when it opens its
|
||||||
// stream (see /events).
|
// stream (see /events).
|
||||||
@@ -665,33 +531,19 @@ function stateFrame(state) {
|
|||||||
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
||||||
workspace: workspaceView(),
|
workspace: workspaceView(),
|
||||||
meter: meterView(ledgerEntries()),
|
meter: meterView(ledgerEntries()),
|
||||||
subagents: subagentsView(state),
|
|
||||||
...(updateInfo ? { update: updateInfo } : {}),
|
|
||||||
have: haveKey(),
|
have: haveKey(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// The page shows the switch only when `offered && supported` (FR-3); the
|
|
||||||
// frame says both and leaves combining them to the page. `instruction: null`
|
|
||||||
// is the shipped default, which the page reads from subagents.js itself.
|
|
||||||
function subagentsView(state) {
|
|
||||||
const workflow = state && state.workflow;
|
|
||||||
const { on, instruction, max, revision } = subagentSettingNow() || { ...defaultSetting(workflow), revision: 0 };
|
|
||||||
return { offered: offered(workflow), supported: openCapsNow().includes("subagents"), on, instruction, max, revision };
|
|
||||||
}
|
|
||||||
|
|
||||||
function haveKey() {
|
function haveKey() {
|
||||||
const { pending, stop } = resultFlags();
|
const { pending, stop } = resultFlags();
|
||||||
chatEntries();
|
chatEntries();
|
||||||
chatPickedUp();
|
chatPickedUp();
|
||||||
workspaceNow();
|
workspaceNow();
|
||||||
ledgerEntries();
|
ledgerEntries();
|
||||||
subagentSettingNow();
|
|
||||||
openCapsNow();
|
|
||||||
return (
|
return (
|
||||||
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
|
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
|
||||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
|
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
|
||||||
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -716,12 +568,6 @@ function recordSubmitted(state, actions) {
|
|||||||
if (action.type === "comment") {
|
if (action.type === "comment") {
|
||||||
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
|
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
|
||||||
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
|
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
|
||||||
// The person's side of the Notes thread. Left to the agent it was never
|
|
||||||
// written, so a question asked in a note vanished once it was picked up
|
|
||||||
// and the reply under it answered nothing on the page.
|
|
||||||
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
|
|
||||||
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
|
|
||||||
}
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const { i, type, ...rest } = action;
|
const { i, type, ...rest } = action;
|
||||||
@@ -1007,38 +853,6 @@ function pushState() {
|
|||||||
if (stateNow) broadcast("state", stateFrame(stateNow));
|
if (stateNow) broadcast("state", stateFrame(stateNow));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------- update check */
|
|
||||||
|
|
||||||
// The version this console was installed as: install.js writes version.json
|
|
||||||
// beside console.mjs; a dev checkout falls back to the repo root's.
|
|
||||||
function installedVersion() {
|
|
||||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
|
||||||
const version = readJson(file, {}).version;
|
|
||||||
if (typeof version === "string" && version) return version;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filled in once the boot-time check answers; until then, and whenever it
|
|
||||||
// fails, the frame carries no `update` and the page shows no banner.
|
|
||||||
let updateInfo = null;
|
|
||||||
let updateLatest = null;
|
|
||||||
|
|
||||||
// Started at boot and never awaited: git may take up to its 10 s limit, and
|
|
||||||
// nothing the person sees waits on it. The catch is not optional: a throw in
|
|
||||||
// pushState() would otherwise be an unhandled rejection, which ends the server.
|
|
||||||
function startUpdateCheck() {
|
|
||||||
const installed = installedVersion();
|
|
||||||
if (!installed) return;
|
|
||||||
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
|
|
||||||
.then((result) => {
|
|
||||||
updateLatest = result?.latest ?? null;
|
|
||||||
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
|
|
||||||
if (updateInfo) pushState();
|
|
||||||
})
|
|
||||||
.catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
let agentSeenAt = Date.now();
|
let agentSeenAt = Date.now();
|
||||||
function agentLastSeen() {
|
function agentLastSeen() {
|
||||||
return new Date(agentSeenAt).toISOString();
|
return new Date(agentSeenAt).toISOString();
|
||||||
@@ -1145,8 +959,10 @@ const server = http.createServer((req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (pathname === "/version" && req.method === "GET") {
|
if (pathname === "/version" && req.method === "GET") {
|
||||||
const version = installedVersion();
|
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||||
if (version) return json(res, 200, { version, latest: updateLatest });
|
const version = readJson(file, {}).version;
|
||||||
|
if (typeof version === "string" && version) return json(res, 200, { version });
|
||||||
|
}
|
||||||
return json(res, 404, { error: "no version" });
|
return json(res, 404, { error: "no version" });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1194,7 +1010,7 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/draft" && req.method === "POST") {
|
if (pathname === "/draft" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (err, body) => {
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||||
// Debounced client-side; this is just the durable mirror. Twenty minutes
|
// Debounced client-side; this is just the durable mirror. Twenty minutes
|
||||||
// of someone's structured answers must not die with a closed tab.
|
// of someone's structured answers must not die with a closed tab.
|
||||||
try {
|
try {
|
||||||
@@ -1219,7 +1035,7 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/looks" && req.method === "POST") {
|
if (pathname === "/looks" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (err, body) => {
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||||
// `set` carries only the keys one tab changed, merged onto what is on
|
// `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.
|
// disk, so a tab holding stale settings cannot undo another tab's change.
|
||||||
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
|
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
|
||||||
@@ -1235,39 +1051,6 @@ const server = http.createServer((req, res) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Subagents switch for the session's workflow. Saved per project folder
|
|
||||||
// for the next session, and applied to this one with a bumped revision, which
|
|
||||||
// is what console.mjs hands the agent at its next pickup. Never blocked by,
|
|
||||||
// and never blocking, a card send.
|
|
||||||
if (pathname === "/subagents" && req.method === "POST") {
|
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
|
||||||
return readBody(req, (err, body) => {
|
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
|
||||||
const state = readState();
|
|
||||||
if (!state || !offered(state.workflow)) return json(res, 400, { error: "not-offered" });
|
|
||||||
const clean = cleanSetting(body);
|
|
||||||
if (clean.error) return json(res, 400, { error: clean.error });
|
|
||||||
const { on, instruction, max } = clean;
|
|
||||||
const current = readSubagentSetting(DIR);
|
|
||||||
const next = { workflow: state.workflow, on, instruction, max };
|
|
||||||
// The store is per project, so another session may have moved it since
|
|
||||||
// this one synced: it always takes the person's latest pick. Only a
|
|
||||||
// real change to this session's setting bumps what the agent hears.
|
|
||||||
const unchanged = Boolean(current && sameSetting(current, next));
|
|
||||||
try {
|
|
||||||
saveSubagentStoreEntry(sessionWorktree(), state.workflow, { on, instruction, max });
|
|
||||||
if (!unchanged) writeSubagentSetting(DIR, { ...next, revision: (current ? current.revision : 0) + 1 });
|
|
||||||
} catch (e) {
|
|
||||||
return json(res, 500, { error: String(e.message) });
|
|
||||||
}
|
|
||||||
if (unchanged) return json(res, 200, { ok: true, setting: current });
|
|
||||||
const setting = readSubagentSetting(DIR);
|
|
||||||
appendEvent(DIR, { type: "subagents", on, revision: setting.revision });
|
|
||||||
pushState();
|
|
||||||
return json(res, 200, { ok: true, setting });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// The launcher's model menu: what ships (read-only here) and what the user added.
|
// The launcher's model menu: what ships (read-only here) and what the user added.
|
||||||
if (pathname === "/models" && req.method === "GET") {
|
if (pathname === "/models" && req.method === "GET") {
|
||||||
const saved = readJson(USER_MODELS_FILE, null) || {};
|
const saved = readJson(USER_MODELS_FILE, null) || {};
|
||||||
@@ -1278,7 +1061,7 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/models" && req.method === "POST") {
|
if (pathname === "/models" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (err, body) => {
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||||
const { models, error } = cleanModels(body && body.models);
|
const { models, error } = cleanModels(body && body.models);
|
||||||
if (error) return json(res, 400, { error });
|
if (error) return json(res, 400, { error });
|
||||||
try {
|
try {
|
||||||
@@ -1291,24 +1074,6 @@ const server = http.createServer((req, res) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
|
|
||||||
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
|
|
||||||
// still finds. Never this session, never a path the page sent.
|
|
||||||
if (pathname === "/cleanup" && req.method === "POST") {
|
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
|
||||||
return readBody(req, (err, body) => {
|
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
|
||||||
if (body && Array.isArray(body.delete)) {
|
|
||||||
return removeCleanup(body.delete, { skipSid: SID })
|
|
||||||
.then((done) => json(res, 200, { ok: true, ...done }))
|
|
||||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
|
||||||
}
|
|
||||||
return cleanupFindings({ skipSid: SID })
|
|
||||||
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
|
|
||||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pathname === "/upload" && req.method === "POST") {
|
if (pathname === "/upload" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
const contentType = String(req.headers["content-type"] || "");
|
const contentType = String(req.headers["content-type"] || "");
|
||||||
@@ -1415,7 +1180,7 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/submit" && req.method === "POST") {
|
if (pathname === "/submit" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (err, body) => {
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||||
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
|
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
|
||||||
return json(res, 400, { error: "actions must be a non-empty array" });
|
return json(res, 400, { error: "actions must be a non-empty array" });
|
||||||
}
|
}
|
||||||
@@ -1496,9 +1261,6 @@ const server = http.createServer((req, res) => {
|
|||||||
try {
|
try {
|
||||||
ensureConversation(written.state);
|
ensureConversation(written.state);
|
||||||
} catch {}
|
} catch {}
|
||||||
try {
|
|
||||||
syncSubagentSetting(written.state);
|
|
||||||
} catch {}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Name the items that went. A page with OTHER answers staged should drop
|
// Name the items that went. A page with OTHER answers staged should drop
|
||||||
@@ -1519,7 +1281,6 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/chat" && req.method === "POST") {
|
if (pathname === "/chat" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (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 (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||||
const state = readState() || {};
|
const state = readState() || {};
|
||||||
const current = currentConversation(chatEntries()).conversation;
|
const current = currentConversation(chatEntries()).conversation;
|
||||||
@@ -1583,7 +1344,6 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/chat/decision" && req.method === "POST") {
|
if (pathname === "/chat/decision" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (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 (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" });
|
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
|
||||||
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
|
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
|
||||||
@@ -1632,7 +1392,6 @@ const server = http.createServer((req, res) => {
|
|||||||
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
|
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (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 (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||||
let answer;
|
let answer;
|
||||||
try {
|
try {
|
||||||
@@ -1644,25 +1403,6 @@ const server = http.createServer((req, res) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Which list the workspace is: a spec's, or the project's (`spec` empty).
|
|
||||||
// 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.
|
|
||||||
if (pathname === "/workspace/scope" && req.method === "POST") {
|
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
|
||||||
return readBody(req, (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 : "";
|
|
||||||
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
|
|
||||||
try {
|
|
||||||
setScope(workspaceNow(), spec, "project");
|
|
||||||
} catch (e) {
|
|
||||||
return json(res, 500, { error: String(e.message) });
|
|
||||||
}
|
|
||||||
return json(res, 200, workspaceView());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only ever returns a path: the page then adds it through /workspace/add.
|
// Only ever returns a path: the page then adds it through /workspace/add.
|
||||||
if (pathname === "/workspace/browse" && req.method === "POST") {
|
if (pathname === "/workspace/browse" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
@@ -1751,19 +1491,15 @@ function readBody(req, cb) {
|
|||||||
let tooBig = false;
|
let tooBig = false;
|
||||||
req.on("data", (c) => {
|
req.on("data", (c) => {
|
||||||
size += c.length;
|
size += c.length;
|
||||||
// Drain past the cap rather than destroy, exactly like readRaw: a
|
|
||||||
// destroyed request emits 'close', never 'end' or 'error', so cb would
|
|
||||||
// never run and the page would see a reset instead of the 413 that names
|
|
||||||
// the problem.
|
|
||||||
if (size > MAX_BODY) {
|
if (size > MAX_BODY) {
|
||||||
tooBig = true;
|
tooBig = true;
|
||||||
chunks.length = 0;
|
req.destroy();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
chunks.push(c);
|
chunks.push(c);
|
||||||
});
|
});
|
||||||
req.on("end", () => {
|
req.on("end", () => {
|
||||||
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
|
if (tooBig) return cb(new Error("too large"));
|
||||||
try {
|
try {
|
||||||
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -1825,12 +1561,6 @@ function checkState() {
|
|||||||
try {
|
try {
|
||||||
ensureConversation(parsed);
|
ensureConversation(parsed);
|
||||||
} catch {}
|
} catch {}
|
||||||
try {
|
|
||||||
syncSubagentSetting(parsed);
|
|
||||||
} catch {}
|
|
||||||
try {
|
|
||||||
followSpecDir(parsed);
|
|
||||||
} catch {}
|
|
||||||
pushState();
|
pushState();
|
||||||
}
|
}
|
||||||
lastStateStamp = stamp;
|
lastStateStamp = stamp;
|
||||||
@@ -2002,13 +1732,7 @@ function onListening(port) {
|
|||||||
try {
|
try {
|
||||||
bootWorkspace();
|
bootWorkspace();
|
||||||
} catch {}
|
} catch {}
|
||||||
try {
|
|
||||||
syncSubagentSetting(readState());
|
|
||||||
} catch {}
|
|
||||||
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
||||||
try {
|
|
||||||
startUpdateCheck();
|
|
||||||
} catch {}
|
|
||||||
try {
|
try {
|
||||||
process.send?.({ type: "listening", port });
|
process.send?.({ type: "listening", port });
|
||||||
} catch {}
|
} catch {}
|
||||||
|
|||||||
@@ -1,138 +0,0 @@
|
|||||||
// Plan2Code Web Console - is a newer Plan2Code release out?
|
|
||||||
//
|
|
||||||
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
|
|
||||||
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
|
|
||||||
// release tag is "latest". The server
|
|
||||||
// starts this at boot and never waits on it; the answer, failures included, is
|
|
||||||
// cached for an hour so a burst of sessions asks GitHub once.
|
|
||||||
//
|
|
||||||
// Nothing here reads, stores or sends a credential: git authenticates itself,
|
|
||||||
// with every prompt turned off so a missing login fails fast instead of
|
|
||||||
// opening a window nobody asked for.
|
|
||||||
//
|
|
||||||
// Node built-ins only.
|
|
||||||
|
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { spawn } from "node:child_process";
|
|
||||||
|
|
||||||
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
|
|
||||||
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
|
||||||
export const CACHE_MS = 60 * 60 * 1000;
|
|
||||||
|
|
||||||
const SEMVER = /^\d+\.\d+\.\d+$/;
|
|
||||||
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
|
|
||||||
|
|
||||||
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
|
|
||||||
export function compareVersions(a, b) {
|
|
||||||
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
|
|
||||||
const x = a.split(".").map(Number);
|
|
||||||
const y = b.split(".").map(Number);
|
|
||||||
for (let i = 0; i < 3; i++) {
|
|
||||||
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
|
|
||||||
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
|
|
||||||
* pre-releases or other tag names are ignored. Null when nothing matches.
|
|
||||||
*/
|
|
||||||
export function latestTag(text) {
|
|
||||||
if (typeof text !== "string") return null;
|
|
||||||
let best = null;
|
|
||||||
for (const line of text.split(/\r?\n/)) {
|
|
||||||
const m = TAG_REF.exec(line.trim());
|
|
||||||
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
|
|
||||||
}
|
|
||||||
return best;
|
|
||||||
}
|
|
||||||
|
|
||||||
function readCache(cacheFile, now) {
|
|
||||||
try {
|
|
||||||
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
|
|
||||||
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
|
|
||||||
return typeof cached.latest === "string" ? cached.latest : null;
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function writeCache(cacheFile, data) {
|
|
||||||
const tmp = cacheFile + "." + process.pid + ".tmp";
|
|
||||||
try {
|
|
||||||
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
|
|
||||||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
|
|
||||||
fs.renameSync(tmp, cacheFile);
|
|
||||||
} catch {
|
|
||||||
try {
|
|
||||||
fs.rmSync(tmp, { force: true });
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
|
|
||||||
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
|
|
||||||
* window, no prompt.
|
|
||||||
*/
|
|
||||||
export function runLsRemote({ timeoutMs = 10000 } = {}) {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
let settled = false;
|
|
||||||
const done = (value) => {
|
|
||||||
if (settled) return;
|
|
||||||
settled = true;
|
|
||||||
clearTimeout(timer);
|
|
||||||
resolve(value);
|
|
||||||
};
|
|
||||||
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
|
|
||||||
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
|
|
||||||
let child;
|
|
||||||
try {
|
|
||||||
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
|
|
||||||
shell: false,
|
|
||||||
windowsHide: true,
|
|
||||||
stdio: ["ignore", "pipe", "ignore"],
|
|
||||||
env,
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
return resolve(null);
|
|
||||||
}
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
try {
|
|
||||||
child.kill();
|
|
||||||
} catch {}
|
|
||||||
done(null);
|
|
||||||
}, timeoutMs);
|
|
||||||
timer.unref?.();
|
|
||||||
let out = "";
|
|
||||||
child.stdout.setEncoding("utf8");
|
|
||||||
child.stdout.on("data", (chunk) => {
|
|
||||||
out += chunk;
|
|
||||||
});
|
|
||||||
child.on("error", () => done(null));
|
|
||||||
child.on("close", (code) => done(code === 0 ? out : null));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether `installed` is behind the newest release: `{ installed, latest,
|
|
||||||
* updateAvailable }`, or null when either version is unknown. Reuses a cache
|
|
||||||
* under an hour old, and caches a failed lookup as `latest: null` so it is
|
|
||||||
* not retried until the hour is up. Never throws.
|
|
||||||
*/
|
|
||||||
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
|
|
||||||
try {
|
|
||||||
let latest = readCache(cacheFile, now);
|
|
||||||
if (latest === undefined) {
|
|
||||||
latest = latestTag(await run());
|
|
||||||
writeCache(cacheFile, { checkedAt: now, latest });
|
|
||||||
}
|
|
||||||
const order = compareVersions(installed, latest);
|
|
||||||
if (latest === null || order === null) return null;
|
|
||||||
return { installed, latest, updateAvailable: order < 0 };
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "Plan2Code",
|
"name": "Plan2Code",
|
||||||
"version": "2.5.0",
|
"version": "2.4.1",
|
||||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"ai",
|
"ai",
|
||||||
@@ -17,6 +17,6 @@
|
|||||||
"url": "https://github.com/jparkerweb/plan2code"
|
"url": "https://github.com/jparkerweb/plan2code"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||||
"releaseDate": "2026-10-06",
|
"releaseDate": "2026-10-02",
|
||||||
"mode": "utility"
|
"mode": "utility"
|
||||||
}
|
}
|
||||||
@@ -1,247 +0,0 @@
|
|||||||
// Plan2Code skill scripts: shared plumbing.
|
|
||||||
//
|
|
||||||
// Every script in a skill's scripts/ directory imports this file. It owns the
|
|
||||||
// conventions the SKILL.md prompts rely on, so they are identical everywhere:
|
|
||||||
//
|
|
||||||
// stdout one JSON object, always. `{ "ok": true, ... }` on success,
|
|
||||||
// `{ "ok": false, "error": "<code>", "message": "...", "next": "..." }`
|
|
||||||
// on a handled failure.
|
|
||||||
// stderr a one-line human diagnostic on failure (the same message + next).
|
|
||||||
// exit 0 ok · 1 unexpected crash · 2 bad arguments · 3 not found ·
|
|
||||||
// 4 invalid input or a check that failed · 5 refused (would clobber
|
|
||||||
// or break a rule).
|
|
||||||
//
|
|
||||||
// Node 18+ built-ins only, no build step: this ships inside every skill.
|
|
||||||
|
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
||||||
|
|
||||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
||||||
|
|
||||||
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
|
|
||||||
|
|
||||||
export class CliError extends Error {
|
|
||||||
constructor(exit, error, message, next) {
|
|
||||||
super(message);
|
|
||||||
this.exit = exit;
|
|
||||||
this.error = error;
|
|
||||||
this.next = next;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
|
|
||||||
export function fail(exit, error, message, next) {
|
|
||||||
throw new CliError(exit, error, message, next);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function out(obj) {
|
|
||||||
process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse argv into { _: positionals, <flag>: value }.
|
|
||||||
* `booleans` names flags that take no value; every other `--flag` takes the
|
|
||||||
* next argument, and repeats of a flag listed in `lists` collect into an array.
|
|
||||||
* `--flag=value` works too. Unknown flags are a usage error, so a typo never
|
|
||||||
* silently changes behavior.
|
|
||||||
*/
|
|
||||||
export function parseArgs(argv, { booleans = [], values = [], lists = [] } = {}) {
|
|
||||||
const known = new Set([...booleans, ...values, ...lists, "help"]);
|
|
||||||
const args = { _: [] };
|
|
||||||
for (let i = 0; i < argv.length; i++) {
|
|
||||||
const a = argv[i];
|
|
||||||
if (!a.startsWith("--")) {
|
|
||||||
args._.push(a);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let name = a.slice(2);
|
|
||||||
let value;
|
|
||||||
const eq = name.indexOf("=");
|
|
||||||
if (eq !== -1) {
|
|
||||||
value = name.slice(eq + 1);
|
|
||||||
name = name.slice(0, eq);
|
|
||||||
}
|
|
||||||
if (!known.has(name)) {
|
|
||||||
fail(EXIT.USAGE, "unknown-flag", `Unknown flag --${name}.`, "Run with --help for the flags this script takes.");
|
|
||||||
}
|
|
||||||
if (name === "help" || booleans.includes(name)) {
|
|
||||||
args[name] = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (value === undefined) {
|
|
||||||
if (i + 1 >= argv.length) {
|
|
||||||
fail(EXIT.USAGE, "missing-value", `--${name} needs a value.`, "Run with --help for usage.");
|
|
||||||
}
|
|
||||||
value = argv[++i];
|
|
||||||
}
|
|
||||||
if (lists.includes(name)) (args[name] ||= []).push(value);
|
|
||||||
else args[name] = value;
|
|
||||||
}
|
|
||||||
return args;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Run a script's main(). Prints usage on --help, turns CliError into the JSON
|
|
||||||
* failure shape plus an exit code, and anything else into exit 1 with the stack
|
|
||||||
* on stderr. Sets process.exitCode rather than calling process.exit(), so
|
|
||||||
* stdout is never cut off mid-write.
|
|
||||||
*/
|
|
||||||
export async function run(usage, main) {
|
|
||||||
try {
|
|
||||||
const argv = process.argv.slice(2);
|
|
||||||
if (argv.includes("--help") || argv.includes("-h")) {
|
|
||||||
process.stdout.write(usage.trim() + "\n");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await main(argv);
|
|
||||||
} catch (err) {
|
|
||||||
if (err instanceof CliError) {
|
|
||||||
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
|
|
||||||
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
|
|
||||||
process.exitCode = err.exit;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
process.stderr.write(`unexpected error: ${err && err.stack ? err.stack : err}\n`);
|
|
||||||
out({ ok: false, error: "crash", message: String(err && err.message ? err.message : err) });
|
|
||||||
process.exitCode = EXIT.CRASH;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ time */
|
|
||||||
|
|
||||||
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
|
|
||||||
// clock, for tests and for reproducing a run. Otherwise: the local clock, which
|
|
||||||
// is what "today" means to the person reading the date in their files.
|
|
||||||
export function now() {
|
|
||||||
const pinned = process.env.PLAN2CODE_NOW;
|
|
||||||
if (pinned) {
|
|
||||||
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
|
|
||||||
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
|
|
||||||
const d = new Date(pinned);
|
|
||||||
if (!Number.isNaN(d.getTime())) return d;
|
|
||||||
}
|
|
||||||
return new Date();
|
|
||||||
}
|
|
||||||
|
|
||||||
const pad = (n) => String(n).padStart(2, "0");
|
|
||||||
|
|
||||||
/** YYYY-MM-DD */
|
|
||||||
export function isoDate(d = now()) {
|
|
||||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** YYYYMMDD */
|
|
||||||
export function compactDate(d = now()) {
|
|
||||||
return isoDate(d).replace(/-/g, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
/** YYYY-MM-DD HH:mm */
|
|
||||||
export function stamp(d = now()) {
|
|
||||||
return `${isoDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** HHMMSS */
|
|
||||||
export function clock(d = now()) {
|
|
||||||
return `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ----------------------------------------------------------------- files */
|
|
||||||
|
|
||||||
export function readText(file) {
|
|
||||||
try {
|
|
||||||
return fs.readFileSync(file, "utf8");
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isDir(p) {
|
|
||||||
try {
|
|
||||||
return fs.statSync(p).isDirectory();
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Write a file only when its content changes. Returns true when it wrote. */
|
|
||||||
export function writeIfChanged(file, content) {
|
|
||||||
const current = readText(file);
|
|
||||||
if (current === content) return false;
|
|
||||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
||||||
fs.writeFileSync(file, content);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Normalise line endings for parsing; keep the original for writing back. */
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
|
|
||||||
export function rel(root, p) {
|
|
||||||
return path.relative(root, p).split(path.sep).join("/") || ".";
|
|
||||||
}
|
|
||||||
|
|
||||||
/* --------------------------------------------------------- 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
|
|
||||||
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
|
|
||||||
// metrics-bait scan, so the scripts import it rather than keep a second copy.
|
|
||||||
const CONSOLE_LIB_CANDIDATES = [
|
|
||||||
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
|
|
||||||
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
|
|
||||||
];
|
|
||||||
|
|
||||||
let consoleLibPromise;
|
|
||||||
export function consoleLib() {
|
|
||||||
consoleLibPromise ||= (async () => {
|
|
||||||
for (const candidate of CONSOLE_LIB_CANDIDATES) {
|
|
||||||
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
|
|
||||||
}
|
|
||||||
fail(
|
|
||||||
EXIT.NOT_FOUND,
|
|
||||||
"console-lib-missing",
|
|
||||||
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
|
|
||||||
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
|
|
||||||
);
|
|
||||||
})();
|
|
||||||
return consoleLibPromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
|
|
||||||
export function version() {
|
|
||||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
|
||||||
const text = readText(file);
|
|
||||||
if (!text) continue;
|
|
||||||
try {
|
|
||||||
const v = JSON.parse(text).version;
|
|
||||||
if (typeof v === "string") return v;
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -1,676 +0,0 @@
|
|||||||
#!/usr/bin/env node
|
|
||||||
// specs.mjs: where every spec under specs/ stands, read from its files.
|
|
||||||
//
|
|
||||||
// The pipeline skills (plan, document, implement, revise-plan, finalize,
|
|
||||||
// review, handoff) all need the same filesystem facts: which specs exist, what
|
|
||||||
// a spec's PLAN-DRAFT says, which phases are open, how many tasks are done.
|
|
||||||
// Those have one correct answer, so this script computes them instead of each
|
|
||||||
// prompt re-deriving them by hand. It also performs the two mechanical writes
|
|
||||||
// (a Phase Checklist marker, the archive move), with --dry-run.
|
|
||||||
//
|
|
||||||
// Shell listing only matters to people: specs/ is gitignored, so editor search
|
|
||||||
// tools skip it. This script reads the disk directly and does not care.
|
|
||||||
|
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, consoleLib, isoDate, phaseFiles } from "./common.mjs";
|
|
||||||
|
|
||||||
const USAGE = `
|
|
||||||
specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
|
|
||||||
|
|
||||||
node specs.mjs list [--root <dir>]
|
|
||||||
Every active spec under specs/ (never specs--completed/), newest first:
|
|
||||||
state, detail, PLAN-DRAFT files with their **Status:** line, overview,
|
|
||||||
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
|
|
||||||
Groups, per-phase task counts by marker, task-numbering problems,
|
|
||||||
completion, the implement phase-selection verdict ("next"), the pending
|
|
||||||
phases, and consistency checks. <spec> is specs/<name>, <name>, or a path
|
|
||||||
to its overview.md.
|
|
||||||
|
|
||||||
node specs.mjs metrics <spec> --step document|finalize [--set key=value ...]
|
|
||||||
The METRICS_JSON comment for that step, countable fields computed from
|
|
||||||
the files; judgment fields come from --set (numbers only).
|
|
||||||
document: total_tasks, tasks_per_phase, phase_count,
|
|
||||||
parallel_groups_identified computed; pass
|
|
||||||
--set verification_items_added=N (your Verification Summary's
|
|
||||||
Added total; the VERIFICATION comments are reported as a check).
|
|
||||||
finalize: completion_rate_at_audit, tasks_completed, tasks_total; pass
|
|
||||||
--set verification_failures_found=N
|
|
||||||
--set documentation_updates_needed=N.
|
|
||||||
|
|
||||||
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
|
|
||||||
Status line. Refuses a phase with duplicate checklist rows, and refuses
|
|
||||||
in-progress -> open (started work stays marked).
|
|
||||||
|
|
||||||
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/.
|
|
||||||
|
|
||||||
Markers: [ ] pending · [/] in progress · [x] complete · [!] blocked · [?] assumed.
|
|
||||||
Exit: 0 ok · 2 bad arguments · 3 spec not found · 4 cannot parse / check
|
|
||||||
failed · 5 refused.
|
|
||||||
`;
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------- resolving */
|
|
||||||
|
|
||||||
function realOrResolved(p) {
|
|
||||||
try {
|
|
||||||
return fs.realpathSync.native(p);
|
|
||||||
} catch {
|
|
||||||
return path.resolve(p);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const samePath = (a, b) => (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
|
|
||||||
|
|
||||||
// Read-only commands (status, metrics) accept an archived spec, because
|
|
||||||
// Finalize reads its own spec after Step 6 moved it. Writes never do.
|
|
||||||
function resolveSpec(root, arg, { allowArchived = false } = {}) {
|
|
||||||
if (!arg) fail(EXIT.USAGE, "missing-spec", "Name the spec: specs/<name>, <name>, or its overview.md path.", "Run `specs.mjs list` to see the active specs.");
|
|
||||||
let p = arg.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
||||||
if (/\/overview\.md$/i.test(p) || /\/phase-[^/]*\.md$/i.test(p)) p = p.replace(/\/[^/]+$/, "");
|
|
||||||
const abs = path.isAbsolute(p) ? p : p.includes("/") ? path.join(root, p) : path.join(root, "specs", p);
|
|
||||||
const relPath = rel(root, abs);
|
|
||||||
if (!allowArchived && /(^|\/)specs--completed(\/|$)/.test(relPath)) {
|
|
||||||
fail(EXIT.REFUSED, "archived-spec", `${relPath} is archived; the pipeline only changes active specs under specs/.`, "Pick an active spec from `specs.mjs list`.");
|
|
||||||
}
|
|
||||||
// A spec is a folder directly under specs/ (or specs--completed/ for a read).
|
|
||||||
// Without this, `archive .` would move all of specs/ and `archive ./src` a
|
|
||||||
// source folder.
|
|
||||||
const homes = [path.join(root, "specs"), ...(allowArchived ? [path.join(root, "specs--completed")] : [])].map(realOrResolved);
|
|
||||||
const parent = realOrResolved(path.dirname(path.resolve(abs)));
|
|
||||||
if (!homes.some((h) => samePath(h, parent))) {
|
|
||||||
fail(EXIT.REFUSED, "not-a-spec", `${relPath} is not a spec folder: a spec sits directly under specs/${allowArchived ? " (or specs--completed/)" : ""}.`, "Pass specs/<name> or <name>; run `specs.mjs list` to see the active specs.");
|
|
||||||
}
|
|
||||||
if (!isDir(abs)) {
|
|
||||||
fail(EXIT.NOT_FOUND, "spec-not-found", `No spec folder at ${relPath}.`, "Run `specs.mjs list` from the project root (or pass --root) to see the active specs.");
|
|
||||||
}
|
|
||||||
return { dir: abs, rel: relPath, name: path.basename(abs) };
|
|
||||||
}
|
|
||||||
|
|
||||||
/* -------------------------------------------------------------- parsing */
|
|
||||||
|
|
||||||
const MARKERS = { " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" };
|
|
||||||
// Task 2.3, a lettered sub-task 3.6a, or a named one such as a testing task 1.T.
|
|
||||||
const TASK_RE = /^\s*[-*] \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
|
|
||||||
const CHECKBOX_RE = /^\s*[-*] \[(.)\]/;
|
|
||||||
// The Status line in any of the forms people write it: **Status:**, **Status**:
|
|
||||||
// or a plain Status:, optionally as a list item. Groups: everything up to the
|
|
||||||
// value (kept as written when the value is rewritten), the value, trailing blanks.
|
|
||||||
const STATUS_RE = /^([ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*)(.+?)([ \t]*)$/m;
|
|
||||||
|
|
||||||
function statusOf(text) {
|
|
||||||
const m = (text || "").match(STATUS_RE);
|
|
||||||
return m ? m[2] : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A markdown section's lines: from its heading to the next heading of the same or higher level. */
|
|
||||||
function section(text, headingRe) {
|
|
||||||
const lines = text.split(/\r?\n/);
|
|
||||||
const start = lines.findIndex((l) => /^#{1,6}\s/.test(l) && headingRe.test(l));
|
|
||||||
if (start === -1) return null;
|
|
||||||
const level = lines[start].match(/^#+/)[0].length;
|
|
||||||
let end = lines.length;
|
|
||||||
for (let i = start + 1; i < lines.length; i++) {
|
|
||||||
const m = lines[i].match(/^(#+)\s/);
|
|
||||||
if (m && m[1].length <= level) {
|
|
||||||
end = i;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { start, end, lines: lines.slice(start + 1, end) };
|
|
||||||
}
|
|
||||||
|
|
||||||
function plainText(s) {
|
|
||||||
return s
|
|
||||||
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
|
|
||||||
.replace(/[*_`]/g, "")
|
|
||||||
.replace(/\s+/g, " ")
|
|
||||||
.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Phase Checklist rows: the first "Phase N" on each checkbox line names the phase. */
|
|
||||||
function parseChecklist(overview) {
|
|
||||||
const sec = section(overview, /Phase Checklist/i);
|
|
||||||
if (!sec) return { found: false, phases: [], unparsed: [] };
|
|
||||||
const phases = [];
|
|
||||||
const unparsed = [];
|
|
||||||
sec.lines.forEach((line, i) => {
|
|
||||||
const m = line.match(CHECKBOX_RE);
|
|
||||||
if (!m) return;
|
|
||||||
const text = plainText(line.replace(CHECKBOX_RE, ""));
|
|
||||||
const num = text.match(/\bPhase\s+(\d+)\b/i);
|
|
||||||
if (!num) {
|
|
||||||
unparsed.push({ line: sec.start + 2 + i, text: line.trim() });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const after = text.slice(num.index + num[0].length).replace(/^\s*[:\-–—]\s*/, "");
|
|
||||||
const name = after.split(/\s+[-–—]\s+|\s+\(|\s+_\(|:\s|\s+see\s+phase-/i)[0].replace(/\s*phase-\d+\.md\s*$/i, "").trim();
|
|
||||||
phases.push({
|
|
||||||
number: Number(num[1]),
|
|
||||||
marker: m[1],
|
|
||||||
state: MARKERS[m[1]] || "unknown",
|
|
||||||
name: name.replace(/\s*\[Milestone[^\]]*\]\s*$/i, "") || `Phase ${num[1]}`,
|
|
||||||
line: sec.start + 2 + i,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
return { found: true, phases, unparsed };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** "2, 3", "2-4" and "2–4" (or an em dash) alike: ranges expand, so a group cell never loses a phase. */
|
|
||||||
function phaseList(cell) {
|
|
||||||
const outList = [];
|
|
||||||
for (const part of cell.match(/\d+\s*[-–\u2014]\s*\d+|\d+/g) || []) {
|
|
||||||
const r = part.match(/^(\d+)\s*[-–\u2014]\s*(\d+)$/);
|
|
||||||
if (r && Number(r[2]) >= Number(r[1]) && Number(r[2]) - Number(r[1]) < 100) {
|
|
||||||
for (let n = Number(r[1]); n <= Number(r[2]); n++) outList.push(n);
|
|
||||||
} else outList.push(...part.match(/\d+/g).map(Number));
|
|
||||||
}
|
|
||||||
return [...new Set(outList)];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Parallel Execution Groups table: real groups only (a named group with 2+ phases). */
|
|
||||||
function parseGroups(overview) {
|
|
||||||
const sec = section(overview, /Parallel Execution Groups/i);
|
|
||||||
if (!sec) return { found: false, groups: [] };
|
|
||||||
const groups = [];
|
|
||||||
const seen = new Set();
|
|
||||||
for (const line of sec.lines) {
|
|
||||||
if (!/^\s*\|/.test(line) || /^\s*\|[\s:|-]+\|\s*$/.test(line)) continue;
|
|
||||||
const cells = line.split("|").slice(1, -1).map((c) => c.trim());
|
|
||||||
if (cells.length < 2 || /^group$/i.test(cells[0])) continue;
|
|
||||||
const id = plainText(cells[0]);
|
|
||||||
const phases = phaseList(cells[1]);
|
|
||||||
// "None", a dash, a single phase, a group its author labelled sequential
|
|
||||||
// ("A (sequential)"), or a Phases cell written as a chain ("1 → 2") is not
|
|
||||||
// a parallel group.
|
|
||||||
if (!id || /^(none|-|–|—)$/i.test(id) || /\bsequential\b/i.test(id) || /→|->|\bthen\b/i.test(cells[1]) || phases.length < 2) continue;
|
|
||||||
const key = `${id}:${phases.join(",")}`;
|
|
||||||
if (seen.has(key)) continue;
|
|
||||||
seen.add(key);
|
|
||||||
groups.push({ id, phases, reason: plainText(cells[2] || "") });
|
|
||||||
}
|
|
||||||
return { found: true, groups };
|
|
||||||
}
|
|
||||||
|
|
||||||
function firstSentence(text) {
|
|
||||||
const t = plainText(text);
|
|
||||||
const m = t.match(/^(.+?[.!?])(\s|$)/);
|
|
||||||
return (m ? m[1] : t).slice(0, 240);
|
|
||||||
}
|
|
||||||
|
|
||||||
function parsePhaseFile(file, number) {
|
|
||||||
const text = readText(file) || "";
|
|
||||||
const lines = text.split(/\r?\n/);
|
|
||||||
const title = (lines.find((l) => /^#\s/.test(l)) || "").replace(/^#\s+/, "").trim();
|
|
||||||
const status = statusOf(text);
|
|
||||||
const counts = { pending: 0, "in-progress": 0, complete: 0, blocked: 0, assumed: 0, unknown: 0 };
|
|
||||||
const tasks = [];
|
|
||||||
const strayCheckboxes = [];
|
|
||||||
const unmatchedTasks = [];
|
|
||||||
let heading = "";
|
|
||||||
lines.forEach((line, i) => {
|
|
||||||
const h = line.match(/^#{1,6}\s+(.*)$/);
|
|
||||||
if (h) heading = plainText(h[1]);
|
|
||||||
const t = line.match(TASK_RE);
|
|
||||||
if (t) {
|
|
||||||
const state = MARKERS[t[1]] || "unknown";
|
|
||||||
counts[state]++;
|
|
||||||
const named = !/^\d+$/.test(t[3]);
|
|
||||||
tasks.push({ id: `${t[2]}.${t[3]}${t[4]}`, phase: Number(t[2]), seq: named ? null : Number(t[3]), named, suffix: t[4], marker: t[1], state, line: i + 1 });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// A line that looks like a task but is not counted as one (Task 1.4A,
|
|
||||||
// "1. [ ] **Task", a non-bold "- [ ] Task 1.3") would make the audit undercount.
|
|
||||||
if (/^\s*(?:[-*]|\d+\.)\s+\[.\].*\bTask\s+\d+\./i.test(line)) unmatchedTasks.push({ line: i + 1, text: line.trim().slice(0, 120) });
|
|
||||||
if (CHECKBOX_RE.test(line)) strayCheckboxes.push({ line: i + 1, section: heading, text: line.trim().slice(0, 120) });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Numbering: every task belongs to this phase, the base numbers run 1..n with
|
|
||||||
// no gaps or repeats, and a lettered task (3.6a) sits after its base (3.6).
|
|
||||||
// Named tasks (1.T) are outside the numeric sequence.
|
|
||||||
const numbering = [];
|
|
||||||
const bases = [];
|
|
||||||
for (const t of tasks) {
|
|
||||||
if (t.phase !== number) numbering.push(`Task ${t.id} is in phase-${number}.md but numbered for Phase ${t.phase}`);
|
|
||||||
if (!t.suffix && !t.named) bases.push(t.seq);
|
|
||||||
}
|
|
||||||
const seenIds = new Set();
|
|
||||||
for (const t of tasks) {
|
|
||||||
if (seenIds.has(t.id)) numbering.push(`Task ${t.id} appears more than once`);
|
|
||||||
seenIds.add(t.id);
|
|
||||||
if (t.suffix && !t.named && !bases.includes(t.seq)) numbering.push(`Task ${t.id} has no base Task ${t.phase}.${t.seq}`);
|
|
||||||
}
|
|
||||||
bases.forEach((seq, i) => {
|
|
||||||
if (seq !== i + 1 && !numbering.some((n) => n.startsWith("Task numbering"))) {
|
|
||||||
numbering.push(`Task numbering is not sequential: expected ${number}.${i + 1}, found ${number}.${seq}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const overviewSec = section(text, /^#{1,6}\s+Overview\b/i);
|
|
||||||
const goalText = overviewSec ? overviewSec.lines.join("\n").split(/\n\s*\n/).map((p) => p.trim()).find((p) => p && !/^[-*|>]/.test(p)) : "";
|
|
||||||
return {
|
|
||||||
title,
|
|
||||||
status,
|
|
||||||
goal: goalText ? firstSentence(goalText) : null,
|
|
||||||
total: tasks.length,
|
|
||||||
counts,
|
|
||||||
open: counts.pending + counts["in-progress"] + counts.blocked + counts.unknown,
|
|
||||||
// Open work a phase cannot be approved over; blocked tasks may stand ([!] is allowed at sign-off).
|
|
||||||
unfinished: counts.pending + counts["in-progress"] + counts.unknown,
|
|
||||||
tasks,
|
|
||||||
numbering,
|
|
||||||
strayCheckboxes,
|
|
||||||
unmatchedTasks,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function planDrafts(dir) {
|
|
||||||
return fs
|
|
||||||
.readdirSync(dir)
|
|
||||||
.filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n))
|
|
||||||
.sort()
|
|
||||||
.map((file) => ({
|
|
||||||
file,
|
|
||||||
archived: /-prev\.md$/i.test(file),
|
|
||||||
status: statusOf(readText(path.join(dir, file))),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---------------------------------------------------------------- status */
|
|
||||||
|
|
||||||
function specStatus(spec) {
|
|
||||||
const overviewPath = path.join(spec.dir, "overview.md");
|
|
||||||
const overview = readText(overviewPath);
|
|
||||||
const files = phaseFiles(spec.dir);
|
|
||||||
// An empty overview.md still exists; only a missing one is "no overview".
|
|
||||||
const hasOverview = overview !== null;
|
|
||||||
const checklist = hasOverview ? parseChecklist(overview) : { found: false, phases: [], unparsed: [] };
|
|
||||||
const groups = hasOverview ? parseGroups(overview) : { found: false, groups: [] };
|
|
||||||
const checks = [];
|
|
||||||
const check = (level, code, message) => checks.push({ level, code, message });
|
|
||||||
for (const [n, names] of files.extra) {
|
|
||||||
check("warn", "duplicate-phase-file", `Phase ${n} has more than one file: using ${files.get(n)}, ignoring ${names.join(", ")}`);
|
|
||||||
}
|
|
||||||
const rowsByNumber = new Map();
|
|
||||||
for (const r of checklist.phases) rowsByNumber.set(r.number, [...(rowsByNumber.get(r.number) || []), r]);
|
|
||||||
for (const [n, rows] of rowsByNumber) {
|
|
||||||
if (rows.length > 1) check("error", "duplicate-checklist-row", `Phase ${n} has ${rows.length} rows in the Phase Checklist (overview.md lines ${rows.map((r) => r.line).join(", ")}); the first one is used`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const phases = [];
|
|
||||||
const numbers = new Set([...checklist.phases.map((p) => p.number), ...files.keys()]);
|
|
||||||
for (const number of [...numbers].sort((a, b) => a - b)) {
|
|
||||||
const row = checklist.phases.find((p) => p.number === number) || null;
|
|
||||||
const file = files.get(number) || null;
|
|
||||||
const parsed = file ? parsePhaseFile(path.join(spec.dir, file), number) : null;
|
|
||||||
phases.push({
|
|
||||||
number,
|
|
||||||
name: row ? row.name : parsed ? parsed.title.replace(/^Phase\s+\d+\s*[:\-–—]?\s*/i, "") : `Phase ${number}`,
|
|
||||||
checklist: row ? row.state : null,
|
|
||||||
marker: row ? row.marker : null,
|
|
||||||
file,
|
|
||||||
status: parsed ? parsed.status : null,
|
|
||||||
goal: parsed ? parsed.goal : null,
|
|
||||||
tasks: parsed ? { total: parsed.total, open: parsed.open, ...parsed.counts } : null,
|
|
||||||
blockedTasks: parsed ? parsed.tasks.filter((t) => t.state === "blocked").map((t) => t.id) : [],
|
|
||||||
assumedTasks: parsed ? parsed.tasks.filter((t) => t.state === "assumed").map((t) => t.id) : [],
|
|
||||||
openTasks: parsed ? parsed.tasks.filter((t) => ["pending", "in-progress", "blocked", "unknown"].includes(t.state)).map((t) => t.id) : [],
|
|
||||||
});
|
|
||||||
if (!row && hasOverview) check("error", "missing-checklist-row", `phase-${number}.md has no row in overview.md's Phase Checklist`);
|
|
||||||
if (row && !file) check("error", "missing-phase-file", `Phase Checklist lists Phase ${number} but there is no phase-${number}.md`);
|
|
||||||
if (parsed) {
|
|
||||||
for (const n of parsed.numbering) check("error", "task-numbering", `phase-${number}.md: ${n}`);
|
|
||||||
// Prerequisites and criteria are plain bullets by rule; other checkbox
|
|
||||||
// blocks (a Phase Testing list) are the template's own and are not tasks.
|
|
||||||
for (const s of parsed.strayCheckboxes.filter((c) => /prerequisite|criteria/i.test(c.section))) {
|
|
||||||
check("warn", "criteria-checkbox", `phase-${number}.md:${s.line} is a checkbox under "${s.section}"; prerequisites and criteria use plain bullets`);
|
|
||||||
}
|
|
||||||
if (parsed.total === 0) check("warn", "no-tasks", `phase-${number}.md has no **Task ${number}.N:** checkbox lines`);
|
|
||||||
for (const u of parsed.unmatchedTasks) {
|
|
||||||
check("warn", "uncounted-task", `phase-${number}.md:${u.line} looks like a task but is not counted (a task line is "- [ ] **Task ${number}.N:**"): ${u.text}`);
|
|
||||||
}
|
|
||||||
const done = parsed.counts.complete + parsed.counts.assumed;
|
|
||||||
const rowDone = row && (row.state === "complete" || row.state === "assumed");
|
|
||||||
// A phase may be approved with blocked [!] tasks left (Implementation
|
|
||||||
// Mode's self-review allows "[x] or blocked [!]"); only unfinished work is an error.
|
|
||||||
if (rowDone && parsed.unfinished > 0) {
|
|
||||||
check("error", "checked-with-open-tasks", `Phase ${number} is [${row.marker}] in overview.md but ${parsed.unfinished} task(s) are not done (${phases.at(-1).openTasks.filter((id) => !phases.at(-1).blockedTasks.includes(id)).join(", ")})`);
|
|
||||||
} else if (rowDone && parsed.counts.blocked > 0) {
|
|
||||||
check("info", "approved-with-blocked", `Phase ${number} is [${row.marker}] with ${parsed.counts.blocked} blocked task(s) (${phases.at(-1).blockedTasks.join(", ")})`);
|
|
||||||
}
|
|
||||||
if (row && row.state === "pending" && parsed.total > 0 && done > 0) {
|
|
||||||
// Done tasks under a [ ] phase with work still open is what a re-opened
|
|
||||||
// phase looks like (revise-plan); with nothing open it is a missed mark.
|
|
||||||
if (parsed.unfinished > 0) check("info", "partly-done-unchecked", `Phase ${number} is [ ] with ${done} task(s) done and ${parsed.unfinished} open (normal for a re-opened phase)`);
|
|
||||||
else check("warn", "unchecked-with-done-tasks", `Phase ${number} is [ ] in overview.md but all ${done} unblocked task(s) are done`);
|
|
||||||
}
|
|
||||||
if (row && !rowDone && row.state !== "pending" && parsed.total > 0 && parsed.unfinished === 0) {
|
|
||||||
check("info", "done-not-approved", `Phase ${number}: every task is done but overview.md still shows [${row.marker}] (normal until the user approves the phase)`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!hasOverview) check("error", "no-overview", `${spec.rel} has no overview.md`);
|
|
||||||
else if (!checklist.found) check("error", "no-checklist", "overview.md has no ## Phase Checklist section");
|
|
||||||
for (const u of checklist.unparsed) check("warn", "unparsed-checklist-row", `overview.md:${u.line} is a checkbox in the Phase Checklist with no "Phase N" in it: ${u.text}`);
|
|
||||||
for (const g of groups.groups) {
|
|
||||||
for (const n of g.phases) if (!numbers.has(n)) check("error", "group-unknown-phase", `Parallel group ${g.id} names Phase ${n}, which does not exist`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Totals. Completed = [x] plus [?] (assumed complete); [?] is reported on its own too.
|
|
||||||
// Incomplete = [ ] + [/] (+ unreadable markers); Blocked is its own column.
|
|
||||||
const totals = { total: 0, complete: 0, assumed: 0, pending: 0, "in-progress": 0, blocked: 0, unknown: 0 };
|
|
||||||
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;
|
|
||||||
|
|
||||||
return {
|
|
||||||
ok: true,
|
|
||||||
spec: spec.rel,
|
|
||||||
name: spec.name,
|
|
||||||
overview: hasOverview ? "overview.md" : null,
|
|
||||||
planDrafts: planDrafts(spec.dir),
|
|
||||||
phases,
|
|
||||||
parallelGroups: groups.groups,
|
|
||||||
totals: { ...totals, completed, incomplete: totals.pending + totals["in-progress"] + totals.unknown },
|
|
||||||
completion: completion === null ? null : Number(completion.toFixed(4)),
|
|
||||||
completionPercent: completion === null ? null : Math.round(completion * 100),
|
|
||||||
next: nextPhase(phases, groups.groups, checklist.found),
|
|
||||||
pending: phases
|
|
||||||
.filter((p) => p.checklist && p.checklist !== "complete" && p.checklist !== "assumed")
|
|
||||||
.map((p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null, open: p.tasks ? p.tasks.open : null, goal: p.goal })),
|
|
||||||
checks,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Implementation Mode's phase-selection table, applied mechanically.
|
|
||||||
* 2+ workable phases in the same parallel group, consecutive -> choose (warn if all [/])
|
|
||||||
* a single [/] -> ask-resume · a single [ ] -> auto-start · nothing workable -> none
|
|
||||||
*/
|
|
||||||
function nextPhase(phases, groups, haveChecklist) {
|
|
||||||
if (!haveChecklist) return { action: "none", reason: "no Phase Checklist in overview.md" };
|
|
||||||
const ordered = phases.filter((p) => p.checklist);
|
|
||||||
const isDone = (p) => p.checklist === "complete" || p.checklist === "assumed";
|
|
||||||
const workable = ordered.filter((p) => p.checklist === "pending" || p.checklist === "in-progress");
|
|
||||||
if (!workable.length) {
|
|
||||||
return { action: "none", reason: ordered.length && ordered.every(isDone) ? "every phase is complete" : "no [ ] or [/] phase in the Phase Checklist" };
|
|
||||||
}
|
|
||||||
const first = workable[0];
|
|
||||||
const brief = (p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null });
|
|
||||||
// A blocked [!] phase ahead of the pick is skipped, but never silently.
|
|
||||||
const skipped = ordered.slice(0, ordered.indexOf(first)).filter((p) => !isDone(p)).map(brief);
|
|
||||||
const note = skipped.length ? { skipped, warning: `skipping ${skipped.map((p) => `Phase ${p.number} [${p.state}]`).join(", ")} ahead of it` } : {};
|
|
||||||
const group = groups.find((g) => g.phases.includes(first.number));
|
|
||||||
if (group) {
|
|
||||||
// Consecutive same-group incomplete phases, in checklist order, starting at the first workable one.
|
|
||||||
const run = [];
|
|
||||||
for (const p of ordered.slice(ordered.indexOf(first))) {
|
|
||||||
if (!group.phases.includes(p.number)) break;
|
|
||||||
if (isDone(p)) continue;
|
|
||||||
if (p.checklist === "pending" || p.checklist === "in-progress") run.push(p);
|
|
||||||
else break;
|
|
||||||
}
|
|
||||||
if (run.length >= 2) {
|
|
||||||
const allStarted = run.every((p) => p.checklist === "in-progress");
|
|
||||||
const warnings = [
|
|
||||||
...(allStarted ? ["every option is already [/]: another agent may be working on it, so picking one risks duplicated work"] : []),
|
|
||||||
...(note.warning ? [note.warning] : []),
|
|
||||||
];
|
|
||||||
return {
|
|
||||||
action: "choose",
|
|
||||||
group: group.id,
|
|
||||||
options: run.map(brief),
|
|
||||||
...(note.skipped ? { skipped: note.skipped } : {}),
|
|
||||||
...(warnings.length ? { warning: warnings.join("; ") } : {}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { action: first.checklist === "in-progress" ? "ask-resume" : "auto-start", phase: brief(first), ...note };
|
|
||||||
}
|
|
||||||
|
|
||||||
/* --------------------------------------------------------------- commands */
|
|
||||||
|
|
||||||
async function cmdList(args) {
|
|
||||||
const root = path.resolve(args.root || ".");
|
|
||||||
const { scanProject } = await consoleLib();
|
|
||||||
const scan = scanProject(root);
|
|
||||||
const specs = scan.specs.map((s) => {
|
|
||||||
const dir = path.join(root, s.dir);
|
|
||||||
let names = [];
|
|
||||||
try {
|
|
||||||
names = fs.readdirSync(dir);
|
|
||||||
} catch {}
|
|
||||||
return {
|
|
||||||
dir: s.dir,
|
|
||||||
name: s.name,
|
|
||||||
state: s.state,
|
|
||||||
detail: s.detail,
|
|
||||||
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,
|
|
||||||
pathfinder: isDir(path.join(dir, "pathfinder")),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
let completed = [];
|
|
||||||
try {
|
|
||||||
completed = fs.readdirSync(path.join(root, "specs--completed")).filter((n) => isDir(path.join(root, "specs--completed", n))).sort();
|
|
||||||
} catch {}
|
|
||||||
out({
|
|
||||||
ok: true,
|
|
||||||
root,
|
|
||||||
hasAgents: scan.hasAgents,
|
|
||||||
specsDir: isDir(path.join(root, "specs")),
|
|
||||||
specs,
|
|
||||||
completed,
|
|
||||||
...(specs.length ? {} : { note: "No active specs under specs/." }),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function cmdStatus(args) {
|
|
||||||
const root = path.resolve(args.root || ".");
|
|
||||||
out(specStatus(resolveSpec(root, args._[1], { allowArchived: true })));
|
|
||||||
}
|
|
||||||
|
|
||||||
function countVerificationAdded(dir) {
|
|
||||||
let n = 0;
|
|
||||||
for (const name of fs.readdirSync(dir)) {
|
|
||||||
if (!/\.md$/i.test(name) || /^PLAN-/i.test(name)) continue;
|
|
||||||
n += ((readText(path.join(dir, name)) || "").match(/<!--\s*VERIFICATION:\s*Added\b/gi) || []).length;
|
|
||||||
}
|
|
||||||
return n;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function cmdMetrics(args) {
|
|
||||||
const root = path.resolve(args.root || ".");
|
|
||||||
const spec = resolveSpec(root, args._[1], { allowArchived: true });
|
|
||||||
const step = args.step;
|
|
||||||
if (step !== "document" && step !== "finalize") fail(EXIT.USAGE, "bad-step", "--step must be document or finalize.", "Plan's METRICS_JSON is written by hand in its Phase 7.");
|
|
||||||
const sets = {};
|
|
||||||
for (const kv of args.set || []) {
|
|
||||||
const m = kv.match(/^([a-z_]+)=(-?\d+(?:\.\d+)?)$/);
|
|
||||||
if (!m) fail(EXIT.USAGE, "bad-set", `--set ${kv} is not key=number.`, "Example: --set verification_failures_found=1");
|
|
||||||
sets[m[1]] = Number(m[2]);
|
|
||||||
}
|
|
||||||
// --set supplies the judgment fields only; the computed ones are never overridden.
|
|
||||||
const SETTABLE = { document: ["verification_items_added"], finalize: ["verification_failures_found", "documentation_updates_needed"] };
|
|
||||||
for (const k of Object.keys(sets)) {
|
|
||||||
if (!SETTABLE[step].includes(k)) fail(EXIT.USAGE, "bad-set", `--set ${k} is not a field you supply for --step ${step}.`, `Only ${SETTABLE[step].join(", ")}; the rest is computed from the files.`);
|
|
||||||
}
|
|
||||||
const st = specStatus(spec);
|
|
||||||
const withTasks = st.phases.filter((p) => p.tasks);
|
|
||||||
let metrics;
|
|
||||||
let hint;
|
|
||||||
if (step === "document") {
|
|
||||||
// verification_items_added is the Added total of the Verification Summary
|
|
||||||
// you presented, not something the files record, so it comes from --set.
|
|
||||||
// The <!-- VERIFICATION: Added --> comments are a cross-check only.
|
|
||||||
if (!("verification_items_added" in sets)) fail(EXIT.USAGE, "missing-set", "document needs --set verification_items_added=N (the Added column total of your Verification Summary).", `The spec has ${countVerificationAdded(spec.dir)} <!-- VERIFICATION: Added --> comment(s), as a cross-check.`);
|
|
||||||
metrics = {
|
|
||||||
step: "document",
|
|
||||||
total_tasks: st.totals.total,
|
|
||||||
tasks_per_phase: withTasks.map((p) => p.tasks.total),
|
|
||||||
phase_count: st.phases.length,
|
|
||||||
parallel_groups_identified: st.parallelGroups.length,
|
|
||||||
...sets,
|
|
||||||
};
|
|
||||||
hint = { verificationCommentsFound: countVerificationAdded(spec.dir) };
|
|
||||||
} else {
|
|
||||||
const missing = ["verification_failures_found", "documentation_updates_needed"].filter((k) => !(k in sets));
|
|
||||||
if (missing.length) fail(EXIT.USAGE, "missing-set", `finalize needs ${missing.map((k) => `--set ${k}=N`).join(" and ")}.`, "Those two counts are your judgment from Steps 2 and 4.");
|
|
||||||
metrics = {
|
|
||||||
step: "finalize",
|
|
||||||
completion_rate_at_audit: st.completion === null ? 0 : Number(st.completion.toFixed(2)),
|
|
||||||
tasks_completed: st.totals.completed,
|
|
||||||
tasks_total: st.totals.total,
|
|
||||||
...sets,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
out({ ok: true, spec: spec.rel, metrics, comment: `<!-- METRICS_JSON ${spacedJson(metrics)} -->`, ...(hint || {}), checks: st.checks.filter((c) => c.level === "error") });
|
|
||||||
}
|
|
||||||
|
|
||||||
// The house style of every METRICS_JSON comment: {"key": value, "list": [1, 2]}.
|
|
||||||
function spacedJson(obj) {
|
|
||||||
const v = (x) => (Array.isArray(x) ? `[${x.map(v).join(", ")}]` : x && typeof x === "object" ? spacedJson(x) : JSON.stringify(x));
|
|
||||||
return `{${Object.entries(obj).map(([k, x]) => `${JSON.stringify(k)}: ${v(x)}`).join(", ")}}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const TO = { open: " ", "in-progress": "/", done: "x" };
|
|
||||||
|
|
||||||
async function cmdMark(args) {
|
|
||||||
const root = path.resolve(args.root || ".");
|
|
||||||
const spec = resolveSpec(root, args._[1]);
|
|
||||||
const number = Number(args.phase);
|
|
||||||
if (!Number.isInteger(number) || number < 0) fail(EXIT.USAGE, "bad-phase", "--phase needs a phase number.", "Example: --phase 2");
|
|
||||||
if (!(args.to in TO)) fail(EXIT.USAGE, "bad-to", "--to must be open, in-progress or done.", "open = [ ], in-progress = [/], done = [x]");
|
|
||||||
const overviewPath = path.join(spec.dir, "overview.md");
|
|
||||||
const overview = readText(overviewPath);
|
|
||||||
if (overview === null) fail(EXIT.NOT_FOUND, "no-overview", `${spec.rel} has no overview.md.`, "Run /plan2code-2-document first.");
|
|
||||||
const checklist = parseChecklist(overview);
|
|
||||||
const rows = checklist.phases.filter((p) => p.number === number);
|
|
||||||
const row = rows[0];
|
|
||||||
if (!row) fail(EXIT.NOT_FOUND, "no-row", `overview.md's Phase Checklist has no row for Phase ${number}.`, "Run `specs.mjs status` to see the phases it lists.");
|
|
||||||
if (rows.length > 1) fail(EXIT.REFUSED, "duplicate-row", `Phase ${number} has ${rows.length} rows in the Phase Checklist (lines ${rows.map((r) => r.line).join(", ")}); marking one would be a guess.`, "Remove the duplicate row, then rerun.");
|
|
||||||
const target = TO[args.to];
|
|
||||||
if (row.marker === "/" && target === " ") {
|
|
||||||
fail(EXIT.REFUSED, "no-reset", `Phase ${number} is [/]; started work is never reset to [ ].`, "Leave it [/] (a later session resumes it), or mark it done once approved.");
|
|
||||||
}
|
|
||||||
const changes = [];
|
|
||||||
const lines = overview.split(/\r?\n/);
|
|
||||||
const idx = row.line - 1;
|
|
||||||
const next = lines[idx].replace(/\[(.)\]/, `[${target}]`);
|
|
||||||
if (next !== lines[idx]) {
|
|
||||||
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.
|
|
||||||
let phaseText = null;
|
|
||||||
let phasePath = null;
|
|
||||||
let unfinished = [];
|
|
||||||
const warnings = [];
|
|
||||||
const file = phaseFiles(spec.dir).get(number);
|
|
||||||
if (file) {
|
|
||||||
phasePath = path.join(spec.dir, file);
|
|
||||||
const text = readText(phasePath) || "";
|
|
||||||
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;
|
|
||||||
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.`);
|
|
||||||
}
|
|
||||||
if (!args["dry-run"]) {
|
|
||||||
if (changes.some((c) => c.file.endsWith("overview.md"))) fs.writeFileSync(overviewPath, lines.join(eol(overview)));
|
|
||||||
if (phaseText !== null) fs.writeFileSync(phasePath, phaseText);
|
|
||||||
}
|
|
||||||
const doneEarly = target === "x" && unfinished.length > 0;
|
|
||||||
if (doneEarly) warnings.unshift(`Phase ${number} was marked done with ${unfinished.length} unfinished task(s): ${unfinished.join(", ")}. Mark only a phase the user approved.`);
|
|
||||||
out({
|
|
||||||
ok: true,
|
|
||||||
spec: spec.rel,
|
|
||||||
phase: number,
|
|
||||||
name: row.name,
|
|
||||||
dryRun: !!args["dry-run"],
|
|
||||||
changed: changes.length > 0,
|
|
||||||
changes,
|
|
||||||
...(warnings.length ? { warning: warnings.join(" ") } : {}),
|
|
||||||
...(doneEarly ? { unfinished } : {}),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function listRel(dir, base = dir) {
|
|
||||||
const outList = [];
|
|
||||||
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
||||||
const p = path.join(dir, e.name);
|
|
||||||
if (e.isDirectory()) outList.push(...listRel(p, base));
|
|
||||||
else outList.push(rel(base, p));
|
|
||||||
}
|
|
||||||
return outList.sort();
|
|
||||||
}
|
|
||||||
|
|
||||||
async function cmdArchive(args) {
|
|
||||||
const root = path.resolve(args.root || ".");
|
|
||||||
const spec = resolveSpec(root, args._[1]);
|
|
||||||
const target = path.join(root, "specs--completed", spec.name);
|
|
||||||
if (fs.existsSync(target)) {
|
|
||||||
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);
|
|
||||||
if (!args["dry-run"]) {
|
|
||||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
||||||
try {
|
|
||||||
fs.renameSync(spec.dir, target);
|
|
||||||
} catch (err) {
|
|
||||||
// A rename across volumes (or a locked file on Windows) fails; copy then remove.
|
|
||||||
try {
|
|
||||||
fs.cpSync(spec.dir, target, { recursive: true, errorOnExist: true, force: false });
|
|
||||||
} 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.`);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
fs.rmSync(spec.dir, { recursive: true, force: true });
|
|
||||||
} catch (rmErr) {
|
|
||||||
fail(EXIT.INVALID, "source-not-removed", `Copied to specs--completed/${spec.name}/ but could not remove ${spec.rel} (${rmErr.code || rmErr.message}); both copies now exist.`, `Close whatever holds files in ${spec.rel} open, then delete it by hand. The archive is complete.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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)) {
|
|
||||||
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"}.`,
|
|
||||||
`Compare ${spec.rel} with specs--completed/${spec.name}/ and finish the move by hand; archive refuses to rerun while the target exists.`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
out({
|
|
||||||
ok: true,
|
|
||||||
dryRun: !!args["dry-run"],
|
|
||||||
from: spec.rel,
|
|
||||||
to: `specs--completed/${spec.name}`,
|
|
||||||
files,
|
|
||||||
...(args["dry-run"] ? {} : { sourceRemoved: sourceGone, filesAtTarget: moved.length, archivedOn: isoDate() }),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
run(USAGE, async (argv) => {
|
|
||||||
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "step", "phase", "to"], lists: ["set"] });
|
|
||||||
const cmd = args._[0];
|
|
||||||
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, archive: cmdArchive };
|
|
||||||
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, metrics, mark, archive. Run with --help.");
|
|
||||||
await commands[cmd](args);
|
|
||||||
});
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "Plan2Code",
|
|
||||||
"version": "2.5.0",
|
|
||||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
|
||||||
"keywords": [
|
|
||||||
"ai",
|
|
||||||
"workflow",
|
|
||||||
"development",
|
|
||||||
"planning",
|
|
||||||
"implementation",
|
|
||||||
"plan"
|
|
||||||
],
|
|
||||||
"author": "Justin Parker",
|
|
||||||
"license": "MIT",
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "https://github.com/jparkerweb/plan2code"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
|
||||||
"releaseDate": "2026-10-06",
|
|
||||||
"mode": "utility"
|
|
||||||
}
|
|
||||||
@@ -29,17 +29,11 @@ The FIRST thing you do, before anything else in this file — before Step 1, bef
|
|||||||
- **Question options:** Never offer 'execute', 'implement', or any execution-shaped synonym. Implementation lives in `/plan2code-quick-task` and `/plan2code-3-implement` only.
|
- **Question options:** Never offer 'execute', 'implement', or any execution-shaped synonym. Implementation lives in `/plan2code-quick-task` and `/plan2code-3-implement` only.
|
||||||
- **Web console exception:** the console's temporary payload files (outside the repo, in the session folder `open` prints) are the one allowed write outside `specs/`. They are messages to the page, never project files.
|
- **Web console exception:** the console's temporary payload files (outside the repo, in the session folder `open` prints) are the one allowed write outside `specs/`. They are messages to the page, never project files.
|
||||||
|
|
||||||
## Scripts
|
|
||||||
|
|
||||||
`<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" 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.
|
|
||||||
|
|
||||||
## Required Context
|
## Required Context
|
||||||
|
|
||||||
Find the spec with `specs.mjs list`, then request these files if not provided:
|
⚠️ IMPORTANT: `specs/` is gitignored — NEVER use Glob (silently fails). Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
|
||||||
|
|
||||||
|
Request these files if not provided:
|
||||||
- `specs/<feature-name>/overview.md`
|
- `specs/<feature-name>/overview.md`
|
||||||
- All `specs/<feature-name>/phase-X.md` files
|
- All `specs/<feature-name>/phase-X.md` files
|
||||||
|
|
||||||
@@ -95,11 +89,13 @@ Present findings and confirm understanding before continuing.
|
|||||||
1. [Change description]
|
1. [Change description]
|
||||||
2. [Change description]
|
2. [Change description]
|
||||||
|
|
||||||
|
```
|
||||||
⋅
|
⋅
|
||||||
╭───╮
|
╭───╮
|
||||||
│ ★ │╱
|
│ ★ │╱
|
||||||
╱│ ~ │ Here's the plan. What do you think?
|
╱│ ~ │ Here's the plan. What do you think?
|
||||||
╰┬─┬╯
|
╰┬─┬╯
|
||||||
|
```
|
||||||
|
|
||||||
Approve the spec-update plan? (approve / refine / abort). Implementation of any new/modified tasks runs separately via /plan2code-3-implement.
|
Approve the spec-update plan? (approve / refine / abort). Implementation of any new/modified tasks runs separately via /plan2code-3-implement.
|
||||||
```
|
```
|
||||||
@@ -134,21 +130,24 @@ Approve the spec-update plan? (approve / refine / abort). Implementation of any
|
|||||||
- Added: [date]
|
- Added: [date]
|
||||||
- Reason: [reason]
|
- Reason: [reason]
|
||||||
```
|
```
|
||||||
- Update overview.md: `[x]` → `[ ]` (`specs.mjs mark <spec> --phase <N> --to open`, which also sets that phase file's `**Status:**` back to In Progress)
|
- Update overview.md: `[x]` → `[ ]`
|
||||||
- Add comment: `<!-- Re-opened: [date] - [reason] -->`
|
- Add comment: `<!-- Re-opened: [date] - [reason] -->`
|
||||||
|
|
||||||
### STEP 4: Consistency Check
|
### STEP 4: Consistency Check
|
||||||
|
|
||||||
`🔄 [REVISION] Step 4: Consistency Check`
|
`🔄 [REVISION] Step 4: Consistency Check`
|
||||||
|
|
||||||
Run `specs.mjs status <spec>`. Its `checks` cover the mechanical items: task numbers sequential (`task-numbering`), overview.md checklist matches the phase files (`missing-checklist-row`, `missing-phase-file`), incomplete phases unchecked and complete ones checked (`checked-with-open-tasks`, `unchecked-with-done-tasks`; `partly-done-unchecked` is the normal look of a phase you just re-opened). Then verify the rest yourself:
|
Verify updated specs are consistent:
|
||||||
|
|
||||||
|
- [ ] Task numbers sequential
|
||||||
- [ ] Phase dependencies valid
|
- [ ] Phase dependencies valid
|
||||||
- [ ] No orphaned references
|
- [ ] No orphaned references
|
||||||
- [ ] Tech stack updated if needed
|
- [ ] Tech stack updated if needed
|
||||||
- [ ] Success criteria achievable
|
- [ ] Success criteria achievable
|
||||||
|
- [ ] overview.md checklist matches phase files
|
||||||
|
- [ ] Incomplete phases unchecked, complete phases checked
|
||||||
|
|
||||||
Report and resolve issues (every `error` in `checks` included), then rerun `status` before continuing.
|
Report and resolve issues before continuing.
|
||||||
|
|
||||||
### STEP 5: Summary
|
### STEP 5: Summary
|
||||||
|
|
||||||
@@ -242,7 +241,7 @@ If user says "abort" or "cancel":
|
|||||||
|
|
||||||
Work summary — tell user: change type, tasks added/modified/removed, phases re-opened (if any).
|
Work summary — tell user: change type, tasks added/modified/removed, phases re-opened (if any).
|
||||||
|
|
||||||
**Pending phases after revision** — list `status`'s `pending` (every phase not `[x]`, re-opened ones included) with its task count so the user can plan next implementation sessions.
|
**Pending phases after revision** — read overview.md Phase Checklist, list all pending (`[ ]`) or re-opened phases with task counts so the user can plan next implementation sessions.
|
||||||
|
|
||||||
Returning context: Revised specs in `specs/<feature-name>/`. Run `/plan2code-3-implement --web` in a new conversation to continue implementation.
|
Returning context: Revised specs in `specs/<feature-name>/`. Run `/plan2code-3-implement --web` in a new conversation to continue implementation.
|
||||||
|
|
||||||
|
|||||||
@@ -60,16 +60,7 @@ The first payload for a phase you are about to build:
|
|||||||
```
|
```
|
||||||
|
|
||||||
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
|
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
|
||||||
progress bar is the first thing someone watching a build looks at. The session
|
progress bar is the first thing someone watching a build looks at.
|
||||||
meter counts the build's tasks from `cleared` as it rises, so keep it current,
|
|
||||||
and start every phase (a second one in the same run too) at `"cleared": 0`.
|
|
||||||
|
|
||||||
`"version": 1` is for the first phase of a session only. A doc's version
|
|
||||||
never goes back (console.md → House rules, rule 9), so a later phase in the
|
|
||||||
same session reposts `phase` and `phasefile` at one more than the version the
|
|
||||||
page holds, with the new phase's title and content. The same goes for
|
|
||||||
`report` at sign-off and `review` in a mid-session review: version 1 the
|
|
||||||
first time, then up from wherever the page has it.
|
|
||||||
|
|
||||||
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
||||||
the person can read the prerequisites and task specs while you build. Re-post
|
the person can read the prerequisites and task specs while you build. Re-post
|
||||||
@@ -118,12 +109,6 @@ printed), never into the project or into `~/.plan2code/console/` directly:
|
|||||||
- Do not call `wait` while building. There is nothing to collect, and the page
|
- Do not call `wait` while building. There is nothing to collect, and the page
|
||||||
holds anything the person sends until you next look.
|
holds anything the person sends until you next look.
|
||||||
|
|
||||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
|
||||||
`chat` check between tasks. Follow console.md → Standing instructions for
|
|
||||||
handing independent tasks to helpers and reporting them as `helpers`. Keep the
|
|
||||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
|
||||||
with you.
|
|
||||||
|
|
||||||
### Quick questions between tasks
|
### Quick questions between tasks
|
||||||
|
|
||||||
The person can ask a Quick question on the Ask tab at any point in a build
|
The person can ask a Quick question on the Ask tab at any point in a build
|
||||||
@@ -150,15 +135,8 @@ not questions. Put them in the phase doc as they happen, and in the report.
|
|||||||
|
|
||||||
### When the workflow asks something
|
### When the workflow asks something
|
||||||
|
|
||||||
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }` in
|
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }`, and
|
||||||
the SAME post, and go into the wait loop. When the answer lands, set `working`
|
go into the wait loop. When the answer lands, set `working` again and carry on.
|
||||||
again and carry on.
|
|
||||||
|
|
||||||
A question stops the build. Never leave yourself `working` with a question
|
|
||||||
open, and never "carry on while you decide": the page reads `working` as "not
|
|
||||||
your turn", and the person is left looking at a question they cannot answer.
|
|
||||||
If there is other work the answer does not touch, finish it before you ask,
|
|
||||||
then ask and wait.
|
|
||||||
|
|
||||||
| Moment | `kind` | Notes |
|
| Moment | `kind` | Notes |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -208,8 +186,7 @@ only ever be offered once nothing could come of it:
|
|||||||
`reply` carries `Approve this phase: approved`, which is the terminal's
|
`reply` carries `Approve this phase: approved`, which is the terminal's
|
||||||
`approved`. If the note that came with an approval asks for a change, treat it
|
`approved`. If the note that came with an approval asks for a change, treat it
|
||||||
as "describe any issues": do the change first and ask again. `changes` means
|
as "describe any issues": do the change first and ask again. `changes` means
|
||||||
exactly what it says: address it, bump the report's version (a later phase's
|
exactly what it says: address it, bump the report's version, and reopen the
|
||||||
report starts above the last one's, too), and reopen the
|
|
||||||
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||||
person asking for the code review before they approve anything — see "The
|
person asking for the code review before they approve anything — see "The
|
||||||
review, mid-session" below.
|
review, mid-session" below.
|
||||||
@@ -249,9 +226,8 @@ sign-off card, and approving past it was the answer. `implement-review` ends
|
|||||||
the same way; that phase was reviewed already. Only a finished `quick-task`
|
the same way; that phase was reviewed already. Only a finished `quick-task`
|
||||||
still offers the review on its finish — see below.
|
still offers the review on its finish — see below.
|
||||||
|
|
||||||
`run` gives the approved phase its final score on the session meter (console.md →
|
`run` scores the approved phase on the session meter (console.md → Posting an
|
||||||
Posting an update → Session meter), in the same post that records the approval;
|
update → Session meter), in the same post that records the approval:
|
||||||
it takes over what the build already counted from `cleared`, never adds to it:
|
|
||||||
`implement-phase` for Implement, `implement-review-phase` for Implement +
|
`implement-phase` for Implement, `implement-review-phase` for Implement +
|
||||||
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
|
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
|
||||||
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
|
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
|
||||||
@@ -409,10 +385,7 @@ a question still owed, above the ending itself:
|
|||||||
|
|
||||||
The same build, then Stage 2 publishes the findings exactly as above (the
|
The same build, then Stage 2 publishes the findings exactly as above (the
|
||||||
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
|
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
|
||||||
item: Stage 4 is the only gate. The post that starts Stage 2's review carries
|
item: Stage 4 is the only gate. Stage 4 is the sign-off above **without the
|
||||||
`"run": { "event": "review", "id": "review" }`, as above: in this workflow it
|
|
||||||
scores the review stage's 1 point on the meter as it begins, and the phase's
|
|
||||||
final `run` leaves that point out. Stage 4 is the sign-off above **without the
|
|
||||||
review verdict** — the phase was already reviewed — with the review results
|
review verdict** — the phase was already reviewed — with the review results
|
||||||
and unresolved findings in the report doc, header "Reviewed and ready for
|
and unresolved findings in the report doc, header "Reviewed and ready for
|
||||||
sign-off" in the item's `body`. The finish never carries `review`, and its
|
sign-off" in the item's `body`. The finish never carries `review`, and its
|
||||||
|
|||||||
@@ -170,7 +170,7 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
|
|||||||
|
|
||||||
| Exit | Meaning | What you do |
|
| Exit | Meaning | What you do |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace) and `subagents` (the helpers switch, see Standing instructions). | Handle the cards (if any), the chat (if any), any `workspace` changes and any `subagents` block, then post once (below, Quick questions, Workspace and Standing instructions). |
|
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace). | Handle the cards (if any), the chat (if any) and any `workspace` changes, then post once (below, Quick questions and Workspace). |
|
||||||
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
||||||
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
||||||
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
||||||
@@ -243,7 +243,7 @@ summarise it back.
|
|||||||
Then, in ONE `post`, do all of:
|
Then, in ONE `post`, do all of:
|
||||||
|
|
||||||
- mark each answered item `"status": "answered"` and record its `answer`
|
- mark each answered item `"status": "answered"` and record its `answer`
|
||||||
- reply to every note in that item's `thread` (shape below)
|
- add your replies to any comment threads
|
||||||
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
||||||
questions)
|
questions)
|
||||||
- publish the next batch of questions
|
- publish the next batch of questions
|
||||||
@@ -251,26 +251,6 @@ Then, in ONE `post`, do all of:
|
|||||||
|
|
||||||
One post is one atomic update, so the page never shows a half-changed state.
|
One post is one atomic update, so the page never shows a half-changed state.
|
||||||
|
|
||||||
### Replying to a note
|
|
||||||
|
|
||||||
A `comment` is the person talking to you about that card, often asking
|
|
||||||
something. It shows in the card's **Notes on this** panel, and so does your
|
|
||||||
answer:
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{ "items": [{ "id": "p4", "thread": [
|
|
||||||
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
|
|
||||||
] }] }
|
|
||||||
```
|
|
||||||
|
|
||||||
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
|
|
||||||
`md`: the page reads nothing else. An entry with no `text` is rejected.
|
|
||||||
- The server writes their note into the thread as it arrives. Do not repeat
|
|
||||||
it, and send only your new entries: `thread` appends.
|
|
||||||
- Answer what they asked, in the thread, even when you also change a doc or
|
|
||||||
re-ask the question. "I've updated the doc" alone leaves the question in the
|
|
||||||
panel with no answer under it.
|
|
||||||
|
|
||||||
### Recording the answer
|
### Recording the answer
|
||||||
|
|
||||||
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
||||||
@@ -576,15 +556,8 @@ enforces it, so never tell someone to keep asking past it.
|
|||||||
The person can add folders beside the one the session started in (a shared
|
The person can add folders beside the one the session started in (a shared
|
||||||
library, a design folder), from the footer's folder label. Together they are
|
library, a design folder), from the footer's folder label. Together they are
|
||||||
the session's **workspace**: context for every skill run in this console
|
the session's **workspace**: context for every skill run in this console
|
||||||
session, each folder addressed by a short `@name`. It outlives dashboard hops,
|
session, each folder addressed by a short `@name`. It outlives dashboard hops;
|
||||||
and it is remembered: every change is saved to `workspaces.json` beside
|
a new console session starts with the original folder alone.
|
||||||
`looks.json` (never into the project), keyed by the folder the session runs
|
|
||||||
in and then by spec. A session with a spec opens on that spec's list, one with
|
|
||||||
none on the project's; a spec with nothing saved starts as a copy of the
|
|
||||||
project's list. The dashboard's picker swaps the list as the selection moves,
|
|
||||||
and a `specDir` you post mid-run takes the current list with it. There is
|
|
||||||
nothing for you to load: `open` prints the list, and a switch of spec on a
|
|
||||||
resume reaches you as ordinary workspace changes on your next `wait`.
|
|
||||||
|
|
||||||
### What you are told
|
### What you are told
|
||||||
|
|
||||||
@@ -647,84 +620,6 @@ for permission is not a failure; report only a read that failed after it.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Standing instructions
|
|
||||||
|
|
||||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
|
||||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
|
||||||
from the top bar's Subagents button. Their pick is saved per project and per
|
|
||||||
skill, off by default, and reaches you as a standing instruction, only when it
|
|
||||||
changes.
|
|
||||||
|
|
||||||
### What arrives
|
|
||||||
|
|
||||||
A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`,
|
|
||||||
after the card lines, the `Quick question:` blocks and the `Workspace:` lines.
|
|
||||||
It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting
|
|
||||||
change alone never ends a `wait` slice: it waits for the next send, or for
|
|
||||||
your next `chat` check.
|
|
||||||
|
|
||||||
```
|
|
||||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
|
||||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
|
||||||
Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.
|
|
||||||
With no way to start helpers, report one "working alone" entry for this skill run instead.
|
|
||||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.
|
|
||||||
At most 3 helpers at once.
|
|
||||||
```
|
|
||||||
|
|
||||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
|
||||||
An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …`
|
|
||||||
with the whole block again; switching off arrives as one line:
|
|
||||||
`Subagents: off (revision 4) — don't start new helpers for the rest of this session.`
|
|
||||||
|
|
||||||
It is a console setting, not something the person typed. It never answers a
|
|
||||||
card, and it is never recorded under `specs/`.
|
|
||||||
|
|
||||||
### Obeying it
|
|
||||||
|
|
||||||
- **On:** hand independent work to helpers if your tools allow it, at most
|
|
||||||
`max` at once, following the instruction lines. `max` is advisory: your
|
|
||||||
harness's own limit still applies.
|
|
||||||
- **A higher revision replaces a lower one.** Follow the latest block only.
|
|
||||||
- **Off:** start no new helpers for the rest of the session. Let running ones
|
|
||||||
finish and report them.
|
|
||||||
- **Nothing arrives:** keep doing what the skill says.
|
|
||||||
- **Scope is the skill run it arrived in.** After a dashboard launch, no block
|
|
||||||
means the switch is off for this skill, even if an earlier skill in the same
|
|
||||||
conversation was told "on": `open` starts the count again, and a launch with
|
|
||||||
the switch off sends nothing.
|
|
||||||
|
|
||||||
### Reporting helpers
|
|
||||||
|
|
||||||
Post them, at your check-ins, so the page's Subagents tab can show them. The
|
|
||||||
page never hears from a helper directly:
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{ "helpers": [
|
|
||||||
{ "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" },
|
|
||||||
{ "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." }
|
|
||||||
] }
|
|
||||||
```
|
|
||||||
|
|
||||||
- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and
|
|
||||||
`state` (`running`, `done` or `failed`) are required; `result` (at most 200)
|
|
||||||
is the one line you add once a helper ends.
|
|
||||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
|
||||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
|
||||||
too; a resume into the same skill keeps it.
|
|
||||||
- One post per change worth seeing, not a stream.
|
|
||||||
- Questions for the person stay with you, never with a helper: most harnesses
|
|
||||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
|
||||||
session.
|
|
||||||
- **No way to start helpers?** Post one `{ "id": "alone", "alone": true }`
|
|
||||||
entry for the skill run instead. The tab then says you are working alone.
|
|
||||||
- **Pathfinder:** research questions always use helpers and are always
|
|
||||||
reported, whatever the switch says. The switch governs recon, sketches and
|
|
||||||
lookups beside the conversation.
|
|
||||||
- Helpers add no session meter points. Post no `run` for them.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Launches (dashboard only)
|
## Launches (dashboard only)
|
||||||
|
|
||||||
A `dashboard` session is not a conversation: the page draws a menu of every
|
A `dashboard` session is not a conversation: the page draws a menu of every
|
||||||
@@ -759,17 +654,9 @@ finish are dropped, so you start on a blank page and post your own. A skill
|
|||||||
run inline from another (a quick task's review) keeps the page it was
|
run inline from another (a quick task's review) keeps the page it was
|
||||||
handed. A
|
handed. A
|
||||||
fresh `open` would strand the page the person is watching on the dashboard's
|
fresh `open` would strand the page the person is watching on the dashboard's
|
||||||
session while your questions went to a page nobody has open.
|
session while your questions went to a page nobody has open. Then run the
|
||||||
|
skill normally: its Interface question was already answered by being
|
||||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
launched, so start where its real work starts.
|
||||||
> own file-read tool and follow it from the top instead.** Every Plan2Code
|
|
||||||
> skill below the dashboard ships `disable-model-invocation: true` on
|
|
||||||
> purpose — it exists to be read and followed inline, not launched as a
|
|
||||||
> sub-skill — and calling one through a skill-invocation tool errors out and
|
|
||||||
> strands the hand-off mid-launch.
|
|
||||||
|
|
||||||
Its Interface step is already answered by having been launched, so start
|
|
||||||
where its real work starts.
|
|
||||||
|
|
||||||
The menu itself is the page's own list — you never send it. The page knows
|
The menu itself is the page's own list — you never send it. The page knows
|
||||||
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
||||||
@@ -841,10 +728,7 @@ commands follow the pipeline: the sign-off's is
|
|||||||
|
|
||||||
### Review (`review`)
|
### Review (`review`)
|
||||||
|
|
||||||
Scope questions up front — run standalone with nothing named, the first is
|
Scope questions up front, then the findings report as a doc (`id: "report"`),
|
||||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
|
||||||
uncommitted changes, specs, files you name; each option with its size),
|
|
||||||
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
|
|
||||||
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
||||||
id, carrying `"doc": "report"` so the card links straight to the findings.
|
id, carrying `"doc": "report"` so the card links straight to the findings.
|
||||||
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
||||||
@@ -878,14 +762,12 @@ that is what the person is there to download. The finish carries no
|
|||||||
- Chart Step 8's research subagents must all report back before the
|
- Chart Step 8's research subagents must all report back before the
|
||||||
finish (Finishing → Nothing of yours may still be running); the finish
|
finish (Finishing → Nothing of yours may still be running); the finish
|
||||||
body then names what each one found.
|
body then names what each one found.
|
||||||
- Report every research subagent as a helper, whatever the Subagents switch
|
|
||||||
says (Standing instructions → Reporting helpers).
|
|
||||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||||
sees the Trail Footer, and without this their last screen promises a question
|
sees the Trail Footer, and without this their last screen promises a question
|
||||||
that is never coming.
|
that is never coming.
|
||||||
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
|
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
|
||||||
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
|
and `pathfinder-research` (id = the question's file slug) as each research
|
||||||
subagent reports back, or when you resolve a `research` question yourself
|
subagent reports back, or when you resolve a `research` question yourself
|
||||||
(Posting an update → Session meter). Other questions score through their
|
(Posting an update → Session meter). Other questions score through their
|
||||||
answers, so there is nothing to post for them.
|
answers, so there is nothing to post for them.
|
||||||
@@ -938,13 +820,7 @@ know:
|
|||||||
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) so the page reader sees it land. |
|
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) so the page reader sees it land. |
|
||||||
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
|
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
|
||||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
|
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`. |
|
||||||
|
|
||||||
Post `activity` as each step starts, before its doc or question lands — reading
|
|
||||||
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
|
|
||||||
implementation — the same way Review does. A step with no card of its own
|
|
||||||
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
|
|
||||||
Finalize".
|
|
||||||
|
|
||||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||||
Stopping mid-finalize loses nothing
|
Stopping mid-finalize loses nothing
|
||||||
@@ -976,7 +852,7 @@ question or doc lands:
|
|||||||
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
||||||
|
|
||||||
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
||||||
merge by `id` (an unknown id is added), and `thread` appends. Send only
|
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
|
||||||
what changed. A whole-file rewrite would put the entire session back into your
|
what changed. A whole-file rewrite would put the entire session back into your
|
||||||
context on every turn.
|
context on every turn.
|
||||||
|
|
||||||
@@ -1018,9 +894,7 @@ Per-unit work is yours to report, with `run` in any post:
|
|||||||
not count), a whole number from 1 to 999. A built phase scores by its size,
|
not count), a whole number from 1 to 999. A built phase scores by its size,
|
||||||
one point per 3 tasks rounded up, and Implement + Review one more for the
|
one point per 3 tasks rounded up, and Implement + Review one more for the
|
||||||
review. Always send it: without it a phase scores a flat 2 (or 3), however
|
review. Always send it: without it a phase scores a flat 2 (or 3), however
|
||||||
big it was. On any other event it is exit `3`. The console already counts a
|
big it was. On any other event it is exit `3`.
|
||||||
build's tasks from `headline.cleared` as they are ticked off; the phase's
|
|
||||||
`run` takes that count over with the final score, so it never counts twice.
|
|
||||||
- One `run` per post. Which events a workflow reports is in its own notes
|
- One `run` per post. Which events a workflow reports is in its own notes
|
||||||
(Workflow notes → Pathfinder; `building.md` for Implement and for the
|
(Workflow notes → Pathfinder; `building.md` for Implement and for the
|
||||||
review run on the page after a build).
|
review run on the page after a build).
|
||||||
@@ -1229,16 +1103,6 @@ A patch that breaks one of these is rejected with exit `3` and a message:
|
|||||||
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
||||||
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
||||||
and 5 cover `reason` and `hint`.
|
and 5 cover `reason` and `hint`.
|
||||||
8. **`helpers` entries are well formed** (Standing instructions → Reporting
|
|
||||||
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
|
|
||||||
and a known `state` within their limits, plus at most one `alone` entry.
|
|
||||||
Rules 4 and 5 cover `title`, `ask` and `result`.
|
|
||||||
9. **A doc's `version` never goes back.** Sending a known doc a lower
|
|
||||||
`version` than the page holds is refused: it is almost always a stale or
|
|
||||||
copied payload. The same version again is fine, and a dashboard hop starts
|
|
||||||
every doc fresh. Anything else reusing a doc id in the same session (a
|
|
||||||
build's second phase, a second report or review) continues from the
|
|
||||||
version the page holds.
|
|
||||||
|
|
||||||
These are workflow rules you already follow. The server just makes them checkable.
|
These are workflow rules you already follow. The server just makes them checkable.
|
||||||
|
|
||||||
@@ -1260,9 +1124,7 @@ cannot see them, and the moment it says the session ended, the person is
|
|||||||
free to close that terminal and kill them mid-write. While you wait, post
|
free to close that terminal and kill them mid-write. While you wait, post
|
||||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||||
and update the count as each returns. Never write a `finish.body` that says
|
and update the count as each returns. Never write a `finish.body` that says
|
||||||
work "is running in the background" or "will finish on its own". Mark every
|
work "is running in the background" or "will finish on its own".
|
||||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
|
||||||
never ends on a row still running.
|
|
||||||
|
|
||||||
### 1. Post the finish
|
### 1. Post the finish
|
||||||
|
|
||||||
@@ -1368,7 +1230,7 @@ answers were submitted but never picked up.
|
|||||||
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
||||||
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
||||||
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
||||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||||
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
||||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||||
|
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ import {
|
|||||||
die,
|
die,
|
||||||
ensureDir,
|
ensureDir,
|
||||||
fileStamp,
|
fileStamp,
|
||||||
forgetWorkspace,
|
|
||||||
handOff,
|
handOff,
|
||||||
handleFile,
|
handleFile,
|
||||||
healthOk,
|
healthOk,
|
||||||
@@ -64,21 +63,16 @@ import {
|
|||||||
readChat,
|
readChat,
|
||||||
readJson,
|
readJson,
|
||||||
readLedger,
|
readLedger,
|
||||||
readSubagentCursor,
|
|
||||||
readSubagentSetting,
|
|
||||||
readWorkspace,
|
readWorkspace,
|
||||||
reapHandles,
|
reapHandles,
|
||||||
rememberedWorkspace,
|
|
||||||
remoteWarning,
|
remoteWarning,
|
||||||
removeScratch,
|
removeScratch,
|
||||||
removeSessions,
|
removeSessions,
|
||||||
repoRoots,
|
repoRoots,
|
||||||
resetSubagentCursor,
|
|
||||||
scanProject,
|
scanProject,
|
||||||
SESSION_MAX_AGE_MS,
|
SESSION_MAX_AGE_MS,
|
||||||
sessionDir,
|
sessionDir,
|
||||||
sleepSync,
|
sleepSync,
|
||||||
specKey,
|
|
||||||
staleScratch,
|
staleScratch,
|
||||||
staleSessions,
|
staleSessions,
|
||||||
sweepUploads,
|
sweepUploads,
|
||||||
@@ -91,11 +85,9 @@ import {
|
|||||||
workspaceForAgent,
|
workspaceForAgent,
|
||||||
writeCursor,
|
writeCursor,
|
||||||
writeJsonAtomic,
|
writeJsonAtomic,
|
||||||
writeSubagentCursor,
|
|
||||||
writeWorkspaceCursor,
|
writeWorkspaceCursor,
|
||||||
} from "./lib.mjs";
|
} from "./lib.mjs";
|
||||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount } from "./public/meter.js";
|
||||||
import { blockFor, offered } from "./public/subagents.js";
|
|
||||||
import { changeLine } from "./public/workspace.js";
|
import { changeLine } from "./public/workspace.js";
|
||||||
|
|
||||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||||
@@ -315,11 +307,7 @@ async function cmdOpen() {
|
|||||||
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
||||||
}
|
}
|
||||||
state = written.state;
|
state = written.state;
|
||||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
|
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
|
||||||
// A new agent conversation has been told nothing yet (FR-6).
|
|
||||||
try {
|
|
||||||
resetSubagentCursor(dir);
|
|
||||||
} catch {}
|
|
||||||
trace("open: state written");
|
trace("open: state written");
|
||||||
|
|
||||||
// Dashboard launches are recorded too (they score nothing), so the folder
|
// Dashboard launches are recorded too (they score nothing), so the folder
|
||||||
@@ -329,7 +317,7 @@ async function cmdOpen() {
|
|||||||
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
|
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
|
||||||
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
|
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
|
||||||
} catch {}
|
} catch {}
|
||||||
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
|
const workspace = workspaceOnOpen(dir, worktree);
|
||||||
|
|
||||||
// Month-old sessions and scratch files: listed before the print so the
|
// Month-old sessions and scratch files: listed before the print so the
|
||||||
// agent can see what went, removed after it so the page waits for nothing.
|
// agent can see what went, removed after it so the page waits for nothing.
|
||||||
@@ -346,18 +334,9 @@ async function cmdOpen() {
|
|||||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||||
};
|
};
|
||||||
|
|
||||||
// A standing instruction the new agent is owed, as `subagents` and a
|
|
||||||
// `reply` holding only its lines; neither key when nothing is owed.
|
|
||||||
const subagentsOwed = () => {
|
|
||||||
awaitSubagentSync(dir, state.workflow);
|
|
||||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
|
||||||
return [out.subagents ? out : {}, cursor];
|
|
||||||
};
|
|
||||||
|
|
||||||
// Reuse a live server if one is already serving this session.
|
// Reuse a live server if one is already serving this session.
|
||||||
if (existing && (await reusable)) {
|
if (existing && (await reusable)) {
|
||||||
if (!args["no-open"]) openBrowser(existing.url);
|
if (!args["no-open"]) openBrowser(existing.url);
|
||||||
const [owed, subCursor] = subagentsOwed();
|
|
||||||
print({
|
print({
|
||||||
ok: true,
|
ok: true,
|
||||||
sid,
|
sid,
|
||||||
@@ -367,11 +346,9 @@ async function cmdOpen() {
|
|||||||
pendingResult: carried,
|
pendingResult: carried,
|
||||||
terminalLine: terminalLine(existing.url),
|
terminalLine: terminalLine(existing.url),
|
||||||
workspace,
|
workspace,
|
||||||
...owed,
|
|
||||||
...swept,
|
...swept,
|
||||||
...remoteWarning(),
|
...remoteWarning(),
|
||||||
});
|
});
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
sweep();
|
sweep();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -404,7 +381,6 @@ async function cmdOpen() {
|
|||||||
const notes = [];
|
const notes = [];
|
||||||
if (remote.note) notes.push(remote.note);
|
if (remote.note) notes.push(remote.note);
|
||||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||||
const [owed, subCursor] = subagentsOwed();
|
|
||||||
print({
|
print({
|
||||||
ok: true,
|
ok: true,
|
||||||
sid,
|
sid,
|
||||||
@@ -415,12 +391,10 @@ async function cmdOpen() {
|
|||||||
pendingResult: carried,
|
pendingResult: carried,
|
||||||
terminalLine: terminalLine(handle.url),
|
terminalLine: terminalLine(handle.url),
|
||||||
workspace,
|
workspace,
|
||||||
...owed,
|
|
||||||
...swept,
|
...swept,
|
||||||
...(remote.remote ? { remote: remote.remote } : {}),
|
...(remote.remote ? { remote: remote.remote } : {}),
|
||||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||||
});
|
});
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
// After the print, never before it: the page and the link wait for nothing.
|
// After the print, never before it: the page and the link wait for nothing.
|
||||||
sweep();
|
sweep();
|
||||||
}
|
}
|
||||||
@@ -429,11 +403,10 @@ async function cmdOpen() {
|
|||||||
* The workspace as `open` hands it to the agent, and the cursor seeded to
|
* The workspace as `open` hands it to the agent, and the cursor seeded to
|
||||||
* match: the agent now has the whole list, so no change up to here is owed.
|
* match: the agent now has the whole list, so no change up to here is owed.
|
||||||
* Read-only on workspace.json, which only the server writes; on a fresh
|
* Read-only on workspace.json, which only the server writes; on a fresh
|
||||||
* session the server has not made it yet, so what was remembered for this
|
* session the server has not made it yet, so the original folder stands in.
|
||||||
* folder and spec stands in, the same list the server is about to make.
|
|
||||||
*/
|
*/
|
||||||
function workspaceOnOpen(dir, worktree, specDir) {
|
function workspaceOnOpen(dir, worktree) {
|
||||||
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
|
const ws = readWorkspace(dir) || initialWorkspace(worktree);
|
||||||
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
|
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
|
||||||
try {
|
try {
|
||||||
writeWorkspaceCursor(dir, ws.version || 0);
|
writeWorkspaceCursor(dir, ws.version || 0);
|
||||||
@@ -616,13 +589,6 @@ function cmdPost() {
|
|||||||
const next = written.state;
|
const next = written.state;
|
||||||
|
|
||||||
for (const line of ledgerLines) appendLedger(dir, line);
|
for (const line of ledgerLines) appendLedger(dir, line);
|
||||||
// A build scores its tasks as it clears them (meter.js, PROGRESS_WORKFLOWS),
|
|
||||||
// after any `run` in the same post, so a phase finished here ends its count.
|
|
||||||
if (patch.headline && typeof patch.headline === "object") {
|
|
||||||
const ledger = readLedger(dir);
|
|
||||||
const progress = progressEntry(ledger, lastLaunchId(ledger), next.workflow, patch.headline.cleared);
|
|
||||||
if (progress) appendLedger(dir, progress);
|
|
||||||
}
|
|
||||||
appendEvent(dir, { type: "post", items: (patch.items || []).length });
|
appendEvent(dir, { type: "post", items: (patch.items || []).length });
|
||||||
|
|
||||||
const open = next.items.filter((i) => isOpen(i) && i.required !== false).length;
|
const open = next.items.filter((i) => isOpen(i) && i.required !== false).length;
|
||||||
@@ -797,7 +763,7 @@ function serverGone(sid) {
|
|||||||
|
|
||||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||||
function deliverChat(dir, sid, entries, url) {
|
function deliverChat(dir, sid, entries, url) {
|
||||||
const [withWs, changes] = withWorkspace(dir, {
|
const [out, changes] = withWorkspace(dir, {
|
||||||
type: "chat",
|
type: "chat",
|
||||||
at: nowIso(),
|
at: nowIso(),
|
||||||
sid,
|
sid,
|
||||||
@@ -805,11 +771,9 @@ function deliverChat(dir, sid, entries, url) {
|
|||||||
chat: entries,
|
chat: entries,
|
||||||
reply: chatReplyLines(entries),
|
reply: chatReplyLines(entries),
|
||||||
});
|
});
|
||||||
const [out, subCursor] = withSubagents(dir, withWs);
|
|
||||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||||
advanceCursor(dir, entries);
|
advanceCursor(dir, entries);
|
||||||
advanceWorkspace(dir, changes);
|
advanceWorkspace(dir, changes);
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
process.exitCode = 0;
|
process.exitCode = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -831,52 +795,6 @@ function advanceWorkspace(dir, changes) {
|
|||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The server rewrites the session's setting for a new workflow only once its
|
|
||||||
// watcher sees the state `open` just wrote, so a launch or hop that read the
|
|
||||||
// file at once would find the old workflow's and owe the agent nothing until
|
|
||||||
// its next pickup. Give the server a moment to catch up instead, never
|
|
||||||
// writing the file ourselves (FR-7). A session with no setting file at all is
|
|
||||||
// an older server, which never writes one: a short look, not the full wait.
|
|
||||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
|
||||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
|
||||||
function awaitSubagentSync(dir, workflow) {
|
|
||||||
if (!offered(workflow)) return;
|
|
||||||
const start = Date.now();
|
|
||||||
for (;;) {
|
|
||||||
const setting = readSubagentSetting(dir);
|
|
||||||
if (setting && setting.workflow === workflow) return;
|
|
||||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
|
||||||
if (Date.now() - start >= budget) return;
|
|
||||||
sleepSync(25);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Subagents switch the agent is owed, added to what it is about to read:
|
|
||||||
// the setting as `subagents`, and its lines last in `reply`, after card lines,
|
|
||||||
// Quick questions and Workspace lines (FR-9). Read from the session's own
|
|
||||||
// setting file only, which only the server writes (FR-7). A setting for
|
|
||||||
// another workflow is the server not having caught up with a hop yet: it
|
|
||||||
// rides on the next pickup instead.
|
|
||||||
function withSubagents(dir, out) {
|
|
||||||
const setting = readSubagentSetting(dir);
|
|
||||||
if (!setting) return [out, null];
|
|
||||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
|
||||||
if (setting.workflow !== workflow) return [out, null];
|
|
||||||
const block = blockFor(setting, readSubagentCursor(dir));
|
|
||||||
if (!block) return [out, null];
|
|
||||||
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
|
|
||||||
return [{ ...out, subagents: block.field, reply }, block.cursor];
|
|
||||||
}
|
|
||||||
|
|
||||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
|
||||||
// block at the next pickup, never loses it.
|
|
||||||
function advanceSubagents(dir, cursor) {
|
|
||||||
if (!cursor) return;
|
|
||||||
try {
|
|
||||||
writeSubagentCursor(dir, cursor);
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Print first, then this, exactly as consume() stamps a result: a kill in
|
// Print first, then this, exactly as consume() stamps a result: a kill in
|
||||||
// between can only hand the same chat over again, and collectChat() drops
|
// between can only hand the same chat over again, and collectChat() drops
|
||||||
// anything that already has a reply.
|
// anything that already has a reply.
|
||||||
@@ -903,17 +821,15 @@ async function cmdChat() {
|
|||||||
}
|
}
|
||||||
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||||
const changes = pendingWorkspaceChanges(dir);
|
const changes = pendingWorkspaceChanges(dir);
|
||||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
if (!entries.length && !changes.length) {
|
||||||
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
|
|
||||||
if (!entries.length && !changes.length && !subCursor) {
|
|
||||||
print({ chat: [] });
|
print({ chat: [] });
|
||||||
process.exitCode = 10;
|
process.exitCode = 10;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||||
|
print({ chat: entries, workspace: changes, reply, terminalLine: terminalLine(handle.url) });
|
||||||
advanceCursor(dir, entries);
|
advanceCursor(dir, entries);
|
||||||
advanceWorkspace(dir, changes);
|
advanceWorkspace(dir, changes);
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
process.exitCode = 0;
|
process.exitCode = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -938,8 +854,7 @@ function consume(dir, resultPath, result, url, chat = []) {
|
|||||||
// never on result.json itself.
|
// never on result.json itself.
|
||||||
const withChat = { ...collected, chat };
|
const withChat = { ...collected, chat };
|
||||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
const [out, changes] = withWorkspace(dir, withChat);
|
||||||
const [out, subCursor] = withSubagents(dir, withWs);
|
|
||||||
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
||||||
try {
|
try {
|
||||||
writeJsonAtomic(resultPath, collected);
|
writeJsonAtomic(resultPath, collected);
|
||||||
@@ -948,7 +863,6 @@ function consume(dir, resultPath, result, url, chat = []) {
|
|||||||
ledgerAnswers(dir, result);
|
ledgerAnswers(dir, result);
|
||||||
advanceCursor(dir, chat);
|
advanceCursor(dir, chat);
|
||||||
advanceWorkspace(dir, changes);
|
advanceWorkspace(dir, changes);
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1032,18 +946,6 @@ function realNearest(p) {
|
|||||||
return path.join(fs.realpathSync(existing), path.relative(existing, p));
|
return path.join(fs.realpathSync(existing), path.relative(existing, p));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------------- forget */
|
|
||||||
|
|
||||||
// Drop the folder list remembered for one spec (Finalize, once the spec is
|
|
||||||
// archived). The project's own list and every other spec's are untouched.
|
|
||||||
function cmdForget() {
|
|
||||||
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
|
|
||||||
let spec = specKey(args.spec);
|
|
||||||
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
|
|
||||||
const worktree = repoRoots().worktree;
|
|
||||||
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ----------------------------------------------------------------- help */
|
/* ----------------------------------------------------------------- help */
|
||||||
|
|
||||||
function cmdHelp() {
|
function cmdHelp() {
|
||||||
@@ -1059,20 +961,13 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
|||||||
first post. --file is optional, and --title defaults to the
|
first post. --file is optional, and --title defaults to the
|
||||||
project's folder name. Also prints workspace: { folders: [{ name,
|
project's folder name. Also prints workspace: { folders: [{ name,
|
||||||
path, description?, original? }], missing? }, the folders this
|
path, description?, original? }], missing? }, the folders this
|
||||||
console session reads as context, addressed as @name. The list is
|
console session reads as context, addressed as @name.
|
||||||
remembered per folder and spec in workspaces.json beside looks.json.
|
|
||||||
May also print subagents: { state, revision, max, instruction } and
|
|
||||||
a reply holding only its "Subagents: ..." lines, when a standing
|
|
||||||
instruction (the page's Subagents switch) is owed to you.
|
|
||||||
post --session <sid> --file <patch.json>
|
post --session <sid> --file <patch.json>
|
||||||
Merge a patch into the session. Prints terminalLine while the
|
Merge a patch into the session. Prints terminalLine while the
|
||||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||||
{ name, reason, hint? } (a workspace folder you could not read);
|
{ name, reason, hint? } (a workspace folder you could not read);
|
||||||
both go to the ledger, never into the state. A patch may also
|
both go to the ledger, never into the state.
|
||||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
|
||||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
|
||||||
(see console.md → Standing instructions).
|
|
||||||
wait --session <sid> [--seconds <N>]
|
wait --session <sid> [--seconds <N>]
|
||||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||||
@@ -1083,24 +978,16 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
|||||||
"workspace" (changes since you last heard, each once, with a
|
"workspace" (changes since you last heard, each once, with a
|
||||||
"Workspace: ..." line in reply); exit 10 counts them as
|
"Workspace: ..." line in reply); exit 10 counts them as
|
||||||
pendingWorkspace, and a change alone never ends a slice.
|
pendingWorkspace, and a change alone never ends a slice.
|
||||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
|
||||||
by the person, with its "Subagents: ..." lines last in reply); a
|
|
||||||
setting change alone never ends a slice either.
|
|
||||||
chat --session <sid>
|
chat --session <sid>
|
||||||
Collect Quick questions, workspace changes and a Subagents
|
Collect Quick questions and workspace changes now, never waiting,
|
||||||
setting change now, never waiting, never touching card sends.
|
never touching card sends. Exit 0 = { chat, workspace, reply,
|
||||||
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
|
terminalLine }, 10 = none, 20 = server gone.
|
||||||
10 = none, 20 = server gone.
|
|
||||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||||
messages with it during a console session.
|
messages with it during a console session.
|
||||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||||
Copy a cited note attachment into specs/<idea>/attachments/. Prints
|
Copy a cited note attachment into specs/<idea>/attachments/. Prints
|
||||||
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
|
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
|
||||||
missing. Paste link as it is.
|
missing. Paste link as it is.
|
||||||
forget --spec specs/<idea>
|
|
||||||
Drop the workspace folders remembered for that spec, in this
|
|
||||||
folder (Finalize, after archiving it). Prints { ok, spec, forgot };
|
|
||||||
forgot is false when nothing was saved. Exit 2 = bad usage.
|
|
||||||
status [--session <sid>] [--all]
|
status [--session <sid>] [--all]
|
||||||
One session, or every session belonging to this project.
|
One session, or every session belonging to this project.
|
||||||
stop --session <sid> | --all
|
stop --session <sid> | --all
|
||||||
@@ -1319,7 +1206,6 @@ const COMMANDS = {
|
|||||||
wait: cmdWait,
|
wait: cmdWait,
|
||||||
chat: cmdChat,
|
chat: cmdChat,
|
||||||
keep: cmdKeep,
|
keep: cmdKeep,
|
||||||
forget: cmdForget,
|
|
||||||
status: cmdStatus,
|
status: cmdStatus,
|
||||||
stop: cmdStop,
|
stop: cmdStop,
|
||||||
help: cmdHelp,
|
help: cmdHelp,
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ import { fileURLToPath } from "node:url";
|
|||||||
import { CHAT_LIMIT } from "./public/chat.js";
|
import { CHAT_LIMIT } from "./public/chat.js";
|
||||||
import { DOC_TYPES } from "./public/answers.js";
|
import { DOC_TYPES } from "./public/answers.js";
|
||||||
import { defaultName } from "./public/workspace.js";
|
import { defaultName } from "./public/workspace.js";
|
||||||
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
|
||||||
|
|
||||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
export const PUBLIC_DIR = path.join(HERE, "public");
|
export const PUBLIC_DIR = path.join(HERE, "public");
|
||||||
@@ -49,10 +48,6 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
|
|||||||
|
|
||||||
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
||||||
|
|
||||||
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
|
|
||||||
// so every session within the hour reuses one lookup.
|
|
||||||
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
|
|
||||||
|
|
||||||
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
||||||
// test run (or a second sandboxed instance) shares one handle directory with
|
// test run (or a second sandboxed instance) shares one handle directory with
|
||||||
// the real thing, and `stop --all` reaches outside its own world and kills a
|
// the real thing, and `stop --all` reaches outside its own world and kills a
|
||||||
@@ -183,8 +178,8 @@ function lockStale(lock) {
|
|||||||
// Run fn while holding the session's state lock, and release it however fn
|
// Run fn while holding the session's state lock, and release it however fn
|
||||||
// ends. fn must not call process.exit(): the release would never run, and the
|
// ends. fn must not call process.exit(): the release would never run, and the
|
||||||
// next writer would wait out the stale age.
|
// next writer would wait out the stale age.
|
||||||
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
|
export function withStateLock(dir, fn) {
|
||||||
const lock = path.join(dir, lockName);
|
const lock = path.join(dir, STATE_LOCK_FILE);
|
||||||
const deadline = Date.now() + LOCK_WAIT_MS;
|
const deadline = Date.now() + LOCK_WAIT_MS;
|
||||||
let fd = null;
|
let fd = null;
|
||||||
for (let attempt = 0; fd === null; attempt++) {
|
for (let attempt = 0; fd === null; attempt++) {
|
||||||
@@ -193,7 +188,7 @@ export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
|
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
|
||||||
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
|
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
|
||||||
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
|
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
|
||||||
if (err.code === "EEXIST" && lockStale(lock)) {
|
if (err.code === "EEXIST" && lockStale(lock)) {
|
||||||
try {
|
try {
|
||||||
fs.rmSync(lock, { force: true });
|
fs.rmSync(lock, { force: true });
|
||||||
@@ -492,16 +487,8 @@ export async function removeSessions(sessionsDir, sids) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The console folder's own files that no sweep may ever remove: the person's
|
// The console folder's own files that no sweep may ever remove: the person's
|
||||||
// looks, the folders remembered per project and spec, the Subagents switch
|
// looks and the pointer to this console's directory.
|
||||||
// saved per project and workflow, the pointer to this console's directory,
|
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "console-dir"]);
|
||||||
// and the cached release check.
|
|
||||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
|
||||||
"looks.json",
|
|
||||||
"workspaces.json",
|
|
||||||
"subagents.json",
|
|
||||||
"console-dir",
|
|
||||||
"update-check.json",
|
|
||||||
]);
|
|
||||||
|
|
||||||
function isScratchName(name) {
|
function isScratchName(name) {
|
||||||
return (
|
return (
|
||||||
@@ -548,148 +535,6 @@ export async function removeScratch(consoleDir, names) {
|
|||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------- cleanup */
|
|
||||||
|
|
||||||
// What User Preferences -> Cleanup never removes. The console folder keeps its
|
|
||||||
// protected files, its sessions dir (old sessions go one by one, by age) and,
|
|
||||||
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
|
|
||||||
// console, the launcher (bin/, launcher.json) and the models the person added.
|
|
||||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
|
||||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
|
|
||||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
|
||||||
// folders hold files that live for milliseconds -- a held
|
|
||||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
|
||||||
// rename -- and removing one mid-write loses another session's change.
|
|
||||||
export const STRAY_GRACE_MS = 60 * 60 * 1000;
|
|
||||||
|
|
||||||
// Bytes under `p`, never following a symlink: a link counts as itself.
|
|
||||||
async function diskBytes(p) {
|
|
||||||
let st;
|
|
||||||
try {
|
|
||||||
st = await fs.promises.lstat(p);
|
|
||||||
} catch {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
if (!st.isDirectory()) return st.size;
|
|
||||||
let entries;
|
|
||||||
try {
|
|
||||||
entries = await fs.promises.readdir(p);
|
|
||||||
} catch {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
let total = 0;
|
|
||||||
for (const name of entries) total += await diskBytes(path.join(p, name));
|
|
||||||
return total;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The newest mtime of anything under `p`, never following a symlink. A folder
|
|
||||||
// counts by its files, since rewriting a file never touches its folder's
|
|
||||||
// mtime; an empty folder counts by its own. Anything unreadable on the way
|
|
||||||
// down answers Infinity, so it reads as just touched and stays.
|
|
||||||
function newestMtime(p) {
|
|
||||||
let st;
|
|
||||||
try {
|
|
||||||
st = fs.lstatSync(p);
|
|
||||||
} catch {
|
|
||||||
return Infinity;
|
|
||||||
}
|
|
||||||
if (!st.isDirectory()) return st.mtimeMs;
|
|
||||||
let entries;
|
|
||||||
try {
|
|
||||||
entries = fs.readdirSync(p);
|
|
||||||
} catch {
|
|
||||||
return Infinity;
|
|
||||||
}
|
|
||||||
if (!entries.length) return st.mtimeMs;
|
|
||||||
let newest = 0;
|
|
||||||
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
|
|
||||||
return newest;
|
|
||||||
}
|
|
||||||
|
|
||||||
function entryKind(entry) {
|
|
||||||
if (entry.isSymbolicLink()) return "link";
|
|
||||||
return entry.isDirectory() ? "folder" : "file";
|
|
||||||
}
|
|
||||||
|
|
||||||
function strayEntries(dir, kept, where, now) {
|
|
||||||
let entries;
|
|
||||||
try {
|
|
||||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
||||||
} catch {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
|
|
||||||
return entries
|
|
||||||
.filter((e) => !kept.has(e.name))
|
|
||||||
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
|
||||||
.filter((e) => settled(e.path));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Everything Cleanup would remove, worked out on the server and never taken
|
|
||||||
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
|
|
||||||
* `open` sweeps by, plus every file in the folder that old, so a resumed
|
|
||||||
* session or a saved draft keeps it), anything at the top of the console folder that is
|
|
||||||
* not kept, and -- only when the console runs from its default home inside
|
|
||||||
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
|
|
||||||
* touched within `STRAY_GRACE_MS` are left for a later scan. A
|
|
||||||
* console running from another home (tests, dev) never reaches ~/.plan2code.
|
|
||||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
|
||||||
*/
|
|
||||||
export async function cleanupFindings({
|
|
||||||
consoleDir = HOME_DIR,
|
|
||||||
plan2codeDir = PLAN2CODE_DIR,
|
|
||||||
now = Date.now(),
|
|
||||||
maxAgeMs = SESSION_MAX_AGE_MS,
|
|
||||||
skipSid,
|
|
||||||
} = {}) {
|
|
||||||
const found = [];
|
|
||||||
const sessionsDir = path.join(consoleDir, "sessions");
|
|
||||||
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
|
|
||||||
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
|
|
||||||
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
|
|
||||||
}
|
|
||||||
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
|
|
||||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
|
||||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
|
||||||
}
|
|
||||||
const items = [];
|
|
||||||
let bytes = 0;
|
|
||||||
for (const f of found) {
|
|
||||||
const size = await diskBytes(f.path);
|
|
||||||
bytes += size;
|
|
||||||
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
|
|
||||||
}
|
|
||||||
return { items, bytes };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
|
|
||||||
* worked out afresh first and only ids on it are touched, so a name from the
|
|
||||||
* page is never a path, and anything that stopped qualifying since the scan
|
|
||||||
* (a session touched again) stays. A link is unlinked, never followed.
|
|
||||||
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
|
|
||||||
*/
|
|
||||||
export async function removeCleanup(ids, opts = {}) {
|
|
||||||
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
|
|
||||||
const { items } = await cleanupFindings(opts);
|
|
||||||
const removed = [];
|
|
||||||
const failed = [];
|
|
||||||
let bytes = 0;
|
|
||||||
for (const item of items) {
|
|
||||||
if (!wanted.has(item.id)) continue;
|
|
||||||
try {
|
|
||||||
if (item.kind === "link") await fs.promises.unlink(item.path);
|
|
||||||
else await fs.promises.rm(item.path, { recursive: true, force: true });
|
|
||||||
removed.push(item.id);
|
|
||||||
bytes += item.bytes;
|
|
||||||
} catch {
|
|
||||||
failed.push(item.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { removed, bytes, failed };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
||||||
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
||||||
@@ -1025,7 +870,7 @@ export function handOff(child, pre) {
|
|||||||
|
|
||||||
/* ----------------------------------------------------------- patch merge */
|
/* ----------------------------------------------------------- patch merge */
|
||||||
|
|
||||||
const APPEND_KEYS = new Set(["thread"]);
|
const APPEND_KEYS = new Set(["thread", "comments"]);
|
||||||
|
|
||||||
function isPlainObject(v) {
|
function isPlainObject(v) {
|
||||||
return v !== null && typeof v === "object" && !Array.isArray(v);
|
return v !== null && typeof v === "object" && !Array.isArray(v);
|
||||||
@@ -1050,7 +895,7 @@ function mergeOne(target, patch, where) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
||||||
// Named fields are replaced whole; thread appends.
|
// Named fields are replaced whole; thread/comments append.
|
||||||
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||||
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
||||||
for (const entry of patchList) {
|
for (const entry of patchList) {
|
||||||
@@ -1109,60 +954,11 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
|||||||
return merged;
|
return merged;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
|
|
||||||
// borrow the shape of the replies and doc blocks they also write, so `from` /
|
|
||||||
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
|
|
||||||
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
|
|
||||||
// at all is refused. The person's own notes are recorded by the server when
|
|
||||||
// they send, so an agent that echoes one back is not shown it twice.
|
|
||||||
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
|
|
||||||
|
|
||||||
function normalizeThreads(patchList, currentItems) {
|
|
||||||
return patchList.map((entry) => {
|
|
||||||
if (!isPlainObject(entry) || entry.thread == null) return entry;
|
|
||||||
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
|
|
||||||
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
|
|
||||||
const said = new Set(
|
|
||||||
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
|
|
||||||
);
|
|
||||||
const thread = [];
|
|
||||||
for (const m of entry.thread) {
|
|
||||||
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
|
|
||||||
guard(m, "thread");
|
|
||||||
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
|
|
||||||
if (!key) {
|
|
||||||
throw new Error(
|
|
||||||
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const { from, role, md, body, content, ...rest } = m;
|
|
||||||
const who = (m.who || from || role) === "user" ? "user" : "agent";
|
|
||||||
const text = m[key];
|
|
||||||
if (who === "user" && said.has(text.trim())) continue;
|
|
||||||
thread.push({ ...rest, who, text });
|
|
||||||
}
|
|
||||||
return { ...entry, thread };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
||||||
|
|
||||||
// Blocks merge by id like docs do, so a patch that only settles a block's
|
// Blocks merge by id like docs do, so a patch that only settles a block's
|
||||||
// state keeps its text. Blocks left out of the patch stay as they are.
|
// state keeps its text. Blocks left out of the patch stay as they are.
|
||||||
function mergeDocs(current, patchList) {
|
function mergeDocs(current, patchList) {
|
||||||
// A doc's version only moves forward. One going back is a stale or copied
|
|
||||||
// payload (last phase's progress script, say), and the page would quietly
|
|
||||||
// show the old content under the new run's name.
|
|
||||||
for (const entry of patchList) {
|
|
||||||
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
|
|
||||||
const prev = (current || []).find((d) => d && d.id === entry.id);
|
|
||||||
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
|
|
||||||
throw new Error(
|
|
||||||
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
|
|
||||||
"Versions only go up: bump it, and check the payload is the current one."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
||||||
for (const entry of patchList) {
|
for (const entry of patchList) {
|
||||||
if (!Array.isArray(entry.blocks)) continue;
|
if (!Array.isArray(entry.blocks)) continue;
|
||||||
@@ -1199,19 +995,12 @@ export function applyPatch(state, patch) {
|
|||||||
break;
|
break;
|
||||||
case "items":
|
case "items":
|
||||||
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
||||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
|
next.items = dropStaleSubmissions(next.items, state.items, v);
|
||||||
break;
|
break;
|
||||||
case "topics":
|
case "topics":
|
||||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||||
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
||||||
break;
|
break;
|
||||||
case "helpers":
|
|
||||||
// The agent's report of its helpers, for the page's Subagents tab.
|
|
||||||
// Only `post` writes it; the server's /submit never touches it.
|
|
||||||
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
|
|
||||||
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
|
|
||||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
|
||||||
break;
|
|
||||||
case "docs":
|
case "docs":
|
||||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||||
next.docs = mergeDocs(next.docs, v);
|
next.docs = mergeDocs(next.docs, v);
|
||||||
@@ -1258,11 +1047,15 @@ function stampTimes(before, next) {
|
|||||||
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
||||||
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
||||||
}
|
}
|
||||||
if (Array.isArray(next.items)) {
|
for (const list of [next.items, next.docs]) {
|
||||||
for (const entry of next.items) {
|
if (!Array.isArray(list)) continue;
|
||||||
|
for (const entry of list) {
|
||||||
if (Array.isArray(entry.thread)) {
|
if (Array.isArray(entry.thread)) {
|
||||||
for (const m of entry.thread) if (!m.at) m.at = now;
|
for (const m of entry.thread) if (!m.at) m.at = now;
|
||||||
}
|
}
|
||||||
|
if (Array.isArray(entry.comments)) {
|
||||||
|
for (const m of entry.comments) if (!m.at) m.at = now;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Array.isArray(next.docs)) {
|
if (Array.isArray(next.docs)) {
|
||||||
@@ -1495,10 +1288,7 @@ export function validate(state) {
|
|||||||
// server's record of an answer someone pressed Send on; if their own words
|
// server's record of an answer someone pressed Send on; if their own words
|
||||||
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
||||||
// would be rejected and the session would wedge with no way out.
|
// would be rejected and the session would wedge with no way out.
|
||||||
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
|
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
|
||||||
...rest,
|
|
||||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
|
||||||
}));
|
|
||||||
const prose =
|
const prose =
|
||||||
JSON.stringify(authored) +
|
JSON.stringify(authored) +
|
||||||
JSON.stringify(state.docs || []) +
|
JSON.stringify(state.docs || []) +
|
||||||
@@ -1506,20 +1296,6 @@ export function validate(state) {
|
|||||||
JSON.stringify(state.menu || {});
|
JSON.stringify(state.menu || {});
|
||||||
problems.push(...proseProblems(prose));
|
problems.push(...proseProblems(prose));
|
||||||
|
|
||||||
// The agent's report of its helpers: the shape the page draws from
|
|
||||||
// (subagents.js), then the same prose scan as everything else it writes.
|
|
||||||
if (state.helpers != null) {
|
|
||||||
problems.push(...checkHelpers(state.helpers));
|
|
||||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
|
||||||
if (!isPlainObject(helper)) continue;
|
|
||||||
for (const field of ["title", "ask", "result"]) {
|
|
||||||
if (typeof helper[field] === "string") {
|
|
||||||
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return problems;
|
return problems;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1549,8 +1325,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
|||||||
* A resume that passes through the dashboard (a finished skill going back to
|
* A resume that passes through the dashboard (a finished skill going back to
|
||||||
* it, or a launch from its menu) is a new skill taking the page over, so it
|
* it, or a launch from its menu) is a new skill taking the page over, so it
|
||||||
* starts from a blank page: the last skill's questions, sections, docs,
|
* starts from a blank page: the last skill's questions, sections, docs,
|
||||||
* helpers, headline and ending are its record on disk, not the next skill's
|
* headline and ending are its record on disk, not the next skill's opening.
|
||||||
* opening.
|
|
||||||
* Only the session's identity carries across. `workspace.json`,
|
* Only the session's identity carries across. `workspace.json`,
|
||||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||||
* and the meter outlive every hop.
|
* and the meter outlive every hop.
|
||||||
@@ -1577,8 +1352,6 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
|
|||||||
// workspace.json the server. Folders, version, change log, missing, remote.
|
// workspace.json the server. Folders, version, change log, missing, remote.
|
||||||
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
||||||
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
||||||
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
|
|
||||||
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
|
|
||||||
export const CHAT_FILE = "chat.ndjson";
|
export const CHAT_FILE = "chat.ndjson";
|
||||||
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
||||||
export const WORKSPACE_FILE = "workspace.json";
|
export const WORKSPACE_FILE = "workspace.json";
|
||||||
@@ -1846,125 +1619,17 @@ export function readWorkspace(dir) {
|
|||||||
return readJson(path.join(dir, WORKSPACE_FILE), null);
|
return readJson(path.join(dir, WORKSPACE_FILE), null);
|
||||||
}
|
}
|
||||||
|
|
||||||
// A fresh workspace: the original folder, named after itself, plus whatever
|
// A fresh workspace: just the original folder, named after itself.
|
||||||
// was remembered for this folder and spec (rememberedWorkspace() below).
|
export function initialWorkspace(worktree) {
|
||||||
export function initialWorkspace(worktree, remembered = null) {
|
|
||||||
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
|
|
||||||
if (remembered && remembered.original) {
|
|
||||||
if (remembered.original.name) original.name = remembered.original.name;
|
|
||||||
if (remembered.original.description) original.description = remembered.original.description;
|
|
||||||
}
|
|
||||||
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
|
|
||||||
id: "f" + (i + 1),
|
|
||||||
path: f.path,
|
|
||||||
name: f.name,
|
|
||||||
description: f.description || "",
|
|
||||||
...(f.nested ? { nested: true } : {}),
|
|
||||||
}));
|
|
||||||
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------ remembered workspaces */
|
|
||||||
|
|
||||||
// The folder list outlives the console session: one file for the person,
|
|
||||||
// beside looks.json, keyed by the folder a session runs in and then by spec.
|
|
||||||
// Never under specs/: the paths are this machine's, and the server never
|
|
||||||
// writes into a project.
|
|
||||||
//
|
|
||||||
// { "projects": { "<folded worktree>": {
|
|
||||||
// "path": "<worktree>",
|
|
||||||
// "project": { original, folders, at }, // no spec picked
|
|
||||||
// "specs": { "specs/<name>": { original, folders, at } } } } }
|
|
||||||
//
|
|
||||||
// `original` holds the first folder's name and description only (its path is
|
|
||||||
// always the session's own); `folders` the added ones as { path, name,
|
|
||||||
// description, nested? }. Two writers, the server on every change and
|
|
||||||
// `console.mjs forget`, each a read-modify-write of one key.
|
|
||||||
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
|
|
||||||
|
|
||||||
const foldKey = (p) => {
|
|
||||||
const resolved = path.resolve(String(p || ""));
|
|
||||||
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
|
|
||||||
};
|
|
||||||
|
|
||||||
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
|
|
||||||
export function specKey(specDir) {
|
|
||||||
return String(specDir || "")
|
|
||||||
.trim()
|
|
||||||
.replace(/\\/g, "/")
|
|
||||||
.replace(/^\.\//, "")
|
|
||||||
.replace(/\/+$/, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function readStore() {
|
|
||||||
const saved = readJson(WORKSPACES_FILE, null);
|
|
||||||
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What was remembered for this folder and spec: `{ entry, from }`, where
|
|
||||||
* `from` is "spec" when the spec has its own list, "project" when it falls
|
|
||||||
* back to the project's (a spec's list starts as a copy of it), and null
|
|
||||||
* when nothing was ever saved.
|
|
||||||
*/
|
|
||||||
export function rememberedWorkspace(worktree, specDir) {
|
|
||||||
const project = readStore().projects[foldKey(worktree)];
|
|
||||||
if (!project) return { entry: null, from: null };
|
|
||||||
const spec = specKey(specDir);
|
|
||||||
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
|
|
||||||
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
|
|
||||||
}
|
|
||||||
|
|
||||||
// The workspace's folders as the store keeps them.
|
|
||||||
export function rememberable(ws) {
|
|
||||||
const folders = (ws && ws.folders) || [];
|
|
||||||
const first = folders.find((f) => f.original) || {};
|
|
||||||
return {
|
return {
|
||||||
original: { name: first.name || "", description: first.description || "" },
|
version: 0,
|
||||||
folders: folders
|
folders: [{ id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }],
|
||||||
.filter((f) => !f.original)
|
missing: [],
|
||||||
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
|
changes: [],
|
||||||
at: nowIso(),
|
remote: "",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Every server and `console.mjs forget` writes the one file, so each
|
|
||||||
// read-modify-write holds this lock beside it.
|
|
||||||
const WORKSPACES_LOCK = "workspaces.json.lock";
|
|
||||||
|
|
||||||
// Save the list for this folder and spec ("" for the project's own).
|
|
||||||
export function rememberWorkspace(worktree, specDir, ws) {
|
|
||||||
ensureDir(path.dirname(WORKSPACES_FILE));
|
|
||||||
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveRemembered(worktree, specDir, ws) {
|
|
||||||
const store = readStore();
|
|
||||||
const key = foldKey(worktree);
|
|
||||||
const project = store.projects[key] || { path: path.resolve(worktree) };
|
|
||||||
const spec = specKey(specDir);
|
|
||||||
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
|
|
||||||
else project.project = rememberable(ws);
|
|
||||||
store.projects[key] = project;
|
|
||||||
writeJsonAtomic(WORKSPACES_FILE, store);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
|
|
||||||
export function forgetWorkspace(worktree, specDir) {
|
|
||||||
const spec = specKey(specDir);
|
|
||||||
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
|
|
||||||
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
|
|
||||||
}
|
|
||||||
|
|
||||||
function dropRemembered(worktree, spec) {
|
|
||||||
const store = readStore();
|
|
||||||
const project = store.projects[foldKey(worktree)];
|
|
||||||
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
|
|
||||||
delete project.specs[spec];
|
|
||||||
writeJsonAtomic(WORKSPACES_FILE, store);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only server.mjs may call this.
|
// Single-writer rule: only server.mjs may call this.
|
||||||
export function writeWorkspace(dir, ws) {
|
export function writeWorkspace(dir, ws) {
|
||||||
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
|
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
|
||||||
@@ -2034,98 +1699,6 @@ export function pendingWorkspaceChanges(dir) {
|
|||||||
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------ the Subagents switch */
|
|
||||||
|
|
||||||
// The person's Subagents switch, remembered per project folder and workflow:
|
|
||||||
//
|
|
||||||
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
|
|
||||||
//
|
|
||||||
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
|
|
||||||
// workflow's shipped default.
|
|
||||||
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
|
|
||||||
const SUBAGENTS_LOCK = "subagents.json.lock";
|
|
||||||
|
|
||||||
function readSubagentStore() {
|
|
||||||
const saved = readJson(SUBAGENTS_FILE, null);
|
|
||||||
return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
|
||||||
}
|
|
||||||
|
|
||||||
// The saved `{ on, instruction, max }` for this folder and workflow, or the
|
|
||||||
// default's when nothing (or something malformed) is saved.
|
|
||||||
export function subagentStoreEntry(worktree, workflow) {
|
|
||||||
const { on, instruction, max } = defaultSetting(workflow);
|
|
||||||
const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null;
|
|
||||||
const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null;
|
|
||||||
return saved && !saved.error ? saved : { on, instruction, max };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only server.mjs may call this.
|
|
||||||
export function saveSubagentStoreEntry(worktree, workflow, value) {
|
|
||||||
ensureDir(path.dirname(SUBAGENTS_FILE));
|
|
||||||
withStateLock(
|
|
||||||
path.dirname(SUBAGENTS_FILE),
|
|
||||||
() => {
|
|
||||||
const store = readSubagentStore();
|
|
||||||
const key = foldKey(worktree);
|
|
||||||
const project = store[key] && typeof store[key] === "object" ? store[key] : {};
|
|
||||||
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } };
|
|
||||||
writeJsonAtomic(SUBAGENTS_FILE, store);
|
|
||||||
},
|
|
||||||
SUBAGENTS_LOCK
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
|
||||||
|
|
||||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
|
||||||
|
|
||||||
// This session's switch, `{ workflow, on, instruction, max, revision }`, or
|
|
||||||
// null when there is none or it is malformed.
|
|
||||||
export function readSubagentSetting(dir) {
|
|
||||||
const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null);
|
|
||||||
if (!s || typeof s !== "object") return null;
|
|
||||||
if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null;
|
|
||||||
return s;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only server.mjs may call this. The revision never goes
|
|
||||||
// backwards within a session.
|
|
||||||
export function writeSubagentSetting(dir, setting) {
|
|
||||||
const previous = readSubagentSetting(dir);
|
|
||||||
const revision = Math.max(previous ? previous.revision : 0, setting.revision);
|
|
||||||
return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision });
|
|
||||||
}
|
|
||||||
|
|
||||||
export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json";
|
|
||||||
const CURSOR_STATES = new Set(["none", "on", "off"]);
|
|
||||||
|
|
||||||
// What the agent was last told: `{ revision, state }`.
|
|
||||||
export function readSubagentCursor(dir) {
|
|
||||||
const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null);
|
|
||||||
if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" };
|
|
||||||
return { revision: saved.revision, state: saved.state };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only console.mjs may call this. Never backwards, like
|
|
||||||
// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one.
|
|
||||||
export function writeSubagentCursor(dir, cursor) {
|
|
||||||
const old = readSubagentCursor(dir);
|
|
||||||
const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state };
|
|
||||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The one place the cursor may go back: `open`, which starts a fresh agent.
|
|
||||||
export function resetSubagentCursor(dir) {
|
|
||||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// The `caps` of the last `open` event: what the agent's console copy can do.
|
|
||||||
export function latestOpenCaps(dir) {
|
|
||||||
const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open");
|
|
||||||
const last = opens[opens.length - 1];
|
|
||||||
return last && Array.isArray(last.caps) ? last.caps : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flag the case where the link cannot be opened by the person it is for.
|
* Flag the case where the link cannot be opened by the person it is for.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
|
|||||||
if (!s || typeof s !== "object") return null;
|
if (!s || typeof s !== "object") return null;
|
||||||
if (item.answer && typeof item.answer === "object") return null;
|
if (item.answer && typeof item.answer === "object") return null;
|
||||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||||
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
|
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||||
return replied ? null : s;
|
return replied ? null : s;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,33 +74,17 @@ export function submittedAwaiting(item) {
|
|||||||
* agent has yet to say anything after it. The server records it as `sentNote`
|
* agent has yet to say anything after it. The server records it as `sentNote`
|
||||||
* on every send, so the page can show it in the Notes pane and in the Sent
|
* on every send, so the page can show it in the Notes pane and in the Sent
|
||||||
* box instead of letting it vanish into a send that shows no sign of arriving.
|
* box instead of letting it vanish into a send that shows no sign of arriving.
|
||||||
* Any agent message from the send onwards, or one with no clock to compare,
|
* Any thread message from the send onwards, or none with a clock to compare,
|
||||||
* means it has been picked up. The person's own entries never count: the
|
* means it has been picked up.
|
||||||
* server writes their note into the thread as it arrives.
|
|
||||||
*/
|
*/
|
||||||
export function noteAwaiting(item) {
|
export function noteAwaiting(item) {
|
||||||
const n = item && item.sentNote;
|
const n = item && item.sentNote;
|
||||||
if (!n || typeof n !== "object") return null;
|
if (!n || typeof n !== "object") return null;
|
||||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||||
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
|
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
|
||||||
return picked ? null : n;
|
return picked ? null : n;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Who said a thread entry and what they said. The contract is `{ who, text }`
|
|
||||||
* and the server lifts anything else into it, but sessions written before that
|
|
||||||
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
|
|
||||||
*/
|
|
||||||
export function threadWho(m) {
|
|
||||||
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
|
|
||||||
}
|
|
||||||
|
|
||||||
export function threadText(m) {
|
|
||||||
if (!m) return "";
|
|
||||||
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/* -------------------------------------------------------------- labels */
|
/* -------------------------------------------------------------- labels */
|
||||||
|
|
||||||
export function optionLabel(item, k) {
|
export function optionLabel(item, k) {
|
||||||
|
|||||||
@@ -23,9 +23,6 @@
|
|||||||
--warn-soft: #fbe7e3;
|
--warn-soft: #fbe7e3;
|
||||||
--focus: #1f6feb;
|
--focus: #1f6feb;
|
||||||
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
||||||
/* A soft accent halo for the things that want noticing: the update banner
|
|
||||||
and an enabled Send. Built from --accent, so a picked accent glows too. */
|
|
||||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
|
|
||||||
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||||
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
||||||
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
||||||
@@ -64,7 +61,6 @@
|
|||||||
--warn-soft: #34201d;
|
--warn-soft: #34201d;
|
||||||
--focus: #6aa3ff;
|
--focus: #6aa3ff;
|
||||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +85,6 @@
|
|||||||
--warn-soft: #34201d;
|
--warn-soft: #34201d;
|
||||||
--focus: #6aa3ff;
|
--focus: #6aa3ff;
|
||||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
* { box-sizing: border-box; }
|
* { box-sizing: border-box; }
|
||||||
@@ -208,26 +203,6 @@ body {
|
|||||||
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
||||||
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||||
|
|
||||||
/* Subagents: an orchestrator and its helpers. Unlit is a hollow outline in
|
|
||||||
the quiet ink; lit fills the nodes with the highlight color. */
|
|
||||||
.subagents-btn { border-color: var(--rule-2); color: var(--ink-2); display: inline-flex; align-items: center; justify-content: center; }
|
|
||||||
.btn.subagents-btn { padding: 0 6px; align-self: stretch; }
|
|
||||||
.subagents-btn[hidden] { display: none; }
|
|
||||||
.subagents-btn svg { width: 16px; height: 16px; display: block; }
|
|
||||||
.subagents-btn .sa-link { fill: none; stroke: var(--ink-2); stroke-width: 1.2; stroke-linecap: round; }
|
|
||||||
.subagents-btn .sa-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
|
|
||||||
.subagents-btn .sa-node { fill: none; stroke: var(--ink-2); stroke-width: 1.2; }
|
|
||||||
.subagents-btn[aria-pressed="true"] .sa-hub,
|
|
||||||
.subagents-btn[aria-pressed="true"] .sa-node { fill: var(--accent); stroke: var(--accent); }
|
|
||||||
.subagents-btn[aria-pressed="true"] .sa-link { stroke: var(--accent); }
|
|
||||||
.subagents-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
|
||||||
.subagents-btn:hover:not(:disabled) .sa-link,
|
|
||||||
.subagents-btn:hover:not(:disabled) .sa-hub,
|
|
||||||
.subagents-btn:hover:not(:disabled) .sa-node { stroke: var(--accent); }
|
|
||||||
.subagents-btn:disabled .sa-link,
|
|
||||||
.subagents-btn:disabled .sa-hub,
|
|
||||||
.subagents-btn:disabled .sa-node { stroke: var(--ink-3); fill: none; }
|
|
||||||
|
|
||||||
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
||||||
|
|
||||||
/* The session meter: a ring that fills with the points and a few words, in
|
/* The session meter: a ring that fills with the points and a few words, in
|
||||||
@@ -1121,15 +1096,6 @@ h1 {
|
|||||||
.ask-disabled-note.is-limit, .ask-disabled-note.is-waiting { color: var(--ink-2); background: var(--panel-2); border: 1px solid var(--rule); }
|
.ask-disabled-note.is-limit, .ask-disabled-note.is-waiting { color: var(--ink-2); background: var(--panel-2); border: 1px solid var(--rule); }
|
||||||
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
||||||
|
|
||||||
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
|
|
||||||
the tiny ring, left of the label. The extra .spinner is for specificity:
|
|
||||||
.spinner.tiny comes later and zeroes the margin otherwise. */
|
|
||||||
.view-tab .spinner.tab-spin {
|
|
||||||
display: inline-block;
|
|
||||||
margin-right: 7px;
|
|
||||||
vertical-align: -1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* A reply landed while another tab was open. */
|
/* A reply landed while another tab was open. */
|
||||||
.view-tab .tab-dot {
|
.view-tab .tab-dot {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
@@ -1450,30 +1416,6 @@ h1 {
|
|||||||
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
||||||
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
||||||
|
|
||||||
/* The Subagents tab: one row per reported helper, newest state in a pill. */
|
|
||||||
.sa-card h2 { margin: 0 0 6px; }
|
|
||||||
.sa-card > .help { margin: 0 0 16px; }
|
|
||||||
.sa-alone { margin: 0; color: var(--ink-2); }
|
|
||||||
.sa-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
|
|
||||||
.sa-row { border: 1px solid var(--rule); border-radius: 8px; background: var(--panel-2); padding: 12px 14px; }
|
|
||||||
.sa-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
|
||||||
.sa-title { min-width: 0; overflow-wrap: anywhere; }
|
|
||||||
.sa-ask {
|
|
||||||
margin: 4px 0 0; color: var(--ink-2); font-size: 13.5px;
|
|
||||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
|
|
||||||
}
|
|
||||||
.sa-result { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
|
||||||
.sa-pill { display: inline-flex; align-items: center; gap: 6px; flex: none; }
|
|
||||||
.sa-pill.is-running { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
|
|
||||||
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
|
|
||||||
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
|
|
||||||
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
|
|
||||||
/* The dialog's number box, themed like the page's other inputs. */
|
|
||||||
.subagents input[type="number"] {
|
|
||||||
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
|
|
||||||
border: 1px solid var(--rule-2); border-radius: 6px; padding: 4px 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------ settled answer */
|
/* ------------------------------------------------------ settled answer */
|
||||||
|
|
||||||
.answered {
|
.answered {
|
||||||
@@ -1707,13 +1649,11 @@ input[type="text"].invalid { border-color: var(--warn); }
|
|||||||
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||||
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
||||||
/* Send glows and breathes while there is something to send: the steady
|
/* Send breathes while there is something to send: a soft accent ring that
|
||||||
--glow, plus a soft accent ring that spreads and fades. The ring is off
|
spreads and fades. Off under reduced motion, below. */
|
||||||
under reduced motion, below; the glow stays. */
|
|
||||||
#btn-send:not(:disabled) { box-shadow: var(--glow); }
|
|
||||||
@keyframes send-pulse {
|
@keyframes send-pulse {
|
||||||
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
|
0% { box-shadow: 0 0 0 0 var(--accent-line); }
|
||||||
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
|
100% { box-shadow: 0 0 0 6px transparent; }
|
||||||
}
|
}
|
||||||
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
||||||
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
||||||
@@ -2015,8 +1955,6 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.footer-where:hover { text-decoration: underline; }
|
.footer-where:hover { text-decoration: underline; }
|
||||||
/* The project name, in the person's highlight color. */
|
|
||||||
.where-project { color: var(--accent); font-weight: 600; }
|
|
||||||
/* A folder is missing or the agent could not read one: the dialog says which. */
|
/* A folder is missing or the agent could not read one: the dialog says which. */
|
||||||
.where-alert {
|
.where-alert {
|
||||||
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
||||||
@@ -2059,18 +1997,6 @@ kbd {
|
|||||||
}
|
}
|
||||||
.waiting-pane h2 { font: 600 23px/1.3 var(--serif); color: var(--ink); margin: 0; }
|
.waiting-pane h2 { font: 600 23px/1.3 var(--serif); color: var(--ink); margin: 0; }
|
||||||
.waiting-pane p { margin: 0; }
|
.waiting-pane p { margin: 0; }
|
||||||
/* The words that open the tasks tab: bold in the highlight color, a button
|
|
||||||
that reads as part of the sentence. */
|
|
||||||
.waiting-jump {
|
|
||||||
font: inherit;
|
|
||||||
font-weight: 700;
|
|
||||||
color: var(--accent);
|
|
||||||
background: none;
|
|
||||||
border: 0;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
button.waiting-jump { cursor: pointer; text-decoration: underline; text-decoration-color: var(--accent-line); text-underline-offset: 3px; }
|
|
||||||
button.waiting-jump:hover { text-decoration-color: var(--accent); }
|
|
||||||
/* Once the work is under way Planny steps back a size, and the ring in
|
/* Once the work is under way Planny steps back a size, and the ring in
|
||||||
front of the stage name carries the "still going" signal instead. */
|
front of the stage name carries the "still going" signal instead. */
|
||||||
.waiting-pane .pose-stage { height: 130px; transition: height 0.35s ease; }
|
.waiting-pane .pose-stage { height: 130px; transition: height 0.35s ease; }
|
||||||
@@ -2273,7 +2199,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
.modal.help[open] { display: flex; }
|
.modal.help[open] { display: flex; }
|
||||||
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
||||||
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
||||||
.help-version a { color: inherit; }
|
|
||||||
|
|
||||||
.help-layout {
|
.help-layout {
|
||||||
display: grid;
|
display: grid;
|
||||||
@@ -2580,9 +2505,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
actions stay put. */
|
actions stay put. */
|
||||||
.modal.workspace { max-width: 680px; }
|
.modal.workspace { max-width: 680px; }
|
||||||
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
||||||
.workspace .modal-blurb { margin-bottom: 6px; }
|
|
||||||
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
|
|
||||||
|
|
||||||
.workspace-list {
|
.workspace-list {
|
||||||
list-style: none; margin: 0; padding: 0;
|
list-style: none; margin: 0; padding: 0;
|
||||||
display: grid; gap: 12px;
|
display: grid; gap: 12px;
|
||||||
@@ -2723,74 +2645,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
border-left-width: 4px;
|
border-left-width: 4px;
|
||||||
color: var(--ink);
|
color: var(--ink);
|
||||||
}
|
}
|
||||||
/* A newer release: the same slot, in the accent, with the label as the way
|
|
||||||
into the update modal and a small × that hides it for this session. */
|
|
||||||
.dash-nudge.update-banner {
|
|
||||||
position: relative;
|
|
||||||
padding-left: 40px;
|
|
||||||
padding-right: 40px;
|
|
||||||
border-left-width: 4px;
|
|
||||||
border-left-color: var(--accent-line);
|
|
||||||
color: var(--ink);
|
|
||||||
box-shadow: var(--glow);
|
|
||||||
}
|
|
||||||
.update-banner-open {
|
|
||||||
flex: 1 1 16em;
|
|
||||||
padding: 0;
|
|
||||||
border: 0;
|
|
||||||
background: none;
|
|
||||||
color: inherit;
|
|
||||||
font: inherit;
|
|
||||||
font-weight: 600;
|
|
||||||
letter-spacing: 0.02em;
|
|
||||||
text-align: center;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.update-banner-open:hover { text-decoration: underline; }
|
|
||||||
/* Pinned to the right edge, out of the flow, so the label centres on the
|
|
||||||
whole banner rather than on what the × leaves of it. */
|
|
||||||
.update-banner-dismiss {
|
|
||||||
position: absolute;
|
|
||||||
top: 50%;
|
|
||||||
right: 10px;
|
|
||||||
transform: translateY(-50%);
|
|
||||||
padding: 0 6px;
|
|
||||||
border: 0;
|
|
||||||
border-radius: var(--radius);
|
|
||||||
background: none;
|
|
||||||
color: inherit;
|
|
||||||
font: inherit;
|
|
||||||
font-size: 16px;
|
|
||||||
line-height: 1;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.update-banner-dismiss:hover { background: var(--accent-line); }
|
|
||||||
/* Wide enough that the update command sits on one line beside Copy; a
|
|
||||||
narrow window still wraps it rather than overflowing. */
|
|
||||||
#update-modal { max-width: 720px; }
|
|
||||||
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
|
|
||||||
.update-steps li { margin: 4px 0; }
|
|
||||||
/* The hand-off copy row, in the modal's first step: the command and its Copy
|
|
||||||
side by side. */
|
|
||||||
.update-command {
|
|
||||||
margin: 6px 0 4px;
|
|
||||||
display: flex;
|
|
||||||
align-items: stretch;
|
|
||||||
gap: 10px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
}
|
|
||||||
.update-command code {
|
|
||||||
flex: 1 1 260px;
|
|
||||||
min-width: 0;
|
|
||||||
font: 13px/1.5 var(--mono);
|
|
||||||
color: var(--ink);
|
|
||||||
background: var(--panel);
|
|
||||||
border: 1px solid var(--rule-2);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 10px 12px;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
||||||
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
||||||
.dash-working {
|
.dash-working {
|
||||||
@@ -3275,6 +3129,11 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
0%, 15%, 75%, 100% { transform: scale(1); opacity: 0.16; }
|
0%, 15%, 75%, 100% { transform: scale(1); opacity: 0.16; }
|
||||||
45% { transform: scale(0.7); opacity: 0.08; }
|
45% { transform: scale(0.7); opacity: 0.08; }
|
||||||
}
|
}
|
||||||
|
.pose .fz-halo { opacity: 0.25; animation: fz-halo 1.6s ease-in-out infinite; }
|
||||||
|
@keyframes fz-halo {
|
||||||
|
0%, 100% { transform: scale(1); opacity: 0.2; }
|
||||||
|
45% { transform: scale(1.3); opacity: 0.4; }
|
||||||
|
}
|
||||||
.pose .fz-tick { stroke: var(--accent-ink); }
|
.pose .fz-tick { stroke: var(--accent-ink); }
|
||||||
.pose .fz-flag { transform-origin: 0% 50%; animation: fz-wave 1.2s ease-in-out infinite; }
|
.pose .fz-flag { transform-origin: 0% 50%; animation: fz-wave 1.2s ease-in-out infinite; }
|
||||||
@keyframes fz-wave {
|
@keyframes fz-wave {
|
||||||
@@ -3517,18 +3376,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||||
.models-actions .help.error { color: var(--danger, #d64545); }
|
.models-actions .help.error { color: var(--danger, #d64545); }
|
||||||
|
|
||||||
/* User Preferences: Cleanup's list of what would go, shown before anything
|
|
||||||
is deleted. */
|
|
||||||
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
|
|
||||||
.cleanup-list:empty { display: none; }
|
|
||||||
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
|
|
||||||
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
|
|
||||||
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
|
|
||||||
.cleanup-size { flex: none; color: var(--ink-3); }
|
|
||||||
.cleanup-more { display: grid; gap: 4px; }
|
|
||||||
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
|
|
||||||
#cleanup-delete[hidden] { display: none; }
|
|
||||||
|
|
||||||
/* A word the person has to type, bold and in their highlight color so it
|
/* A word the person has to type, bold and in their highlight color so it
|
||||||
does not get lost in the status sentence. */
|
does not get lost in the status sentence. */
|
||||||
.agent-key {
|
.agent-key {
|
||||||
|
|||||||
@@ -66,8 +66,6 @@ import {
|
|||||||
submittedAwaiting,
|
submittedAwaiting,
|
||||||
noteAwaiting,
|
noteAwaiting,
|
||||||
suggestionFrom,
|
suggestionFrom,
|
||||||
threadText,
|
|
||||||
threadWho,
|
|
||||||
THUMB_EDGE,
|
THUMB_EDGE,
|
||||||
turnGate,
|
turnGate,
|
||||||
verdictText,
|
verdictText,
|
||||||
@@ -103,15 +101,6 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
|
|||||||
import { RED_BANNER } from "./meter.js";
|
import { RED_BANNER } from "./meter.js";
|
||||||
import { applyMention, matchNames, mentionAt } from "./mentions.js";
|
import { applyMention, matchNames, mentionAt } from "./mentions.js";
|
||||||
import { faviconState, setFavicon } from "./favicon.js";
|
import { faviconState, setFavicon } from "./favicon.js";
|
||||||
import {
|
|
||||||
CHECKIN_LINE,
|
|
||||||
PATHFINDER_RESEARCH_LINE,
|
|
||||||
defaultInstruction,
|
|
||||||
helperRows,
|
|
||||||
showSwitch,
|
|
||||||
showTab,
|
|
||||||
switchLabel,
|
|
||||||
} from "./subagents.js";
|
|
||||||
|
|
||||||
const $ = (id) => document.getElementById(id);
|
const $ = (id) => document.getElementById(id);
|
||||||
|
|
||||||
@@ -457,10 +446,6 @@ document.addEventListener("click", (e) => {
|
|||||||
|
|
||||||
|
|
||||||
const GONE_AFTER_MS = 8000;
|
const GONE_AFTER_MS = 8000;
|
||||||
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
|
|
||||||
// wipe an unrelated warning that landed while the page was gone (an upload
|
|
||||||
// failure, a refused send).
|
|
||||||
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
|
|
||||||
const WORKING_GRACE_MS = 5 * 60 * 1000;
|
const WORKING_GRACE_MS = 5 * 60 * 1000;
|
||||||
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
||||||
// listening. The difference is the cost of being wrong: a working agent that
|
// listening. The difference is the cost of being wrong: a working agent that
|
||||||
@@ -536,12 +521,6 @@ let chatFrame = null;
|
|||||||
// sends them.
|
// sends them.
|
||||||
let wsFrame = null;
|
let wsFrame = null;
|
||||||
let meterFrame = null;
|
let meterFrame = null;
|
||||||
// The frame's update ({ installed, latest }), present only when a newer
|
|
||||||
// release is out; null otherwise.
|
|
||||||
let updateFrame = null;
|
|
||||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
|
||||||
// revision }), or null before a server that sends it.
|
|
||||||
let subagentsFrame = null;
|
|
||||||
let chatDot = false;
|
let chatDot = false;
|
||||||
let chatSending = false;
|
let chatSending = false;
|
||||||
let chatResetting = false;
|
let chatResetting = false;
|
||||||
@@ -587,6 +566,7 @@ function fresh() {
|
|||||||
drafts: {},
|
drafts: {},
|
||||||
images: {},
|
images: {},
|
||||||
sent: {},
|
sent: {},
|
||||||
|
sentAt: null,
|
||||||
stopping: null,
|
stopping: null,
|
||||||
afterBuild: null,
|
afterBuild: null,
|
||||||
homeward: null,
|
homeward: null,
|
||||||
@@ -890,14 +870,10 @@ function adopt(body) {
|
|||||||
chatFrame = body.chat || null;
|
chatFrame = body.chat || null;
|
||||||
if (body.workspace) wsFrame = body.workspace;
|
if (body.workspace) wsFrame = body.workspace;
|
||||||
if (body.meter) meterFrame = body.meter;
|
if (body.meter) meterFrame = body.meter;
|
||||||
// Always replaced: an absent key means no update.
|
|
||||||
updateFrame = body.update || null;
|
|
||||||
// Always replaced too: an older server sends none, and then there is no switch.
|
|
||||||
subagentsFrame = body.subagents || null;
|
|
||||||
lastContact = Date.now();
|
lastContact = Date.now();
|
||||||
if (gone) {
|
if (gone) {
|
||||||
gone = false;
|
gone = false;
|
||||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
banner(null);
|
||||||
}
|
}
|
||||||
if (firstLoad) {
|
if (firstLoad) {
|
||||||
load();
|
load();
|
||||||
@@ -1040,9 +1016,7 @@ function adopt(body) {
|
|||||||
render();
|
render();
|
||||||
if ($("workspace-modal").open) renderWorkspace();
|
if ($("workspace-modal").open) renderWorkspace();
|
||||||
tellFolderIssues();
|
tellFolderIssues();
|
||||||
// The Overview tab's file changes under a build, so a tab you are watching
|
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
|
||||||
// refetches on every new frame too, not only on the click that opened it.
|
|
||||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
|
|
||||||
if (announce) showArrival(announce);
|
if (announce) showArrival(announce);
|
||||||
// New entries land at the bottom of the rail. Gliding down to them beats
|
// New entries land at the bottom of the rail. Gliding down to them beats
|
||||||
// leaving the list parked where it was while it grew underneath.
|
// leaving the list parked where it was while it grew underneath.
|
||||||
@@ -1175,12 +1149,15 @@ function markGone() {
|
|||||||
// of the server means there, and a banner promising a reconnect would
|
// of the server means there, and a banner promising a reconnect would
|
||||||
// argue with it.
|
// argue with it.
|
||||||
if (!finish() && !stopInProgress()) {
|
if (!finish() && !stopInProgress()) {
|
||||||
banner(GONE_BANNER, "warn");
|
banner(
|
||||||
|
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
|
||||||
|
"warn"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
render();
|
render();
|
||||||
} else if (!bad && gone) {
|
} else if (!bad && gone) {
|
||||||
gone = false;
|
gone = false;
|
||||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
banner(null);
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1205,6 +1182,7 @@ function connect() {
|
|||||||
} catch {}
|
} catch {}
|
||||||
});
|
});
|
||||||
es.addEventListener("submitted", (e) => {
|
es.addEventListener("submitted", (e) => {
|
||||||
|
local.sentAt = Date.now();
|
||||||
// Drop only what was actually sent.
|
// Drop only what was actually sent.
|
||||||
//
|
//
|
||||||
// This event fires for a send from ANY tab of this session, which is why it
|
// This event fires for a send from ANY tab of this session, which is why it
|
||||||
@@ -1315,7 +1293,6 @@ function render() {
|
|||||||
renderChrome();
|
renderChrome();
|
||||||
renderStatus();
|
renderStatus();
|
||||||
renderBriefButton();
|
renderBriefButton();
|
||||||
renderSubagentsButton();
|
|
||||||
renderStopButton();
|
renderStopButton();
|
||||||
renderHomeButton();
|
renderHomeButton();
|
||||||
tabAdded = renderViews();
|
tabAdded = renderViews();
|
||||||
@@ -1581,7 +1558,7 @@ function renderChrome() {
|
|||||||
renderMeter();
|
renderMeter();
|
||||||
$("title").textContent = S.title || "Session";
|
$("title").textContent = S.title || "Session";
|
||||||
$("badge").textContent = workflowLabel(S.workflow);
|
$("badge").textContent = workflowLabel(S.workflow);
|
||||||
renderTabTitle();
|
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||||
|
|
||||||
const h = S.headline || {};
|
const h = S.headline || {};
|
||||||
// On a finished session an open item is frozen: the send on it counts as
|
// On a finished session an open item is frozen: the send on it counts as
|
||||||
@@ -1822,19 +1799,14 @@ async function sendBrief() {
|
|||||||
reply: briefPhrase(choice.range),
|
reply: briefPhrase(choice.range),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
|
||||||
if (!res.ok) throw new Error(String(res.status));
|
if (!res.ok) throw new Error(String(res.status));
|
||||||
$("brief-modal").close();
|
$("brief-modal").close();
|
||||||
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
||||||
setTimeout(() => banner(null), 5000);
|
setTimeout(() => banner(null), 5000);
|
||||||
pendingResult = true;
|
pendingResult = true;
|
||||||
render();
|
render();
|
||||||
} catch (err) {
|
} catch {
|
||||||
if (err && err.pending) pendingResult = true;
|
why.textContent = "That did not go through. Try again in a moment.";
|
||||||
why.textContent =
|
|
||||||
err && err.pending
|
|
||||||
? "Your last answers are still being picked up. Try again in a moment."
|
|
||||||
: "That did not go through. Try again in a moment.";
|
|
||||||
} finally {
|
} finally {
|
||||||
go.disabled = false;
|
go.disabled = false;
|
||||||
go.textContent = "Write the brief";
|
go.textContent = "Write the brief";
|
||||||
@@ -1850,77 +1822,11 @@ function renderBriefButton() {
|
|||||||
if (offer) btn.disabled = gone || pendingResult;
|
if (offer) btn.disabled = gone || pendingResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shown only where the skill opts in and the agent's console copy can deliver
|
|
||||||
// it. Lit while helpers are on; a click opens the dialog, never toggles.
|
|
||||||
function renderSubagentsButton() {
|
|
||||||
const btn = $("btn-subagents");
|
|
||||||
const offer = showSwitch(subagentsFrame);
|
|
||||||
btn.hidden = !offer;
|
|
||||||
if (!offer) return;
|
|
||||||
const label = switchLabel(subagentsFrame);
|
|
||||||
btn.setAttribute("aria-pressed", String(Boolean(subagentsFrame.on)));
|
|
||||||
btn.title = label;
|
|
||||||
btn.setAttribute("aria-label", label);
|
|
||||||
btn.disabled = gone;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
|
||||||
// instruction is the shipped default, shown as its text so it can be edited.
|
|
||||||
function openSubagents() {
|
|
||||||
if (!showSwitch(subagentsFrame)) return;
|
|
||||||
const on = Boolean(subagentsFrame.on);
|
|
||||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
|
|
||||||
radio.checked = radio.value === (on ? "on" : "off");
|
|
||||||
}
|
|
||||||
$("subagents-instruction").value = subagentsFrame.instruction ?? defaultInstruction(S.workflow);
|
|
||||||
$("subagents-max").value = String(subagentsFrame.max);
|
|
||||||
$("subagents-checkin").textContent = CHECKIN_LINE;
|
|
||||||
const research = $("subagents-research");
|
|
||||||
research.textContent = PATHFINDER_RESEARCH_LINE;
|
|
||||||
research.hidden = S.workflow !== "pathfinder";
|
|
||||||
$("subagents-status").textContent = "";
|
|
||||||
$("subagents-save").disabled = false;
|
|
||||||
$("subagents-modal").showModal();
|
|
||||||
const checked = document.querySelector('input[name="subagents-on"]:checked');
|
|
||||||
if (checked) checked.focus();
|
|
||||||
}
|
|
||||||
|
|
||||||
const SUBAGENTS_ERRORS = {
|
|
||||||
max: "Pick a number from 1 to 20.",
|
|
||||||
"too-long": "The instruction is over 2,000 characters.",
|
|
||||||
"not-offered": "This skill doesn't use helpers.",
|
|
||||||
bad: "That didn't save. Try again.",
|
|
||||||
};
|
|
||||||
const SUBAGENTS_LOST = "Lost contact with Plan2Code. Try again once it's back.";
|
|
||||||
|
|
||||||
async function saveSubagents() {
|
|
||||||
const save = $("subagents-save");
|
|
||||||
const status = $("subagents-status");
|
|
||||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
|
||||||
const text = $("subagents-instruction").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(S.workflow) ? null : text;
|
|
||||||
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
|
|
||||||
save.disabled = true;
|
|
||||||
status.textContent = "";
|
|
||||||
const res = await postJson("/subagents", body);
|
|
||||||
save.disabled = false;
|
|
||||||
// The next state frame redraws the button.
|
|
||||||
if (res.status === 200) return $("subagents-modal").close();
|
|
||||||
if (res.status === 400) status.textContent = SUBAGENTS_ERRORS[res.body && res.body.error] || SUBAGENTS_ERRORS.bad;
|
|
||||||
else if (res.status === 403 || res.status === 0) status.textContent = SUBAGENTS_LOST;
|
|
||||||
else status.textContent = SUBAGENTS_ERRORS.bad;
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderViews() {
|
function renderViews() {
|
||||||
const nav = $("views");
|
const nav = $("views");
|
||||||
nav.replaceChildren();
|
nav.replaceChildren();
|
||||||
// Sent and not yet picked up: the same ring as Ask, until Plan2Code moves on
|
|
||||||
// or goes quiet (a turning ring would pass a dead session for a slow one).
|
|
||||||
const sentBusy = pendingResult && !gone && !agentAdrift();
|
|
||||||
const tabs = [
|
const tabs = [
|
||||||
{ id: "questions", label: isDashboard() ? "Dashboard" : "Questions", count: myTurn().length, busy: sentBusy },
|
{ id: "questions", label: isDashboard() ? "Dashboard" : "Questions", count: myTurn().length },
|
||||||
];
|
];
|
||||||
// Built in rather than posted: present exactly while the spec in view has
|
// Built in rather than posted: present exactly while the spec in view has
|
||||||
// an overview.md. A tab that vanishes under the person sends them home.
|
// an overview.md. A tab that vanishes under the person sends them home.
|
||||||
@@ -1928,30 +1834,12 @@ function renderViews() {
|
|||||||
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
||||||
else if (view === "overview") view = "questions";
|
else if (view === "overview") view = "questions";
|
||||||
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
||||||
// The helpers the agent reported, from the first one on; cleared by a
|
|
||||||
// dashboard hop, which sends the person home like the Overview tab does.
|
|
||||||
if (showTab(subagentsFrame, S.helpers)) {
|
|
||||||
// From the rows the tab draws, so the badge never counts helpers the
|
|
||||||
// working-alone note hides.
|
|
||||||
const running = helperRows(S.helpers).rows.filter((r) => r.state === "running").length;
|
|
||||||
tabs.push({ id: "subagents", label: "Subagents", count: running });
|
|
||||||
} else if (view === "subagents") view = "questions";
|
|
||||||
// Always last, on every workflow and after a finish: the Quick question chat.
|
// Always last, on every workflow and after a finish: the Quick question chat.
|
||||||
// The ring left of "Ask" shows exactly when the conversation's own ring does:
|
tabs.push({ id: "ask", label: "Ask", count: 0, dot: chatDot });
|
||||||
// a question the agent picked up and has not answered yet.
|
|
||||||
const ask = askState();
|
|
||||||
const askBusy = ask.view.rows.some((r) => r.working) && ask.send.state !== "offline" && !agentAdrift();
|
|
||||||
tabs.push({ id: "ask", label: "Ask", count: 0, dot: chatDot, busy: askBusy });
|
|
||||||
|
|
||||||
for (const t of tabs) {
|
for (const t of tabs) {
|
||||||
const b = el("button", "view-tab", t.label);
|
const b = el("button", "view-tab", t.label);
|
||||||
b.type = "button";
|
b.type = "button";
|
||||||
if (t.busy) {
|
|
||||||
const spin = el("span", "spinner tiny tab-spin");
|
|
||||||
spin.setAttribute("aria-hidden", "true");
|
|
||||||
b.prepend(spin);
|
|
||||||
b.title = t.id === "ask" ? "Plan2Code is working on an answer" : "Sent. Waiting for Plan2Code";
|
|
||||||
}
|
|
||||||
b.setAttribute("aria-current", String(view === t.id || (t.id === "questions" && view === "end")));
|
b.setAttribute("aria-current", String(view === t.id || (t.id === "questions" && view === "end")));
|
||||||
if (t.count) {
|
if (t.count) {
|
||||||
const c = el("span", "tab-count", String(t.count));
|
const c = el("span", "tab-count", String(t.count));
|
||||||
@@ -2216,7 +2104,6 @@ function paintMain(main) {
|
|||||||
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
|
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
|
||||||
if (view === "overview") return renderOverview(main);
|
if (view === "overview") return renderOverview(main);
|
||||||
if (view === "ask") return renderAsk(main);
|
if (view === "ask") return renderAsk(main);
|
||||||
if (view === "subagents") return renderSubagents(main);
|
|
||||||
|
|
||||||
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
||||||
// the top of the rail. The hand-off lives here alone now, rather than
|
// the top of the rail. The hand-off lives here alone now, rather than
|
||||||
@@ -2615,51 +2502,6 @@ function roleNudge() {
|
|||||||
return nudge;
|
return nudge;
|
||||||
}
|
}
|
||||||
|
|
||||||
// × on the update banner hides it for this console session only, and only
|
|
||||||
// for the release it named. Blocked storage means "not dismissed".
|
|
||||||
function updateDismissKey() {
|
|
||||||
try {
|
|
||||||
return "p2c-update-dismissed:" + S.sid;
|
|
||||||
} catch {
|
|
||||||
return "p2c-update-dismissed:";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateDismissed() {
|
|
||||||
try {
|
|
||||||
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
|
||||||
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
|
|
||||||
|
|
||||||
function releasesLink(text) {
|
|
||||||
const a = el("a", null, text);
|
|
||||||
a.href = RELEASES_URL;
|
|
||||||
a.target = "_blank";
|
|
||||||
a.rel = "noopener noreferrer";
|
|
||||||
return a;
|
|
||||||
}
|
|
||||||
|
|
||||||
function openUpdateModal() {
|
|
||||||
if (!updateFrame) return;
|
|
||||||
const versions = $("update-versions");
|
|
||||||
versions.replaceChildren(
|
|
||||||
document.createTextNode("Version "),
|
|
||||||
releasesLink("v" + updateFrame.latest),
|
|
||||||
document.createTextNode(" is out — you have "),
|
|
||||||
el("code", null, updateFrame.installed),
|
|
||||||
document.createTextNode(".")
|
|
||||||
);
|
|
||||||
const row = $("update-command");
|
|
||||||
const code = el("code", null, UPDATE_COMMAND);
|
|
||||||
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
|
|
||||||
$("update-modal").showModal();
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderDashboard(main) {
|
function renderDashboard(main) {
|
||||||
maybeWake();
|
maybeWake();
|
||||||
const menu = (S && S.menu) || {};
|
const menu = (S && S.menu) || {};
|
||||||
@@ -2671,25 +2513,6 @@ function renderDashboard(main) {
|
|||||||
warn.setAttribute("role", "status");
|
warn.setAttribute("role", "status");
|
||||||
wrap.appendChild(warn);
|
wrap.appendChild(warn);
|
||||||
}
|
}
|
||||||
// Built here only, so no other workflow's page ever shows it.
|
|
||||||
if (updateFrame && !updateDismissed()) {
|
|
||||||
const notice = el("div", "dash-nudge update-banner");
|
|
||||||
notice.setAttribute("role", "status");
|
|
||||||
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
|
|
||||||
open.type = "button";
|
|
||||||
open.addEventListener("click", openUpdateModal);
|
|
||||||
const dismiss = el("button", "update-banner-dismiss", "×");
|
|
||||||
dismiss.type = "button";
|
|
||||||
dismiss.setAttribute("aria-label", "Dismiss until next time");
|
|
||||||
dismiss.addEventListener("click", () => {
|
|
||||||
try {
|
|
||||||
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
|
|
||||||
} catch {}
|
|
||||||
render();
|
|
||||||
});
|
|
||||||
notice.append(open, dismiss);
|
|
||||||
wrap.appendChild(notice);
|
|
||||||
}
|
|
||||||
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
||||||
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
||||||
if (typeof menu.note === "string" && menu.note.trim()) {
|
if (typeof menu.note === "string" && menu.note.trim()) {
|
||||||
@@ -2719,7 +2542,6 @@ function renderDashboard(main) {
|
|||||||
const specs = specList();
|
const specs = specList();
|
||||||
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
|
if (specs.length) wrap.appendChild(renderSpecPicker(specs));
|
||||||
wrap.appendChild(hideUnavailableToggle());
|
wrap.appendChild(hideUnavailableToggle());
|
||||||
if (!local.launching && !launchScoping) syncWorkspaceScope();
|
|
||||||
|
|
||||||
// "Unavailable" is the scan's verdict for the selected spec, not the
|
// "Unavailable" is the scan's verdict for the selected spec, not the
|
||||||
// momentary greying while a launch is in flight or the server is away, so
|
// momentary greying while a launch is in flight or the server is away, so
|
||||||
@@ -3141,11 +2963,6 @@ async function launchSkill(entry) {
|
|||||||
// cards that take no spec (utilities, setup) launch untargeted even while
|
// cards that take no spec (utilities, setup) launch untargeted even while
|
||||||
// a spec is selected.
|
// a spec is selected.
|
||||||
if (target) action.spec = target.dir;
|
if (target) action.spec = target.dir;
|
||||||
// The skill opens on the folders remembered for what it was launched for.
|
|
||||||
// Held until the launch is in flight: the swap's own frame re-renders the
|
|
||||||
// dashboard, which would otherwise sync back to the picker's spec.
|
|
||||||
launchScoping = true;
|
|
||||||
await syncWorkspaceScope(target ? target.dir : "");
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/submit", {
|
const res = await fetch("/submit", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -3156,7 +2973,6 @@ async function launchSkill(entry) {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (res.status === 409) {
|
if (res.status === 409) {
|
||||||
launchScoping = false;
|
|
||||||
pendingResult = true;
|
pendingResult = true;
|
||||||
banner("Your last pick is still being picked up. One moment.", "info");
|
banner("Your last pick is still being picked up. One moment.", "info");
|
||||||
return;
|
return;
|
||||||
@@ -3164,12 +2980,10 @@ async function launchSkill(entry) {
|
|||||||
if (!res.ok) throw new Error(String(res.status));
|
if (!res.ok) throw new Error(String(res.status));
|
||||||
sound("startSkill");
|
sound("startSkill");
|
||||||
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
|
local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
|
||||||
launchScoping = false;
|
|
||||||
pendingResult = true;
|
pendingResult = true;
|
||||||
save();
|
save();
|
||||||
render();
|
render();
|
||||||
} catch {
|
} catch {
|
||||||
launchScoping = false;
|
|
||||||
banner("That did not go through. Nothing was lost; try again.", "warn");
|
banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3387,11 +3201,7 @@ document.addEventListener("keydown", cancelSkipMove, true);
|
|||||||
function skipAndMoveOn(id) {
|
function skipAndMoveOn(id) {
|
||||||
cancelSkipMove();
|
cancelSkipMove();
|
||||||
local.skipFlash = id;
|
local.skipFlash = id;
|
||||||
// A note already typed goes along: skipping the question is not retracting
|
stage(id, { type: "skip", skipped: true });
|
||||||
// the comment. Dropping it would leave the text in the box but out of the
|
|
||||||
// send, which looks kept and is not.
|
|
||||||
const cur = local.staged[id];
|
|
||||||
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
|
|
||||||
skipTimer = setTimeout(() => {
|
skipTimer = setTimeout(() => {
|
||||||
skipTimer = null;
|
skipTimer = null;
|
||||||
local.skipFlash = null;
|
local.skipFlash = null;
|
||||||
@@ -3508,41 +3318,15 @@ function renderWaiting(main) {
|
|||||||
}
|
}
|
||||||
pane.appendChild(title);
|
pane.appendChild(title);
|
||||||
pane.appendChild(el("p", null, doing));
|
pane.appendChild(el("p", null, doing));
|
||||||
const ask = "If Plan2Code needs you, the question appears here on its own.";
|
pane.appendChild(
|
||||||
if (!docs().length) {
|
el(
|
||||||
pane.appendChild(el("p", null, ask));
|
"p",
|
||||||
return;
|
null,
|
||||||
}
|
docs().length
|
||||||
// "Task" and the tasks tab's own name both open that tab, so the pointer is
|
? "The tabs above fill in as it goes. You can follow along with live `Task` updates in the `Phase tasks` tab. If Plan2Code needs you, the question appears here on its own."
|
||||||
// one click from what it points at. A build posts it as `phase` ("Phase N
|
: "If Plan2Code needs you, the question appears here on its own."
|
||||||
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
|
)
|
||||||
// Plan) has nothing live to follow, so it gets no pointer at all.
|
|
||||||
const list =
|
|
||||||
docs().find((d) => d.id === "phase") ||
|
|
||||||
docs().find((d) => d.id === "tasks") ||
|
|
||||||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
|
|
||||||
if (!list) {
|
|
||||||
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const jump = (word) => {
|
|
||||||
const b = el("button", "waiting-jump", word);
|
|
||||||
b.type = "button";
|
|
||||||
b.addEventListener("click", () => {
|
|
||||||
view = "doc:" + list.id;
|
|
||||||
render();
|
|
||||||
});
|
|
||||||
return b;
|
|
||||||
};
|
|
||||||
const p = el("p");
|
|
||||||
p.append(
|
|
||||||
"The tabs above fill in as it goes. You can follow along with live ",
|
|
||||||
jump("Task"),
|
|
||||||
" updates in the ",
|
|
||||||
jump(list.title || "Phase tasks"),
|
|
||||||
" tab. " + ask
|
|
||||||
);
|
);
|
||||||
pane.appendChild(p);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// A notice is context for the question it sits beside, so it lives inside the
|
// A notice is context for the question it sits beside, so it lives inside the
|
||||||
@@ -3678,8 +3462,8 @@ function renderSettled(card, item) {
|
|||||||
// would misreport which of the two was the answer.
|
// would misreport which of the two was the answer.
|
||||||
let prose = text;
|
let prose = text;
|
||||||
if (!prose && !lines.length) {
|
if (!prose && !lines.length) {
|
||||||
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
|
const mine = (item.thread || []).filter((m) => m.who === "user");
|
||||||
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
|
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
const nothing = !lines.length && !prose;
|
const nothing = !lines.length && !prose;
|
||||||
@@ -4495,10 +4279,6 @@ function buildChecklist(card, item, staged) {
|
|||||||
const commitList = (change) => {
|
const commitList = (change) => {
|
||||||
const cur = local.staged[item.id];
|
const cur = local.staged[item.id];
|
||||||
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
|
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
|
||||||
// A tick or a state IS the answer, so it ends a skip staged earlier:
|
|
||||||
// left in place, `skipped` would collapse the reply to "skip" while the
|
|
||||||
// card showed ticked steps on their way.
|
|
||||||
delete next.skipped;
|
|
||||||
const empty = !(next.done && next.done.length) && !next.state && !next.text;
|
const empty = !(next.done && next.done.length) && !next.state && !next.text;
|
||||||
stage(item.id, empty ? null : next);
|
stage(item.id, empty ? null : next);
|
||||||
};
|
};
|
||||||
@@ -4548,7 +4328,7 @@ function buildChecklist(card, item, staged) {
|
|||||||
function buildMenu(card, item, staged) {
|
function buildMenu(card, item, staged) {
|
||||||
const list = el("ul", "options");
|
const list = el("ul", "options");
|
||||||
const name = "menu-" + item.id;
|
const name = "menu-" + item.id;
|
||||||
for (const [i, o] of (item.options || []).entries()) {
|
for (const o of item.options || []) {
|
||||||
const picked = staged && staged.k === o.k;
|
const picked = staged && staged.k === o.k;
|
||||||
const li = el("li", "option" + (picked ? " is-picked" : ""));
|
const li = el("li", "option" + (picked ? " is-picked" : ""));
|
||||||
const label = el("label");
|
const label = el("label");
|
||||||
@@ -4556,13 +4336,7 @@ function buildMenu(card, item, staged) {
|
|||||||
const radio = el("input");
|
const radio = el("input");
|
||||||
radio.type = "radio";
|
radio.type = "radio";
|
||||||
radio.name = name;
|
radio.name = name;
|
||||||
// The same id buildChoice gives its radios: withFocus finds the focused
|
|
||||||
// input by id after the render this change() sets off, and without one a
|
|
||||||
// keyboard user arrowing through the menu lands on <body> every time.
|
|
||||||
radio.id = optionId(item, o, i);
|
|
||||||
radio.value = o.k;
|
|
||||||
radio.checked = Boolean(picked);
|
radio.checked = Boolean(picked);
|
||||||
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
|
|
||||||
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
|
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
|
||||||
const body = el("div", "option-body");
|
const body = el("div", "option-body");
|
||||||
const head = el("div", "option-label");
|
const head = el("div", "option-label");
|
||||||
@@ -4861,42 +4635,6 @@ function renderOverview(main) {
|
|||||||
main.appendChild(box);
|
main.appendChild(box);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The helpers the agent reported, as it last posted them. Everything here is
|
|
||||||
// the agent's text, so it goes in as text, never as markup.
|
|
||||||
function renderSubagents(main) {
|
|
||||||
const card = el("section", "card sa-card");
|
|
||||||
card.appendChild(el("h2", null, "Subagents"));
|
|
||||||
card.appendChild(el("p", "help", CHECKIN_LINE));
|
|
||||||
const { alone, rows } = helperRows(S.helpers);
|
|
||||||
if (alone) {
|
|
||||||
card.appendChild(
|
|
||||||
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
|
|
||||||
);
|
|
||||||
main.appendChild(card);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const list = el("ul", "sa-list");
|
|
||||||
for (const row of rows) {
|
|
||||||
const item = el("li", "sa-row");
|
|
||||||
const head = el("div", "sa-head");
|
|
||||||
head.appendChild(el("strong", "sa-title", row.title));
|
|
||||||
const pill = el("span", "pill sa-pill is-" + row.state);
|
|
||||||
if (row.state === "running") {
|
|
||||||
const spin = el("span", "spinner tiny");
|
|
||||||
spin.setAttribute("aria-hidden", "true");
|
|
||||||
pill.appendChild(spin);
|
|
||||||
}
|
|
||||||
pill.appendChild(document.createTextNode(row.stateLabel));
|
|
||||||
head.appendChild(pill);
|
|
||||||
item.appendChild(head);
|
|
||||||
item.appendChild(el("p", "sa-ask", row.ask));
|
|
||||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
|
||||||
list.appendChild(item);
|
|
||||||
}
|
|
||||||
card.appendChild(list);
|
|
||||||
main.appendChild(card);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---------------------------------------------------------------- ask */
|
/* ---------------------------------------------------------------- ask */
|
||||||
|
|
||||||
// The frame's chat block, with `offline` worked out now rather than when the
|
// The frame's chat block, with `offline` worked out now rather than when the
|
||||||
@@ -5495,30 +5233,20 @@ function renderAside() {
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// A note that has been sent but not yet picked up: marked as waiting, so the
|
|
||||||
// send is seen to have gone, until the agent replies. The server writes the
|
|
||||||
// note into the thread as it arrives; a session from before that has only
|
|
||||||
// `sentNote`, which gets a box of its own below.
|
|
||||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
|
||||||
let waitingShown = false;
|
|
||||||
for (const m of thread) {
|
for (const m of thread) {
|
||||||
const mine = threadWho(m) === "user";
|
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
|
||||||
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
|
|
||||||
if (pending) waitingShown = true;
|
|
||||||
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
|
|
||||||
const who = el("div", "msg-who");
|
const who = el("div", "msg-who");
|
||||||
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
|
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
|
||||||
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
|
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||||
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
|
||||||
box.appendChild(who);
|
box.appendChild(who);
|
||||||
const text = threadText(m);
|
box.appendChild(md(m.text, "md"));
|
||||||
if (text) box.appendChild(md(text, "md"));
|
|
||||||
const tray = mine ? sentAttachments(m) : null;
|
|
||||||
if (tray) box.appendChild(tray);
|
|
||||||
aside.appendChild(box);
|
aside.appendChild(box);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (waiting && !waitingShown) {
|
// A note that has been sent but not yet picked up: shown at once, so the
|
||||||
|
// send is seen to have gone, and gone when the agent replies.
|
||||||
|
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||||
|
if (waiting) {
|
||||||
const box = el("div", "msg you pending");
|
const box = el("div", "msg you pending");
|
||||||
const who = el("div", "msg-who");
|
const who = el("div", "msg-who");
|
||||||
who.appendChild(el("span", null, "You"));
|
who.appendChild(el("span", null, "You"));
|
||||||
@@ -5818,10 +5546,7 @@ async function attachFiles(itemId, files) {
|
|||||||
const taken = wanted.slice(0, room);
|
const taken = wanted.slice(0, room);
|
||||||
// One banner at a time, so every refusal goes into it, each by name.
|
// One banner at a time, so every refusal goes into it, each by name.
|
||||||
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
|
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
|
||||||
if (taken.length < wanted.length)
|
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
|
||||||
said.push(
|
|
||||||
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
|
|
||||||
);
|
|
||||||
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
|
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
taken.map(async (file) => {
|
taken.map(async (file) => {
|
||||||
@@ -5924,19 +5649,6 @@ function sendState() {
|
|||||||
: { disabled: true, why: "Your last answers are on their way. One moment.", short: "" };
|
: { disabled: true, why: "Your last answers are on their way. One moment.", short: "" };
|
||||||
}
|
}
|
||||||
if (agentWorking()) {
|
if (agentWorking()) {
|
||||||
// A question the agent left open while still working is still a question,
|
|
||||||
// and its answer has nowhere better to wait than the server, which holds
|
|
||||||
// a send until the agent next looks. The contract says to switch to
|
|
||||||
// "waiting" before asking, but an agent that asks and carries on ("while
|
|
||||||
// you decide") must not lock the person out of answering for up to an
|
|
||||||
// hour of quietMinutes.
|
|
||||||
if (myTurn().length && (stagedCount() || pendingNotes().length)) {
|
|
||||||
return {
|
|
||||||
disabled: false,
|
|
||||||
why: "Plan2Code is still working. Your answers wait for it to look.",
|
|
||||||
short: "Still working · it reads this next",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const ms = workingMs();
|
const ms = workingMs();
|
||||||
if (ms > patience(WORKING_GRACE_MS)) {
|
if (ms > patience(WORKING_GRACE_MS)) {
|
||||||
// A stuck agent must not lock someone out of their own session, so the
|
// A stuck agent must not lock someone out of their own session, so the
|
||||||
@@ -6079,30 +5791,10 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
|
|||||||
// session opened before the server wrote `worktree` has nothing to show, so
|
// session opened before the server wrote `worktree` has nothing to show, so
|
||||||
// the slot stays hidden. The footer renders on every tick, so the DOM is only
|
// the slot stays hidden. The footer renders on every tick, so the DOM is only
|
||||||
// touched when the labels change, or when a resize clears the key.
|
// touched when the labels change, or when a resize clears the key.
|
||||||
// The project's name: the workspace's original folder, or the session's
|
|
||||||
// worktree folder before a frame carries the workspace.
|
|
||||||
function projectName() {
|
|
||||||
const folders = workspaceFolders();
|
|
||||||
if (folders.length && folders[0].name) return folders[0].name;
|
|
||||||
const path = (S && S.worktree) || "";
|
|
||||||
return path ? path.split(/[\\/]/).filter(Boolean).pop() || path : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// The browser tab's title, led by the project so tabs from different
|
|
||||||
// projects are told apart. Called from the chrome and the footer, since the
|
|
||||||
// workspace frame can arrive after either.
|
|
||||||
function renderTabTitle() {
|
|
||||||
if (!S) return;
|
|
||||||
const name = projectName();
|
|
||||||
document.title =
|
|
||||||
(name ? name + " · " : "") + (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderWhere() {
|
function renderWhere() {
|
||||||
const b = $("footer-where");
|
const b = $("footer-where");
|
||||||
const folders = workspaceFolders();
|
const folders = workspaceFolders();
|
||||||
const path = S.worktree || "";
|
const path = S.worktree || "";
|
||||||
renderTabTitle();
|
|
||||||
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
|
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
|
||||||
const labels = folders.length
|
const labels = folders.length
|
||||||
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
|
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
|
||||||
@@ -6115,16 +5807,7 @@ function renderWhere() {
|
|||||||
let label = labels[0];
|
let label = labels[0];
|
||||||
for (const text of labels) {
|
for (const text of labels) {
|
||||||
label = text;
|
label = text;
|
||||||
// The project name takes the highlight color, so several consoles side by
|
|
||||||
// side tell apart at a glance; the rest of the label stays quiet.
|
|
||||||
const name = projectName();
|
|
||||||
b.textContent = "";
|
|
||||||
if (name && text.startsWith(name)) {
|
|
||||||
b.appendChild(el("span", "where-project", name));
|
|
||||||
b.appendChild(document.createTextNode(text.slice(name.length)));
|
|
||||||
} else {
|
|
||||||
b.textContent = text;
|
b.textContent = text;
|
||||||
}
|
|
||||||
if (alert) {
|
if (alert) {
|
||||||
const dot = el("span", "where-alert");
|
const dot = el("span", "where-alert");
|
||||||
dot.setAttribute("aria-hidden", "true");
|
dot.setAttribute("aria-hidden", "true");
|
||||||
@@ -6171,32 +5854,6 @@ async function postJson(url, body) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The workspace follows the dashboard's picker: the folders remembered for
|
|
||||||
the selected spec, or the project's own under "Start from scratch". The
|
|
||||||
server swaps the list and remembers every change after it. */
|
|
||||||
let scopeAsked = null;
|
|
||||||
// True from a launch's scope sync until its send has gone (or failed).
|
|
||||||
let launchScoping = false;
|
|
||||||
async function syncWorkspaceScope(spec) {
|
|
||||||
if (!S || S.workflow !== "dashboard" || gone || !wsFrame) return;
|
|
||||||
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
|
|
||||||
if ((wsFrame.scope || "") === want || scopeAsked === want) return;
|
|
||||||
scopeAsked = want;
|
|
||||||
const { status, body } = await postJson("/workspace/scope", { spec: want });
|
|
||||||
if (status === 200 && body && Array.isArray(body.folders)) wsFrame = { ...wsFrame, ...body };
|
|
||||||
scopeAsked = null;
|
|
||||||
if ($("workspace-modal").open) renderWorkspace();
|
|
||||||
}
|
|
||||||
|
|
||||||
// The dialog's "Remembered for" line: whose list this is.
|
|
||||||
function workspaceScopeText() {
|
|
||||||
const scope = (wsFrame && wsFrame.scope) || "";
|
|
||||||
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
|
|
||||||
const spec = specList().find((s) => s.dir === scope);
|
|
||||||
const name = spec ? spec.name : scope.split("/").pop();
|
|
||||||
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
|
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
|
||||||
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
|
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
|
||||||
// The folder whose Remove is waiting on its inline confirm, by id.
|
// The folder whose Remove is waiting on its inline confirm, by id.
|
||||||
@@ -6236,7 +5893,6 @@ function renderWorkspace() {
|
|||||||
}
|
}
|
||||||
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
|
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
|
||||||
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
|
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
|
||||||
$("workspace-scope").textContent = workspaceScopeText();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function workspaceRow(f) {
|
function workspaceRow(f) {
|
||||||
@@ -6700,10 +6356,6 @@ async function goHome() {
|
|||||||
$("home-modal").close();
|
$("home-modal").close();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
$("home-modal").close();
|
$("home-modal").close();
|
||||||
// The server is holding an uncollected result: Send, Home and Stop all
|
|
||||||
// need to read as busy until the frame or the ping says otherwise, same
|
|
||||||
// as send() and sendAfterBuild() do on a 409.
|
|
||||||
if (err && err.pending) pendingResult = true;
|
|
||||||
banner(
|
banner(
|
||||||
err && err.pending
|
err && err.pending
|
||||||
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
||||||
@@ -6764,7 +6416,6 @@ async function stopSession() {
|
|||||||
stoppingHidden = false;
|
stoppingHidden = false;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
$("stop-modal").close();
|
$("stop-modal").close();
|
||||||
if (err && err.pending) pendingResult = true;
|
|
||||||
banner(
|
banner(
|
||||||
err && err.pending
|
err && err.pending
|
||||||
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
||||||
@@ -6919,6 +6570,7 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
|
|||||||
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
|
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
|
||||||
}
|
}
|
||||||
local.staged = {};
|
local.staged = {};
|
||||||
|
local.sentAt = Date.now();
|
||||||
save();
|
save();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6971,7 +6623,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
|
|||||||
// something the agent never hears.
|
// something the agent never hears.
|
||||||
function tokenFor(item, v) {
|
function tokenFor(item, v) {
|
||||||
const map = item.token || {};
|
const map = item.token || {};
|
||||||
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
|
if (v.skipped) return "skip";
|
||||||
const parts = [];
|
const parts = [];
|
||||||
if (v.k) parts.push(map[v.k] || v.k);
|
if (v.k) parts.push(map[v.k] || v.k);
|
||||||
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
|
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
|
||||||
@@ -7203,14 +6855,14 @@ function renderAbout() {
|
|||||||
let helpBuilt = false;
|
let helpBuilt = false;
|
||||||
|
|
||||||
async function renderHelpVersion() {
|
async function renderHelpVersion() {
|
||||||
const slot = $("help-version");
|
const el = $("help-version");
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/version", { cache: "no-store" });
|
const res = await fetch("/version", { cache: "no-store" });
|
||||||
const { version } = res.ok ? await res.json() : {};
|
const { version } = res.ok ? await res.json() : {};
|
||||||
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
|
el.textContent = version ? "Plan2Code v" + version : "";
|
||||||
slot.hidden = !version;
|
el.hidden = !version;
|
||||||
} catch {
|
} catch {
|
||||||
slot.hidden = true;
|
el.hidden = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -7318,7 +6970,6 @@ function openHelpOn(id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$("btn-home").addEventListener("click", openHomeConfirm);
|
$("btn-home").addEventListener("click", openHomeConfirm);
|
||||||
$("update-done").addEventListener("click", () => $("update-modal").close());
|
|
||||||
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
||||||
$("home-go").addEventListener("click", goHome);
|
$("home-go").addEventListener("click", goHome);
|
||||||
$("btn-stop").addEventListener("click", openStopConfirm);
|
$("btn-stop").addEventListener("click", openStopConfirm);
|
||||||
@@ -7349,7 +7000,6 @@ function lightDismiss(dlg) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
lightDismiss($("looks-modal"));
|
lightDismiss($("looks-modal"));
|
||||||
lightDismiss($("subagents-modal"));
|
|
||||||
lightDismiss($("help-modal"));
|
lightDismiss($("help-modal"));
|
||||||
lightDismiss($("workspace-modal"));
|
lightDismiss($("workspace-modal"));
|
||||||
lightDismiss($("welcome-modal"));
|
lightDismiss($("welcome-modal"));
|
||||||
@@ -7399,7 +7049,6 @@ $("btn-looks").addEventListener("click", () => {
|
|||||||
});
|
});
|
||||||
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
||||||
$("looks-modal").addEventListener("close", () => {
|
$("looks-modal").addEventListener("close", () => {
|
||||||
resetCleanup();
|
|
||||||
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
|
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
|
||||||
});
|
});
|
||||||
$("looks-reset").addEventListener("click", () => {
|
$("looks-reset").addEventListener("click", () => {
|
||||||
@@ -7546,119 +7195,7 @@ $("models-reset").addEventListener("click", () => {
|
|||||||
renderModels();
|
renderModels();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Cleanup: the server works out what in ~/.plan2code is not needed and
|
|
||||||
// shows it first; Delete these sends back only the ids it was shown, and the
|
|
||||||
// server re-checks every one before removing it.
|
|
||||||
let cleanupFound = null;
|
|
||||||
// Bumped by every scan, delete and reset: a response from an older one is
|
|
||||||
// dropped, so a scan still in flight when Preferences closes cannot refill it.
|
|
||||||
let cleanupGen = 0;
|
|
||||||
const CLEANUP_SHOWN = 8;
|
|
||||||
|
|
||||||
function setCleanupStatus(text, isError) {
|
|
||||||
const status = $("cleanup-status");
|
|
||||||
status.textContent = text;
|
|
||||||
status.classList.toggle("error", Boolean(isError));
|
|
||||||
}
|
|
||||||
|
|
||||||
function cleanupLabel(item) {
|
|
||||||
if (item.where === "session") return "Session " + item.name;
|
|
||||||
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
|
|
||||||
return where + item.name + (item.kind === "folder" ? "/" : "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function cleanupSummary(items, bytes) {
|
|
||||||
const sessions = items.filter((i) => i.where === "session").length;
|
|
||||||
const strays = items.length - sessions;
|
|
||||||
const parts = [];
|
|
||||||
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
|
|
||||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
|
||||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resetCleanup() {
|
|
||||||
cleanupGen++;
|
|
||||||
cleanupFound = null;
|
|
||||||
$("cleanup-list").replaceChildren();
|
|
||||||
$("cleanup-delete").hidden = true;
|
|
||||||
$("cleanup-delete").disabled = false;
|
|
||||||
$("cleanup-scan").disabled = false;
|
|
||||||
setCleanupStatus("", false);
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderCleanup() {
|
|
||||||
const list = $("cleanup-list");
|
|
||||||
list.replaceChildren();
|
|
||||||
const items = (cleanupFound && cleanupFound.items) || [];
|
|
||||||
$("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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function scanCleanup() {
|
|
||||||
const gen = ++cleanupGen;
|
|
||||||
$("cleanup-scan").disabled = true;
|
|
||||||
$("cleanup-delete").disabled = true;
|
|
||||||
setCleanupStatus("Looking…", false);
|
|
||||||
const { status, body } = await postJson("/cleanup", { scan: true });
|
|
||||||
if (gen !== cleanupGen) return;
|
|
||||||
$("cleanup-scan").disabled = false;
|
|
||||||
$("cleanup-delete").disabled = false;
|
|
||||||
if (status !== 200 || !body.ok) {
|
|
||||||
cleanupFound = null;
|
|
||||||
renderCleanup();
|
|
||||||
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
|
|
||||||
}
|
|
||||||
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function deleteCleanup() {
|
|
||||||
if (!cleanupFound || !cleanupFound.items.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) });
|
|
||||||
if (gen !== cleanupGen) return;
|
|
||||||
$("cleanup-delete").disabled = false;
|
|
||||||
$("cleanup-scan").disabled = false;
|
|
||||||
if (status !== 200 || !body.ok) {
|
|
||||||
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
|
|
||||||
}
|
|
||||||
const removed = (body.removed || []).length;
|
|
||||||
const failed = (body.failed || []).length;
|
|
||||||
cleanupFound = null;
|
|
||||||
renderCleanup();
|
|
||||||
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
|
|
||||||
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
|
|
||||||
}
|
|
||||||
|
|
||||||
$("cleanup-scan").addEventListener("click", scanCleanup);
|
|
||||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
|
||||||
|
|
||||||
$("btn-brief").addEventListener("click", openBrief);
|
$("btn-brief").addEventListener("click", openBrief);
|
||||||
$("btn-subagents").addEventListener("click", openSubagents);
|
|
||||||
$("subagents-default").addEventListener("click", () => {
|
|
||||||
$("subagents-instruction").value = defaultInstruction(S.workflow);
|
|
||||||
});
|
|
||||||
$("subagents-save").addEventListener("click", saveSubagents);
|
|
||||||
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
|
|
||||||
$("subagents-modal").addEventListener("close", () => $("btn-subagents").focus());
|
|
||||||
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
||||||
$("brief-go").addEventListener("click", sendBrief);
|
$("brief-go").addEventListener("click", sendBrief);
|
||||||
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ export const HELP_TABS = Object.freeze([
|
|||||||
tab("dashboard", "The dashboard", true),
|
tab("dashboard", "The dashboard", true),
|
||||||
tab("meter", "Session meter", false),
|
tab("meter", "Session meter", false),
|
||||||
tab("build", "Watching a build", false),
|
tab("build", "Watching a build", false),
|
||||||
tab("subagents", "Helpers (subagents)", false),
|
|
||||||
tab("ask", "Ask a quick question", false),
|
tab("ask", "Ask a quick question", false),
|
||||||
tab("finishing", "Stopping and finishing", false),
|
tab("finishing", "Stopping and finishing", false),
|
||||||
tab("stuck", "When something looks stuck", true),
|
tab("stuck", "When something looks stuck", true),
|
||||||
@@ -40,7 +39,6 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
|||||||
if (gone || adrift) return "stuck";
|
if (gone || adrift) return "stuck";
|
||||||
if (workspace) return "workspace";
|
if (workspace) return "workspace";
|
||||||
if (v === "ask") return "ask";
|
if (v === "ask") return "ask";
|
||||||
if (v === "subagents") return "subagents";
|
|
||||||
if (dashboard && meterRed) return "meter";
|
if (dashboard && meterRed) return "meter";
|
||||||
if (dashboard) return "dashboard";
|
if (dashboard) return "dashboard";
|
||||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||||
|
|||||||
@@ -21,7 +21,6 @@
|
|||||||
<link rel="modulepreload" href="/starters.js" />
|
<link rel="modulepreload" href="/starters.js" />
|
||||||
<link rel="modulepreload" href="/workspace.js" />
|
<link rel="modulepreload" href="/workspace.js" />
|
||||||
<link rel="modulepreload" href="/meter.js" />
|
<link rel="modulepreload" href="/meter.js" />
|
||||||
<link rel="modulepreload" href="/subagents.js" />
|
|
||||||
<link rel="modulepreload" href="/mentions.js" />
|
<link rel="modulepreload" href="/mentions.js" />
|
||||||
<link rel="modulepreload" href="/favicon.js" />
|
<link rel="modulepreload" href="/favicon.js" />
|
||||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||||
@@ -173,18 +172,6 @@
|
|||||||
<button type="button" class="btn ghost small brief-btn" id="btn-brief" hidden>
|
<button type="button" class="btn ghost small brief-btn" id="btn-brief" hidden>
|
||||||
Write a brief
|
Write a brief
|
||||||
</button>
|
</button>
|
||||||
<!-- Subagents: opted-in skills only. Lit while helpers are on; a click
|
|
||||||
opens the Subagents dialog and never toggles them itself. -->
|
|
||||||
<button type="button" class="btn ghost small subagents-btn" id="btn-subagents" aria-pressed="false" hidden>
|
|
||||||
<!-- An orchestrator and its helpers: one larger node linked to three smaller ones. -->
|
|
||||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
||||||
<path class="sa-link" d="M6.9 6.6L10.9 3.9M7.4 8h3.5M6.9 9.4l4 2.7" />
|
|
||||||
<circle cx="4.6" cy="8" r="2.6" class="sa-hub" />
|
|
||||||
<circle cx="12.4" cy="3" r="1.5" class="sa-node" />
|
|
||||||
<circle cx="12.4" cy="8" r="1.5" class="sa-node" />
|
|
||||||
<circle cx="12.4" cy="13" r="1.5" class="sa-node" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="views-group">
|
<div class="views-group">
|
||||||
<span class="views-arrow" aria-hidden="true">
|
<span class="views-arrow" aria-hidden="true">
|
||||||
@@ -418,7 +405,7 @@
|
|||||||
</svg>
|
</svg>
|
||||||
|
|
||||||
<!-- 4 Finalize: hopping for joy, both arms up, beside the checkmark
|
<!-- 4 Finalize: hopping for joy, both arms up, beside the checkmark
|
||||||
flag, confetti drifting down. -->
|
flag, confetti drifting down and his star glowing. -->
|
||||||
<svg class="pose pose-finalize" data-pose="finalize" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
|
<svg class="pose pose-finalize" data-pose="finalize" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
|
||||||
<ellipse class="shadow fz-shadow" cx="120" cy="198" rx="34" ry="5" />
|
<ellipse class="shadow fz-shadow" cx="120" cy="198" rx="34" ry="5" />
|
||||||
<g class="fz-hop">
|
<g class="fz-hop">
|
||||||
@@ -428,6 +415,7 @@
|
|||||||
<rect class="sh" x="80" y="72" width="80" height="108" rx="16" />
|
<rect class="sh" x="80" y="72" width="80" height="108" rx="16" />
|
||||||
<path class="ln" d="M80 116 L60 90" /><circle class="fl" cx="60" cy="90" r="5.5" />
|
<path class="ln" d="M80 116 L60 90" /><circle class="fl" cx="60" cy="90" r="5.5" />
|
||||||
<path class="ln" d="M160 116 L180 90" /><circle class="fl" cx="180" cy="90" r="5.5" />
|
<path class="ln" d="M160 116 L180 90" /><circle class="fl" cx="180" cy="90" r="5.5" />
|
||||||
|
<circle class="ac fz-halo" cx="120" cy="98" r="23" />
|
||||||
<path class="ey blink" d="M120 84 L123.64 92.98 L133.31 93.67 L125.9 99.92 L128.23 109.33 L120 104.2 L111.77 109.33 L114.1 99.92 L106.69 93.67 L116.36 92.98 Z" />
|
<path class="ey blink" d="M120 84 L123.64 92.98 L133.31 93.67 L125.9 99.92 L128.23 109.33 L120 104.2 L111.77 109.33 L114.1 99.92 L106.69 93.67 L116.36 92.98 Z" />
|
||||||
<path class="ey" d="M106 118 Q120 134 134 118 Z" />
|
<path class="ey" d="M106 118 Q120 134 134 118 Z" />
|
||||||
</g>
|
</g>
|
||||||
@@ -593,13 +581,6 @@
|
|||||||
<rect x="3" y="9" width="18" height="6" rx="3" />
|
<rect x="3" y="9" width="18" height="6" rx="3" />
|
||||||
<path d="M6 12h7" />
|
<path d="M6 12h7" />
|
||||||
</symbol>
|
</symbol>
|
||||||
<symbol id="hi-subagents" viewBox="0 0 24 24" fill="none">
|
|
||||||
<circle cx="7" cy="12" r="3.5" />
|
|
||||||
<circle cx="18" cy="5" r="2" />
|
|
||||||
<circle cx="18" cy="12" r="2" />
|
|
||||||
<circle cx="18" cy="19" r="2" />
|
|
||||||
<path d="M10 10l6-4M10.5 12H16M10 14l6 4" />
|
|
||||||
</symbol>
|
|
||||||
<symbol id="hi-ask" viewBox="0 0 24 24" fill="none">
|
<symbol id="hi-ask" viewBox="0 0 24 24" fill="none">
|
||||||
<path d="M4 5h16v11H10l-4 4v-4H4z" />
|
<path d="M4 5h16v11H10l-4 4v-4H4z" />
|
||||||
<path d="M8 9.5h8M8 12.5h5" />
|
<path d="M8 9.5h8M8 12.5h5" />
|
||||||
@@ -852,28 +833,10 @@
|
|||||||
Click the folder name in the middle of the bottom bar. It shows your
|
Click the folder name in the middle of the bottom bar. It shows your
|
||||||
folder's name and branch, such as <strong>shop · main</strong>, and
|
folder's name and branch, such as <strong>shop · main</strong>, and
|
||||||
<strong>shop + 2 folders · main</strong> once you have added some.
|
<strong>shop + 2 folders · main</strong> once you have added some.
|
||||||
It carries across steps you start from the dashboard.
|
The workspace lasts for this console session only: it carries across
|
||||||
|
steps you start from the dashboard, and a new console session starts
|
||||||
|
with just the folder you started in.
|
||||||
</p>
|
</p>
|
||||||
<h4>Remembered for next time</h4>
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
Every change is saved as you make it, so the next console session in
|
|
||||||
this folder starts with the same folders.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
Each spec keeps its own list. The first time you pick a spec on the
|
|
||||||
dashboard it starts as a copy of the project's list (the one shown
|
|
||||||
under <strong>Start from scratch</strong>), and after that the two
|
|
||||||
are separate. Picking a spec loads its list; the line under the
|
|
||||||
dialog's title says whose list you are looking at.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
The lists live in <code>workspaces.json</code> in your own
|
|
||||||
Plan2Code settings folder, beside your look and feel, never in the
|
|
||||||
project. Finalize offers to forget a spec's list when it archives the
|
|
||||||
spec.
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
<h4>Adding a folder</h4>
|
<h4>Adding a folder</h4>
|
||||||
<ul>
|
<ul>
|
||||||
<li>
|
<li>
|
||||||
@@ -1311,14 +1274,6 @@
|
|||||||
come back, and you can change your role any time from the swatch
|
come back, and you can change your role any time from the swatch
|
||||||
button.
|
button.
|
||||||
</p>
|
</p>
|
||||||
<h4>When an update is out</h4>
|
|
||||||
<p>
|
|
||||||
When a newer Plan2Code release is out, the dashboard shows
|
|
||||||
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
|
|
||||||
to run in your terminal; × hides it until the next
|
|
||||||
<code>/plan2code</code>. The version at the bottom of Help links to
|
|
||||||
the Releases page.
|
|
||||||
</p>
|
|
||||||
<h4>The cards</h4>
|
<h4>The cards</h4>
|
||||||
<p>They come in three groups.</p>
|
<p>They come in three groups.</p>
|
||||||
<p><strong>First, the project</strong></p>
|
<p><strong>First, the project</strong></p>
|
||||||
@@ -1408,10 +1363,9 @@
|
|||||||
<h4>What it counts</h4>
|
<h4>What it counts</h4>
|
||||||
<p>
|
<p>
|
||||||
Each step you run here adds points: a plan or a set of documents
|
Each step you run here adds points: a plan or a set of documents
|
||||||
weighs more than a quick task, and a built phase more still, by how
|
weighs more than a single answered question, and a built phase more
|
||||||
many tasks it completed: a big phase adds more than a small one.
|
still, by how many tasks it completed: a big phase adds more than a
|
||||||
Every two questions you answer within one step add a point too
|
small one. Every two questions you answer add a point too, so a long
|
||||||
(rounded down, so a single answer adds nothing), so a long
|
|
||||||
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
|
back-and-forth counts for more than a short one. Click the ring to see the count and a list of each step that added
|
||||||
points, with what it added. It is a rule of thumb, not a
|
points, with what it added. It is a rule of thumb, not a
|
||||||
reading of Plan2Code's real memory: long sessions tend to make it
|
reading of Plan2Code's real memory: long sessions tend to make it
|
||||||
@@ -1497,61 +1451,7 @@
|
|||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 12: Helpers (subagents) -->
|
<!-- Tab 12: Ask a quick question -->
|
||||||
<section class="help-panel" data-tab="subagents">
|
|
||||||
<h3>Helpers (subagents)</h3>
|
|
||||||
<p>
|
|
||||||
On a build, a review and Pathfinder, Plan2Code can hand independent
|
|
||||||
pieces of work to helpers (subagents) while it keeps the conversation
|
|
||||||
with you. The <strong>Subagents</strong> button in the top bar, after
|
|
||||||
Stop session, is lit while helpers are on.
|
|
||||||
</p>
|
|
||||||
<h4>The switch</h4>
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
Clicking the button opens the <strong>Subagents</strong> dialog; it
|
|
||||||
never switches helpers on or off by itself. Pick <strong>Use
|
|
||||||
helpers</strong> or <strong>Work alone</strong>, edit the instruction
|
|
||||||
Plan2Code follows (<strong>Reset to default</strong> puts the
|
|
||||||
shipped one back), and say how many may run at once.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
It is off by default and saved for this project and this skill, so
|
|
||||||
the next session of the same skill here starts the same way.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
The change reaches Plan2Code at its next check-in, as a setting,
|
|
||||||
not as something you typed. How many helpers it can really start is
|
|
||||||
up to your agent; some have no helpers at all.
|
|
||||||
</li>
|
|
||||||
<li>The button only appears on skills that use helpers, and only when Plan2Code can pass the setting on.</li>
|
|
||||||
</ul>
|
|
||||||
<h4>The Subagents tab</h4>
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
With the first helper, a <strong>Subagents</strong> tab appears before
|
|
||||||
Ask: one row each, with what it was asked, whether it is running, done
|
|
||||||
or failed, and a one-line result at the end. The number on the tab is
|
|
||||||
how many are still running.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
Helpers report through Plan2Code, so the rows change at its
|
|
||||||
check-ins, not live. The page cannot stop a helper; ask Plan2Code
|
|
||||||
on the Ask tab if one should stop.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
<strong>Working alone</strong> means your agent has no way to start
|
|
||||||
helpers here, so it is doing the work itself.
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
Pathfinder always uses helpers for its research questions, whatever
|
|
||||||
the switch says, and they show here too.
|
|
||||||
</li>
|
|
||||||
<li>The tab clears when you go back to the dashboard.</li>
|
|
||||||
</ul>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<!-- Tab 13: Ask a quick question -->
|
|
||||||
<section class="help-panel" data-tab="ask">
|
<section class="help-panel" data-tab="ask">
|
||||||
<h3>Ask a quick question</h3>
|
<h3>Ask a quick question</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1642,7 +1542,7 @@
|
|||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 14: Stopping and finishing -->
|
<!-- Tab 13: Stopping and finishing -->
|
||||||
<section class="help-panel" data-tab="finishing">
|
<section class="help-panel" data-tab="finishing">
|
||||||
<h3>Stopping and finishing</h3>
|
<h3>Stopping and finishing</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1724,7 +1624,7 @@
|
|||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 15: When something looks stuck -->
|
<!-- Tab 14: When something looks stuck -->
|
||||||
<section class="help-panel" data-tab="stuck">
|
<section class="help-panel" data-tab="stuck">
|
||||||
<h3>When something looks stuck</h3>
|
<h3>When something looks stuck</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1846,7 +1746,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 16: Keyboard and preferences -->
|
<!-- Tab 15: Keyboard and preferences -->
|
||||||
<section class="help-panel" data-tab="prefs">
|
<section class="help-panel" data-tab="prefs">
|
||||||
<h3>Keyboard and preferences</h3>
|
<h3>Keyboard and preferences</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1927,15 +1827,6 @@
|
|||||||
joining the strip. Keep only the ones you want; ticking a box plays
|
joining the strip. Keep only the ones you want; ticking a box plays
|
||||||
its sound.
|
its sound.
|
||||||
</li>
|
</li>
|
||||||
<li>
|
|
||||||
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
|
|
||||||
lists what Plan2Code doesn't need in your
|
|
||||||
<code>~/.plan2code</code> folder: sessions nobody has opened for
|
|
||||||
30 days, and files or folders that ended up there by mistake. It
|
|
||||||
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.
|
|
||||||
</li>
|
|
||||||
<li>
|
<li>
|
||||||
<strong>Back to default</strong> puts everything back as it was, and
|
<strong>Back to default</strong> puts everything back as it was, and
|
||||||
sets Role back to Not set.
|
sets Role back to Not set.
|
||||||
@@ -1962,7 +1853,7 @@
|
|||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Tab 17: Privacy and where things are saved -->
|
<!-- Tab 16: Privacy and where things are saved -->
|
||||||
<section class="help-panel" data-tab="privacy">
|
<section class="help-panel" data-tab="privacy">
|
||||||
<h3>Privacy and where things are saved</h3>
|
<h3>Privacy and where things are saved</h3>
|
||||||
<p class="help-lead">
|
<p class="help-lead">
|
||||||
@@ -1999,11 +1890,7 @@
|
|||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
your role, theme, colors, card width and sounds, in
|
your role, theme, colors, card width and sounds, in
|
||||||
<code>looks.json</code>;
|
<code>looks.json</code>.
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
your Subagents switch for each project and skill, in
|
|
||||||
<code>subagents.json</code>.
|
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
<p>
|
<p>
|
||||||
@@ -2078,16 +1965,6 @@
|
|||||||
</div>
|
</div>
|
||||||
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<fieldset class="modal-ranges looks-cleanup">
|
|
||||||
<legend>Cleanup</legend>
|
|
||||||
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
|
|
||||||
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
|
|
||||||
<div class="models-actions">
|
|
||||||
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
|
|
||||||
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
|
|
||||||
<span class="help" id="cleanup-status" role="status"></span>
|
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset class="modal-ranges looks-models">
|
<fieldset class="modal-ranges looks-models">
|
||||||
<legend>Models</legend>
|
<legend>Models</legend>
|
||||||
<div class="models-tabs" role="group" aria-label="Which agent">
|
<div class="models-tabs" role="group" aria-label="Which agent">
|
||||||
@@ -2117,46 +1994,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
<!-- Subagents: the switch for this skill, filled from the frame's
|
|
||||||
`subagents` by app.js and saved through POST /subagents. It borrows
|
|
||||||
the User Preferences dialog's classes, so it needs no dialog styles of
|
|
||||||
its own, only a themed number box. -->
|
|
||||||
<dialog class="modal looks subagents" id="subagents-modal" aria-labelledby="subagents-title">
|
|
||||||
<h2 id="subagents-title">Subagents</h2>
|
|
||||||
<p class="modal-blurb">
|
|
||||||
Let Plan2Code hand independent work to helpers in this skill. Saved for this
|
|
||||||
project and this skill.
|
|
||||||
</p>
|
|
||||||
<fieldset class="modal-ranges looks-row">
|
|
||||||
<legend>Helpers</legend>
|
|
||||||
<label><input type="radio" name="subagents-on" value="on" /> <span>Use helpers</span></label>
|
|
||||||
<label><input type="radio" name="subagents-on" value="off" checked /> <span>Work alone</span></label>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset class="modal-ranges">
|
|
||||||
<legend>Instruction</legend>
|
|
||||||
<textarea id="subagents-instruction" rows="4" maxlength="2000" aria-label="Instruction"></textarea>
|
|
||||||
<div class="models-actions">
|
|
||||||
<button type="button" class="btn small ghost" id="subagents-default">Reset to default</button>
|
|
||||||
<span class="help">Passed to the agent as written, at its next check-in.</span>
|
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
<fieldset class="modal-ranges">
|
|
||||||
<legend>At most</legend>
|
|
||||||
<label>
|
|
||||||
<input type="number" id="subagents-max" min="1" max="20" step="1" aria-label="At most this many helpers at once" />
|
|
||||||
<span>helpers at once</span>
|
|
||||||
</label>
|
|
||||||
<p class="help">Advisory: your agent's own limit still applies.</p>
|
|
||||||
</fieldset>
|
|
||||||
<p class="help" id="subagents-checkin"></p>
|
|
||||||
<p class="help" id="subagents-research" hidden></p>
|
|
||||||
<p class="help" id="subagents-status" role="status"></p>
|
|
||||||
<div class="modal-actions">
|
|
||||||
<button type="button" class="btn ghost" id="subagents-cancel">Cancel</button>
|
|
||||||
<button type="button" class="btn primary" id="subagents-save">Save</button>
|
|
||||||
</div>
|
|
||||||
</dialog>
|
|
||||||
|
|
||||||
<!-- The Workspace: the folder this session started in plus any added as
|
<!-- The Workspace: the folder this session started in plus any added as
|
||||||
context. The list is drawn by app.js from the frame's `workspace`;
|
context. The list is drawn by app.js from the frame's `workspace`;
|
||||||
every change goes through the server's /workspace routes. -->
|
every change goes through the server's /workspace routes. -->
|
||||||
@@ -2166,7 +2003,6 @@
|
|||||||
The folders the agent uses as context this session. It reads the extra ones for
|
The folders the agent uses as context this session. It reads the extra ones for
|
||||||
reference and only changes them if you ask.
|
reference and only changes them if you ask.
|
||||||
</p>
|
</p>
|
||||||
<p class="workspace-scope" id="workspace-scope"></p>
|
|
||||||
<ul class="workspace-list" id="workspace-list"></ul>
|
<ul class="workspace-list" id="workspace-list"></ul>
|
||||||
<div class="workspace-add">
|
<div class="workspace-add">
|
||||||
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
|
<label class="workspace-add-label" for="workspace-path">Add a folder</label>
|
||||||
@@ -2326,24 +2162,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
|
|
||||||
the copy row are filled by app.js; the update itself runs in a
|
|
||||||
terminal, never from this page. -->
|
|
||||||
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
|
|
||||||
<h2 id="update-title">A new Plan2Code is available</h2>
|
|
||||||
<p class="modal-blurb" id="update-versions"></p>
|
|
||||||
<ol class="update-steps">
|
|
||||||
<li>
|
|
||||||
Run this in your terminal (not in this page or your agent):
|
|
||||||
<div class="update-command" id="update-command"></div>
|
|
||||||
</li>
|
|
||||||
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
|
|
||||||
</ol>
|
|
||||||
<div class="modal-actions">
|
|
||||||
<button type="button" class="btn primary" id="update-done">Close</button>
|
|
||||||
</div>
|
|
||||||
</dialog>
|
|
||||||
|
|
||||||
<footer class="footer">
|
<footer class="footer">
|
||||||
<div class="footer-summary" id="footer-summary" aria-live="polite">
|
<div class="footer-summary" id="footer-summary" aria-live="polite">
|
||||||
Nothing to send yet.
|
Nothing to send yet.
|
||||||
|
|||||||
@@ -5,10 +5,7 @@
|
|||||||
// popover; this file owns the rules. No DOM access at module scope and no
|
// popover; this file owns the rules. No DOM access at module scope and no
|
||||||
// imports: the page and `node --test` both import this file.
|
// imports: the page and `node --test` both import this file.
|
||||||
|
|
||||||
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
|
const NAME_CHAR = /[a-z0-9-]/;
|
||||||
// by the workspace rules, and a query typed with a capital otherwise matches
|
|
||||||
// nothing and opens no suggestions at all.
|
|
||||||
const NAME_CHAR = /[a-z0-9-]/i;
|
|
||||||
const MAX_MATCHES = 6;
|
const MAX_MATCHES = 6;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -26,13 +23,11 @@ export function mentionAt(text, caret) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Names starting with the query first, then names containing it, in the
|
// Names starting with the query first, then names containing it, in the
|
||||||
// order given, at most six. Case-folded: folder names are lowercase by rule,
|
// order given, at most six.
|
||||||
// and "@Repo" should still find @repo rather than claim nothing matches.
|
|
||||||
export function matchNames(names, query) {
|
export function matchNames(names, query) {
|
||||||
const q = String(query || "").toLowerCase();
|
const q = String(query || "");
|
||||||
const fold = (n) => String(n).toLowerCase();
|
const prefix = names.filter((n) => n.startsWith(q));
|
||||||
const prefix = names.filter((n) => fold(n).startsWith(q));
|
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
|
||||||
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
|
|
||||||
return [...prefix, ...inside].slice(0, MAX_MATCHES);
|
return [...prefix, ...inside].slice(0, MAX_MATCHES);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -53,55 +53,16 @@ export const TASK_EVENTS = Object.freeze(new Set(Object.keys(TASK_BONUS)));
|
|||||||
// The most tasks one run may report: past this it is a typo, not a phase.
|
// The most tasks one run may report: past this it is a typo, not a phase.
|
||||||
export const MAX_TASKS = 999;
|
export const MAX_TASKS = 999;
|
||||||
|
|
||||||
// A build scores while it runs, not only once it is approved: console.mjs
|
|
||||||
// writes a `progress` ledger entry whenever a build's `headline.cleared`
|
|
||||||
// rises, and the build's row scores those tasks at TASKS_PER_POINT with no
|
|
||||||
// bonus. The phase's `run` then takes the row over with its final score, so
|
|
||||||
// the total only ever climbs. Workflows whose headline counts tasks:
|
|
||||||
export const PROGRESS_WORKFLOWS = Object.freeze(new Set(["implement", "implement-review"]));
|
|
||||||
|
|
||||||
// Implement + Review reviews every phase as a stage of the build. A `review`
|
|
||||||
// run inside it is that stage, so it scores the phase's TASK_BONUS when it
|
|
||||||
// starts, and the phase's own run leaves the bonus out after it.
|
|
||||||
const BUILT_IN_REVIEW = Object.freeze({ "implement-review": "implement-review-phase" });
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The ledger entry a build's progress post stands for, or null when it adds
|
|
||||||
* nothing: not a task-counting workflow, no whole `cleared`, or no more tasks
|
|
||||||
* than this build already has. `seg` is how many phases this skill run has
|
|
||||||
* finished, so a second phase in the same run starts its own count, but only
|
|
||||||
* once its headline is back at 0: until then a `cleared` is the finished
|
|
||||||
* phase's, posted again, and opening a build on it would count it twice.
|
|
||||||
*/
|
|
||||||
export function progressEntry(entries, launch, workflow, cleared) {
|
|
||||||
if (!PROGRESS_WORKFLOWS.has(workflow)) return null;
|
|
||||||
if (cleared !== 0 && !isTaskCount(cleared)) return null;
|
|
||||||
const list = Array.isArray(entries) ? entries : [];
|
|
||||||
const seg = list.filter((e) => e && e.kind === "run" && TASK_EVENTS.has(e.event) && launchOf(e.id) === launch).length;
|
|
||||||
const build = `${launch}:b${seg}`;
|
|
||||||
const mine = list.filter((e) => e && e.kind === "progress" && e.build === build);
|
|
||||||
const entry = (tasks) => ({ kind: "progress", id: `${build}:${tasks}`, build, workflow, tasks });
|
|
||||||
if (cleared === 0) return seg > 0 && !mine.length ? entry(0) : null;
|
|
||||||
if (seg > 0 && !mine.length) return null;
|
|
||||||
const most = mine.reduce((n, e) => Math.max(n, e.tasks), 0);
|
|
||||||
return cleared > most ? entry(cleared) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A valid `run.tasks`: a whole number from 1 to MAX_TASKS. */
|
/** A valid `run.tasks`: a whole number from 1 to MAX_TASKS. */
|
||||||
export function isTaskCount(tasks) {
|
export function isTaskCount(tasks) {
|
||||||
return Number.isInteger(tasks) && tasks >= 1 && tasks <= MAX_TASKS;
|
return Number.isInteger(tasks) && tasks >= 1 && tasks <= MAX_TASKS;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** What one `run` scores, from its event and (for a built phase) its tasks. */
|
||||||
* What one `run` scores, from its event and (for a built phase) its tasks.
|
export function runPoints(event, tasks) {
|
||||||
* `bonus: false` leaves the review bonus out, for a phase whose review
|
|
||||||
* already scored.
|
|
||||||
*/
|
|
||||||
export function runPoints(event, tasks, { bonus = true } = {}) {
|
|
||||||
if (TASK_EVENTS.has(event) && isTaskCount(tasks)) {
|
if (TASK_EVENTS.has(event) && isTaskCount(tasks)) {
|
||||||
return Math.ceil(tasks / TASKS_PER_POINT) + (bonus ? TASK_BONUS[event] : 0);
|
return Math.ceil(tasks / TASKS_PER_POINT) + TASK_BONUS[event];
|
||||||
}
|
}
|
||||||
if (TASK_EVENTS.has(event) && !bonus) return weightOf(event) - TASK_BONUS[event];
|
|
||||||
return weightOf(event);
|
return weightOf(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,8 +133,6 @@ export function breakdownFrom(entries) {
|
|||||||
const seen = new Set();
|
const seen = new Set();
|
||||||
const rows = [];
|
const rows = [];
|
||||||
const answers = new Map(); // launch id -> { row, count, workflow }
|
const answers = new Map(); // launch id -> { row, count, workflow }
|
||||||
const builds = new Map(); // launch id -> the row of the build in progress
|
|
||||||
const reviewed = new Set(); // launch ids whose built-in review has scored
|
|
||||||
for (const entry of Array.isArray(entries) ? entries : []) {
|
for (const entry of Array.isArray(entries) ? entries : []) {
|
||||||
if (!entry || typeof entry !== "object") continue;
|
if (!entry || typeof entry !== "object") continue;
|
||||||
if (entry.id !== undefined) {
|
if (entry.id !== undefined) {
|
||||||
@@ -191,54 +150,17 @@ export function breakdownFrom(entries) {
|
|||||||
tally.count += 1;
|
tally.count += 1;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (entry.kind === "progress") {
|
|
||||||
if (!isTaskCount(entry.tasks)) continue;
|
|
||||||
const launch = launchOf(entry.id);
|
|
||||||
let row = builds.get(launch);
|
|
||||||
if (!row || row.build !== entry.build) {
|
|
||||||
row = { label: "", points: 0, build: entry.build, tasks: 0 };
|
|
||||||
builds.set(launch, row);
|
|
||||||
rows.push(row);
|
|
||||||
}
|
|
||||||
if (entry.tasks > row.tasks) {
|
|
||||||
row.tasks = entry.tasks;
|
|
||||||
row.points = Math.ceil(entry.tasks / TASKS_PER_POINT);
|
|
||||||
const where = WORKFLOW_NAMES[entry.workflow] || "Build";
|
|
||||||
row.label = `${where}: ${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"} built so far`;
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let points = 0;
|
let points = 0;
|
||||||
let label = "";
|
let label = "";
|
||||||
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) {
|
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) {
|
||||||
points = weightOf(entry.workflow);
|
points = weightOf(entry.workflow);
|
||||||
label = LAUNCH_LABELS[entry.workflow] || entry.workflow;
|
label = LAUNCH_LABELS[entry.workflow] || entry.workflow;
|
||||||
} else if (entry.kind === "run") {
|
} else if (entry.kind === "run") {
|
||||||
const launch = launchOf(entry.id);
|
points = runPoints(entry.event, entry.tasks);
|
||||||
const builtIn = BUILT_IN_REVIEW[entry.workflow];
|
|
||||||
if (entry.event === "review" && builtIn) {
|
|
||||||
// The review stage of Implement + Review: it scores the bonus its
|
|
||||||
// phase would otherwise carry, once per skill run.
|
|
||||||
if (reviewed.has(launch)) continue;
|
|
||||||
reviewed.add(launch);
|
|
||||||
points = TASK_BONUS[builtIn];
|
|
||||||
label = `${WORKFLOW_NAMES[entry.workflow]}: code review run`;
|
|
||||||
} else {
|
|
||||||
const bonus = !(TASK_EVENTS.has(entry.event) && reviewed.has(launch));
|
|
||||||
points = runPoints(entry.event, entry.tasks, { bonus });
|
|
||||||
const unit = unitOf(entry.id);
|
const unit = unitOf(entry.id);
|
||||||
const counted = TASK_EVENTS.has(entry.event) && isTaskCount(entry.tasks);
|
const counted = TASK_EVENTS.has(entry.event) && isTaskCount(entry.tasks);
|
||||||
const size = counted ? ` (${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"})` : "";
|
const size = counted ? ` (${entry.tasks} ${entry.tasks === 1 ? "task" : "tasks"})` : "";
|
||||||
label = (RUN_LABELS[entry.event] || entry.event) + (unit && unit !== entry.event ? `: ${unit}` : "") + size;
|
label = (RUN_LABELS[entry.event] || entry.event) + (unit ? `: ${unit}` : "") + size;
|
||||||
}
|
|
||||||
// A finished phase takes over its build's progress row, in place.
|
|
||||||
if (TASK_EVENTS.has(entry.event) && builds.has(launch)) {
|
|
||||||
const row = builds.get(launch);
|
|
||||||
builds.delete(launch);
|
|
||||||
row.label = label;
|
|
||||||
row.points = Math.max(points, row.points);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (points > 0) rows.push({ label, points });
|
if (points > 0) rows.push({ label, points });
|
||||||
}
|
}
|
||||||
@@ -247,7 +169,7 @@ export function breakdownFrom(entries) {
|
|||||||
const where = WORKFLOW_NAMES[workflow] ? ` in ${WORKFLOW_NAMES[workflow]}` : "";
|
const where = WORKFLOW_NAMES[workflow] ? ` in ${WORKFLOW_NAMES[workflow]}` : "";
|
||||||
row.label = `${count} ${count === 1 ? "answer" : "answers"}${where}`;
|
row.label = `${count} ${count === 1 ? "answer" : "answers"}${where}`;
|
||||||
}
|
}
|
||||||
return rows.filter((row) => row.points > 0).map(({ label, points }) => ({ label, points }));
|
return rows.filter((row) => row.points > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The session's points, folded from ledger entries in order. */
|
/** The session's points, folded from ledger entries in order. */
|
||||||
|
|||||||
@@ -1,223 +0,0 @@
|
|||||||
// Plan2Code Web Console - the Subagents switch's opt-in table, wording and checks.
|
|
||||||
//
|
|
||||||
// The source of truth for which workflows offer the switch, the instruction
|
|
||||||
// each one ships with, the fixed frame every "on" block carries, the exact
|
|
||||||
// lines the agent reads at a pickup (blockFor()), and the house rules for the
|
|
||||||
// helpers an agent reports back (checkHelper()). No DOM access at module scope
|
|
||||||
// and no imports: the server, console.mjs, the page and `node --test` all
|
|
||||||
// import this file.
|
|
||||||
|
|
||||||
// The one place a skill opts in (FR-1). Wording is behaviour-level and names
|
|
||||||
// no harness tool, so any agent can follow it or harmlessly ignore it.
|
|
||||||
export const SUBAGENT_WORKFLOWS = Object.freeze({
|
|
||||||
implement: Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
|
||||||
}),
|
|
||||||
"implement-review": Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
|
||||||
}),
|
|
||||||
"quick-task": Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
|
||||||
}),
|
|
||||||
review: Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Split the review across helpers by area (for example correctness, tests and security), then merge and de-duplicate their findings yourself before you report.",
|
|
||||||
}),
|
|
||||||
pathfinder: Object.freeze({
|
|
||||||
instruction:
|
|
||||||
"Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
export function offered(workflow) {
|
|
||||||
return typeof workflow === "string" && Object.prototype.hasOwnProperty.call(SUBAGENT_WORKFLOWS, workflow);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const MAX_MIN = 1;
|
|
||||||
export const MAX_MAX = 20;
|
|
||||||
export const DEFAULT_MAX = 3;
|
|
||||||
export const INSTRUCTION_MAX_CHARS = 2000;
|
|
||||||
export const HELPER_TITLE_MAX = 80;
|
|
||||||
export const HELPER_ASK_MAX = 400;
|
|
||||||
export const HELPER_RESULT_MAX = 200;
|
|
||||||
export const HELPER_STATES = Object.freeze(["running", "done", "failed"]);
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------- settings */
|
|
||||||
|
|
||||||
export function defaultInstruction(workflow) {
|
|
||||||
return offered(workflow) ? SUBAGENT_WORKFLOWS[workflow].instruction : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// The person's own text when they wrote some, else the workflow's default.
|
|
||||||
export function effectiveInstruction(setting) {
|
|
||||||
const own = setting && typeof setting.instruction === "string" ? setting.instruction.trim() : "";
|
|
||||||
return own || defaultInstruction(setting && setting.workflow);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function defaultSetting(workflow) {
|
|
||||||
return { workflow, on: false, instruction: null, max: DEFAULT_MAX };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* `{ on, instruction, max }` from untrusted input, or `{ error }` naming the
|
|
||||||
* field that failed: "bad" (wrong type), "too-long" (instruction) or "max".
|
|
||||||
* Returns an error object rather than throwing, so the route and the store
|
|
||||||
* reader share one validator. An empty instruction means the default: null.
|
|
||||||
*/
|
|
||||||
export function cleanSetting(input) {
|
|
||||||
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "bad" };
|
|
||||||
if (typeof input.on !== "boolean") return { error: "bad" };
|
|
||||||
let instruction = null;
|
|
||||||
if (input.instruction !== null && input.instruction !== undefined) {
|
|
||||||
if (typeof input.instruction !== "string") return { error: "bad" };
|
|
||||||
const trimmed = input.instruction.trim();
|
|
||||||
if (trimmed.length > INSTRUCTION_MAX_CHARS) return { error: "too-long" };
|
|
||||||
instruction = trimmed || null;
|
|
||||||
}
|
|
||||||
const max = input.max;
|
|
||||||
if (!Number.isInteger(max) || max < MAX_MIN || max > MAX_MAX) return { error: "max" };
|
|
||||||
return { on: input.on, instruction, max };
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------ the lines */
|
|
||||||
|
|
||||||
// The non-editable part of every "on" block (FR-8).
|
|
||||||
export const FRAME_LINES = Object.freeze([
|
|
||||||
"Hand independent work to helpers if your tools allow it; otherwise carry on alone.",
|
|
||||||
"Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.",
|
|
||||||
'With no way to start helpers, report one "working alone" entry for this skill run instead.',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
|
|
||||||
|
|
||||||
// Only the first line of a block starts at column 0, so no line inside it can
|
|
||||||
// be read as an entry of its own (NFR-5).
|
|
||||||
export function onLines({ revision, replaces, max, instruction }) {
|
|
||||||
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
|
|
||||||
const own = String(instruction || "")
|
|
||||||
.split("\n")
|
|
||||||
.map((line) => line.trimEnd())
|
|
||||||
.filter((line) => line.trim());
|
|
||||||
return [
|
|
||||||
`Subagents: on (${label}) — a console setting, not typed by the person.`,
|
|
||||||
...[...FRAME_LINES, ...own, `At most ${max} helpers at once.`].map((line) => " " + line),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function offLine(revision) {
|
|
||||||
return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What the agent is owed at a pickup, given the session setting and the
|
|
||||||
* cursor of what it was last told: `null`, or `{ field, lines, cursor }`
|
|
||||||
* where `cursor` is what to write once the lines are printed. Never says
|
|
||||||
* "off" to an agent that was not told "on" (FR-6). Pure: no clock, no I/O.
|
|
||||||
*/
|
|
||||||
export function blockFor(setting, told) {
|
|
||||||
const last = told || { revision: 0, state: "none" };
|
|
||||||
if (!setting || !offered(setting.workflow) || !(setting.revision > last.revision)) return null;
|
|
||||||
const { revision, max } = setting;
|
|
||||||
const instruction = effectiveInstruction(setting);
|
|
||||||
if (setting.on) {
|
|
||||||
const replaces = last.state === "on" ? last.revision : undefined;
|
|
||||||
return {
|
|
||||||
field: { state: "on", revision, max, instruction },
|
|
||||||
lines: onLines({ revision, replaces, max, instruction }),
|
|
||||||
cursor: { revision, state: "on" },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (last.state !== "on") return null;
|
|
||||||
return {
|
|
||||||
field: { state: "off", revision, max, instruction },
|
|
||||||
lines: [offLine(revision)],
|
|
||||||
cursor: { revision, state: "off" },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------ helpers */
|
|
||||||
|
|
||||||
const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
||||||
const nonEmpty = (v) => typeof v === "string" && v.trim() !== "";
|
|
||||||
|
|
||||||
// The problems with one reported helper, [] when it is fine.
|
|
||||||
export function checkHelper(entry) {
|
|
||||||
if (!isPlainObject(entry)) return ["helper: each entry must be an object"];
|
|
||||||
if (!nonEmpty(entry.id)) return ["helper: id must be a non-empty string"];
|
|
||||||
const who = `helper "${entry.id}"`;
|
|
||||||
if (entry.alone === true) return entry.id === "alone" ? [] : [`${who}: the working-alone entry must have id "alone"`];
|
|
||||||
const problems = [];
|
|
||||||
if (!nonEmpty(entry.title)) problems.push(`${who}: title must be a non-empty string`);
|
|
||||||
else if (entry.title.length > HELPER_TITLE_MAX) problems.push(`${who}: title must be at most ${HELPER_TITLE_MAX} characters`);
|
|
||||||
if (!nonEmpty(entry.ask)) problems.push(`${who}: ask must be a non-empty string`);
|
|
||||||
else if (entry.ask.length > HELPER_ASK_MAX) problems.push(`${who}: ask must be at most ${HELPER_ASK_MAX} characters`);
|
|
||||||
if (!HELPER_STATES.includes(entry.state)) problems.push(`${who}: state must be running, done or failed`);
|
|
||||||
if (entry.result !== undefined) {
|
|
||||||
if (typeof entry.result !== "string") problems.push(`${who}: result must be a string`);
|
|
||||||
else if (entry.result.length > HELPER_RESULT_MAX) problems.push(`${who}: result must be at most ${HELPER_RESULT_MAX} characters`);
|
|
||||||
}
|
|
||||||
return problems;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The problems with a whole merged list.
|
|
||||||
export function checkHelpers(list) {
|
|
||||||
if (!Array.isArray(list)) return ["helpers must be an array"];
|
|
||||||
const problems = [];
|
|
||||||
const seen = new Set();
|
|
||||||
let alone = 0;
|
|
||||||
for (const entry of list) {
|
|
||||||
if (isPlainObject(entry) && nonEmpty(entry.id)) {
|
|
||||||
if (seen.has(entry.id)) problems.push(`helper "${entry.id}": duplicate id`);
|
|
||||||
seen.add(entry.id);
|
|
||||||
if (entry.alone === true && ++alone === 2) problems.push(`helper "${entry.id}": only one working-alone entry is allowed`);
|
|
||||||
}
|
|
||||||
problems.push(...checkHelper(entry));
|
|
||||||
}
|
|
||||||
return problems;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------ the page */
|
|
||||||
|
|
||||||
// The page's rules for the button, the modal and the tab, kept here so they
|
|
||||||
// are tested without a browser. `frame` is the state frame's `subagents`
|
|
||||||
// block; app.js only renders what these say.
|
|
||||||
|
|
||||||
export const CHECKIN_LINE = "Helpers report through Plan2Code, so their progress shows here at its check-ins, not live.";
|
|
||||||
|
|
||||||
const STATE_LABELS = Object.freeze({ running: "Running", done: "Done", failed: "Failed" });
|
|
||||||
|
|
||||||
// The switch shows only where the skill opts in AND the agent's console copy
|
|
||||||
// said it can deliver it (FR-3).
|
|
||||||
export function showSwitch(frame) {
|
|
||||||
return Boolean(frame && frame.offered && frame.supported);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The button's tooltip and accessible name (FR-2).
|
|
||||||
export function switchLabel(frame) {
|
|
||||||
return frame && frame.on ? "Subagents: on" : "Subagents: off";
|
|
||||||
}
|
|
||||||
|
|
||||||
// What the Subagents tab draws: the working-alone note, or one row per helper
|
|
||||||
// in the order the agent reported them. A result shows once the helper ended.
|
|
||||||
export function helperRows(helpers) {
|
|
||||||
const list = Array.isArray(helpers) ? helpers.filter(isPlainObject) : [];
|
|
||||||
if (list.some((h) => h.alone === true)) return { alone: true, rows: [] };
|
|
||||||
const rows = list.map(({ id, title, ask, state, result }) => ({
|
|
||||||
id,
|
|
||||||
title,
|
|
||||||
ask,
|
|
||||||
state,
|
|
||||||
stateLabel: STATE_LABELS[state] || STATE_LABELS.running,
|
|
||||||
...((state === "done" || state === "failed") && typeof result === "string" && result ? { result } : {}),
|
|
||||||
}));
|
|
||||||
return { alone: false, rows };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Never an empty tab. Independent of on / off, so Pathfinder's research
|
|
||||||
// helpers show even with the switch off (FR-11, FR-12).
|
|
||||||
export function showTab(frame, helpers) {
|
|
||||||
return showSwitch(frame) && Array.isArray(helpers) && helpers.length > 0;
|
|
||||||
}
|
|
||||||
@@ -25,21 +25,17 @@ import {
|
|||||||
LOOKS_FILE,
|
LOOKS_FILE,
|
||||||
PUBLIC_DIR,
|
PUBLIC_DIR,
|
||||||
SHIPPED_MODELS_FILE,
|
SHIPPED_MODELS_FILE,
|
||||||
SUBAGENTS_SETTING_FILE,
|
|
||||||
UPDATE_CHECK_FILE,
|
|
||||||
USER_MODELS_FILE,
|
USER_MODELS_FILE,
|
||||||
WORKSPACE_FILE,
|
WORKSPACE_FILE,
|
||||||
appendChat,
|
appendChat,
|
||||||
appendEvent,
|
appendEvent,
|
||||||
chatForFrame,
|
chatForFrame,
|
||||||
checkDocument,
|
checkDocument,
|
||||||
cleanupFindings,
|
|
||||||
currentConversation,
|
currentConversation,
|
||||||
ensureDir,
|
ensureDir,
|
||||||
fileStamp,
|
fileStamp,
|
||||||
handleFile,
|
handleFile,
|
||||||
initialWorkspace,
|
initialWorkspace,
|
||||||
latestOpenCaps,
|
|
||||||
nowIso,
|
nowIso,
|
||||||
parseArgs,
|
parseArgs,
|
||||||
pendingChatCount,
|
pendingChatCount,
|
||||||
@@ -48,28 +44,18 @@ import {
|
|||||||
readJson,
|
readJson,
|
||||||
readLedger,
|
readLedger,
|
||||||
readOverview,
|
readOverview,
|
||||||
readSubagentSetting,
|
|
||||||
readWorkspace,
|
readWorkspace,
|
||||||
rememberWorkspace,
|
|
||||||
rememberedWorkspace,
|
|
||||||
removeCleanup,
|
|
||||||
remoteWarning,
|
remoteWarning,
|
||||||
saveSubagentStoreEntry,
|
|
||||||
specKey,
|
|
||||||
subagentStoreEntry,
|
|
||||||
typedCount,
|
typedCount,
|
||||||
withStateLock,
|
withStateLock,
|
||||||
writeJsonAtomic,
|
writeJsonAtomic,
|
||||||
writeSubagentSetting,
|
|
||||||
writeWorkspace,
|
writeWorkspace,
|
||||||
} from "./lib.mjs";
|
} from "./lib.mjs";
|
||||||
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
|
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
|
||||||
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
|
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
|
||||||
import { meterView } from "./public/meter.js";
|
import { meterView } from "./public/meter.js";
|
||||||
import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
|
||||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||||
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
||||||
import { checkForUpdate } from "./update-check.mjs";
|
|
||||||
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
|
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
|
||||||
|
|
||||||
const args = parseArgs(process.argv.slice(2));
|
const args = parseArgs(process.argv.slice(2));
|
||||||
@@ -219,7 +205,6 @@ const SERVABLE = new Set([
|
|||||||
"starters.js",
|
"starters.js",
|
||||||
"workspace.js",
|
"workspace.js",
|
||||||
"meter.js",
|
"meter.js",
|
||||||
"subagents.js",
|
|
||||||
"mentions.js",
|
"mentions.js",
|
||||||
"favicon.js",
|
"favicon.js",
|
||||||
"start-stop.mp3",
|
"start-stop.mp3",
|
||||||
@@ -341,9 +326,7 @@ function workspaceNow() {
|
|||||||
return ws;
|
return ws;
|
||||||
}
|
}
|
||||||
const root = sessionWorktree();
|
const root = sessionWorktree();
|
||||||
const scope = specKey(stateNow?.specDir);
|
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
|
||||||
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
|
|
||||||
const fresh = { ...initialWorkspace(root || PROJECT, remembered), scope, remote: remoteWarning().remote || "" };
|
|
||||||
// There but unreadable for now (a scanner's lock): never written over, and
|
// There but unreadable for now (a scanner's lock): never written over, and
|
||||||
// never cached, so the next call reads it again.
|
// never cached, so the next call reads it again.
|
||||||
if (stamp) return workspaceSeen.ws || fresh;
|
if (stamp) return workspaceSeen.ws || fresh;
|
||||||
@@ -364,87 +347,13 @@ function saveWorkspace(ws) {
|
|||||||
|
|
||||||
// One change: a new version, an entry in the change log the agent is handed,
|
// One change: a new version, an entry in the change log the agent is handed,
|
||||||
// the file, and every open page.
|
// the file, and every open page.
|
||||||
function bumpWorkspace(ws, change, { remember = true } = {}) {
|
function bumpWorkspace(ws, change) {
|
||||||
ws.version = (ws.version || 0) + 1;
|
ws.version = (ws.version || 0) + 1;
|
||||||
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
|
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
|
||||||
saveWorkspace(ws);
|
saveWorkspace(ws);
|
||||||
// Remembered for the next console session too. A folder gone missing or
|
|
||||||
// found again is not a change of mind, so it is not saved.
|
|
||||||
if (remember) rememberNow(ws);
|
|
||||||
pushState();
|
pushState();
|
||||||
}
|
}
|
||||||
|
|
||||||
function rememberNow(ws) {
|
|
||||||
const root = sessionWorktree();
|
|
||||||
if (!root) return;
|
|
||||||
try {
|
|
||||||
rememberWorkspace(root, ws.scope || "", ws);
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Point the workspace at another spec ("" for the project's own list) and
|
|
||||||
* swap in what was remembered there, logging each difference as a change so
|
|
||||||
* the agent's cursor stays truthful. A spec with nothing saved starts from
|
|
||||||
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
|
|
||||||
* list it has and saves it as the spec's (`seed: "current"`, a spec created
|
|
||||||
* mid-run). Folders keep their ids when their path stays.
|
|
||||||
*/
|
|
||||||
function setScope(ws, spec, seed = "project") {
|
|
||||||
const root = sessionWorktree();
|
|
||||||
const next = specKey(spec);
|
|
||||||
if (!root || (ws.scope || "") === next) return false;
|
|
||||||
const found = rememberedWorkspace(root, next);
|
|
||||||
ws.scope = next;
|
|
||||||
if (next && found.from !== "spec" && seed === "current") {
|
|
||||||
saveWorkspace(ws);
|
|
||||||
rememberNow(ws);
|
|
||||||
pushState();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
const want = initialWorkspace(root, found.entry).folders;
|
|
||||||
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
|
|
||||||
const kept = new Set();
|
|
||||||
const folders = [];
|
|
||||||
const changes = [];
|
|
||||||
for (const w of want) {
|
|
||||||
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
|
|
||||||
if (!have) {
|
|
||||||
folders.push({ ...w, id: "pending" });
|
|
||||||
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
kept.add(have);
|
|
||||||
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
|
|
||||||
if ((have.description || "") !== (w.description || "")) {
|
|
||||||
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
|
|
||||||
}
|
|
||||||
folders.push({ ...have, name: w.name, description: w.description || "" });
|
|
||||||
}
|
|
||||||
for (const f of ws.folders) {
|
|
||||||
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
|
|
||||||
}
|
|
||||||
ws.folders = folders.filter((f) => f.id !== "pending");
|
|
||||||
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
|
|
||||||
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
|
|
||||||
if (!changes.length) {
|
|
||||||
saveWorkspace(ws);
|
|
||||||
pushState();
|
|
||||||
}
|
|
||||||
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
|
|
||||||
checkFolders(ws);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
|
|
||||||
// learns its spec late) takes the workspace with it.
|
|
||||||
function followSpecDir(state) {
|
|
||||||
const spec = specKey(state && state.specDir);
|
|
||||||
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
|
|
||||||
const ws = workspaceNow();
|
|
||||||
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
|
|
||||||
}
|
|
||||||
|
|
||||||
function isFolder(p) {
|
function isFolder(p) {
|
||||||
try {
|
try {
|
||||||
return fs.statSync(p).isDirectory();
|
return fs.statSync(p).isDirectory();
|
||||||
@@ -461,10 +370,10 @@ function checkFolders(ws) {
|
|||||||
const marked = ws.missing.includes(f.id);
|
const marked = ws.missing.includes(f.id);
|
||||||
if (!there && !marked) {
|
if (!there && !marked) {
|
||||||
ws.missing = [...ws.missing, f.id];
|
ws.missing = [...ws.missing, f.id];
|
||||||
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
|
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path });
|
||||||
} else if (there && marked) {
|
} else if (there && marked) {
|
||||||
ws.missing = ws.missing.filter((id) => id !== f.id);
|
ws.missing = ws.missing.filter((id) => id !== f.id);
|
||||||
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
|
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -493,8 +402,8 @@ function folderIssues(entries) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function workspaceView() {
|
function workspaceView() {
|
||||||
const { folders, missing, remote, scope } = workspaceNow();
|
const { folders, missing, remote } = workspaceNow();
|
||||||
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ledgerEntries()) };
|
return { folders, missing: missing || [], remote: remote || "", issues: folderIssues(ledgerEntries()) };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Whether child sits strictly under parent.
|
// Whether child sits strictly under parent.
|
||||||
@@ -583,7 +492,6 @@ function bootWorkspace() {
|
|||||||
saveWorkspace(ws);
|
saveWorkspace(ws);
|
||||||
}
|
}
|
||||||
checkFolders(ws);
|
checkFolders(ws);
|
||||||
followSpecDir(stateNow);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -609,48 +517,6 @@ function ensureConversation(state) {
|
|||||||
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------ subagents */
|
|
||||||
|
|
||||||
// subagents-setting.json has one writer, this server, and the agent hears of
|
|
||||||
// it only through what console.mjs reads there; events.ndjson's latest `open`
|
|
||||||
// says whether the agent's console copy can carry it. Both re-read only when
|
|
||||||
// their file has moved.
|
|
||||||
const SUBAGENTS_SETTING_PATH = path.join(DIR, SUBAGENTS_SETTING_FILE);
|
|
||||||
const EVENTS_PATH = path.join(DIR, "events.ndjson");
|
|
||||||
|
|
||||||
let subagentSettingSeen = { stamp: null, setting: null };
|
|
||||||
function subagentSettingNow() {
|
|
||||||
const stamp = fileStamp(SUBAGENTS_SETTING_PATH);
|
|
||||||
if (stamp !== subagentSettingSeen.stamp) subagentSettingSeen = { stamp, setting: readSubagentSetting(DIR) };
|
|
||||||
return subagentSettingSeen.setting;
|
|
||||||
}
|
|
||||||
|
|
||||||
let capsSeen = { stamp: null, caps: [] };
|
|
||||||
function openCapsNow() {
|
|
||||||
const stamp = fileStamp(EVENTS_PATH);
|
|
||||||
if (stamp !== capsSeen.stamp) capsSeen = { stamp, caps: latestOpenCaps(DIR) };
|
|
||||||
return capsSeen.caps;
|
|
||||||
}
|
|
||||||
|
|
||||||
const sameSetting = (a, b) => a.workflow === b.workflow && a.on === b.on && a.instruction === b.instruction && a.max === b.max;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Turn the per-project store into this session's setting, for the workflow
|
|
||||||
* the session is in now. The only place that happens (FR-7): a session an
|
|
||||||
* older server ran has no setting file, so nothing is ever injected into it.
|
|
||||||
* A record that already matches is left alone, revision and all, so a
|
|
||||||
* restart alone never re-tells the agent anything.
|
|
||||||
*/
|
|
||||||
function syncSubagentSetting(state) {
|
|
||||||
if (!state || typeof state.workflow !== "string") return;
|
|
||||||
const { workflow } = state;
|
|
||||||
const { on, instruction, max } = offered(workflow) ? subagentStoreEntry(sessionWorktree(), workflow) : defaultSetting(workflow);
|
|
||||||
const target = { workflow, on, instruction, max };
|
|
||||||
const current = readSubagentSetting(DIR);
|
|
||||||
if (current && sameSetting(current, target)) return;
|
|
||||||
writeSubagentSetting(DIR, { ...target, revision: (current ? current.revision : 0) + 1 });
|
|
||||||
}
|
|
||||||
|
|
||||||
// What the page needs to draw itself, in the shape of the SSE state frame.
|
// What the page needs to draw itself, in the shape of the SSE state frame.
|
||||||
// `have` names that exact view, for the page to hand back when it opens its
|
// `have` names that exact view, for the page to hand back when it opens its
|
||||||
// stream (see /events).
|
// stream (see /events).
|
||||||
@@ -665,33 +531,19 @@ function stateFrame(state) {
|
|||||||
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
||||||
workspace: workspaceView(),
|
workspace: workspaceView(),
|
||||||
meter: meterView(ledgerEntries()),
|
meter: meterView(ledgerEntries()),
|
||||||
subagents: subagentsView(state),
|
|
||||||
...(updateInfo ? { update: updateInfo } : {}),
|
|
||||||
have: haveKey(),
|
have: haveKey(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// The page shows the switch only when `offered && supported` (FR-3); the
|
|
||||||
// frame says both and leaves combining them to the page. `instruction: null`
|
|
||||||
// is the shipped default, which the page reads from subagents.js itself.
|
|
||||||
function subagentsView(state) {
|
|
||||||
const workflow = state && state.workflow;
|
|
||||||
const { on, instruction, max, revision } = subagentSettingNow() || { ...defaultSetting(workflow), revision: 0 };
|
|
||||||
return { offered: offered(workflow), supported: openCapsNow().includes("subagents"), on, instruction, max, revision };
|
|
||||||
}
|
|
||||||
|
|
||||||
function haveKey() {
|
function haveKey() {
|
||||||
const { pending, stop } = resultFlags();
|
const { pending, stop } = resultFlags();
|
||||||
chatEntries();
|
chatEntries();
|
||||||
chatPickedUp();
|
chatPickedUp();
|
||||||
workspaceNow();
|
workspaceNow();
|
||||||
ledgerEntries();
|
ledgerEntries();
|
||||||
subagentSettingNow();
|
|
||||||
openCapsNow();
|
|
||||||
return (
|
return (
|
||||||
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
|
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
|
||||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
|
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
|
||||||
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -716,12 +568,6 @@ function recordSubmitted(state, actions) {
|
|||||||
if (action.type === "comment") {
|
if (action.type === "comment") {
|
||||||
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
|
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
|
||||||
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
|
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
|
||||||
// The person's side of the Notes thread. Left to the agent it was never
|
|
||||||
// written, so a question asked in a note vanished once it was picked up
|
|
||||||
// and the reply under it answered nothing on the page.
|
|
||||||
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
|
|
||||||
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
|
|
||||||
}
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const { i, type, ...rest } = action;
|
const { i, type, ...rest } = action;
|
||||||
@@ -1007,38 +853,6 @@ function pushState() {
|
|||||||
if (stateNow) broadcast("state", stateFrame(stateNow));
|
if (stateNow) broadcast("state", stateFrame(stateNow));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------- update check */
|
|
||||||
|
|
||||||
// The version this console was installed as: install.js writes version.json
|
|
||||||
// beside console.mjs; a dev checkout falls back to the repo root's.
|
|
||||||
function installedVersion() {
|
|
||||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
|
||||||
const version = readJson(file, {}).version;
|
|
||||||
if (typeof version === "string" && version) return version;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filled in once the boot-time check answers; until then, and whenever it
|
|
||||||
// fails, the frame carries no `update` and the page shows no banner.
|
|
||||||
let updateInfo = null;
|
|
||||||
let updateLatest = null;
|
|
||||||
|
|
||||||
// Started at boot and never awaited: git may take up to its 10 s limit, and
|
|
||||||
// nothing the person sees waits on it. The catch is not optional: a throw in
|
|
||||||
// pushState() would otherwise be an unhandled rejection, which ends the server.
|
|
||||||
function startUpdateCheck() {
|
|
||||||
const installed = installedVersion();
|
|
||||||
if (!installed) return;
|
|
||||||
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
|
|
||||||
.then((result) => {
|
|
||||||
updateLatest = result?.latest ?? null;
|
|
||||||
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
|
|
||||||
if (updateInfo) pushState();
|
|
||||||
})
|
|
||||||
.catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
let agentSeenAt = Date.now();
|
let agentSeenAt = Date.now();
|
||||||
function agentLastSeen() {
|
function agentLastSeen() {
|
||||||
return new Date(agentSeenAt).toISOString();
|
return new Date(agentSeenAt).toISOString();
|
||||||
@@ -1145,8 +959,10 @@ const server = http.createServer((req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (pathname === "/version" && req.method === "GET") {
|
if (pathname === "/version" && req.method === "GET") {
|
||||||
const version = installedVersion();
|
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||||
if (version) return json(res, 200, { version, latest: updateLatest });
|
const version = readJson(file, {}).version;
|
||||||
|
if (typeof version === "string" && version) return json(res, 200, { version });
|
||||||
|
}
|
||||||
return json(res, 404, { error: "no version" });
|
return json(res, 404, { error: "no version" });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1194,7 +1010,7 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/draft" && req.method === "POST") {
|
if (pathname === "/draft" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (err, body) => {
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||||
// Debounced client-side; this is just the durable mirror. Twenty minutes
|
// Debounced client-side; this is just the durable mirror. Twenty minutes
|
||||||
// of someone's structured answers must not die with a closed tab.
|
// of someone's structured answers must not die with a closed tab.
|
||||||
try {
|
try {
|
||||||
@@ -1219,7 +1035,7 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/looks" && req.method === "POST") {
|
if (pathname === "/looks" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (err, body) => {
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||||
// `set` carries only the keys one tab changed, merged onto what is on
|
// `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.
|
// disk, so a tab holding stale settings cannot undo another tab's change.
|
||||||
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
|
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
|
||||||
@@ -1235,39 +1051,6 @@ const server = http.createServer((req, res) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Subagents switch for the session's workflow. Saved per project folder
|
|
||||||
// for the next session, and applied to this one with a bumped revision, which
|
|
||||||
// is what console.mjs hands the agent at its next pickup. Never blocked by,
|
|
||||||
// and never blocking, a card send.
|
|
||||||
if (pathname === "/subagents" && req.method === "POST") {
|
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
|
||||||
return readBody(req, (err, body) => {
|
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
|
||||||
const state = readState();
|
|
||||||
if (!state || !offered(state.workflow)) return json(res, 400, { error: "not-offered" });
|
|
||||||
const clean = cleanSetting(body);
|
|
||||||
if (clean.error) return json(res, 400, { error: clean.error });
|
|
||||||
const { on, instruction, max } = clean;
|
|
||||||
const current = readSubagentSetting(DIR);
|
|
||||||
const next = { workflow: state.workflow, on, instruction, max };
|
|
||||||
// The store is per project, so another session may have moved it since
|
|
||||||
// this one synced: it always takes the person's latest pick. Only a
|
|
||||||
// real change to this session's setting bumps what the agent hears.
|
|
||||||
const unchanged = Boolean(current && sameSetting(current, next));
|
|
||||||
try {
|
|
||||||
saveSubagentStoreEntry(sessionWorktree(), state.workflow, { on, instruction, max });
|
|
||||||
if (!unchanged) writeSubagentSetting(DIR, { ...next, revision: (current ? current.revision : 0) + 1 });
|
|
||||||
} catch (e) {
|
|
||||||
return json(res, 500, { error: String(e.message) });
|
|
||||||
}
|
|
||||||
if (unchanged) return json(res, 200, { ok: true, setting: current });
|
|
||||||
const setting = readSubagentSetting(DIR);
|
|
||||||
appendEvent(DIR, { type: "subagents", on, revision: setting.revision });
|
|
||||||
pushState();
|
|
||||||
return json(res, 200, { ok: true, setting });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// The launcher's model menu: what ships (read-only here) and what the user added.
|
// The launcher's model menu: what ships (read-only here) and what the user added.
|
||||||
if (pathname === "/models" && req.method === "GET") {
|
if (pathname === "/models" && req.method === "GET") {
|
||||||
const saved = readJson(USER_MODELS_FILE, null) || {};
|
const saved = readJson(USER_MODELS_FILE, null) || {};
|
||||||
@@ -1278,7 +1061,7 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/models" && req.method === "POST") {
|
if (pathname === "/models" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (err, body) => {
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||||
const { models, error } = cleanModels(body && body.models);
|
const { models, error } = cleanModels(body && body.models);
|
||||||
if (error) return json(res, 400, { error });
|
if (error) return json(res, 400, { error });
|
||||||
try {
|
try {
|
||||||
@@ -1291,24 +1074,6 @@ const server = http.createServer((req, res) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
|
|
||||||
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
|
|
||||||
// still finds. Never this session, never a path the page sent.
|
|
||||||
if (pathname === "/cleanup" && req.method === "POST") {
|
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
|
||||||
return readBody(req, (err, body) => {
|
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
|
||||||
if (body && Array.isArray(body.delete)) {
|
|
||||||
return removeCleanup(body.delete, { skipSid: SID })
|
|
||||||
.then((done) => json(res, 200, { ok: true, ...done }))
|
|
||||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
|
||||||
}
|
|
||||||
return cleanupFindings({ skipSid: SID })
|
|
||||||
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
|
|
||||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pathname === "/upload" && req.method === "POST") {
|
if (pathname === "/upload" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
const contentType = String(req.headers["content-type"] || "");
|
const contentType = String(req.headers["content-type"] || "");
|
||||||
@@ -1415,7 +1180,7 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/submit" && req.method === "POST") {
|
if (pathname === "/submit" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (err, body) => {
|
||||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||||
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
|
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
|
||||||
return json(res, 400, { error: "actions must be a non-empty array" });
|
return json(res, 400, { error: "actions must be a non-empty array" });
|
||||||
}
|
}
|
||||||
@@ -1496,9 +1261,6 @@ const server = http.createServer((req, res) => {
|
|||||||
try {
|
try {
|
||||||
ensureConversation(written.state);
|
ensureConversation(written.state);
|
||||||
} catch {}
|
} catch {}
|
||||||
try {
|
|
||||||
syncSubagentSetting(written.state);
|
|
||||||
} catch {}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Name the items that went. A page with OTHER answers staged should drop
|
// Name the items that went. A page with OTHER answers staged should drop
|
||||||
@@ -1519,7 +1281,6 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/chat" && req.method === "POST") {
|
if (pathname === "/chat" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (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 (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||||
const state = readState() || {};
|
const state = readState() || {};
|
||||||
const current = currentConversation(chatEntries()).conversation;
|
const current = currentConversation(chatEntries()).conversation;
|
||||||
@@ -1583,7 +1344,6 @@ const server = http.createServer((req, res) => {
|
|||||||
if (pathname === "/chat/decision" && req.method === "POST") {
|
if (pathname === "/chat/decision" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (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 (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" });
|
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
|
||||||
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
|
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
|
||||||
@@ -1632,7 +1392,6 @@ const server = http.createServer((req, res) => {
|
|||||||
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
|
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
return readBody(req, (err, body) => {
|
return readBody(req, (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 (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||||
let answer;
|
let answer;
|
||||||
try {
|
try {
|
||||||
@@ -1644,25 +1403,6 @@ const server = http.createServer((req, res) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Which list the workspace is: a spec's, or the project's (`spec` empty).
|
|
||||||
// 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.
|
|
||||||
if (pathname === "/workspace/scope" && req.method === "POST") {
|
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
|
||||||
return readBody(req, (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 : "";
|
|
||||||
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
|
|
||||||
try {
|
|
||||||
setScope(workspaceNow(), spec, "project");
|
|
||||||
} catch (e) {
|
|
||||||
return json(res, 500, { error: String(e.message) });
|
|
||||||
}
|
|
||||||
return json(res, 200, workspaceView());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only ever returns a path: the page then adds it through /workspace/add.
|
// Only ever returns a path: the page then adds it through /workspace/add.
|
||||||
if (pathname === "/workspace/browse" && req.method === "POST") {
|
if (pathname === "/workspace/browse" && req.method === "POST") {
|
||||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||||
@@ -1751,19 +1491,15 @@ function readBody(req, cb) {
|
|||||||
let tooBig = false;
|
let tooBig = false;
|
||||||
req.on("data", (c) => {
|
req.on("data", (c) => {
|
||||||
size += c.length;
|
size += c.length;
|
||||||
// Drain past the cap rather than destroy, exactly like readRaw: a
|
|
||||||
// destroyed request emits 'close', never 'end' or 'error', so cb would
|
|
||||||
// never run and the page would see a reset instead of the 413 that names
|
|
||||||
// the problem.
|
|
||||||
if (size > MAX_BODY) {
|
if (size > MAX_BODY) {
|
||||||
tooBig = true;
|
tooBig = true;
|
||||||
chunks.length = 0;
|
req.destroy();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
chunks.push(c);
|
chunks.push(c);
|
||||||
});
|
});
|
||||||
req.on("end", () => {
|
req.on("end", () => {
|
||||||
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
|
if (tooBig) return cb(new Error("too large"));
|
||||||
try {
|
try {
|
||||||
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -1825,12 +1561,6 @@ function checkState() {
|
|||||||
try {
|
try {
|
||||||
ensureConversation(parsed);
|
ensureConversation(parsed);
|
||||||
} catch {}
|
} catch {}
|
||||||
try {
|
|
||||||
syncSubagentSetting(parsed);
|
|
||||||
} catch {}
|
|
||||||
try {
|
|
||||||
followSpecDir(parsed);
|
|
||||||
} catch {}
|
|
||||||
pushState();
|
pushState();
|
||||||
}
|
}
|
||||||
lastStateStamp = stamp;
|
lastStateStamp = stamp;
|
||||||
@@ -2002,13 +1732,7 @@ function onListening(port) {
|
|||||||
try {
|
try {
|
||||||
bootWorkspace();
|
bootWorkspace();
|
||||||
} catch {}
|
} catch {}
|
||||||
try {
|
|
||||||
syncSubagentSetting(readState());
|
|
||||||
} catch {}
|
|
||||||
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
||||||
try {
|
|
||||||
startUpdateCheck();
|
|
||||||
} catch {}
|
|
||||||
try {
|
try {
|
||||||
process.send?.({ type: "listening", port });
|
process.send?.({ type: "listening", port });
|
||||||
} catch {}
|
} catch {}
|
||||||
|
|||||||
@@ -1,138 +0,0 @@
|
|||||||
// Plan2Code Web Console - is a newer Plan2Code release out?
|
|
||||||
//
|
|
||||||
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
|
|
||||||
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
|
|
||||||
// release tag is "latest". The server
|
|
||||||
// starts this at boot and never waits on it; the answer, failures included, is
|
|
||||||
// cached for an hour so a burst of sessions asks GitHub once.
|
|
||||||
//
|
|
||||||
// Nothing here reads, stores or sends a credential: git authenticates itself,
|
|
||||||
// with every prompt turned off so a missing login fails fast instead of
|
|
||||||
// opening a window nobody asked for.
|
|
||||||
//
|
|
||||||
// Node built-ins only.
|
|
||||||
|
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { spawn } from "node:child_process";
|
|
||||||
|
|
||||||
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
|
|
||||||
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
|
||||||
export const CACHE_MS = 60 * 60 * 1000;
|
|
||||||
|
|
||||||
const SEMVER = /^\d+\.\d+\.\d+$/;
|
|
||||||
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
|
|
||||||
|
|
||||||
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
|
|
||||||
export function compareVersions(a, b) {
|
|
||||||
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
|
|
||||||
const x = a.split(".").map(Number);
|
|
||||||
const y = b.split(".").map(Number);
|
|
||||||
for (let i = 0; i < 3; i++) {
|
|
||||||
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
|
|
||||||
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
|
|
||||||
* pre-releases or other tag names are ignored. Null when nothing matches.
|
|
||||||
*/
|
|
||||||
export function latestTag(text) {
|
|
||||||
if (typeof text !== "string") return null;
|
|
||||||
let best = null;
|
|
||||||
for (const line of text.split(/\r?\n/)) {
|
|
||||||
const m = TAG_REF.exec(line.trim());
|
|
||||||
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
|
|
||||||
}
|
|
||||||
return best;
|
|
||||||
}
|
|
||||||
|
|
||||||
function readCache(cacheFile, now) {
|
|
||||||
try {
|
|
||||||
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
|
|
||||||
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
|
|
||||||
return typeof cached.latest === "string" ? cached.latest : null;
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function writeCache(cacheFile, data) {
|
|
||||||
const tmp = cacheFile + "." + process.pid + ".tmp";
|
|
||||||
try {
|
|
||||||
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
|
|
||||||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
|
|
||||||
fs.renameSync(tmp, cacheFile);
|
|
||||||
} catch {
|
|
||||||
try {
|
|
||||||
fs.rmSync(tmp, { force: true });
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
|
|
||||||
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
|
|
||||||
* window, no prompt.
|
|
||||||
*/
|
|
||||||
export function runLsRemote({ timeoutMs = 10000 } = {}) {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
let settled = false;
|
|
||||||
const done = (value) => {
|
|
||||||
if (settled) return;
|
|
||||||
settled = true;
|
|
||||||
clearTimeout(timer);
|
|
||||||
resolve(value);
|
|
||||||
};
|
|
||||||
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
|
|
||||||
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
|
|
||||||
let child;
|
|
||||||
try {
|
|
||||||
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
|
|
||||||
shell: false,
|
|
||||||
windowsHide: true,
|
|
||||||
stdio: ["ignore", "pipe", "ignore"],
|
|
||||||
env,
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
return resolve(null);
|
|
||||||
}
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
try {
|
|
||||||
child.kill();
|
|
||||||
} catch {}
|
|
||||||
done(null);
|
|
||||||
}, timeoutMs);
|
|
||||||
timer.unref?.();
|
|
||||||
let out = "";
|
|
||||||
child.stdout.setEncoding("utf8");
|
|
||||||
child.stdout.on("data", (chunk) => {
|
|
||||||
out += chunk;
|
|
||||||
});
|
|
||||||
child.on("error", () => done(null));
|
|
||||||
child.on("close", (code) => done(code === 0 ? out : null));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether `installed` is behind the newest release: `{ installed, latest,
|
|
||||||
* updateAvailable }`, or null when either version is unknown. Reuses a cache
|
|
||||||
* under an hour old, and caches a failed lookup as `latest: null` so it is
|
|
||||||
* not retried until the hour is up. Never throws.
|
|
||||||
*/
|
|
||||||
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
|
|
||||||
try {
|
|
||||||
let latest = readCache(cacheFile, now);
|
|
||||||
if (latest === undefined) {
|
|
||||||
latest = latestTag(await run());
|
|
||||||
writeCache(cacheFile, { checkedAt: now, latest });
|
|
||||||
}
|
|
||||||
const order = compareVersions(installed, latest);
|
|
||||||
if (latest === null || order === null) return null;
|
|
||||||
return { installed, latest, updateAvailable: order < 0 };
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "Plan2Code",
|
"name": "Plan2Code",
|
||||||
"version": "2.5.0",
|
"version": "2.4.1",
|
||||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"ai",
|
"ai",
|
||||||
@@ -17,6 +17,6 @@
|
|||||||
"url": "https://github.com/jparkerweb/plan2code"
|
"url": "https://github.com/jparkerweb/plan2code"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||||
"releaseDate": "2026-10-06",
|
"releaseDate": "2026-10-02",
|
||||||
"mode": "utility"
|
"mode": "utility"
|
||||||
}
|
}
|
||||||
@@ -1,247 +0,0 @@
|
|||||||
// Plan2Code skill scripts: shared plumbing.
|
|
||||||
//
|
|
||||||
// Every script in a skill's scripts/ directory imports this file. It owns the
|
|
||||||
// conventions the SKILL.md prompts rely on, so they are identical everywhere:
|
|
||||||
//
|
|
||||||
// stdout one JSON object, always. `{ "ok": true, ... }` on success,
|
|
||||||
// `{ "ok": false, "error": "<code>", "message": "...", "next": "..." }`
|
|
||||||
// on a handled failure.
|
|
||||||
// stderr a one-line human diagnostic on failure (the same message + next).
|
|
||||||
// exit 0 ok · 1 unexpected crash · 2 bad arguments · 3 not found ·
|
|
||||||
// 4 invalid input or a check that failed · 5 refused (would clobber
|
|
||||||
// or break a rule).
|
|
||||||
//
|
|
||||||
// Node 18+ built-ins only, no build step: this ships inside every skill.
|
|
||||||
|
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
||||||
|
|
||||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
||||||
|
|
||||||
export const EXIT = { OK: 0, CRASH: 1, USAGE: 2, NOT_FOUND: 3, INVALID: 4, REFUSED: 5 };
|
|
||||||
|
|
||||||
export class CliError extends Error {
|
|
||||||
constructor(exit, error, message, next) {
|
|
||||||
super(message);
|
|
||||||
this.exit = exit;
|
|
||||||
this.error = error;
|
|
||||||
this.next = next;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Throw a handled failure: the run() wrapper prints it and sets the exit code. */
|
|
||||||
export function fail(exit, error, message, next) {
|
|
||||||
throw new CliError(exit, error, message, next);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function out(obj) {
|
|
||||||
process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse argv into { _: positionals, <flag>: value }.
|
|
||||||
* `booleans` names flags that take no value; every other `--flag` takes the
|
|
||||||
* next argument, and repeats of a flag listed in `lists` collect into an array.
|
|
||||||
* `--flag=value` works too. Unknown flags are a usage error, so a typo never
|
|
||||||
* silently changes behavior.
|
|
||||||
*/
|
|
||||||
export function parseArgs(argv, { booleans = [], values = [], lists = [] } = {}) {
|
|
||||||
const known = new Set([...booleans, ...values, ...lists, "help"]);
|
|
||||||
const args = { _: [] };
|
|
||||||
for (let i = 0; i < argv.length; i++) {
|
|
||||||
const a = argv[i];
|
|
||||||
if (!a.startsWith("--")) {
|
|
||||||
args._.push(a);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let name = a.slice(2);
|
|
||||||
let value;
|
|
||||||
const eq = name.indexOf("=");
|
|
||||||
if (eq !== -1) {
|
|
||||||
value = name.slice(eq + 1);
|
|
||||||
name = name.slice(0, eq);
|
|
||||||
}
|
|
||||||
if (!known.has(name)) {
|
|
||||||
fail(EXIT.USAGE, "unknown-flag", `Unknown flag --${name}.`, "Run with --help for the flags this script takes.");
|
|
||||||
}
|
|
||||||
if (name === "help" || booleans.includes(name)) {
|
|
||||||
args[name] = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (value === undefined) {
|
|
||||||
if (i + 1 >= argv.length) {
|
|
||||||
fail(EXIT.USAGE, "missing-value", `--${name} needs a value.`, "Run with --help for usage.");
|
|
||||||
}
|
|
||||||
value = argv[++i];
|
|
||||||
}
|
|
||||||
if (lists.includes(name)) (args[name] ||= []).push(value);
|
|
||||||
else args[name] = value;
|
|
||||||
}
|
|
||||||
return args;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Run a script's main(). Prints usage on --help, turns CliError into the JSON
|
|
||||||
* failure shape plus an exit code, and anything else into exit 1 with the stack
|
|
||||||
* on stderr. Sets process.exitCode rather than calling process.exit(), so
|
|
||||||
* stdout is never cut off mid-write.
|
|
||||||
*/
|
|
||||||
export async function run(usage, main) {
|
|
||||||
try {
|
|
||||||
const argv = process.argv.slice(2);
|
|
||||||
if (argv.includes("--help") || argv.includes("-h")) {
|
|
||||||
process.stdout.write(usage.trim() + "\n");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await main(argv);
|
|
||||||
} catch (err) {
|
|
||||||
if (err instanceof CliError) {
|
|
||||||
out({ ok: false, error: err.error, message: err.message, ...(err.next ? { next: err.next } : {}) });
|
|
||||||
process.stderr.write(`error: ${err.message}${err.next ? `\nnext: ${err.next}` : ""}\n`);
|
|
||||||
process.exitCode = err.exit;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
process.stderr.write(`unexpected error: ${err && err.stack ? err.stack : err}\n`);
|
|
||||||
out({ ok: false, error: "crash", message: String(err && err.message ? err.message : err) });
|
|
||||||
process.exitCode = EXIT.CRASH;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ time */
|
|
||||||
|
|
||||||
// PLAN2CODE_NOW ("YYYY-MM-DD HH:mm" or any Date-parsable string) pins the
|
|
||||||
// clock, for tests and for reproducing a run. Otherwise: the local clock, which
|
|
||||||
// is what "today" means to the person reading the date in their files.
|
|
||||||
export function now() {
|
|
||||||
const pinned = process.env.PLAN2CODE_NOW;
|
|
||||||
if (pinned) {
|
|
||||||
const m = pinned.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
|
|
||||||
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +(m[4] || 0), +(m[5] || 0), +(m[6] || 0));
|
|
||||||
const d = new Date(pinned);
|
|
||||||
if (!Number.isNaN(d.getTime())) return d;
|
|
||||||
}
|
|
||||||
return new Date();
|
|
||||||
}
|
|
||||||
|
|
||||||
const pad = (n) => String(n).padStart(2, "0");
|
|
||||||
|
|
||||||
/** YYYY-MM-DD */
|
|
||||||
export function isoDate(d = now()) {
|
|
||||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** YYYYMMDD */
|
|
||||||
export function compactDate(d = now()) {
|
|
||||||
return isoDate(d).replace(/-/g, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
/** YYYY-MM-DD HH:mm */
|
|
||||||
export function stamp(d = now()) {
|
|
||||||
return `${isoDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** HHMMSS */
|
|
||||||
export function clock(d = now()) {
|
|
||||||
return `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ----------------------------------------------------------------- files */
|
|
||||||
|
|
||||||
export function readText(file) {
|
|
||||||
try {
|
|
||||||
return fs.readFileSync(file, "utf8");
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isDir(p) {
|
|
||||||
try {
|
|
||||||
return fs.statSync(p).isDirectory();
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Write a file only when its content changes. Returns true when it wrote. */
|
|
||||||
export function writeIfChanged(file, content) {
|
|
||||||
const current = readText(file);
|
|
||||||
if (current === content) return false;
|
|
||||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
||||||
fs.writeFileSync(file, content);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Normalise line endings for parsing; keep the original for writing back. */
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Forward-slash path relative to root, for output the agent pastes into prompts. */
|
|
||||||
export function rel(root, p) {
|
|
||||||
return path.relative(root, p).split(path.sep).join("/") || ".";
|
|
||||||
}
|
|
||||||
|
|
||||||
/* --------------------------------------------------------- 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
|
|
||||||
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
|
|
||||||
// metrics-bait scan, so the scripts import it rather than keep a second copy.
|
|
||||||
const CONSOLE_LIB_CANDIDATES = [
|
|
||||||
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
|
|
||||||
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
|
|
||||||
];
|
|
||||||
|
|
||||||
let consoleLibPromise;
|
|
||||||
export function consoleLib() {
|
|
||||||
consoleLibPromise ||= (async () => {
|
|
||||||
for (const candidate of CONSOLE_LIB_CANDIDATES) {
|
|
||||||
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
|
|
||||||
}
|
|
||||||
fail(
|
|
||||||
EXIT.NOT_FOUND,
|
|
||||||
"console-lib-missing",
|
|
||||||
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
|
|
||||||
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
|
|
||||||
);
|
|
||||||
})();
|
|
||||||
return consoleLibPromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The version these scripts shipped with (scripts/version.json, or the repo's). */
|
|
||||||
export function version() {
|
|
||||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
|
||||||
const text = readText(file);
|
|
||||||
if (!text) continue;
|
|
||||||
try {
|
|
||||||
const v = JSON.parse(text).version;
|
|
||||||
if (typeof v === "string") return v;
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -1,676 +0,0 @@
|
|||||||
#!/usr/bin/env node
|
|
||||||
// specs.mjs: where every spec under specs/ stands, read from its files.
|
|
||||||
//
|
|
||||||
// The pipeline skills (plan, document, implement, revise-plan, finalize,
|
|
||||||
// review, handoff) all need the same filesystem facts: which specs exist, what
|
|
||||||
// a spec's PLAN-DRAFT says, which phases are open, how many tasks are done.
|
|
||||||
// Those have one correct answer, so this script computes them instead of each
|
|
||||||
// prompt re-deriving them by hand. It also performs the two mechanical writes
|
|
||||||
// (a Phase Checklist marker, the archive move), with --dry-run.
|
|
||||||
//
|
|
||||||
// Shell listing only matters to people: specs/ is gitignored, so editor search
|
|
||||||
// tools skip it. This script reads the disk directly and does not care.
|
|
||||||
|
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, consoleLib, isoDate, phaseFiles } from "./common.mjs";
|
|
||||||
|
|
||||||
const USAGE = `
|
|
||||||
specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
|
|
||||||
|
|
||||||
node specs.mjs list [--root <dir>]
|
|
||||||
Every active spec under specs/ (never specs--completed/), newest first:
|
|
||||||
state, detail, PLAN-DRAFT files with their **Status:** line, overview,
|
|
||||||
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
|
|
||||||
Groups, per-phase task counts by marker, task-numbering problems,
|
|
||||||
completion, the implement phase-selection verdict ("next"), the pending
|
|
||||||
phases, and consistency checks. <spec> is specs/<name>, <name>, or a path
|
|
||||||
to its overview.md.
|
|
||||||
|
|
||||||
node specs.mjs metrics <spec> --step document|finalize [--set key=value ...]
|
|
||||||
The METRICS_JSON comment for that step, countable fields computed from
|
|
||||||
the files; judgment fields come from --set (numbers only).
|
|
||||||
document: total_tasks, tasks_per_phase, phase_count,
|
|
||||||
parallel_groups_identified computed; pass
|
|
||||||
--set verification_items_added=N (your Verification Summary's
|
|
||||||
Added total; the VERIFICATION comments are reported as a check).
|
|
||||||
finalize: completion_rate_at_audit, tasks_completed, tasks_total; pass
|
|
||||||
--set verification_failures_found=N
|
|
||||||
--set documentation_updates_needed=N.
|
|
||||||
|
|
||||||
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
|
|
||||||
Status line. Refuses a phase with duplicate checklist rows, and refuses
|
|
||||||
in-progress -> open (started work stays marked).
|
|
||||||
|
|
||||||
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/.
|
|
||||||
|
|
||||||
Markers: [ ] pending · [/] in progress · [x] complete · [!] blocked · [?] assumed.
|
|
||||||
Exit: 0 ok · 2 bad arguments · 3 spec not found · 4 cannot parse / check
|
|
||||||
failed · 5 refused.
|
|
||||||
`;
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------- resolving */
|
|
||||||
|
|
||||||
function realOrResolved(p) {
|
|
||||||
try {
|
|
||||||
return fs.realpathSync.native(p);
|
|
||||||
} catch {
|
|
||||||
return path.resolve(p);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const samePath = (a, b) => (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
|
|
||||||
|
|
||||||
// Read-only commands (status, metrics) accept an archived spec, because
|
|
||||||
// Finalize reads its own spec after Step 6 moved it. Writes never do.
|
|
||||||
function resolveSpec(root, arg, { allowArchived = false } = {}) {
|
|
||||||
if (!arg) fail(EXIT.USAGE, "missing-spec", "Name the spec: specs/<name>, <name>, or its overview.md path.", "Run `specs.mjs list` to see the active specs.");
|
|
||||||
let p = arg.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
||||||
if (/\/overview\.md$/i.test(p) || /\/phase-[^/]*\.md$/i.test(p)) p = p.replace(/\/[^/]+$/, "");
|
|
||||||
const abs = path.isAbsolute(p) ? p : p.includes("/") ? path.join(root, p) : path.join(root, "specs", p);
|
|
||||||
const relPath = rel(root, abs);
|
|
||||||
if (!allowArchived && /(^|\/)specs--completed(\/|$)/.test(relPath)) {
|
|
||||||
fail(EXIT.REFUSED, "archived-spec", `${relPath} is archived; the pipeline only changes active specs under specs/.`, "Pick an active spec from `specs.mjs list`.");
|
|
||||||
}
|
|
||||||
// A spec is a folder directly under specs/ (or specs--completed/ for a read).
|
|
||||||
// Without this, `archive .` would move all of specs/ and `archive ./src` a
|
|
||||||
// source folder.
|
|
||||||
const homes = [path.join(root, "specs"), ...(allowArchived ? [path.join(root, "specs--completed")] : [])].map(realOrResolved);
|
|
||||||
const parent = realOrResolved(path.dirname(path.resolve(abs)));
|
|
||||||
if (!homes.some((h) => samePath(h, parent))) {
|
|
||||||
fail(EXIT.REFUSED, "not-a-spec", `${relPath} is not a spec folder: a spec sits directly under specs/${allowArchived ? " (or specs--completed/)" : ""}.`, "Pass specs/<name> or <name>; run `specs.mjs list` to see the active specs.");
|
|
||||||
}
|
|
||||||
if (!isDir(abs)) {
|
|
||||||
fail(EXIT.NOT_FOUND, "spec-not-found", `No spec folder at ${relPath}.`, "Run `specs.mjs list` from the project root (or pass --root) to see the active specs.");
|
|
||||||
}
|
|
||||||
return { dir: abs, rel: relPath, name: path.basename(abs) };
|
|
||||||
}
|
|
||||||
|
|
||||||
/* -------------------------------------------------------------- parsing */
|
|
||||||
|
|
||||||
const MARKERS = { " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" };
|
|
||||||
// Task 2.3, a lettered sub-task 3.6a, or a named one such as a testing task 1.T.
|
|
||||||
const TASK_RE = /^\s*[-*] \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
|
|
||||||
const CHECKBOX_RE = /^\s*[-*] \[(.)\]/;
|
|
||||||
// The Status line in any of the forms people write it: **Status:**, **Status**:
|
|
||||||
// or a plain Status:, optionally as a list item. Groups: everything up to the
|
|
||||||
// value (kept as written when the value is rewritten), the value, trailing blanks.
|
|
||||||
const STATUS_RE = /^([ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*)(.+?)([ \t]*)$/m;
|
|
||||||
|
|
||||||
function statusOf(text) {
|
|
||||||
const m = (text || "").match(STATUS_RE);
|
|
||||||
return m ? m[2] : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A markdown section's lines: from its heading to the next heading of the same or higher level. */
|
|
||||||
function section(text, headingRe) {
|
|
||||||
const lines = text.split(/\r?\n/);
|
|
||||||
const start = lines.findIndex((l) => /^#{1,6}\s/.test(l) && headingRe.test(l));
|
|
||||||
if (start === -1) return null;
|
|
||||||
const level = lines[start].match(/^#+/)[0].length;
|
|
||||||
let end = lines.length;
|
|
||||||
for (let i = start + 1; i < lines.length; i++) {
|
|
||||||
const m = lines[i].match(/^(#+)\s/);
|
|
||||||
if (m && m[1].length <= level) {
|
|
||||||
end = i;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { start, end, lines: lines.slice(start + 1, end) };
|
|
||||||
}
|
|
||||||
|
|
||||||
function plainText(s) {
|
|
||||||
return s
|
|
||||||
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
|
|
||||||
.replace(/[*_`]/g, "")
|
|
||||||
.replace(/\s+/g, " ")
|
|
||||||
.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Phase Checklist rows: the first "Phase N" on each checkbox line names the phase. */
|
|
||||||
function parseChecklist(overview) {
|
|
||||||
const sec = section(overview, /Phase Checklist/i);
|
|
||||||
if (!sec) return { found: false, phases: [], unparsed: [] };
|
|
||||||
const phases = [];
|
|
||||||
const unparsed = [];
|
|
||||||
sec.lines.forEach((line, i) => {
|
|
||||||
const m = line.match(CHECKBOX_RE);
|
|
||||||
if (!m) return;
|
|
||||||
const text = plainText(line.replace(CHECKBOX_RE, ""));
|
|
||||||
const num = text.match(/\bPhase\s+(\d+)\b/i);
|
|
||||||
if (!num) {
|
|
||||||
unparsed.push({ line: sec.start + 2 + i, text: line.trim() });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const after = text.slice(num.index + num[0].length).replace(/^\s*[:\-–—]\s*/, "");
|
|
||||||
const name = after.split(/\s+[-–—]\s+|\s+\(|\s+_\(|:\s|\s+see\s+phase-/i)[0].replace(/\s*phase-\d+\.md\s*$/i, "").trim();
|
|
||||||
phases.push({
|
|
||||||
number: Number(num[1]),
|
|
||||||
marker: m[1],
|
|
||||||
state: MARKERS[m[1]] || "unknown",
|
|
||||||
name: name.replace(/\s*\[Milestone[^\]]*\]\s*$/i, "") || `Phase ${num[1]}`,
|
|
||||||
line: sec.start + 2 + i,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
return { found: true, phases, unparsed };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** "2, 3", "2-4" and "2–4" (or an em dash) alike: ranges expand, so a group cell never loses a phase. */
|
|
||||||
function phaseList(cell) {
|
|
||||||
const outList = [];
|
|
||||||
for (const part of cell.match(/\d+\s*[-–\u2014]\s*\d+|\d+/g) || []) {
|
|
||||||
const r = part.match(/^(\d+)\s*[-–\u2014]\s*(\d+)$/);
|
|
||||||
if (r && Number(r[2]) >= Number(r[1]) && Number(r[2]) - Number(r[1]) < 100) {
|
|
||||||
for (let n = Number(r[1]); n <= Number(r[2]); n++) outList.push(n);
|
|
||||||
} else outList.push(...part.match(/\d+/g).map(Number));
|
|
||||||
}
|
|
||||||
return [...new Set(outList)];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Parallel Execution Groups table: real groups only (a named group with 2+ phases). */
|
|
||||||
function parseGroups(overview) {
|
|
||||||
const sec = section(overview, /Parallel Execution Groups/i);
|
|
||||||
if (!sec) return { found: false, groups: [] };
|
|
||||||
const groups = [];
|
|
||||||
const seen = new Set();
|
|
||||||
for (const line of sec.lines) {
|
|
||||||
if (!/^\s*\|/.test(line) || /^\s*\|[\s:|-]+\|\s*$/.test(line)) continue;
|
|
||||||
const cells = line.split("|").slice(1, -1).map((c) => c.trim());
|
|
||||||
if (cells.length < 2 || /^group$/i.test(cells[0])) continue;
|
|
||||||
const id = plainText(cells[0]);
|
|
||||||
const phases = phaseList(cells[1]);
|
|
||||||
// "None", a dash, a single phase, a group its author labelled sequential
|
|
||||||
// ("A (sequential)"), or a Phases cell written as a chain ("1 → 2") is not
|
|
||||||
// a parallel group.
|
|
||||||
if (!id || /^(none|-|–|—)$/i.test(id) || /\bsequential\b/i.test(id) || /→|->|\bthen\b/i.test(cells[1]) || phases.length < 2) continue;
|
|
||||||
const key = `${id}:${phases.join(",")}`;
|
|
||||||
if (seen.has(key)) continue;
|
|
||||||
seen.add(key);
|
|
||||||
groups.push({ id, phases, reason: plainText(cells[2] || "") });
|
|
||||||
}
|
|
||||||
return { found: true, groups };
|
|
||||||
}
|
|
||||||
|
|
||||||
function firstSentence(text) {
|
|
||||||
const t = plainText(text);
|
|
||||||
const m = t.match(/^(.+?[.!?])(\s|$)/);
|
|
||||||
return (m ? m[1] : t).slice(0, 240);
|
|
||||||
}
|
|
||||||
|
|
||||||
function parsePhaseFile(file, number) {
|
|
||||||
const text = readText(file) || "";
|
|
||||||
const lines = text.split(/\r?\n/);
|
|
||||||
const title = (lines.find((l) => /^#\s/.test(l)) || "").replace(/^#\s+/, "").trim();
|
|
||||||
const status = statusOf(text);
|
|
||||||
const counts = { pending: 0, "in-progress": 0, complete: 0, blocked: 0, assumed: 0, unknown: 0 };
|
|
||||||
const tasks = [];
|
|
||||||
const strayCheckboxes = [];
|
|
||||||
const unmatchedTasks = [];
|
|
||||||
let heading = "";
|
|
||||||
lines.forEach((line, i) => {
|
|
||||||
const h = line.match(/^#{1,6}\s+(.*)$/);
|
|
||||||
if (h) heading = plainText(h[1]);
|
|
||||||
const t = line.match(TASK_RE);
|
|
||||||
if (t) {
|
|
||||||
const state = MARKERS[t[1]] || "unknown";
|
|
||||||
counts[state]++;
|
|
||||||
const named = !/^\d+$/.test(t[3]);
|
|
||||||
tasks.push({ id: `${t[2]}.${t[3]}${t[4]}`, phase: Number(t[2]), seq: named ? null : Number(t[3]), named, suffix: t[4], marker: t[1], state, line: i + 1 });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// A line that looks like a task but is not counted as one (Task 1.4A,
|
|
||||||
// "1. [ ] **Task", a non-bold "- [ ] Task 1.3") would make the audit undercount.
|
|
||||||
if (/^\s*(?:[-*]|\d+\.)\s+\[.\].*\bTask\s+\d+\./i.test(line)) unmatchedTasks.push({ line: i + 1, text: line.trim().slice(0, 120) });
|
|
||||||
if (CHECKBOX_RE.test(line)) strayCheckboxes.push({ line: i + 1, section: heading, text: line.trim().slice(0, 120) });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Numbering: every task belongs to this phase, the base numbers run 1..n with
|
|
||||||
// no gaps or repeats, and a lettered task (3.6a) sits after its base (3.6).
|
|
||||||
// Named tasks (1.T) are outside the numeric sequence.
|
|
||||||
const numbering = [];
|
|
||||||
const bases = [];
|
|
||||||
for (const t of tasks) {
|
|
||||||
if (t.phase !== number) numbering.push(`Task ${t.id} is in phase-${number}.md but numbered for Phase ${t.phase}`);
|
|
||||||
if (!t.suffix && !t.named) bases.push(t.seq);
|
|
||||||
}
|
|
||||||
const seenIds = new Set();
|
|
||||||
for (const t of tasks) {
|
|
||||||
if (seenIds.has(t.id)) numbering.push(`Task ${t.id} appears more than once`);
|
|
||||||
seenIds.add(t.id);
|
|
||||||
if (t.suffix && !t.named && !bases.includes(t.seq)) numbering.push(`Task ${t.id} has no base Task ${t.phase}.${t.seq}`);
|
|
||||||
}
|
|
||||||
bases.forEach((seq, i) => {
|
|
||||||
if (seq !== i + 1 && !numbering.some((n) => n.startsWith("Task numbering"))) {
|
|
||||||
numbering.push(`Task numbering is not sequential: expected ${number}.${i + 1}, found ${number}.${seq}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const overviewSec = section(text, /^#{1,6}\s+Overview\b/i);
|
|
||||||
const goalText = overviewSec ? overviewSec.lines.join("\n").split(/\n\s*\n/).map((p) => p.trim()).find((p) => p && !/^[-*|>]/.test(p)) : "";
|
|
||||||
return {
|
|
||||||
title,
|
|
||||||
status,
|
|
||||||
goal: goalText ? firstSentence(goalText) : null,
|
|
||||||
total: tasks.length,
|
|
||||||
counts,
|
|
||||||
open: counts.pending + counts["in-progress"] + counts.blocked + counts.unknown,
|
|
||||||
// Open work a phase cannot be approved over; blocked tasks may stand ([!] is allowed at sign-off).
|
|
||||||
unfinished: counts.pending + counts["in-progress"] + counts.unknown,
|
|
||||||
tasks,
|
|
||||||
numbering,
|
|
||||||
strayCheckboxes,
|
|
||||||
unmatchedTasks,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function planDrafts(dir) {
|
|
||||||
return fs
|
|
||||||
.readdirSync(dir)
|
|
||||||
.filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n))
|
|
||||||
.sort()
|
|
||||||
.map((file) => ({
|
|
||||||
file,
|
|
||||||
archived: /-prev\.md$/i.test(file),
|
|
||||||
status: statusOf(readText(path.join(dir, file))),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---------------------------------------------------------------- status */
|
|
||||||
|
|
||||||
function specStatus(spec) {
|
|
||||||
const overviewPath = path.join(spec.dir, "overview.md");
|
|
||||||
const overview = readText(overviewPath);
|
|
||||||
const files = phaseFiles(spec.dir);
|
|
||||||
// An empty overview.md still exists; only a missing one is "no overview".
|
|
||||||
const hasOverview = overview !== null;
|
|
||||||
const checklist = hasOverview ? parseChecklist(overview) : { found: false, phases: [], unparsed: [] };
|
|
||||||
const groups = hasOverview ? parseGroups(overview) : { found: false, groups: [] };
|
|
||||||
const checks = [];
|
|
||||||
const check = (level, code, message) => checks.push({ level, code, message });
|
|
||||||
for (const [n, names] of files.extra) {
|
|
||||||
check("warn", "duplicate-phase-file", `Phase ${n} has more than one file: using ${files.get(n)}, ignoring ${names.join(", ")}`);
|
|
||||||
}
|
|
||||||
const rowsByNumber = new Map();
|
|
||||||
for (const r of checklist.phases) rowsByNumber.set(r.number, [...(rowsByNumber.get(r.number) || []), r]);
|
|
||||||
for (const [n, rows] of rowsByNumber) {
|
|
||||||
if (rows.length > 1) check("error", "duplicate-checklist-row", `Phase ${n} has ${rows.length} rows in the Phase Checklist (overview.md lines ${rows.map((r) => r.line).join(", ")}); the first one is used`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const phases = [];
|
|
||||||
const numbers = new Set([...checklist.phases.map((p) => p.number), ...files.keys()]);
|
|
||||||
for (const number of [...numbers].sort((a, b) => a - b)) {
|
|
||||||
const row = checklist.phases.find((p) => p.number === number) || null;
|
|
||||||
const file = files.get(number) || null;
|
|
||||||
const parsed = file ? parsePhaseFile(path.join(spec.dir, file), number) : null;
|
|
||||||
phases.push({
|
|
||||||
number,
|
|
||||||
name: row ? row.name : parsed ? parsed.title.replace(/^Phase\s+\d+\s*[:\-–—]?\s*/i, "") : `Phase ${number}`,
|
|
||||||
checklist: row ? row.state : null,
|
|
||||||
marker: row ? row.marker : null,
|
|
||||||
file,
|
|
||||||
status: parsed ? parsed.status : null,
|
|
||||||
goal: parsed ? parsed.goal : null,
|
|
||||||
tasks: parsed ? { total: parsed.total, open: parsed.open, ...parsed.counts } : null,
|
|
||||||
blockedTasks: parsed ? parsed.tasks.filter((t) => t.state === "blocked").map((t) => t.id) : [],
|
|
||||||
assumedTasks: parsed ? parsed.tasks.filter((t) => t.state === "assumed").map((t) => t.id) : [],
|
|
||||||
openTasks: parsed ? parsed.tasks.filter((t) => ["pending", "in-progress", "blocked", "unknown"].includes(t.state)).map((t) => t.id) : [],
|
|
||||||
});
|
|
||||||
if (!row && hasOverview) check("error", "missing-checklist-row", `phase-${number}.md has no row in overview.md's Phase Checklist`);
|
|
||||||
if (row && !file) check("error", "missing-phase-file", `Phase Checklist lists Phase ${number} but there is no phase-${number}.md`);
|
|
||||||
if (parsed) {
|
|
||||||
for (const n of parsed.numbering) check("error", "task-numbering", `phase-${number}.md: ${n}`);
|
|
||||||
// Prerequisites and criteria are plain bullets by rule; other checkbox
|
|
||||||
// blocks (a Phase Testing list) are the template's own and are not tasks.
|
|
||||||
for (const s of parsed.strayCheckboxes.filter((c) => /prerequisite|criteria/i.test(c.section))) {
|
|
||||||
check("warn", "criteria-checkbox", `phase-${number}.md:${s.line} is a checkbox under "${s.section}"; prerequisites and criteria use plain bullets`);
|
|
||||||
}
|
|
||||||
if (parsed.total === 0) check("warn", "no-tasks", `phase-${number}.md has no **Task ${number}.N:** checkbox lines`);
|
|
||||||
for (const u of parsed.unmatchedTasks) {
|
|
||||||
check("warn", "uncounted-task", `phase-${number}.md:${u.line} looks like a task but is not counted (a task line is "- [ ] **Task ${number}.N:**"): ${u.text}`);
|
|
||||||
}
|
|
||||||
const done = parsed.counts.complete + parsed.counts.assumed;
|
|
||||||
const rowDone = row && (row.state === "complete" || row.state === "assumed");
|
|
||||||
// A phase may be approved with blocked [!] tasks left (Implementation
|
|
||||||
// Mode's self-review allows "[x] or blocked [!]"); only unfinished work is an error.
|
|
||||||
if (rowDone && parsed.unfinished > 0) {
|
|
||||||
check("error", "checked-with-open-tasks", `Phase ${number} is [${row.marker}] in overview.md but ${parsed.unfinished} task(s) are not done (${phases.at(-1).openTasks.filter((id) => !phases.at(-1).blockedTasks.includes(id)).join(", ")})`);
|
|
||||||
} else if (rowDone && parsed.counts.blocked > 0) {
|
|
||||||
check("info", "approved-with-blocked", `Phase ${number} is [${row.marker}] with ${parsed.counts.blocked} blocked task(s) (${phases.at(-1).blockedTasks.join(", ")})`);
|
|
||||||
}
|
|
||||||
if (row && row.state === "pending" && parsed.total > 0 && done > 0) {
|
|
||||||
// Done tasks under a [ ] phase with work still open is what a re-opened
|
|
||||||
// phase looks like (revise-plan); with nothing open it is a missed mark.
|
|
||||||
if (parsed.unfinished > 0) check("info", "partly-done-unchecked", `Phase ${number} is [ ] with ${done} task(s) done and ${parsed.unfinished} open (normal for a re-opened phase)`);
|
|
||||||
else check("warn", "unchecked-with-done-tasks", `Phase ${number} is [ ] in overview.md but all ${done} unblocked task(s) are done`);
|
|
||||||
}
|
|
||||||
if (row && !rowDone && row.state !== "pending" && parsed.total > 0 && parsed.unfinished === 0) {
|
|
||||||
check("info", "done-not-approved", `Phase ${number}: every task is done but overview.md still shows [${row.marker}] (normal until the user approves the phase)`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!hasOverview) check("error", "no-overview", `${spec.rel} has no overview.md`);
|
|
||||||
else if (!checklist.found) check("error", "no-checklist", "overview.md has no ## Phase Checklist section");
|
|
||||||
for (const u of checklist.unparsed) check("warn", "unparsed-checklist-row", `overview.md:${u.line} is a checkbox in the Phase Checklist with no "Phase N" in it: ${u.text}`);
|
|
||||||
for (const g of groups.groups) {
|
|
||||||
for (const n of g.phases) if (!numbers.has(n)) check("error", "group-unknown-phase", `Parallel group ${g.id} names Phase ${n}, which does not exist`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Totals. Completed = [x] plus [?] (assumed complete); [?] is reported on its own too.
|
|
||||||
// Incomplete = [ ] + [/] (+ unreadable markers); Blocked is its own column.
|
|
||||||
const totals = { total: 0, complete: 0, assumed: 0, pending: 0, "in-progress": 0, blocked: 0, unknown: 0 };
|
|
||||||
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;
|
|
||||||
|
|
||||||
return {
|
|
||||||
ok: true,
|
|
||||||
spec: spec.rel,
|
|
||||||
name: spec.name,
|
|
||||||
overview: hasOverview ? "overview.md" : null,
|
|
||||||
planDrafts: planDrafts(spec.dir),
|
|
||||||
phases,
|
|
||||||
parallelGroups: groups.groups,
|
|
||||||
totals: { ...totals, completed, incomplete: totals.pending + totals["in-progress"] + totals.unknown },
|
|
||||||
completion: completion === null ? null : Number(completion.toFixed(4)),
|
|
||||||
completionPercent: completion === null ? null : Math.round(completion * 100),
|
|
||||||
next: nextPhase(phases, groups.groups, checklist.found),
|
|
||||||
pending: phases
|
|
||||||
.filter((p) => p.checklist && p.checklist !== "complete" && p.checklist !== "assumed")
|
|
||||||
.map((p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null, open: p.tasks ? p.tasks.open : null, goal: p.goal })),
|
|
||||||
checks,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Implementation Mode's phase-selection table, applied mechanically.
|
|
||||||
* 2+ workable phases in the same parallel group, consecutive -> choose (warn if all [/])
|
|
||||||
* a single [/] -> ask-resume · a single [ ] -> auto-start · nothing workable -> none
|
|
||||||
*/
|
|
||||||
function nextPhase(phases, groups, haveChecklist) {
|
|
||||||
if (!haveChecklist) return { action: "none", reason: "no Phase Checklist in overview.md" };
|
|
||||||
const ordered = phases.filter((p) => p.checklist);
|
|
||||||
const isDone = (p) => p.checklist === "complete" || p.checklist === "assumed";
|
|
||||||
const workable = ordered.filter((p) => p.checklist === "pending" || p.checklist === "in-progress");
|
|
||||||
if (!workable.length) {
|
|
||||||
return { action: "none", reason: ordered.length && ordered.every(isDone) ? "every phase is complete" : "no [ ] or [/] phase in the Phase Checklist" };
|
|
||||||
}
|
|
||||||
const first = workable[0];
|
|
||||||
const brief = (p) => ({ number: p.number, name: p.name, state: p.checklist, tasks: p.tasks ? p.tasks.total : null });
|
|
||||||
// A blocked [!] phase ahead of the pick is skipped, but never silently.
|
|
||||||
const skipped = ordered.slice(0, ordered.indexOf(first)).filter((p) => !isDone(p)).map(brief);
|
|
||||||
const note = skipped.length ? { skipped, warning: `skipping ${skipped.map((p) => `Phase ${p.number} [${p.state}]`).join(", ")} ahead of it` } : {};
|
|
||||||
const group = groups.find((g) => g.phases.includes(first.number));
|
|
||||||
if (group) {
|
|
||||||
// Consecutive same-group incomplete phases, in checklist order, starting at the first workable one.
|
|
||||||
const run = [];
|
|
||||||
for (const p of ordered.slice(ordered.indexOf(first))) {
|
|
||||||
if (!group.phases.includes(p.number)) break;
|
|
||||||
if (isDone(p)) continue;
|
|
||||||
if (p.checklist === "pending" || p.checklist === "in-progress") run.push(p);
|
|
||||||
else break;
|
|
||||||
}
|
|
||||||
if (run.length >= 2) {
|
|
||||||
const allStarted = run.every((p) => p.checklist === "in-progress");
|
|
||||||
const warnings = [
|
|
||||||
...(allStarted ? ["every option is already [/]: another agent may be working on it, so picking one risks duplicated work"] : []),
|
|
||||||
...(note.warning ? [note.warning] : []),
|
|
||||||
];
|
|
||||||
return {
|
|
||||||
action: "choose",
|
|
||||||
group: group.id,
|
|
||||||
options: run.map(brief),
|
|
||||||
...(note.skipped ? { skipped: note.skipped } : {}),
|
|
||||||
...(warnings.length ? { warning: warnings.join("; ") } : {}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { action: first.checklist === "in-progress" ? "ask-resume" : "auto-start", phase: brief(first), ...note };
|
|
||||||
}
|
|
||||||
|
|
||||||
/* --------------------------------------------------------------- commands */
|
|
||||||
|
|
||||||
async function cmdList(args) {
|
|
||||||
const root = path.resolve(args.root || ".");
|
|
||||||
const { scanProject } = await consoleLib();
|
|
||||||
const scan = scanProject(root);
|
|
||||||
const specs = scan.specs.map((s) => {
|
|
||||||
const dir = path.join(root, s.dir);
|
|
||||||
let names = [];
|
|
||||||
try {
|
|
||||||
names = fs.readdirSync(dir);
|
|
||||||
} catch {}
|
|
||||||
return {
|
|
||||||
dir: s.dir,
|
|
||||||
name: s.name,
|
|
||||||
state: s.state,
|
|
||||||
detail: s.detail,
|
|
||||||
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,
|
|
||||||
pathfinder: isDir(path.join(dir, "pathfinder")),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
let completed = [];
|
|
||||||
try {
|
|
||||||
completed = fs.readdirSync(path.join(root, "specs--completed")).filter((n) => isDir(path.join(root, "specs--completed", n))).sort();
|
|
||||||
} catch {}
|
|
||||||
out({
|
|
||||||
ok: true,
|
|
||||||
root,
|
|
||||||
hasAgents: scan.hasAgents,
|
|
||||||
specsDir: isDir(path.join(root, "specs")),
|
|
||||||
specs,
|
|
||||||
completed,
|
|
||||||
...(specs.length ? {} : { note: "No active specs under specs/." }),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function cmdStatus(args) {
|
|
||||||
const root = path.resolve(args.root || ".");
|
|
||||||
out(specStatus(resolveSpec(root, args._[1], { allowArchived: true })));
|
|
||||||
}
|
|
||||||
|
|
||||||
function countVerificationAdded(dir) {
|
|
||||||
let n = 0;
|
|
||||||
for (const name of fs.readdirSync(dir)) {
|
|
||||||
if (!/\.md$/i.test(name) || /^PLAN-/i.test(name)) continue;
|
|
||||||
n += ((readText(path.join(dir, name)) || "").match(/<!--\s*VERIFICATION:\s*Added\b/gi) || []).length;
|
|
||||||
}
|
|
||||||
return n;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function cmdMetrics(args) {
|
|
||||||
const root = path.resolve(args.root || ".");
|
|
||||||
const spec = resolveSpec(root, args._[1], { allowArchived: true });
|
|
||||||
const step = args.step;
|
|
||||||
if (step !== "document" && step !== "finalize") fail(EXIT.USAGE, "bad-step", "--step must be document or finalize.", "Plan's METRICS_JSON is written by hand in its Phase 7.");
|
|
||||||
const sets = {};
|
|
||||||
for (const kv of args.set || []) {
|
|
||||||
const m = kv.match(/^([a-z_]+)=(-?\d+(?:\.\d+)?)$/);
|
|
||||||
if (!m) fail(EXIT.USAGE, "bad-set", `--set ${kv} is not key=number.`, "Example: --set verification_failures_found=1");
|
|
||||||
sets[m[1]] = Number(m[2]);
|
|
||||||
}
|
|
||||||
// --set supplies the judgment fields only; the computed ones are never overridden.
|
|
||||||
const SETTABLE = { document: ["verification_items_added"], finalize: ["verification_failures_found", "documentation_updates_needed"] };
|
|
||||||
for (const k of Object.keys(sets)) {
|
|
||||||
if (!SETTABLE[step].includes(k)) fail(EXIT.USAGE, "bad-set", `--set ${k} is not a field you supply for --step ${step}.`, `Only ${SETTABLE[step].join(", ")}; the rest is computed from the files.`);
|
|
||||||
}
|
|
||||||
const st = specStatus(spec);
|
|
||||||
const withTasks = st.phases.filter((p) => p.tasks);
|
|
||||||
let metrics;
|
|
||||||
let hint;
|
|
||||||
if (step === "document") {
|
|
||||||
// verification_items_added is the Added total of the Verification Summary
|
|
||||||
// you presented, not something the files record, so it comes from --set.
|
|
||||||
// The <!-- VERIFICATION: Added --> comments are a cross-check only.
|
|
||||||
if (!("verification_items_added" in sets)) fail(EXIT.USAGE, "missing-set", "document needs --set verification_items_added=N (the Added column total of your Verification Summary).", `The spec has ${countVerificationAdded(spec.dir)} <!-- VERIFICATION: Added --> comment(s), as a cross-check.`);
|
|
||||||
metrics = {
|
|
||||||
step: "document",
|
|
||||||
total_tasks: st.totals.total,
|
|
||||||
tasks_per_phase: withTasks.map((p) => p.tasks.total),
|
|
||||||
phase_count: st.phases.length,
|
|
||||||
parallel_groups_identified: st.parallelGroups.length,
|
|
||||||
...sets,
|
|
||||||
};
|
|
||||||
hint = { verificationCommentsFound: countVerificationAdded(spec.dir) };
|
|
||||||
} else {
|
|
||||||
const missing = ["verification_failures_found", "documentation_updates_needed"].filter((k) => !(k in sets));
|
|
||||||
if (missing.length) fail(EXIT.USAGE, "missing-set", `finalize needs ${missing.map((k) => `--set ${k}=N`).join(" and ")}.`, "Those two counts are your judgment from Steps 2 and 4.");
|
|
||||||
metrics = {
|
|
||||||
step: "finalize",
|
|
||||||
completion_rate_at_audit: st.completion === null ? 0 : Number(st.completion.toFixed(2)),
|
|
||||||
tasks_completed: st.totals.completed,
|
|
||||||
tasks_total: st.totals.total,
|
|
||||||
...sets,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
out({ ok: true, spec: spec.rel, metrics, comment: `<!-- METRICS_JSON ${spacedJson(metrics)} -->`, ...(hint || {}), checks: st.checks.filter((c) => c.level === "error") });
|
|
||||||
}
|
|
||||||
|
|
||||||
// The house style of every METRICS_JSON comment: {"key": value, "list": [1, 2]}.
|
|
||||||
function spacedJson(obj) {
|
|
||||||
const v = (x) => (Array.isArray(x) ? `[${x.map(v).join(", ")}]` : x && typeof x === "object" ? spacedJson(x) : JSON.stringify(x));
|
|
||||||
return `{${Object.entries(obj).map(([k, x]) => `${JSON.stringify(k)}: ${v(x)}`).join(", ")}}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const TO = { open: " ", "in-progress": "/", done: "x" };
|
|
||||||
|
|
||||||
async function cmdMark(args) {
|
|
||||||
const root = path.resolve(args.root || ".");
|
|
||||||
const spec = resolveSpec(root, args._[1]);
|
|
||||||
const number = Number(args.phase);
|
|
||||||
if (!Number.isInteger(number) || number < 0) fail(EXIT.USAGE, "bad-phase", "--phase needs a phase number.", "Example: --phase 2");
|
|
||||||
if (!(args.to in TO)) fail(EXIT.USAGE, "bad-to", "--to must be open, in-progress or done.", "open = [ ], in-progress = [/], done = [x]");
|
|
||||||
const overviewPath = path.join(spec.dir, "overview.md");
|
|
||||||
const overview = readText(overviewPath);
|
|
||||||
if (overview === null) fail(EXIT.NOT_FOUND, "no-overview", `${spec.rel} has no overview.md.`, "Run /plan2code-2-document first.");
|
|
||||||
const checklist = parseChecklist(overview);
|
|
||||||
const rows = checklist.phases.filter((p) => p.number === number);
|
|
||||||
const row = rows[0];
|
|
||||||
if (!row) fail(EXIT.NOT_FOUND, "no-row", `overview.md's Phase Checklist has no row for Phase ${number}.`, "Run `specs.mjs status` to see the phases it lists.");
|
|
||||||
if (rows.length > 1) fail(EXIT.REFUSED, "duplicate-row", `Phase ${number} has ${rows.length} rows in the Phase Checklist (lines ${rows.map((r) => r.line).join(", ")}); marking one would be a guess.`, "Remove the duplicate row, then rerun.");
|
|
||||||
const target = TO[args.to];
|
|
||||||
if (row.marker === "/" && target === " ") {
|
|
||||||
fail(EXIT.REFUSED, "no-reset", `Phase ${number} is [/]; started work is never reset to [ ].`, "Leave it [/] (a later session resumes it), or mark it done once approved.");
|
|
||||||
}
|
|
||||||
const changes = [];
|
|
||||||
const lines = overview.split(/\r?\n/);
|
|
||||||
const idx = row.line - 1;
|
|
||||||
const next = lines[idx].replace(/\[(.)\]/, `[${target}]`);
|
|
||||||
if (next !== lines[idx]) {
|
|
||||||
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.
|
|
||||||
let phaseText = null;
|
|
||||||
let phasePath = null;
|
|
||||||
let unfinished = [];
|
|
||||||
const warnings = [];
|
|
||||||
const file = phaseFiles(spec.dir).get(number);
|
|
||||||
if (file) {
|
|
||||||
phasePath = path.join(spec.dir, file);
|
|
||||||
const text = readText(phasePath) || "";
|
|
||||||
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;
|
|
||||||
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.`);
|
|
||||||
}
|
|
||||||
if (!args["dry-run"]) {
|
|
||||||
if (changes.some((c) => c.file.endsWith("overview.md"))) fs.writeFileSync(overviewPath, lines.join(eol(overview)));
|
|
||||||
if (phaseText !== null) fs.writeFileSync(phasePath, phaseText);
|
|
||||||
}
|
|
||||||
const doneEarly = target === "x" && unfinished.length > 0;
|
|
||||||
if (doneEarly) warnings.unshift(`Phase ${number} was marked done with ${unfinished.length} unfinished task(s): ${unfinished.join(", ")}. Mark only a phase the user approved.`);
|
|
||||||
out({
|
|
||||||
ok: true,
|
|
||||||
spec: spec.rel,
|
|
||||||
phase: number,
|
|
||||||
name: row.name,
|
|
||||||
dryRun: !!args["dry-run"],
|
|
||||||
changed: changes.length > 0,
|
|
||||||
changes,
|
|
||||||
...(warnings.length ? { warning: warnings.join(" ") } : {}),
|
|
||||||
...(doneEarly ? { unfinished } : {}),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function listRel(dir, base = dir) {
|
|
||||||
const outList = [];
|
|
||||||
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
||||||
const p = path.join(dir, e.name);
|
|
||||||
if (e.isDirectory()) outList.push(...listRel(p, base));
|
|
||||||
else outList.push(rel(base, p));
|
|
||||||
}
|
|
||||||
return outList.sort();
|
|
||||||
}
|
|
||||||
|
|
||||||
async function cmdArchive(args) {
|
|
||||||
const root = path.resolve(args.root || ".");
|
|
||||||
const spec = resolveSpec(root, args._[1]);
|
|
||||||
const target = path.join(root, "specs--completed", spec.name);
|
|
||||||
if (fs.existsSync(target)) {
|
|
||||||
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);
|
|
||||||
if (!args["dry-run"]) {
|
|
||||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
||||||
try {
|
|
||||||
fs.renameSync(spec.dir, target);
|
|
||||||
} catch (err) {
|
|
||||||
// A rename across volumes (or a locked file on Windows) fails; copy then remove.
|
|
||||||
try {
|
|
||||||
fs.cpSync(spec.dir, target, { recursive: true, errorOnExist: true, force: false });
|
|
||||||
} 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.`);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
fs.rmSync(spec.dir, { recursive: true, force: true });
|
|
||||||
} catch (rmErr) {
|
|
||||||
fail(EXIT.INVALID, "source-not-removed", `Copied to specs--completed/${spec.name}/ but could not remove ${spec.rel} (${rmErr.code || rmErr.message}); both copies now exist.`, `Close whatever holds files in ${spec.rel} open, then delete it by hand. The archive is complete.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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)) {
|
|
||||||
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"}.`,
|
|
||||||
`Compare ${spec.rel} with specs--completed/${spec.name}/ and finish the move by hand; archive refuses to rerun while the target exists.`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
out({
|
|
||||||
ok: true,
|
|
||||||
dryRun: !!args["dry-run"],
|
|
||||||
from: spec.rel,
|
|
||||||
to: `specs--completed/${spec.name}`,
|
|
||||||
files,
|
|
||||||
...(args["dry-run"] ? {} : { sourceRemoved: sourceGone, filesAtTarget: moved.length, archivedOn: isoDate() }),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
run(USAGE, async (argv) => {
|
|
||||||
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "step", "phase", "to"], lists: ["set"] });
|
|
||||||
const cmd = args._[0];
|
|
||||||
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, archive: cmdArchive };
|
|
||||||
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, metrics, mark, archive. Run with --help.");
|
|
||||||
await commands[cmd](args);
|
|
||||||
});
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "Plan2Code",
|
|
||||||
"version": "2.5.0",
|
|
||||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
|
||||||
"keywords": [
|
|
||||||
"ai",
|
|
||||||
"workflow",
|
|
||||||
"development",
|
|
||||||
"planning",
|
|
||||||
"implementation",
|
|
||||||
"plan"
|
|
||||||
],
|
|
||||||
"author": "Justin Parker",
|
|
||||||
"license": "MIT",
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "https://github.com/jparkerweb/plan2code"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
|
||||||
"releaseDate": "2026-10-06",
|
|
||||||
"mode": "utility"
|
|
||||||
}
|
|
||||||
@@ -16,14 +16,6 @@ Technical writer transforming planning documents into precise, complete implemen
|
|||||||
|
|
||||||
The FIRST thing you do, before anything else — before Auto-Discovery: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow document` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec` once known), then <D>/console.md → Documentation. Switchable anytime. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console.md → Launches), then Auto-Discovery. `__stop` ends it; post `finish` BEFORE `stop` at every end.
|
The FIRST thing you do, before anything else — before Auto-Discovery: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow document` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec` once known), then <D>/console.md → Documentation. Switchable anytime. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console.md → Launches), then Auto-Discovery. `__stop` ends it; post `finish` BEFORE `stop` at every end.
|
||||||
|
|
||||||
## Scripts
|
|
||||||
|
|
||||||
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-2-document/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>/specs.mjs" list`: every active spec with its `planDrafts` (file and **Status:** line).
|
|
||||||
- `node "<S>/specs.mjs" status <spec>`: once written, the phases, task counts, goals, parallel groups and `checks` the files produce.
|
|
||||||
- `node "<S>/specs.mjs" metrics <spec> --step document --set verification_items_added=<N>`: the METRICS_JSON line.
|
|
||||||
|
|
||||||
## Rules
|
## Rules
|
||||||
|
|
||||||
- Follow `./AGENTS.md` if it exists
|
- Follow `./AGENTS.md` if it exists
|
||||||
@@ -36,11 +28,11 @@ The FIRST thing you do, before anything else — before Auto-Discovery: ask **we
|
|||||||
|
|
||||||
## Auto-Discovery
|
## Auto-Discovery
|
||||||
|
|
||||||
`specs/` is gitignored, so Glob silently finds nothing there; `specs.mjs` reads it directly.
|
⚠️ IMPORTANT: `specs/` is gitignored — NEVER use Glob (silently fails). Shell only: `ls specs/` (Bash) or `Get-ChildItem specs/` (PS).
|
||||||
|
|
||||||
**Before asking user for input:**
|
**Before asking user for input:**
|
||||||
|
|
||||||
1. Run `specs.mjs list` and collect every spec's `planDrafts` (skip `archived` ones, the `-prev` copies)
|
1. Run `ls specs/` then check each folder for `PLAN-DRAFT-*.md`
|
||||||
2. **One found:** Use it, inform user: "Found: `specs/<feature>/PLAN-DRAFT-<date>.md`"
|
2. **One found:** Use it, inform user: "Found: `specs/<feature>/PLAN-DRAFT-<date>.md`"
|
||||||
3. **Multiple found:** List all, ask which to document
|
3. **Multiple found:** List all, ask which to document
|
||||||
4. **None found:** Fall back to Required Context below
|
4. **None found:** Fall back to Required Context below
|
||||||
@@ -107,16 +99,14 @@ Line numbers may only appear as SUPPLEMENTAL context alongside a semantic refere
|
|||||||
5. **Use existing** `specs/<feature-name>/` directory
|
5. **Use existing** `specs/<feature-name>/` directory
|
||||||
6. **Write** `overview.md` first, copying from PLAN-DRAFT:
|
6. **Write** `overview.md` first, copying from PLAN-DRAFT:
|
||||||
- Summary (from Executive Summary)
|
- Summary (from Executive Summary)
|
||||||
- Phase Checklist (Implementation Phases), directly under Summary
|
|
||||||
- Parallel Execution Groups (filled in step 8)
|
|
||||||
- Tech Stack table (exact copy)
|
- Tech Stack table (exact copy)
|
||||||
- Architecture Pattern and Component Overview (section 4)
|
- Architecture Pattern and Component Overview (section 4)
|
||||||
- Risks and Mitigations table (section 6)
|
- Risks and Mitigations table (section 6)
|
||||||
- Success Criteria (plain bullet list, no checkboxes) (section 7)
|
- Success Criteria (plain bullet list, no checkboxes) (section 7)
|
||||||
|
- Phase Checklist (Implementation Phases)
|
||||||
- Quick Reference (Key Files, Environment Variables, External Dependencies)
|
- Quick Reference (Key Files, Environment Variables, External Dependencies)
|
||||||
7. **Write** each `phase-X.md` with detailed tasks — run the complexity check per task; split any that fail, combine adjacent trivial tasks
|
7. **Write** each `phase-X.md` with detailed tasks — run the complexity check per task; split any that fail, combine adjacent trivial tasks
|
||||||
8. **Analyze** parallel execution eligibility
|
8. **Analyze** parallel execution eligibility
|
||||||
8a. **Check the structure:** `specs.mjs status specs/<feature-name>`. Fix every `error` and `warn` in `checks` (task numbering, a checkbox under Prerequisites or criteria, a checklist row with no phase file), and confirm `phases` and `parallelGroups` read back as you wrote them
|
|
||||||
9. **Verify** all PLAN-DRAFT requirements covered:
|
9. **Verify** all PLAN-DRAFT requirements covered:
|
||||||
- 9A: Re-read PLAN-DRAFT as source of truth
|
- 9A: Re-read PLAN-DRAFT as source of truth
|
||||||
- 9B: Cross-reference each section against docs
|
- 9B: Cross-reference each section against docs
|
||||||
@@ -186,13 +176,13 @@ Use kebab-case for feature name (e.g., `user-authentication`).
|
|||||||
|
|
||||||
### overview.md
|
### 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 (Not Started | In Progress | Complete).
|
||||||
|
|
||||||
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).
|
Sections: Summary (from Executive Summary), Tech Stack table (exact copy from PLAN-DRAFT), Architecture (Pattern + Component Overview table), Risks and Mitigations table, Success Criteria checklist, Phase Checklist, Parallel Execution Groups table (from analysis), Quick Reference (Key Files, Environment Variables, External Dependencies), Completion Summary (filled during finalization).
|
||||||
|
|
||||||
### phase-X.md
|
### phase-X.md
|
||||||
|
|
||||||
Header: Phase name, Status on its own line as `**Status:** <value>` (Not Started | In Progress | Complete; `specs.mjs mark` updates it), Estimated Tasks count.
|
Header: Phase name, Status, Estimated Tasks count.
|
||||||
|
|
||||||
Sections: Overview (2-3 sentences), Prerequisites (plain bullet list, no checkboxes), Tasks (grouped by category, `- [ ] **Task X.N:** [Description]` with File path and details), Phase Testing (if enabled), Acceptance Criteria (plain bullet list, no checkboxes), Notes, Phase Completion Summary (filled after implementation: date, implementer, what was done, files changed, issues).
|
Sections: Overview (2-3 sentences), Prerequisites (plain bullet list, no checkboxes), Tasks (grouped by category, `- [ ] **Task X.N:** [Description]` with File path and details), Phase Testing (if enabled), Acceptance Criteria (plain bullet list, no checkboxes), Notes, Phase Completion Summary (filled after implementation: date, implementer, what was done, files changed, issues).
|
||||||
|
|
||||||
@@ -226,13 +216,13 @@ Total tasks: Y
|
|||||||
Parallel Execution: [Groups or "None - sequential only"]
|
Parallel Execution: [Groups or "None - sequential only"]
|
||||||
```
|
```
|
||||||
|
|
||||||
Also append a machine-parseable metrics comment to the END of `overview.md` for the metrics pipeline, shaped like:
|
Also append a machine-parseable metrics comment to the END of `overview.md` for the metrics pipeline:
|
||||||
|
|
||||||
```
|
```
|
||||||
<!-- METRICS_JSON {"step": "document", "total_tasks": 28, "tasks_per_phase": [7, 7, 7, 7], "phase_count": 4, "parallel_groups_identified": 2, "verification_items_added": 3} -->
|
<!-- METRICS_JSON {"step": "document", "total_tasks": 28, "tasks_per_phase": [7, 7, 7, 7], "phase_count": 4, "parallel_groups_identified": 2, "verification_items_added": 3} -->
|
||||||
```
|
```
|
||||||
|
|
||||||
Paste the `comment` from `specs.mjs metrics specs/<feature-name> --step document --set verification_items_added=<N>`, where N is the Added column total of your Verification Summary. It counts the tasks, phases and parallel groups from the files.
|
Replace values with actuals. `verification_items_added` = total Added column from the Verification Summary table.
|
||||||
|
|
||||||
**Tell user:**
|
**Tell user:**
|
||||||
1. What was created (spec files list)
|
1. What was created (spec files list)
|
||||||
@@ -240,7 +230,7 @@ Paste the `comment` from `specs.mjs metrics specs/<feature-name> --step document
|
|||||||
3. Next command: `/plan2code-3-implement-review --web` (quality-gated) or `/plan2code-3-implement --web` (implementation only)
|
3. Next command: `/plan2code-3-implement-review --web` (quality-gated) or `/plan2code-3-implement --web` (implementation only)
|
||||||
4. Start NEW conversation for implementation
|
4. Start NEW conversation for implementation
|
||||||
|
|
||||||
**Phase Overview** — present a table from `status`'s `phases`: phase name, task count (`tasks.total`), one-sentence goal (`goal`, tightened if it runs long; write one yourself when it is null). Helps the user plan sessions and identify review gates.
|
**Phase Overview** — read each `phase-X.md` and present a table: phase name, task count, one-sentence goal. Helps the user plan sessions and identify review gates.
|
||||||
|
|
||||||
```
|
```
|
||||||
⋅
|
⋅
|
||||||
|
|||||||
@@ -60,16 +60,7 @@ The first payload for a phase you are about to build:
|
|||||||
```
|
```
|
||||||
|
|
||||||
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
|
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
|
||||||
progress bar is the first thing someone watching a build looks at. The session
|
progress bar is the first thing someone watching a build looks at.
|
||||||
meter counts the build's tasks from `cleared` as it rises, so keep it current,
|
|
||||||
and start every phase (a second one in the same run too) at `"cleared": 0`.
|
|
||||||
|
|
||||||
`"version": 1` is for the first phase of a session only. A doc's version
|
|
||||||
never goes back (console.md → House rules, rule 9), so a later phase in the
|
|
||||||
same session reposts `phase` and `phasefile` at one more than the version the
|
|
||||||
page holds, with the new phase's title and content. The same goes for
|
|
||||||
`report` at sign-off and `review` in a mid-session review: version 1 the
|
|
||||||
first time, then up from wherever the page has it.
|
|
||||||
|
|
||||||
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
||||||
the person can read the prerequisites and task specs while you build. Re-post
|
the person can read the prerequisites and task specs while you build. Re-post
|
||||||
@@ -118,12 +109,6 @@ printed), never into the project or into `~/.plan2code/console/` directly:
|
|||||||
- Do not call `wait` while building. There is nothing to collect, and the page
|
- Do not call `wait` while building. There is nothing to collect, and the page
|
||||||
holds anything the person sends until you next look.
|
holds anything the person sends until you next look.
|
||||||
|
|
||||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
|
||||||
`chat` check between tasks. Follow console.md → Standing instructions for
|
|
||||||
handing independent tasks to helpers and reporting them as `helpers`. Keep the
|
|
||||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
|
||||||
with you.
|
|
||||||
|
|
||||||
### Quick questions between tasks
|
### Quick questions between tasks
|
||||||
|
|
||||||
The person can ask a Quick question on the Ask tab at any point in a build
|
The person can ask a Quick question on the Ask tab at any point in a build
|
||||||
@@ -150,15 +135,8 @@ not questions. Put them in the phase doc as they happen, and in the report.
|
|||||||
|
|
||||||
### When the workflow asks something
|
### When the workflow asks something
|
||||||
|
|
||||||
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }` in
|
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }`, and
|
||||||
the SAME post, and go into the wait loop. When the answer lands, set `working`
|
go into the wait loop. When the answer lands, set `working` again and carry on.
|
||||||
again and carry on.
|
|
||||||
|
|
||||||
A question stops the build. Never leave yourself `working` with a question
|
|
||||||
open, and never "carry on while you decide": the page reads `working` as "not
|
|
||||||
your turn", and the person is left looking at a question they cannot answer.
|
|
||||||
If there is other work the answer does not touch, finish it before you ask,
|
|
||||||
then ask and wait.
|
|
||||||
|
|
||||||
| Moment | `kind` | Notes |
|
| Moment | `kind` | Notes |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -208,8 +186,7 @@ only ever be offered once nothing could come of it:
|
|||||||
`reply` carries `Approve this phase: approved`, which is the terminal's
|
`reply` carries `Approve this phase: approved`, which is the terminal's
|
||||||
`approved`. If the note that came with an approval asks for a change, treat it
|
`approved`. If the note that came with an approval asks for a change, treat it
|
||||||
as "describe any issues": do the change first and ask again. `changes` means
|
as "describe any issues": do the change first and ask again. `changes` means
|
||||||
exactly what it says: address it, bump the report's version (a later phase's
|
exactly what it says: address it, bump the report's version, and reopen the
|
||||||
report starts above the last one's, too), and reopen the
|
|
||||||
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||||
person asking for the code review before they approve anything — see "The
|
person asking for the code review before they approve anything — see "The
|
||||||
review, mid-session" below.
|
review, mid-session" below.
|
||||||
@@ -249,9 +226,8 @@ sign-off card, and approving past it was the answer. `implement-review` ends
|
|||||||
the same way; that phase was reviewed already. Only a finished `quick-task`
|
the same way; that phase was reviewed already. Only a finished `quick-task`
|
||||||
still offers the review on its finish — see below.
|
still offers the review on its finish — see below.
|
||||||
|
|
||||||
`run` gives the approved phase its final score on the session meter (console.md →
|
`run` scores the approved phase on the session meter (console.md → Posting an
|
||||||
Posting an update → Session meter), in the same post that records the approval;
|
update → Session meter), in the same post that records the approval:
|
||||||
it takes over what the build already counted from `cleared`, never adds to it:
|
|
||||||
`implement-phase` for Implement, `implement-review-phase` for Implement +
|
`implement-phase` for Implement, `implement-review-phase` for Implement +
|
||||||
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
|
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
|
||||||
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
|
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
|
||||||
@@ -409,10 +385,7 @@ a question still owed, above the ending itself:
|
|||||||
|
|
||||||
The same build, then Stage 2 publishes the findings exactly as above (the
|
The same build, then Stage 2 publishes the findings exactly as above (the
|
||||||
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
|
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
|
||||||
item: Stage 4 is the only gate. The post that starts Stage 2's review carries
|
item: Stage 4 is the only gate. Stage 4 is the sign-off above **without the
|
||||||
`"run": { "event": "review", "id": "review" }`, as above: in this workflow it
|
|
||||||
scores the review stage's 1 point on the meter as it begins, and the phase's
|
|
||||||
final `run` leaves that point out. Stage 4 is the sign-off above **without the
|
|
||||||
review verdict** — the phase was already reviewed — with the review results
|
review verdict** — the phase was already reviewed — with the review results
|
||||||
and unresolved findings in the report doc, header "Reviewed and ready for
|
and unresolved findings in the report doc, header "Reviewed and ready for
|
||||||
sign-off" in the item's `body`. The finish never carries `review`, and its
|
sign-off" in the item's `body`. The finish never carries `review`, and its
|
||||||
|
|||||||
@@ -170,7 +170,7 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
|
|||||||
|
|
||||||
| Exit | Meaning | What you do |
|
| Exit | Meaning | What you do |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace) and `subagents` (the helpers switch, see Standing instructions). | Handle the cards (if any), the chat (if any), any `workspace` changes and any `subagents` block, then post once (below, Quick questions, Workspace and Standing instructions). |
|
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace). | Handle the cards (if any), the chat (if any) and any `workspace` changes, then post once (below, Quick questions and Workspace). |
|
||||||
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
||||||
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
||||||
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
||||||
@@ -243,7 +243,7 @@ summarise it back.
|
|||||||
Then, in ONE `post`, do all of:
|
Then, in ONE `post`, do all of:
|
||||||
|
|
||||||
- mark each answered item `"status": "answered"` and record its `answer`
|
- mark each answered item `"status": "answered"` and record its `answer`
|
||||||
- reply to every note in that item's `thread` (shape below)
|
- add your replies to any comment threads
|
||||||
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
||||||
questions)
|
questions)
|
||||||
- publish the next batch of questions
|
- publish the next batch of questions
|
||||||
@@ -251,26 +251,6 @@ Then, in ONE `post`, do all of:
|
|||||||
|
|
||||||
One post is one atomic update, so the page never shows a half-changed state.
|
One post is one atomic update, so the page never shows a half-changed state.
|
||||||
|
|
||||||
### Replying to a note
|
|
||||||
|
|
||||||
A `comment` is the person talking to you about that card, often asking
|
|
||||||
something. It shows in the card's **Notes on this** panel, and so does your
|
|
||||||
answer:
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{ "items": [{ "id": "p4", "thread": [
|
|
||||||
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
|
|
||||||
] }] }
|
|
||||||
```
|
|
||||||
|
|
||||||
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
|
|
||||||
`md`: the page reads nothing else. An entry with no `text` is rejected.
|
|
||||||
- The server writes their note into the thread as it arrives. Do not repeat
|
|
||||||
it, and send only your new entries: `thread` appends.
|
|
||||||
- Answer what they asked, in the thread, even when you also change a doc or
|
|
||||||
re-ask the question. "I've updated the doc" alone leaves the question in the
|
|
||||||
panel with no answer under it.
|
|
||||||
|
|
||||||
### Recording the answer
|
### Recording the answer
|
||||||
|
|
||||||
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
||||||
@@ -576,15 +556,8 @@ enforces it, so never tell someone to keep asking past it.
|
|||||||
The person can add folders beside the one the session started in (a shared
|
The person can add folders beside the one the session started in (a shared
|
||||||
library, a design folder), from the footer's folder label. Together they are
|
library, a design folder), from the footer's folder label. Together they are
|
||||||
the session's **workspace**: context for every skill run in this console
|
the session's **workspace**: context for every skill run in this console
|
||||||
session, each folder addressed by a short `@name`. It outlives dashboard hops,
|
session, each folder addressed by a short `@name`. It outlives dashboard hops;
|
||||||
and it is remembered: every change is saved to `workspaces.json` beside
|
a new console session starts with the original folder alone.
|
||||||
`looks.json` (never into the project), keyed by the folder the session runs
|
|
||||||
in and then by spec. A session with a spec opens on that spec's list, one with
|
|
||||||
none on the project's; a spec with nothing saved starts as a copy of the
|
|
||||||
project's list. The dashboard's picker swaps the list as the selection moves,
|
|
||||||
and a `specDir` you post mid-run takes the current list with it. There is
|
|
||||||
nothing for you to load: `open` prints the list, and a switch of spec on a
|
|
||||||
resume reaches you as ordinary workspace changes on your next `wait`.
|
|
||||||
|
|
||||||
### What you are told
|
### What you are told
|
||||||
|
|
||||||
@@ -647,84 +620,6 @@ for permission is not a failure; report only a read that failed after it.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Standing instructions
|
|
||||||
|
|
||||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
|
||||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
|
||||||
from the top bar's Subagents button. Their pick is saved per project and per
|
|
||||||
skill, off by default, and reaches you as a standing instruction, only when it
|
|
||||||
changes.
|
|
||||||
|
|
||||||
### What arrives
|
|
||||||
|
|
||||||
A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`,
|
|
||||||
after the card lines, the `Quick question:` blocks and the `Workspace:` lines.
|
|
||||||
It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting
|
|
||||||
change alone never ends a `wait` slice: it waits for the next send, or for
|
|
||||||
your next `chat` check.
|
|
||||||
|
|
||||||
```
|
|
||||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
|
||||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
|
||||||
Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.
|
|
||||||
With no way to start helpers, report one "working alone" entry for this skill run instead.
|
|
||||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.
|
|
||||||
At most 3 helpers at once.
|
|
||||||
```
|
|
||||||
|
|
||||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
|
||||||
An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …`
|
|
||||||
with the whole block again; switching off arrives as one line:
|
|
||||||
`Subagents: off (revision 4) — don't start new helpers for the rest of this session.`
|
|
||||||
|
|
||||||
It is a console setting, not something the person typed. It never answers a
|
|
||||||
card, and it is never recorded under `specs/`.
|
|
||||||
|
|
||||||
### Obeying it
|
|
||||||
|
|
||||||
- **On:** hand independent work to helpers if your tools allow it, at most
|
|
||||||
`max` at once, following the instruction lines. `max` is advisory: your
|
|
||||||
harness's own limit still applies.
|
|
||||||
- **A higher revision replaces a lower one.** Follow the latest block only.
|
|
||||||
- **Off:** start no new helpers for the rest of the session. Let running ones
|
|
||||||
finish and report them.
|
|
||||||
- **Nothing arrives:** keep doing what the skill says.
|
|
||||||
- **Scope is the skill run it arrived in.** After a dashboard launch, no block
|
|
||||||
means the switch is off for this skill, even if an earlier skill in the same
|
|
||||||
conversation was told "on": `open` starts the count again, and a launch with
|
|
||||||
the switch off sends nothing.
|
|
||||||
|
|
||||||
### Reporting helpers
|
|
||||||
|
|
||||||
Post them, at your check-ins, so the page's Subagents tab can show them. The
|
|
||||||
page never hears from a helper directly:
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{ "helpers": [
|
|
||||||
{ "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" },
|
|
||||||
{ "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." }
|
|
||||||
] }
|
|
||||||
```
|
|
||||||
|
|
||||||
- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and
|
|
||||||
`state` (`running`, `done` or `failed`) are required; `result` (at most 200)
|
|
||||||
is the one line you add once a helper ends.
|
|
||||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
|
||||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
|
||||||
too; a resume into the same skill keeps it.
|
|
||||||
- One post per change worth seeing, not a stream.
|
|
||||||
- Questions for the person stay with you, never with a helper: most harnesses
|
|
||||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
|
||||||
session.
|
|
||||||
- **No way to start helpers?** Post one `{ "id": "alone", "alone": true }`
|
|
||||||
entry for the skill run instead. The tab then says you are working alone.
|
|
||||||
- **Pathfinder:** research questions always use helpers and are always
|
|
||||||
reported, whatever the switch says. The switch governs recon, sketches and
|
|
||||||
lookups beside the conversation.
|
|
||||||
- Helpers add no session meter points. Post no `run` for them.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Launches (dashboard only)
|
## Launches (dashboard only)
|
||||||
|
|
||||||
A `dashboard` session is not a conversation: the page draws a menu of every
|
A `dashboard` session is not a conversation: the page draws a menu of every
|
||||||
@@ -759,17 +654,9 @@ finish are dropped, so you start on a blank page and post your own. A skill
|
|||||||
run inline from another (a quick task's review) keeps the page it was
|
run inline from another (a quick task's review) keeps the page it was
|
||||||
handed. A
|
handed. A
|
||||||
fresh `open` would strand the page the person is watching on the dashboard's
|
fresh `open` would strand the page the person is watching on the dashboard's
|
||||||
session while your questions went to a page nobody has open.
|
session while your questions went to a page nobody has open. Then run the
|
||||||
|
skill normally: its Interface question was already answered by being
|
||||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
launched, so start where its real work starts.
|
||||||
> own file-read tool and follow it from the top instead.** Every Plan2Code
|
|
||||||
> skill below the dashboard ships `disable-model-invocation: true` on
|
|
||||||
> purpose — it exists to be read and followed inline, not launched as a
|
|
||||||
> sub-skill — and calling one through a skill-invocation tool errors out and
|
|
||||||
> strands the hand-off mid-launch.
|
|
||||||
|
|
||||||
Its Interface step is already answered by having been launched, so start
|
|
||||||
where its real work starts.
|
|
||||||
|
|
||||||
The menu itself is the page's own list — you never send it. The page knows
|
The menu itself is the page's own list — you never send it. The page knows
|
||||||
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
||||||
@@ -841,10 +728,7 @@ commands follow the pipeline: the sign-off's is
|
|||||||
|
|
||||||
### Review (`review`)
|
### Review (`review`)
|
||||||
|
|
||||||
Scope questions up front — run standalone with nothing named, the first is
|
Scope questions up front, then the findings report as a doc (`id: "report"`),
|
||||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
|
||||||
uncommitted changes, specs, files you name; each option with its size),
|
|
||||||
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
|
|
||||||
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
||||||
id, carrying `"doc": "report"` so the card links straight to the findings.
|
id, carrying `"doc": "report"` so the card links straight to the findings.
|
||||||
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
||||||
@@ -878,14 +762,12 @@ that is what the person is there to download. The finish carries no
|
|||||||
- Chart Step 8's research subagents must all report back before the
|
- Chart Step 8's research subagents must all report back before the
|
||||||
finish (Finishing → Nothing of yours may still be running); the finish
|
finish (Finishing → Nothing of yours may still be running); the finish
|
||||||
body then names what each one found.
|
body then names what each one found.
|
||||||
- Report every research subagent as a helper, whatever the Subagents switch
|
|
||||||
says (Standing instructions → Reporting helpers).
|
|
||||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||||
sees the Trail Footer, and without this their last screen promises a question
|
sees the Trail Footer, and without this their last screen promises a question
|
||||||
that is never coming.
|
that is never coming.
|
||||||
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
|
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
|
||||||
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
|
and `pathfinder-research` (id = the question's file slug) as each research
|
||||||
subagent reports back, or when you resolve a `research` question yourself
|
subagent reports back, or when you resolve a `research` question yourself
|
||||||
(Posting an update → Session meter). Other questions score through their
|
(Posting an update → Session meter). Other questions score through their
|
||||||
answers, so there is nothing to post for them.
|
answers, so there is nothing to post for them.
|
||||||
@@ -938,13 +820,7 @@ know:
|
|||||||
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) so the page reader sees it land. |
|
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`) so the page reader sees it land. |
|
||||||
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
|
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
|
||||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
|
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`. |
|
||||||
|
|
||||||
Post `activity` as each step starts, before its doc or question lands — reading
|
|
||||||
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
|
|
||||||
implementation — the same way Review does. A step with no card of its own
|
|
||||||
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
|
|
||||||
Finalize".
|
|
||||||
|
|
||||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||||
Stopping mid-finalize loses nothing
|
Stopping mid-finalize loses nothing
|
||||||
@@ -976,7 +852,7 @@ question or doc lands:
|
|||||||
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
||||||
|
|
||||||
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
||||||
merge by `id` (an unknown id is added), and `thread` appends. Send only
|
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
|
||||||
what changed. A whole-file rewrite would put the entire session back into your
|
what changed. A whole-file rewrite would put the entire session back into your
|
||||||
context on every turn.
|
context on every turn.
|
||||||
|
|
||||||
@@ -1018,9 +894,7 @@ Per-unit work is yours to report, with `run` in any post:
|
|||||||
not count), a whole number from 1 to 999. A built phase scores by its size,
|
not count), a whole number from 1 to 999. A built phase scores by its size,
|
||||||
one point per 3 tasks rounded up, and Implement + Review one more for the
|
one point per 3 tasks rounded up, and Implement + Review one more for the
|
||||||
review. Always send it: without it a phase scores a flat 2 (or 3), however
|
review. Always send it: without it a phase scores a flat 2 (or 3), however
|
||||||
big it was. On any other event it is exit `3`. The console already counts a
|
big it was. On any other event it is exit `3`.
|
||||||
build's tasks from `headline.cleared` as they are ticked off; the phase's
|
|
||||||
`run` takes that count over with the final score, so it never counts twice.
|
|
||||||
- One `run` per post. Which events a workflow reports is in its own notes
|
- One `run` per post. Which events a workflow reports is in its own notes
|
||||||
(Workflow notes → Pathfinder; `building.md` for Implement and for the
|
(Workflow notes → Pathfinder; `building.md` for Implement and for the
|
||||||
review run on the page after a build).
|
review run on the page after a build).
|
||||||
@@ -1229,16 +1103,6 @@ A patch that breaks one of these is rejected with exit `3` and a message:
|
|||||||
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
||||||
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
||||||
and 5 cover `reason` and `hint`.
|
and 5 cover `reason` and `hint`.
|
||||||
8. **`helpers` entries are well formed** (Standing instructions → Reporting
|
|
||||||
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
|
|
||||||
and a known `state` within their limits, plus at most one `alone` entry.
|
|
||||||
Rules 4 and 5 cover `title`, `ask` and `result`.
|
|
||||||
9. **A doc's `version` never goes back.** Sending a known doc a lower
|
|
||||||
`version` than the page holds is refused: it is almost always a stale or
|
|
||||||
copied payload. The same version again is fine, and a dashboard hop starts
|
|
||||||
every doc fresh. Anything else reusing a doc id in the same session (a
|
|
||||||
build's second phase, a second report or review) continues from the
|
|
||||||
version the page holds.
|
|
||||||
|
|
||||||
These are workflow rules you already follow. The server just makes them checkable.
|
These are workflow rules you already follow. The server just makes them checkable.
|
||||||
|
|
||||||
@@ -1260,9 +1124,7 @@ cannot see them, and the moment it says the session ended, the person is
|
|||||||
free to close that terminal and kill them mid-write. While you wait, post
|
free to close that terminal and kill them mid-write. While you wait, post
|
||||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||||
and update the count as each returns. Never write a `finish.body` that says
|
and update the count as each returns. Never write a `finish.body` that says
|
||||||
work "is running in the background" or "will finish on its own". Mark every
|
work "is running in the background" or "will finish on its own".
|
||||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
|
||||||
never ends on a row still running.
|
|
||||||
|
|
||||||
### 1. Post the finish
|
### 1. Post the finish
|
||||||
|
|
||||||
@@ -1368,7 +1230,7 @@ answers were submitted but never picked up.
|
|||||||
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
||||||
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
||||||
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
||||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||||
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
||||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||||
|
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ import {
|
|||||||
die,
|
die,
|
||||||
ensureDir,
|
ensureDir,
|
||||||
fileStamp,
|
fileStamp,
|
||||||
forgetWorkspace,
|
|
||||||
handOff,
|
handOff,
|
||||||
handleFile,
|
handleFile,
|
||||||
healthOk,
|
healthOk,
|
||||||
@@ -64,21 +63,16 @@ import {
|
|||||||
readChat,
|
readChat,
|
||||||
readJson,
|
readJson,
|
||||||
readLedger,
|
readLedger,
|
||||||
readSubagentCursor,
|
|
||||||
readSubagentSetting,
|
|
||||||
readWorkspace,
|
readWorkspace,
|
||||||
reapHandles,
|
reapHandles,
|
||||||
rememberedWorkspace,
|
|
||||||
remoteWarning,
|
remoteWarning,
|
||||||
removeScratch,
|
removeScratch,
|
||||||
removeSessions,
|
removeSessions,
|
||||||
repoRoots,
|
repoRoots,
|
||||||
resetSubagentCursor,
|
|
||||||
scanProject,
|
scanProject,
|
||||||
SESSION_MAX_AGE_MS,
|
SESSION_MAX_AGE_MS,
|
||||||
sessionDir,
|
sessionDir,
|
||||||
sleepSync,
|
sleepSync,
|
||||||
specKey,
|
|
||||||
staleScratch,
|
staleScratch,
|
||||||
staleSessions,
|
staleSessions,
|
||||||
sweepUploads,
|
sweepUploads,
|
||||||
@@ -91,11 +85,9 @@ import {
|
|||||||
workspaceForAgent,
|
workspaceForAgent,
|
||||||
writeCursor,
|
writeCursor,
|
||||||
writeJsonAtomic,
|
writeJsonAtomic,
|
||||||
writeSubagentCursor,
|
|
||||||
writeWorkspaceCursor,
|
writeWorkspaceCursor,
|
||||||
} from "./lib.mjs";
|
} from "./lib.mjs";
|
||||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount } from "./public/meter.js";
|
||||||
import { blockFor, offered } from "./public/subagents.js";
|
|
||||||
import { changeLine } from "./public/workspace.js";
|
import { changeLine } from "./public/workspace.js";
|
||||||
|
|
||||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||||
@@ -315,11 +307,7 @@ async function cmdOpen() {
|
|||||||
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
||||||
}
|
}
|
||||||
state = written.state;
|
state = written.state;
|
||||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
|
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
|
||||||
// A new agent conversation has been told nothing yet (FR-6).
|
|
||||||
try {
|
|
||||||
resetSubagentCursor(dir);
|
|
||||||
} catch {}
|
|
||||||
trace("open: state written");
|
trace("open: state written");
|
||||||
|
|
||||||
// Dashboard launches are recorded too (they score nothing), so the folder
|
// Dashboard launches are recorded too (they score nothing), so the folder
|
||||||
@@ -329,7 +317,7 @@ async function cmdOpen() {
|
|||||||
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
|
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
|
||||||
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
|
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
|
||||||
} catch {}
|
} catch {}
|
||||||
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
|
const workspace = workspaceOnOpen(dir, worktree);
|
||||||
|
|
||||||
// Month-old sessions and scratch files: listed before the print so the
|
// Month-old sessions and scratch files: listed before the print so the
|
||||||
// agent can see what went, removed after it so the page waits for nothing.
|
// agent can see what went, removed after it so the page waits for nothing.
|
||||||
@@ -346,18 +334,9 @@ async function cmdOpen() {
|
|||||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||||
};
|
};
|
||||||
|
|
||||||
// A standing instruction the new agent is owed, as `subagents` and a
|
|
||||||
// `reply` holding only its lines; neither key when nothing is owed.
|
|
||||||
const subagentsOwed = () => {
|
|
||||||
awaitSubagentSync(dir, state.workflow);
|
|
||||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
|
||||||
return [out.subagents ? out : {}, cursor];
|
|
||||||
};
|
|
||||||
|
|
||||||
// Reuse a live server if one is already serving this session.
|
// Reuse a live server if one is already serving this session.
|
||||||
if (existing && (await reusable)) {
|
if (existing && (await reusable)) {
|
||||||
if (!args["no-open"]) openBrowser(existing.url);
|
if (!args["no-open"]) openBrowser(existing.url);
|
||||||
const [owed, subCursor] = subagentsOwed();
|
|
||||||
print({
|
print({
|
||||||
ok: true,
|
ok: true,
|
||||||
sid,
|
sid,
|
||||||
@@ -367,11 +346,9 @@ async function cmdOpen() {
|
|||||||
pendingResult: carried,
|
pendingResult: carried,
|
||||||
terminalLine: terminalLine(existing.url),
|
terminalLine: terminalLine(existing.url),
|
||||||
workspace,
|
workspace,
|
||||||
...owed,
|
|
||||||
...swept,
|
...swept,
|
||||||
...remoteWarning(),
|
...remoteWarning(),
|
||||||
});
|
});
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
sweep();
|
sweep();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -404,7 +381,6 @@ async function cmdOpen() {
|
|||||||
const notes = [];
|
const notes = [];
|
||||||
if (remote.note) notes.push(remote.note);
|
if (remote.note) notes.push(remote.note);
|
||||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||||
const [owed, subCursor] = subagentsOwed();
|
|
||||||
print({
|
print({
|
||||||
ok: true,
|
ok: true,
|
||||||
sid,
|
sid,
|
||||||
@@ -415,12 +391,10 @@ async function cmdOpen() {
|
|||||||
pendingResult: carried,
|
pendingResult: carried,
|
||||||
terminalLine: terminalLine(handle.url),
|
terminalLine: terminalLine(handle.url),
|
||||||
workspace,
|
workspace,
|
||||||
...owed,
|
|
||||||
...swept,
|
...swept,
|
||||||
...(remote.remote ? { remote: remote.remote } : {}),
|
...(remote.remote ? { remote: remote.remote } : {}),
|
||||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||||
});
|
});
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
// After the print, never before it: the page and the link wait for nothing.
|
// After the print, never before it: the page and the link wait for nothing.
|
||||||
sweep();
|
sweep();
|
||||||
}
|
}
|
||||||
@@ -429,11 +403,10 @@ async function cmdOpen() {
|
|||||||
* The workspace as `open` hands it to the agent, and the cursor seeded to
|
* The workspace as `open` hands it to the agent, and the cursor seeded to
|
||||||
* match: the agent now has the whole list, so no change up to here is owed.
|
* match: the agent now has the whole list, so no change up to here is owed.
|
||||||
* Read-only on workspace.json, which only the server writes; on a fresh
|
* Read-only on workspace.json, which only the server writes; on a fresh
|
||||||
* session the server has not made it yet, so what was remembered for this
|
* session the server has not made it yet, so the original folder stands in.
|
||||||
* folder and spec stands in, the same list the server is about to make.
|
|
||||||
*/
|
*/
|
||||||
function workspaceOnOpen(dir, worktree, specDir) {
|
function workspaceOnOpen(dir, worktree) {
|
||||||
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
|
const ws = readWorkspace(dir) || initialWorkspace(worktree);
|
||||||
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
|
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
|
||||||
try {
|
try {
|
||||||
writeWorkspaceCursor(dir, ws.version || 0);
|
writeWorkspaceCursor(dir, ws.version || 0);
|
||||||
@@ -616,13 +589,6 @@ function cmdPost() {
|
|||||||
const next = written.state;
|
const next = written.state;
|
||||||
|
|
||||||
for (const line of ledgerLines) appendLedger(dir, line);
|
for (const line of ledgerLines) appendLedger(dir, line);
|
||||||
// A build scores its tasks as it clears them (meter.js, PROGRESS_WORKFLOWS),
|
|
||||||
// after any `run` in the same post, so a phase finished here ends its count.
|
|
||||||
if (patch.headline && typeof patch.headline === "object") {
|
|
||||||
const ledger = readLedger(dir);
|
|
||||||
const progress = progressEntry(ledger, lastLaunchId(ledger), next.workflow, patch.headline.cleared);
|
|
||||||
if (progress) appendLedger(dir, progress);
|
|
||||||
}
|
|
||||||
appendEvent(dir, { type: "post", items: (patch.items || []).length });
|
appendEvent(dir, { type: "post", items: (patch.items || []).length });
|
||||||
|
|
||||||
const open = next.items.filter((i) => isOpen(i) && i.required !== false).length;
|
const open = next.items.filter((i) => isOpen(i) && i.required !== false).length;
|
||||||
@@ -797,7 +763,7 @@ function serverGone(sid) {
|
|||||||
|
|
||||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||||
function deliverChat(dir, sid, entries, url) {
|
function deliverChat(dir, sid, entries, url) {
|
||||||
const [withWs, changes] = withWorkspace(dir, {
|
const [out, changes] = withWorkspace(dir, {
|
||||||
type: "chat",
|
type: "chat",
|
||||||
at: nowIso(),
|
at: nowIso(),
|
||||||
sid,
|
sid,
|
||||||
@@ -805,11 +771,9 @@ function deliverChat(dir, sid, entries, url) {
|
|||||||
chat: entries,
|
chat: entries,
|
||||||
reply: chatReplyLines(entries),
|
reply: chatReplyLines(entries),
|
||||||
});
|
});
|
||||||
const [out, subCursor] = withSubagents(dir, withWs);
|
|
||||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||||
advanceCursor(dir, entries);
|
advanceCursor(dir, entries);
|
||||||
advanceWorkspace(dir, changes);
|
advanceWorkspace(dir, changes);
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
process.exitCode = 0;
|
process.exitCode = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -831,52 +795,6 @@ function advanceWorkspace(dir, changes) {
|
|||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The server rewrites the session's setting for a new workflow only once its
|
|
||||||
// watcher sees the state `open` just wrote, so a launch or hop that read the
|
|
||||||
// file at once would find the old workflow's and owe the agent nothing until
|
|
||||||
// its next pickup. Give the server a moment to catch up instead, never
|
|
||||||
// writing the file ourselves (FR-7). A session with no setting file at all is
|
|
||||||
// an older server, which never writes one: a short look, not the full wait.
|
|
||||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
|
||||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
|
||||||
function awaitSubagentSync(dir, workflow) {
|
|
||||||
if (!offered(workflow)) return;
|
|
||||||
const start = Date.now();
|
|
||||||
for (;;) {
|
|
||||||
const setting = readSubagentSetting(dir);
|
|
||||||
if (setting && setting.workflow === workflow) return;
|
|
||||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
|
||||||
if (Date.now() - start >= budget) return;
|
|
||||||
sleepSync(25);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Subagents switch the agent is owed, added to what it is about to read:
|
|
||||||
// the setting as `subagents`, and its lines last in `reply`, after card lines,
|
|
||||||
// Quick questions and Workspace lines (FR-9). Read from the session's own
|
|
||||||
// setting file only, which only the server writes (FR-7). A setting for
|
|
||||||
// another workflow is the server not having caught up with a hop yet: it
|
|
||||||
// rides on the next pickup instead.
|
|
||||||
function withSubagents(dir, out) {
|
|
||||||
const setting = readSubagentSetting(dir);
|
|
||||||
if (!setting) return [out, null];
|
|
||||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
|
||||||
if (setting.workflow !== workflow) return [out, null];
|
|
||||||
const block = blockFor(setting, readSubagentCursor(dir));
|
|
||||||
if (!block) return [out, null];
|
|
||||||
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
|
|
||||||
return [{ ...out, subagents: block.field, reply }, block.cursor];
|
|
||||||
}
|
|
||||||
|
|
||||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
|
||||||
// block at the next pickup, never loses it.
|
|
||||||
function advanceSubagents(dir, cursor) {
|
|
||||||
if (!cursor) return;
|
|
||||||
try {
|
|
||||||
writeSubagentCursor(dir, cursor);
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Print first, then this, exactly as consume() stamps a result: a kill in
|
// Print first, then this, exactly as consume() stamps a result: a kill in
|
||||||
// between can only hand the same chat over again, and collectChat() drops
|
// between can only hand the same chat over again, and collectChat() drops
|
||||||
// anything that already has a reply.
|
// anything that already has a reply.
|
||||||
@@ -903,17 +821,15 @@ async function cmdChat() {
|
|||||||
}
|
}
|
||||||
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||||
const changes = pendingWorkspaceChanges(dir);
|
const changes = pendingWorkspaceChanges(dir);
|
||||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
if (!entries.length && !changes.length) {
|
||||||
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
|
|
||||||
if (!entries.length && !changes.length && !subCursor) {
|
|
||||||
print({ chat: [] });
|
print({ chat: [] });
|
||||||
process.exitCode = 10;
|
process.exitCode = 10;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||||
|
print({ chat: entries, workspace: changes, reply, terminalLine: terminalLine(handle.url) });
|
||||||
advanceCursor(dir, entries);
|
advanceCursor(dir, entries);
|
||||||
advanceWorkspace(dir, changes);
|
advanceWorkspace(dir, changes);
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
process.exitCode = 0;
|
process.exitCode = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -938,8 +854,7 @@ function consume(dir, resultPath, result, url, chat = []) {
|
|||||||
// never on result.json itself.
|
// never on result.json itself.
|
||||||
const withChat = { ...collected, chat };
|
const withChat = { ...collected, chat };
|
||||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
const [out, changes] = withWorkspace(dir, withChat);
|
||||||
const [out, subCursor] = withSubagents(dir, withWs);
|
|
||||||
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
||||||
try {
|
try {
|
||||||
writeJsonAtomic(resultPath, collected);
|
writeJsonAtomic(resultPath, collected);
|
||||||
@@ -948,7 +863,6 @@ function consume(dir, resultPath, result, url, chat = []) {
|
|||||||
ledgerAnswers(dir, result);
|
ledgerAnswers(dir, result);
|
||||||
advanceCursor(dir, chat);
|
advanceCursor(dir, chat);
|
||||||
advanceWorkspace(dir, changes);
|
advanceWorkspace(dir, changes);
|
||||||
advanceSubagents(dir, subCursor);
|
|
||||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1032,18 +946,6 @@ function realNearest(p) {
|
|||||||
return path.join(fs.realpathSync(existing), path.relative(existing, p));
|
return path.join(fs.realpathSync(existing), path.relative(existing, p));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --------------------------------------------------------------- forget */
|
|
||||||
|
|
||||||
// Drop the folder list remembered for one spec (Finalize, once the spec is
|
|
||||||
// archived). The project's own list and every other spec's are untouched.
|
|
||||||
function cmdForget() {
|
|
||||||
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
|
|
||||||
let spec = specKey(args.spec);
|
|
||||||
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
|
|
||||||
const worktree = repoRoots().worktree;
|
|
||||||
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ----------------------------------------------------------------- help */
|
/* ----------------------------------------------------------------- help */
|
||||||
|
|
||||||
function cmdHelp() {
|
function cmdHelp() {
|
||||||
@@ -1059,20 +961,13 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
|||||||
first post. --file is optional, and --title defaults to the
|
first post. --file is optional, and --title defaults to the
|
||||||
project's folder name. Also prints workspace: { folders: [{ name,
|
project's folder name. Also prints workspace: { folders: [{ name,
|
||||||
path, description?, original? }], missing? }, the folders this
|
path, description?, original? }], missing? }, the folders this
|
||||||
console session reads as context, addressed as @name. The list is
|
console session reads as context, addressed as @name.
|
||||||
remembered per folder and spec in workspaces.json beside looks.json.
|
|
||||||
May also print subagents: { state, revision, max, instruction } and
|
|
||||||
a reply holding only its "Subagents: ..." lines, when a standing
|
|
||||||
instruction (the page's Subagents switch) is owed to you.
|
|
||||||
post --session <sid> --file <patch.json>
|
post --session <sid> --file <patch.json>
|
||||||
Merge a patch into the session. Prints terminalLine while the
|
Merge a patch into the session. Prints terminalLine while the
|
||||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||||
{ name, reason, hint? } (a workspace folder you could not read);
|
{ name, reason, hint? } (a workspace folder you could not read);
|
||||||
both go to the ledger, never into the state. A patch may also
|
both go to the ledger, never into the state.
|
||||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
|
||||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
|
||||||
(see console.md → Standing instructions).
|
|
||||||
wait --session <sid> [--seconds <N>]
|
wait --session <sid> [--seconds <N>]
|
||||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||||
@@ -1083,24 +978,16 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
|||||||
"workspace" (changes since you last heard, each once, with a
|
"workspace" (changes since you last heard, each once, with a
|
||||||
"Workspace: ..." line in reply); exit 10 counts them as
|
"Workspace: ..." line in reply); exit 10 counts them as
|
||||||
pendingWorkspace, and a change alone never ends a slice.
|
pendingWorkspace, and a change alone never ends a slice.
|
||||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
|
||||||
by the person, with its "Subagents: ..." lines last in reply); a
|
|
||||||
setting change alone never ends a slice either.
|
|
||||||
chat --session <sid>
|
chat --session <sid>
|
||||||
Collect Quick questions, workspace changes and a Subagents
|
Collect Quick questions and workspace changes now, never waiting,
|
||||||
setting change now, never waiting, never touching card sends.
|
never touching card sends. Exit 0 = { chat, workspace, reply,
|
||||||
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
|
terminalLine }, 10 = none, 20 = server gone.
|
||||||
10 = none, 20 = server gone.
|
|
||||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||||
messages with it during a console session.
|
messages with it during a console session.
|
||||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||||
Copy a cited note attachment into specs/<idea>/attachments/. Prints
|
Copy a cited note attachment into specs/<idea>/attachments/. Prints
|
||||||
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
|
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
|
||||||
missing. Paste link as it is.
|
missing. Paste link as it is.
|
||||||
forget --spec specs/<idea>
|
|
||||||
Drop the workspace folders remembered for that spec, in this
|
|
||||||
folder (Finalize, after archiving it). Prints { ok, spec, forgot };
|
|
||||||
forgot is false when nothing was saved. Exit 2 = bad usage.
|
|
||||||
status [--session <sid>] [--all]
|
status [--session <sid>] [--all]
|
||||||
One session, or every session belonging to this project.
|
One session, or every session belonging to this project.
|
||||||
stop --session <sid> | --all
|
stop --session <sid> | --all
|
||||||
@@ -1319,7 +1206,6 @@ const COMMANDS = {
|
|||||||
wait: cmdWait,
|
wait: cmdWait,
|
||||||
chat: cmdChat,
|
chat: cmdChat,
|
||||||
keep: cmdKeep,
|
keep: cmdKeep,
|
||||||
forget: cmdForget,
|
|
||||||
status: cmdStatus,
|
status: cmdStatus,
|
||||||
stop: cmdStop,
|
stop: cmdStop,
|
||||||
help: cmdHelp,
|
help: cmdHelp,
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ import { fileURLToPath } from "node:url";
|
|||||||
import { CHAT_LIMIT } from "./public/chat.js";
|
import { CHAT_LIMIT } from "./public/chat.js";
|
||||||
import { DOC_TYPES } from "./public/answers.js";
|
import { DOC_TYPES } from "./public/answers.js";
|
||||||
import { defaultName } from "./public/workspace.js";
|
import { defaultName } from "./public/workspace.js";
|
||||||
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
|
||||||
|
|
||||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
export const PUBLIC_DIR = path.join(HERE, "public");
|
export const PUBLIC_DIR = path.join(HERE, "public");
|
||||||
@@ -49,10 +48,6 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
|
|||||||
|
|
||||||
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
||||||
|
|
||||||
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
|
|
||||||
// so every session within the hour reuses one lookup.
|
|
||||||
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
|
|
||||||
|
|
||||||
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
||||||
// test run (or a second sandboxed instance) shares one handle directory with
|
// test run (or a second sandboxed instance) shares one handle directory with
|
||||||
// the real thing, and `stop --all` reaches outside its own world and kills a
|
// the real thing, and `stop --all` reaches outside its own world and kills a
|
||||||
@@ -183,8 +178,8 @@ function lockStale(lock) {
|
|||||||
// Run fn while holding the session's state lock, and release it however fn
|
// Run fn while holding the session's state lock, and release it however fn
|
||||||
// ends. fn must not call process.exit(): the release would never run, and the
|
// ends. fn must not call process.exit(): the release would never run, and the
|
||||||
// next writer would wait out the stale age.
|
// next writer would wait out the stale age.
|
||||||
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
|
export function withStateLock(dir, fn) {
|
||||||
const lock = path.join(dir, lockName);
|
const lock = path.join(dir, STATE_LOCK_FILE);
|
||||||
const deadline = Date.now() + LOCK_WAIT_MS;
|
const deadline = Date.now() + LOCK_WAIT_MS;
|
||||||
let fd = null;
|
let fd = null;
|
||||||
for (let attempt = 0; fd === null; attempt++) {
|
for (let attempt = 0; fd === null; attempt++) {
|
||||||
@@ -193,7 +188,7 @@ export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
|
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
|
||||||
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
|
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
|
||||||
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
|
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
|
||||||
if (err.code === "EEXIST" && lockStale(lock)) {
|
if (err.code === "EEXIST" && lockStale(lock)) {
|
||||||
try {
|
try {
|
||||||
fs.rmSync(lock, { force: true });
|
fs.rmSync(lock, { force: true });
|
||||||
@@ -492,16 +487,8 @@ export async function removeSessions(sessionsDir, sids) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The console folder's own files that no sweep may ever remove: the person's
|
// The console folder's own files that no sweep may ever remove: the person's
|
||||||
// looks, the folders remembered per project and spec, the Subagents switch
|
// looks and the pointer to this console's directory.
|
||||||
// saved per project and workflow, the pointer to this console's directory,
|
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "console-dir"]);
|
||||||
// and the cached release check.
|
|
||||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
|
||||||
"looks.json",
|
|
||||||
"workspaces.json",
|
|
||||||
"subagents.json",
|
|
||||||
"console-dir",
|
|
||||||
"update-check.json",
|
|
||||||
]);
|
|
||||||
|
|
||||||
function isScratchName(name) {
|
function isScratchName(name) {
|
||||||
return (
|
return (
|
||||||
@@ -548,148 +535,6 @@ export async function removeScratch(consoleDir, names) {
|
|||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------- cleanup */
|
|
||||||
|
|
||||||
// What User Preferences -> Cleanup never removes. The console folder keeps its
|
|
||||||
// protected files, its sessions dir (old sessions go one by one, by age) and,
|
|
||||||
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
|
|
||||||
// console, the launcher (bin/, launcher.json) and the models the person added.
|
|
||||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
|
||||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
|
|
||||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
|
||||||
// folders hold files that live for milliseconds -- a held
|
|
||||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
|
||||||
// rename -- and removing one mid-write loses another session's change.
|
|
||||||
export const STRAY_GRACE_MS = 60 * 60 * 1000;
|
|
||||||
|
|
||||||
// Bytes under `p`, never following a symlink: a link counts as itself.
|
|
||||||
async function diskBytes(p) {
|
|
||||||
let st;
|
|
||||||
try {
|
|
||||||
st = await fs.promises.lstat(p);
|
|
||||||
} catch {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
if (!st.isDirectory()) return st.size;
|
|
||||||
let entries;
|
|
||||||
try {
|
|
||||||
entries = await fs.promises.readdir(p);
|
|
||||||
} catch {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
let total = 0;
|
|
||||||
for (const name of entries) total += await diskBytes(path.join(p, name));
|
|
||||||
return total;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The newest mtime of anything under `p`, never following a symlink. A folder
|
|
||||||
// counts by its files, since rewriting a file never touches its folder's
|
|
||||||
// mtime; an empty folder counts by its own. Anything unreadable on the way
|
|
||||||
// down answers Infinity, so it reads as just touched and stays.
|
|
||||||
function newestMtime(p) {
|
|
||||||
let st;
|
|
||||||
try {
|
|
||||||
st = fs.lstatSync(p);
|
|
||||||
} catch {
|
|
||||||
return Infinity;
|
|
||||||
}
|
|
||||||
if (!st.isDirectory()) return st.mtimeMs;
|
|
||||||
let entries;
|
|
||||||
try {
|
|
||||||
entries = fs.readdirSync(p);
|
|
||||||
} catch {
|
|
||||||
return Infinity;
|
|
||||||
}
|
|
||||||
if (!entries.length) return st.mtimeMs;
|
|
||||||
let newest = 0;
|
|
||||||
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
|
|
||||||
return newest;
|
|
||||||
}
|
|
||||||
|
|
||||||
function entryKind(entry) {
|
|
||||||
if (entry.isSymbolicLink()) return "link";
|
|
||||||
return entry.isDirectory() ? "folder" : "file";
|
|
||||||
}
|
|
||||||
|
|
||||||
function strayEntries(dir, kept, where, now) {
|
|
||||||
let entries;
|
|
||||||
try {
|
|
||||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
||||||
} catch {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
|
|
||||||
return entries
|
|
||||||
.filter((e) => !kept.has(e.name))
|
|
||||||
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
|
||||||
.filter((e) => settled(e.path));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Everything Cleanup would remove, worked out on the server and never taken
|
|
||||||
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
|
|
||||||
* `open` sweeps by, plus every file in the folder that old, so a resumed
|
|
||||||
* session or a saved draft keeps it), anything at the top of the console folder that is
|
|
||||||
* not kept, and -- only when the console runs from its default home inside
|
|
||||||
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
|
|
||||||
* touched within `STRAY_GRACE_MS` are left for a later scan. A
|
|
||||||
* console running from another home (tests, dev) never reaches ~/.plan2code.
|
|
||||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
|
||||||
*/
|
|
||||||
export async function cleanupFindings({
|
|
||||||
consoleDir = HOME_DIR,
|
|
||||||
plan2codeDir = PLAN2CODE_DIR,
|
|
||||||
now = Date.now(),
|
|
||||||
maxAgeMs = SESSION_MAX_AGE_MS,
|
|
||||||
skipSid,
|
|
||||||
} = {}) {
|
|
||||||
const found = [];
|
|
||||||
const sessionsDir = path.join(consoleDir, "sessions");
|
|
||||||
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
|
|
||||||
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
|
|
||||||
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
|
|
||||||
}
|
|
||||||
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
|
|
||||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
|
||||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
|
||||||
}
|
|
||||||
const items = [];
|
|
||||||
let bytes = 0;
|
|
||||||
for (const f of found) {
|
|
||||||
const size = await diskBytes(f.path);
|
|
||||||
bytes += size;
|
|
||||||
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
|
|
||||||
}
|
|
||||||
return { items, bytes };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
|
|
||||||
* worked out afresh first and only ids on it are touched, so a name from the
|
|
||||||
* page is never a path, and anything that stopped qualifying since the scan
|
|
||||||
* (a session touched again) stays. A link is unlinked, never followed.
|
|
||||||
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
|
|
||||||
*/
|
|
||||||
export async function removeCleanup(ids, opts = {}) {
|
|
||||||
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
|
|
||||||
const { items } = await cleanupFindings(opts);
|
|
||||||
const removed = [];
|
|
||||||
const failed = [];
|
|
||||||
let bytes = 0;
|
|
||||||
for (const item of items) {
|
|
||||||
if (!wanted.has(item.id)) continue;
|
|
||||||
try {
|
|
||||||
if (item.kind === "link") await fs.promises.unlink(item.path);
|
|
||||||
else await fs.promises.rm(item.path, { recursive: true, force: true });
|
|
||||||
removed.push(item.id);
|
|
||||||
bytes += item.bytes;
|
|
||||||
} catch {
|
|
||||||
failed.push(item.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { removed, bytes, failed };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
||||||
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
||||||
@@ -1025,7 +870,7 @@ export function handOff(child, pre) {
|
|||||||
|
|
||||||
/* ----------------------------------------------------------- patch merge */
|
/* ----------------------------------------------------------- patch merge */
|
||||||
|
|
||||||
const APPEND_KEYS = new Set(["thread"]);
|
const APPEND_KEYS = new Set(["thread", "comments"]);
|
||||||
|
|
||||||
function isPlainObject(v) {
|
function isPlainObject(v) {
|
||||||
return v !== null && typeof v === "object" && !Array.isArray(v);
|
return v !== null && typeof v === "object" && !Array.isArray(v);
|
||||||
@@ -1050,7 +895,7 @@ function mergeOne(target, patch, where) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
||||||
// Named fields are replaced whole; thread appends.
|
// Named fields are replaced whole; thread/comments append.
|
||||||
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||||
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
||||||
for (const entry of patchList) {
|
for (const entry of patchList) {
|
||||||
@@ -1109,60 +954,11 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
|||||||
return merged;
|
return merged;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
|
|
||||||
// borrow the shape of the replies and doc blocks they also write, so `from` /
|
|
||||||
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
|
|
||||||
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
|
|
||||||
// at all is refused. The person's own notes are recorded by the server when
|
|
||||||
// they send, so an agent that echoes one back is not shown it twice.
|
|
||||||
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
|
|
||||||
|
|
||||||
function normalizeThreads(patchList, currentItems) {
|
|
||||||
return patchList.map((entry) => {
|
|
||||||
if (!isPlainObject(entry) || entry.thread == null) return entry;
|
|
||||||
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
|
|
||||||
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
|
|
||||||
const said = new Set(
|
|
||||||
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
|
|
||||||
);
|
|
||||||
const thread = [];
|
|
||||||
for (const m of entry.thread) {
|
|
||||||
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
|
|
||||||
guard(m, "thread");
|
|
||||||
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
|
|
||||||
if (!key) {
|
|
||||||
throw new Error(
|
|
||||||
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const { from, role, md, body, content, ...rest } = m;
|
|
||||||
const who = (m.who || from || role) === "user" ? "user" : "agent";
|
|
||||||
const text = m[key];
|
|
||||||
if (who === "user" && said.has(text.trim())) continue;
|
|
||||||
thread.push({ ...rest, who, text });
|
|
||||||
}
|
|
||||||
return { ...entry, thread };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
||||||
|
|
||||||
// Blocks merge by id like docs do, so a patch that only settles a block's
|
// Blocks merge by id like docs do, so a patch that only settles a block's
|
||||||
// state keeps its text. Blocks left out of the patch stay as they are.
|
// state keeps its text. Blocks left out of the patch stay as they are.
|
||||||
function mergeDocs(current, patchList) {
|
function mergeDocs(current, patchList) {
|
||||||
// A doc's version only moves forward. One going back is a stale or copied
|
|
||||||
// payload (last phase's progress script, say), and the page would quietly
|
|
||||||
// show the old content under the new run's name.
|
|
||||||
for (const entry of patchList) {
|
|
||||||
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
|
|
||||||
const prev = (current || []).find((d) => d && d.id === entry.id);
|
|
||||||
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
|
|
||||||
throw new Error(
|
|
||||||
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
|
|
||||||
"Versions only go up: bump it, and check the payload is the current one."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
||||||
for (const entry of patchList) {
|
for (const entry of patchList) {
|
||||||
if (!Array.isArray(entry.blocks)) continue;
|
if (!Array.isArray(entry.blocks)) continue;
|
||||||
@@ -1199,19 +995,12 @@ export function applyPatch(state, patch) {
|
|||||||
break;
|
break;
|
||||||
case "items":
|
case "items":
|
||||||
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
||||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
|
next.items = dropStaleSubmissions(next.items, state.items, v);
|
||||||
break;
|
break;
|
||||||
case "topics":
|
case "topics":
|
||||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||||
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
||||||
break;
|
break;
|
||||||
case "helpers":
|
|
||||||
// The agent's report of its helpers, for the page's Subagents tab.
|
|
||||||
// Only `post` writes it; the server's /submit never touches it.
|
|
||||||
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
|
|
||||||
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
|
|
||||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
|
||||||
break;
|
|
||||||
case "docs":
|
case "docs":
|
||||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||||
next.docs = mergeDocs(next.docs, v);
|
next.docs = mergeDocs(next.docs, v);
|
||||||
@@ -1258,11 +1047,15 @@ function stampTimes(before, next) {
|
|||||||
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
||||||
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
||||||
}
|
}
|
||||||
if (Array.isArray(next.items)) {
|
for (const list of [next.items, next.docs]) {
|
||||||
for (const entry of next.items) {
|
if (!Array.isArray(list)) continue;
|
||||||
|
for (const entry of list) {
|
||||||
if (Array.isArray(entry.thread)) {
|
if (Array.isArray(entry.thread)) {
|
||||||
for (const m of entry.thread) if (!m.at) m.at = now;
|
for (const m of entry.thread) if (!m.at) m.at = now;
|
||||||
}
|
}
|
||||||
|
if (Array.isArray(entry.comments)) {
|
||||||
|
for (const m of entry.comments) if (!m.at) m.at = now;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Array.isArray(next.docs)) {
|
if (Array.isArray(next.docs)) {
|
||||||
@@ -1495,10 +1288,7 @@ export function validate(state) {
|
|||||||
// server's record of an answer someone pressed Send on; if their own words
|
// server's record of an answer someone pressed Send on; if their own words
|
||||||
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
||||||
// would be rejected and the session would wedge with no way out.
|
// would be rejected and the session would wedge with no way out.
|
||||||
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
|
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
|
||||||
...rest,
|
|
||||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
|
||||||
}));
|
|
||||||
const prose =
|
const prose =
|
||||||
JSON.stringify(authored) +
|
JSON.stringify(authored) +
|
||||||
JSON.stringify(state.docs || []) +
|
JSON.stringify(state.docs || []) +
|
||||||
@@ -1506,20 +1296,6 @@ export function validate(state) {
|
|||||||
JSON.stringify(state.menu || {});
|
JSON.stringify(state.menu || {});
|
||||||
problems.push(...proseProblems(prose));
|
problems.push(...proseProblems(prose));
|
||||||
|
|
||||||
// The agent's report of its helpers: the shape the page draws from
|
|
||||||
// (subagents.js), then the same prose scan as everything else it writes.
|
|
||||||
if (state.helpers != null) {
|
|
||||||
problems.push(...checkHelpers(state.helpers));
|
|
||||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
|
||||||
if (!isPlainObject(helper)) continue;
|
|
||||||
for (const field of ["title", "ask", "result"]) {
|
|
||||||
if (typeof helper[field] === "string") {
|
|
||||||
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return problems;
|
return problems;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1549,8 +1325,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
|||||||
* A resume that passes through the dashboard (a finished skill going back to
|
* A resume that passes through the dashboard (a finished skill going back to
|
||||||
* it, or a launch from its menu) is a new skill taking the page over, so it
|
* it, or a launch from its menu) is a new skill taking the page over, so it
|
||||||
* starts from a blank page: the last skill's questions, sections, docs,
|
* starts from a blank page: the last skill's questions, sections, docs,
|
||||||
* helpers, headline and ending are its record on disk, not the next skill's
|
* headline and ending are its record on disk, not the next skill's opening.
|
||||||
* opening.
|
|
||||||
* Only the session's identity carries across. `workspace.json`,
|
* Only the session's identity carries across. `workspace.json`,
|
||||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||||
* and the meter outlive every hop.
|
* and the meter outlive every hop.
|
||||||
@@ -1577,8 +1352,6 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
|
|||||||
// workspace.json the server. Folders, version, change log, missing, remote.
|
// workspace.json the server. Folders, version, change log, missing, remote.
|
||||||
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
||||||
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
||||||
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
|
|
||||||
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
|
|
||||||
export const CHAT_FILE = "chat.ndjson";
|
export const CHAT_FILE = "chat.ndjson";
|
||||||
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
||||||
export const WORKSPACE_FILE = "workspace.json";
|
export const WORKSPACE_FILE = "workspace.json";
|
||||||
@@ -1846,125 +1619,17 @@ export function readWorkspace(dir) {
|
|||||||
return readJson(path.join(dir, WORKSPACE_FILE), null);
|
return readJson(path.join(dir, WORKSPACE_FILE), null);
|
||||||
}
|
}
|
||||||
|
|
||||||
// A fresh workspace: the original folder, named after itself, plus whatever
|
// A fresh workspace: just the original folder, named after itself.
|
||||||
// was remembered for this folder and spec (rememberedWorkspace() below).
|
export function initialWorkspace(worktree) {
|
||||||
export function initialWorkspace(worktree, remembered = null) {
|
|
||||||
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
|
|
||||||
if (remembered && remembered.original) {
|
|
||||||
if (remembered.original.name) original.name = remembered.original.name;
|
|
||||||
if (remembered.original.description) original.description = remembered.original.description;
|
|
||||||
}
|
|
||||||
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
|
|
||||||
id: "f" + (i + 1),
|
|
||||||
path: f.path,
|
|
||||||
name: f.name,
|
|
||||||
description: f.description || "",
|
|
||||||
...(f.nested ? { nested: true } : {}),
|
|
||||||
}));
|
|
||||||
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------ remembered workspaces */
|
|
||||||
|
|
||||||
// The folder list outlives the console session: one file for the person,
|
|
||||||
// beside looks.json, keyed by the folder a session runs in and then by spec.
|
|
||||||
// Never under specs/: the paths are this machine's, and the server never
|
|
||||||
// writes into a project.
|
|
||||||
//
|
|
||||||
// { "projects": { "<folded worktree>": {
|
|
||||||
// "path": "<worktree>",
|
|
||||||
// "project": { original, folders, at }, // no spec picked
|
|
||||||
// "specs": { "specs/<name>": { original, folders, at } } } } }
|
|
||||||
//
|
|
||||||
// `original` holds the first folder's name and description only (its path is
|
|
||||||
// always the session's own); `folders` the added ones as { path, name,
|
|
||||||
// description, nested? }. Two writers, the server on every change and
|
|
||||||
// `console.mjs forget`, each a read-modify-write of one key.
|
|
||||||
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
|
|
||||||
|
|
||||||
const foldKey = (p) => {
|
|
||||||
const resolved = path.resolve(String(p || ""));
|
|
||||||
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
|
|
||||||
};
|
|
||||||
|
|
||||||
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
|
|
||||||
export function specKey(specDir) {
|
|
||||||
return String(specDir || "")
|
|
||||||
.trim()
|
|
||||||
.replace(/\\/g, "/")
|
|
||||||
.replace(/^\.\//, "")
|
|
||||||
.replace(/\/+$/, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function readStore() {
|
|
||||||
const saved = readJson(WORKSPACES_FILE, null);
|
|
||||||
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What was remembered for this folder and spec: `{ entry, from }`, where
|
|
||||||
* `from` is "spec" when the spec has its own list, "project" when it falls
|
|
||||||
* back to the project's (a spec's list starts as a copy of it), and null
|
|
||||||
* when nothing was ever saved.
|
|
||||||
*/
|
|
||||||
export function rememberedWorkspace(worktree, specDir) {
|
|
||||||
const project = readStore().projects[foldKey(worktree)];
|
|
||||||
if (!project) return { entry: null, from: null };
|
|
||||||
const spec = specKey(specDir);
|
|
||||||
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
|
|
||||||
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
|
|
||||||
}
|
|
||||||
|
|
||||||
// The workspace's folders as the store keeps them.
|
|
||||||
export function rememberable(ws) {
|
|
||||||
const folders = (ws && ws.folders) || [];
|
|
||||||
const first = folders.find((f) => f.original) || {};
|
|
||||||
return {
|
return {
|
||||||
original: { name: first.name || "", description: first.description || "" },
|
version: 0,
|
||||||
folders: folders
|
folders: [{ id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true }],
|
||||||
.filter((f) => !f.original)
|
missing: [],
|
||||||
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
|
changes: [],
|
||||||
at: nowIso(),
|
remote: "",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Every server and `console.mjs forget` writes the one file, so each
|
|
||||||
// read-modify-write holds this lock beside it.
|
|
||||||
const WORKSPACES_LOCK = "workspaces.json.lock";
|
|
||||||
|
|
||||||
// Save the list for this folder and spec ("" for the project's own).
|
|
||||||
export function rememberWorkspace(worktree, specDir, ws) {
|
|
||||||
ensureDir(path.dirname(WORKSPACES_FILE));
|
|
||||||
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveRemembered(worktree, specDir, ws) {
|
|
||||||
const store = readStore();
|
|
||||||
const key = foldKey(worktree);
|
|
||||||
const project = store.projects[key] || { path: path.resolve(worktree) };
|
|
||||||
const spec = specKey(specDir);
|
|
||||||
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
|
|
||||||
else project.project = rememberable(ws);
|
|
||||||
store.projects[key] = project;
|
|
||||||
writeJsonAtomic(WORKSPACES_FILE, store);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
|
|
||||||
export function forgetWorkspace(worktree, specDir) {
|
|
||||||
const spec = specKey(specDir);
|
|
||||||
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
|
|
||||||
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
|
|
||||||
}
|
|
||||||
|
|
||||||
function dropRemembered(worktree, spec) {
|
|
||||||
const store = readStore();
|
|
||||||
const project = store.projects[foldKey(worktree)];
|
|
||||||
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
|
|
||||||
delete project.specs[spec];
|
|
||||||
writeJsonAtomic(WORKSPACES_FILE, store);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only server.mjs may call this.
|
// Single-writer rule: only server.mjs may call this.
|
||||||
export function writeWorkspace(dir, ws) {
|
export function writeWorkspace(dir, ws) {
|
||||||
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
|
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
|
||||||
@@ -2034,98 +1699,6 @@ export function pendingWorkspaceChanges(dir) {
|
|||||||
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------ the Subagents switch */
|
|
||||||
|
|
||||||
// The person's Subagents switch, remembered per project folder and workflow:
|
|
||||||
//
|
|
||||||
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
|
|
||||||
//
|
|
||||||
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
|
|
||||||
// workflow's shipped default.
|
|
||||||
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
|
|
||||||
const SUBAGENTS_LOCK = "subagents.json.lock";
|
|
||||||
|
|
||||||
function readSubagentStore() {
|
|
||||||
const saved = readJson(SUBAGENTS_FILE, null);
|
|
||||||
return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
|
||||||
}
|
|
||||||
|
|
||||||
// The saved `{ on, instruction, max }` for this folder and workflow, or the
|
|
||||||
// default's when nothing (or something malformed) is saved.
|
|
||||||
export function subagentStoreEntry(worktree, workflow) {
|
|
||||||
const { on, instruction, max } = defaultSetting(workflow);
|
|
||||||
const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null;
|
|
||||||
const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null;
|
|
||||||
return saved && !saved.error ? saved : { on, instruction, max };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only server.mjs may call this.
|
|
||||||
export function saveSubagentStoreEntry(worktree, workflow, value) {
|
|
||||||
ensureDir(path.dirname(SUBAGENTS_FILE));
|
|
||||||
withStateLock(
|
|
||||||
path.dirname(SUBAGENTS_FILE),
|
|
||||||
() => {
|
|
||||||
const store = readSubagentStore();
|
|
||||||
const key = foldKey(worktree);
|
|
||||||
const project = store[key] && typeof store[key] === "object" ? store[key] : {};
|
|
||||||
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } };
|
|
||||||
writeJsonAtomic(SUBAGENTS_FILE, store);
|
|
||||||
},
|
|
||||||
SUBAGENTS_LOCK
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
|
||||||
|
|
||||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
|
||||||
|
|
||||||
// This session's switch, `{ workflow, on, instruction, max, revision }`, or
|
|
||||||
// null when there is none or it is malformed.
|
|
||||||
export function readSubagentSetting(dir) {
|
|
||||||
const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null);
|
|
||||||
if (!s || typeof s !== "object") return null;
|
|
||||||
if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null;
|
|
||||||
return s;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only server.mjs may call this. The revision never goes
|
|
||||||
// backwards within a session.
|
|
||||||
export function writeSubagentSetting(dir, setting) {
|
|
||||||
const previous = readSubagentSetting(dir);
|
|
||||||
const revision = Math.max(previous ? previous.revision : 0, setting.revision);
|
|
||||||
return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision });
|
|
||||||
}
|
|
||||||
|
|
||||||
export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json";
|
|
||||||
const CURSOR_STATES = new Set(["none", "on", "off"]);
|
|
||||||
|
|
||||||
// What the agent was last told: `{ revision, state }`.
|
|
||||||
export function readSubagentCursor(dir) {
|
|
||||||
const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null);
|
|
||||||
if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" };
|
|
||||||
return { revision: saved.revision, state: saved.state };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-writer rule: only console.mjs may call this. Never backwards, like
|
|
||||||
// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one.
|
|
||||||
export function writeSubagentCursor(dir, cursor) {
|
|
||||||
const old = readSubagentCursor(dir);
|
|
||||||
const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state };
|
|
||||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The one place the cursor may go back: `open`, which starts a fresh agent.
|
|
||||||
export function resetSubagentCursor(dir) {
|
|
||||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// The `caps` of the last `open` event: what the agent's console copy can do.
|
|
||||||
export function latestOpenCaps(dir) {
|
|
||||||
const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open");
|
|
||||||
const last = opens[opens.length - 1];
|
|
||||||
return last && Array.isArray(last.caps) ? last.caps : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flag the case where the link cannot be opened by the person it is for.
|
* Flag the case where the link cannot be opened by the person it is for.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
|
|||||||
if (!s || typeof s !== "object") return null;
|
if (!s || typeof s !== "object") return null;
|
||||||
if (item.answer && typeof item.answer === "object") return null;
|
if (item.answer && typeof item.answer === "object") return null;
|
||||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||||
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
|
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||||
return replied ? null : s;
|
return replied ? null : s;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,33 +74,17 @@ export function submittedAwaiting(item) {
|
|||||||
* agent has yet to say anything after it. The server records it as `sentNote`
|
* agent has yet to say anything after it. The server records it as `sentNote`
|
||||||
* on every send, so the page can show it in the Notes pane and in the Sent
|
* on every send, so the page can show it in the Notes pane and in the Sent
|
||||||
* box instead of letting it vanish into a send that shows no sign of arriving.
|
* box instead of letting it vanish into a send that shows no sign of arriving.
|
||||||
* Any agent message from the send onwards, or one with no clock to compare,
|
* Any thread message from the send onwards, or none with a clock to compare,
|
||||||
* means it has been picked up. The person's own entries never count: the
|
* means it has been picked up.
|
||||||
* server writes their note into the thread as it arrives.
|
|
||||||
*/
|
*/
|
||||||
export function noteAwaiting(item) {
|
export function noteAwaiting(item) {
|
||||||
const n = item && item.sentNote;
|
const n = item && item.sentNote;
|
||||||
if (!n || typeof n !== "object") return null;
|
if (!n || typeof n !== "object") return null;
|
||||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||||
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
|
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
|
||||||
return picked ? null : n;
|
return picked ? null : n;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Who said a thread entry and what they said. The contract is `{ who, text }`
|
|
||||||
* and the server lifts anything else into it, but sessions written before that
|
|
||||||
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
|
|
||||||
*/
|
|
||||||
export function threadWho(m) {
|
|
||||||
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
|
|
||||||
}
|
|
||||||
|
|
||||||
export function threadText(m) {
|
|
||||||
if (!m) return "";
|
|
||||||
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/* -------------------------------------------------------------- labels */
|
/* -------------------------------------------------------------- labels */
|
||||||
|
|
||||||
export function optionLabel(item, k) {
|
export function optionLabel(item, k) {
|
||||||
|
|||||||
@@ -23,9 +23,6 @@
|
|||||||
--warn-soft: #fbe7e3;
|
--warn-soft: #fbe7e3;
|
||||||
--focus: #1f6feb;
|
--focus: #1f6feb;
|
||||||
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
||||||
/* A soft accent halo for the things that want noticing: the update banner
|
|
||||||
and an enabled Send. Built from --accent, so a picked accent glows too. */
|
|
||||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
|
|
||||||
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||||
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
||||||
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
||||||
@@ -64,7 +61,6 @@
|
|||||||
--warn-soft: #34201d;
|
--warn-soft: #34201d;
|
||||||
--focus: #6aa3ff;
|
--focus: #6aa3ff;
|
||||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +85,6 @@
|
|||||||
--warn-soft: #34201d;
|
--warn-soft: #34201d;
|
||||||
--focus: #6aa3ff;
|
--focus: #6aa3ff;
|
||||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
* { box-sizing: border-box; }
|
* { box-sizing: border-box; }
|
||||||
@@ -208,26 +203,6 @@ body {
|
|||||||
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
||||||
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||||
|
|
||||||
/* Subagents: an orchestrator and its helpers. Unlit is a hollow outline in
|
|
||||||
the quiet ink; lit fills the nodes with the highlight color. */
|
|
||||||
.subagents-btn { border-color: var(--rule-2); color: var(--ink-2); display: inline-flex; align-items: center; justify-content: center; }
|
|
||||||
.btn.subagents-btn { padding: 0 6px; align-self: stretch; }
|
|
||||||
.subagents-btn[hidden] { display: none; }
|
|
||||||
.subagents-btn svg { width: 16px; height: 16px; display: block; }
|
|
||||||
.subagents-btn .sa-link { fill: none; stroke: var(--ink-2); stroke-width: 1.2; stroke-linecap: round; }
|
|
||||||
.subagents-btn .sa-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
|
|
||||||
.subagents-btn .sa-node { fill: none; stroke: var(--ink-2); stroke-width: 1.2; }
|
|
||||||
.subagents-btn[aria-pressed="true"] .sa-hub,
|
|
||||||
.subagents-btn[aria-pressed="true"] .sa-node { fill: var(--accent); stroke: var(--accent); }
|
|
||||||
.subagents-btn[aria-pressed="true"] .sa-link { stroke: var(--accent); }
|
|
||||||
.subagents-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
|
||||||
.subagents-btn:hover:not(:disabled) .sa-link,
|
|
||||||
.subagents-btn:hover:not(:disabled) .sa-hub,
|
|
||||||
.subagents-btn:hover:not(:disabled) .sa-node { stroke: var(--accent); }
|
|
||||||
.subagents-btn:disabled .sa-link,
|
|
||||||
.subagents-btn:disabled .sa-hub,
|
|
||||||
.subagents-btn:disabled .sa-node { stroke: var(--ink-3); fill: none; }
|
|
||||||
|
|
||||||
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
||||||
|
|
||||||
/* The session meter: a ring that fills with the points and a few words, in
|
/* The session meter: a ring that fills with the points and a few words, in
|
||||||
@@ -1121,15 +1096,6 @@ h1 {
|
|||||||
.ask-disabled-note.is-limit, .ask-disabled-note.is-waiting { color: var(--ink-2); background: var(--panel-2); border: 1px solid var(--rule); }
|
.ask-disabled-note.is-limit, .ask-disabled-note.is-waiting { color: var(--ink-2); background: var(--panel-2); border: 1px solid var(--rule); }
|
||||||
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
||||||
|
|
||||||
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
|
|
||||||
the tiny ring, left of the label. The extra .spinner is for specificity:
|
|
||||||
.spinner.tiny comes later and zeroes the margin otherwise. */
|
|
||||||
.view-tab .spinner.tab-spin {
|
|
||||||
display: inline-block;
|
|
||||||
margin-right: 7px;
|
|
||||||
vertical-align: -1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* A reply landed while another tab was open. */
|
/* A reply landed while another tab was open. */
|
||||||
.view-tab .tab-dot {
|
.view-tab .tab-dot {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
@@ -1450,30 +1416,6 @@ h1 {
|
|||||||
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
||||||
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
||||||
|
|
||||||
/* The Subagents tab: one row per reported helper, newest state in a pill. */
|
|
||||||
.sa-card h2 { margin: 0 0 6px; }
|
|
||||||
.sa-card > .help { margin: 0 0 16px; }
|
|
||||||
.sa-alone { margin: 0; color: var(--ink-2); }
|
|
||||||
.sa-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
|
|
||||||
.sa-row { border: 1px solid var(--rule); border-radius: 8px; background: var(--panel-2); padding: 12px 14px; }
|
|
||||||
.sa-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
|
||||||
.sa-title { min-width: 0; overflow-wrap: anywhere; }
|
|
||||||
.sa-ask {
|
|
||||||
margin: 4px 0 0; color: var(--ink-2); font-size: 13.5px;
|
|
||||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
|
|
||||||
}
|
|
||||||
.sa-result { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
|
||||||
.sa-pill { display: inline-flex; align-items: center; gap: 6px; flex: none; }
|
|
||||||
.sa-pill.is-running { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
|
|
||||||
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
|
|
||||||
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
|
|
||||||
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
|
|
||||||
/* The dialog's number box, themed like the page's other inputs. */
|
|
||||||
.subagents input[type="number"] {
|
|
||||||
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
|
|
||||||
border: 1px solid var(--rule-2); border-radius: 6px; padding: 4px 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------ settled answer */
|
/* ------------------------------------------------------ settled answer */
|
||||||
|
|
||||||
.answered {
|
.answered {
|
||||||
@@ -1707,13 +1649,11 @@ input[type="text"].invalid { border-color: var(--warn); }
|
|||||||
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||||
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
||||||
/* Send glows and breathes while there is something to send: the steady
|
/* Send breathes while there is something to send: a soft accent ring that
|
||||||
--glow, plus a soft accent ring that spreads and fades. The ring is off
|
spreads and fades. Off under reduced motion, below. */
|
||||||
under reduced motion, below; the glow stays. */
|
|
||||||
#btn-send:not(:disabled) { box-shadow: var(--glow); }
|
|
||||||
@keyframes send-pulse {
|
@keyframes send-pulse {
|
||||||
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
|
0% { box-shadow: 0 0 0 0 var(--accent-line); }
|
||||||
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
|
100% { box-shadow: 0 0 0 6px transparent; }
|
||||||
}
|
}
|
||||||
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
||||||
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
||||||
@@ -2015,8 +1955,6 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.footer-where:hover { text-decoration: underline; }
|
.footer-where:hover { text-decoration: underline; }
|
||||||
/* The project name, in the person's highlight color. */
|
|
||||||
.where-project { color: var(--accent); font-weight: 600; }
|
|
||||||
/* A folder is missing or the agent could not read one: the dialog says which. */
|
/* A folder is missing or the agent could not read one: the dialog says which. */
|
||||||
.where-alert {
|
.where-alert {
|
||||||
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
||||||
@@ -2059,18 +1997,6 @@ kbd {
|
|||||||
}
|
}
|
||||||
.waiting-pane h2 { font: 600 23px/1.3 var(--serif); color: var(--ink); margin: 0; }
|
.waiting-pane h2 { font: 600 23px/1.3 var(--serif); color: var(--ink); margin: 0; }
|
||||||
.waiting-pane p { margin: 0; }
|
.waiting-pane p { margin: 0; }
|
||||||
/* The words that open the tasks tab: bold in the highlight color, a button
|
|
||||||
that reads as part of the sentence. */
|
|
||||||
.waiting-jump {
|
|
||||||
font: inherit;
|
|
||||||
font-weight: 700;
|
|
||||||
color: var(--accent);
|
|
||||||
background: none;
|
|
||||||
border: 0;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
button.waiting-jump { cursor: pointer; text-decoration: underline; text-decoration-color: var(--accent-line); text-underline-offset: 3px; }
|
|
||||||
button.waiting-jump:hover { text-decoration-color: var(--accent); }
|
|
||||||
/* Once the work is under way Planny steps back a size, and the ring in
|
/* Once the work is under way Planny steps back a size, and the ring in
|
||||||
front of the stage name carries the "still going" signal instead. */
|
front of the stage name carries the "still going" signal instead. */
|
||||||
.waiting-pane .pose-stage { height: 130px; transition: height 0.35s ease; }
|
.waiting-pane .pose-stage { height: 130px; transition: height 0.35s ease; }
|
||||||
@@ -2273,7 +2199,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
.modal.help[open] { display: flex; }
|
.modal.help[open] { display: flex; }
|
||||||
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
||||||
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
||||||
.help-version a { color: inherit; }
|
|
||||||
|
|
||||||
.help-layout {
|
.help-layout {
|
||||||
display: grid;
|
display: grid;
|
||||||
@@ -2580,9 +2505,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
actions stay put. */
|
actions stay put. */
|
||||||
.modal.workspace { max-width: 680px; }
|
.modal.workspace { max-width: 680px; }
|
||||||
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
||||||
.workspace .modal-blurb { margin-bottom: 6px; }
|
|
||||||
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
|
|
||||||
|
|
||||||
.workspace-list {
|
.workspace-list {
|
||||||
list-style: none; margin: 0; padding: 0;
|
list-style: none; margin: 0; padding: 0;
|
||||||
display: grid; gap: 12px;
|
display: grid; gap: 12px;
|
||||||
@@ -2723,74 +2645,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
border-left-width: 4px;
|
border-left-width: 4px;
|
||||||
color: var(--ink);
|
color: var(--ink);
|
||||||
}
|
}
|
||||||
/* A newer release: the same slot, in the accent, with the label as the way
|
|
||||||
into the update modal and a small × that hides it for this session. */
|
|
||||||
.dash-nudge.update-banner {
|
|
||||||
position: relative;
|
|
||||||
padding-left: 40px;
|
|
||||||
padding-right: 40px;
|
|
||||||
border-left-width: 4px;
|
|
||||||
border-left-color: var(--accent-line);
|
|
||||||
color: var(--ink);
|
|
||||||
box-shadow: var(--glow);
|
|
||||||
}
|
|
||||||
.update-banner-open {
|
|
||||||
flex: 1 1 16em;
|
|
||||||
padding: 0;
|
|
||||||
border: 0;
|
|
||||||
background: none;
|
|
||||||
color: inherit;
|
|
||||||
font: inherit;
|
|
||||||
font-weight: 600;
|
|
||||||
letter-spacing: 0.02em;
|
|
||||||
text-align: center;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.update-banner-open:hover { text-decoration: underline; }
|
|
||||||
/* Pinned to the right edge, out of the flow, so the label centres on the
|
|
||||||
whole banner rather than on what the × leaves of it. */
|
|
||||||
.update-banner-dismiss {
|
|
||||||
position: absolute;
|
|
||||||
top: 50%;
|
|
||||||
right: 10px;
|
|
||||||
transform: translateY(-50%);
|
|
||||||
padding: 0 6px;
|
|
||||||
border: 0;
|
|
||||||
border-radius: var(--radius);
|
|
||||||
background: none;
|
|
||||||
color: inherit;
|
|
||||||
font: inherit;
|
|
||||||
font-size: 16px;
|
|
||||||
line-height: 1;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.update-banner-dismiss:hover { background: var(--accent-line); }
|
|
||||||
/* Wide enough that the update command sits on one line beside Copy; a
|
|
||||||
narrow window still wraps it rather than overflowing. */
|
|
||||||
#update-modal { max-width: 720px; }
|
|
||||||
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
|
|
||||||
.update-steps li { margin: 4px 0; }
|
|
||||||
/* The hand-off copy row, in the modal's first step: the command and its Copy
|
|
||||||
side by side. */
|
|
||||||
.update-command {
|
|
||||||
margin: 6px 0 4px;
|
|
||||||
display: flex;
|
|
||||||
align-items: stretch;
|
|
||||||
gap: 10px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
}
|
|
||||||
.update-command code {
|
|
||||||
flex: 1 1 260px;
|
|
||||||
min-width: 0;
|
|
||||||
font: 13px/1.5 var(--mono);
|
|
||||||
color: var(--ink);
|
|
||||||
background: var(--panel);
|
|
||||||
border: 1px solid var(--rule-2);
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 10px 12px;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
||||||
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
||||||
.dash-working {
|
.dash-working {
|
||||||
@@ -3275,6 +3129,11 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
0%, 15%, 75%, 100% { transform: scale(1); opacity: 0.16; }
|
0%, 15%, 75%, 100% { transform: scale(1); opacity: 0.16; }
|
||||||
45% { transform: scale(0.7); opacity: 0.08; }
|
45% { transform: scale(0.7); opacity: 0.08; }
|
||||||
}
|
}
|
||||||
|
.pose .fz-halo { opacity: 0.25; animation: fz-halo 1.6s ease-in-out infinite; }
|
||||||
|
@keyframes fz-halo {
|
||||||
|
0%, 100% { transform: scale(1); opacity: 0.2; }
|
||||||
|
45% { transform: scale(1.3); opacity: 0.4; }
|
||||||
|
}
|
||||||
.pose .fz-tick { stroke: var(--accent-ink); }
|
.pose .fz-tick { stroke: var(--accent-ink); }
|
||||||
.pose .fz-flag { transform-origin: 0% 50%; animation: fz-wave 1.2s ease-in-out infinite; }
|
.pose .fz-flag { transform-origin: 0% 50%; animation: fz-wave 1.2s ease-in-out infinite; }
|
||||||
@keyframes fz-wave {
|
@keyframes fz-wave {
|
||||||
@@ -3517,18 +3376,6 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
|||||||
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||||
.models-actions .help.error { color: var(--danger, #d64545); }
|
.models-actions .help.error { color: var(--danger, #d64545); }
|
||||||
|
|
||||||
/* User Preferences: Cleanup's list of what would go, shown before anything
|
|
||||||
is deleted. */
|
|
||||||
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
|
|
||||||
.cleanup-list:empty { display: none; }
|
|
||||||
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
|
|
||||||
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
|
|
||||||
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
|
|
||||||
.cleanup-size { flex: none; color: var(--ink-3); }
|
|
||||||
.cleanup-more { display: grid; gap: 4px; }
|
|
||||||
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
|
|
||||||
#cleanup-delete[hidden] { display: none; }
|
|
||||||
|
|
||||||
/* A word the person has to type, bold and in their highlight color so it
|
/* A word the person has to type, bold and in their highlight color so it
|
||||||
does not get lost in the status sentence. */
|
does not get lost in the status sentence. */
|
||||||
.agent-key {
|
.agent-key {
|
||||||
|
|||||||
Loaded 100 of 355 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user