Compare commits

..
101 Commits
Author SHA1 Message Date
jparkerweb 57134cf36e Merge pull request #7 from jparkerweb/sync/upstream-v2.4.5
v2.4.2: upstream web console updates (Cleanup, update banner, launcher banner, Notes threads)
2026-10-05 19:11:56 -07:00
jparkerweb c19a072a3a Sync upstream web console updates into v2.4.2: on-demand Cleanup of unused ~/.plan2code files, an UPDATE AVAILABLE banner from the release tags, a colored launcher with a Planny banner, Notes threads that keep the person's notes and read older reply shapes, the repo-local plan2code-model-update maintainer skill, and review fixes (413 for oversize bodies, notes kept on skip, scoped reconnect banner, live Overview tab, busy state on 409, menu keyboard focus, case-insensitive mentions) 2026-10-05 19:10:45 -07:00
jparkerweb cd8a1be568 Change image alt text for banner in README
Updated image alt text in README.md.
2026-10-05 18:56:03 -07:00
jparkerweb f968aeded8 Show a small spinner left of the web console's Questions and Ask tab names while Plan2Code is on it: Questions spins from Send until the answers are picked up, Ask while a picked-up question has no answer yet, and neither turns once the agent goes quiet or offline 2026-10-04 20:14:53 -07:00
jparkerweb fb71a02756 Hoist the Phase Checklist and Parallel Execution Groups to directly under the Summary in Document's overview.md template, so the phases are found without scrolling
AI Assisted
2026-10-04 18:44:23 -07:00
jparkerweb c8e65f12a6 Count a build on the web console's session meter while it runs, and score Implement + Review's built-in review once instead of twice
AI Assisted
2026-10-04 18:44:23 -07:00
jparkerweb 739e56c5cf Make the web console waiting screen's tasks pointer clickable: while a build runs, Task and the tasks tab's own name (Phase N tasks) show bold in the highlight color and open that phase's tasks tab 2026-10-04 15:52:20 -07:00
jparkerweb ade74cd636 Merge pull request #6 from jparkerweb/develop
Let Send through when an agent asks a question mid-build while still …
2026-10-04 14:24:23 -07:00
jparkerweb 48830c1afb Let Send through when an agent asks a question mid-build while still marked working: once an open question has an answer or note staged the web console unlocks Send at once instead of waiting out quietMinutes, and building.md now says a question stops the build (set waiting in the same post and wait) 2026-10-04 14:12:52 -07:00
jparkerweb b65481cb24 Merge pull request #5 from jparkerweb/develop
update web console, dashboard, implement-review, global launcher
2026-10-04 12:20:55 -07:00
jparkerweb 7d54941b75 Port upstream skill scripts into v2.4.1: deterministic workflow steps run as Node scripts beside each SKILL.md (specs, pathfinder, feedback payload, commit message, review scope, agent files, handoff path) with tests, the prompt limit rises to 20,000 chars, upstream review fixes are folded in (linked agent files never overwrite AGENTS.md, review stops with no base, paste-safe commit commands, Pathfinder number high-water mark and dry runs), and web console workspace folders are remembered per project and spec, with Finalize forgetting an archived spec's list
AI Assisted
2026-10-04 12:17:05 -07:00
jparkerweb 5cbc6edce2 Add the session meter rescale to the v2.4.1 CHANGELOG 2026-10-04 07:40:29 -07:00
jparkerweb 6b93bcb4c5 Scale the web console session meter with the work done: built phases score one point per 3 completed tasks (reported as run.tasks), every 2 answered questions add a point to their skill run, each Pathfinder research question adds 1 via the new pathfinder-research event, and thresholds move to yellow at 5, red at 10, ring full at 15 2026-10-03 22:31:14 -07:00
jparkerweb d49f2d5792 Keep Pathfinder from ending a session while its research subagents are still running: wait for every one, show a running count in the web console, mark finished research with a completion line, and re-run interrupted research on resume
AI Assisted
2026-10-03 10:23:38 -07:00
jparkerweb bfb47f3a8e Refresh agent docs, README and quick reference for v2.4.x: document plan2code-bot, launcher model menu, test/dev env vars, full npm test pipeline, GitHub-issues pathfinder backend, and dedupe command lists in favor of the README
AI Assisted
2026-10-03 09:38:55 -07:00
jparkerweb cb86034de9 Sync upstream v2.4.0 into v2.4.1: welcome dialog, bug/idea button with issue templates, version in Help, gear preferences and ocean default accent, plus web console screenshots, new landing page and web-console-first docs
AI Assisted
2026-10-02 20:51:34 -07:00
jparkerweb 0d7c2e140b Sync upstream v2.4.0 (web console, dashboard skill, implement-review, global launcher) with 24 review fixes and a look-around wake-up for Planny
AI Assisted
2026-09-28 19:37:41 -07:00
jparkerweb eefa7082ed Add pathfinder BRIEF mode, resolved-date tracking, and decide-menu-checkpoint cadence (v2.3.0)
AI Assisted
2026-09-03 07:18:34 -07:00
jparkerweb 8acd7b9d9f Modify image tag in README for better display
Updated image tag to include 'object-fit' style.
2026-08-26 22:24:02 -07:00
jparkerweb f026d3eebc Change banner image source to direct URL
Updated image source in README to use a direct URL.
2026-08-26 22:18:20 -07:00
jparkerweb 1b3360dc99 Add clipboard copy functionality for installation command in index.html 2026-08-22 10:10:06 -07:00
jparkerweb 16a736a2a9 Change alt text for banner image in README
Updated image alt text in README.
2026-08-22 09:58:20 -07:00
jparkerwebandDevin 8663eba113 Update the protected repository sync workflow
Keep the encrypted maintainer instructions current without mixing the opaque payload into the installer migration commits.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-08-20 13:42:56 -07:00
jparkerwebandDevin f40ddf5f8e Document the v2.2.0 skills-based distribution
Align release notes, version metadata, installation guidance, and maintainer documentation with the canonical skills workflow.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-08-20 13:42:43 -07:00
jparkerwebandDevin 57e32ab64f Delegate workflow installation to the skills CLI
Replace per-tool distribution generation with a canonical committed skills build so installation and updates share one format.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-08-20 13:42:31 -07:00
jparkerweb 483c3055b2 v2.1.1 - Failure Log convention in the init prompts 2026-08-12 13:54:43 -07:00
jparkerweb ca1e137a54 update init instructions 2026-08-12 13:15:50 -07:00
jparkerweb a7506952c8 Add a GitHub Issues backend to Pathfinder
Chart Step 1 now asks where the map should live: local files under
gitignored specs/ (the default) or a pathfinder:map issue whose decision
questions are its sub-issues, driven by gh. The pick is recorded as the
first Ground rules bullet and never re-asked; Auto-Discovery resolves
either backend, and an issue URL routes straight to github.

On github the local model maps onto the tracker's own primitives rather
than being simulated in issue bodies: sub-issues, native issue
dependencies for blocking, the assignee as the claim, one
pathfinder:<type>-<mode> label so type and mode cannot drift, and an
Answer comment plus a close reason that distinguishes a decision from a
question ruled out of scope. Both wiring calls key on the database id,
not the number. The map body therefore carries no checklist at all.

Sketches, secrets and the PLAN-DRAFT stay on local disk regardless --
plan2code-1-plan discovers its input with ls specs/ and has no notion of
a tracker. github is only offered after a five-check preflight, and the
offer names the repo's visibility, because a map on a public tracker
publishes the destination and the codebase recon. The Step 3 recon is
held until Step 6 so the no-fog off-ramp leaves no litter.

Depth lives in a seventh reference file; the orchestrator was
recompressed to absorb the new section within the 11,000 char limit by
removing duplication with its references. Adapted from the GitHub
tracker doc behind Matt Pocock's wayfinder skill (MIT).

AI Assisted
2026-08-08 19:00:26 -07:00
jparkerweb dd7d8eff2d Point plan2code-bot at the GitHub repo URL
AI Assisted
2026-08-08 12:39:52 -07:00
jparkerweb b9c6d87a2d Release v2.0.0
Ports upstream v1.17.0 and v2.0.0. Breaking: Gemini CLI is no longer an
install target. Adds Pathfinder Step 0, community feedback submission and
ingestion, and Devin CLI as an agent backend.

AI Assisted
2026-08-08 12:39:37 -07:00
jparkerweb 94d53d1152 Update the Claude Code status line
AI Assisted
2026-08-08 12:39:29 -07:00
jparkerweb 0037bde2aa Document Pathfinder and community feedback across the contributor docs
Moves the README's deep material into .readme/ (walkthrough, autonomous
loop, status line, metrics, test bot) and brings AGENTS.md, the .agents-docs
set and QUICK-REFERENCE.md in line with Step 0 and the metrics ingestion
flow.

AI Assisted
2026-08-08 12:39:29 -07:00
jparkerweb 1d88d787a3 Ingest community feedback submissions in plan2code-metrics
Adds a CLI flow that lists open community-feedback issues via gh, validates
and parses each METRICS_JSON payload, imports them deduped by run_id,
re-aggregates and closes the issue. Community runs cohort by Plan2Code
version rather than prompt fingerprint, and local cohorts stay preferred so
ingested feedback never displaces the maintainer's current generation. Adds
Devin CLI as an AI backend.

AI Assisted
2026-08-08 12:39:28 -07:00
jparkerweb 987f7b8b04 Add Devin CLI as a selectable agent backend in plan2code-loop
Upstream replaced GitHub Copilot CLI with Devin; Plan2Code keeps both, so
Claude Code, Copilot CLI and Devin are all selectable and existing Copilot
selections keep working.

AI Assisted
2026-08-08 12:39:28 -07:00
jparkerweb 9bc0cfe652 Drop Gemini CLI as an install target and register Pathfinder
Removes the .gemini/commands/*.toml surface and the build-time inlining it
required; every remaining target resolves reference directives at runtime.
The uninstall entry is retained behind an uninstallOnly flag so .toml files
from earlier versions can still be cleaned up.

AI Assisted
2026-08-08 12:39:13 -07:00
jparkerweb 044d41ad06 Add Pathfinder as an optional Step 0 and offload prompt depth to references
Pathfinder charts an idea that is too big to plan as a map of decision
questions under specs/<idea>/pathfinder/, clearing one per session until it
can hand a PLAN-DRAFT to Step 1. Finalize now archives pathfinder/ with the
spec and revise-plan no longer deletes it — both previously described the
cleanup target in wording that pointed at questions/. Init-update Step 7 and
review Session End move to reference files with inline fallbacks.

AI Assisted
2026-08-08 12:39:13 -07:00
jparkerweb b08b385e76 Pin LF line endings and renormalize the working tree
scripts/validate-char-count.js measures characters on disk, so a CRLF
checkout added ~1 char per line and pushed the 11k-budget prompt files over
the limit depending on how the repo was cloned. Pins eol=lf, marks binaries,
and renormalizes the files that had CRLF.

AI Assisted
2026-08-08 12:38:58 -07:00
jparkerweb 61b3050174 Redesign docs site and README around an airmail postcard theme
Adds a postage-stamp favicon set and banner, removes three orphaned images,
and records the site and README as protected divergences so an upstream sync
can't revert them.

AI Assisted
2026-08-08 12:32:17 -07:00
jparkerweb 7b57d70e31 URL updates 2026-08-01 13:04:39 -07:00
jparkerweb 832cb1637b update URLs 2026-08-01 12:56:52 -07:00
jparkerweb 6290f66d03 Merge pull request #3 from jparkerweb/statusline-worktree
Add git worktree awareness to status line (v1.16.1)
2026-07-31 22:24:02 -07:00
jparkerweb f8f9896d38 Bump to v1.16.1 for status line git worktree awareness 2026-07-31 22:20:38 -07:00
jparkerweb be24b0a8dc Add git worktree awareness to status line
Sessions in a linked worktree previously showed only the worktree's
directory name, so the underlying repository was unidentifiable and the
session looked like an unrelated project.

The project segment now renders as "repo | worktree". Repo identity comes
from git rev-parse --git-common-dir, so it is correct regardless of how the
worktree directory was named. A leading repo prefix is stripped from the
worktree name, and the name collapses to a bare marker when it merely
restates the branch already on screen -- matched across / _ . - separators
and type prefixes like feature/, and only when the branch is displayed.

Gated behind the new items.worktree config flag (default on). Costs one
extra timeout-bounded git call, skipped entirely outside git repos.
2026-07-31 22:20:38 -07:00
jparkerweb 34204d9993 Merge pull request #2 from jparkerweb/handoff
Release v1.16.0: install handoff skill, add publish skill, sync upstream
2026-07-20 22:39:25 -07:00
jparkerweb 3e6566af4f Address PR review feedback: update step label + release-list limit 2026-07-20 22:36:35 -07:00
jparkerweb 1183919964 Set v1.16.0 releaseDate to 2026-07-20 2026-07-20 22:33:24 -07:00
jparkerweb f0a60da2e2 Release v1.16.0: install handoff skill, add publish skill, sync upstream
- Make plan2code-handoff an installed workflow prompt: move to src/,
  register in install.js SOURCE_PROMPTS, remove repo-local-only copy
- Add repo-local maintainer /plan2code-publish skill (cuts GitHub Releases;
  excluded from install.js)
- Review workflow next-step suggestion made context-aware (upstream v1.15.4)
- Doc updates: list handoff in README, QUICK-REFERENCE, architecture table;
  add "Adding a New Workflow Prompt / Skill" checklist to dev-commands
- Fix broken AGENTS.md index links: rename .agents-docs loop/metrics files
  to plan2code-* to match references
- Bump version.json to 1.16.0 to align with package.json and CHANGELOG
2026-07-20 22:31:37 -07:00
jparkerweb 5d0f2c6380 Merge pull request #1 from jparkerweb/handoff
Add plan2code-handoff skill for conversation handoff documents
2026-07-20 22:09:45 -07:00
jparkerweb 495f0cc3f6 Add plan2code-handoff skill for conversation handoff documents
AI Assisted
2026-07-20 22:07:21 -07:00
jparkerweb ed220c3c7d Bump to v1.15.4 for status line reasoning effort and context token count
AI Assisted
2026-07-19 21:22:54 -07:00
jparkerweb 8e700d485c Add reasoning effort label and context token count to status line
AI Assisted
2026-07-19 21:18:10 -07:00
jparkerweb 8f87dcce67 Sync upstream workflow improvements (v1.15.3): session-end summaries, Sync & Maintain in init-update, plan research steps, ls-based spec discovery, revision/commit guardrails; bump version to v1.15.3
AI Assisted
2026-06-28 11:46:40 -07:00
jparkerweb 9e6949ec60 sync update 2026-06-01 20:44:05 -07:00
jparkerweb 36ee3343a0 Stop ignoring CLAUDE.md
AI Assisted
2026-06-01 19:42:19 -07:00
jparkerweb f1e0de5f2d Add password-protected sync-repo skill with encrypted body
Adds a project-local /sync-repo skill whose real instructions are encrypted
at rest (AES-256-GCM + scrypt) in sync-repo.enc and only revealed in-session
after the user supplies the correct passphrase. Plaintext SYNC.md is gitignored
and never committed; *.enc is marked binary to protect the ciphertext bytes.

AI Assisted
2026-06-01 19:41:34 -07:00
jparkerweb b941c3fdb8 v1.15.2 — add Claude CLI status line, Zed support, rename 3b-review to review
- Status line: new src/statusline-claude/ (Planny box-star mascot icon),
  install/uninstall wiring in install.js, Install All (A) + Custom (S)
- Zed agent support across README, AGENTS, docs, init prompt, installer
- Rename /plan2code-3b-review to /plan2code-review (now a standalone
  utility workflow); update file, reference dir, and all cross-references
- install.js: fs.rmSync simplifications, async install, summary cleanup
- Bump to v1.15.2; CHANGELOG entries for v1.15.0/1/2
2026-06-01 16:39:35 -07:00
jparkerweb b79aed8569 v1.14.0 — add Step 3b review workflow, unify file naming, resilient code references
- Add /plan2code-3b-review: 5-step post-implementation review with adaptive
  scope, 11 dimensions, reference-file architecture, and Plan/Apply/Verify fixes
- Unify workflow/skill file naming to single-dash (drop -- and --- conventions)
- Add Devin platform support and CLAUDE.md MANDATORY FIRST STEP template
- Guide agents to use semantic anchors over line numbers in workflow prompts
- Bump version to 1.14.0
2026-05-23 06:58:20 -07:00
jparkerweb ec61e9c2ca v1.11.1 — installer 'A' option and bot evaluation notes
- install.js: split into 'I' (prompts + loop) and new 'A' (everything
  including bot + metrics); update prompt to (I, A, U, C, Q).
- CHANGELOG: document complexity check (1.11.1) and expand 1.11.0
  notes for the LLM-as-judge evaluation system.
- version.json: 1.10.0 -> 1.11.1.
2026-05-11 13:14:35 -07:00
jparkerweb 1d75934e45 plan2code-bot: replace auto-responder with LLM-as-judge evaluation
Bot now acts as an authentic QA agent instead of rubber-stamping every
question and step.

- intelligent-responder answers AskUserQuestion via LLM using current
  observations (tools used, files created, errors) instead of keyword
  matching; auto-responder removed.
- evaluator runs after each step with step-specific criteria
  (prompts/evaluation-criteria.ts), produces 0-100 score plus
  strengths/weaknesses/critical issues. Avg <60 blocks finalization.
- observation-collector captures tool_use, file writes, errors, and
  question reasoning; session-runner falls back to scraping tool_use
  blocks when canUseTool doesn't fire and dedupes both sources.
- Bot writes BOT-EVALUATION.md and BOT-NOTES.md for metrics analysis.
- Idea generator: 12 categories instead of CLI/web-app coin flip,
  stronger seed adherence, less developer-tool bias.
- Init step now writes a minimal AGENTS.md stub instead of running
  the full init skill, avoiding hallucinated architecture before plan.
- Implement step uses Read/Write/Edit/Glob/Grep directly instead of
  a Skill sub-session that produced no visible tool observations.
- bin: add --help, accept --idea="value" form, strip surrounding
  quotes; evaluator maxTurns 3 -> 30; warn when parser misses SCORE.
2026-05-11 13:14:28 -07:00
jparkerweb 882caa1d12 metrics: adopt METRICS_JSON HTML comment as primary format
Plan, document, and finalize prompts now emit a single
<!-- METRICS_JSON {...} --> block with all structured fields. Collector
parses these directly and keeps the old prose/table parsing as fallback.

Also adds a per-task complexity check to the document prompt:
split tasks with 3+ complexity signals (5+ logic branches, 2+
integration points, shared interface mutation, etc.), combine
adjacent trivial tasks.
2026-05-11 13:14:15 -07:00
jparkerweb 1301aa1b40 prompts: drop Git Commit Messages section from AGENTS.md and init flows
Project-specific commit conventions don't belong in the generic init
templates. AGENTS.md, init, and init-update no longer mention or audit
a Git Commit Messages section.
2026-05-11 13:14:08 -07:00
jparkerweb e3ed8e80f2 v1.11.0 — add plan2code-bot to root changelog 2026-03-01 21:33:57 -08:00
jparkerweb 7b3266e7d8 feat: add plan2code-bot with --resume capability and state cleanup
Add the autonomous workflow test runner (plan2code-bot) that uses the
Claude Agent SDK to run plan2code end-to-end. Includes --resume flag
to continue incomplete runs from saved state, and automatic state file
cleanup on successful completion.
2026-03-01 21:30:45 -08:00
jparkerweb bc6e2863dc v1.10.0 2026-03-01 12:24:11 -08:00
jparkerweb da51a8b7fa Planny hit the gym and lost some weight
Trimmed the mascot ASCII art across all prompts and installer.
Planny is now more aerodynamic and 40% less chunky.
2026-02-22 21:48:13 -08:00
jparkerweb 46f96f7fc8 docs: update AGENTS.md with plan2code-metrics section and corrections
- Add plan2code-metrics to architecture tree, dev commands, installer menu
- Add full metrics section (data flow, CLI menu, key files, feedback format, metric targets)
- Fix Code Style: split install.js (CommonJS) vs loop/metrics (TypeScript+ESM)
- Update finalize prompt description to reflect 7 steps
- Add metrics-specific gotchas (internal prompts, feedback table format)
2026-02-22 21:47:45 -08:00
jparkerweb 0e3651b475 v1.8.1 — add user feedback collection to plan2code-metrics 2026-02-22 21:41:16 -08:00
jparkerweb b228f2f9fe feat: add user feedback collection to plan2code-metrics
- Add UserFeedback type (rating 1-10, reason, went well, went poorly)
- Collector parses ## User Feedback table from overview.md
- Aggregator computes avg_user_rating and feedback_count per cohort
- CLI offers interactive feedback collection with pipe-safe escaping
- Finalize prompt collects optional feedback as Step 5 (before archival)
- Analysis/improvement prompts reference avg_user_rating metric target
2026-02-22 21:38:58 -08:00
jparkerweb 9d5dc75eca v1.8.0 — add plan2code-metrics recursive self-improvement toolchain
New package for contributors to collect, aggregate, analyze, and improve
workflow prompts based on real project data. Includes unit tests (vitest),
installer integration, and loop/finalize hints.
2026-02-22 19:57:40 -08:00
jparkerweb 7cb3e81890 v1.7.0 2026-02-22 12:58:08 -08:00
jparkerweb 968bad2548 v1.6.1 2026-02-18 15:16:11 -08:00
jparkerweb b942b2b9f0 v1.5.4 2026-02-17 09:13:23 -08:00
jparkerweb 725af08c90 spacing 2026-02-03 20:32:18 -08:00
jparkerweb c10354abff v1.5.2 2026-01-27 12:11:00 -08:00
jparkerweb b1502edfb2 v1.3.3: Learning Capture Protocol and improved session instructions 2025-12-31 13:07:27 -08:00
jparkerweb 87b6b643f0 naming and prompt cleanup 2025-12-25 22:02:24 -08:00
jparkerweb d6354099a9 docs 2025-12-25 21:45:41 -08:00
jparkerweb 582cfccdf5 docs
Updated README to include new workflow details and installation instructions.
2025-12-25 21:45:05 -08:00
jparkerweb b3369e5f76 docs 2025-12-23 17:23:23 -08:00
jparkerweb 0cbacb2a37 improved build and install process 2025-12-23 15:42:35 -08:00
jparkerweb 1eeab9cbb3 Delete .windsurf directory 2025-12-22 09:11:18 -08:00
jparkerweb 7ec47ba7b1 Delete .github directory 2025-12-22 09:11:10 -08:00
jparkerweb 61bad114ec Delete .cursor directory 2025-12-22 09:11:00 -08:00
jparkerweb d8369a0b8c Delete .continue directory 2025-12-22 09:10:49 -08:00
jparkerweb bdebbe30ae Delete .claude directory 2025-12-22 09:10:40 -08:00
jparkerweb bb76590667 Delete .agent directory 2025-12-22 09:10:27 -08:00
jparkerweb e88f467b40 v1.0.4 - Added explicit transition check to Planning Phase 6 2025-12-07 17:52:40 -08:00
jparkerweb 6c04256274 v1.0.3 2025-12-05 21:44:21 -08:00
jparkerweb b2a2ddfc43 v1.0.2 2025-12-05 15:41:23 -08:00
jparkerweb ef30ff0858 - Added Initial Context Check to Planning Phase 1 - Model now asks about additional files, reference materials, and external integrations before
analyzing requirements
- Added user verification checklist and git checkpoint to `Implementation Phase 3` - Phase completion reports now guide users through verification and git checkpointing before starting the next phase
2025-12-05 10:43:58 -08:00
jparkerweb 06f8f78e89 docs 2025-12-04 21:30:41 -08:00
jparkerweb 3dc6681151 docs 2025-12-04 20:51:05 -08:00
jparkerweb 0727988616 docs 2025-12-04 20:28:25 -08:00
jparkerweb 5703ecf8bd update website 2025-12-04 20:23:33 -08:00
jparkerweb fb945f3084 Revise README for Plan2Code workflow updates
Updated the README to reflect changes in the Plan2Code workflow, including new file references and installation instructions.
2025-12-04 18:10:42 -08:00
jparkerweb 47574f78cb docs 2025-12-04 18:09:23 -08:00
jparkerweb 7888f06f11 Create CNAME 2025-12-04 17:47:20 -08:00
jparkerweb 38bd676afa Update and rename plan2code.html to index.html 2025-12-04 17:42:27 -08:00
jparkerweb 7bca4bf9b7 docs 2025-12-04 17:36:20 -08:00
jparkerweb 1bd05b2fe5 v1.0.0 2025-12-04 17:34:22 -08:00
jparkerweb 89437d36b4 Initial commit 2025-12-02 20:59:19 -08:00
194 changed files with 496 additions and 14985 deletions

No files matched your search

+3 -14
View File
@@ -173,13 +173,12 @@ 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`) |
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()`; plus `cleanupFindings()` / `removeCleanup()` for User Preferences → Cleanup |
| `public/` | `index.html`, `app.js`, `answers.js`, `labels.js`, `boot.js`, `chat.js`, `help.js`, `starters.js`, `workspace.js`, `meter.js`, `subagents.js`, `mentions.js`, `favicon.js`, `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/` | `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` (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/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/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, `console.mjs`, `lib.mjs`, the page and the tests; in `SERVABLE` and preloaded |
| `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 |
@@ -219,16 +218,6 @@ Key design points:
| `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 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.
- **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.
@@ -239,7 +228,7 @@ 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.
- **`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".
- **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.
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.
+1 -1
View File
@@ -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
U0VOQwGE6gnFffEC/Dv8DbPj9gXzCNp4DSPL7X9/2NPC3i0bN8rPSi2rJ11aKFhGw6Y5eM6b8K4kShUQWLdEM2KSSBwkW90P18Xqv/W+ffeHPf+f+M9uYFheUeHqI9UytwiDNsnurdFtB69qGIlx2svo0CgoWmOPGloXxZckNqzgJsvukbIsLOfDtP/eFYRtzctXOwYLPwQ7uxwpQ7vbgxEp+fomem4tNPh2VdRuFXWdQ6XCVUjilAGMx7JCdAtvfYTkAnws1DDIcR5q9rMF/TJNWIJwMoQqs/FGCuPbGfAvX1jINqkY09ez8As+lGDeL3a45KPubcYNHSXHob0RLartkHfBoUDlTxP45rGpY1cwrnBmydDXpNLWo/+NtV+KeDKgLYtEndbuUIIV2V4zRJRLsdSaybrwkMNDxihXMFaUDE/ebezvBYcf+5UcxsH6WIaEGLn/LvwQxjZaLFHTF1tCHz6U15dJYKB0IwGU1eebt9slJM49c3Y213mPAvhiJkZhRispeExo+cvdTCxQzciUr8+vy+/5h+30ZYpeRGVP072uQYgmS3UIMDbcJNGhrHaES1SPB2YI934unEVNvwNZtOKsDuT18d7DI9nzLaOORWXd6F4xv7r+/sNzRz1IUhVQ9gNUejKJd6G92SyBvepevX+DCGFNuR2aE3cMmfzgxAK+/Nsmt0aMaSf5GwNX4xG1uAHMPyopYfLHvvMrQ6HiZDk0lcxoHclqRMgLQ/fdMFUtbOOSRArwE/aHPbwHE45JSKWZZHkU1JGQtUmPSAH55lpxukSt3gfnl0DZY0ApCQAcMTUE6HNSWRdeXROXCJc6UibjrlU4mBjbb6RDGQfs6X4NZ2WSuX7Gj0W35z7++LCqZ7cYRmIYXweaJc2rxnmZim0bUnJkzCjAS3sfUMakTFlJIzDnxZRhKGWsPukyl39axdQ6zTjj5hAkqTnlajNU7flHHXe80rwNzWlNhOERRB6su2wyrHcI8rgLFmVfSivQ9zw00wi5soqXjaYgGoXDxkzd9+vtMScfXcdJl5LtEWUrvKcP/Q+FpMnxf66SnpwOEHYL61ciAMw3zggJvAo9xyd9g9DySbaRgqVZBGPEI7+s7bTSLWv4lXcgIwAnFFchvK2wKxb+r5Dn6lcZPghWuLBYHhnloPmheCog5go19ANK9ik3xjmo8PFNUxdGPGTS/QCmYzrPpPhyCi5m41kYupPoPbH3gcTCQhQwQJ/A/nS9qnr9CkDsRXD4gpjEyRaMx0Ad3xxQ/aQFnZzqjo0RwpKs4L6qbXBJRRoZAMtXL+J3vLh9EBUfWig71poLLIDzsGS2m3D71ggPQBFlxxelv80IJ9MgEtFga9CWc/NsLark8dTzZyZnOOzvT0ikxzuY5tadrXiVZbunTNP+Alzf6mNPIuTZT1FGC7S3deLQz8i0mqGFRV9JIFzq1/Z3HkmK5HVWrRHZXCkcyueeF++N5rCHnIVJEsXLKLhr4e7OBLEIq38qv4b3NmTP46WvgGOeuGbNRhfHbh1+vfk2buGqdS7hdgNBTaNpaEaOsO3Uhq1y4HFN73861mlLUF0xr5GYCLjoQIleD0RiPF3oNw0GdOfJGmRXzV/u//XSU9DYi3yjyv+aqA5XoWduBFS6dBUDQN4k006ThqpOAMu8tXNvGQVsLv/ORifyWyZYfJFxkG3uB4qiAr1sMNhpzWlhOlb2JjrraRzQeHF9bp/DfrE5LcjMPl4XbhbcvxgyLtWAHjZRWjeglmJFdWXhgynMfyn2Zt4AShRY8Ou9CMOO/iy+ddiREje4ExLrl7bq6hboPi3BDuX95QPRKEBbtCwoLikTK5nDP43CaIGDpMu/i03f05UrGC6NNqblidP29XvCKXpY3ZqoX3yVG5p4nstRbtr+sacqKl0JguXwiG0xMEDS3VVnYkV0W+Kk/H0HkT2MfsJr6ppqjWY1l8mzmoqLkC9YluOskzEc7bWOmUOi7vbbghheQDmT0YmNFIJ+eqz4raXW2SkyTCQZKZuGlmrn7o6ApXamwzpacjYxe7/72xvMPUBWYYmwMRpK745ebNwVihtnks6cn/XWFKUz0wtrWSUYY+tEU/qrOQ7L8gznM53p0mjkVeWRMzqnBydwOdBPkjHtLU784u4BSTm3PgglLYJBM9jfSMFBh79srn99J7GqyBaT2QDZE/PNwOybcd+ap+l2jDV442UuqWSwMEV8xs5v/Bk/5kDnW7A2bN0xI6rdpfibJLs3c9i8M0+XM1yNlesPJAR5nDA/v19sP+wKYZSMO5jIrQLLCKA3Tsq07ujeAbOd62wGIJU4vjHfHAO8I2Hw38HbAM2SVzG6g8zMzEqm36Rl027Fdons3EBwqtMJ6hrx3nHvR96JOwJ866KmlPqT+vjoCh+2HYNLmsS4ipzAUkMYqVnPvnGICDPXX/WkL+0buKXu70jcaW+5Mys/ke41/IH8OJUf6ztLKclO4bBwtfUfE0vxXotj+6x8QNBEsdZl+OHXYemQ+fKd7jhqSTarJRx+cYtwOSUVzEWDxDt+zUp4EF06hfW5kyeY/0OW2t36rx9VULfG78ELo/zH2TXWQWgS2wEdmeXYJ5lzDtPW+XFxSRnYxr+qpceFXAVeMas9sFyG0hG8ey6pth6dPudgcD3fvfzobzaLtMgHiuCSEwHwwQptQ/YprDc2MV20UDW2IlG1yS9D3WgDuRBgQafJegjsDAPFvcpuBwf5JFdFRVBTEUv85GqZ91MNME2vPgo46amuNK3+OerpBitXChDDIw5RCcHIGdXu1+xqshgxvv0xahqRzYRmZr0mLg0jHoSYD3dyzX00//0ApefiRkKgw0yWfgJywQabrXv/NPrgaaK5+d6bwl7BnBAJfNHCDJ5R5CdbWRdkTw1XhD2QADZtURJ9yvnUDX1G2ftLZ/hmnlXGu1Kyin4snhMsnxwhX7mTaFUanY4u9QOGU+jUzbDqqDCHOfPWNDXYhaz4igr34MtAry+PM1LUHIV4UKM6ckI7q2k82LrG1UzfzjDUqtaXaTMeNEI72Gj8D+/jQPfFZeWvO3zvFYlRjSSGy3oIJnXz54TJLb2vpxFvjPDoQZ51V4VZm480b41f3EoX+iWC3Qejf6H0AGut+TSiO7mDStG9MqNApYS0DFubDokwvHNouZRRA2N5RMAnRkYWrLmvZ2MyVPpyU4SS5uiXY2EaV2Ld3RTmf3vGH3vR8I6fzcmcgGw0pkaTqeH/Z0p1Tn1hH9MqfEWMdFCCtOCZm2D9xa/OYI/0ZjkXQxYLjcPhZkMX7XyU/vuuhGkrPbAOWfO03qwx6b/1LCbXa3nM4zgdLR4oBc0wm2q1oHN2ahTT1G2kTxAqz+zeAn7WI2g7Di6X0lJ1b131MmO8Y9fgmXTiSO6FXmMQmddr6JaBHPl/0oUdA3+/m2smVuYuxtBhYVV4BlDRexfd5vm+fnqY1A3tAKJnI0cMzy86idcAIjnobpcJmnqwmIQ3rJGvz5+azOLPtckxeTyaoe2654lU4OBT3k2+tm+vYVJPDSobCrsxWIht1ij0Z6NvLjjy+yx+EYgNLNFPZ4Q1xEb0MYH3R4dyCC7zAlzzzxiofey1hZGvplsttyYlZVhKOuMuZbCtUmj90p6k85UeDhme+c6qVdz/hUhbnd8Lo4acV1HIWoj794XnsOSKME5ITGK8tx692eEbc9C+zEbycZ+u9zAcFhL8+5H1F0R4H+ByLArSHp48oEupL3fye4uBXH+m1cMXlc8lE0UzzD9lICvKWNlCyWfhSD8CVGtshVu7hwhRbgJUvkzxNSyhDhvk3x6XZtifBH6dYekmWJrjSPOWFjAJe349/fALLPJRobmyDywS0pZ/tWaGlezfI6q18w8ldvJulRn36rr7yQonNq8QZbtvj24QnIWgBoAEW4l3w+0TDcJsmKSQ7tg0oGfmgtcpULH8gry01h50abpI17enIY7UVt1+gvJKAg2Foyt4S+v0yBMZWA7C7VCh0LZJmHbHmR6qkB90McDyq/zp3Bc5PqVFaltyujbZP8XMN3pM9714hyqhA0F37ox2m7moIRB1XflyIB3D1tOUvLE16djurt6ew8GzeFDIMqph+h97Ufb8pgfVCzBfatCG0iDwBe2ETEkNLwRUDN/uVwl0Pr6pbILVEaOAS1xPebIK89eDaX6mlS/m0aWWaqt/xGncGPTVlSNWn6V9sB2WVgGz1IJqS2i0A/YwA0Qi6dW37BpS2rpQdD2BHniImTeSMQe6oJDZSOBf3iAAZnExl8PcAgEB/Dwc+RrQUHYtSIk5BJCtTFjEXcY/08lUix9C3o0uIGRIDTdTwN4smBokFawcSo3OPjFAiPZcLU0K0ppfpF7/AkWqYIV5weLd9ElFT6ajcNjdqm2PXrhtEu72TmiKKfioZHfanlB3PUjsOPm1+s7X5AwWWhJerScXfHpFPhX4GFBPe3GVGbZ6yWfpG4rjd166HBDFbRbRB0Pbe+AiQNJHBLcErss6mTOVMdy2uAKVyHStKWRPR1cMHy/pcLKsxYRKtBu4I0KWcdHLMtZ02f4wbapiKVAn2W8tN8J/m7f7yBvvrHFdj3eOlE6F8LBVtMNL3A5kCKQa4BBhMF0gmmWc/idHKLPu73hELAHmr4uI37ehgX5prXfB/wJ6jqPH+nu5El5MGGy8SYAQrQDL6tzooXqQoSO1txwMeCY/KTRMXAGdWLJGUiXzXLykZrEx6b3WvHhC9PcN7JGGmNgZ6oXNCzDPnan4UDfFyMW/PGFgoUBptZ2rLbkjeBVe/GQ9xTOuiOVcr1CpVPGv4FQCeKQmeH+08R7zTvuQA9iqngLE0o3g0WLioaMYVBkKFva3xw0TOPMv7Sj+NGPqeilr6QkcoVSxxf3H+wVBTPJForIutmbCOjvsrms7Vo6yaALIfeE4P9QvBthQ1lI52GbtvUhxSmUv7OZcw/QgYWg4R+MKkZxp8/Ombst1wUjIqraX2hac7iwdk81uroMLine truncated
+1 -1
View File
@@ -15,7 +15,7 @@ background processes.** Optional, and unrelated to the workflow itself.
On Pro / Max / Teams accounts, where rate limits are available:
```
╭───╮ Opus 5 / high │ plan2code │ feature/PCWEB-11702-pathfinder │ +12 -3
╭───╮ Opus 5 / high │ plan2code │ feature/pathfinder-github-iss │ +12 -3
│ ★ │ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
╰┬─┬╯ 3h 5m ($4.62) │ ▰▰▰▰▰▱▱▱▱▱▱▱ 42% (84K) │ 5h: 28% · 7d: 61%
```
+2 -32
View File
@@ -153,7 +153,7 @@ it opens on the page without asking.
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
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
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.
@@ -339,33 +339,6 @@ it is remembered for next time:
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
A small ring pill in the top bar — **Session: fresh** (green), **Session:
@@ -648,8 +621,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>/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/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 |
Each of the workspace and meter files has exactly one writer: the server owns
@@ -675,7 +646,7 @@ never the record, `specs/` in your project is.
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
`workspaces.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
@@ -730,7 +701,6 @@ origin.
| `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/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
+2 -2
View File
@@ -40,7 +40,7 @@ Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line
## Web Console
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a 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 (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), 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)
@@ -92,4 +92,4 @@ 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.
- 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.
- After a sync, grep for a bare `Smarsh/` owner slug as well as `github.com/smarsh/...` URLs: the rebrand map only rewrites URLs, so `gh --repo Smarsh/smarsh2code` became `Smarsh/plan2code` in `feedback-payload.mjs` (and its test) until it was fixed by hand to `jparkerweb/plan2code`.
- 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.
-14
View File
@@ -2,20 +2,6 @@
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
+1 -1
View File
@@ -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.
Version 2.5.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
Version 2.4.2 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
---
+1 -1
View File
@@ -375,7 +375,7 @@ footer a { color: inherit; }
<div class="wrap">
<a href="https://github.com/jparkerweb/plan2code">Plan2Code on GitHub</a>
<span>MIT license</span>
<a href="https://github.com/jparkerweb/plan2code/releases">Releases</a>
<span>Version 2.4.1</span>
</div>
</footer>
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "plan2code",
"version": "2.5.0",
"version": "2.4.2",
"private": true,
"bin": {
"plan2code-install": "./install.js"
+8 -8
View File
@@ -230,16 +230,16 @@ test("specs archive: dry-run, move, refuse to clobber", () => {
test("commit-msg: ticket from the branch, the three -m flags, subject rules", () => {
const repo = tmp("commit");
const g = gitInit(repo, "feature/PCWEB-10968-export-csv");
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, "PCWEB-10968");
assert.equal(ok.json.command, 'git add -A && git commit -m "Add the export endpoint" -m "PCWEB-10968" -m "AI Assisted"');
assert.equal(ok.json.message, "Add the export endpoint\n\nPCWEB-10968\nAI Assisted");
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);
@@ -425,9 +425,9 @@ test("specs: --set cannot override computed fields; empty overview exists; uncou
test("commit-msg: a repo with no commits, stray arguments, and paths quoted for every shell", () => {
const repo = tmp("commit2");
gitInit(repo, "feature/PCWEB-12-x");
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, "PCWEB-12", "no commits yet");
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");
@@ -572,12 +572,12 @@ test("specs: an em dash in a group range expands like a hyphen", () => {
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/PCWEB-12-x");
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 "PCWEB-12" -m "AI Assisted"');
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;
+7 -646
View File
@@ -151,24 +151,6 @@ import {
WEIGHTS,
YELLOW_AT,
} from "../src/web-console/public/meter.js";
import {
blockFor,
CHECKIN_LINE,
checkHelper,
checkHelpers,
cleanSetting,
defaultInstruction,
defaultSetting,
effectiveInstruction,
FRAME_LINES,
helperRows,
offered,
offLine,
showSwitch,
showTab,
SUBAGENT_WORKFLOWS,
switchLabel,
} from "../src/web-console/public/subagents.js";
import { applyMention, matchNames, mentionAt } from "../src/web-console/public/mentions.js";
import { FAVICON_BODY, FAVICON_COLORS, faviconState, faviconSvg } from "../src/web-console/public/favicon.js";
import { CACHE_MS, RELEASES_URL, REPO_URL, checkForUpdate, compareVersions, latestTag } from "../src/web-console/update-check.mjs";
@@ -185,18 +167,12 @@ import {
cwdHash,
handOff,
initialWorkspace,
latestOpenCaps,
parseArgs,
pendingWorkspaceChanges,
PROTECTED_CONSOLE_FILES,
readChat,
readLedger,
readSubagentCursor,
readSubagentSetting,
readWorkspaceCursor,
resetSubagentCursor,
writeSubagentCursor,
writeSubagentSetting,
readOverview,
removeCleanup,
removeScratch,
@@ -733,7 +709,6 @@ test("every module the page imports is actually served", async () => {
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
for (const m of html.matchAll(/<link rel="modulepreload" href="\/([^"]+)"/g)) wanted.add(m[1]);
assert.ok(wanted.has("chat.js"), "the page preloads chat.js");
assert.ok(wanted.has("subagents.js"), "the page preloads subagents.js");
assert.ok(wanted.size > 1, "found the imports");
for (const f of wanted) {
const res = await fetch(`${baseUrl}/${f}`, { headers: { cookie: consoleCookie(baseUrl, token), connection: "close" } });
@@ -847,9 +822,9 @@ const helpTemplate = () => {
return tpl[1];
};
test("help: 17 tabs with unique ids", () => {
assert.equal(HELP_TABS.length, 17);
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 17);
test("help: 16 tabs with unique ids", () => {
assert.equal(HELP_TABS.length, 16);
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 16);
assert.ok(Object.isFrozen(HELP_TABS) && HELP_TABS.every((t) => Object.isFrozen(t)), "the tab list is frozen");
});
@@ -919,8 +894,6 @@ test("help: helpTabFor opens on the tab for where the person is", () => {
[{ adrift: true, view: "ask" }, "stuck"],
[{ view: "ask" }, "ask"],
[{ view: "ask", dashboard: true }, "ask"],
[{ view: "subagents" }, "subagents"],
[{ view: "subagents", workflow: "implement" }, "subagents"],
[{ dashboard: true }, "dashboard"],
[{ dashboard: true, view: "overview" }, "dashboard"],
[{ workspace: true }, "workspace"],
@@ -3485,15 +3458,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe
return p;
};
const removable = [file("p2.json"), file("helper.mjs")];
const kept = [
file("looks.json"),
file("workspaces.json"),
file("subagents.json"),
file("console-dir"),
file("update-check.json"),
file("notes.txt"),
file("p3.json", false),
];
const kept = [file("looks.json"), file("workspaces.json"), file("console-dir"), file("update-check.json"), file("notes.txt"), file("p3.json", false)];
const subdir = path.join(dir, "x.json");
fs.mkdirSync(subdir);
backdate(subdir);
@@ -3502,18 +3467,12 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe
const stale = staleScratch(dir, Date.now(), SESSION_MAX_AGE_MS).sort();
assert.deepEqual(stale, ["helper.mjs", "p2.json"]);
assert.deepEqual(
(await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "subagents.json", "../p.json", "console-dir", "update-check.json"])).sort(),
(await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "../p.json", "console-dir", "update-check.json"])).sort(),
["helper.mjs", "p2.json"]
);
for (const p of removable) assert.equal(fs.existsSync(p), false, p);
for (const p of kept) assert.ok(fs.existsSync(p), p);
assert.deepEqual([...PROTECTED_CONSOLE_FILES].sort(), [
"console-dir",
"looks.json",
"subagents.json",
"update-check.json",
"workspaces.json",
]);
assert.deepEqual([...PROTECTED_CONSOLE_FILES].sort(), ["console-dir", "looks.json", "update-check.json", "workspaces.json"]);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
@@ -3547,9 +3506,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
const drafted = session("20250801-101010-dddddd", true);
put(path.join(drafted, "draft.json"));
const kept = [
...["looks.json", "workspaces.json", "subagents.json", "console-dir", "update-check.json"].map((n) =>
put(path.join(consoleDir, n))
),
...["looks.json", "workspaces.json", "console-dir", "update-check.json"].map((n) => put(path.join(consoleDir, n))),
put(path.join(plan2code, "launcher.json")),
put(path.join(plan2code, "models.json")),
put(path.join(plan2code, "bin", "plan2code.js"), "x"),
@@ -5181,232 +5138,6 @@ test("workspace cursor never moves backwards, and only changes past it are pendi
}
});
test("subagents: only the five opted-in workflows offer the switch", () => {
for (const w of ["implement", "implement-review", "quick-task", "review", "pathfinder"]) {
assert.equal(offered(w), true, w);
assert.ok(defaultInstruction(w).length > 0, `${w} has a default instruction`);
}
for (const w of ["dashboard", "plan", "document", "init", "handoff", "constructor", "toString", undefined]) {
assert.equal(offered(w), false, String(w));
assert.equal(defaultInstruction(w), "");
}
assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 5);
assert.deepEqual(defaultSetting("review"), { workflow: "review", on: false, instruction: null, max: 3 });
assert.equal(effectiveInstruction({ workflow: "review", instruction: " " }), defaultInstruction("review"));
assert.equal(effectiveInstruction({ workflow: "review", instruction: " Mine " }), "Mine");
});
test("subagents: blockFor walks every switch transition, and never says off to an agent not told on", () => {
const setting = (on, revision, extra = {}) => ({ workflow: "implement", on, instruction: null, max: 3, revision, ...extra });
const none = { revision: 0, state: "none" };
assert.equal(blockFor(setting(false, 1), none), null, "never on: nothing");
assert.equal(blockFor(null, none), null, "no setting: nothing");
const on = blockFor(setting(true, 2), none);
assert.equal(on.lines[0], "Subagents: on (revision 2) — a console setting, not typed by the person.");
assert.ok(!on.lines[0].includes("replaces"));
assert.deepEqual(on.field, { state: "on", revision: 2, max: 3, instruction: defaultInstruction("implement") });
assert.deepEqual(on.cursor, { revision: 2, state: "on" });
assert.equal(on.lines[on.lines.length - 1], " At most 3 helpers at once.");
for (const frame of FRAME_LINES) assert.ok(on.lines.includes(" " + frame), frame);
const edit = blockFor(setting(true, 5, { instruction: "First line\n\nSecond line", max: 7 }), { revision: 4, state: "on" });
assert.equal(edit.lines[0], "Subagents: on (revision 5, replaces revision 4) — a console setting, not typed by the person.");
assert.ok(edit.lines.includes(" First line") && edit.lines.includes(" Second line"), "the instruction's own lines are indented");
assert.ok(!edit.lines.some((line) => !line.trim()), "blank instruction lines are dropped");
const nested = blockFor(setting(true, 2, { instruction: "- a\r\n - b\n \n" }), none);
assert.deepEqual(nested.lines.slice(-3, -1), [" - a", " - b"], "the person's own indentation survives, CRLF and blank lines do not");
assert.equal(edit.field.max, 7);
for (const line of edit.lines.slice(1)) assert.match(line, /^ {2}\S/, "only the first line starts at column 0");
const off = blockFor(setting(false, 6), { revision: 5, state: "on" });
assert.deepEqual(off.lines, [offLine(6)]);
assert.equal(off.lines[0], "Subagents: off (revision 6) — don't start new helpers for the rest of this session.");
assert.deepEqual(off.cursor, { revision: 6, state: "off" });
assert.equal(off.field.state, "off");
assert.equal(blockFor(setting(false, 6), { revision: 6, state: "off" }), null, "same revision again: nothing");
assert.equal(blockFor(setting(true, 6), { revision: 6, state: "on" }), null, "same revision while on: nothing");
assert.equal(blockFor(setting(false, 3), { revision: 2, state: "off" }), null, "off after off: nothing");
assert.equal(blockFor(setting(true, 6), none).lines[0], "Subagents: on (revision 6) — a console setting, not typed by the person.", "a reset cursor re-states on");
assert.equal(blockFor(setting(false, 6), none), null, "a reset cursor with it off: nothing");
assert.equal(blockFor({ ...setting(true, 9), workflow: "plan" }, none), null, "a workflow that does not offer it: nothing");
});
test("subagents: the injected wording names no harness tool", () => {
const texts = [...FRAME_LINES, ...Object.keys(SUBAGENT_WORKFLOWS).map(defaultInstruction), offLine(1)];
for (const text of texts) {
for (const tool of ["run_subagent", "subagent_type", "Task(", "spawn_agent", "/agents", "Agent tool"]) {
assert.ok(!text.includes(tool), `"${text}" names ${tool}`);
}
}
});
test("subagents: cleanSetting accepts a good setting and names the field that fails", () => {
assert.deepEqual(cleanSetting({ on: true, instruction: null, max: 3 }), { on: true, instruction: null, max: 3 });
assert.deepEqual(cleanSetting({ on: false, instruction: " Do it ", max: 20 }), { on: false, instruction: "Do it", max: 20 });
assert.equal(cleanSetting({ on: true, instruction: "", max: 1 }).instruction, null, "an empty instruction is the default");
for (const max of [0, 21, 2.5, "3"]) assert.deepEqual(cleanSetting({ on: true, instruction: null, max }), { error: "max" }, String(max));
assert.deepEqual(cleanSetting({ on: true, instruction: "x".repeat(2001), max: 3 }), { error: "too-long" });
assert.deepEqual(cleanSetting({ on: "yes", instruction: null, max: 3 }), { error: "bad" });
assert.deepEqual(cleanSetting({ on: true, instruction: 7, max: 3 }), { error: "bad" });
assert.deepEqual(cleanSetting(null), { error: "bad" });
});
test("subagents: checkHelper and checkHelpers name the helper behind every problem", () => {
const running = { id: "h1", title: "Read the store", ask: "Find the lock helpers", state: "running" };
const done = { id: "h2", title: "Tests", ask: "Run the suite", state: "done", result: "All green" };
assert.deepEqual(checkHelper(running), []);
assert.deepEqual(checkHelper(done), []);
assert.deepEqual(checkHelper({ id: "alone", alone: true }), []);
assert.deepEqual(checkHelpers([running, done, { id: "alone", alone: true }]), []);
const one = (entry) => {
const problems = checkHelper(entry);
assert.equal(problems.length, 1, JSON.stringify(problems));
assert.match(problems[0], new RegExp(`helper "${entry.id}"`));
return problems[0];
};
one({ ...running, title: undefined });
assert.match(one({ ...running, state: "paused" }), /state must be running, done or failed/);
one({ ...running, title: "t".repeat(81) });
one({ ...running, ask: "a".repeat(401) });
one({ ...done, result: "r".repeat(201) });
const dupes = checkHelpers([running, { ...done, id: "h1" }]);
assert.ok(dupes.some((p) => p === 'helper "h1": duplicate id'), dupes.join("; "));
const alones = checkHelpers([{ id: "alone", alone: true }, { id: "alone", alone: true }]);
assert.ok(alones.some((p) => /helper "alone": only one working-alone entry/.test(p)), alones.join("; "));
assert.deepEqual(checkHelpers("nope"), ["helpers must be an array"]);
});
test("subagents: the page shows the switch only when offered and supported, and the tab only with a helper", () => {
assert.equal(showSwitch(null), false);
assert.equal(showSwitch({ offered: false, supported: true, on: true }), false);
assert.equal(showSwitch({ offered: true, supported: false, on: true }), false);
assert.equal(showSwitch({ offered: true, supported: true, on: false }), true);
assert.equal(switchLabel({ on: true }), "Subagents: on");
assert.equal(switchLabel({ on: false }), "Subagents: off");
const on = { offered: true, supported: true, on: true };
const off = { offered: true, supported: true, on: false };
const helper = { id: "h1", title: "Research", ask: "Check the docs", state: "running" };
assert.equal(showTab(on, []), false, "never an empty tab, even when on");
assert.equal(showTab(on, undefined), false);
assert.equal(showTab(off, [helper]), true, "a helper shows with the switch off (Pathfinder research)");
assert.equal(showTab({ ...on, supported: false }, [helper]), false, "no tab where the switch cannot show");
assert.ok(CHECKIN_LINE.includes("check-ins, not live"));
});
test("subagents: helperRows labels each state, shows a result only once a helper ended, and collapses to working alone", () => {
assert.deepEqual(helperRows([{ id: "alone", alone: true }]), { alone: true, rows: [] });
assert.deepEqual(helperRows(undefined), { alone: false, rows: [] });
const { alone, rows } = helperRows([
{ id: "h1", title: "One", ask: "a", state: "running", result: "not yet" },
{ id: "h2", title: "Two", ask: "b", state: "done", result: "Found 2 call sites" },
{ id: "h3", title: "Three", ask: "c", state: "failed", result: "Timed out" },
]);
assert.equal(alone, false);
assert.deepEqual(rows.map((r) => [r.id, r.stateLabel]), [["h1", "Running"], ["h2", "Done"], ["h3", "Failed"]]);
assert.equal("result" in rows[0], false, "a running helper has no result in its row");
assert.equal(rows[1].result, "Found 2 call sites");
assert.equal(rows[2].result, "Timed out");
});
test("page: the Subagents button sits right after Write a brief, and its dialog is in the page with no inline styles or scripts", () => {
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
const row = html.match(/<div class="row-left">([\s\S]*?)<\/div>\s*<div class="views-group">/);
assert.ok(row, "index.html has the second row's left cluster");
const ids = [...row[1].matchAll(/<button[^>]*\bid="([^"]+)"/g)].map((m) => m[1]);
assert.equal(ids[ids.indexOf("btn-brief") + 1], "btn-subagents", "the Subagents button follows Write a brief");
assert.match(row[1], /<button[^>]*id="btn-subagents"[^>]*\bhidden\b/, "the button starts hidden");
for (const part of ["sa-hub", "sa-node", "sa-link"]) assert.ok(row[1].includes(`class="${part}"`), `the icon has ${part}`);
const dialog = html.match(/<dialog class="modal looks subagents" id="subagents-modal" aria-labelledby="subagents-title">([\s\S]*?)<\/dialog>/);
assert.ok(dialog, "index.html has the Subagents dialog");
for (const id of ["subagents-instruction", "subagents-default", "subagents-max", "subagents-checkin", "subagents-research", "subagents-status", "subagents-cancel", "subagents-save"]) {
assert.ok(dialog[1].includes(`id="${id}"`), `the dialog carries #${id}`);
}
assert.doesNotMatch(dialog[1], /\sstyle=/);
assert.doesNotMatch(dialog[1], /<script/i);
});
test("subagents: the store round-trips per project and workflow under the console home", () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-subagents-home-"));
try {
const project = path.join(home, "My Repo");
const script = `
const lib = await import(${JSON.stringify(new URL("../src/web-console/lib.mjs", import.meta.url).href)});
const project = ${JSON.stringify(project)};
lib.saveSubagentStoreEntry(project, "implement", { on: true, instruction: "Mine", max: 5 });
const flipped = project.replace(/My Repo$/, "MY REPO");
console.log(JSON.stringify({
file: lib.SUBAGENTS_FILE,
saved: lib.subagentStoreEntry(project, "implement"),
otherCase: lib.subagentStoreEntry(flipped, "implement"),
unsaved: lib.subagentStoreEntry(project, "review"),
}));
`;
const res = spawnSync(process.execPath, ["--input-type=module", "-e", script], {
env: { ...process.env, PLAN2CODE_CONSOLE_HOME: home },
encoding: "utf8",
});
assert.equal(res.status, 0, res.stderr);
const out = JSON.parse(res.stdout);
assert.equal(out.file, path.join(home, "subagents.json"), "the store follows PLAN2CODE_CONSOLE_HOME");
assert.deepEqual(out.saved, { on: true, instruction: "Mine", max: 5 });
if (process.platform === "win32" || process.platform === "darwin") {
assert.deepEqual(out.otherCase, out.saved, "a different-case path reads the same entry");
}
assert.deepEqual(out.unsaved, { on: false, instruction: null, max: 3 });
assert.ok(!fs.existsSync(path.join(home, "subagents.json.lock")), "the lock is released");
} finally {
fs.rmSync(home, { recursive: true, force: true });
}
});
test("subagents: the session setting and the cursor never go backwards, except a reset", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-subagents-"));
try {
assert.equal(readSubagentSetting(dir), null);
writeSubagentSetting(dir, { workflow: "implement", on: true, instruction: null, max: 3, revision: 5 });
writeSubagentSetting(dir, { workflow: "implement", on: false, instruction: null, max: 3, revision: 3 });
assert.equal(readSubagentSetting(dir).revision, 5);
assert.equal(readSubagentSetting(dir).on, false, "the rest of the setting is still written");
fs.writeFileSync(path.join(dir, "subagents-setting.json"), JSON.stringify({ workflow: "implement", on: "yes", max: 3, revision: 1 }));
assert.equal(readSubagentSetting(dir), null, "malformed reads null");
assert.deepEqual(readSubagentCursor(dir), { revision: 0, state: "none" });
writeSubagentCursor(dir, { revision: 4, state: "on" });
writeSubagentCursor(dir, { revision: 2, state: "off" });
assert.deepEqual(readSubagentCursor(dir), { revision: 4, state: "on" });
resetSubagentCursor(dir);
assert.deepEqual(readSubagentCursor(dir), { revision: 0, state: "none" });
fs.writeFileSync(path.join(dir, "subagents-cursor.json"), JSON.stringify({ revision: 2, state: "maybe" }));
assert.deepEqual(readSubagentCursor(dir), { revision: 0, state: "none" });
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("subagents: latestOpenCaps reads the last open event, skipping a torn line", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-caps-"));
const events = path.join(dir, "events.ndjson");
try {
assert.deepEqual(latestOpenCaps(dir), [], "no events yet");
fs.writeFileSync(events, [{ type: "open", caps: ["subagents"] }, { type: "open" }].map((e) => JSON.stringify(e)).join("\n") + "\n");
assert.deepEqual(latestOpenCaps(dir), [], "the latest open has no caps");
fs.appendFileSync(events, JSON.stringify({ type: "post" }) + "\n" + JSON.stringify({ type: "open", caps: ["subagents"] }) + "\n");
assert.deepEqual(latestOpenCaps(dir), ["subagents"]);
fs.appendFileSync(events, '{"type":"open","ca');
assert.deepEqual(latestOpenCaps(dir), ["subagents"], "a torn final line is ignored");
assert.ok(PROTECTED_CONSOLE_FILES.has("subagents.json"));
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("initialWorkspace names the original folder after itself and marks it original", () => {
const ws = initialWorkspace(path.join("C:", "git", "My Repo"));
assert.equal(ws.version, 0);
@@ -5769,376 +5500,6 @@ test("workspace: chat hands over a workspace change on its own, then has nothing
}
});
/* ------------------------------------------- subagents: end to end */
// The switch is remembered per project folder in the console home, so every
// test that starts from "off" clears it first.
const SUBAGENTS_STORE = path.join(HOME, "subagents.json");
const subagentsSession = (extra = {}, { keepStore = false } = {}) => {
if (!keepStore) fs.rmSync(SUBAGENTS_STORE, { force: true });
return openSession({ workflow: "implement", ...extra });
};
const setSubagents = async (s, body) => {
const res = await s.send("/subagents", body);
return { status: res.status, body: await res.json() };
};
const frameSubagents = async (s) =>
(await (await fetch(`${s.base}/state`, { headers: { cookie: s.cookie, connection: "close" } })).json()).subagents;
const ON3 = { on: true, instruction: null, max: 3 };
const submitAndWait = async (s) => {
assert.equal((await s.send("/submit", EXPORT_A)).status, 200);
return cli(["wait", "--session", s.sid, "--seconds", "10"]);
};
const subagentLines = (reply) =>
String(reply || "")
.split("\n")
.filter((l) => l.startsWith("Subagents:"));
test("subagents: a change reaches the next pickup once, last in reply, edits name what they replace and off follows only an on", async () => {
const s = subagentsSession();
const extra = tempFolder();
try {
const on = await setSubagents(s, ON3);
assert.equal(on.status, 200);
assert.equal(on.body.ok, true);
const rev = on.body.setting.revision;
assert.deepEqual(on.body.setting, { workflow: "implement", on: true, instruction: null, max: 3, revision: rev });
assert.equal((await ask(s, "Which files does the first task touch?")).status, 200);
assert.equal((await addFolder(s, { path: extra })).status, 200);
const first = await submitAndWait(s);
assert.equal(first.status, 0);
assert.deepEqual(first.json.subagents, { state: "on", revision: rev, max: 3, instruction: defaultInstruction("implement") });
const reply = first.json.reply;
const at = (re) => reply.search(re);
assert.ok(at(/^Export format: a$/m) === 0, reply);
assert.ok(at(/^Quick question:/m) > 0, reply);
assert.ok(at(/^Workspace:/m) > at(/^Quick question:/m), reply);
assert.ok(at(/^Subagents:/m) > at(/^Workspace:/m), reply);
assert.match(reply, new RegExp(`^Subagents: on \\(revision ${rev}\\) — a console setting, not typed by the person\\.$`, "m"));
assert.ok(reply.endsWith("\n At most 3 helpers at once."), "the block goes last");
assert.deepEqual(subagentLines(reply).length, 1, "one block");
assert.deepEqual(readSubagentCursor(s.session), { revision: rev, state: "on" });
const second = await submitAndWait(s);
assert.equal("subagents" in second.json, false, "handed over once");
assert.deepEqual(subagentLines(second.json.reply), []);
const edited = await setSubagents(s, { ...ON3, max: 5 });
assert.equal(edited.body.setting.revision, rev + 1);
const third = await submitAndWait(s);
assert.equal(third.json.subagents.revision, rev + 1);
assert.equal(third.json.subagents.max, 5);
assert.deepEqual(subagentLines(third.json.reply), [
`Subagents: on (revision ${rev + 1}, replaces revision ${rev}) — a console setting, not typed by the person.`,
]);
const same = await setSubagents(s, { ...ON3, max: 5 });
assert.equal(same.status, 200);
assert.equal(same.body.setting.revision, rev + 1, "saving the same values bumps nothing");
assert.equal("subagents" in (await submitAndWait(s)).json, false, "and injects nothing");
const off = await setSubagents(s, { ...ON3, on: false, max: 5 });
assert.equal(off.body.setting.revision, rev + 2, "off is a revision of its own");
const fourth = await submitAndWait(s);
assert.equal(fourth.json.subagents.state, "off");
assert.deepEqual(subagentLines(fourth.json.reply), [
`Subagents: off (revision ${rev + 2}) — don't start new helpers for the rest of this session.`,
]);
assert.equal("subagents" in (await submitAndWait(s)).json, false, "off is said once");
} finally {
cli(["stop", "--session", s.sid]);
fs.rmSync(extra, { recursive: true, force: true });
}
});
test("subagents: never on means never a line, and chat hands a pending block over on its own", async () => {
const s = subagentsSession();
try {
const off = await setSubagents(s, { on: false, instruction: null, max: 4 });
assert.equal(off.status, 200);
const got = await submitAndWait(s);
assert.equal("subagents" in got.json, false);
assert.deepEqual(subagentLines(got.json.reply), [], "off is never said to an agent not told on");
assert.equal(cli(["chat", "--session", s.sid]).status, 10);
assert.equal((await setSubagents(s, { on: true, instruction: "Split by file.", max: 4 })).status, 200);
const chat = cli(["chat", "--session", s.sid]);
assert.equal(chat.status, 0);
assert.deepEqual(chat.json.chat, []);
assert.equal(chat.json.subagents.state, "on");
assert.equal(chat.json.subagents.instruction, "Split by file.");
assert.match(chat.json.reply, /^Subagents: on \(revision \d+\)/);
assert.match(chat.json.reply, /^ {2}Split by file\.$/m);
assert.ok(chat.json.terminalLine);
assert.equal(cli(["chat", "--session", s.sid]).status, 10, "then nothing");
} finally {
cli(["stop", "--session", s.sid]);
}
});
test("subagents: a resume re-states an on setting once, says nothing when off, and a lost cursor repeats the block", async () => {
const s = subagentsSession();
try {
const rev = (await setSubagents(s, ON3)).body.setting.revision;
const resumed = cli(["open", "--resume", s.sid, "--no-open"]);
assert.equal(resumed.json.ok, true);
assert.deepEqual(resumed.json.subagents, { state: "on", revision: rev, max: 3, instruction: defaultInstruction("implement") });
assert.equal(subagentLines(resumed.json.reply)[0], `Subagents: on (revision ${rev}) — a console setting, not typed by the person.`);
assert.ok(resumed.json.reply.split("\n").every((l, i) => i === 0 || l.startsWith(" ")), "only the block's lines");
assert.equal("subagents" in (await submitAndWait(s)).json, false, "the next pickup carries nothing");
// The print happened but the cursor write did not: the block comes again.
fs.writeFileSync(path.join(s.session, "subagents-cursor.json"), JSON.stringify({ revision: 0, state: "none" }));
const again = await submitAndWait(s);
assert.equal(again.json.subagents.state, "on");
assert.deepEqual(subagentLines(again.json.reply), [`Subagents: on (revision ${rev}) — a console setting, not typed by the person.`]);
assert.deepEqual(readSubagentCursor(s.session), { revision: rev, state: "on" });
assert.equal((await setSubagents(s, { ...ON3, on: false })).status, 200);
const quiet = cli(["open", "--resume", s.sid, "--no-open"]);
assert.equal("subagents" in quiet.json, false, "a resume with the switch off says nothing");
assert.equal("reply" in quiet.json, false);
assert.equal("subagents" in (await submitAndWait(s)).json, false, "nor does the next pickup");
} finally {
cli(["stop", "--session", s.sid]);
}
});
test("subagents: a dashboard launch into implement hears implement's saved setting once", async () => {
const seed = subagentsSession();
try {
assert.equal((await setSubagents(seed, ON3)).status, 200);
} finally {
cli(["stop", "--session", seed.sid]);
}
const s = consoleSession(["--workflow", "dashboard"]);
try {
assert.equal((await s.get("/state")).subagents.offered, false, "the dashboard offers no switch");
const launched = cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]);
// On the launch itself, not at a later pickup: a skill may do its main
// work before it ever collects anything.
assert.equal(launched.json.subagents?.state, "on", "the launch's own open output carries the block");
assert.match(launched.json.reply, /^Subagents: on \(revision \d+\)/);
await sleep(1200);
assert.equal(cli(["chat", "--session", s.sid]).status, 10, "never both");
const view = await s.get("/state");
assert.deepEqual([view.subagents.offered, view.subagents.supported, view.subagents.on], [true, true, true]);
} finally {
cli(["stop", "--session", s.sid]);
}
});
test("subagents: the setting survives a restart at the same revision and starts the next session in the project", async () => {
const s = subagentsSession();
let next = null;
try {
const saved = await setSubagents(s, { on: true, instruction: "Split by file.", max: 7 });
assert.equal(saved.status, 200);
const rev = saved.body.setting.revision;
cli(["stop", "--session", s.sid]);
const resumed = cli(["open", "--resume", s.sid, "--no-open"]);
const frame = await (
await fetch(`${sessionUrl(resumed.json.url).base}/state`, { headers: { cookie: sessionUrl(resumed.json.url).cookie, connection: "close" } })
).json();
assert.deepEqual(
[frame.subagents.on, frame.subagents.instruction, frame.subagents.max, frame.subagents.revision],
[true, "Split by file.", 7, rev],
"a restart alone bumps nothing"
);
next = subagentsSession({}, { keepStore: true });
const fresh = await frameSubagents(next);
assert.deepEqual([fresh.on, fresh.instruction, fresh.max], [true, "Split by file.", 7], "a new session in the same project starts there");
} finally {
cli(["stop", "--session", s.sid]);
if (next) cli(["stop", "--session", next.sid]);
}
});
test("subagents: a save that matches this session still becomes the project's setting, without a bump", async () => {
const b = subagentsSession();
const a = subagentsSession({}, { keepStore: true });
let c = null;
try {
const before = (await frameSubagents(b)).revision;
assert.equal((await setSubagents(a, ON3)).status, 200, "another session turns it on for the project");
const same = await setSubagents(b, { ...ON3, on: false });
assert.equal(same.status, 200);
assert.equal(same.body.setting.revision, before, "nothing changed for this session's agent");
assert.equal("subagents" in (await submitAndWait(b)).json, false);
c = subagentsSession({}, { keepStore: true });
assert.equal((await frameSubagents(c)).on, false, "the next session starts from the person's latest pick");
} finally {
for (const s of [a, b, c]) if (s) cli(["stop", "--session", s.sid]);
}
});
test("subagents: a workflow without the switch refuses it, bad bodies name the field, and an older copy's open hides it", async () => {
const plan = subagentsSession({ workflow: "plan" });
const s = subagentsSession();
try {
assert.deepEqual(await setSubagents(plan, ON3), { status: 400, body: { error: "not-offered" } });
assert.equal((await frameSubagents(plan)).offered, false);
assert.equal("subagents" in (await submitAndWait(plan)).json, false);
assert.deepEqual(await setSubagents(s, { ...ON3, max: 0 }), { status: 400, body: { error: "max" } });
assert.deepEqual(await setSubagents(s, { ...ON3, max: 21 }), { status: 400, body: { error: "max" } });
assert.deepEqual(await setSubagents(s, { ...ON3, instruction: "x".repeat(2001) }), { status: 400, body: { error: "too-long" } });
assert.deepEqual(await setSubagents(s, { ...ON3, on: "yes" }), { status: 400, body: { error: "bad" } });
assert.equal((await frameSubagents(s)).supported, true, "this copy's open carries caps");
fs.appendFileSync(path.join(s.session, "events.ndjson"), JSON.stringify({ at: new Date().toISOString(), type: "open", resumed: true }) + "\n");
assert.equal((await frameSubagents(s)).supported, false, "an older copy's open has no caps");
cli(["open", "--resume", s.sid, "--no-open"]);
assert.equal((await frameSubagents(s)).supported, true);
// A session an older server ran has no setting file: nothing is injected,
// whatever the store says.
assert.equal((await setSubagents(s, ON3)).status, 200);
fs.rmSync(path.join(s.session, "subagents-setting.json"), { force: true });
assert.equal("subagents" in (await submitAndWait(s)).json, false);
} finally {
cli(["stop", "--session", plan.sid]);
cli(["stop", "--session", s.sid]);
}
});
/* ------------------------------------------ subagents: helper reports */
const reportedHelper = (id, extra = {}) => ({ id, title: `Helper ${id}`, ask: "Find the callers of applyPatch", state: "running", ...extra });
test("helpers: post merges them by id, takes one working-alone entry, and null clears the list", () => {
const s = consoleSession(["--workflow", "implement"]);
try {
assert.equal(postPatch(s, { helpers: [reportedHelper("h1")] }).status, 0);
const done = reportedHelper("h1", { state: "done", result: "Found 2 call sites" });
assert.equal(postPatch(s, { helpers: [done, reportedHelper("h2")] }).status, 0);
assert.deepEqual(readState(s.session).helpers, [done, reportedHelper("h2")], "h1 updated in place, h2 added");
assert.equal(postPatch(s, { helpers: [{ id: "alone", alone: true }] }).status, 0);
assert.deepEqual(readState(s.session).helpers.map((h) => h.id), ["h1", "h2", "alone"]);
const second = postPatch(s, { helpers: [{ id: "solo", alone: true }] }, { expectFail: true });
assert.equal(second.status, 3);
assert.match(second.stderr, /helper "solo"/);
assert.deepEqual(readState(s.session).helpers.map((h) => h.id), ["h1", "h2", "alone"], "the refused entry was not written");
assert.equal(postPatch(s, { helpers: null }).status, 0);
assert.equal("helpers" in readState(s.session), false);
} finally {
cli(["stop", "--session", s.sid]);
}
});
test("helpers: every malformed report exits 3 naming the helper, and nothing is written", () => {
const s = consoleSession(["--workflow", "implement"]);
try {
assert.equal(postPatch(s, { helpers: [reportedHelper("h1")] }).status, 0);
const statePath = path.join(s.session, "state.json");
const before = fs.readFileSync(statePath, "utf8");
const cases = [
["missing title", [{ id: "h3", ask: "Read the docs", state: "running" }], /helper "h3": title must be a non-empty string/],
["unknown state", [reportedHelper("h3", { state: "paused" })], /helper "h3": state must be running, done or failed/],
["81-char title", [reportedHelper("h3", { title: "t".repeat(81) })], /helper "h3": title must be at most 80 characters/],
["401-char ask", [reportedHelper("h3", { ask: "a".repeat(401) })], /helper "h3": ask must be at most 400 characters/],
["201-char result", [reportedHelper("h3", { state: "done", result: "r".repeat(201) })], /helper "h3": result must be at most 200 characters/],
["completion marker", [reportedHelper("h3", { state: "done", result: "PHASE_COMPLETE" })], /helper "h3" result contains a loop completion marker/],
["metrics bait", [reportedHelper("h3", { title: "Risk 3" })], /helper "h3" title contains "Risk 3"/],
["not an array", { id: "h3" }, /"helpers" must be an array/],
["null entry", [null], /"helpers" entries must be objects/],
["string entry", ["h3"], /"helpers" entries must be objects/],
];
for (const [name, helpers, re] of cases) {
const res = postPatch(s, { helpers }, { expectFail: true });
assert.equal(res.status, 3, name);
assert.match(res.stderr, re, name);
assert.equal(fs.readFileSync(statePath, "utf8"), before, `${name}: nothing written`);
}
} finally {
cli(["stop", "--session", s.sid]);
}
});
test("docs: a doc's version never goes back; the same version again is fine, and a hop starts every doc fresh", () => {
const s = consoleSession(["--workflow", "implement"]);
try {
const doc = (version, md) => ({ docs: [{ id: "phase", title: "Phase 5 tasks", version, blocks: [{ id: "tasks", state: "settled", md }] }] });
assert.equal(postPatch(s, doc(7, "- [x] Task 4.1")).status, 0);
assert.equal(postPatch(s, doc(7, "- [x] Task 4.1 (again)")).status, 0, "the same version again is fine");
const statePath = path.join(s.session, "state.json");
const before = fs.readFileSync(statePath, "utf8");
const stale = postPatch(s, doc(1, "- [ ] Task 4.1"), { expectFail: true });
assert.equal(stale.status, 3);
assert.match(stale.stderr, /doc "phase" is at version 7 on the page; this patch sends version 1/);
assert.equal(fs.readFileSync(statePath, "utf8"), before, "nothing written");
assert.equal(postPatch(s, doc(8, "- [ ] Task 5.1")).status, 0, "a higher version goes through");
assert.equal(postPatch(s, { docs: [{ id: "phase", blocks: [{ id: "tasks", state: "settled", md: "- [x] Task 5.1" }] }] }).status, 0, "a patch with no version is not checked");
cli(["open", "--resume", s.sid, "--no-open", "--workflow", "dashboard"]);
cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]);
assert.equal(postPatch(s, doc(1, "- [ ] Task 1.1")).status, 0, "after a hop the doc starts fresh");
} finally {
cli(["stop", "--session", s.sid]);
}
});
test("docs: a second phase in one build session goes through as building.md teaches it", () => {
const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "building.md"), "utf8");
assert.match(md, /`"version": 1` is for the first phase of a session only/);
assert.match(md, /a later phase in the\s+same session reposts `phase` and `phasefile` at one more than the version the\s+page holds/);
const s = consoleSession(["--workflow", "implement"]);
try {
const phase = (n, version, md) => ({
headline: { stage: `Phase ${n}`, cleared: 0 },
docs: [
{ id: "phase", title: `Phase ${n} tasks`, version, blocks: [{ id: "tasks", state: "settled", md }] },
{ id: "phasefile", title: `phase-${n}.md`, version, blocks: [{ id: "body", state: "settled", md }] },
],
});
assert.equal(postPatch(s, phase(1, 1, "- [ ] Task 1.1")).status, 0);
assert.equal(postPatch(s, phase(1, 2, "- [x] Task 1.1")).status, 0);
const restarted = postPatch(s, phase(2, 1, "- [ ] Task 2.1"), { expectFail: true });
assert.equal(restarted.status, 3, "restarting at version 1 is refused");
assert.equal(postPatch(s, phase(2, 3, "- [ ] Task 2.1")).status, 0, "continuing from the page's version goes through");
const docs = readState(s.session).docs;
assert.deepEqual(
docs.map((d) => [d.id, d.title, d.version]),
[["phase", "Phase 2 tasks", 3], ["phasefile", "phase-2.md", 3]]
);
} finally {
cli(["stop", "--session", s.sid]);
}
});
test("helpers: a dashboard hop clears them, a same-workflow or paused resume keeps them, and the meter never moves", async () => {
const s = consoleSession(["--workflow", "implement"]);
try {
const meterBefore = (await s.get("/state")).meter;
assert.equal(postPatch(s, { helpers: [reportedHelper("h1"), { id: "alone", alone: true }] }).status, 0);
assert.deepEqual((await s.get("/state")).meter, meterBefore, "helper reports add nothing to the meter");
assert.equal(readLedger(s.session).some((e) => JSON.stringify(e).includes("h1")), false, "nothing about helpers reaches the ledger");
cli(["open", "--resume", s.sid, "--no-open"]);
assert.equal(readState(s.session).helpers.length, 2, "a resume with no --workflow keeps them");
cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]);
assert.equal(readState(s.session).helpers.length, 2, "a resume into the same workflow keeps them");
assert.equal(postPatch(s, { finish: { headline: "Paused at Task 2" } }).status, 0);
cli(["open", "--resume", s.sid, "--no-open"]);
const resumed = readState(s.session);
assert.equal("finish" in resumed, false, "the pause came down");
assert.equal(resumed.helpers.length, 2, "taking a pause down keeps them");
cli(["open", "--resume", s.sid, "--no-open", "--workflow", "dashboard"]);
assert.equal("helpers" in readState(s.session), false, "the hop to the dashboard drops them");
cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]);
assert.equal("helpers" in readState(s.session), false, "and the hop back brings none");
} finally {
cli(["stop", "--session", s.sid]);
}
});
test("meter: a repeated run counts once, a bad one appends nothing, and neither reaches state.json", async () => {
const s = openSession();
try {
@@ -64,13 +64,6 @@ progress bar is the first thing someone watching a build looks at. The session
meter counts the build's tasks from `cleared` as it rises, so keep it current,
and start every phase (a second one in the same run too) at `"cleared": 0`.
`"version": 1` is for the first phase of a session only. A doc's version
never goes back (console.md → House rules, rule 9), so a later phase in the
same session reposts `phase` and `phasefile` at one more than the version the
page holds, with the new phase's title and content. The same goes for
`report` at sign-off and `review` in a mid-session review: version 1 the
first time, then up from wherever the page has it.
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
the person can read the prerequisites and task specs while you build. Re-post
it whenever the file changes, which is every task: the checkbox write that
@@ -118,12 +111,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
holds anything the person sends until you next look.
A build may receive a `Subagents:` standing instruction, on `open` output or a
`chat` check between tasks. Follow console.md → Standing instructions for
handing independent tasks to helpers and reporting them as `helpers`. Keep the
per-task progress posts, the checkbox writes, the chat checks and the sign-off
with you.
### Quick questions between tasks
The person can ask a Quick question on the Ask tab at any point in a build
@@ -208,8 +195,7 @@ only ever be offered once nothing could come of it:
`reply` carries `Approve this phase: approved`, which is the terminal's
`approved`. If the note that came with an approval asks for a change, treat it
as "describe any issues": do the change first and ask again. `changes` means
exactly what it says: address it, bump the report's version (a later phase's
report starts above the last one's, too), and reopen the
exactly what it says: address it, bump the report's version, and reopen the
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
person asking for the code review before they approve anything — see "The
review, mid-session" below.
@@ -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 |
| --- | --- | --- |
| `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. |
| `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. |
@@ -647,84 +647,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)
A `dashboard` session is not a conversation: the page draws a menu of every
@@ -841,10 +763,7 @@ commands follow the pipeline: the sign-off's is
### Review (`review`)
Scope questions up front — run standalone with nothing named, the first is
a `choice`, "What should I review?", built from a quick scan (branch changes,
uncommitted changes, specs, files you name; each option with its size),
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
Scope questions up front, then the findings report as a doc (`id: "report"`),
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
id, carrying `"doc": "report"` so the card links straight to the findings.
Settle that item (`"status": "answered"` plus the `answer` they sent) in
@@ -878,8 +797,6 @@ 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
finish (Finishing → Nothing of yours may still be running); the finish
body then names what each one found.
- Report every research subagent as a helper, whatever the Subagents switch
says (Standing instructions → Reporting helpers).
- At every session end, post `finish` (headline, `body`, and Form A's command as
`command`) BEFORE `stop`. Someone who spent the session in the browser never
sees the Trail Footer, and without this their last screen promises a question
@@ -1229,16 +1146,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
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
and 5 cover `reason` and `hint`.
8. **`helpers` entries are well formed** (Standing instructions → Reporting
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
and a known `state` within their limits, plus at most one `alone` entry.
Rules 4 and 5 cover `title`, `ask` and `result`.
9. **A doc's `version` never goes back.** Sending a known doc a lower
`version` than the page holds is refused: it is almost always a stale or
copied payload. The same version again is fine, and a dashboard hop starts
every doc fresh. Anything else reusing a doc id in the same session (a
build's second phase, a second report or review) continues from the
version the page holds.
These are workflow rules you already follow. The server just makes them checkable.
@@ -1260,9 +1167,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
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
and update the count as each returns. Never write a `finish.body` that says
work "is running in the background" or "will finish on its own". Mark every
reported helper `done` or `failed` before the finish, so the Subagents tab
never ends on a row still running.
work "is running in the background" or "will finish on its own".
### 1. Post the finish
@@ -64,8 +64,6 @@ import {
readChat,
readJson,
readLedger,
readSubagentCursor,
readSubagentSetting,
readWorkspace,
reapHandles,
rememberedWorkspace,
@@ -73,7 +71,6 @@ import {
removeScratch,
removeSessions,
repoRoots,
resetSubagentCursor,
scanProject,
SESSION_MAX_AGE_MS,
sessionDir,
@@ -91,11 +88,9 @@ import {
workspaceForAgent,
writeCursor,
writeJsonAtomic,
writeSubagentCursor,
writeWorkspaceCursor,
} from "./lib.mjs";
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
import { blockFor, offered } from "./public/subagents.js";
import { changeLine } from "./public/workspace.js";
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
@@ -315,11 +310,7 @@ async function cmdOpen() {
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
// A new agent conversation has been told nothing yet (FR-6).
try {
resetSubagentCursor(dir);
} catch {}
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
trace("open: state written");
// Dashboard launches are recorded too (they score nothing), so the folder
@@ -346,18 +337,9 @@ async function cmdOpen() {
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
};
// A standing instruction the new agent is owed, as `subagents` and a
// `reply` holding only its lines; neither key when nothing is owed.
const subagentsOwed = () => {
awaitSubagentSync(dir, state.workflow);
const [out, cursor] = withSubagents(dir, { reply: "" });
return [out.subagents ? out : {}, cursor];
};
// Reuse a live server if one is already serving this session.
if (existing && (await reusable)) {
if (!args["no-open"]) openBrowser(existing.url);
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -367,11 +349,9 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(existing.url),
workspace,
...owed,
...swept,
...remoteWarning(),
});
advanceSubagents(dir, subCursor);
sweep();
return;
}
@@ -404,7 +384,6 @@ async function cmdOpen() {
const notes = [];
if (remote.note) notes.push(remote.note);
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -415,12 +394,10 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(handle.url),
workspace,
...owed,
...swept,
...(remote.remote ? { remote: remote.remote } : {}),
...(notes.length ? { note: notes.join(" ") } : {}),
});
advanceSubagents(dir, subCursor);
// After the print, never before it: the page and the link wait for nothing.
sweep();
}
@@ -797,7 +774,7 @@ function serverGone(sid) {
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
function deliverChat(dir, sid, entries, url) {
const [withWs, changes] = withWorkspace(dir, {
const [out, changes] = withWorkspace(dir, {
type: "chat",
at: nowIso(),
sid,
@@ -805,11 +782,9 @@ function deliverChat(dir, sid, entries, url) {
chat: entries,
reply: chatReplyLines(entries),
});
const [out, subCursor] = withSubagents(dir, withWs);
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
advanceCursor(dir, entries);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -831,52 +806,6 @@ function advanceWorkspace(dir, changes) {
} catch {}
}
// The server rewrites the session's setting for a new workflow only once its
// watcher sees the state `open` just wrote, so a launch or hop that read the
// file at once would find the old workflow's and owe the agent nothing until
// its next pickup. Give the server a moment to catch up instead, never
// writing the file ourselves (FR-7). A session with no setting file at all is
// an older server, which never writes one: a short look, not the full wait.
const SUBAGENT_SYNC_WAIT_MS = 1500;
const SUBAGENT_SYNC_MISSING_MS = 250;
function awaitSubagentSync(dir, workflow) {
if (!offered(workflow)) return;
const start = Date.now();
for (;;) {
const setting = readSubagentSetting(dir);
if (setting && setting.workflow === workflow) return;
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
if (Date.now() - start >= budget) return;
sleepSync(25);
}
}
// The Subagents switch the agent is owed, added to what it is about to read:
// the setting as `subagents`, and its lines last in `reply`, after card lines,
// Quick questions and Workspace lines (FR-9). Read from the session's own
// setting file only, which only the server writes (FR-7). A setting for
// another workflow is the server not having caught up with a hop yet: it
// rides on the next pickup instead.
function withSubagents(dir, out) {
const setting = readSubagentSetting(dir);
if (!setting) return [out, null];
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
if (setting.workflow !== workflow) return [out, null];
const block = blockFor(setting, readSubagentCursor(dir));
if (!block) return [out, null];
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
return [{ ...out, subagents: block.field, reply }, block.cursor];
}
// After the print, like advanceWorkspace(): a kill in between repeats the
// block at the next pickup, never loses it.
function advanceSubagents(dir, cursor) {
if (!cursor) return;
try {
writeSubagentCursor(dir, cursor);
} catch {}
}
// Print first, then this, exactly as consume() stamps a result: a kill in
// between can only hand the same chat over again, and collectChat() drops
// anything that already has a reply.
@@ -903,17 +832,15 @@ async function cmdChat() {
}
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
const changes = pendingWorkspaceChanges(dir);
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
if (!entries.length && !changes.length && !subCursor) {
if (!entries.length && !changes.length) {
print({ chat: [] });
process.exitCode = 10;
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);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -938,8 +865,7 @@ function consume(dir, resultPath, result, url, chat = []) {
// never on result.json itself.
const withChat = { ...collected, chat };
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
const [withWs, changes] = withWorkspace(dir, withChat);
const [out, subCursor] = withSubagents(dir, withWs);
const [out, changes] = withWorkspace(dir, withChat);
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
try {
writeJsonAtomic(resultPath, collected);
@@ -948,7 +874,6 @@ function consume(dir, resultPath, result, url, chat = []) {
ledgerAnswers(dir, result);
advanceCursor(dir, chat);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = result.type === "cancel" ? 30 : 0;
}
@@ -1061,18 +986,12 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
May also print subagents: { state, revision, max, instruction } and
a reply holding only its "Subagents: ..." lines, when a standing
instruction (the page's Subagents switch) is owed to you.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
carry run: { event, id, tasks? } (session meter points) and folderIssue:
{ name, reason, hint? } (a workspace folder you could not read);
both go to the ledger, never into the state. A patch may also
carry helpers: [{ id, title, ask, state, result? }] or one
{ id: "alone", alone: true }, merged by id, for the Subagents tab
(see console.md → Standing instructions).
both go to the ledger, never into the state.
wait --session <sid> [--seconds <N>]
A bounded wait slice, sized below your shell timeout. Exit 0 = the
result is on stdout, 10 = still waiting ("Waiting on your answer
@@ -1083,14 +1002,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
"workspace" (changes since you last heard, each once, with a
"Workspace: ..." line in reply); exit 10 counts them as
pendingWorkspace, and a change alone never ends a slice.
Exit 0 may also carry "subagents" (a console setting, not typed
by the person, with its "Subagents: ..." lines last in reply); a
setting change alone never ends a slice either.
chat --session <sid>
Collect Quick questions, workspace changes and a Subagents
setting change now, never waiting, never touching card sends.
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
10 = none, 20 = server gone.
Collect Quick questions and workspace changes now, never waiting,
never touching card sends. Exit 0 = { chat, workspace, reply,
terminalLine }, 10 = none, 20 = server gone.
terminalLine is "→ Look at the web console: <url>": end your terminal
messages with it during a console session.
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
@@ -25,7 +25,6 @@ import { fileURLToPath } from "node:url";
import { CHAT_LIMIT } from "./public/chat.js";
import { DOC_TYPES } from "./public/answers.js";
import { defaultName } from "./public/workspace.js";
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const PUBLIC_DIR = path.join(HERE, "public");
@@ -492,16 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, the Subagents switch
// saved per project and workflow, the pointer to this console's directory,
// and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set([
"looks.json",
"workspaces.json",
"subagents.json",
"console-dir",
"update-check.json",
]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -1150,19 +1142,6 @@ const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
// state keeps its text. Blocks left out of the patch stay as they are.
function mergeDocs(current, patchList) {
// A doc's version only moves forward. One going back is a stale or copied
// payload (last phase's progress script, say), and the page would quietly
// show the old content under the new run's name.
for (const entry of patchList) {
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
const prev = (current || []).find((d) => d && d.id === entry.id);
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
throw new Error(
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
"Versions only go up: bump it, and check the payload is the current one."
);
}
}
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
for (const entry of patchList) {
if (!Array.isArray(entry.blocks)) continue;
@@ -1205,13 +1184,6 @@ export function applyPatch(state, patch) {
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
break;
case "helpers":
// The agent's report of its helpers, for the page's Subagents tab.
// Only `post` writes it; the server's /submit never touches it.
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
break;
case "docs":
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
next.docs = mergeDocs(next.docs, v);
@@ -1506,20 +1478,6 @@ export function validate(state) {
JSON.stringify(state.menu || {});
problems.push(...proseProblems(prose));
// The agent's report of its helpers: the shape the page draws from
// (subagents.js), then the same prose scan as everything else it writes.
if (state.helpers != null) {
problems.push(...checkHelpers(state.helpers));
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
if (!isPlainObject(helper)) continue;
for (const field of ["title", "ask", "result"]) {
if (typeof helper[field] === "string") {
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
}
}
}
}
return problems;
}
@@ -1549,8 +1507,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
* A resume that passes through the dashboard (a finished skill going back to
* it, or a launch from its menu) is a new skill taking the page over, so it
* starts from a blank page: the last skill's questions, sections, docs,
* helpers, headline and ending are its record on disk, not the next skill's
* opening.
* headline and ending are its record on disk, not the next skill's opening.
* Only the session's identity carries across. `workspace.json`,
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
* and the meter outlive every hop.
@@ -1577,8 +1534,6 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
// workspace.json the server. Folders, version, change log, missing, remote.
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
export const CHAT_FILE = "chat.ndjson";
export const CHAT_CURSOR_FILE = "chat-cursor.json";
export const WORKSPACE_FILE = "workspace.json";
@@ -2034,98 +1989,6 @@ export function pendingWorkspaceChanges(dir) {
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.
*
@@ -208,26 +208,6 @@ body {
.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); }
/* 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; }
/* The session meter: a ring that fills with the points and a few words, in
@@ -1450,30 +1430,6 @@ h1 {
.pill.done { background: var(--ok-soft); color: var(--ok); }
.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 */
.answered {
@@ -2015,8 +1971,6 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
cursor: pointer;
}
.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. */
.where-alert {
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
@@ -103,15 +103,6 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
import { RED_BANNER } from "./meter.js";
import { applyMention, matchNames, mentionAt } from "./mentions.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);
@@ -539,9 +530,6 @@ 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 chatSending = false;
let chatResetting = false;
@@ -892,8 +880,6 @@ function adopt(body) {
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();
if (gone) {
gone = false;
@@ -1315,7 +1301,6 @@ function render() {
renderChrome();
renderStatus();
renderBriefButton();
renderSubagentsButton();
renderStopButton();
renderHomeButton();
tabAdded = renderViews();
@@ -1581,7 +1566,7 @@ function renderChrome() {
renderMeter();
$("title").textContent = S.title || "Session";
$("badge").textContent = workflowLabel(S.workflow);
renderTabTitle();
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
const h = S.headline || {};
// On a finished session an open item is frozen: the send on it counts as
@@ -1850,69 +1835,6 @@ function renderBriefButton() {
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() {
const nav = $("views");
nav.replaceChildren();
@@ -1928,14 +1850,6 @@ function renderViews() {
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
else if (view === "overview") view = "questions";
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.
// The ring left of "Ask" shows exactly when the conversation's own ring does:
// a question the agent picked up and has not answered yet.
@@ -2216,7 +2130,6 @@ function paintMain(main) {
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
if (view === "overview") return renderOverview(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 top of the rail. The hand-off lives here alone now, rather than
@@ -4861,42 +4774,6 @@ function renderOverview(main) {
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 */
// The frame's chat block, with `offline` worked out now rather than when the
@@ -6079,30 +5956,10 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
// 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
// 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() {
const b = $("footer-where");
const folders = workspaceFolders();
const path = S.worktree || "";
renderTabTitle();
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
const labels = folders.length
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
@@ -6115,16 +5972,7 @@ function renderWhere() {
let label = labels[0];
for (const text of labels) {
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) {
const dot = el("span", "where-alert");
dot.setAttribute("aria-hidden", "true");
@@ -7349,7 +7197,6 @@ function lightDismiss(dlg) {
});
}
lightDismiss($("looks-modal"));
lightDismiss($("subagents-modal"));
lightDismiss($("help-modal"));
lightDismiss($("workspace-modal"));
lightDismiss($("welcome-modal"));
@@ -7652,13 +7499,6 @@ $("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("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-go").addEventListener("click", sendBrief);
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("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("subagents", "Helpers (subagents)", false),
tab("ask", "Ask a quick question", false),
tab("finishing", "Stopping and finishing", false),
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 (workspace) return "workspace";
if (v === "ask") return "ask";
if (v === "subagents") return "subagents";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v.startsWith("doc:")) return "docs";
@@ -21,7 +21,6 @@
<link rel="modulepreload" href="/starters.js" />
<link rel="modulepreload" href="/workspace.js" />
<link rel="modulepreload" href="/meter.js" />
<link rel="modulepreload" href="/subagents.js" />
<link rel="modulepreload" href="/mentions.js" />
<link rel="modulepreload" href="/favicon.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>
Write a brief
</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 class="views-group">
<span class="views-arrow" aria-hidden="true">
@@ -593,13 +580,6 @@
<rect x="3" y="9" width="18" height="6" rx="3" />
<path d="M6 12h7" />
</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">
<path d="M4 5h16v11H10l-4 4v-4H4z" />
<path d="M8 9.5h8M8 12.5h5" />
@@ -1497,61 +1477,7 @@
</p>
</section>
<!-- Tab 12: Helpers (subagents) -->
<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 -->
<!-- Tab 12: Ask a quick question -->
<section class="help-panel" data-tab="ask">
<h3>Ask a quick question</h3>
<p class="help-lead">
@@ -1642,7 +1568,7 @@
</p>
</section>
<!-- Tab 14: Stopping and finishing -->
<!-- Tab 13: Stopping and finishing -->
<section class="help-panel" data-tab="finishing">
<h3>Stopping and finishing</h3>
<p class="help-lead">
@@ -1724,7 +1650,7 @@
</p>
</section>
<!-- Tab 15: When something looks stuck -->
<!-- Tab 14: When something looks stuck -->
<section class="help-panel" data-tab="stuck">
<h3>When something looks stuck</h3>
<p class="help-lead">
@@ -1846,7 +1772,7 @@
</div>
</section>
<!-- Tab 16: Keyboard and preferences -->
<!-- Tab 15: Keyboard and preferences -->
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
@@ -1962,7 +1888,7 @@
</ul>
</section>
<!-- Tab 17: Privacy and where things are saved -->
<!-- Tab 16: Privacy and where things are saved -->
<section class="help-panel" data-tab="privacy">
<h3>Privacy and where things are saved</h3>
<p class="help-lead">
@@ -1999,11 +1925,7 @@
</li>
<li>
your role, theme, colors, card width and sounds, in
<code>looks.json</code>;
</li>
<li>
your Subagents switch for each project and skill, in
<code>subagents.json</code>.
<code>looks.json</code>.
</li>
</ul>
<p>
@@ -2117,46 +2039,6 @@
</div>
</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
context. The list is drawn by app.js from the frame's `workspace`;
every change goes through the server's /workspace routes. -->
@@ -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,7 +25,6 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
SUBAGENTS_SETTING_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
@@ -39,7 +38,6 @@ import {
fileStamp,
handleFile,
initialWorkspace,
latestOpenCaps,
nowIso,
parseArgs,
pendingChatCount,
@@ -48,25 +46,20 @@ import {
readJson,
readLedger,
readOverview,
readSubagentSetting,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
saveSubagentStoreEntry,
specKey,
subagentStoreEntry,
typedCount,
withStateLock,
writeJsonAtomic,
writeSubagentSetting,
writeWorkspace,
} from "./lib.mjs";
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 { 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 { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
@@ -219,7 +212,6 @@ const SERVABLE = new Set([
"starters.js",
"workspace.js",
"meter.js",
"subagents.js",
"mentions.js",
"favicon.js",
"start-stop.mp3",
@@ -609,48 +601,6 @@ function ensureConversation(state) {
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.
// `have` names that exact view, for the page to hand back when it opens its
// stream (see /events).
@@ -665,33 +615,20 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
subagents: subagentsView(state),
...(updateInfo ? { update: updateInfo } : {}),
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() {
const { pending, stop } = resultFlags();
chatEntries();
chatPickedUp();
workspaceNow();
ledgerEntries();
subagentSettingNow();
openCapsNow();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -1235,39 +1172,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.
if (pathname === "/models" && req.method === "GET") {
const saved = readJson(USER_MODELS_FILE, null) || {};
@@ -1496,9 +1400,6 @@ const server = http.createServer((req, res) => {
try {
ensureConversation(written.state);
} catch {}
try {
syncSubagentSetting(written.state);
} catch {}
}
}
// Name the items that went. A page with OTHER answers staged should drop
@@ -1825,9 +1726,6 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
syncSubagentSetting(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
@@ -2002,9 +1900,6 @@ function onListening(port) {
try {
bootWorkspace();
} catch {}
try {
syncSubagentSetting(readState());
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -64,13 +64,6 @@ progress bar is the first thing someone watching a build looks at. The session
meter counts the build's tasks from `cleared` as it rises, so keep it current,
and start every phase (a second one in the same run too) at `"cleared": 0`.
`"version": 1` is for the first phase of a session only. A doc's version
never goes back (console.md → House rules, rule 9), so a later phase in the
same session reposts `phase` and `phasefile` at one more than the version the
page holds, with the new phase's title and content. The same goes for
`report` at sign-off and `review` in a mid-session review: version 1 the
first time, then up from wherever the page has it.
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
the person can read the prerequisites and task specs while you build. Re-post
it whenever the file changes, which is every task: the checkbox write that
@@ -118,12 +111,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
holds anything the person sends until you next look.
A build may receive a `Subagents:` standing instruction, on `open` output or a
`chat` check between tasks. Follow console.md → Standing instructions for
handing independent tasks to helpers and reporting them as `helpers`. Keep the
per-task progress posts, the checkbox writes, the chat checks and the sign-off
with you.
### Quick questions between tasks
The person can ask a Quick question on the Ask tab at any point in a build
@@ -208,8 +195,7 @@ only ever be offered once nothing could come of it:
`reply` carries `Approve this phase: approved`, which is the terminal's
`approved`. If the note that came with an approval asks for a change, treat it
as "describe any issues": do the change first and ask again. `changes` means
exactly what it says: address it, bump the report's version (a later phase's
report starts above the last one's, too), and reopen the
exactly what it says: address it, bump the report's version, and reopen the
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
person asking for the code review before they approve anything — see "The
review, mid-session" below.
@@ -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 |
| --- | --- | --- |
| `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. |
| `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. |
@@ -647,84 +647,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)
A `dashboard` session is not a conversation: the page draws a menu of every
@@ -841,10 +763,7 @@ commands follow the pipeline: the sign-off's is
### Review (`review`)
Scope questions up front — run standalone with nothing named, the first is
a `choice`, "What should I review?", built from a quick scan (branch changes,
uncommitted changes, specs, files you name; each option with its size),
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
Scope questions up front, then the findings report as a doc (`id: "report"`),
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
id, carrying `"doc": "report"` so the card links straight to the findings.
Settle that item (`"status": "answered"` plus the `answer` they sent) in
@@ -878,8 +797,6 @@ 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
finish (Finishing → Nothing of yours may still be running); the finish
body then names what each one found.
- Report every research subagent as a helper, whatever the Subagents switch
says (Standing instructions → Reporting helpers).
- At every session end, post `finish` (headline, `body`, and Form A's command as
`command`) BEFORE `stop`. Someone who spent the session in the browser never
sees the Trail Footer, and without this their last screen promises a question
@@ -1229,16 +1146,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
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
and 5 cover `reason` and `hint`.
8. **`helpers` entries are well formed** (Standing instructions → Reporting
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
and a known `state` within their limits, plus at most one `alone` entry.
Rules 4 and 5 cover `title`, `ask` and `result`.
9. **A doc's `version` never goes back.** Sending a known doc a lower
`version` than the page holds is refused: it is almost always a stale or
copied payload. The same version again is fine, and a dashboard hop starts
every doc fresh. Anything else reusing a doc id in the same session (a
build's second phase, a second report or review) continues from the
version the page holds.
These are workflow rules you already follow. The server just makes them checkable.
@@ -1260,9 +1167,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
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
and update the count as each returns. Never write a `finish.body` that says
work "is running in the background" or "will finish on its own". Mark every
reported helper `done` or `failed` before the finish, so the Subagents tab
never ends on a row still running.
work "is running in the background" or "will finish on its own".
### 1. Post the finish
@@ -64,8 +64,6 @@ import {
readChat,
readJson,
readLedger,
readSubagentCursor,
readSubagentSetting,
readWorkspace,
reapHandles,
rememberedWorkspace,
@@ -73,7 +71,6 @@ import {
removeScratch,
removeSessions,
repoRoots,
resetSubagentCursor,
scanProject,
SESSION_MAX_AGE_MS,
sessionDir,
@@ -91,11 +88,9 @@ import {
workspaceForAgent,
writeCursor,
writeJsonAtomic,
writeSubagentCursor,
writeWorkspaceCursor,
} from "./lib.mjs";
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
import { blockFor, offered } from "./public/subagents.js";
import { changeLine } from "./public/workspace.js";
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
@@ -315,11 +310,7 @@ async function cmdOpen() {
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
// A new agent conversation has been told nothing yet (FR-6).
try {
resetSubagentCursor(dir);
} catch {}
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
trace("open: state written");
// Dashboard launches are recorded too (they score nothing), so the folder
@@ -346,18 +337,9 @@ async function cmdOpen() {
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
};
// A standing instruction the new agent is owed, as `subagents` and a
// `reply` holding only its lines; neither key when nothing is owed.
const subagentsOwed = () => {
awaitSubagentSync(dir, state.workflow);
const [out, cursor] = withSubagents(dir, { reply: "" });
return [out.subagents ? out : {}, cursor];
};
// Reuse a live server if one is already serving this session.
if (existing && (await reusable)) {
if (!args["no-open"]) openBrowser(existing.url);
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -367,11 +349,9 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(existing.url),
workspace,
...owed,
...swept,
...remoteWarning(),
});
advanceSubagents(dir, subCursor);
sweep();
return;
}
@@ -404,7 +384,6 @@ async function cmdOpen() {
const notes = [];
if (remote.note) notes.push(remote.note);
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -415,12 +394,10 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(handle.url),
workspace,
...owed,
...swept,
...(remote.remote ? { remote: remote.remote } : {}),
...(notes.length ? { note: notes.join(" ") } : {}),
});
advanceSubagents(dir, subCursor);
// After the print, never before it: the page and the link wait for nothing.
sweep();
}
@@ -797,7 +774,7 @@ function serverGone(sid) {
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
function deliverChat(dir, sid, entries, url) {
const [withWs, changes] = withWorkspace(dir, {
const [out, changes] = withWorkspace(dir, {
type: "chat",
at: nowIso(),
sid,
@@ -805,11 +782,9 @@ function deliverChat(dir, sid, entries, url) {
chat: entries,
reply: chatReplyLines(entries),
});
const [out, subCursor] = withSubagents(dir, withWs);
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
advanceCursor(dir, entries);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -831,52 +806,6 @@ function advanceWorkspace(dir, changes) {
} catch {}
}
// The server rewrites the session's setting for a new workflow only once its
// watcher sees the state `open` just wrote, so a launch or hop that read the
// file at once would find the old workflow's and owe the agent nothing until
// its next pickup. Give the server a moment to catch up instead, never
// writing the file ourselves (FR-7). A session with no setting file at all is
// an older server, which never writes one: a short look, not the full wait.
const SUBAGENT_SYNC_WAIT_MS = 1500;
const SUBAGENT_SYNC_MISSING_MS = 250;
function awaitSubagentSync(dir, workflow) {
if (!offered(workflow)) return;
const start = Date.now();
for (;;) {
const setting = readSubagentSetting(dir);
if (setting && setting.workflow === workflow) return;
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
if (Date.now() - start >= budget) return;
sleepSync(25);
}
}
// The Subagents switch the agent is owed, added to what it is about to read:
// the setting as `subagents`, and its lines last in `reply`, after card lines,
// Quick questions and Workspace lines (FR-9). Read from the session's own
// setting file only, which only the server writes (FR-7). A setting for
// another workflow is the server not having caught up with a hop yet: it
// rides on the next pickup instead.
function withSubagents(dir, out) {
const setting = readSubagentSetting(dir);
if (!setting) return [out, null];
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
if (setting.workflow !== workflow) return [out, null];
const block = blockFor(setting, readSubagentCursor(dir));
if (!block) return [out, null];
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
return [{ ...out, subagents: block.field, reply }, block.cursor];
}
// After the print, like advanceWorkspace(): a kill in between repeats the
// block at the next pickup, never loses it.
function advanceSubagents(dir, cursor) {
if (!cursor) return;
try {
writeSubagentCursor(dir, cursor);
} catch {}
}
// Print first, then this, exactly as consume() stamps a result: a kill in
// between can only hand the same chat over again, and collectChat() drops
// anything that already has a reply.
@@ -903,17 +832,15 @@ async function cmdChat() {
}
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
const changes = pendingWorkspaceChanges(dir);
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
if (!entries.length && !changes.length && !subCursor) {
if (!entries.length && !changes.length) {
print({ chat: [] });
process.exitCode = 10;
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);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -938,8 +865,7 @@ function consume(dir, resultPath, result, url, chat = []) {
// never on result.json itself.
const withChat = { ...collected, chat };
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
const [withWs, changes] = withWorkspace(dir, withChat);
const [out, subCursor] = withSubagents(dir, withWs);
const [out, changes] = withWorkspace(dir, withChat);
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
try {
writeJsonAtomic(resultPath, collected);
@@ -948,7 +874,6 @@ function consume(dir, resultPath, result, url, chat = []) {
ledgerAnswers(dir, result);
advanceCursor(dir, chat);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = result.type === "cancel" ? 30 : 0;
}
@@ -1061,18 +986,12 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
May also print subagents: { state, revision, max, instruction } and
a reply holding only its "Subagents: ..." lines, when a standing
instruction (the page's Subagents switch) is owed to you.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
carry run: { event, id, tasks? } (session meter points) and folderIssue:
{ name, reason, hint? } (a workspace folder you could not read);
both go to the ledger, never into the state. A patch may also
carry helpers: [{ id, title, ask, state, result? }] or one
{ id: "alone", alone: true }, merged by id, for the Subagents tab
(see console.md → Standing instructions).
both go to the ledger, never into the state.
wait --session <sid> [--seconds <N>]
A bounded wait slice, sized below your shell timeout. Exit 0 = the
result is on stdout, 10 = still waiting ("Waiting on your answer
@@ -1083,14 +1002,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
"workspace" (changes since you last heard, each once, with a
"Workspace: ..." line in reply); exit 10 counts them as
pendingWorkspace, and a change alone never ends a slice.
Exit 0 may also carry "subagents" (a console setting, not typed
by the person, with its "Subagents: ..." lines last in reply); a
setting change alone never ends a slice either.
chat --session <sid>
Collect Quick questions, workspace changes and a Subagents
setting change now, never waiting, never touching card sends.
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
10 = none, 20 = server gone.
Collect Quick questions and workspace changes now, never waiting,
never touching card sends. Exit 0 = { chat, workspace, reply,
terminalLine }, 10 = none, 20 = server gone.
terminalLine is "→ Look at the web console: <url>": end your terminal
messages with it during a console session.
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
@@ -25,7 +25,6 @@ import { fileURLToPath } from "node:url";
import { CHAT_LIMIT } from "./public/chat.js";
import { DOC_TYPES } from "./public/answers.js";
import { defaultName } from "./public/workspace.js";
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const PUBLIC_DIR = path.join(HERE, "public");
@@ -492,16 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, the Subagents switch
// saved per project and workflow, the pointer to this console's directory,
// and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set([
"looks.json",
"workspaces.json",
"subagents.json",
"console-dir",
"update-check.json",
]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -1150,19 +1142,6 @@ const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
// state keeps its text. Blocks left out of the patch stay as they are.
function mergeDocs(current, patchList) {
// A doc's version only moves forward. One going back is a stale or copied
// payload (last phase's progress script, say), and the page would quietly
// show the old content under the new run's name.
for (const entry of patchList) {
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
const prev = (current || []).find((d) => d && d.id === entry.id);
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
throw new Error(
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
"Versions only go up: bump it, and check the payload is the current one."
);
}
}
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
for (const entry of patchList) {
if (!Array.isArray(entry.blocks)) continue;
@@ -1205,13 +1184,6 @@ export function applyPatch(state, patch) {
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
break;
case "helpers":
// The agent's report of its helpers, for the page's Subagents tab.
// Only `post` writes it; the server's /submit never touches it.
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
break;
case "docs":
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
next.docs = mergeDocs(next.docs, v);
@@ -1506,20 +1478,6 @@ export function validate(state) {
JSON.stringify(state.menu || {});
problems.push(...proseProblems(prose));
// The agent's report of its helpers: the shape the page draws from
// (subagents.js), then the same prose scan as everything else it writes.
if (state.helpers != null) {
problems.push(...checkHelpers(state.helpers));
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
if (!isPlainObject(helper)) continue;
for (const field of ["title", "ask", "result"]) {
if (typeof helper[field] === "string") {
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
}
}
}
}
return problems;
}
@@ -1549,8 +1507,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
* A resume that passes through the dashboard (a finished skill going back to
* it, or a launch from its menu) is a new skill taking the page over, so it
* starts from a blank page: the last skill's questions, sections, docs,
* helpers, headline and ending are its record on disk, not the next skill's
* opening.
* headline and ending are its record on disk, not the next skill's opening.
* Only the session's identity carries across. `workspace.json`,
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
* and the meter outlive every hop.
@@ -1577,8 +1534,6 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
// workspace.json the server. Folders, version, change log, missing, remote.
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
export const CHAT_FILE = "chat.ndjson";
export const CHAT_CURSOR_FILE = "chat-cursor.json";
export const WORKSPACE_FILE = "workspace.json";
@@ -2034,98 +1989,6 @@ export function pendingWorkspaceChanges(dir) {
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.
*
@@ -208,26 +208,6 @@ body {
.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); }
/* 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; }
/* The session meter: a ring that fills with the points and a few words, in
@@ -1450,30 +1430,6 @@ h1 {
.pill.done { background: var(--ok-soft); color: var(--ok); }
.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 */
.answered {
@@ -2015,8 +1971,6 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
cursor: pointer;
}
.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. */
.where-alert {
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
@@ -103,15 +103,6 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
import { RED_BANNER } from "./meter.js";
import { applyMention, matchNames, mentionAt } from "./mentions.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);
@@ -539,9 +530,6 @@ 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 chatSending = false;
let chatResetting = false;
@@ -892,8 +880,6 @@ function adopt(body) {
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();
if (gone) {
gone = false;
@@ -1315,7 +1301,6 @@ function render() {
renderChrome();
renderStatus();
renderBriefButton();
renderSubagentsButton();
renderStopButton();
renderHomeButton();
tabAdded = renderViews();
@@ -1581,7 +1566,7 @@ function renderChrome() {
renderMeter();
$("title").textContent = S.title || "Session";
$("badge").textContent = workflowLabel(S.workflow);
renderTabTitle();
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
const h = S.headline || {};
// On a finished session an open item is frozen: the send on it counts as
@@ -1850,69 +1835,6 @@ function renderBriefButton() {
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() {
const nav = $("views");
nav.replaceChildren();
@@ -1928,14 +1850,6 @@ function renderViews() {
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
else if (view === "overview") view = "questions";
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.
// The ring left of "Ask" shows exactly when the conversation's own ring does:
// a question the agent picked up and has not answered yet.
@@ -2216,7 +2130,6 @@ function paintMain(main) {
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
if (view === "overview") return renderOverview(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 top of the rail. The hand-off lives here alone now, rather than
@@ -4861,42 +4774,6 @@ function renderOverview(main) {
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 */
// The frame's chat block, with `offline` worked out now rather than when the
@@ -6079,30 +5956,10 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
// 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
// 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() {
const b = $("footer-where");
const folders = workspaceFolders();
const path = S.worktree || "";
renderTabTitle();
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
const labels = folders.length
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
@@ -6115,16 +5972,7 @@ function renderWhere() {
let label = labels[0];
for (const text of labels) {
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) {
const dot = el("span", "where-alert");
dot.setAttribute("aria-hidden", "true");
@@ -7349,7 +7197,6 @@ function lightDismiss(dlg) {
});
}
lightDismiss($("looks-modal"));
lightDismiss($("subagents-modal"));
lightDismiss($("help-modal"));
lightDismiss($("workspace-modal"));
lightDismiss($("welcome-modal"));
@@ -7652,13 +7499,6 @@ $("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("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-go").addEventListener("click", sendBrief);
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("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("subagents", "Helpers (subagents)", false),
tab("ask", "Ask a quick question", false),
tab("finishing", "Stopping and finishing", false),
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 (workspace) return "workspace";
if (v === "ask") return "ask";
if (v === "subagents") return "subagents";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v.startsWith("doc:")) return "docs";
@@ -21,7 +21,6 @@
<link rel="modulepreload" href="/starters.js" />
<link rel="modulepreload" href="/workspace.js" />
<link rel="modulepreload" href="/meter.js" />
<link rel="modulepreload" href="/subagents.js" />
<link rel="modulepreload" href="/mentions.js" />
<link rel="modulepreload" href="/favicon.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>
Write a brief
</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 class="views-group">
<span class="views-arrow" aria-hidden="true">
@@ -593,13 +580,6 @@
<rect x="3" y="9" width="18" height="6" rx="3" />
<path d="M6 12h7" />
</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">
<path d="M4 5h16v11H10l-4 4v-4H4z" />
<path d="M8 9.5h8M8 12.5h5" />
@@ -1497,61 +1477,7 @@
</p>
</section>
<!-- Tab 12: Helpers (subagents) -->
<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 -->
<!-- Tab 12: Ask a quick question -->
<section class="help-panel" data-tab="ask">
<h3>Ask a quick question</h3>
<p class="help-lead">
@@ -1642,7 +1568,7 @@
</p>
</section>
<!-- Tab 14: Stopping and finishing -->
<!-- Tab 13: Stopping and finishing -->
<section class="help-panel" data-tab="finishing">
<h3>Stopping and finishing</h3>
<p class="help-lead">
@@ -1724,7 +1650,7 @@
</p>
</section>
<!-- Tab 15: When something looks stuck -->
<!-- Tab 14: When something looks stuck -->
<section class="help-panel" data-tab="stuck">
<h3>When something looks stuck</h3>
<p class="help-lead">
@@ -1846,7 +1772,7 @@
</div>
</section>
<!-- Tab 16: Keyboard and preferences -->
<!-- Tab 15: Keyboard and preferences -->
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
@@ -1962,7 +1888,7 @@
</ul>
</section>
<!-- Tab 17: Privacy and where things are saved -->
<!-- Tab 16: Privacy and where things are saved -->
<section class="help-panel" data-tab="privacy">
<h3>Privacy and where things are saved</h3>
<p class="help-lead">
@@ -1999,11 +1925,7 @@
</li>
<li>
your role, theme, colors, card width and sounds, in
<code>looks.json</code>;
</li>
<li>
your Subagents switch for each project and skill, in
<code>subagents.json</code>.
<code>looks.json</code>.
</li>
</ul>
<p>
@@ -2117,46 +2039,6 @@
</div>
</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
context. The list is drawn by app.js from the frame's `workspace`;
every change goes through the server's /workspace routes. -->
@@ -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,7 +25,6 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
SUBAGENTS_SETTING_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
@@ -39,7 +38,6 @@ import {
fileStamp,
handleFile,
initialWorkspace,
latestOpenCaps,
nowIso,
parseArgs,
pendingChatCount,
@@ -48,25 +46,20 @@ import {
readJson,
readLedger,
readOverview,
readSubagentSetting,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
saveSubagentStoreEntry,
specKey,
subagentStoreEntry,
typedCount,
withStateLock,
writeJsonAtomic,
writeSubagentSetting,
writeWorkspace,
} from "./lib.mjs";
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 { 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 { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
@@ -219,7 +212,6 @@ const SERVABLE = new Set([
"starters.js",
"workspace.js",
"meter.js",
"subagents.js",
"mentions.js",
"favicon.js",
"start-stop.mp3",
@@ -609,48 +601,6 @@ function ensureConversation(state) {
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.
// `have` names that exact view, for the page to hand back when it opens its
// stream (see /events).
@@ -665,33 +615,20 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
subagents: subagentsView(state),
...(updateInfo ? { update: updateInfo } : {}),
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() {
const { pending, stop } = resultFlags();
chatEntries();
chatPickedUp();
workspaceNow();
ledgerEntries();
subagentSettingNow();
openCapsNow();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -1235,39 +1172,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.
if (pathname === "/models" && req.method === "GET") {
const saved = readJson(USER_MODELS_FILE, null) || {};
@@ -1496,9 +1400,6 @@ const server = http.createServer((req, res) => {
try {
ensureConversation(written.state);
} catch {}
try {
syncSubagentSetting(written.state);
} catch {}
}
}
// Name the items that went. A page with OTHER answers staged should drop
@@ -1825,9 +1726,6 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
syncSubagentSetting(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
@@ -2002,9 +1900,6 @@ function onListening(port) {
try {
bootWorkspace();
} catch {}
try {
syncSubagentSetting(readState());
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -64,13 +64,6 @@ progress bar is the first thing someone watching a build looks at. The session
meter counts the build's tasks from `cleared` as it rises, so keep it current,
and start every phase (a second one in the same run too) at `"cleared": 0`.
`"version": 1` is for the first phase of a session only. A doc's version
never goes back (console.md → House rules, rule 9), so a later phase in the
same session reposts `phase` and `phasefile` at one more than the version the
page holds, with the new phase's title and content. The same goes for
`report` at sign-off and `review` in a mid-session review: version 1 the
first time, then up from wherever the page has it.
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
the person can read the prerequisites and task specs while you build. Re-post
it whenever the file changes, which is every task: the checkbox write that
@@ -118,12 +111,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
holds anything the person sends until you next look.
A build may receive a `Subagents:` standing instruction, on `open` output or a
`chat` check between tasks. Follow console.md → Standing instructions for
handing independent tasks to helpers and reporting them as `helpers`. Keep the
per-task progress posts, the checkbox writes, the chat checks and the sign-off
with you.
### Quick questions between tasks
The person can ask a Quick question on the Ask tab at any point in a build
@@ -208,8 +195,7 @@ only ever be offered once nothing could come of it:
`reply` carries `Approve this phase: approved`, which is the terminal's
`approved`. If the note that came with an approval asks for a change, treat it
as "describe any issues": do the change first and ask again. `changes` means
exactly what it says: address it, bump the report's version (a later phase's
report starts above the last one's, too), and reopen the
exactly what it says: address it, bump the report's version, and reopen the
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
person asking for the code review before they approve anything — see "The
review, mid-session" below.
@@ -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 |
| --- | --- | --- |
| `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. |
| `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. |
@@ -647,84 +647,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)
A `dashboard` session is not a conversation: the page draws a menu of every
@@ -841,10 +763,7 @@ commands follow the pipeline: the sign-off's is
### Review (`review`)
Scope questions up front — run standalone with nothing named, the first is
a `choice`, "What should I review?", built from a quick scan (branch changes,
uncommitted changes, specs, files you name; each option with its size),
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
Scope questions up front, then the findings report as a doc (`id: "report"`),
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
id, carrying `"doc": "report"` so the card links straight to the findings.
Settle that item (`"status": "answered"` plus the `answer` they sent) in
@@ -878,8 +797,6 @@ 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
finish (Finishing → Nothing of yours may still be running); the finish
body then names what each one found.
- Report every research subagent as a helper, whatever the Subagents switch
says (Standing instructions → Reporting helpers).
- At every session end, post `finish` (headline, `body`, and Form A's command as
`command`) BEFORE `stop`. Someone who spent the session in the browser never
sees the Trail Footer, and without this their last screen promises a question
@@ -1229,16 +1146,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
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
and 5 cover `reason` and `hint`.
8. **`helpers` entries are well formed** (Standing instructions → Reporting
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
and a known `state` within their limits, plus at most one `alone` entry.
Rules 4 and 5 cover `title`, `ask` and `result`.
9. **A doc's `version` never goes back.** Sending a known doc a lower
`version` than the page holds is refused: it is almost always a stale or
copied payload. The same version again is fine, and a dashboard hop starts
every doc fresh. Anything else reusing a doc id in the same session (a
build's second phase, a second report or review) continues from the
version the page holds.
These are workflow rules you already follow. The server just makes them checkable.
@@ -1260,9 +1167,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
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
and update the count as each returns. Never write a `finish.body` that says
work "is running in the background" or "will finish on its own". Mark every
reported helper `done` or `failed` before the finish, so the Subagents tab
never ends on a row still running.
work "is running in the background" or "will finish on its own".
### 1. Post the finish
@@ -64,8 +64,6 @@ import {
readChat,
readJson,
readLedger,
readSubagentCursor,
readSubagentSetting,
readWorkspace,
reapHandles,
rememberedWorkspace,
@@ -73,7 +71,6 @@ import {
removeScratch,
removeSessions,
repoRoots,
resetSubagentCursor,
scanProject,
SESSION_MAX_AGE_MS,
sessionDir,
@@ -91,11 +88,9 @@ import {
workspaceForAgent,
writeCursor,
writeJsonAtomic,
writeSubagentCursor,
writeWorkspaceCursor,
} from "./lib.mjs";
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
import { blockFor, offered } from "./public/subagents.js";
import { changeLine } from "./public/workspace.js";
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
@@ -315,11 +310,7 @@ async function cmdOpen() {
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
// A new agent conversation has been told nothing yet (FR-6).
try {
resetSubagentCursor(dir);
} catch {}
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
trace("open: state written");
// Dashboard launches are recorded too (they score nothing), so the folder
@@ -346,18 +337,9 @@ async function cmdOpen() {
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
};
// A standing instruction the new agent is owed, as `subagents` and a
// `reply` holding only its lines; neither key when nothing is owed.
const subagentsOwed = () => {
awaitSubagentSync(dir, state.workflow);
const [out, cursor] = withSubagents(dir, { reply: "" });
return [out.subagents ? out : {}, cursor];
};
// Reuse a live server if one is already serving this session.
if (existing && (await reusable)) {
if (!args["no-open"]) openBrowser(existing.url);
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -367,11 +349,9 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(existing.url),
workspace,
...owed,
...swept,
...remoteWarning(),
});
advanceSubagents(dir, subCursor);
sweep();
return;
}
@@ -404,7 +384,6 @@ async function cmdOpen() {
const notes = [];
if (remote.note) notes.push(remote.note);
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -415,12 +394,10 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(handle.url),
workspace,
...owed,
...swept,
...(remote.remote ? { remote: remote.remote } : {}),
...(notes.length ? { note: notes.join(" ") } : {}),
});
advanceSubagents(dir, subCursor);
// After the print, never before it: the page and the link wait for nothing.
sweep();
}
@@ -797,7 +774,7 @@ function serverGone(sid) {
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
function deliverChat(dir, sid, entries, url) {
const [withWs, changes] = withWorkspace(dir, {
const [out, changes] = withWorkspace(dir, {
type: "chat",
at: nowIso(),
sid,
@@ -805,11 +782,9 @@ function deliverChat(dir, sid, entries, url) {
chat: entries,
reply: chatReplyLines(entries),
});
const [out, subCursor] = withSubagents(dir, withWs);
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
advanceCursor(dir, entries);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -831,52 +806,6 @@ function advanceWorkspace(dir, changes) {
} catch {}
}
// The server rewrites the session's setting for a new workflow only once its
// watcher sees the state `open` just wrote, so a launch or hop that read the
// file at once would find the old workflow's and owe the agent nothing until
// its next pickup. Give the server a moment to catch up instead, never
// writing the file ourselves (FR-7). A session with no setting file at all is
// an older server, which never writes one: a short look, not the full wait.
const SUBAGENT_SYNC_WAIT_MS = 1500;
const SUBAGENT_SYNC_MISSING_MS = 250;
function awaitSubagentSync(dir, workflow) {
if (!offered(workflow)) return;
const start = Date.now();
for (;;) {
const setting = readSubagentSetting(dir);
if (setting && setting.workflow === workflow) return;
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
if (Date.now() - start >= budget) return;
sleepSync(25);
}
}
// The Subagents switch the agent is owed, added to what it is about to read:
// the setting as `subagents`, and its lines last in `reply`, after card lines,
// Quick questions and Workspace lines (FR-9). Read from the session's own
// setting file only, which only the server writes (FR-7). A setting for
// another workflow is the server not having caught up with a hop yet: it
// rides on the next pickup instead.
function withSubagents(dir, out) {
const setting = readSubagentSetting(dir);
if (!setting) return [out, null];
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
if (setting.workflow !== workflow) return [out, null];
const block = blockFor(setting, readSubagentCursor(dir));
if (!block) return [out, null];
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
return [{ ...out, subagents: block.field, reply }, block.cursor];
}
// After the print, like advanceWorkspace(): a kill in between repeats the
// block at the next pickup, never loses it.
function advanceSubagents(dir, cursor) {
if (!cursor) return;
try {
writeSubagentCursor(dir, cursor);
} catch {}
}
// Print first, then this, exactly as consume() stamps a result: a kill in
// between can only hand the same chat over again, and collectChat() drops
// anything that already has a reply.
@@ -903,17 +832,15 @@ async function cmdChat() {
}
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
const changes = pendingWorkspaceChanges(dir);
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
if (!entries.length && !changes.length && !subCursor) {
if (!entries.length && !changes.length) {
print({ chat: [] });
process.exitCode = 10;
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);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -938,8 +865,7 @@ function consume(dir, resultPath, result, url, chat = []) {
// never on result.json itself.
const withChat = { ...collected, chat };
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
const [withWs, changes] = withWorkspace(dir, withChat);
const [out, subCursor] = withSubagents(dir, withWs);
const [out, changes] = withWorkspace(dir, withChat);
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
try {
writeJsonAtomic(resultPath, collected);
@@ -948,7 +874,6 @@ function consume(dir, resultPath, result, url, chat = []) {
ledgerAnswers(dir, result);
advanceCursor(dir, chat);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = result.type === "cancel" ? 30 : 0;
}
@@ -1061,18 +986,12 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
May also print subagents: { state, revision, max, instruction } and
a reply holding only its "Subagents: ..." lines, when a standing
instruction (the page's Subagents switch) is owed to you.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
carry run: { event, id, tasks? } (session meter points) and folderIssue:
{ name, reason, hint? } (a workspace folder you could not read);
both go to the ledger, never into the state. A patch may also
carry helpers: [{ id, title, ask, state, result? }] or one
{ id: "alone", alone: true }, merged by id, for the Subagents tab
(see console.md → Standing instructions).
both go to the ledger, never into the state.
wait --session <sid> [--seconds <N>]
A bounded wait slice, sized below your shell timeout. Exit 0 = the
result is on stdout, 10 = still waiting ("Waiting on your answer
@@ -1083,14 +1002,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
"workspace" (changes since you last heard, each once, with a
"Workspace: ..." line in reply); exit 10 counts them as
pendingWorkspace, and a change alone never ends a slice.
Exit 0 may also carry "subagents" (a console setting, not typed
by the person, with its "Subagents: ..." lines last in reply); a
setting change alone never ends a slice either.
chat --session <sid>
Collect Quick questions, workspace changes and a Subagents
setting change now, never waiting, never touching card sends.
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
10 = none, 20 = server gone.
Collect Quick questions and workspace changes now, never waiting,
never touching card sends. Exit 0 = { chat, workspace, reply,
terminalLine }, 10 = none, 20 = server gone.
terminalLine is "→ Look at the web console: <url>": end your terminal
messages with it during a console session.
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
@@ -25,7 +25,6 @@ import { fileURLToPath } from "node:url";
import { CHAT_LIMIT } from "./public/chat.js";
import { DOC_TYPES } from "./public/answers.js";
import { defaultName } from "./public/workspace.js";
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const PUBLIC_DIR = path.join(HERE, "public");
@@ -492,16 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, the Subagents switch
// saved per project and workflow, the pointer to this console's directory,
// and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set([
"looks.json",
"workspaces.json",
"subagents.json",
"console-dir",
"update-check.json",
]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -1150,19 +1142,6 @@ const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
// state keeps its text. Blocks left out of the patch stay as they are.
function mergeDocs(current, patchList) {
// A doc's version only moves forward. One going back is a stale or copied
// payload (last phase's progress script, say), and the page would quietly
// show the old content under the new run's name.
for (const entry of patchList) {
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
const prev = (current || []).find((d) => d && d.id === entry.id);
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
throw new Error(
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
"Versions only go up: bump it, and check the payload is the current one."
);
}
}
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
for (const entry of patchList) {
if (!Array.isArray(entry.blocks)) continue;
@@ -1205,13 +1184,6 @@ export function applyPatch(state, patch) {
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
break;
case "helpers":
// The agent's report of its helpers, for the page's Subagents tab.
// Only `post` writes it; the server's /submit never touches it.
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
break;
case "docs":
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
next.docs = mergeDocs(next.docs, v);
@@ -1506,20 +1478,6 @@ export function validate(state) {
JSON.stringify(state.menu || {});
problems.push(...proseProblems(prose));
// The agent's report of its helpers: the shape the page draws from
// (subagents.js), then the same prose scan as everything else it writes.
if (state.helpers != null) {
problems.push(...checkHelpers(state.helpers));
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
if (!isPlainObject(helper)) continue;
for (const field of ["title", "ask", "result"]) {
if (typeof helper[field] === "string") {
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
}
}
}
}
return problems;
}
@@ -1549,8 +1507,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
* A resume that passes through the dashboard (a finished skill going back to
* it, or a launch from its menu) is a new skill taking the page over, so it
* starts from a blank page: the last skill's questions, sections, docs,
* helpers, headline and ending are its record on disk, not the next skill's
* opening.
* headline and ending are its record on disk, not the next skill's opening.
* Only the session's identity carries across. `workspace.json`,
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
* and the meter outlive every hop.
@@ -1577,8 +1534,6 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
// workspace.json the server. Folders, version, change log, missing, remote.
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
export const CHAT_FILE = "chat.ndjson";
export const CHAT_CURSOR_FILE = "chat-cursor.json";
export const WORKSPACE_FILE = "workspace.json";
@@ -2034,98 +1989,6 @@ export function pendingWorkspaceChanges(dir) {
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.
*
@@ -208,26 +208,6 @@ body {
.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); }
/* 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; }
/* The session meter: a ring that fills with the points and a few words, in
@@ -1450,30 +1430,6 @@ h1 {
.pill.done { background: var(--ok-soft); color: var(--ok); }
.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 */
.answered {
@@ -2015,8 +1971,6 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
cursor: pointer;
}
.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. */
.where-alert {
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
@@ -103,15 +103,6 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
import { RED_BANNER } from "./meter.js";
import { applyMention, matchNames, mentionAt } from "./mentions.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);
@@ -539,9 +530,6 @@ 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 chatSending = false;
let chatResetting = false;
@@ -892,8 +880,6 @@ function adopt(body) {
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();
if (gone) {
gone = false;
@@ -1315,7 +1301,6 @@ function render() {
renderChrome();
renderStatus();
renderBriefButton();
renderSubagentsButton();
renderStopButton();
renderHomeButton();
tabAdded = renderViews();
@@ -1581,7 +1566,7 @@ function renderChrome() {
renderMeter();
$("title").textContent = S.title || "Session";
$("badge").textContent = workflowLabel(S.workflow);
renderTabTitle();
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
const h = S.headline || {};
// On a finished session an open item is frozen: the send on it counts as
@@ -1850,69 +1835,6 @@ function renderBriefButton() {
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() {
const nav = $("views");
nav.replaceChildren();
@@ -1928,14 +1850,6 @@ function renderViews() {
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
else if (view === "overview") view = "questions";
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.
// The ring left of "Ask" shows exactly when the conversation's own ring does:
// a question the agent picked up and has not answered yet.
@@ -2216,7 +2130,6 @@ function paintMain(main) {
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
if (view === "overview") return renderOverview(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 top of the rail. The hand-off lives here alone now, rather than
@@ -4861,42 +4774,6 @@ function renderOverview(main) {
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 */
// The frame's chat block, with `offline` worked out now rather than when the
@@ -6079,30 +5956,10 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
// 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
// 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() {
const b = $("footer-where");
const folders = workspaceFolders();
const path = S.worktree || "";
renderTabTitle();
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
const labels = folders.length
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
@@ -6115,16 +5972,7 @@ function renderWhere() {
let label = labels[0];
for (const text of labels) {
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) {
const dot = el("span", "where-alert");
dot.setAttribute("aria-hidden", "true");
@@ -7349,7 +7197,6 @@ function lightDismiss(dlg) {
});
}
lightDismiss($("looks-modal"));
lightDismiss($("subagents-modal"));
lightDismiss($("help-modal"));
lightDismiss($("workspace-modal"));
lightDismiss($("welcome-modal"));
@@ -7652,13 +7499,6 @@ $("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("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-go").addEventListener("click", sendBrief);
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("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("subagents", "Helpers (subagents)", false),
tab("ask", "Ask a quick question", false),
tab("finishing", "Stopping and finishing", false),
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 (workspace) return "workspace";
if (v === "ask") return "ask";
if (v === "subagents") return "subagents";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v.startsWith("doc:")) return "docs";
@@ -21,7 +21,6 @@
<link rel="modulepreload" href="/starters.js" />
<link rel="modulepreload" href="/workspace.js" />
<link rel="modulepreload" href="/meter.js" />
<link rel="modulepreload" href="/subagents.js" />
<link rel="modulepreload" href="/mentions.js" />
<link rel="modulepreload" href="/favicon.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>
Write a brief
</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 class="views-group">
<span class="views-arrow" aria-hidden="true">
@@ -593,13 +580,6 @@
<rect x="3" y="9" width="18" height="6" rx="3" />
<path d="M6 12h7" />
</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">
<path d="M4 5h16v11H10l-4 4v-4H4z" />
<path d="M8 9.5h8M8 12.5h5" />
@@ -1497,61 +1477,7 @@
</p>
</section>
<!-- Tab 12: Helpers (subagents) -->
<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 -->
<!-- Tab 12: Ask a quick question -->
<section class="help-panel" data-tab="ask">
<h3>Ask a quick question</h3>
<p class="help-lead">
@@ -1642,7 +1568,7 @@
</p>
</section>
<!-- Tab 14: Stopping and finishing -->
<!-- Tab 13: Stopping and finishing -->
<section class="help-panel" data-tab="finishing">
<h3>Stopping and finishing</h3>
<p class="help-lead">
@@ -1724,7 +1650,7 @@
</p>
</section>
<!-- Tab 15: When something looks stuck -->
<!-- Tab 14: When something looks stuck -->
<section class="help-panel" data-tab="stuck">
<h3>When something looks stuck</h3>
<p class="help-lead">
@@ -1846,7 +1772,7 @@
</div>
</section>
<!-- Tab 16: Keyboard and preferences -->
<!-- Tab 15: Keyboard and preferences -->
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
@@ -1962,7 +1888,7 @@
</ul>
</section>
<!-- Tab 17: Privacy and where things are saved -->
<!-- Tab 16: Privacy and where things are saved -->
<section class="help-panel" data-tab="privacy">
<h3>Privacy and where things are saved</h3>
<p class="help-lead">
@@ -1999,11 +1925,7 @@
</li>
<li>
your role, theme, colors, card width and sounds, in
<code>looks.json</code>;
</li>
<li>
your Subagents switch for each project and skill, in
<code>subagents.json</code>.
<code>looks.json</code>.
</li>
</ul>
<p>
@@ -2117,46 +2039,6 @@
</div>
</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
context. The list is drawn by app.js from the frame's `workspace`;
every change goes through the server's /workspace routes. -->
@@ -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,7 +25,6 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
SUBAGENTS_SETTING_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
@@ -39,7 +38,6 @@ import {
fileStamp,
handleFile,
initialWorkspace,
latestOpenCaps,
nowIso,
parseArgs,
pendingChatCount,
@@ -48,25 +46,20 @@ import {
readJson,
readLedger,
readOverview,
readSubagentSetting,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
saveSubagentStoreEntry,
specKey,
subagentStoreEntry,
typedCount,
withStateLock,
writeJsonAtomic,
writeSubagentSetting,
writeWorkspace,
} from "./lib.mjs";
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 { 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 { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
@@ -219,7 +212,6 @@ const SERVABLE = new Set([
"starters.js",
"workspace.js",
"meter.js",
"subagents.js",
"mentions.js",
"favicon.js",
"start-stop.mp3",
@@ -609,48 +601,6 @@ function ensureConversation(state) {
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.
// `have` names that exact view, for the page to hand back when it opens its
// stream (see /events).
@@ -665,33 +615,20 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
subagents: subagentsView(state),
...(updateInfo ? { update: updateInfo } : {}),
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() {
const { pending, stop } = resultFlags();
chatEntries();
chatPickedUp();
workspaceNow();
ledgerEntries();
subagentSettingNow();
openCapsNow();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -1235,39 +1172,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.
if (pathname === "/models" && req.method === "GET") {
const saved = readJson(USER_MODELS_FILE, null) || {};
@@ -1496,9 +1400,6 @@ const server = http.createServer((req, res) => {
try {
ensureConversation(written.state);
} catch {}
try {
syncSubagentSetting(written.state);
} catch {}
}
}
// Name the items that went. A page with OTHER answers staged should drop
@@ -1825,9 +1726,6 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
syncSubagentSetting(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
@@ -2002,9 +1900,6 @@ function onListening(port) {
try {
bootWorkspace();
} catch {}
try {
syncSubagentSetting(readState());
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -64,13 +64,6 @@ progress bar is the first thing someone watching a build looks at. The session
meter counts the build's tasks from `cleared` as it rises, so keep it current,
and start every phase (a second one in the same run too) at `"cleared": 0`.
`"version": 1` is for the first phase of a session only. A doc's version
never goes back (console.md → House rules, rule 9), so a later phase in the
same session reposts `phase` and `phasefile` at one more than the version the
page holds, with the new phase's title and content. The same goes for
`report` at sign-off and `review` in a mid-session review: version 1 the
first time, then up from wherever the page has it.
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
the person can read the prerequisites and task specs while you build. Re-post
it whenever the file changes, which is every task: the checkbox write that
@@ -118,12 +111,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
holds anything the person sends until you next look.
A build may receive a `Subagents:` standing instruction, on `open` output or a
`chat` check between tasks. Follow console.md → Standing instructions for
handing independent tasks to helpers and reporting them as `helpers`. Keep the
per-task progress posts, the checkbox writes, the chat checks and the sign-off
with you.
### Quick questions between tasks
The person can ask a Quick question on the Ask tab at any point in a build
@@ -208,8 +195,7 @@ only ever be offered once nothing could come of it:
`reply` carries `Approve this phase: approved`, which is the terminal's
`approved`. If the note that came with an approval asks for a change, treat it
as "describe any issues": do the change first and ask again. `changes` means
exactly what it says: address it, bump the report's version (a later phase's
report starts above the last one's, too), and reopen the
exactly what it says: address it, bump the report's version, and reopen the
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
person asking for the code review before they approve anything — see "The
review, mid-session" below.
@@ -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 |
| --- | --- | --- |
| `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. |
| `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. |
@@ -647,84 +647,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)
A `dashboard` session is not a conversation: the page draws a menu of every
@@ -841,10 +763,7 @@ commands follow the pipeline: the sign-off's is
### Review (`review`)
Scope questions up front — run standalone with nothing named, the first is
a `choice`, "What should I review?", built from a quick scan (branch changes,
uncommitted changes, specs, files you name; each option with its size),
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
Scope questions up front, then the findings report as a doc (`id: "report"`),
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
id, carrying `"doc": "report"` so the card links straight to the findings.
Settle that item (`"status": "answered"` plus the `answer` they sent) in
@@ -878,8 +797,6 @@ 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
finish (Finishing → Nothing of yours may still be running); the finish
body then names what each one found.
- Report every research subagent as a helper, whatever the Subagents switch
says (Standing instructions → Reporting helpers).
- At every session end, post `finish` (headline, `body`, and Form A's command as
`command`) BEFORE `stop`. Someone who spent the session in the browser never
sees the Trail Footer, and without this their last screen promises a question
@@ -1229,16 +1146,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
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
and 5 cover `reason` and `hint`.
8. **`helpers` entries are well formed** (Standing instructions → Reporting
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
and a known `state` within their limits, plus at most one `alone` entry.
Rules 4 and 5 cover `title`, `ask` and `result`.
9. **A doc's `version` never goes back.** Sending a known doc a lower
`version` than the page holds is refused: it is almost always a stale or
copied payload. The same version again is fine, and a dashboard hop starts
every doc fresh. Anything else reusing a doc id in the same session (a
build's second phase, a second report or review) continues from the
version the page holds.
These are workflow rules you already follow. The server just makes them checkable.
@@ -1260,9 +1167,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
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
and update the count as each returns. Never write a `finish.body` that says
work "is running in the background" or "will finish on its own". Mark every
reported helper `done` or `failed` before the finish, so the Subagents tab
never ends on a row still running.
work "is running in the background" or "will finish on its own".
### 1. Post the finish
@@ -64,8 +64,6 @@ import {
readChat,
readJson,
readLedger,
readSubagentCursor,
readSubagentSetting,
readWorkspace,
reapHandles,
rememberedWorkspace,
@@ -73,7 +71,6 @@ import {
removeScratch,
removeSessions,
repoRoots,
resetSubagentCursor,
scanProject,
SESSION_MAX_AGE_MS,
sessionDir,
@@ -91,11 +88,9 @@ import {
workspaceForAgent,
writeCursor,
writeJsonAtomic,
writeSubagentCursor,
writeWorkspaceCursor,
} from "./lib.mjs";
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
import { blockFor, offered } from "./public/subagents.js";
import { changeLine } from "./public/workspace.js";
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
@@ -315,11 +310,7 @@ async function cmdOpen() {
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
// A new agent conversation has been told nothing yet (FR-6).
try {
resetSubagentCursor(dir);
} catch {}
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
trace("open: state written");
// Dashboard launches are recorded too (they score nothing), so the folder
@@ -346,18 +337,9 @@ async function cmdOpen() {
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
};
// A standing instruction the new agent is owed, as `subagents` and a
// `reply` holding only its lines; neither key when nothing is owed.
const subagentsOwed = () => {
awaitSubagentSync(dir, state.workflow);
const [out, cursor] = withSubagents(dir, { reply: "" });
return [out.subagents ? out : {}, cursor];
};
// Reuse a live server if one is already serving this session.
if (existing && (await reusable)) {
if (!args["no-open"]) openBrowser(existing.url);
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -367,11 +349,9 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(existing.url),
workspace,
...owed,
...swept,
...remoteWarning(),
});
advanceSubagents(dir, subCursor);
sweep();
return;
}
@@ -404,7 +384,6 @@ async function cmdOpen() {
const notes = [];
if (remote.note) notes.push(remote.note);
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -415,12 +394,10 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(handle.url),
workspace,
...owed,
...swept,
...(remote.remote ? { remote: remote.remote } : {}),
...(notes.length ? { note: notes.join(" ") } : {}),
});
advanceSubagents(dir, subCursor);
// After the print, never before it: the page and the link wait for nothing.
sweep();
}
@@ -797,7 +774,7 @@ function serverGone(sid) {
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
function deliverChat(dir, sid, entries, url) {
const [withWs, changes] = withWorkspace(dir, {
const [out, changes] = withWorkspace(dir, {
type: "chat",
at: nowIso(),
sid,
@@ -805,11 +782,9 @@ function deliverChat(dir, sid, entries, url) {
chat: entries,
reply: chatReplyLines(entries),
});
const [out, subCursor] = withSubagents(dir, withWs);
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
advanceCursor(dir, entries);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -831,52 +806,6 @@ function advanceWorkspace(dir, changes) {
} catch {}
}
// The server rewrites the session's setting for a new workflow only once its
// watcher sees the state `open` just wrote, so a launch or hop that read the
// file at once would find the old workflow's and owe the agent nothing until
// its next pickup. Give the server a moment to catch up instead, never
// writing the file ourselves (FR-7). A session with no setting file at all is
// an older server, which never writes one: a short look, not the full wait.
const SUBAGENT_SYNC_WAIT_MS = 1500;
const SUBAGENT_SYNC_MISSING_MS = 250;
function awaitSubagentSync(dir, workflow) {
if (!offered(workflow)) return;
const start = Date.now();
for (;;) {
const setting = readSubagentSetting(dir);
if (setting && setting.workflow === workflow) return;
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
if (Date.now() - start >= budget) return;
sleepSync(25);
}
}
// The Subagents switch the agent is owed, added to what it is about to read:
// the setting as `subagents`, and its lines last in `reply`, after card lines,
// Quick questions and Workspace lines (FR-9). Read from the session's own
// setting file only, which only the server writes (FR-7). A setting for
// another workflow is the server not having caught up with a hop yet: it
// rides on the next pickup instead.
function withSubagents(dir, out) {
const setting = readSubagentSetting(dir);
if (!setting) return [out, null];
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
if (setting.workflow !== workflow) return [out, null];
const block = blockFor(setting, readSubagentCursor(dir));
if (!block) return [out, null];
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
return [{ ...out, subagents: block.field, reply }, block.cursor];
}
// After the print, like advanceWorkspace(): a kill in between repeats the
// block at the next pickup, never loses it.
function advanceSubagents(dir, cursor) {
if (!cursor) return;
try {
writeSubagentCursor(dir, cursor);
} catch {}
}
// Print first, then this, exactly as consume() stamps a result: a kill in
// between can only hand the same chat over again, and collectChat() drops
// anything that already has a reply.
@@ -903,17 +832,15 @@ async function cmdChat() {
}
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
const changes = pendingWorkspaceChanges(dir);
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
if (!entries.length && !changes.length && !subCursor) {
if (!entries.length && !changes.length) {
print({ chat: [] });
process.exitCode = 10;
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);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -938,8 +865,7 @@ function consume(dir, resultPath, result, url, chat = []) {
// never on result.json itself.
const withChat = { ...collected, chat };
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
const [withWs, changes] = withWorkspace(dir, withChat);
const [out, subCursor] = withSubagents(dir, withWs);
const [out, changes] = withWorkspace(dir, withChat);
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
try {
writeJsonAtomic(resultPath, collected);
@@ -948,7 +874,6 @@ function consume(dir, resultPath, result, url, chat = []) {
ledgerAnswers(dir, result);
advanceCursor(dir, chat);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = result.type === "cancel" ? 30 : 0;
}
@@ -1061,18 +986,12 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
May also print subagents: { state, revision, max, instruction } and
a reply holding only its "Subagents: ..." lines, when a standing
instruction (the page's Subagents switch) is owed to you.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
carry run: { event, id, tasks? } (session meter points) and folderIssue:
{ name, reason, hint? } (a workspace folder you could not read);
both go to the ledger, never into the state. A patch may also
carry helpers: [{ id, title, ask, state, result? }] or one
{ id: "alone", alone: true }, merged by id, for the Subagents tab
(see console.md → Standing instructions).
both go to the ledger, never into the state.
wait --session <sid> [--seconds <N>]
A bounded wait slice, sized below your shell timeout. Exit 0 = the
result is on stdout, 10 = still waiting ("Waiting on your answer
@@ -1083,14 +1002,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
"workspace" (changes since you last heard, each once, with a
"Workspace: ..." line in reply); exit 10 counts them as
pendingWorkspace, and a change alone never ends a slice.
Exit 0 may also carry "subagents" (a console setting, not typed
by the person, with its "Subagents: ..." lines last in reply); a
setting change alone never ends a slice either.
chat --session <sid>
Collect Quick questions, workspace changes and a Subagents
setting change now, never waiting, never touching card sends.
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
10 = none, 20 = server gone.
Collect Quick questions and workspace changes now, never waiting,
never touching card sends. Exit 0 = { chat, workspace, reply,
terminalLine }, 10 = none, 20 = server gone.
terminalLine is "→ Look at the web console: <url>": end your terminal
messages with it during a console session.
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
@@ -25,7 +25,6 @@ import { fileURLToPath } from "node:url";
import { CHAT_LIMIT } from "./public/chat.js";
import { DOC_TYPES } from "./public/answers.js";
import { defaultName } from "./public/workspace.js";
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const PUBLIC_DIR = path.join(HERE, "public");
@@ -492,16 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, the Subagents switch
// saved per project and workflow, the pointer to this console's directory,
// and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set([
"looks.json",
"workspaces.json",
"subagents.json",
"console-dir",
"update-check.json",
]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -1150,19 +1142,6 @@ const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
// state keeps its text. Blocks left out of the patch stay as they are.
function mergeDocs(current, patchList) {
// A doc's version only moves forward. One going back is a stale or copied
// payload (last phase's progress script, say), and the page would quietly
// show the old content under the new run's name.
for (const entry of patchList) {
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
const prev = (current || []).find((d) => d && d.id === entry.id);
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
throw new Error(
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
"Versions only go up: bump it, and check the payload is the current one."
);
}
}
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
for (const entry of patchList) {
if (!Array.isArray(entry.blocks)) continue;
@@ -1205,13 +1184,6 @@ export function applyPatch(state, patch) {
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
break;
case "helpers":
// The agent's report of its helpers, for the page's Subagents tab.
// Only `post` writes it; the server's /submit never touches it.
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
break;
case "docs":
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
next.docs = mergeDocs(next.docs, v);
@@ -1506,20 +1478,6 @@ export function validate(state) {
JSON.stringify(state.menu || {});
problems.push(...proseProblems(prose));
// The agent's report of its helpers: the shape the page draws from
// (subagents.js), then the same prose scan as everything else it writes.
if (state.helpers != null) {
problems.push(...checkHelpers(state.helpers));
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
if (!isPlainObject(helper)) continue;
for (const field of ["title", "ask", "result"]) {
if (typeof helper[field] === "string") {
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
}
}
}
}
return problems;
}
@@ -1549,8 +1507,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
* A resume that passes through the dashboard (a finished skill going back to
* it, or a launch from its menu) is a new skill taking the page over, so it
* starts from a blank page: the last skill's questions, sections, docs,
* helpers, headline and ending are its record on disk, not the next skill's
* opening.
* headline and ending are its record on disk, not the next skill's opening.
* Only the session's identity carries across. `workspace.json`,
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
* and the meter outlive every hop.
@@ -1577,8 +1534,6 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
// workspace.json the server. Folders, version, change log, missing, remote.
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
export const CHAT_FILE = "chat.ndjson";
export const CHAT_CURSOR_FILE = "chat-cursor.json";
export const WORKSPACE_FILE = "workspace.json";
@@ -2034,98 +1989,6 @@ export function pendingWorkspaceChanges(dir) {
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.
*
@@ -208,26 +208,6 @@ body {
.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); }
/* 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; }
/* The session meter: a ring that fills with the points and a few words, in
@@ -1450,30 +1430,6 @@ h1 {
.pill.done { background: var(--ok-soft); color: var(--ok); }
.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 */
.answered {
@@ -2015,8 +1971,6 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
cursor: pointer;
}
.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. */
.where-alert {
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
@@ -103,15 +103,6 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
import { RED_BANNER } from "./meter.js";
import { applyMention, matchNames, mentionAt } from "./mentions.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);
@@ -539,9 +530,6 @@ 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 chatSending = false;
let chatResetting = false;
@@ -892,8 +880,6 @@ function adopt(body) {
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();
if (gone) {
gone = false;
@@ -1315,7 +1301,6 @@ function render() {
renderChrome();
renderStatus();
renderBriefButton();
renderSubagentsButton();
renderStopButton();
renderHomeButton();
tabAdded = renderViews();
@@ -1581,7 +1566,7 @@ function renderChrome() {
renderMeter();
$("title").textContent = S.title || "Session";
$("badge").textContent = workflowLabel(S.workflow);
renderTabTitle();
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
const h = S.headline || {};
// On a finished session an open item is frozen: the send on it counts as
@@ -1850,69 +1835,6 @@ function renderBriefButton() {
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() {
const nav = $("views");
nav.replaceChildren();
@@ -1928,14 +1850,6 @@ function renderViews() {
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
else if (view === "overview") view = "questions";
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.
// The ring left of "Ask" shows exactly when the conversation's own ring does:
// a question the agent picked up and has not answered yet.
@@ -2216,7 +2130,6 @@ function paintMain(main) {
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
if (view === "overview") return renderOverview(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 top of the rail. The hand-off lives here alone now, rather than
@@ -4861,42 +4774,6 @@ function renderOverview(main) {
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 */
// The frame's chat block, with `offline` worked out now rather than when the
@@ -6079,30 +5956,10 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
// 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
// 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() {
const b = $("footer-where");
const folders = workspaceFolders();
const path = S.worktree || "";
renderTabTitle();
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
const labels = folders.length
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
@@ -6115,16 +5972,7 @@ function renderWhere() {
let label = labels[0];
for (const text of labels) {
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) {
const dot = el("span", "where-alert");
dot.setAttribute("aria-hidden", "true");
@@ -7349,7 +7197,6 @@ function lightDismiss(dlg) {
});
}
lightDismiss($("looks-modal"));
lightDismiss($("subagents-modal"));
lightDismiss($("help-modal"));
lightDismiss($("workspace-modal"));
lightDismiss($("welcome-modal"));
@@ -7652,13 +7499,6 @@ $("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("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-go").addEventListener("click", sendBrief);
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("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("subagents", "Helpers (subagents)", false),
tab("ask", "Ask a quick question", false),
tab("finishing", "Stopping and finishing", false),
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 (workspace) return "workspace";
if (v === "ask") return "ask";
if (v === "subagents") return "subagents";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v.startsWith("doc:")) return "docs";
@@ -21,7 +21,6 @@
<link rel="modulepreload" href="/starters.js" />
<link rel="modulepreload" href="/workspace.js" />
<link rel="modulepreload" href="/meter.js" />
<link rel="modulepreload" href="/subagents.js" />
<link rel="modulepreload" href="/mentions.js" />
<link rel="modulepreload" href="/favicon.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>
Write a brief
</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 class="views-group">
<span class="views-arrow" aria-hidden="true">
@@ -593,13 +580,6 @@
<rect x="3" y="9" width="18" height="6" rx="3" />
<path d="M6 12h7" />
</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">
<path d="M4 5h16v11H10l-4 4v-4H4z" />
<path d="M8 9.5h8M8 12.5h5" />
@@ -1497,61 +1477,7 @@
</p>
</section>
<!-- Tab 12: Helpers (subagents) -->
<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 -->
<!-- Tab 12: Ask a quick question -->
<section class="help-panel" data-tab="ask">
<h3>Ask a quick question</h3>
<p class="help-lead">
@@ -1642,7 +1568,7 @@
</p>
</section>
<!-- Tab 14: Stopping and finishing -->
<!-- Tab 13: Stopping and finishing -->
<section class="help-panel" data-tab="finishing">
<h3>Stopping and finishing</h3>
<p class="help-lead">
@@ -1724,7 +1650,7 @@
</p>
</section>
<!-- Tab 15: When something looks stuck -->
<!-- Tab 14: When something looks stuck -->
<section class="help-panel" data-tab="stuck">
<h3>When something looks stuck</h3>
<p class="help-lead">
@@ -1846,7 +1772,7 @@
</div>
</section>
<!-- Tab 16: Keyboard and preferences -->
<!-- Tab 15: Keyboard and preferences -->
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
@@ -1962,7 +1888,7 @@
</ul>
</section>
<!-- Tab 17: Privacy and where things are saved -->
<!-- Tab 16: Privacy and where things are saved -->
<section class="help-panel" data-tab="privacy">
<h3>Privacy and where things are saved</h3>
<p class="help-lead">
@@ -1999,11 +1925,7 @@
</li>
<li>
your role, theme, colors, card width and sounds, in
<code>looks.json</code>;
</li>
<li>
your Subagents switch for each project and skill, in
<code>subagents.json</code>.
<code>looks.json</code>.
</li>
</ul>
<p>
@@ -2117,46 +2039,6 @@
</div>
</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
context. The list is drawn by app.js from the frame's `workspace`;
every change goes through the server's /workspace routes. -->
@@ -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,7 +25,6 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
SUBAGENTS_SETTING_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
@@ -39,7 +38,6 @@ import {
fileStamp,
handleFile,
initialWorkspace,
latestOpenCaps,
nowIso,
parseArgs,
pendingChatCount,
@@ -48,25 +46,20 @@ import {
readJson,
readLedger,
readOverview,
readSubagentSetting,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
saveSubagentStoreEntry,
specKey,
subagentStoreEntry,
typedCount,
withStateLock,
writeJsonAtomic,
writeSubagentSetting,
writeWorkspace,
} from "./lib.mjs";
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 { 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 { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
@@ -219,7 +212,6 @@ const SERVABLE = new Set([
"starters.js",
"workspace.js",
"meter.js",
"subagents.js",
"mentions.js",
"favicon.js",
"start-stop.mp3",
@@ -609,48 +601,6 @@ function ensureConversation(state) {
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.
// `have` names that exact view, for the page to hand back when it opens its
// stream (see /events).
@@ -665,33 +615,20 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
subagents: subagentsView(state),
...(updateInfo ? { update: updateInfo } : {}),
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() {
const { pending, stop } = resultFlags();
chatEntries();
chatPickedUp();
workspaceNow();
ledgerEntries();
subagentSettingNow();
openCapsNow();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -1235,39 +1172,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.
if (pathname === "/models" && req.method === "GET") {
const saved = readJson(USER_MODELS_FILE, null) || {};
@@ -1496,9 +1400,6 @@ const server = http.createServer((req, res) => {
try {
ensureConversation(written.state);
} catch {}
try {
syncSubagentSetting(written.state);
} catch {}
}
}
// Name the items that went. A page with OTHER answers staged should drop
@@ -1825,9 +1726,6 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
syncSubagentSetting(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
@@ -2002,9 +1900,6 @@ function onListening(port) {
try {
bootWorkspace();
} catch {}
try {
syncSubagentSetting(readState());
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -39,10 +39,10 @@ Three levels -- auto-detected, always respect explicit user override:
| Scope | Trigger | Reviews |
|-------|---------|---------|
| **Focused** | User names files/functions, or conversation work detected | Specified files only |
| **Branch** | "review my changes", or picked when asked | Branch changes vs main |
| **Branch** | "review my changes" or no context available | Branch changes vs main |
| **Full** | "full review" or names a subsystem | Entire codebase/subsystem |
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Scope already decided by a host workflow (a build's review, `building.md`) = use it. 4) Standalone with nothing named = scan, then ask (Step 1). Never default to `branch` silently. Ambiguous? Ask.
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Fallback = `branch`. Ambiguous? Ask.
**Thoroughness:** Scope controls WHAT is reviewed, not HOW DEEPLY. Every review is thorough.
@@ -52,7 +52,7 @@ Three levels -- auto-detected, always respect explicit user override:
## Process
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, scan and use `ask_user_question` (Step 1) — never guess.
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, use `ask_user_question` — never guess.
**Reference files:** Companion files loaded via Read directives. Fallback rules inline if unavailable.
@@ -62,8 +62,7 @@ Three levels -- auto-detected, always respect explicit user override:
1. **User prompt** — use it.
2. **Conversation context** — recent work? Those artifacts. Scope: `focused`.
3. **Standalone, nothing named** — do not assume a target. Do a quick scan (no file reading): `review-scope.mjs`, `specs.mjs list`, recent commits. Then ask what to review (`ask_user_question`; a `choice` on the console, scope questions up front), offering only options the scan supports, each with its size: the branch's changes vs base (files, ~lines, `commits`), uncommitted changes only (when any), a spec/plan under `specs/` (when any), a named subsystem or full codebase, or specific files/folders (free text via Other). Recommend the likeliest first. Nothing found (`empty: true`, no specs)? Ask for files or a subsystem. Use the answer as the scope, then continue.
4. **Scan details** — `review-scope.mjs` compares the branch with its base (`main`, else `master`; `--base` overrides; `base` says which it used) and adds staged, unstaged and untracked changes: `files` (status, lines), `counts`, `commits`, `mix`, `batchByRisk`. `empty: true`? Ask user. Exit 3 `no-base` (no `main` or `master`, or no such `--base`)? Rerun with `--base <trunk>`, asking the user which branch is the trunk if unclear. Exit 3 `not-a-repo`? Ask user which files to review.
3. **Git fallback** — run `review-scope.mjs`. It compares the branch with its base (`main`, else `master`; `--base` overrides; `base` says which it used) and adds staged, unstaged and untracked changes: `files` (status, lines), `counts`, `commits`, `mix`, `batchByRisk`. `empty: true`? Ask user. Exit 3 `no-base` (no `main` or `master`, or no such `--base`)? Rerun with `--base <trunk>`, asking the user which branch is the trunk if unclear. Exit 3 `not-a-repo`? Ask user which files to review.
**Classify review type** from context (auto-detect; use `ask_user_question` only if ambiguous):
@@ -57,7 +57,7 @@ Run against EVERY finding. If any question raises doubt, re-investigate or drop.
**Finding survives (real bug):** Reviewer finds `processItems()` at line 47 accesses `items[0].id` with no empty-array check. Re-reads source — confirmed no guard. Traces callers — `orchestrator.js:82` can pass empty array. Adversarial check passes (correctness issue, additive fix). Presented at High.
**Finding dropped (pcweb-jira false positive):** Reviewer recommends removing `jira-api-catalog.md` from consumer loading to "reduce context." Adversarial check: "Does my fix remove something the system depends on?" YES — agents Read these files at runtime to construct valid API calls. Four of five checks fail. Dropped.
**Finding dropped (jira skill false positive):** Reviewer recommends removing `jira-api-catalog.md` from consumer loading to "reduce context." Adversarial check: "Does my fix remove something the system depends on?" YES — agents Read these files at runtime to construct valid API calls. Four of five checks fail. Dropped.
**Finding dropped (false consolidation):** Reviewer flags per-platform config files as "duplicates." Adversarial check: "Am I optimizing for the wrong metric?" YES — platforms have distinct values and will diverge further. Separation is a design choice. Dropped.
@@ -64,13 +64,6 @@ progress bar is the first thing someone watching a build looks at. The session
meter counts the build's tasks from `cleared` as it rises, so keep it current,
and start every phase (a second one in the same run too) at `"cleared": 0`.
`"version": 1` is for the first phase of a session only. A doc's version
never goes back (console.md → House rules, rule 9), so a later phase in the
same session reposts `phase` and `phasefile` at one more than the version the
page holds, with the new phase's title and content. The same goes for
`report` at sign-off and `review` in a mid-session review: version 1 the
first time, then up from wherever the page has it.
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
the person can read the prerequisites and task specs while you build. Re-post
it whenever the file changes, which is every task: the checkbox write that
@@ -118,12 +111,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
holds anything the person sends until you next look.
A build may receive a `Subagents:` standing instruction, on `open` output or a
`chat` check between tasks. Follow console.md → Standing instructions for
handing independent tasks to helpers and reporting them as `helpers`. Keep the
per-task progress posts, the checkbox writes, the chat checks and the sign-off
with you.
### Quick questions between tasks
The person can ask a Quick question on the Ask tab at any point in a build
@@ -208,8 +195,7 @@ only ever be offered once nothing could come of it:
`reply` carries `Approve this phase: approved`, which is the terminal's
`approved`. If the note that came with an approval asks for a change, treat it
as "describe any issues": do the change first and ask again. `changes` means
exactly what it says: address it, bump the report's version (a later phase's
report starts above the last one's, too), and reopen the
exactly what it says: address it, bump the report's version, and reopen the
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
person asking for the code review before they approve anything — see "The
review, mid-session" below.
@@ -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 |
| --- | --- | --- |
| `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. |
| `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. |
@@ -647,84 +647,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)
A `dashboard` session is not a conversation: the page draws a menu of every
@@ -841,10 +763,7 @@ commands follow the pipeline: the sign-off's is
### Review (`review`)
Scope questions up front — run standalone with nothing named, the first is
a `choice`, "What should I review?", built from a quick scan (branch changes,
uncommitted changes, specs, files you name; each option with its size),
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
Scope questions up front, then the findings report as a doc (`id: "report"`),
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
id, carrying `"doc": "report"` so the card links straight to the findings.
Settle that item (`"status": "answered"` plus the `answer` they sent) in
@@ -878,8 +797,6 @@ 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
finish (Finishing → Nothing of yours may still be running); the finish
body then names what each one found.
- Report every research subagent as a helper, whatever the Subagents switch
says (Standing instructions → Reporting helpers).
- At every session end, post `finish` (headline, `body`, and Form A's command as
`command`) BEFORE `stop`. Someone who spent the session in the browser never
sees the Trail Footer, and without this their last screen promises a question
@@ -1229,16 +1146,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
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
and 5 cover `reason` and `hint`.
8. **`helpers` entries are well formed** (Standing instructions → Reporting
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
and a known `state` within their limits, plus at most one `alone` entry.
Rules 4 and 5 cover `title`, `ask` and `result`.
9. **A doc's `version` never goes back.** Sending a known doc a lower
`version` than the page holds is refused: it is almost always a stale or
copied payload. The same version again is fine, and a dashboard hop starts
every doc fresh. Anything else reusing a doc id in the same session (a
build's second phase, a second report or review) continues from the
version the page holds.
These are workflow rules you already follow. The server just makes them checkable.
@@ -1260,9 +1167,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
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
and update the count as each returns. Never write a `finish.body` that says
work "is running in the background" or "will finish on its own". Mark every
reported helper `done` or `failed` before the finish, so the Subagents tab
never ends on a row still running.
work "is running in the background" or "will finish on its own".
### 1. Post the finish
@@ -64,8 +64,6 @@ import {
readChat,
readJson,
readLedger,
readSubagentCursor,
readSubagentSetting,
readWorkspace,
reapHandles,
rememberedWorkspace,
@@ -73,7 +71,6 @@ import {
removeScratch,
removeSessions,
repoRoots,
resetSubagentCursor,
scanProject,
SESSION_MAX_AGE_MS,
sessionDir,
@@ -91,11 +88,9 @@ import {
workspaceForAgent,
writeCursor,
writeJsonAtomic,
writeSubagentCursor,
writeWorkspaceCursor,
} from "./lib.mjs";
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
import { blockFor, offered } from "./public/subagents.js";
import { changeLine } from "./public/workspace.js";
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
@@ -315,11 +310,7 @@ async function cmdOpen() {
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
// A new agent conversation has been told nothing yet (FR-6).
try {
resetSubagentCursor(dir);
} catch {}
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
trace("open: state written");
// Dashboard launches are recorded too (they score nothing), so the folder
@@ -346,18 +337,9 @@ async function cmdOpen() {
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
};
// A standing instruction the new agent is owed, as `subagents` and a
// `reply` holding only its lines; neither key when nothing is owed.
const subagentsOwed = () => {
awaitSubagentSync(dir, state.workflow);
const [out, cursor] = withSubagents(dir, { reply: "" });
return [out.subagents ? out : {}, cursor];
};
// Reuse a live server if one is already serving this session.
if (existing && (await reusable)) {
if (!args["no-open"]) openBrowser(existing.url);
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -367,11 +349,9 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(existing.url),
workspace,
...owed,
...swept,
...remoteWarning(),
});
advanceSubagents(dir, subCursor);
sweep();
return;
}
@@ -404,7 +384,6 @@ async function cmdOpen() {
const notes = [];
if (remote.note) notes.push(remote.note);
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -415,12 +394,10 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(handle.url),
workspace,
...owed,
...swept,
...(remote.remote ? { remote: remote.remote } : {}),
...(notes.length ? { note: notes.join(" ") } : {}),
});
advanceSubagents(dir, subCursor);
// After the print, never before it: the page and the link wait for nothing.
sweep();
}
@@ -797,7 +774,7 @@ function serverGone(sid) {
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
function deliverChat(dir, sid, entries, url) {
const [withWs, changes] = withWorkspace(dir, {
const [out, changes] = withWorkspace(dir, {
type: "chat",
at: nowIso(),
sid,
@@ -805,11 +782,9 @@ function deliverChat(dir, sid, entries, url) {
chat: entries,
reply: chatReplyLines(entries),
});
const [out, subCursor] = withSubagents(dir, withWs);
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
advanceCursor(dir, entries);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -831,52 +806,6 @@ function advanceWorkspace(dir, changes) {
} catch {}
}
// The server rewrites the session's setting for a new workflow only once its
// watcher sees the state `open` just wrote, so a launch or hop that read the
// file at once would find the old workflow's and owe the agent nothing until
// its next pickup. Give the server a moment to catch up instead, never
// writing the file ourselves (FR-7). A session with no setting file at all is
// an older server, which never writes one: a short look, not the full wait.
const SUBAGENT_SYNC_WAIT_MS = 1500;
const SUBAGENT_SYNC_MISSING_MS = 250;
function awaitSubagentSync(dir, workflow) {
if (!offered(workflow)) return;
const start = Date.now();
for (;;) {
const setting = readSubagentSetting(dir);
if (setting && setting.workflow === workflow) return;
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
if (Date.now() - start >= budget) return;
sleepSync(25);
}
}
// The Subagents switch the agent is owed, added to what it is about to read:
// the setting as `subagents`, and its lines last in `reply`, after card lines,
// Quick questions and Workspace lines (FR-9). Read from the session's own
// setting file only, which only the server writes (FR-7). A setting for
// another workflow is the server not having caught up with a hop yet: it
// rides on the next pickup instead.
function withSubagents(dir, out) {
const setting = readSubagentSetting(dir);
if (!setting) return [out, null];
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
if (setting.workflow !== workflow) return [out, null];
const block = blockFor(setting, readSubagentCursor(dir));
if (!block) return [out, null];
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
return [{ ...out, subagents: block.field, reply }, block.cursor];
}
// After the print, like advanceWorkspace(): a kill in between repeats the
// block at the next pickup, never loses it.
function advanceSubagents(dir, cursor) {
if (!cursor) return;
try {
writeSubagentCursor(dir, cursor);
} catch {}
}
// Print first, then this, exactly as consume() stamps a result: a kill in
// between can only hand the same chat over again, and collectChat() drops
// anything that already has a reply.
@@ -903,17 +832,15 @@ async function cmdChat() {
}
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
const changes = pendingWorkspaceChanges(dir);
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
if (!entries.length && !changes.length && !subCursor) {
if (!entries.length && !changes.length) {
print({ chat: [] });
process.exitCode = 10;
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);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -938,8 +865,7 @@ function consume(dir, resultPath, result, url, chat = []) {
// never on result.json itself.
const withChat = { ...collected, chat };
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
const [withWs, changes] = withWorkspace(dir, withChat);
const [out, subCursor] = withSubagents(dir, withWs);
const [out, changes] = withWorkspace(dir, withChat);
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
try {
writeJsonAtomic(resultPath, collected);
@@ -948,7 +874,6 @@ function consume(dir, resultPath, result, url, chat = []) {
ledgerAnswers(dir, result);
advanceCursor(dir, chat);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = result.type === "cancel" ? 30 : 0;
}
@@ -1061,18 +986,12 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
May also print subagents: { state, revision, max, instruction } and
a reply holding only its "Subagents: ..." lines, when a standing
instruction (the page's Subagents switch) is owed to you.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
carry run: { event, id, tasks? } (session meter points) and folderIssue:
{ name, reason, hint? } (a workspace folder you could not read);
both go to the ledger, never into the state. A patch may also
carry helpers: [{ id, title, ask, state, result? }] or one
{ id: "alone", alone: true }, merged by id, for the Subagents tab
(see console.md → Standing instructions).
both go to the ledger, never into the state.
wait --session <sid> [--seconds <N>]
A bounded wait slice, sized below your shell timeout. Exit 0 = the
result is on stdout, 10 = still waiting ("Waiting on your answer
@@ -1083,14 +1002,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
"workspace" (changes since you last heard, each once, with a
"Workspace: ..." line in reply); exit 10 counts them as
pendingWorkspace, and a change alone never ends a slice.
Exit 0 may also carry "subagents" (a console setting, not typed
by the person, with its "Subagents: ..." lines last in reply); a
setting change alone never ends a slice either.
chat --session <sid>
Collect Quick questions, workspace changes and a Subagents
setting change now, never waiting, never touching card sends.
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
10 = none, 20 = server gone.
Collect Quick questions and workspace changes now, never waiting,
never touching card sends. Exit 0 = { chat, workspace, reply,
terminalLine }, 10 = none, 20 = server gone.
terminalLine is "→ Look at the web console: <url>": end your terminal
messages with it during a console session.
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
@@ -25,7 +25,6 @@ import { fileURLToPath } from "node:url";
import { CHAT_LIMIT } from "./public/chat.js";
import { DOC_TYPES } from "./public/answers.js";
import { defaultName } from "./public/workspace.js";
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const PUBLIC_DIR = path.join(HERE, "public");
@@ -492,16 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, the Subagents switch
// saved per project and workflow, the pointer to this console's directory,
// and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set([
"looks.json",
"workspaces.json",
"subagents.json",
"console-dir",
"update-check.json",
]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -1150,19 +1142,6 @@ const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
// state keeps its text. Blocks left out of the patch stay as they are.
function mergeDocs(current, patchList) {
// A doc's version only moves forward. One going back is a stale or copied
// payload (last phase's progress script, say), and the page would quietly
// show the old content under the new run's name.
for (const entry of patchList) {
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
const prev = (current || []).find((d) => d && d.id === entry.id);
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
throw new Error(
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
"Versions only go up: bump it, and check the payload is the current one."
);
}
}
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
for (const entry of patchList) {
if (!Array.isArray(entry.blocks)) continue;
@@ -1205,13 +1184,6 @@ export function applyPatch(state, patch) {
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
break;
case "helpers":
// The agent's report of its helpers, for the page's Subagents tab.
// Only `post` writes it; the server's /submit never touches it.
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
break;
case "docs":
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
next.docs = mergeDocs(next.docs, v);
@@ -1506,20 +1478,6 @@ export function validate(state) {
JSON.stringify(state.menu || {});
problems.push(...proseProblems(prose));
// The agent's report of its helpers: the shape the page draws from
// (subagents.js), then the same prose scan as everything else it writes.
if (state.helpers != null) {
problems.push(...checkHelpers(state.helpers));
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
if (!isPlainObject(helper)) continue;
for (const field of ["title", "ask", "result"]) {
if (typeof helper[field] === "string") {
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
}
}
}
}
return problems;
}
@@ -1549,8 +1507,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
* A resume that passes through the dashboard (a finished skill going back to
* it, or a launch from its menu) is a new skill taking the page over, so it
* starts from a blank page: the last skill's questions, sections, docs,
* helpers, headline and ending are its record on disk, not the next skill's
* opening.
* headline and ending are its record on disk, not the next skill's opening.
* Only the session's identity carries across. `workspace.json`,
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
* and the meter outlive every hop.
@@ -1577,8 +1534,6 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
// workspace.json the server. Folders, version, change log, missing, remote.
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
export const CHAT_FILE = "chat.ndjson";
export const CHAT_CURSOR_FILE = "chat-cursor.json";
export const WORKSPACE_FILE = "workspace.json";
@@ -2034,98 +1989,6 @@ export function pendingWorkspaceChanges(dir) {
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.
*
@@ -208,26 +208,6 @@ body {
.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); }
/* 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; }
/* The session meter: a ring that fills with the points and a few words, in
@@ -1450,30 +1430,6 @@ h1 {
.pill.done { background: var(--ok-soft); color: var(--ok); }
.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 */
.answered {
@@ -2015,8 +1971,6 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
cursor: pointer;
}
.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. */
.where-alert {
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
@@ -103,15 +103,6 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
import { RED_BANNER } from "./meter.js";
import { applyMention, matchNames, mentionAt } from "./mentions.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);
@@ -539,9 +530,6 @@ 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 chatSending = false;
let chatResetting = false;
@@ -892,8 +880,6 @@ function adopt(body) {
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();
if (gone) {
gone = false;
@@ -1315,7 +1301,6 @@ function render() {
renderChrome();
renderStatus();
renderBriefButton();
renderSubagentsButton();
renderStopButton();
renderHomeButton();
tabAdded = renderViews();
@@ -1581,7 +1566,7 @@ function renderChrome() {
renderMeter();
$("title").textContent = S.title || "Session";
$("badge").textContent = workflowLabel(S.workflow);
renderTabTitle();
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
const h = S.headline || {};
// On a finished session an open item is frozen: the send on it counts as
@@ -1850,69 +1835,6 @@ function renderBriefButton() {
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() {
const nav = $("views");
nav.replaceChildren();
@@ -1928,14 +1850,6 @@ function renderViews() {
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
else if (view === "overview") view = "questions";
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.
// The ring left of "Ask" shows exactly when the conversation's own ring does:
// a question the agent picked up and has not answered yet.
@@ -2216,7 +2130,6 @@ function paintMain(main) {
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
if (view === "overview") return renderOverview(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 top of the rail. The hand-off lives here alone now, rather than
@@ -4861,42 +4774,6 @@ function renderOverview(main) {
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 */
// The frame's chat block, with `offline` worked out now rather than when the
@@ -6079,30 +5956,10 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
// 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
// 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() {
const b = $("footer-where");
const folders = workspaceFolders();
const path = S.worktree || "";
renderTabTitle();
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
const labels = folders.length
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
@@ -6115,16 +5972,7 @@ function renderWhere() {
let label = labels[0];
for (const text of labels) {
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) {
const dot = el("span", "where-alert");
dot.setAttribute("aria-hidden", "true");
@@ -7349,7 +7197,6 @@ function lightDismiss(dlg) {
});
}
lightDismiss($("looks-modal"));
lightDismiss($("subagents-modal"));
lightDismiss($("help-modal"));
lightDismiss($("workspace-modal"));
lightDismiss($("welcome-modal"));
@@ -7652,13 +7499,6 @@ $("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("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-go").addEventListener("click", sendBrief);
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("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("subagents", "Helpers (subagents)", false),
tab("ask", "Ask a quick question", false),
tab("finishing", "Stopping and finishing", false),
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 (workspace) return "workspace";
if (v === "ask") return "ask";
if (v === "subagents") return "subagents";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v.startsWith("doc:")) return "docs";
@@ -21,7 +21,6 @@
<link rel="modulepreload" href="/starters.js" />
<link rel="modulepreload" href="/workspace.js" />
<link rel="modulepreload" href="/meter.js" />
<link rel="modulepreload" href="/subagents.js" />
<link rel="modulepreload" href="/mentions.js" />
<link rel="modulepreload" href="/favicon.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>
Write a brief
</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 class="views-group">
<span class="views-arrow" aria-hidden="true">
@@ -593,13 +580,6 @@
<rect x="3" y="9" width="18" height="6" rx="3" />
<path d="M6 12h7" />
</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">
<path d="M4 5h16v11H10l-4 4v-4H4z" />
<path d="M8 9.5h8M8 12.5h5" />
@@ -1497,61 +1477,7 @@
</p>
</section>
<!-- Tab 12: Helpers (subagents) -->
<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 -->
<!-- Tab 12: Ask a quick question -->
<section class="help-panel" data-tab="ask">
<h3>Ask a quick question</h3>
<p class="help-lead">
@@ -1642,7 +1568,7 @@
</p>
</section>
<!-- Tab 14: Stopping and finishing -->
<!-- Tab 13: Stopping and finishing -->
<section class="help-panel" data-tab="finishing">
<h3>Stopping and finishing</h3>
<p class="help-lead">
@@ -1724,7 +1650,7 @@
</p>
</section>
<!-- Tab 15: When something looks stuck -->
<!-- Tab 14: When something looks stuck -->
<section class="help-panel" data-tab="stuck">
<h3>When something looks stuck</h3>
<p class="help-lead">
@@ -1846,7 +1772,7 @@
</div>
</section>
<!-- Tab 16: Keyboard and preferences -->
<!-- Tab 15: Keyboard and preferences -->
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
@@ -1962,7 +1888,7 @@
</ul>
</section>
<!-- Tab 17: Privacy and where things are saved -->
<!-- Tab 16: Privacy and where things are saved -->
<section class="help-panel" data-tab="privacy">
<h3>Privacy and where things are saved</h3>
<p class="help-lead">
@@ -1999,11 +1925,7 @@
</li>
<li>
your role, theme, colors, card width and sounds, in
<code>looks.json</code>;
</li>
<li>
your Subagents switch for each project and skill, in
<code>subagents.json</code>.
<code>looks.json</code>.
</li>
</ul>
<p>
@@ -2117,46 +2039,6 @@
</div>
</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
context. The list is drawn by app.js from the frame's `workspace`;
every change goes through the server's /workspace routes. -->
@@ -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,7 +25,6 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
SUBAGENTS_SETTING_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
@@ -39,7 +38,6 @@ import {
fileStamp,
handleFile,
initialWorkspace,
latestOpenCaps,
nowIso,
parseArgs,
pendingChatCount,
@@ -48,25 +46,20 @@ import {
readJson,
readLedger,
readOverview,
readSubagentSetting,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
saveSubagentStoreEntry,
specKey,
subagentStoreEntry,
typedCount,
withStateLock,
writeJsonAtomic,
writeSubagentSetting,
writeWorkspace,
} from "./lib.mjs";
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 { 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 { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
@@ -219,7 +212,6 @@ const SERVABLE = new Set([
"starters.js",
"workspace.js",
"meter.js",
"subagents.js",
"mentions.js",
"favicon.js",
"start-stop.mp3",
@@ -609,48 +601,6 @@ function ensureConversation(state) {
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.
// `have` names that exact view, for the page to hand back when it opens its
// stream (see /events).
@@ -665,33 +615,20 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
subagents: subagentsView(state),
...(updateInfo ? { update: updateInfo } : {}),
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() {
const { pending, stop } = resultFlags();
chatEntries();
chatPickedUp();
workspaceNow();
ledgerEntries();
subagentSettingNow();
openCapsNow();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -1235,39 +1172,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.
if (pathname === "/models" && req.method === "GET") {
const saved = readJson(USER_MODELS_FILE, null) || {};
@@ -1496,9 +1400,6 @@ const server = http.createServer((req, res) => {
try {
ensureConversation(written.state);
} catch {}
try {
syncSubagentSetting(written.state);
} catch {}
}
}
// Name the items that went. A page with OTHER answers staged should drop
@@ -1825,9 +1726,6 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
syncSubagentSetting(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
@@ -2002,9 +1900,6 @@ function onListening(port) {
try {
bootWorkspace();
} catch {}
try {
syncSubagentSetting(readState());
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -10,7 +10,7 @@
//
// and derives the ticket from a branch named <prefix>/<TICKET-ID>-description,
// where the ticket is an uppercase project key, a hyphen and an integer
// (PCWEB-10968). This script reads the branch, extracts the ticket and prints
// (ABC-10968). This script reads the branch, extracts the ticket and prints
// the exact command, so no prompt re-implements the rule by eye.
import { execFileSync } from "node:child_process";
@@ -96,7 +96,7 @@ run(USAGE, async (argv) => {
let branch = null;
let ticket = args.ticket ? args.ticket.trim() : null;
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like PCWEB-10968.");
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like ABC-10968.");
if (!ticket) {
branch = currentBranch();
ticket = ticketFromBranch(branch);
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -39,10 +39,10 @@ Three levels -- auto-detected, always respect explicit user override:
| Scope | Trigger | Reviews |
|-------|---------|---------|
| **Focused** | User names files/functions, or conversation work detected | Specified files only |
| **Branch** | "review my changes", or picked when asked | Branch changes vs main |
| **Branch** | "review my changes" or no context available | Branch changes vs main |
| **Full** | "full review" or names a subsystem | Entire codebase/subsystem |
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Scope already decided by a host workflow (a build's review, `building.md`) = use it. 4) Standalone with nothing named = scan, then ask (Step 1). Never default to `branch` silently. Ambiguous? Ask.
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Fallback = `branch`. Ambiguous? Ask.
**Thoroughness:** Scope controls WHAT is reviewed, not HOW DEEPLY. Every review is thorough.
@@ -52,7 +52,7 @@ Three levels -- auto-detected, always respect explicit user override:
## Process
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, scan and use `ask_user_question` (Step 1) — never guess.
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, use `ask_user_question` — never guess.
**Reference files:** Companion files loaded via Read directives. Fallback rules inline if unavailable.
@@ -62,8 +62,7 @@ Three levels -- auto-detected, always respect explicit user override:
1. **User prompt** — use it.
2. **Conversation context** — recent work? Those artifacts. Scope: `focused`.
3. **Standalone, nothing named** — do not assume a target. Do a quick scan (no file reading): `review-scope.mjs`, `specs.mjs list`, recent commits. Then ask what to review (`ask_user_question`; a `choice` on the console, scope questions up front), offering only options the scan supports, each with its size: the branch's changes vs base (files, ~lines, `commits`), uncommitted changes only (when any), a spec/plan under `specs/` (when any), a named subsystem or full codebase, or specific files/folders (free text via Other). Recommend the likeliest first. Nothing found (`empty: true`, no specs)? Ask for files or a subsystem. Use the answer as the scope, then continue.
4. **Scan details** — `review-scope.mjs` compares the branch with its base (`main`, else `master`; `--base` overrides; `base` says which it used) and adds staged, unstaged and untracked changes: `files` (status, lines), `counts`, `commits`, `mix`, `batchByRisk`. `empty: true`? Ask user. Exit 3 `no-base` (no `main` or `master`, or no such `--base`)? Rerun with `--base <trunk>`, asking the user which branch is the trunk if unclear. Exit 3 `not-a-repo`? Ask user which files to review.
3. **Git fallback** — run `review-scope.mjs`. It compares the branch with its base (`main`, else `master`; `--base` overrides; `base` says which it used) and adds staged, unstaged and untracked changes: `files` (status, lines), `counts`, `commits`, `mix`, `batchByRisk`. `empty: true`? Ask user. Exit 3 `no-base` (no `main` or `master`, or no such `--base`)? Rerun with `--base <trunk>`, asking the user which branch is the trunk if unclear. Exit 3 `not-a-repo`? Ask user which files to review.
**Classify review type** from context (auto-detect; use `ask_user_question` only if ambiguous):
@@ -57,7 +57,7 @@ Run against EVERY finding. If any question raises doubt, re-investigate or drop.
**Finding survives (real bug):** Reviewer finds `processItems()` at line 47 accesses `items[0].id` with no empty-array check. Re-reads source — confirmed no guard. Traces callers — `orchestrator.js:82` can pass empty array. Adversarial check passes (correctness issue, additive fix). Presented at High.
**Finding dropped (pcweb-jira false positive):** Reviewer recommends removing `jira-api-catalog.md` from consumer loading to "reduce context." Adversarial check: "Does my fix remove something the system depends on?" YES — agents Read these files at runtime to construct valid API calls. Four of five checks fail. Dropped.
**Finding dropped (jira skill false positive):** Reviewer recommends removing `jira-api-catalog.md` from consumer loading to "reduce context." Adversarial check: "Does my fix remove something the system depends on?" YES — agents Read these files at runtime to construct valid API calls. Four of five checks fail. Dropped.
**Finding dropped (false consolidation):** Reviewer flags per-platform config files as "duplicates." Adversarial check: "Am I optimizing for the wrong metric?" YES — platforms have distinct values and will diverge further. Separation is a design choice. Dropped.
@@ -64,13 +64,6 @@ progress bar is the first thing someone watching a build looks at. The session
meter counts the build's tasks from `cleared` as it rises, so keep it current,
and start every phase (a second one in the same run too) at `"cleared": 0`.
`"version": 1` is for the first phase of a session only. A doc's version
never goes back (console.md → House rules, rule 9), so a later phase in the
same session reposts `phase` and `phasefile` at one more than the version the
page holds, with the new phase's title and content. The same goes for
`report` at sign-off and `review` in a mid-session review: version 1 the
first time, then up from wherever the page has it.
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
the person can read the prerequisites and task specs while you build. Re-post
it whenever the file changes, which is every task: the checkbox write that
@@ -118,12 +111,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
holds anything the person sends until you next look.
A build may receive a `Subagents:` standing instruction, on `open` output or a
`chat` check between tasks. Follow console.md → Standing instructions for
handing independent tasks to helpers and reporting them as `helpers`. Keep the
per-task progress posts, the checkbox writes, the chat checks and the sign-off
with you.
### Quick questions between tasks
The person can ask a Quick question on the Ask tab at any point in a build
@@ -208,8 +195,7 @@ only ever be offered once nothing could come of it:
`reply` carries `Approve this phase: approved`, which is the terminal's
`approved`. If the note that came with an approval asks for a change, treat it
as "describe any issues": do the change first and ask again. `changes` means
exactly what it says: address it, bump the report's version (a later phase's
report starts above the last one's, too), and reopen the
exactly what it says: address it, bump the report's version, and reopen the
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
person asking for the code review before they approve anything — see "The
review, mid-session" below.
@@ -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 |
| --- | --- | --- |
| `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. |
| `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. |
@@ -647,84 +647,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)
A `dashboard` session is not a conversation: the page draws a menu of every
@@ -841,10 +763,7 @@ commands follow the pipeline: the sign-off's is
### Review (`review`)
Scope questions up front — run standalone with nothing named, the first is
a `choice`, "What should I review?", built from a quick scan (branch changes,
uncommitted changes, specs, files you name; each option with its size),
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
Scope questions up front, then the findings report as a doc (`id: "report"`),
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
id, carrying `"doc": "report"` so the card links straight to the findings.
Settle that item (`"status": "answered"` plus the `answer` they sent) in
@@ -878,8 +797,6 @@ 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
finish (Finishing → Nothing of yours may still be running); the finish
body then names what each one found.
- Report every research subagent as a helper, whatever the Subagents switch
says (Standing instructions → Reporting helpers).
- At every session end, post `finish` (headline, `body`, and Form A's command as
`command`) BEFORE `stop`. Someone who spent the session in the browser never
sees the Trail Footer, and without this their last screen promises a question
@@ -1229,16 +1146,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
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
and 5 cover `reason` and `hint`.
8. **`helpers` entries are well formed** (Standing instructions → Reporting
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
and a known `state` within their limits, plus at most one `alone` entry.
Rules 4 and 5 cover `title`, `ask` and `result`.
9. **A doc's `version` never goes back.** Sending a known doc a lower
`version` than the page holds is refused: it is almost always a stale or
copied payload. The same version again is fine, and a dashboard hop starts
every doc fresh. Anything else reusing a doc id in the same session (a
build's second phase, a second report or review) continues from the
version the page holds.
These are workflow rules you already follow. The server just makes them checkable.
@@ -1260,9 +1167,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
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
and update the count as each returns. Never write a `finish.body` that says
work "is running in the background" or "will finish on its own". Mark every
reported helper `done` or `failed` before the finish, so the Subagents tab
never ends on a row still running.
work "is running in the background" or "will finish on its own".
### 1. Post the finish
@@ -64,8 +64,6 @@ import {
readChat,
readJson,
readLedger,
readSubagentCursor,
readSubagentSetting,
readWorkspace,
reapHandles,
rememberedWorkspace,
@@ -73,7 +71,6 @@ import {
removeScratch,
removeSessions,
repoRoots,
resetSubagentCursor,
scanProject,
SESSION_MAX_AGE_MS,
sessionDir,
@@ -91,11 +88,9 @@ import {
workspaceForAgent,
writeCursor,
writeJsonAtomic,
writeSubagentCursor,
writeWorkspaceCursor,
} from "./lib.mjs";
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
import { blockFor, offered } from "./public/subagents.js";
import { changeLine } from "./public/workspace.js";
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
@@ -315,11 +310,7 @@ async function cmdOpen() {
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
// A new agent conversation has been told nothing yet (FR-6).
try {
resetSubagentCursor(dir);
} catch {}
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
trace("open: state written");
// Dashboard launches are recorded too (they score nothing), so the folder
@@ -346,18 +337,9 @@ async function cmdOpen() {
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
};
// A standing instruction the new agent is owed, as `subagents` and a
// `reply` holding only its lines; neither key when nothing is owed.
const subagentsOwed = () => {
awaitSubagentSync(dir, state.workflow);
const [out, cursor] = withSubagents(dir, { reply: "" });
return [out.subagents ? out : {}, cursor];
};
// Reuse a live server if one is already serving this session.
if (existing && (await reusable)) {
if (!args["no-open"]) openBrowser(existing.url);
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -367,11 +349,9 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(existing.url),
workspace,
...owed,
...swept,
...remoteWarning(),
});
advanceSubagents(dir, subCursor);
sweep();
return;
}
@@ -404,7 +384,6 @@ async function cmdOpen() {
const notes = [];
if (remote.note) notes.push(remote.note);
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -415,12 +394,10 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(handle.url),
workspace,
...owed,
...swept,
...(remote.remote ? { remote: remote.remote } : {}),
...(notes.length ? { note: notes.join(" ") } : {}),
});
advanceSubagents(dir, subCursor);
// After the print, never before it: the page and the link wait for nothing.
sweep();
}
@@ -797,7 +774,7 @@ function serverGone(sid) {
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
function deliverChat(dir, sid, entries, url) {
const [withWs, changes] = withWorkspace(dir, {
const [out, changes] = withWorkspace(dir, {
type: "chat",
at: nowIso(),
sid,
@@ -805,11 +782,9 @@ function deliverChat(dir, sid, entries, url) {
chat: entries,
reply: chatReplyLines(entries),
});
const [out, subCursor] = withSubagents(dir, withWs);
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
advanceCursor(dir, entries);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -831,52 +806,6 @@ function advanceWorkspace(dir, changes) {
} catch {}
}
// The server rewrites the session's setting for a new workflow only once its
// watcher sees the state `open` just wrote, so a launch or hop that read the
// file at once would find the old workflow's and owe the agent nothing until
// its next pickup. Give the server a moment to catch up instead, never
// writing the file ourselves (FR-7). A session with no setting file at all is
// an older server, which never writes one: a short look, not the full wait.
const SUBAGENT_SYNC_WAIT_MS = 1500;
const SUBAGENT_SYNC_MISSING_MS = 250;
function awaitSubagentSync(dir, workflow) {
if (!offered(workflow)) return;
const start = Date.now();
for (;;) {
const setting = readSubagentSetting(dir);
if (setting && setting.workflow === workflow) return;
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
if (Date.now() - start >= budget) return;
sleepSync(25);
}
}
// The Subagents switch the agent is owed, added to what it is about to read:
// the setting as `subagents`, and its lines last in `reply`, after card lines,
// Quick questions and Workspace lines (FR-9). Read from the session's own
// setting file only, which only the server writes (FR-7). A setting for
// another workflow is the server not having caught up with a hop yet: it
// rides on the next pickup instead.
function withSubagents(dir, out) {
const setting = readSubagentSetting(dir);
if (!setting) return [out, null];
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
if (setting.workflow !== workflow) return [out, null];
const block = blockFor(setting, readSubagentCursor(dir));
if (!block) return [out, null];
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
return [{ ...out, subagents: block.field, reply }, block.cursor];
}
// After the print, like advanceWorkspace(): a kill in between repeats the
// block at the next pickup, never loses it.
function advanceSubagents(dir, cursor) {
if (!cursor) return;
try {
writeSubagentCursor(dir, cursor);
} catch {}
}
// Print first, then this, exactly as consume() stamps a result: a kill in
// between can only hand the same chat over again, and collectChat() drops
// anything that already has a reply.
@@ -903,17 +832,15 @@ async function cmdChat() {
}
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
const changes = pendingWorkspaceChanges(dir);
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
if (!entries.length && !changes.length && !subCursor) {
if (!entries.length && !changes.length) {
print({ chat: [] });
process.exitCode = 10;
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);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -938,8 +865,7 @@ function consume(dir, resultPath, result, url, chat = []) {
// never on result.json itself.
const withChat = { ...collected, chat };
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
const [withWs, changes] = withWorkspace(dir, withChat);
const [out, subCursor] = withSubagents(dir, withWs);
const [out, changes] = withWorkspace(dir, withChat);
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
try {
writeJsonAtomic(resultPath, collected);
@@ -948,7 +874,6 @@ function consume(dir, resultPath, result, url, chat = []) {
ledgerAnswers(dir, result);
advanceCursor(dir, chat);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = result.type === "cancel" ? 30 : 0;
}
@@ -1061,18 +986,12 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
May also print subagents: { state, revision, max, instruction } and
a reply holding only its "Subagents: ..." lines, when a standing
instruction (the page's Subagents switch) is owed to you.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
carry run: { event, id, tasks? } (session meter points) and folderIssue:
{ name, reason, hint? } (a workspace folder you could not read);
both go to the ledger, never into the state. A patch may also
carry helpers: [{ id, title, ask, state, result? }] or one
{ id: "alone", alone: true }, merged by id, for the Subagents tab
(see console.md → Standing instructions).
both go to the ledger, never into the state.
wait --session <sid> [--seconds <N>]
A bounded wait slice, sized below your shell timeout. Exit 0 = the
result is on stdout, 10 = still waiting ("Waiting on your answer
@@ -1083,14 +1002,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
"workspace" (changes since you last heard, each once, with a
"Workspace: ..." line in reply); exit 10 counts them as
pendingWorkspace, and a change alone never ends a slice.
Exit 0 may also carry "subagents" (a console setting, not typed
by the person, with its "Subagents: ..." lines last in reply); a
setting change alone never ends a slice either.
chat --session <sid>
Collect Quick questions, workspace changes and a Subagents
setting change now, never waiting, never touching card sends.
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
10 = none, 20 = server gone.
Collect Quick questions and workspace changes now, never waiting,
never touching card sends. Exit 0 = { chat, workspace, reply,
terminalLine }, 10 = none, 20 = server gone.
terminalLine is "→ Look at the web console: <url>": end your terminal
messages with it during a console session.
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
@@ -25,7 +25,6 @@ import { fileURLToPath } from "node:url";
import { CHAT_LIMIT } from "./public/chat.js";
import { DOC_TYPES } from "./public/answers.js";
import { defaultName } from "./public/workspace.js";
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const PUBLIC_DIR = path.join(HERE, "public");
@@ -492,16 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, the Subagents switch
// saved per project and workflow, the pointer to this console's directory,
// and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set([
"looks.json",
"workspaces.json",
"subagents.json",
"console-dir",
"update-check.json",
]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -1150,19 +1142,6 @@ const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
// state keeps its text. Blocks left out of the patch stay as they are.
function mergeDocs(current, patchList) {
// A doc's version only moves forward. One going back is a stale or copied
// payload (last phase's progress script, say), and the page would quietly
// show the old content under the new run's name.
for (const entry of patchList) {
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
const prev = (current || []).find((d) => d && d.id === entry.id);
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
throw new Error(
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
"Versions only go up: bump it, and check the payload is the current one."
);
}
}
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
for (const entry of patchList) {
if (!Array.isArray(entry.blocks)) continue;
@@ -1205,13 +1184,6 @@ export function applyPatch(state, patch) {
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
break;
case "helpers":
// The agent's report of its helpers, for the page's Subagents tab.
// Only `post` writes it; the server's /submit never touches it.
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
break;
case "docs":
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
next.docs = mergeDocs(next.docs, v);
@@ -1506,20 +1478,6 @@ export function validate(state) {
JSON.stringify(state.menu || {});
problems.push(...proseProblems(prose));
// The agent's report of its helpers: the shape the page draws from
// (subagents.js), then the same prose scan as everything else it writes.
if (state.helpers != null) {
problems.push(...checkHelpers(state.helpers));
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
if (!isPlainObject(helper)) continue;
for (const field of ["title", "ask", "result"]) {
if (typeof helper[field] === "string") {
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
}
}
}
}
return problems;
}
@@ -1549,8 +1507,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
* A resume that passes through the dashboard (a finished skill going back to
* it, or a launch from its menu) is a new skill taking the page over, so it
* starts from a blank page: the last skill's questions, sections, docs,
* helpers, headline and ending are its record on disk, not the next skill's
* opening.
* headline and ending are its record on disk, not the next skill's opening.
* Only the session's identity carries across. `workspace.json`,
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
* and the meter outlive every hop.
@@ -1577,8 +1534,6 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
// workspace.json the server. Folders, version, change log, missing, remote.
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
export const CHAT_FILE = "chat.ndjson";
export const CHAT_CURSOR_FILE = "chat-cursor.json";
export const WORKSPACE_FILE = "workspace.json";
@@ -2034,98 +1989,6 @@ export function pendingWorkspaceChanges(dir) {
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.
*
@@ -208,26 +208,6 @@ body {
.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); }
/* 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; }
/* The session meter: a ring that fills with the points and a few words, in
@@ -1450,30 +1430,6 @@ h1 {
.pill.done { background: var(--ok-soft); color: var(--ok); }
.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 */
.answered {
@@ -2015,8 +1971,6 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
cursor: pointer;
}
.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. */
.where-alert {
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
@@ -103,15 +103,6 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
import { RED_BANNER } from "./meter.js";
import { applyMention, matchNames, mentionAt } from "./mentions.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);
@@ -539,9 +530,6 @@ 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 chatSending = false;
let chatResetting = false;
@@ -892,8 +880,6 @@ function adopt(body) {
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();
if (gone) {
gone = false;
@@ -1315,7 +1301,6 @@ function render() {
renderChrome();
renderStatus();
renderBriefButton();
renderSubagentsButton();
renderStopButton();
renderHomeButton();
tabAdded = renderViews();
@@ -1581,7 +1566,7 @@ function renderChrome() {
renderMeter();
$("title").textContent = S.title || "Session";
$("badge").textContent = workflowLabel(S.workflow);
renderTabTitle();
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
const h = S.headline || {};
// On a finished session an open item is frozen: the send on it counts as
@@ -1850,69 +1835,6 @@ function renderBriefButton() {
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() {
const nav = $("views");
nav.replaceChildren();
@@ -1928,14 +1850,6 @@ function renderViews() {
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
else if (view === "overview") view = "questions";
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.
// The ring left of "Ask" shows exactly when the conversation's own ring does:
// a question the agent picked up and has not answered yet.
@@ -2216,7 +2130,6 @@ function paintMain(main) {
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
if (view === "overview") return renderOverview(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 top of the rail. The hand-off lives here alone now, rather than
@@ -4861,42 +4774,6 @@ function renderOverview(main) {
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 */
// The frame's chat block, with `offline` worked out now rather than when the
@@ -6079,30 +5956,10 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
// 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
// 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() {
const b = $("footer-where");
const folders = workspaceFolders();
const path = S.worktree || "";
renderTabTitle();
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
const labels = folders.length
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
@@ -6115,16 +5972,7 @@ function renderWhere() {
let label = labels[0];
for (const text of labels) {
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) {
const dot = el("span", "where-alert");
dot.setAttribute("aria-hidden", "true");
@@ -7349,7 +7197,6 @@ function lightDismiss(dlg) {
});
}
lightDismiss($("looks-modal"));
lightDismiss($("subagents-modal"));
lightDismiss($("help-modal"));
lightDismiss($("workspace-modal"));
lightDismiss($("welcome-modal"));
@@ -7652,13 +7499,6 @@ $("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("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-go").addEventListener("click", sendBrief);
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("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("subagents", "Helpers (subagents)", false),
tab("ask", "Ask a quick question", false),
tab("finishing", "Stopping and finishing", false),
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 (workspace) return "workspace";
if (v === "ask") return "ask";
if (v === "subagents") return "subagents";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v.startsWith("doc:")) return "docs";
@@ -21,7 +21,6 @@
<link rel="modulepreload" href="/starters.js" />
<link rel="modulepreload" href="/workspace.js" />
<link rel="modulepreload" href="/meter.js" />
<link rel="modulepreload" href="/subagents.js" />
<link rel="modulepreload" href="/mentions.js" />
<link rel="modulepreload" href="/favicon.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>
Write a brief
</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 class="views-group">
<span class="views-arrow" aria-hidden="true">
@@ -593,13 +580,6 @@
<rect x="3" y="9" width="18" height="6" rx="3" />
<path d="M6 12h7" />
</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">
<path d="M4 5h16v11H10l-4 4v-4H4z" />
<path d="M8 9.5h8M8 12.5h5" />
@@ -1497,61 +1477,7 @@
</p>
</section>
<!-- Tab 12: Helpers (subagents) -->
<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 -->
<!-- Tab 12: Ask a quick question -->
<section class="help-panel" data-tab="ask">
<h3>Ask a quick question</h3>
<p class="help-lead">
@@ -1642,7 +1568,7 @@
</p>
</section>
<!-- Tab 14: Stopping and finishing -->
<!-- Tab 13: Stopping and finishing -->
<section class="help-panel" data-tab="finishing">
<h3>Stopping and finishing</h3>
<p class="help-lead">
@@ -1724,7 +1650,7 @@
</p>
</section>
<!-- Tab 15: When something looks stuck -->
<!-- Tab 14: When something looks stuck -->
<section class="help-panel" data-tab="stuck">
<h3>When something looks stuck</h3>
<p class="help-lead">
@@ -1846,7 +1772,7 @@
</div>
</section>
<!-- Tab 16: Keyboard and preferences -->
<!-- Tab 15: Keyboard and preferences -->
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
@@ -1962,7 +1888,7 @@
</ul>
</section>
<!-- Tab 17: Privacy and where things are saved -->
<!-- Tab 16: Privacy and where things are saved -->
<section class="help-panel" data-tab="privacy">
<h3>Privacy and where things are saved</h3>
<p class="help-lead">
@@ -1999,11 +1925,7 @@
</li>
<li>
your role, theme, colors, card width and sounds, in
<code>looks.json</code>;
</li>
<li>
your Subagents switch for each project and skill, in
<code>subagents.json</code>.
<code>looks.json</code>.
</li>
</ul>
<p>
@@ -2117,46 +2039,6 @@
</div>
</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
context. The list is drawn by app.js from the frame's `workspace`;
every change goes through the server's /workspace routes. -->
@@ -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,7 +25,6 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
SUBAGENTS_SETTING_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
@@ -39,7 +38,6 @@ import {
fileStamp,
handleFile,
initialWorkspace,
latestOpenCaps,
nowIso,
parseArgs,
pendingChatCount,
@@ -48,25 +46,20 @@ import {
readJson,
readLedger,
readOverview,
readSubagentSetting,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
saveSubagentStoreEntry,
specKey,
subagentStoreEntry,
typedCount,
withStateLock,
writeJsonAtomic,
writeSubagentSetting,
writeWorkspace,
} from "./lib.mjs";
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 { 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 { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
@@ -219,7 +212,6 @@ const SERVABLE = new Set([
"starters.js",
"workspace.js",
"meter.js",
"subagents.js",
"mentions.js",
"favicon.js",
"start-stop.mp3",
@@ -609,48 +601,6 @@ function ensureConversation(state) {
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.
// `have` names that exact view, for the page to hand back when it opens its
// stream (see /events).
@@ -665,33 +615,20 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
subagents: subagentsView(state),
...(updateInfo ? { update: updateInfo } : {}),
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() {
const { pending, stop } = resultFlags();
chatEntries();
chatPickedUp();
workspaceNow();
ledgerEntries();
subagentSettingNow();
openCapsNow();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -1235,39 +1172,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.
if (pathname === "/models" && req.method === "GET") {
const saved = readJson(USER_MODELS_FILE, null) || {};
@@ -1496,9 +1400,6 @@ const server = http.createServer((req, res) => {
try {
ensureConversation(written.state);
} catch {}
try {
syncSubagentSetting(written.state);
} catch {}
}
}
// Name the items that went. A page with OTHER answers staged should drop
@@ -1825,9 +1726,6 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
syncSubagentSetting(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
@@ -2002,9 +1900,6 @@ function onListening(port) {
try {
bootWorkspace();
} catch {}
try {
syncSubagentSetting(readState());
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -10,7 +10,7 @@
//
// and derives the ticket from a branch named <prefix>/<TICKET-ID>-description,
// where the ticket is an uppercase project key, a hyphen and an integer
// (PCWEB-10968). This script reads the branch, extracts the ticket and prints
// (ABC-10968). This script reads the branch, extracts the ticket and prints
// the exact command, so no prompt re-implements the rule by eye.
import { execFileSync } from "node:child_process";
@@ -96,7 +96,7 @@ run(USAGE, async (argv) => {
let branch = null;
let ticket = args.ticket ? args.ticket.trim() : null;
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like PCWEB-10968.");
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like ABC-10968.");
if (!ticket) {
branch = currentBranch();
ticket = ticketFromBranch(branch);
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -64,13 +64,6 @@ progress bar is the first thing someone watching a build looks at. The session
meter counts the build's tasks from `cleared` as it rises, so keep it current,
and start every phase (a second one in the same run too) at `"cleared": 0`.
`"version": 1` is for the first phase of a session only. A doc's version
never goes back (console.md → House rules, rule 9), so a later phase in the
same session reposts `phase` and `phasefile` at one more than the version the
page holds, with the new phase's title and content. The same goes for
`report` at sign-off and `review` in a mid-session review: version 1 the
first time, then up from wherever the page has it.
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
the person can read the prerequisites and task specs while you build. Re-post
it whenever the file changes, which is every task: the checkbox write that
@@ -118,12 +111,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
holds anything the person sends until you next look.
A build may receive a `Subagents:` standing instruction, on `open` output or a
`chat` check between tasks. Follow console.md → Standing instructions for
handing independent tasks to helpers and reporting them as `helpers`. Keep the
per-task progress posts, the checkbox writes, the chat checks and the sign-off
with you.
### Quick questions between tasks
The person can ask a Quick question on the Ask tab at any point in a build
@@ -208,8 +195,7 @@ only ever be offered once nothing could come of it:
`reply` carries `Approve this phase: approved`, which is the terminal's
`approved`. If the note that came with an approval asks for a change, treat it
as "describe any issues": do the change first and ask again. `changes` means
exactly what it says: address it, bump the report's version (a later phase's
report starts above the last one's, too), and reopen the
exactly what it says: address it, bump the report's version, and reopen the
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
person asking for the code review before they approve anything — see "The
review, mid-session" below.
@@ -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 |
| --- | --- | --- |
| `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. |
| `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. |
@@ -647,84 +647,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)
A `dashboard` session is not a conversation: the page draws a menu of every
@@ -841,10 +763,7 @@ commands follow the pipeline: the sign-off's is
### Review (`review`)
Scope questions up front — run standalone with nothing named, the first is
a `choice`, "What should I review?", built from a quick scan (branch changes,
uncommitted changes, specs, files you name; each option with its size),
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
Scope questions up front, then the findings report as a doc (`id: "report"`),
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
id, carrying `"doc": "report"` so the card links straight to the findings.
Settle that item (`"status": "answered"` plus the `answer` they sent) in
@@ -878,8 +797,6 @@ 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
finish (Finishing → Nothing of yours may still be running); the finish
body then names what each one found.
- Report every research subagent as a helper, whatever the Subagents switch
says (Standing instructions → Reporting helpers).
- At every session end, post `finish` (headline, `body`, and Form A's command as
`command`) BEFORE `stop`. Someone who spent the session in the browser never
sees the Trail Footer, and without this their last screen promises a question
@@ -1229,16 +1146,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
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
and 5 cover `reason` and `hint`.
8. **`helpers` entries are well formed** (Standing instructions → Reporting
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
and a known `state` within their limits, plus at most one `alone` entry.
Rules 4 and 5 cover `title`, `ask` and `result`.
9. **A doc's `version` never goes back.** Sending a known doc a lower
`version` than the page holds is refused: it is almost always a stale or
copied payload. The same version again is fine, and a dashboard hop starts
every doc fresh. Anything else reusing a doc id in the same session (a
build's second phase, a second report or review) continues from the
version the page holds.
These are workflow rules you already follow. The server just makes them checkable.
@@ -1260,9 +1167,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
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
and update the count as each returns. Never write a `finish.body` that says
work "is running in the background" or "will finish on its own". Mark every
reported helper `done` or `failed` before the finish, so the Subagents tab
never ends on a row still running.
work "is running in the background" or "will finish on its own".
### 1. Post the finish
@@ -64,8 +64,6 @@ import {
readChat,
readJson,
readLedger,
readSubagentCursor,
readSubagentSetting,
readWorkspace,
reapHandles,
rememberedWorkspace,
@@ -73,7 +71,6 @@ import {
removeScratch,
removeSessions,
repoRoots,
resetSubagentCursor,
scanProject,
SESSION_MAX_AGE_MS,
sessionDir,
@@ -91,11 +88,9 @@ import {
workspaceForAgent,
writeCursor,
writeJsonAtomic,
writeSubagentCursor,
writeWorkspaceCursor,
} from "./lib.mjs";
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
import { blockFor, offered } from "./public/subagents.js";
import { changeLine } from "./public/workspace.js";
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
@@ -315,11 +310,7 @@ async function cmdOpen() {
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
// A new agent conversation has been told nothing yet (FR-6).
try {
resetSubagentCursor(dir);
} catch {}
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
trace("open: state written");
// Dashboard launches are recorded too (they score nothing), so the folder
@@ -346,18 +337,9 @@ async function cmdOpen() {
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
};
// A standing instruction the new agent is owed, as `subagents` and a
// `reply` holding only its lines; neither key when nothing is owed.
const subagentsOwed = () => {
awaitSubagentSync(dir, state.workflow);
const [out, cursor] = withSubagents(dir, { reply: "" });
return [out.subagents ? out : {}, cursor];
};
// Reuse a live server if one is already serving this session.
if (existing && (await reusable)) {
if (!args["no-open"]) openBrowser(existing.url);
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -367,11 +349,9 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(existing.url),
workspace,
...owed,
...swept,
...remoteWarning(),
});
advanceSubagents(dir, subCursor);
sweep();
return;
}
@@ -404,7 +384,6 @@ async function cmdOpen() {
const notes = [];
if (remote.note) notes.push(remote.note);
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
@@ -415,12 +394,10 @@ async function cmdOpen() {
pendingResult: carried,
terminalLine: terminalLine(handle.url),
workspace,
...owed,
...swept,
...(remote.remote ? { remote: remote.remote } : {}),
...(notes.length ? { note: notes.join(" ") } : {}),
});
advanceSubagents(dir, subCursor);
// After the print, never before it: the page and the link wait for nothing.
sweep();
}
@@ -797,7 +774,7 @@ function serverGone(sid) {
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
function deliverChat(dir, sid, entries, url) {
const [withWs, changes] = withWorkspace(dir, {
const [out, changes] = withWorkspace(dir, {
type: "chat",
at: nowIso(),
sid,
@@ -805,11 +782,9 @@ function deliverChat(dir, sid, entries, url) {
chat: entries,
reply: chatReplyLines(entries),
});
const [out, subCursor] = withSubagents(dir, withWs);
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
advanceCursor(dir, entries);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -831,52 +806,6 @@ function advanceWorkspace(dir, changes) {
} catch {}
}
// The server rewrites the session's setting for a new workflow only once its
// watcher sees the state `open` just wrote, so a launch or hop that read the
// file at once would find the old workflow's and owe the agent nothing until
// its next pickup. Give the server a moment to catch up instead, never
// writing the file ourselves (FR-7). A session with no setting file at all is
// an older server, which never writes one: a short look, not the full wait.
const SUBAGENT_SYNC_WAIT_MS = 1500;
const SUBAGENT_SYNC_MISSING_MS = 250;
function awaitSubagentSync(dir, workflow) {
if (!offered(workflow)) return;
const start = Date.now();
for (;;) {
const setting = readSubagentSetting(dir);
if (setting && setting.workflow === workflow) return;
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
if (Date.now() - start >= budget) return;
sleepSync(25);
}
}
// The Subagents switch the agent is owed, added to what it is about to read:
// the setting as `subagents`, and its lines last in `reply`, after card lines,
// Quick questions and Workspace lines (FR-9). Read from the session's own
// setting file only, which only the server writes (FR-7). A setting for
// another workflow is the server not having caught up with a hop yet: it
// rides on the next pickup instead.
function withSubagents(dir, out) {
const setting = readSubagentSetting(dir);
if (!setting) return [out, null];
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
if (setting.workflow !== workflow) return [out, null];
const block = blockFor(setting, readSubagentCursor(dir));
if (!block) return [out, null];
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
return [{ ...out, subagents: block.field, reply }, block.cursor];
}
// After the print, like advanceWorkspace(): a kill in between repeats the
// block at the next pickup, never loses it.
function advanceSubagents(dir, cursor) {
if (!cursor) return;
try {
writeSubagentCursor(dir, cursor);
} catch {}
}
// Print first, then this, exactly as consume() stamps a result: a kill in
// between can only hand the same chat over again, and collectChat() drops
// anything that already has a reply.
@@ -903,17 +832,15 @@ async function cmdChat() {
}
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
const changes = pendingWorkspaceChanges(dir);
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
if (!entries.length && !changes.length && !subCursor) {
if (!entries.length && !changes.length) {
print({ chat: [] });
process.exitCode = 10;
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);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
@@ -938,8 +865,7 @@ function consume(dir, resultPath, result, url, chat = []) {
// never on result.json itself.
const withChat = { ...collected, chat };
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
const [withWs, changes] = withWorkspace(dir, withChat);
const [out, subCursor] = withSubagents(dir, withWs);
const [out, changes] = withWorkspace(dir, withChat);
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
try {
writeJsonAtomic(resultPath, collected);
@@ -948,7 +874,6 @@ function consume(dir, resultPath, result, url, chat = []) {
ledgerAnswers(dir, result);
advanceCursor(dir, chat);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = result.type === "cancel" ? 30 : 0;
}
@@ -1061,18 +986,12 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
May also print subagents: { state, revision, max, instruction } and
a reply holding only its "Subagents: ..." lines, when a standing
instruction (the page's Subagents switch) is owed to you.
post --session <sid> --file <patch.json>
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. A patch may
carry run: { event, id, tasks? } (session meter points) and folderIssue:
{ name, reason, hint? } (a workspace folder you could not read);
both go to the ledger, never into the state. A patch may also
carry helpers: [{ id, title, ask, state, result? }] or one
{ id: "alone", alone: true }, merged by id, for the Subagents tab
(see console.md → Standing instructions).
both go to the ledger, never into the state.
wait --session <sid> [--seconds <N>]
A bounded wait slice, sized below your shell timeout. Exit 0 = the
result is on stdout, 10 = still waiting ("Waiting on your answer
@@ -1083,14 +1002,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
"workspace" (changes since you last heard, each once, with a
"Workspace: ..." line in reply); exit 10 counts them as
pendingWorkspace, and a change alone never ends a slice.
Exit 0 may also carry "subagents" (a console setting, not typed
by the person, with its "Subagents: ..." lines last in reply); a
setting change alone never ends a slice either.
chat --session <sid>
Collect Quick questions, workspace changes and a Subagents
setting change now, never waiting, never touching card sends.
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
10 = none, 20 = server gone.
Collect Quick questions and workspace changes now, never waiting,
never touching card sends. Exit 0 = { chat, workspace, reply,
terminalLine }, 10 = none, 20 = server gone.
terminalLine is "→ Look at the web console: <url>": end your terminal
messages with it during a console session.
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
@@ -25,7 +25,6 @@ import { fileURLToPath } from "node:url";
import { CHAT_LIMIT } from "./public/chat.js";
import { DOC_TYPES } from "./public/answers.js";
import { defaultName } from "./public/workspace.js";
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const PUBLIC_DIR = path.join(HERE, "public");
@@ -492,16 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, the Subagents switch
// saved per project and workflow, the pointer to this console's directory,
// and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set([
"looks.json",
"workspaces.json",
"subagents.json",
"console-dir",
"update-check.json",
]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -1150,19 +1142,6 @@ const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
// state keeps its text. Blocks left out of the patch stay as they are.
function mergeDocs(current, patchList) {
// A doc's version only moves forward. One going back is a stale or copied
// payload (last phase's progress script, say), and the page would quietly
// show the old content under the new run's name.
for (const entry of patchList) {
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
const prev = (current || []).find((d) => d && d.id === entry.id);
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
throw new Error(
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
"Versions only go up: bump it, and check the payload is the current one."
);
}
}
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
for (const entry of patchList) {
if (!Array.isArray(entry.blocks)) continue;
@@ -1205,13 +1184,6 @@ export function applyPatch(state, patch) {
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
break;
case "helpers":
// The agent's report of its helpers, for the page's Subagents tab.
// Only `post` writes it; the server's /submit never touches it.
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
break;
case "docs":
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
next.docs = mergeDocs(next.docs, v);
@@ -1506,20 +1478,6 @@ export function validate(state) {
JSON.stringify(state.menu || {});
problems.push(...proseProblems(prose));
// The agent's report of its helpers: the shape the page draws from
// (subagents.js), then the same prose scan as everything else it writes.
if (state.helpers != null) {
problems.push(...checkHelpers(state.helpers));
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
if (!isPlainObject(helper)) continue;
for (const field of ["title", "ask", "result"]) {
if (typeof helper[field] === "string") {
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
}
}
}
}
return problems;
}
@@ -1549,8 +1507,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
* A resume that passes through the dashboard (a finished skill going back to
* it, or a launch from its menu) is a new skill taking the page over, so it
* starts from a blank page: the last skill's questions, sections, docs,
* helpers, headline and ending are its record on disk, not the next skill's
* opening.
* headline and ending are its record on disk, not the next skill's opening.
* Only the session's identity carries across. `workspace.json`,
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
* and the meter outlive every hop.
@@ -1577,8 +1534,6 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
// workspace.json the server. Folders, version, change log, missing, remote.
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
export const CHAT_FILE = "chat.ndjson";
export const CHAT_CURSOR_FILE = "chat-cursor.json";
export const WORKSPACE_FILE = "workspace.json";
@@ -2034,98 +1989,6 @@ export function pendingWorkspaceChanges(dir) {
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.
*
@@ -208,26 +208,6 @@ body {
.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); }
/* 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; }
/* The session meter: a ring that fills with the points and a few words, in
@@ -1450,30 +1430,6 @@ h1 {
.pill.done { background: var(--ok-soft); color: var(--ok); }
.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 */
.answered {
@@ -2015,8 +1971,6 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
cursor: pointer;
}
.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. */
.where-alert {
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
@@ -103,15 +103,6 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
import { RED_BANNER } from "./meter.js";
import { applyMention, matchNames, mentionAt } from "./mentions.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);
@@ -539,9 +530,6 @@ 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 chatSending = false;
let chatResetting = false;
@@ -892,8 +880,6 @@ function adopt(body) {
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();
if (gone) {
gone = false;
@@ -1315,7 +1301,6 @@ function render() {
renderChrome();
renderStatus();
renderBriefButton();
renderSubagentsButton();
renderStopButton();
renderHomeButton();
tabAdded = renderViews();
@@ -1581,7 +1566,7 @@ function renderChrome() {
renderMeter();
$("title").textContent = S.title || "Session";
$("badge").textContent = workflowLabel(S.workflow);
renderTabTitle();
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
const h = S.headline || {};
// On a finished session an open item is frozen: the send on it counts as
@@ -1850,69 +1835,6 @@ function renderBriefButton() {
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() {
const nav = $("views");
nav.replaceChildren();
@@ -1928,14 +1850,6 @@ function renderViews() {
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
else if (view === "overview") view = "questions";
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.
// The ring left of "Ask" shows exactly when the conversation's own ring does:
// a question the agent picked up and has not answered yet.
@@ -2216,7 +2130,6 @@ function paintMain(main) {
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
if (view === "overview") return renderOverview(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 top of the rail. The hand-off lives here alone now, rather than
@@ -4861,42 +4774,6 @@ function renderOverview(main) {
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 */
// The frame's chat block, with `offline` worked out now rather than when the
@@ -6079,30 +5956,10 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
// 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
// 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() {
const b = $("footer-where");
const folders = workspaceFolders();
const path = S.worktree || "";
renderTabTitle();
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
const labels = folders.length
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
@@ -6115,16 +5972,7 @@ function renderWhere() {
let label = labels[0];
for (const text of labels) {
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) {
const dot = el("span", "where-alert");
dot.setAttribute("aria-hidden", "true");
@@ -7349,7 +7197,6 @@ function lightDismiss(dlg) {
});
}
lightDismiss($("looks-modal"));
lightDismiss($("subagents-modal"));
lightDismiss($("help-modal"));
lightDismiss($("workspace-modal"));
lightDismiss($("welcome-modal"));
@@ -7652,13 +7499,6 @@ $("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("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-go").addEventListener("click", sendBrief);
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("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("subagents", "Helpers (subagents)", false),
tab("ask", "Ask a quick question", false),
tab("finishing", "Stopping and finishing", false),
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 (workspace) return "workspace";
if (v === "ask") return "ask";
if (v === "subagents") return "subagents";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v.startsWith("doc:")) return "docs";
@@ -21,7 +21,6 @@
<link rel="modulepreload" href="/starters.js" />
<link rel="modulepreload" href="/workspace.js" />
<link rel="modulepreload" href="/meter.js" />
<link rel="modulepreload" href="/subagents.js" />
<link rel="modulepreload" href="/mentions.js" />
<link rel="modulepreload" href="/favicon.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>
Write a brief
</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 class="views-group">
<span class="views-arrow" aria-hidden="true">
@@ -593,13 +580,6 @@
<rect x="3" y="9" width="18" height="6" rx="3" />
<path d="M6 12h7" />
</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">
<path d="M4 5h16v11H10l-4 4v-4H4z" />
<path d="M8 9.5h8M8 12.5h5" />
@@ -1497,61 +1477,7 @@
</p>
</section>
<!-- Tab 12: Helpers (subagents) -->
<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 -->
<!-- Tab 12: Ask a quick question -->
<section class="help-panel" data-tab="ask">
<h3>Ask a quick question</h3>
<p class="help-lead">
@@ -1642,7 +1568,7 @@
</p>
</section>
<!-- Tab 14: Stopping and finishing -->
<!-- Tab 13: Stopping and finishing -->
<section class="help-panel" data-tab="finishing">
<h3>Stopping and finishing</h3>
<p class="help-lead">
@@ -1724,7 +1650,7 @@
</p>
</section>
<!-- Tab 15: When something looks stuck -->
<!-- Tab 14: When something looks stuck -->
<section class="help-panel" data-tab="stuck">
<h3>When something looks stuck</h3>
<p class="help-lead">
@@ -1846,7 +1772,7 @@
</div>
</section>
<!-- Tab 16: Keyboard and preferences -->
<!-- Tab 15: Keyboard and preferences -->
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
@@ -1962,7 +1888,7 @@
</ul>
</section>
<!-- Tab 17: Privacy and where things are saved -->
<!-- Tab 16: Privacy and where things are saved -->
<section class="help-panel" data-tab="privacy">
<h3>Privacy and where things are saved</h3>
<p class="help-lead">
@@ -1999,11 +1925,7 @@
</li>
<li>
your role, theme, colors, card width and sounds, in
<code>looks.json</code>;
</li>
<li>
your Subagents switch for each project and skill, in
<code>subagents.json</code>.
<code>looks.json</code>.
</li>
</ul>
<p>
@@ -2117,46 +2039,6 @@
</div>
</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
context. The list is drawn by app.js from the frame's `workspace`;
every change goes through the server's /workspace routes. -->
@@ -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,7 +25,6 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
SUBAGENTS_SETTING_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
@@ -39,7 +38,6 @@ import {
fileStamp,
handleFile,
initialWorkspace,
latestOpenCaps,
nowIso,
parseArgs,
pendingChatCount,
@@ -48,25 +46,20 @@ import {
readJson,
readLedger,
readOverview,
readSubagentSetting,
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
saveSubagentStoreEntry,
specKey,
subagentStoreEntry,
typedCount,
withStateLock,
writeJsonAtomic,
writeSubagentSetting,
writeWorkspace,
} from "./lib.mjs";
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 { 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 { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
@@ -219,7 +212,6 @@ const SERVABLE = new Set([
"starters.js",
"workspace.js",
"meter.js",
"subagents.js",
"mentions.js",
"favicon.js",
"start-stop.mp3",
@@ -609,48 +601,6 @@ function ensureConversation(state) {
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.
// `have` names that exact view, for the page to hand back when it opens its
// stream (see /events).
@@ -665,33 +615,20 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
subagents: subagentsView(state),
...(updateInfo ? { update: updateInfo } : {}),
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() {
const { pending, stop } = resultFlags();
chatEntries();
chatPickedUp();
workspaceNow();
ledgerEntries();
subagentSettingNow();
openCapsNow();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -1235,39 +1172,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.
if (pathname === "/models" && req.method === "GET") {
const saved = readJson(USER_MODELS_FILE, null) || {};
@@ -1496,9 +1400,6 @@ const server = http.createServer((req, res) => {
try {
ensureConversation(written.state);
} catch {}
try {
syncSubagentSetting(written.state);
} catch {}
}
}
// Name the items that went. A page with OTHER answers staged should drop
@@ -1825,9 +1726,6 @@ function checkState() {
try {
ensureConversation(parsed);
} catch {}
try {
syncSubagentSetting(parsed);
} catch {}
try {
followSpecDir(parsed);
} catch {}
@@ -2002,9 +1900,6 @@ function onListening(port) {
try {
bootWorkspace();
} catch {}
try {
syncSubagentSetting(readState());
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.5.0",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-06",
"releaseDate": "2026-10-05",
"mode": "utility"
}
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff. Show more