mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 20:45:33 -08:00
Update the web console server, screens, help, prefs and loop setup, with matching page and logic suites
AI Assisted
This commit is contained in:
1 parent
2468027a5a
commit
8e34bf1005
119 files changed
+9957
-3728
No files matched your search
@@ -1,154 +1,56 @@
|
||||
# The Review, Mid-Session, on the Web Console
|
||||
# The Review, Mid-Session
|
||||
|
||||
Part of the build contract (`building.md`). Read when the person asks for the
|
||||
review on the page: the `review` verdict on Implement's sign-off card, the
|
||||
**Review it now** button on a finished quick task, or Implement + Review's
|
||||
Stage 2.
|
||||
The console points here on `__review`, or on a `review` card answered with a verdict. Part of the build contract (`building.md`). The same focused review runs from three doors:
|
||||
|
||||
The same focused review runs from either of two doors:
|
||||
- **`implement`:** the `review` verdict on the sign-off card, before anything is approved. A note sent with it is focus for the review. Settle the card in the post that goes back to work: `{"settle":true,"headline":{"stage":"Reviewing Phase 3","cleared":0,"total":0},"run":{"event":"review","id":"review"},"agent":{"status":"working","activity":"Reviewing the 7 files this phase changed","quietMinutes":15}}`
|
||||
- **`quick-task`:** the **Review it now** button on the finished screen (`finish.review`), arriving as `__review`. Take it up with the same post minus `settle`, plus `"finish":null`.
|
||||
- **`implement-review`:** Stage 2 (`notes/implement.md`).
|
||||
|
||||
- **`implement`:** the `review` verdict on the sign-off card, before anything
|
||||
is approved. A note sent with it is theirs — read it as focus for the
|
||||
review. Settle the card with it in the same post that goes back to work:
|
||||
Either way the post that takes the review up carries `"run":{"event":"review","id":"review"}`: the review runs inside this session, so no launch scores it. Never also resume under `--workflow review`, or it counts twice.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"settle": true,
|
||||
"headline": { "stage": "Reviewing Phase 3", "cleared": 0, "total": 0 },
|
||||
"run": { "event": "review", "id": "review" },
|
||||
"agent": { "status": "working", "activity": "Reviewing the 7 files this phase changed", "quietMinutes": 15 }
|
||||
}
|
||||
```
|
||||
A quick-task finish carries `review` and `dashboard:true` and waits for whichever comes first:
|
||||
|
||||
- **`quick-task`:** the **Review it now** button on the finished screen, which
|
||||
`finish.review` puts there. It arrives through the wait loop as an action
|
||||
`{ "i": "__review", "type": "review" }`, like any send. Take it up with the
|
||||
same post minus `settle`, plus `"finish": null` — that takes the session off
|
||||
its ending and back to work.
|
||||
|
||||
Either way, the post that takes the review up carries `"run": { "event":
|
||||
"review", "id": "review" }`: the review runs inside this skill's session, so no
|
||||
launch scores it on the session meter. Never resume the session under
|
||||
`--workflow review` for it as well, or it counts twice.
|
||||
|
||||
A finish carrying `review` keeps the session alive for the answer, so a
|
||||
`quick-task` that just posted one keeps waiting — there is no timeout after
|
||||
a finish.
|
||||
A quick-task finish carries both `review` and `"dashboard": true` and waits
|
||||
for whichever comes first:
|
||||
|
||||
| What arrives | What you do |
|
||||
| Arrives | Do |
|
||||
| --- | --- |
|
||||
| An action `{ "i": "__review", "type": "review" }` | Take the review up (below). |
|
||||
| An action `{ "i": "__dashboard", "type": "dashboard" }` | Take the session back as the dashboard (`console-finish.md` → After the finish). |
|
||||
| An action `{ "i": "__done", "type": "done" }` | `stop` the server. The session is over. |
|
||||
| `wait` exit `20` | The server is gone. Resume it (`open --resume <sid> --workflow <yours>`), give them the new link, and keep waiting. |
|
||||
| The session ends without a press (the terminal closes) | The server sweeps itself after its idle window; the page then shows the terminal command for a review instead of a button that would go nowhere. |
|
||||
| `__review` | Take the review up (below) |
|
||||
| `__dashboard` | Take the session back as the dashboard (`console-finish.md`) |
|
||||
| `__done` | `stop` the server: the session is over |
|
||||
| `wait` exit 20 | `open --resume <sid> --workflow <yours>`, give the new link, keep waiting |
|
||||
|
||||
**Read references/review.md** and run Review Mode with these overrides:
|
||||
**Read `references/review.md`** and run Review Mode with these overrides:
|
||||
|
||||
- **Scope is Focused, and already decided:** the exact change set of this
|
||||
session (files created or modified by the phase or the quick task, plus the
|
||||
tests and docs changed for it). Do not ask about scope. Use overview.md and
|
||||
the phase file for spec compliance; they do not widen the scope.
|
||||
- **The helper rule still applies:** a fresh helper runs the analysis when
|
||||
available, you verify every finding, and the report carries its Reviewed by
|
||||
line.
|
||||
- **No commit instructions and no next-conversation routing** mid-review. The
|
||||
way back out carries both.
|
||||
- The page takes the whole report, so the "top 10 of 15+" rule does not apply,
|
||||
and tables go in the doc.
|
||||
- Scope is Focused and decided: the exact change set of this session (files created or modified by the phase or the quick task, plus the tests and docs changed for it). Do not ask about scope. `overview.md` and the phase file give spec compliance; they do not widen scope.
|
||||
- The helper rule applies: a fresh helper runs the analysis when available, you verify every finding, and the report carries its Reviewed by line.
|
||||
- No commit instructions and no next-conversation routing mid-review; the way back out carries both.
|
||||
- The page takes the whole report: the "top 10 of 15+" rule does not apply, and tables go in the doc.
|
||||
|
||||
## The findings
|
||||
|
||||
The full Review Mode report as a doc, and the fix choice as one `multi` item,
|
||||
posted with `--wait`:
|
||||
In loop mode the pick comes from `--fix`: post the findings and the pick as settled `handledBy:"loop"` items and ask nothing (`notes/loop.md`).
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"docs": [{ "id": "review", "title": "Review findings", "blocks": [
|
||||
{ "id": "report", "state": "settled", "md": "## Overview\n\n...\n\n## Findings\n\n| # | Severity | Issue | File |\n..." }
|
||||
]}],
|
||||
"items": [{
|
||||
"id": "fixes", "kind": "multi", "title": "Which to fix", "required": false, "doc": "review",
|
||||
"body": "Tick what should be fixed now. Anything left unticked is written up as still open. Nothing changes until you send.",
|
||||
"options": [
|
||||
{ "k": "1", "text": "Critical: token is logged in plain text", "detail": "src/auth.ts:42. Fix: redact before logging." },
|
||||
{ "k": "2", "text": "Warning: missing null check on the user lookup", "detail": "src/users.ts:88. Fix: ..." },
|
||||
{ "k": "3", "text": "Suggestion: repeated query could be batched", "detail": "src/report.ts:17. Fix: ..." }
|
||||
],
|
||||
"presets": [
|
||||
{ "label": "Critical and warnings", "ks": ["1", "2"] },
|
||||
{ "label": "All of them", "ks": ["1", "2", "3"] }
|
||||
]
|
||||
}]
|
||||
}
|
||||
```
|
||||
Post the full report as a doc, and the fix choice as one `multi` item, with `--wait`:
|
||||
|
||||
`"doc": "review"` puts a **Read "Review findings" in full** button on the
|
||||
card, so the report is one click from the list rather than behind a tab
|
||||
nobody notices. Always carry it.
|
||||
`{"docs":[{"id":"review","title":"Review findings","blocks":[{"id":"report","md":"## Overview\n\n...\n\n## Findings\n\n| # | Severity | Issue | File |\n..."}]}],"items":[{"id":"fixes","kind":"multi","title":"Which to fix","required":false,"doc":"review","body":"Tick what should be fixed now. Anything unticked is written up as still open. Nothing changes until you send.","options":[{"k":"1","text":"Critical: token is logged in plain text","detail":"src/auth.ts:42. Fix: redact before logging."},{"k":"2","text":"Warning: missing null check on the user lookup","detail":"src/users.ts:88. Fix: ..."}],"presets":[{"label":"Critical and warnings","ks":["1","2"]},{"label":"All of them","ks":["1","2","3"]}]}]}`
|
||||
|
||||
Read the reply as Review Mode's fix choice: `Which to fix: 1, 2` is `S 1,2`,
|
||||
every finding ticked is `A`, and `skip` (or nothing ticked) is "fix none,
|
||||
keep them as unresolved". Leave out `presets` a set would not change (no
|
||||
warnings, one finding). With **zero findings** there is no item: say so in the
|
||||
doc and go straight to the way back out.
|
||||
Findings keep numeric `k` (they are not lettered). `"doc":"review"` puts a "Read in full" button on the card: always carry it. Read the reply as Review Mode's fix choice: `Which to fix: 1, 2` is `S 1,2`, all ticked is `A`, `skip` or nothing ticked is "fix none, keep them as unresolved". Leave out a `preset` a set would not change. With zero findings there is no item: say so in the doc and go to the way back out.
|
||||
|
||||
## Fixing
|
||||
|
||||
Settle the `fixes` item (`"settle": true`) in the same post that goes back to
|
||||
work. The server records their send on the item, but only you decide it is
|
||||
settled; left open it stays on the page as an outstanding question, beside the
|
||||
card you ask next. A send with nothing ticked settles as `{ "ks": [] }`. Then
|
||||
follow Review Mode's Post-Fix Flow, posting `activity` per fix ("Fix 2 of 3: the
|
||||
null check") and `quietMinutes` as in a build.
|
||||
Settle `fixes` (`"settle":true`) in the same post that goes back to work. A send with nothing ticked settles as `{"ks":[]}`. Then follow Review Mode's Post-Fix Flow, posting `activity` per fix ("Fix 2 of 3: the null check") and `quietMinutes` as in a build. In loop mode: one fix round, then a fresh re-check of only the fixes; with `--fix smart` a triage helper picks the findings first (`notes/loop.md`).
|
||||
|
||||
## The way back out
|
||||
|
||||
**`implement` — back to the sign-off.** The review was the preamble to an
|
||||
approval that has not happened yet, so this is where it lands. Fold the review
|
||||
results and any still-open findings into the report doc, then reopen the
|
||||
sign-off **without the review verdict** — re-offering a review that just ran
|
||||
reads as though nothing happened — and post the build's `headline` back (the
|
||||
review set it to its own stage):
|
||||
In loop mode the way out is the `loopOutcome` post, not a sign-off.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "cleared": 9, "total": 9 },
|
||||
"items": [{ "id": "signoff", "status": "reopened",
|
||||
"body": "Reviewed and ready for sign-off. The review found 3 issues: 2 fixed, 1 still open in the Review findings tab. The report is updated.",
|
||||
"verdicts": [
|
||||
{ "id": "approve", "label": "Approve this phase" },
|
||||
{ "id": "show", "label": "Show me it working" },
|
||||
{ "id": "changes", "label": "I want changes" }
|
||||
],
|
||||
"token": { "approve": "approved", "changes": "needs changes", "show": "show me" },
|
||||
"thread": [{ "who": "agent", "text": "Review done: 2 of 3 findings fixed; the rest is written up in the findings tab." }]
|
||||
}]
|
||||
}
|
||||
```
|
||||
**`implement` and `implement-review`: back to the sign-off.** Fold the review results and still-open findings into the report doc, then reopen the sign-off without the review verdict and post the build's `headline` back:
|
||||
|
||||
`show` runs as `notes/implement.md` → Show me it working says, then reopens
|
||||
this card without it. Review Mode's own closing gate ("Reply approved to commit") is this card:
|
||||
approving the phase now covers the fixes too, so there is no separate "Check
|
||||
the fixes" step. On approval, continue at `notes/implement.md` → After
|
||||
approval: the finish.
|
||||
`{"headline":{"cleared":9,"total":9},"items":[{"id":"signoff","status":"reopened","body":"Reviewed and ready for sign-off. The review found 3 issues: 2 fixed, 1 still open in the Review findings tab.","verdicts":[{"id":"approve","label":"Approve this phase"},{"id":"show","label":"Show me it working"},{"id":"changes","label":"I want changes"}],"token":{"approve":"approved","changes":"needs changes","show":"show me"},"thread":[{"who":"agent","text":"Review done: 2 of 3 findings fixed; the rest is in the findings tab."}]}]}`
|
||||
|
||||
**`quick-task` — the closing gate, then the finish.** Review Mode's closing
|
||||
gate ("Reply approved to commit, or request changes") becomes a `review` item
|
||||
titled "Check the fixes", `doc: "review"`, `"nothingYet": false` (the fixes are already made), verdicts `approve` ("The fixes look
|
||||
right") and `changes`, token `approved` / `needs changes`. When it clears,
|
||||
settle it (`"settle": true`) in the same post as the new finish, post the finish
|
||||
**without** `review` (and with `dashboard: true`), then keep waiting for its
|
||||
buttons as `console-finish.md` says; `stop` only on `__done`. An item left open survives on the page as
|
||||
a question still owed, above the ending itself:
|
||||
`show` runs as `notes/implement.md` says and reopens this card without it. Approving now covers the fixes: there is no separate "Check the fixes" step. On approval continue at `notes/implement.md` (the finish).
|
||||
|
||||
**`quick-task`: the closing gate, then the finish.** Post a `review` item "Check the fixes": `doc:"review"`, `"nothingYet":false`, verdicts `approve` ("The fixes look right") and `changes`, token `approved` / `needs changes`. When it clears, settle it in the same post as the new finish, posted without `review` and with `dashboard:true`; keep waiting for its buttons, `stop` only on `__done`. The finish:
|
||||
|
||||
- `headline`: "The review is done"
|
||||
- `body`: findings by severity, what was fixed, what is still open, and the
|
||||
commit command for the fixes, in the project's commit format.
|
||||
- `command`: one commit for the whole quick task, its changes and the fixes
|
||||
together, in the project's commit format (not a second command beside the
|
||||
first), with `commit: true` so **Commit it now** is still on offer, and `changelog: true` so **Update CHANGELOG first** is too.
|
||||
- `headline`: the quick task's own again, e.g. `{ "cleared": 4, "total": 4 }`.
|
||||
- `doc`: `"review"`.
|
||||
- `body`: findings by severity, what was fixed, what is still open, and the commit command for the fixes
|
||||
- `command`: one commit for the whole quick task (changes and fixes together) in the project's commit format, with `commit:true` and `changelog:true`
|
||||
- `doc`: `"review"`. The `headline` object goes back to the quick task's own (`{"cleared":4,"total":4}`).
|
||||
+27
-122
@@ -1,149 +1,54 @@
|
||||
# Build Sessions on the Web Console
|
||||
# Build Sessions
|
||||
|
||||
For `/plan2code-3-implement`, `/plan2code-3-implement-review` and
|
||||
`/plan2code-quick-task`. Everything in `console.md` still applies (the turn,
|
||||
one post per send, `finish` before `stop`, the house rules). This file adds what
|
||||
a build needs, because a build is mostly you working, and the page has to be
|
||||
told so. Then read your workflow's own notes: `notes/implement.md` (Implement
|
||||
and Implement + Review) or `notes/quick-task.md`. `building-review.md` is read
|
||||
only when a review is asked for on the page.
|
||||
|
||||
**The console changes where you ask, not what you build.** Every rule of the
|
||||
workflow stands: the same specs, the same checkbox writes to disk after every
|
||||
task, the same sign-off wording, the same "no git commands". The files under
|
||||
`specs/` and the code are the record. The page is a window onto them.
|
||||
|
||||
---
|
||||
For `implement`, `implement-review` and `quick-task`; read right after `open`, then `notes/implement.md` or `notes/quick-task.md`. `building-review.md` is named by `read` when a review is asked for on the page. The workflow's rules stand: the same specs, the same checkbox writes to disk after every task, the same sign-off wording, no git commands. The files under `specs/` and the code are the record; the page is a window onto them.
|
||||
|
||||
## Opening
|
||||
|
||||
Open first, before reading the spec — the page shows a starting screen while
|
||||
you work out the phase:
|
||||
Open before reading the spec; the page shows a starting screen meanwhile.
|
||||
|
||||
| Workflow you are running | `--workflow` | `--spec` |
|
||||
| Workflow | `--workflow` | `--spec` |
|
||||
| --- | --- | --- |
|
||||
| `/plan2code-3-implement` | `implement` | `specs/<feature>` |
|
||||
| `/plan2code-3-implement-review` | `implement-review` | `specs/<feature>` |
|
||||
| `/plan2code-quick-task` | `quick-task` | leave it out |
|
||||
| `/plan2code-quick-task` | `quick-task` | leave out |
|
||||
|
||||
`--spec` is what the page builds a resume command from if you ever cannot
|
||||
answer a stop yourself. Pass it to `open` when you already know the spec;
|
||||
otherwise post `"specDir": "specs/<feature>"` and a real `title` ("<feature>:
|
||||
Phase 3") in your first update, once the phase is chosen, or with the phase
|
||||
question as its first item if there is one to ask.
|
||||
|
||||
**Launched from the dashboard?** Then the session is already open and the
|
||||
person is watching it — run the `resume` the launch carried (`open --resume
|
||||
<sid> --no-open --workflow <yours>`, plus `--spec` once known) instead of a
|
||||
fresh `open`, exactly as `console-launches.md` says. Everything below is
|
||||
unchanged; the only difference is whose session it was a minute ago.
|
||||
|
||||
---
|
||||
Without `--spec` at `open`, post `"specDir":"specs/<feature>"` and a real `title` ("<feature>: Phase 3") once the phase is chosen. Launched from the dashboard? The session is open: run the `resume` the launch carried (`open --resume <sid> --no-open --workflow <yours>`, plus `--spec` once known).
|
||||
|
||||
## While you build
|
||||
|
||||
Post after every task, in the same breath as writing its checkbox to disk,
|
||||
with no `--wait`. Your notes file shows the exact post; every one carries:
|
||||
Post after every task, in the same breath as writing its checkbox to disk, with no `--wait`. Every post carries:
|
||||
|
||||
- **`headline.cleared` / `total`**: tasks done out of tasks in the run. The
|
||||
progress bar is the first thing someone watching a build looks at, and on
|
||||
Implement (and Implement + Review) the session meter counts the build's tasks
|
||||
from `cleared` as it rises; a quick task scores once, when it opens. Start every
|
||||
phase (a second one in the same run too) at `"cleared": 0`. If the task list
|
||||
grows mid-build, raise `headline.total` in the same post.
|
||||
- **`agent.activity`**: one plain sentence saying what you are doing now. The
|
||||
page shows it beside Planny and in place of "questions coming". No internal
|
||||
vocabulary, no loop completion markers. Number tasks by their position in
|
||||
the run, of the task count (`Task 5 of 9`), not by the file's `5.5`-style
|
||||
labels: the phase is already in the headline. The page rewrites the old form
|
||||
as a safety net.
|
||||
- **`agent.quietMinutes`** (on the post that starts the build): how long you
|
||||
might go without posting (1 to 60; the page always allows at least two). The page calls a working agent stuck
|
||||
after two minutes of silence unless you say otherwise, and a build task can
|
||||
honestly take twenty. Set it to the longest gap you expect, usually 10 to 30.
|
||||
Every post is also a heartbeat. It only counts while you are working, so it
|
||||
holds across the questions you ask: set it once.
|
||||
- **The task list re-read from disk** (Implement): the doc blocks that mirror
|
||||
the spec are `file` blocks, so a progress post re-reads them with
|
||||
`"refresh": true` rather than repeating the text. A quick task's plan lives
|
||||
only on the page, so its steps block stays `md` (`notes/quick-task.md`).
|
||||
Versions move by themselves.
|
||||
- `headline.cleared` / `total`: tasks done of tasks in the run. Start every phase at `"cleared":0`; raise `total` if the list grows. On Implement and Implement + Review the meter counts a build's tasks from `cleared`; a quick task scores once, when it opens.
|
||||
- `agent.activity`: one plain sentence, no internal vocabulary or loop markers. Number tasks by position in the run (`Task 5 of 9`), not the file's `5.5` labels.
|
||||
- `agent.quietMinutes` (on the post that starts the build): the longest gap you expect, usually 10 to 30 (the page calls you stuck after two silent minutes otherwise). Set it once.
|
||||
- the doc blocks that mirror the spec are `file` blocks: re-read them with `"refresh":true`, never repeat the text (`notes/implement.md`). A quick task's steps block stays `md`.
|
||||
|
||||
Do not call `wait` while building. There is nothing to collect, and the page
|
||||
holds anything the person sends until you next look.
|
||||
Do not call `wait` while building. After each progress post, run `node "<CONSOLE>" chat --session <sid>` before the next task: exit 0 means answer everything waiting, under `console-chat.md`, in one post, then continue (a `Workspace:` change takes effect from the next task); 10 nothing waiting; 20 server gone, `open --resume <sid> --workflow <yours>`, give the link, carry on. An approved chat edit is made here, between tasks.
|
||||
|
||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
||||
`chat` check between tasks. Follow `console-subagents.md` for handing
|
||||
independent tasks to helpers and reporting them as `helpers`. Keep the
|
||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
||||
with you.
|
||||
A blocker (`[!]`), a `SPEC NOTE` and a verified or assumed prerequisite are not questions: put them in the phase doc and the report. A `Subagents:` block: hand independent tasks to helpers as `console-subagents.md` says; keep the progress posts, checkbox writes, chat checks and sign-off with you.
|
||||
|
||||
### Quick questions between tasks
|
||||
## When the workflow asks something
|
||||
|
||||
The person can ask a Quick question on the Ask tab at any point in a build
|
||||
(`console-chat.md`). After each task's progress post, check for one before
|
||||
starting the next task:
|
||||
|
||||
```
|
||||
node "<CONSOLE>" chat --session <sid>
|
||||
```
|
||||
|
||||
| Exit | What you do |
|
||||
| --- | --- |
|
||||
| `0` | Answer everything waiting, under `console-chat.md`, in one post, then start the next task. A `workspace` list in the output is a change to the session's folders (`console-workspace.md`): take it into account from the next task on; it needs no reply. |
|
||||
| `10` | Nothing waiting. Carry on. |
|
||||
| `20` | The server is gone: `open --resume <sid> --workflow <yours>`, give them the new link, then carry on. |
|
||||
|
||||
This is an instant check, not a wait: it never sleeps and never touches card
|
||||
sends. It does not replace `wait` at a gate, and no build calls `wait`
|
||||
mid-build for cards. An approved chat edit is made here, between tasks, never
|
||||
in the middle of one.
|
||||
|
||||
A blocker (`[!]`), a `SPEC NOTE` and a verified or assumed prerequisite are
|
||||
not questions. Put them in the phase doc as they happen, and in the report.
|
||||
|
||||
### When the workflow asks something
|
||||
|
||||
Publish it with `post --wait`: a new question hands the turn over by itself
|
||||
(status `waiting`). When the answer lands, collecting it
|
||||
sets you `working` again; carry on.
|
||||
|
||||
A question stops the build. Never post `"status": "working"` with a question
|
||||
open, and never "carry on while you decide": the page reads `working` as "not
|
||||
your turn", and the person is left looking at a question they cannot answer.
|
||||
If there is other work the answer does not touch, finish it before you ask,
|
||||
then ask and wait.
|
||||
Publish it with `post --wait`. A question stops the build: never post `"status":"working"` with a question open, and finish any work the answer does not touch before you ask.
|
||||
|
||||
| Moment | `kind` | Notes |
|
||||
| --- | --- | --- |
|
||||
| Several phases can be picked | `choice` | One option per phase, `detail` = status and task count, `token` = the phase number. Put the "run another agent on a different phase" tip in `body`. |
|
||||
| A phase is already in progress | `confirm` | "Resume Phase 3?" `yes` / `no`. |
|
||||
| `SPEC CONFLICT` | `choice` or `text` | The conflict in `body`, the readings as options where there are clear ones. Never guess on architecture. |
|
||||
| Test failures | `choice` | `1` Fix now, `2` Document and proceed, `3` Investigate first. |
|
||||
| Several phases can be picked | `choice` | one option per phase, `detail` = status and task count, `token` = the phase number; put the "run another agent on a different phase" tip in `body` |
|
||||
| A phase is in progress | `confirm` | "Resume Phase 3?" |
|
||||
| `SPEC CONFLICT` | `choice` or `text` | the conflict in `body`, clear readings as options; never guess on architecture |
|
||||
| Test failures | `choice` | `1` Fix now, `2` Document and proceed, `3` Investigate first |
|
||||
| Shared ground touched | `choice` | run the full suite, run a wider named set, or approve without it; `body` says what was touched and why it is wide |
|
||||
| A small phase, continue with the next? | `confirm` | |
|
||||
| A spec gap only they can close | `text` | |
|
||||
| Something learned for AGENTS.md | `confirm` | The proposed lines in `consequences`. |
|
||||
| Something learned for AGENTS.md | `confirm` | proposed lines in `consequences` |
|
||||
|
||||
Titles stay plain: "Which phase next", "Tests are failing", "Keep going?".
|
||||
Titles stay plain: "Which phase next", "Tests are failing", "Keep going?". In loop mode (`notes/loop.md`) a question is held or stopped by the app, never answered by it; the findings pick and fixes are `handledBy:"loop"` cards.
|
||||
|
||||
---
|
||||
## Stop during a build
|
||||
|
||||
## Stop requests during a build
|
||||
Stop only arrives on the person's turn, never mid-task. On `__stop` (`console-stop.md`):
|
||||
|
||||
The Stop button only works on the person's turn, so it never lands mid-task.
|
||||
When `__stop` arrives (`console-stop.md`):
|
||||
- **implement / implement-review:** Implementation Mode's abort without the "are you sure": the phase stays `[/]`, list completed and remaining tasks, post `finish` with headline starting "Paused" and the resume command (`/plan2code-3-implement specs/<feature>/overview.md`), no `dashboard`, then `stop`.
|
||||
- **quick-task:** say in `finish.body` what was worked out and that nothing was saved unless built; `"command":"/plan2code-quick-task"`.
|
||||
|
||||
- **implement / implement-review:** Implementation Mode's abort, without the
|
||||
"are you sure" (the page asked): the phase stays `[/]`, list completed and
|
||||
remaining tasks, post `finish` with the resume command
|
||||
(`/plan2code-3-implement specs/<feature>/overview.md`), then `stop`. An
|
||||
implement abort is a pause: a headline starting "Paused", no `dashboard`,
|
||||
`stop` at once.
|
||||
- **quick-task:** say in `finish.body` what was worked out, and that nothing was
|
||||
saved unless it was built; `"command": "/plan2code-quick-task"`.
|
||||
|
||||
A mid-build `__dashboard` (the top bar's triangle, `console-stop.md` → "Back
|
||||
to the dashboard, mid-workflow") lands the same way, only on the person's
|
||||
turn. Save exactly as for `__stop` above (an implement phase stays `[/]`), but
|
||||
post no finish and do not `stop`: resume as the dashboard instead, with one
|
||||
terminal line naming what was saved and the resume command.
|
||||
A mid-build `__dashboard` lands the same way: save as for `__stop`, but post no finish and do not `stop`; resume as the dashboard, with one terminal line naming what was saved and the resume command.
|
||||
@@ -3,11 +3,12 @@
|
||||
import path from "node:path";
|
||||
|
||||
import { readJson } from "./files.mjs";
|
||||
import { healthOk, listHandles, pidAlive, terminalLine } from "./sessions.mjs";
|
||||
import { healthOk, listHandles, pidAlive } from "./sessions.mjs";
|
||||
import { chatReplyLines, collectChat, deliverableChat } from "./inbox.mjs";
|
||||
import { pendingWorkspaceChanges } from "./workspace.mjs";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
import { withSubagents, advanceSubagents, serverGone, advanceCursor, advanceWorkspace } from "./cmd-post-wait.mjs";
|
||||
import { withSubagents, advanceSubagents, serverGone, advanceCursor, advanceWorkspace, chatSeqs, lineIfChanged, owedFlags, printOut } from "./cmd-post-wait.mjs";
|
||||
import { duePointers, pointersForSend, rememberPointers } from "./pointers.mjs";
|
||||
|
||||
// The CLI's own pieces, handed over by console.mjs through useCli() before
|
||||
// any command runs: console.mjs runs on import, so it cannot be imported back.
|
||||
@@ -32,13 +33,17 @@ export 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 });
|
||||
const [out, subCursor] = withSubagents(dir, { reply });
|
||||
if (!entries.length && !changes.length && !subCursor) {
|
||||
print({ chat: [] });
|
||||
print({});
|
||||
process.exitCode = 10;
|
||||
return;
|
||||
}
|
||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
||||
const seqs = chatSeqs(entries);
|
||||
const topics = pointersForSend({}, readJson(path.join(dir, "state.json")) || {}, owedFlags(changes, subCursor), entries);
|
||||
const due = duePointers(dir, topics);
|
||||
printOut(dir, { ...out, ...(seqs.length ? { chat: seqs } : {}), ...(due.length ? { read: due } : {}), ...lineIfChanged(dir, handle.url) });
|
||||
rememberPointers(dir, topics);
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
|
||||
@@ -42,21 +42,26 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
|
||||
open [--file <payload.json>] [--workflow <w>] [--title "<t>"] [--spec <dir>]
|
||||
[--session|--resume <sid>] [--no-open] [--idle-ms <ms>]
|
||||
[--loop] (desktop app only; implement or implement-review)
|
||||
Start or resume a session and its server. Prints { ok, sid, session,
|
||||
url, terminalLine }, plus swept { sessions, scratch, handoffs } when
|
||||
old sessions, scratch files or handoffs were removed. Run it FIRST, before
|
||||
url, embed, port, pid, terminalLine }. Run it FIRST, before
|
||||
reading anything: the page shows a starting screen until your
|
||||
first post. --file is optional, and --title defaults to the
|
||||
project's folder name. Also prints workspace: { folders: [{ name,
|
||||
path, description?, original? }], missing? }, the folders this
|
||||
console session reads as context, addressed as @name. The list is
|
||||
remembered per folder and spec in workspaces.json beside looks.json.
|
||||
May also print subagents: { state, revision, max, instruction, strength } and
|
||||
a reply holding only its "Subagents: ..." lines, when a standing
|
||||
instruction (the page's Subagents switch) is owed to you.
|
||||
May also print a reply holding only its "Subagents: ..." lines,
|
||||
when a standing instruction (the page's Subagents switch) is owed
|
||||
to you. workspace only when more than one folder is listed.
|
||||
post --session <sid> --file <patch.json | -> [--wait <N>]
|
||||
Merge a patch into the session. Prints terminalLine while the
|
||||
server is live. Exit 3 = rejected; stderr says why. --wait <N>
|
||||
Merge a patch into the session. Prints { ok, open } (open = the
|
||||
required questions still open), plus terminalLine only when the
|
||||
link changed, read ([path], a topic file to open now) when a
|
||||
pointer is due, and a warning when Quick questions are unanswered.
|
||||
Exit 3 = rejected; stderr names the item id, the field and the
|
||||
field done right. Exit 2 = unreadable patch; stderr gives the
|
||||
line, column and a short excerpt. --wait <N>
|
||||
then waits up to N seconds in the same command (two JSON lines;
|
||||
the exit code is the wait's). The patch may carry settle: true
|
||||
(or a list of item ids) to mark the latest send's cards answered
|
||||
@@ -71,17 +76,20 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
the Subagents tab (help subagents).
|
||||
wait --session <sid> [--seconds <N>]
|
||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||
in the web console"; call again), 20 = server gone (open --resume
|
||||
<sid>), 30 = canceled. Exits 0 and 10 carry terminalLine.
|
||||
Exit 0 may carry "chat" (Quick questions); with no card send it
|
||||
is type: "chat" and actions is empty. Exit 0 may also carry
|
||||
"workspace" (changes since you last heard, each once, with a
|
||||
"Workspace: ..." line in reply); exit 10 counts them as
|
||||
pendingWorkspace, and a change alone never ends a slice.
|
||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
||||
by the person, with its "Subagents: ..." lines last in reply); a
|
||||
setting change alone never ends a slice either. A hop
|
||||
result is on stdout as { reply, session?, read?, ... }, 10 = still
|
||||
waiting ({"waiting":true,"open":N}; call again), 20 = server gone
|
||||
({"gone":true,"fix":"open --resume <sid> --workflow <yours>"}),
|
||||
30 = canceled. terminalLine is printed only when the link changed.
|
||||
reply holds the answers; session lists the "__" session actions
|
||||
whole; read ([path]) names a topic file to open now, once per
|
||||
session per topic and again after a resume. Exit 0 may carry "chat" (the seq of each Quick question
|
||||
handed over, the ids a reply's re needs; the questions are in
|
||||
reply, as "Quick question (<seq>): ..."); with no card send it
|
||||
holds only reply and chat. Workspace changes arrive as
|
||||
"Workspace: ..." lines in reply, each once, and a Subagents
|
||||
setting change as its "Subagents: ..." lines last in reply (a
|
||||
console setting, not typed by the person); a change alone never
|
||||
ends a slice. A hop
|
||||
(__launch, __dashboard, __commit, __changelog) carries resume, the exact
|
||||
open --resume command, and skillFile when installed. Collecting
|
||||
a send sets the page to working; a wait with a question open
|
||||
@@ -89,10 +97,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
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.
|
||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||
messages with it during a console session.
|
||||
Exit 0 = { reply, chat? }, 10 = {} (none), 20 = server gone.
|
||||
terminalLine is "→ Look at the web console: <url>": printed by open and
|
||||
again only when the link changes. End your terminal messages with the
|
||||
latest one during a console session.
|
||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||
Copy a cited note attachment into specs/<idea>/attachments/. Prints
|
||||
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
|
||||
@@ -120,8 +128,12 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
on a refusal.
|
||||
status [--session <sid>] [--all]
|
||||
One session, or (--all) every session on this machine, every project.
|
||||
stop --session <sid> | --all
|
||||
Shut a session's server down. Always post finish first.
|
||||
stop --session <sid> [--force] | --all
|
||||
Shut a session's server down. Always post finish first: a named
|
||||
session with no finish is refused (exit 3, stderr shows the
|
||||
finish to post). --force stops a dead page or an abandoned session
|
||||
anyway (the desktop app passes it on its own shutdowns); --all
|
||||
never asks.
|
||||
|
||||
${workflowLines()}
|
||||
|
||||
@@ -141,6 +153,7 @@ ${workflowLines()}
|
||||
export const HELP_TOPICS = {
|
||||
console: "console.md",
|
||||
building: "building.md",
|
||||
docs: "console-docs.md",
|
||||
"building-review": "building-review.md",
|
||||
finish: "console-finish.md",
|
||||
stop: "console-stop.md",
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
writeWorkspaceCursor,
|
||||
} from "./workspace.mjs";
|
||||
import { readPrHosts, resetSubagentCursor } from "./settings.mjs";
|
||||
import { resetPointers } from "./pointers.mjs";
|
||||
import { WORKFLOWS, isWorkflow } from "./public/skills.js";
|
||||
import { startsClean } from "./public/hops.js";
|
||||
import { snapshot } from "./git-repo.mjs";
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
awaitSubagentSync,
|
||||
withSubagents,
|
||||
advanceSubagents,
|
||||
printOut,
|
||||
} from "./cmd-post-wait.mjs";
|
||||
|
||||
// The CLI's own pieces, handed over by console.mjs through useCli() before
|
||||
@@ -100,6 +102,9 @@ function leavePointer() {
|
||||
// embed mode, and the in-app signal). The app refuses a console without it.
|
||||
const EMBED_API = 1;
|
||||
|
||||
// The only workflows a loop drives (open --loop).
|
||||
const LOOP_WORKFLOWS = ["implement", "implement-review"];
|
||||
|
||||
export async function cmdOpen() {
|
||||
trace("open: start");
|
||||
// A workflow the console does not know is refused first, before the pointer,
|
||||
@@ -109,6 +114,16 @@ export async function cmdOpen() {
|
||||
if (args.workflow !== undefined && !isWorkflow(args.workflow)) {
|
||||
die(`unknown workflow "${args.workflow}"; one of: ${WORKFLOWS.join(", ")}`, 2);
|
||||
}
|
||||
// Loop mode (the desktop app's Implementation Loop) is asked for with
|
||||
// --loop and refused everywhere else, again before the pointer or any
|
||||
// session folder exists.
|
||||
const loopMode = args.loop !== undefined && args.loop !== false;
|
||||
if (loopMode) {
|
||||
if (!inAppSignal()) die("Loop mode runs only inside the Plan2Code desktop app.", 3);
|
||||
if (!LOOP_WORKFLOWS.includes(args.workflow)) {
|
||||
die(`--loop goes only with --workflow ${LOOP_WORKFLOWS.join(" or --workflow ")}`, 2);
|
||||
}
|
||||
}
|
||||
leavePointer();
|
||||
// Under the desktop app the page belongs in the app's window: never the
|
||||
// browser, and (unless a session was named) the app's own session, so one
|
||||
@@ -145,6 +160,9 @@ export async function cmdOpen() {
|
||||
if (!fs.existsSync(dir)) die(`no session "${sid}" to resume`, 1);
|
||||
state = readJson(path.join(dir, "state.json"));
|
||||
if (!state) die(`session "${sid}" has no state`, 1);
|
||||
// A resume starts the reading over: each topic file is named again when
|
||||
// its moment recurs (FR-11), whether or not this is a hop.
|
||||
resetPointers(dir);
|
||||
// A resume can also be a hand-off: the dashboard launches another skill
|
||||
// into its own session, and the first thing that skill needs is for the
|
||||
// page to stop being a dashboard. Letting the flags restate these fields
|
||||
@@ -189,15 +207,44 @@ export async function cmdOpen() {
|
||||
const liveTopics = new Set(s.items.map((i) => i.topic));
|
||||
s.topics = (s.topics || []).filter((t) => liveTopics.has(t.id));
|
||||
}
|
||||
// A launch is a resume that names a workflow and keeps the page put
|
||||
// (`--no-open`: Continue here, a dashboard pick, a pick-up). It starts a
|
||||
// new run, so a real ending from the last one comes down with it. A hop
|
||||
// to another skill already starts clean; this is the same skill again
|
||||
// (Pathfinder into Pathfinder), where the old finish card would freeze
|
||||
// every question the new run asks. A plain `open --resume` (no workflow)
|
||||
// still keeps a real ending, so a re-shared link shows its card.
|
||||
if (s.finish && args.workflow && args["no-open"]) {
|
||||
delete s.finish;
|
||||
delete s.stopWarning;
|
||||
s.agent = { status: "working", since: nowIso() };
|
||||
}
|
||||
if (hop) {
|
||||
s = switchWorkflow(s, {
|
||||
workflow: args.workflow,
|
||||
title: typeof args.title === "string" ? args.title : path.basename(worktree),
|
||||
specDir: args.spec,
|
||||
});
|
||||
} else if (switching) s.workflow = args.workflow;
|
||||
} else if (switching) {
|
||||
s.workflow = args.workflow;
|
||||
// An inline switch (into Review) is not a loop phase.
|
||||
if (!LOOP_WORKFLOWS.includes(args.workflow)) {
|
||||
delete s.loopOutcome;
|
||||
delete s.loopEnd;
|
||||
}
|
||||
}
|
||||
if (args.title) s.title = args.title;
|
||||
if (args.spec) s.specDir = args.spec;
|
||||
// The loop lock follows the flag: --loop locks the page, and a resume
|
||||
// without it (Fix it by hand, from a stop screen) is an ordinary,
|
||||
// unlocked session.
|
||||
if (loopMode) s.loop = { driving: true };
|
||||
else {
|
||||
delete s.loop;
|
||||
// The loop's cards mean nothing without it, and validate() refuses
|
||||
// handledBy outside a loop session, which would wedge every post.
|
||||
s.items = (s.items || []).map(({ handledBy, ...item }) => item);
|
||||
}
|
||||
// Every resume clears the wake-up flag: a server restart, a launch from
|
||||
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
|
||||
// the page because the page cannot write state, and a replay on a return
|
||||
@@ -221,6 +268,8 @@ export async function cmdOpen() {
|
||||
});
|
||||
// Only a freshly opened dashboard plays Planny's wake-up.
|
||||
if (args.workflow === "dashboard") state.wake = true;
|
||||
// Locked from the first frame, before the state is first written.
|
||||
if (loopMode) state.loop = { driving: true };
|
||||
}
|
||||
|
||||
// A first payload's meter and folder reports, as `post` takes them: checked
|
||||
@@ -230,8 +279,9 @@ export async function cmdOpen() {
|
||||
let openReread;
|
||||
let patch = null;
|
||||
if (args.file) {
|
||||
patch = readPatch(args.file);
|
||||
if (!patch) die(`could not read --file ${args.file} as one JSON object`, 2);
|
||||
const read = readPatch(args.file);
|
||||
if (read.error) die(read.error, 2);
|
||||
patch = read.patch;
|
||||
({ run: openRun, folderIssue: openIssue } = patch);
|
||||
delete patch.run;
|
||||
delete patch.folderIssue;
|
||||
@@ -366,10 +416,6 @@ export async function cmdOpen() {
|
||||
const sweptSessions = staleSessions(SESSIONS_DIR, Date.now(), SESSION_MAX_AGE_MS, sid);
|
||||
const sweptScratch = staleScratch(HOME_DIR, Date.now(), SESSION_MAX_AGE_MS);
|
||||
const sweptHandoffs = staleHandoffs(Date.now(), SESSION_MAX_AGE_MS);
|
||||
const swept =
|
||||
sweptSessions.length || sweptScratch.length || sweptHandoffs.length
|
||||
? { swept: { sessions: sweptSessions, scratch: sweptScratch, handoffs: sweptHandoffs } }
|
||||
: {};
|
||||
const sweep = () => {
|
||||
sweepUploads(SESSIONS_DIR, Date.now(), UPLOAD_MAX_AGE_MS, sid).catch(() => {});
|
||||
removeSessions(SESSIONS_DIR, sweptSessions).catch(() => {});
|
||||
@@ -377,32 +423,34 @@ export async function cmdOpen() {
|
||||
removeHandoffs(sweptHandoffs).catch(() => {});
|
||||
};
|
||||
|
||||
// A standing instruction the new agent is owed, as `subagents` and a
|
||||
// `reply` holding only its lines; neither key when nothing is owed.
|
||||
// A standing instruction the new agent is owed, as a `reply` holding only
|
||||
// its lines; no key when nothing is owed.
|
||||
const subagentsOwed = () => {
|
||||
awaitSubagentSync(dir, state.workflow);
|
||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
||||
return [out.subagents ? out : {}, cursor];
|
||||
return [cursor ? out : {}, cursor];
|
||||
};
|
||||
|
||||
// What open tells the agent about the folders: only when there is more than
|
||||
// the folder it started in.
|
||||
const folders = workspace.folders && workspace.folders.length > 1 ? { workspace } : {};
|
||||
|
||||
// Reuse a live server if one is already serving this session.
|
||||
if (existing && (await reusable)) {
|
||||
if (!args["no-open"]) openBrowser(existing.url);
|
||||
const inAppReport = await tellApp(inApp, { url: existing.url, sid, workflow: state.workflow });
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
printOut(dir, {
|
||||
ok: true,
|
||||
sid,
|
||||
session: dir,
|
||||
url: existing.url,
|
||||
embed: EMBED_API,
|
||||
reused: true,
|
||||
...inAppReport,
|
||||
pendingResult: carried,
|
||||
...(carried ? { pendingResult: true } : {}),
|
||||
terminalLine: terminalLine(existing.url),
|
||||
workspace,
|
||||
...folders,
|
||||
...owed,
|
||||
...swept,
|
||||
...remoteWarning(),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
@@ -443,7 +491,7 @@ export async function cmdOpen() {
|
||||
notes.push(`The app did not take the page. Open ${handle.url} in a browser, or press Reload in the app.`);
|
||||
}
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
printOut(dir, {
|
||||
ok: true,
|
||||
sid,
|
||||
session: dir,
|
||||
@@ -452,11 +500,10 @@ export async function cmdOpen() {
|
||||
...inAppReport,
|
||||
port: handle.port,
|
||||
pid: handle.pid,
|
||||
pendingResult: carried,
|
||||
...(carried ? { pendingResult: true } : {}),
|
||||
terminalLine: terminalLine(handle.url),
|
||||
workspace,
|
||||
...folders,
|
||||
...owed,
|
||||
...swept,
|
||||
...(remote.remote ? { remote: remote.remote } : {}),
|
||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||
});
|
||||
@@ -542,7 +589,9 @@ async function startServer(project, worktree, sid, dir, { handoff = true } = {})
|
||||
{
|
||||
// Detached, because harness-managed background tasks get killed at
|
||||
// assorted timeouts and on compaction, which would take the human's
|
||||
// half-finished answers with them. Detached processes are immune.
|
||||
// half-finished answers with them. Detached processes are immune to
|
||||
// that, but not to the desktop app's Job Object on Windows: ending an
|
||||
// agent there ends a server the agent opened (the app's window reconnects).
|
||||
detached: true,
|
||||
// Redirecting stdio to a file is what lets the child outlive us. The
|
||||
// IPC channel is only for the handover, and is closed straight after.
|
||||
|
||||
@@ -14,11 +14,12 @@ import {
|
||||
repoRoots,
|
||||
terminalLine,
|
||||
} from "./sessions.mjs";
|
||||
import { applyPatch, isOpen, proseProblems, resolveDocFiles, resolveDocImages, validate } from "./patches.mjs";
|
||||
import { applyPatch, isOpen, proseProblems, resolveDocFiles, resolveDocImages, rule, validate } from "./patches.mjs";
|
||||
import {
|
||||
CHAT_FILE,
|
||||
chatReplyLines,
|
||||
collectChat,
|
||||
currentConversation,
|
||||
deliverableChat,
|
||||
unansweredChat,
|
||||
readChat,
|
||||
@@ -32,6 +33,7 @@ import { handoffsDir, isHandoffId, markHandoffUsed, readHandoffMeta } from "./ha
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_COMMITS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { blockFor, offered } from "./public/subagents.js";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
import { duePointers, pointersForSend, rememberPointers } from "./pointers.mjs";
|
||||
|
||||
// The CLI's own pieces, handed over by console.mjs through useCli() before
|
||||
// any command runs: console.mjs runs on import, so it cannot be imported back.
|
||||
@@ -40,31 +42,132 @@ export function useCli(cli) {
|
||||
({ args, print, die, mustSession, sessionProject } = cli);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- printed line */
|
||||
|
||||
// The link line is printed by `open` and then only when it changes (a new URL
|
||||
// after a restart or a resume). What was last printed lives in the session
|
||||
// folder, never in state.json, which rides every frame to the page.
|
||||
const PRINTED_FILE = "printed.json";
|
||||
|
||||
export function printedLine(dir) {
|
||||
const saved = readJson(path.join(dir, PRINTED_FILE), {});
|
||||
return saved && typeof saved.terminalLine === "string" ? saved.terminalLine : "";
|
||||
}
|
||||
|
||||
export function rememberLine(dir, line) {
|
||||
try {
|
||||
writeJsonAtomic(path.join(dir, PRINTED_FILE), { terminalLine: line });
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// `{ terminalLine }` when the line for this link differs from the one last
|
||||
// printed, else `{}`. Printing is printOut(), which stores the line after the
|
||||
// print, the order advanceCursor() uses: a kill in between repeats a line,
|
||||
// never loses one.
|
||||
export function lineIfChanged(dir, url) {
|
||||
if (!url) return {};
|
||||
const line = terminalLine(url);
|
||||
return line === printedLine(dir) ? {} : { terminalLine: line };
|
||||
}
|
||||
|
||||
export function printOut(dir, out) {
|
||||
print(out);
|
||||
if (typeof out.terminalLine === "string") rememberLine(dir, out.terminalLine);
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- post */
|
||||
|
||||
// A patch from a file, or from stdin with `--file -`: a heredoc piped into
|
||||
// the command saves the agent writing a file first, one tool call a turn.
|
||||
// A file PowerShell wrote comes with a BOM (Out-File / Set-Content in 5.1) or
|
||||
// in UTF-16 (its `>`), and both are the documented Windows route, so both read.
|
||||
// Indented and minified JSON read alike. Returns `{ patch }`, or `{ error }`
|
||||
// saying what is wrong and where, for the caller to print with exit 2.
|
||||
export function readPatch(file) {
|
||||
let text;
|
||||
try {
|
||||
const buf = fs.readFileSync(file === "-" ? 0 : path.resolve(file));
|
||||
let text;
|
||||
if (buf[0] === 0xff && buf[1] === 0xfe) text = buf.subarray(2).toString("utf16le");
|
||||
else if (buf[0] === 0xfe && buf[1] === 0xff) text = Buffer.from(buf.subarray(2)).swap16().toString("utf16le");
|
||||
else text = buf.toString("utf8");
|
||||
// A patch is one JSON object: an array, string or number would merge
|
||||
// into the state as junk keys ("0", "1"...) and still report ok.
|
||||
const patch = JSON.parse(text.replace(/^\uFEFF/, ""));
|
||||
return patch && typeof patch === "object" && !Array.isArray(patch) ? patch : null;
|
||||
} catch {
|
||||
return null;
|
||||
} catch (e) {
|
||||
return { error: `could not read --file ${file}: ${e.code === "ENOENT" ? "no such file" : e.message}` };
|
||||
}
|
||||
text = text.replace(/^\uFEFF/, "");
|
||||
if (!text.trim()) return { error: "the patch is empty (nothing arrived on stdin? use a quoted heredoc, <<'EOF')" };
|
||||
let patch;
|
||||
try {
|
||||
patch = JSON.parse(text);
|
||||
} catch (e) {
|
||||
return { error: parseErrorAt(text, e.message) };
|
||||
}
|
||||
// A patch is one JSON object: an array, string or number would merge
|
||||
// into the state as junk keys ("0", "1"...) and still report ok.
|
||||
if (!patch || typeof patch !== "object" || Array.isArray(patch)) {
|
||||
const what = patch === null ? "null" : Array.isArray(patch) ? "an array" : `a ${typeof patch}`;
|
||||
return { error: `the patch must be one JSON object ({...}), not ${what}` };
|
||||
}
|
||||
return { patch };
|
||||
}
|
||||
|
||||
// Whether `prefix` could still grow into valid JSON: it parses, or it only
|
||||
// fails by stopping short.
|
||||
function viablePrefix(prefix) {
|
||||
try {
|
||||
JSON.parse(prefix);
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (/end of JSON input|Unterminated/.test(e.message)) return true;
|
||||
const at = /(?:in|after) JSON at position (\d+)/.exec(e.message);
|
||||
return Boolean(at) && Number(at[1]) >= prefix.length;
|
||||
}
|
||||
}
|
||||
|
||||
// Where JSON.parse gave up, as a 0-based character index. Node 18 and Node 20+
|
||||
// word the message differently (and some messages carry no position at all),
|
||||
// so the message's position is used when there is one and the spot is found
|
||||
// by search when there is not.
|
||||
function errorIndex(text, message) {
|
||||
const at = /(?:in|after) JSON at position (\d+)/.exec(message);
|
||||
if (at) return Math.min(Number(at[1]), text.length);
|
||||
const lc = /position \d+ \(line (\d+) column (\d+)\)/.exec(message);
|
||||
if (lc) {
|
||||
const lines = text.split("\n");
|
||||
let index = 0;
|
||||
for (let i = 0; i < Number(lc[1]) - 1 && i < lines.length; i++) index += lines[i].length + 1;
|
||||
return Math.min(index + Number(lc[2]) - 1, text.length);
|
||||
}
|
||||
let lo = 0;
|
||||
let hi = text.length;
|
||||
while (lo < hi) {
|
||||
const mid = Math.ceil((lo + hi) / 2);
|
||||
if (viablePrefix(text.slice(0, mid))) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
// `line L, column C: <what the parser said>`, then up to 30 characters either
|
||||
// side of the spot (newlines shown as \n) and a caret under it.
|
||||
export function parseErrorAt(text, message) {
|
||||
const index = errorIndex(text, message);
|
||||
const before = text.slice(0, index).split("\n");
|
||||
const line = before.length;
|
||||
const column = before[before.length - 1].length + 1;
|
||||
const show = (t) => t.replaceAll("\r", "").replaceAll("\n", "\\n");
|
||||
const left = show(text.slice(Math.max(0, index - 30), index));
|
||||
const right = show(text.slice(index, index + 31));
|
||||
const said = message
|
||||
.replace(/ in JSON at position \d+( \(line \d+ column \d+\))?/, "")
|
||||
.replace(/,\s.*is not valid JSON$/s, "")
|
||||
.replace(/ at position \d+.*$/, "");
|
||||
return `line ${line}, column ${column}: ${said}\n${left}${right}\n${" ".repeat(left.length)}^`;
|
||||
}
|
||||
|
||||
export function failValidation(problems) {
|
||||
process.stderr.write("console: the payload was rejected, nothing was written.\n");
|
||||
for (const p of problems) process.stderr.write(" - " + p + "\n");
|
||||
// A problem that runs over several lines stays under its own bullet.
|
||||
for (const p of problems) process.stderr.write(" - " + String(p).replaceAll("\n", "\n ") + "\n");
|
||||
// exitCode, not exit(): the agent has to read these lines to fix the patch,
|
||||
// and process.exit() can truncate a pipe Node has not flushed.
|
||||
process.exitCode = 3;
|
||||
@@ -87,8 +190,9 @@ function postOnce() {
|
||||
const dir = mustSession();
|
||||
const file = args.file;
|
||||
if (!file) die("post needs --file <path to a JSON patch>", 2);
|
||||
let patch = readPatch(file);
|
||||
if (!patch) die(`could not read --file ${file} as one JSON object`, 2);
|
||||
const read = readPatch(file);
|
||||
if (read.error) die(read.error, 2);
|
||||
let patch = read.patch;
|
||||
|
||||
const statePath = path.join(dir, "state.json");
|
||||
const before = readJson(statePath);
|
||||
@@ -100,6 +204,13 @@ function postOnce() {
|
||||
die(e.message, 3);
|
||||
}
|
||||
|
||||
// A chat reply names the conversation it answers; the agent is no longer
|
||||
// handed the entries, so a missing one means the current conversation.
|
||||
if (patch.chat && Array.isArray(patch.chat.replies)) {
|
||||
const { conversation } = currentConversation(readChat(dir));
|
||||
patch.chat.replies = patch.chat.replies.map((r) => (r && typeof r === "object" && !Array.isArray(r) && r.conversation === undefined ? { ...r, conversation } : r));
|
||||
}
|
||||
|
||||
// Meter and folder reports go to the ledger, never into state.json. Checked
|
||||
// here, before anything is written: a rejected post appends nothing.
|
||||
const { run, folderIssue } = patch;
|
||||
@@ -162,14 +273,18 @@ function postOnce() {
|
||||
const open = next.items.filter((i) => isOpen(i) && i.required !== false && i.kind !== "notice").length;
|
||||
// Only a live server's link: no handle, no line, never a dead link.
|
||||
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === path.basename(dir));
|
||||
print({
|
||||
// The first patch carrying documents names the docs topic file; a refused
|
||||
// post returned above and recorded nothing.
|
||||
const topics = Array.isArray(patch.docs) && patch.docs.length ? ["docs"] : [];
|
||||
const due = duePointers(dir, topics);
|
||||
printOut(dir, {
|
||||
ok: true,
|
||||
items: next.items.length,
|
||||
open,
|
||||
phase: next.phase,
|
||||
...(due.length ? { read: due } : {}),
|
||||
...unansweredNote(dir, next),
|
||||
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
|
||||
...(handle && handle.url ? lineIfChanged(dir, handle.url) : {}),
|
||||
});
|
||||
rememberPointers(dir, topics);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -179,14 +294,14 @@ function postOnce() {
|
||||
* git session. state.git itself is the console's own: a patch never carries it.
|
||||
*/
|
||||
export function liftReread(patch, workflow) {
|
||||
if (Object.hasOwn(patch, "git")) die("state.git is the console's own: post reread instead", 3);
|
||||
if (Object.hasOwn(patch, "git")) die(rule("", "git", "is the console's own state; post reread instead", { reread: true }), 3);
|
||||
const { reread } = patch;
|
||||
delete patch.reread;
|
||||
if (reread === undefined) return undefined;
|
||||
const flagOnly =
|
||||
reread && typeof reread === "object" && !Array.isArray(reread) && Object.keys(reread).length === 1 && typeof reread.refreshFailed === "boolean";
|
||||
if (reread !== true && !flagOnly) die("reread must be true or { refreshFailed: true|false }", 3);
|
||||
if (workflow !== "git") die("reread only goes with the git workflow", 3);
|
||||
if (reread !== true && !flagOnly) die(rule("", "reread", "must be true or { refreshFailed: true|false }", { reread: true }), 3);
|
||||
if (workflow !== "git") die(rule("", "reread", "only goes with the git workflow", { reread: null }), 3);
|
||||
return reread;
|
||||
}
|
||||
|
||||
@@ -218,16 +333,17 @@ export function ledgerFromPost(dir, run, issue, workflow) {
|
||||
const lines = [];
|
||||
if (run !== undefined) {
|
||||
const event = run && typeof run === "object" ? run.event : undefined;
|
||||
if (!RUN_EVENTS.has(event)) die(`run: unknown event "${event}"`, 3);
|
||||
if (typeof run.id !== "string" || !run.id.trim()) die("run: id required", 3);
|
||||
const runRight = { run: { event: "implement-phase", id: "phase-2" } };
|
||||
if (!RUN_EVENTS.has(event)) die(rule("", "run", `unknown event "${event}" (one of: ${[...RUN_EVENTS].join(", ")})`, runRight), 3);
|
||||
if (typeof run.id !== "string" || !run.id.trim()) die(rule("", "run", "needs an id", runRight), 3);
|
||||
if (run.tasks !== undefined) {
|
||||
if (!TASK_EVENTS.has(event)) die(`run: tasks only goes with ${[...TASK_EVENTS].join(" or ")}`, 3);
|
||||
if (!isTaskCount(run.tasks)) die(`run: tasks must be a whole number from 1 to ${MAX_TASKS}`, 3);
|
||||
if (!TASK_EVENTS.has(event)) die(rule("", "run", `tasks only goes with ${[...TASK_EVENTS].join(" or ")}`, { run: { event: [...TASK_EVENTS][0], id: "phase-2", tasks: 9 } }), 3);
|
||||
if (!isTaskCount(run.tasks)) die(rule("", "run", `tasks must be a whole number from 1 to ${MAX_TASKS}`, { run: { event, id: run.id, tasks: 9 } }), 3);
|
||||
}
|
||||
if (run.commits !== undefined) {
|
||||
if (event !== "git-commits") die("run: commits only goes with git-commits", 3);
|
||||
if (event !== "git-commits") die(rule("", "run", "commits only goes with git-commits", { run: { event: "git-commits", id: "commits-1", commits: 2 } }), 3);
|
||||
const ok = Number.isInteger(run.commits) && run.commits >= 1 && run.commits <= MAX_COMMITS;
|
||||
if (!ok) die(`run: commits must be a whole number from 1 to ${MAX_COMMITS}`, 3);
|
||||
if (!ok) die(rule("", "run", `commits must be a whole number from 1 to ${MAX_COMMITS}`, { run: { event, id: run.id, commits: 2 } }), 3);
|
||||
}
|
||||
lines.push({
|
||||
kind: "run",
|
||||
@@ -242,8 +358,8 @@ export function ledgerFromPost(dir, run, issue, workflow) {
|
||||
const text = (v) => typeof v === "string" && v.trim() !== "";
|
||||
const ok =
|
||||
issue && typeof issue === "object" && text(issue.name) && text(issue.reason) && (issue.hint === undefined || text(issue.hint));
|
||||
if (!ok) die("folderIssue must be { name, reason, hint? }, each a non-empty string", 3);
|
||||
const problems = proseProblems(JSON.stringify([issue.reason, issue.hint || ""]), "folderIssue");
|
||||
if (!ok) die(rule("", "folderIssue", "must be { name, reason, hint? }, each a non-empty string", { folderIssue: { name: "api", reason: "..." } }), 3);
|
||||
const problems = [...proseProblems(issue.reason, "folderIssue reason"), ...(issue.hint ? proseProblems(issue.hint, "folderIssue hint") : [])];
|
||||
if (problems.length) die(problems.join("\n "), 3);
|
||||
lines.push({
|
||||
kind: "folder-issue",
|
||||
@@ -282,7 +398,7 @@ export async function cmdWait() {
|
||||
const existing = readJson(resultPath);
|
||||
if (existing && !existing.consumedAt) return consume(dir, resultPath, existing, liveUrl(), pendingChat());
|
||||
const earlyChat = pendingChat();
|
||||
if (earlyChat.length) return deliverChat(dir, sid, earlyChat, liveUrl());
|
||||
if (earlyChat.length) return deliverChat(dir, earlyChat, liveUrl());
|
||||
markWaiting(dir);
|
||||
|
||||
// A stat every 50ms, and a read only when the file has moved. The old tick
|
||||
@@ -324,7 +440,7 @@ export async function cmdWait() {
|
||||
if (chatStamp !== chatSeen) {
|
||||
chatSeen = chatStamp;
|
||||
const entries = pendingChat();
|
||||
if (entries.length) return deliverChat(dir, sid, entries, liveUrl());
|
||||
if (entries.length) return deliverChat(dir, entries, liveUrl());
|
||||
}
|
||||
|
||||
// The health check runs beside the polling, never in its way: awaited
|
||||
@@ -356,26 +472,15 @@ export async function cmdWait() {
|
||||
}
|
||||
|
||||
const state = readJson(path.join(dir, "state.json")) || {};
|
||||
const items = (state.items || []).filter((i) => i.required !== false && i.kind !== "notice");
|
||||
const answered = items.filter((i) => !isOpen(i)).length;
|
||||
const draft = readJson(path.join(dir, "draft.json"), {});
|
||||
const staged = Object.keys(draft.staged || {}).length;
|
||||
const open = (state.items || []).filter((i) => i.required !== false && i.kind !== "notice" && isOpen(i)).length;
|
||||
const handle = listHandles(project).find((h) => h.sid === sid);
|
||||
|
||||
print({
|
||||
status: "waiting",
|
||||
sid,
|
||||
elapsed: fmtMs(Date.now() - Date.parse(state.created || nowIso())),
|
||||
answered,
|
||||
total: items.length,
|
||||
staged,
|
||||
url: handle ? handle.url : "",
|
||||
message: "Waiting on your answer in the web console",
|
||||
next: "NOT FINISHED, do not end your turn or write a summary: relay the message in one line, then run this same wait command again right now. Repeat until the exit code is not 10.",
|
||||
// A workspace change alone never ends a slice: it rides on the next send.
|
||||
printOut(dir, {
|
||||
waiting: true,
|
||||
open,
|
||||
...unansweredNote(dir, state),
|
||||
// A workspace change alone never ends a slice: it rides on the next send.
|
||||
pendingWorkspace: pendingWorkspaceChanges(dir).length,
|
||||
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
|
||||
...(handle && handle.url ? lineIfChanged(dir, handle.url) : {}),
|
||||
});
|
||||
process.exitCode = 10;
|
||||
}
|
||||
@@ -390,25 +495,24 @@ function unansweredNote(dir, state) {
|
||||
}
|
||||
|
||||
export function serverGone(sid) {
|
||||
return {
|
||||
status: "server-gone",
|
||||
sid,
|
||||
message: "The console server is not running. Start it again with `open --resume <sid> --workflow <yours>` (it gets a new link: give it to the person; without --no-open the browser opens it), then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
|
||||
};
|
||||
return { gone: true, fix: `open --resume ${sid} --workflow <yours>` };
|
||||
}
|
||||
|
||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||
function deliverChat(dir, sid, entries, url) {
|
||||
const [withWs, changes] = withWorkspace(dir, {
|
||||
type: "chat",
|
||||
at: nowIso(),
|
||||
sid,
|
||||
actions: [],
|
||||
chat: entries,
|
||||
reply: chatReplyLines(entries),
|
||||
});
|
||||
// The seq numbers of the Quick questions handed over: the ids a `chat.replies`
|
||||
// entry's `re` needs. The questions themselves travel in `reply`.
|
||||
export function chatSeqs(entries) {
|
||||
return entries.filter((e) => e.kind === "message").map((e) => e.seq);
|
||||
}
|
||||
|
||||
// Quick questions and nothing else: an ordinary exit 0 with no card send.
|
||||
function deliverChat(dir, entries, url) {
|
||||
const [withWs, changes] = withWorkspace(dir, { reply: chatReplyLines(entries) });
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
const seqs = chatSeqs(entries);
|
||||
const topics = pointersForSend({}, readJson(path.join(dir, "state.json")) || {}, owedFlags(changes, subCursor), entries);
|
||||
const due = duePointers(dir, topics);
|
||||
printOut(dir, { ...out, ...(seqs.length ? { chat: seqs } : {}), ...(due.length ? { read: due } : {}), ...lineIfChanged(dir, url) });
|
||||
rememberPointers(dir, topics);
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
@@ -416,12 +520,20 @@ function deliverChat(dir, sid, entries, url) {
|
||||
}
|
||||
|
||||
// The workspace changes the agent is owed, added to what it is about to read:
|
||||
// the list as `workspace`, and one line each at the end of `reply`.
|
||||
function withWorkspace(dir, out) {
|
||||
// one `Workspace:` line each at the end of `reply`, in words only. The second
|
||||
// value is the changes, whose length is the "a change happened" flag
|
||||
// (see owedFlags()); the cursor moves after the print.
|
||||
export function withWorkspace(dir, out) {
|
||||
const changes = pendingWorkspaceChanges(dir);
|
||||
if (!changes.length) return [out, changes];
|
||||
const reply = [out.reply, ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
return [{ ...out, workspace: changes, reply }, changes];
|
||||
return [{ ...out, reply }, changes];
|
||||
}
|
||||
|
||||
// Whether the standing instructions in a reply carried a change, for the
|
||||
// pointers that name a topic file when one is delivered.
|
||||
export function owedFlags(changes, subCursor) {
|
||||
return { workspaceChanged: changes.length > 0, subagentsChanged: Boolean(subCursor) };
|
||||
}
|
||||
|
||||
// Print first, then this, as with the chat cursor: a kill in between can only
|
||||
@@ -454,7 +566,7 @@ export function awaitSubagentSync(dir, workflow) {
|
||||
}
|
||||
|
||||
// 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,
|
||||
// its lines last in `reply` (in words only), 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
|
||||
@@ -467,7 +579,7 @@ export function withSubagents(dir, out) {
|
||||
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];
|
||||
return [{ ...out, reply }, block.cursor];
|
||||
}
|
||||
|
||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
||||
@@ -507,15 +619,33 @@ export function advanceCursor(dir, entries) {
|
||||
*/
|
||||
function consume(dir, resultPath, result, url, chat = []) {
|
||||
const collected = { ...result, consumedAt: nowIso() };
|
||||
// The link, any chat and any workspace change ride on what the agent reads,
|
||||
// never on result.json itself.
|
||||
const withChat = { ...collected, chat };
|
||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||
// What the agent reads is a trimmed view: `reply` (the card answers, any
|
||||
// Quick question and any Workspace or Subagents line), the `__` session
|
||||
// actions and the hop fields `reply` cannot carry. result.json keeps the
|
||||
// whole send; the link, chat and standing lines never go into it.
|
||||
const withChat = { reply: chat.length ? [result.reply, chatReplyLines(chat)].filter(Boolean).join("\n") : result.reply };
|
||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
const hop = hopFor(path.basename(dir), result);
|
||||
const session = sessionActions(result);
|
||||
const seqs = chatSeqs(chat);
|
||||
// Read before markWorking() below: a __dashboard asks for the finish topic
|
||||
// or the stop topic by whether a finish is up as the person pressed it.
|
||||
const stateNow = readJson(path.join(dir, "state.json")) || {};
|
||||
const topics = pointersForSend(result, stateNow, owedFlags(changes, subCursor), chat);
|
||||
const due = duePointers(dir, topics);
|
||||
markPickedUp(result);
|
||||
print({ ...out, ...hop, ...handoffFor(result), ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
printOut(dir, {
|
||||
...(out.reply ? { reply: out.reply } : {}),
|
||||
...(session ? { session } : {}),
|
||||
...hop,
|
||||
...handoffFor(result),
|
||||
...(seqs.length ? { chat: seqs } : {}),
|
||||
...(due.length ? { read: due } : {}),
|
||||
...unansweredNote(dir, stateNow),
|
||||
...lineIfChanged(dir, url),
|
||||
});
|
||||
rememberPointers(dir, topics);
|
||||
try {
|
||||
writeJsonAtomic(resultPath, collected);
|
||||
} catch {}
|
||||
@@ -632,6 +762,21 @@ function markPickedUp(result) {
|
||||
// data off disk or the wire, so the name is checked here and not trusted.
|
||||
const SAFE_SPEC = /^specs\/[^/\\"'`$;&|<>(){}*?!#~\r\n]+$/;
|
||||
|
||||
// The send's `__` actions, whole, for the agent: the docs dispatch on them by
|
||||
// `i`. A `type` that only repeats `i` ("__stop" and "stop") is left out. The
|
||||
// card answers, comments and skips are already in `reply`.
|
||||
export function sessionActions(result) {
|
||||
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
|
||||
const kept = actions
|
||||
.filter((a) => a && typeof a.i === "string" && a.i.startsWith("__"))
|
||||
.map((a) => {
|
||||
if (a.type !== a.i.slice(2)) return a;
|
||||
const { type, ...rest } = a;
|
||||
return rest;
|
||||
});
|
||||
return kept.length ? kept : undefined;
|
||||
}
|
||||
|
||||
function hopFor(sid, result) {
|
||||
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
|
||||
const action = actions.find((a) => a && Object.hasOwn(HOP_ACTIONS, a.type) && typeof a.i === "string" && a.i.startsWith("__"));
|
||||
@@ -668,10 +813,3 @@ function ledgerAnswers(dir, result) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function fmtMs(ms) {
|
||||
if (!Number.isFinite(ms) || ms < 0) return "0s";
|
||||
const s = Math.round(ms / 1000);
|
||||
if (s < 60) return `${s}s`;
|
||||
const m = Math.floor(s / 60);
|
||||
return `${m}m ${s % 60}s`;
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import path from "node:path";
|
||||
import { SESSIONS_DIR, appendEvent, readJson } from "./files.mjs";
|
||||
import { attachmentName, healthOk, listHandles, pidAlive, projectRoot, repoRoots, sessionDir } from "./sessions.mjs";
|
||||
import { removeSpec } from "./scan.mjs";
|
||||
import { isOpen } from "./patches.mjs";
|
||||
import { isOpen, rule } from "./patches.mjs";
|
||||
import { pendingChatCount } from "./inbox.mjs";
|
||||
import { forgetWorkspace, specKey } from "./workspace.mjs";
|
||||
import { newHandoff, removeHandoff } from "./handoffs.mjs";
|
||||
@@ -249,6 +249,24 @@ export async function cmdStop() {
|
||||
// the command runs from.
|
||||
const named = !args.all && (args.session || args.sid) ? sessionDir(path.basename(args.session || args.sid)) : null;
|
||||
const project = named && fs.existsSync(named) ? sessionProject(named) : projectRoot();
|
||||
// A stop with no finish posted leaves the page without an ending (FR-12).
|
||||
// Refused for one named session unless --force; --all keeps its behavior.
|
||||
if (named && !args.force) {
|
||||
const state = readJson(path.join(named, "state.json"));
|
||||
if (state && !state.finish) {
|
||||
process.stderr.write(
|
||||
rule(
|
||||
"",
|
||||
"finish",
|
||||
"this session has no finish posted, so the page would be left without an ending. Post one first, then stop",
|
||||
{ finish: { headline: "Paused: <what is saved>", command: "/<the skill to resume>" } },
|
||||
) + `. To stop a dead page or an abandoned session anyway: stop --session ${path.basename(named)} --force
|
||||
`,
|
||||
);
|
||||
process.exitCode = 3;
|
||||
return;
|
||||
}
|
||||
}
|
||||
const handles = listHandles(project);
|
||||
const targets = args.all
|
||||
? handles
|
||||
|
||||
@@ -1,17 +1,7 @@
|
||||
# Keeping Attachments
|
||||
|
||||
Part of the web console contract (`console.md`). Read when a file you write
|
||||
under `specs/<idea>/` cites a note's attachment.
|
||||
Read when a file you write under `specs/<idea>/` cites a note's attachment. Attachments are swept with the session, so keep one first:
|
||||
|
||||
Note attachments are swept with the session. Before a file under `specs/<idea>/`
|
||||
cites one, keep it:
|
||||
|
||||
```
|
||||
node "<CONSOLE>" keep --session <sid> --upload <path> --name <name> --spec specs/<idea> --from <the file you are writing>
|
||||
```
|
||||
|
||||
It prints `{ ok, path, link, image, reused }`: paste `link` as it is
|
||||
(`` for an image, `[name](link)` otherwise) and name the kept file
|
||||
in your next update. Uncited and Quick-question attachments stay where they
|
||||
are. Exit 3 means refused: say so, link nothing.
|
||||
`node "<CONSOLE>" keep --session <sid> --upload <path> --name <name> --spec specs/<idea> --from <the file you are writing>`
|
||||
|
||||
It prints `{ok,path,link,image,reused}`: paste `link` as given (`` for an image, `[name](link)` otherwise) and name the kept file in your next update. Uncited and Quick-question attachments stay where they are. Exit 3 means refused: say so and link nothing.
|
||||
+39
-150
@@ -1,170 +1,59 @@
|
||||
# Quick Questions on the Web Console
|
||||
# Quick Questions (the Ask tab)
|
||||
|
||||
Part of the web console contract (`console.md`). Read the first time `wait` or
|
||||
`chat` hands you a Quick question.
|
||||
The console points here the first time a Quick question reaches you. The person can ask anything on the Ask tab at any time, about this project's files or in general, without waiting for a card. A message never blocks a card send and a card send never blocks a message.
|
||||
|
||||
The page has an **Ask** tab, always the last one, on every workflow. There the
|
||||
person can ask anything, about this project's files or in general, at any
|
||||
time, without waiting for a card. Their messages reach you at your next
|
||||
check-in, through the `wait` you already run (and, in a build, the instant
|
||||
`chat` check). Chat rides its own channel: a message never blocks a card send,
|
||||
and a card send never blocks a message. The page handles its own refusals, so
|
||||
you never see them: `too-long` past 4,000 characters, `limit` after 10
|
||||
messages, `offline` when no agent has checked in for a few minutes (a finish alone does
|
||||
not end the chat: you may still be waiting on its buttons),
|
||||
`stale` after a new conversation started.
|
||||
## How they arrive
|
||||
|
||||
## How chat arrives
|
||||
`wait` exit 0 (or `chat`) carries them in `reply`, after the card lines, plus `chat`: the seq number of each question, the ids your replies need as `re`.
|
||||
|
||||
- `wait` exit `0` may carry `chat: [...]` beside `actions`, or, when no card
|
||||
was sent, be `type: "chat"` with `actions: []`. No exit code changes.
|
||||
- `reply` gains one block per entry after the card lines:
|
||||
```
|
||||
Quick question (12): Where does the export go?
|
||||
About: Export format
|
||||
Image: /home/sam/.plan2code/console/sessions/<sid>/uploads/3f2b9c1e.jpg (shot.png)
|
||||
File: /home/sam/.plan2code/console/sessions/<sid>/uploads/9e4b2d7a.json (config.json)
|
||||
Declined (14): edit r7
|
||||
Note: keep the old name working too
|
||||
Approved (15): edit r9
|
||||
New conversation started. Treat earlier chat as closed.
|
||||
```
|
||||
|
||||
```
|
||||
Quick question: Where does the export go?
|
||||
About: Export format
|
||||
Image: /home/sam/.plan2code/console/sessions/<sid>/uploads/3f2b9c1e.jpg (shot.png)
|
||||
File: /home/sam/.plan2code/console/sessions/<sid>/uploads/9e4b2d7a.json (config.json)
|
||||
Declined: edit r7
|
||||
Note: keep the old name working too (only a decline carries one)
|
||||
New conversation started. Treat earlier chat as closed.
|
||||
```
|
||||
|
||||
Typed text past its first line is indented, so only a real entry ever
|
||||
starts a line.
|
||||
- Each `chat` entry carries `seq`, `conversation` and `kind`: `message`
|
||||
(`text`, optional `about`, `images` and `files`), `decision` (`re`,
|
||||
`decision` `approve` or `decline`, optional `text`) or `reset`.
|
||||
- `about` is set only when the person attached it with **+ Add context**. The
|
||||
page never adds one on its own, so a message without it is a general
|
||||
question, not one about the card on screen.
|
||||
- Open every `Image:` and `File:` path with your file-read tool before you
|
||||
answer, as for notes.
|
||||
- `node "<CONSOLE>" chat --session <sid>` checks right now and never sleeps:
|
||||
exit `0` with `{ chat, reply, terminalLine }`, `10` with `{ chat: [] }` when
|
||||
nothing is waiting, `20` when the server is gone. It never reads or collects
|
||||
card sends; those stay with `wait`.
|
||||
- Open every `Image:` and `File:` path with your file-read tool before you answer.
|
||||
- `About:` is set only when the person attached that context; without it the question is general, not about the card on screen.
|
||||
- After "New conversation started" treat earlier chat as closed and do not raise it unless they do.
|
||||
- `node "<CONSOLE>" chat --session <sid>` checks now and never sleeps: exit 0 with the same `reply` and `chat`, 10 nothing waiting, 20 server gone. It never reads card sends.
|
||||
|
||||
## Answering
|
||||
|
||||
**Every message gets a reply, always.** The Ask tab is the person talking to
|
||||
you, and the page shows "working on the answer" until a reply lands. Never
|
||||
leave one unanswered, whatever it asks and whatever mid-task you are in. When
|
||||
a message asks you to do something, do it if you can, then say what happened; if
|
||||
you will not, the reply says so and why. `post` and `wait` print
|
||||
`unansweredChat` with a `warning` for every message handed over and not yet
|
||||
replied to: treat that as a stop-and-reply.
|
||||
**Every message gets a reply**, whatever it asks and whatever you are mid-task on. `post` and `wait` print `unansweredChat` with a `warning` for each message not yet replied to: stop and reply. When a message asks you to do something, do it if you can, then say what happened; if you will not, say so and why.
|
||||
|
||||
1. Handle any card answers first, under the workflow's own rules.
|
||||
2. Write the chat replies, in inbox order.
|
||||
3. Send **one** `post` with the card updates and `chat: { replies: [...] }`
|
||||
(`chat.replies`).
|
||||
2. Write the replies, in order.
|
||||
3. Send one `post` with the card updates and the replies.
|
||||
|
||||
```jsonc
|
||||
{ "chat": { "replies": [
|
||||
{ "re": 12, "conversation": 3,
|
||||
"md": "The export is written by `src/export.js`, into `out/`." }
|
||||
] } }
|
||||
```
|
||||
`{"chat":{"replies":[{"re":12,"md":"The export is written by `src/export.js`, into `out/`."}]}}`
|
||||
|
||||
- `re` is the message's `seq`, `conversation` is copied from the entry, `md` is
|
||||
markdown. `id` is optional: left out, it is `r<re>`. Give one only when you
|
||||
send two replies to the same message.
|
||||
- Replies merge by `id`, so re-posting the same reply after a repeated
|
||||
delivery replaces it (unlike `thread`, which appends).
|
||||
- Print one terminal line per exchange: `Quick question: <first ~60 characters
|
||||
of the question> — answered in the console`.
|
||||
- Answer questions about the project by reading files and read-only lookups
|
||||
(search, `git log`, reading files); run no other commands.
|
||||
- Questions about what a Plan2Code skill does, asks or writes: read that
|
||||
skill's `SKILL.md` (`~/.agents/skills/<skill>/SKILL.md`, or the table "What
|
||||
each skill reads and writes" in `~/.agents/skills/plan2code/SKILL.md`)
|
||||
before answering. Never answer from menu text, card blurbs or memory. Name
|
||||
files exactly as the skill does; if the skill does not say, say you do not
|
||||
know.
|
||||
- When `about` is set, answer from that context: the card, doc section or
|
||||
spec the person was looking at.
|
||||
- `re` is the message's seq; `md` is markdown and non-empty. `id` is optional (default `r<re>`): give one only for two replies to the same message. Replies merge by `id`, so re-posting the same reply replaces it.
|
||||
- Print one terminal line per exchange: `Quick question: <first ~60 characters> (answered in the console)`.
|
||||
- Answer questions about the project from files and read-only lookups (search, `git log`, reading); run nothing else.
|
||||
- For what a Plan2Code skill does, asks or writes, read that skill's `SKILL.md` (`~/.agents/skills/<skill>/SKILL.md`, or the table "What each skill reads and writes" in `~/.agents/skills/plan2code/SKILL.md`) first. Name files exactly as it does; if it does not say, say you do not know.
|
||||
- With `About:`, answer from that context.
|
||||
|
||||
## Prompts to carry away
|
||||
## A prompt to carry away
|
||||
|
||||
Some questions are really a new task: the person asks for "a prompt", or the
|
||||
right answer is work for a separate Plan, Quick Task or another skill rather
|
||||
than something to do inside this session. Do not start that work here and do
|
||||
not make them retype your answer. Reply with the explanation first, then ONE
|
||||
self-contained prompt in a fenced block with no info string. The page draws
|
||||
every fenced block with a **Copy** button, so the person copies it into a new
|
||||
conversation.
|
||||
When the right answer is a separate task (a new Plan, Quick Task or another skill), explain first, then give ONE self-contained prompt in a fenced block with no info string (the page adds a **Copy** button). The block:
|
||||
|
||||
A good prompt block:
|
||||
|
||||
- opens with plain prose, never a command word. A block whose first line looks
|
||||
like a terminal command (`git`, `npm`, `node`, `rm` and the like, or `#!`)
|
||||
gets the muted "paste it into the Ask tab" hint, which is wrong for a prompt.
|
||||
The check is case-insensitive and also catches everyday verbs that are shell
|
||||
commands (Make, Go, Source, Export, Service, Cat, Echo, Zip, Tar, Cd, Ls), so
|
||||
"Make the report export..." trips it. Start with "In this repo, ..." or "Using
|
||||
the Quick Task skill, ...". A leading skill command (`/plan2code-quick-task ...`)
|
||||
is fine: it gets none;
|
||||
- names the skill to paste it into, the files to read first, and what to do;
|
||||
- states what is out of scope, so the new conversation does not wander;
|
||||
- stands alone: it assumes nothing said in this session, because the new
|
||||
conversation has none of it.
|
||||
|
||||
One block per reply, and only when the work is likely to move to a new
|
||||
conversation. A plain answer stays a plain answer.
|
||||
- opens with plain prose, never a command word: a first line that looks like a shell command (`git`, `npm`, `node`, `rm`, `#!`, or an everyday verb like Make, Go, Source, Export, Cat, Echo, Zip, Tar, Cd, Ls; case-insensitive) gets a "paste into the Ask tab" hint. Start with "In this repo, ..." or "Using the Quick Task skill, ...". A leading `/plan2code-quick-task ...` is fine.
|
||||
- names the skill to paste it into, the files to read first, the task, and what is out of scope.
|
||||
- stands alone: it assumes nothing said in this session.
|
||||
|
||||
## Never steer the workflow
|
||||
|
||||
A chat answer never changes a card's answer, a gate, or where the workflow
|
||||
goes. If a message asks for that ("approve phase 2", "skip the tests
|
||||
question"), reply by pointing to the card — its note box for a comment, its
|
||||
answer for a change — and do not act on it. Chat never counts as an answer to
|
||||
a card and is never recorded under `specs/`.
|
||||
A chat message never answers a card, passes a gate or changes where the workflow goes ("approve phase 2"): point to the card (its note box, its answer) and do not act. Chat is never recorded under `specs/`. A conversation holds at most 10 typed messages; the page enforces it.
|
||||
|
||||
## A new conversation is a clean slate
|
||||
## Edits need approval
|
||||
|
||||
After a `reset` entry (New conversation, or a skill switch through the
|
||||
dashboard) treat earlier chat as closed, and do not bring it up unless the
|
||||
person does. A conversation holds at most 10 typed messages; the page
|
||||
enforces it, so never tell someone to keep asking past it.
|
||||
|
||||
## Edits need approval first
|
||||
|
||||
- A request to change files gets a reply carrying `proposal: { summary,
|
||||
files }` — a plain-English summary and every file that will change — and
|
||||
**no change yet**. The page shows it with Approve and Decline.
|
||||
- Only after `Approved: edit <id>`: make exactly the proposed change, then post
|
||||
a reply (its `re` is the decision's `seq`) carrying `changed: [{ file,
|
||||
added, removed }]`, with line counts from `git diff --numstat -- <files>` (or
|
||||
counted by hand for an untracked file). Name the changed files in your next
|
||||
progress update or `activity` line.
|
||||
- `Declined:` (with any note): acknowledge it and change nothing. A revised
|
||||
proposal is a new reply.
|
||||
- Hard limits: never touch the running skill's own files under
|
||||
`specs/<idea>/` (`post` rejects a proposal that names them); run no commands
|
||||
beyond read-only lookups, except one the person plainly asks you to run in
|
||||
their message (a commit they spell out, a test run): run it, then report the
|
||||
result in the reply; refuse anything else and say why, in the reply.
|
||||
- Edits happen only at check-ins, never mid-task in a build.
|
||||
|
||||
```jsonc
|
||||
{ "chat": { "replies": [
|
||||
{ "id": "r14", "re": 14, "conversation": 3, "md": "I can rename it.",
|
||||
"proposal": { "summary": "Write the export to `out/audit.csv` instead of `out/export.csv`",
|
||||
"files": ["src/export.js", "README.md"] } }
|
||||
] } }
|
||||
```
|
||||
|
||||
## What the server checks
|
||||
|
||||
Each reply needs a unique `id` (or none, to take `r<re>`), an `re` naming a real
|
||||
message or decision `seq`, an integer `conversation` and non-empty `md`. A
|
||||
`proposal` needs a `summary` and project-relative `files`, none under the
|
||||
running skill's `specs/<idea>/`. `changed` is a list of `{ file, added,
|
||||
removed }`. The house rules on completion markers and metric-like words cover
|
||||
reply text too.
|
||||
|
||||
## The same chat twice
|
||||
|
||||
Replies merge by `id`, so re-post the same reply if it is not on the page yet;
|
||||
do not answer the question a second time.
|
||||
- A request to change files gets a reply with `proposal` (a plain-English `summary` and every file that will change) and **no change yet**: `{"chat":{"replies":[{"re":14,"md":"I can rename it.","proposal":{"summary":"Write the export to `out/audit.csv`","files":["src/export.js","README.md"]}}]}}`. The page shows Approve and Decline.
|
||||
- `Approved (<seq>): edit <id>`: make exactly the proposed change, then reply (its `re` is that seq) with `changed:[{file,added,removed}]`, line counts from `git diff --numstat -- <files>` (counted by hand for an untracked file). Name the changed files in your next update.
|
||||
- `Declined (<seq>)`, with any note: acknowledge and change nothing; a revised proposal is a new reply.
|
||||
- Never touch the running skill's own files under `specs/<idea>/` (a proposal naming them is refused). Run no commands beyond read-only lookups, except one they plainly ask for in their message (a commit they spell out, a test run): run it and report. Refuse anything else, saying why.
|
||||
- Edits happen at check-ins, never mid-task in a build.
|
||||
@@ -0,0 +1,27 @@
|
||||
# Documents on the Web Console
|
||||
|
||||
The console points here at your first patch with `docs`. A doc is a tab of blocks the person reads beside the questions.
|
||||
|
||||
`{"docs":[{"id":"map","title":"What we've agreed","note":"what changed in this version","saved":"specs/lunch-vote/pathfinder/map.md","blocks":[{"id":"b1","md":"## Where we're headed\n\n..."},{"id":"b2","state":"assumed","md":"### File format\n\nAssuming CSV..."},{"id":"b4","file":"specs/lunch-vote/overview.md"}]}]}`
|
||||
|
||||
Docs and their blocks merge by `id`; a new id is added at the end. Patch blocks as decisions land:
|
||||
|
||||
- `{"id":"b2","state":"settled"}` settles b2 and keeps its text; blocks you leave out stay.
|
||||
- `{"id":"b3","_delete":true}` removes a block; a doc entry with `"_delete":true` removes the tab.
|
||||
|
||||
## Block content: one of three
|
||||
|
||||
- `md`: markdown you write.
|
||||
- `file`: the console reads the text from that project file (inside the project, 512 KB at most). Re-send the block, or the doc with `"refresh":true`, after the file changes. `"select":"tasks"` keeps only its `- [ ] **Task N.M:**` lines. Never paste a file you can name.
|
||||
- `image`: `{"id":"s1","image":"shots/run.png","alt":"..."}`: a PNG, JPEG or WebP (5 MB at most) saved directly in the session's `shots/` folder (the `session` path `open` printed), named with letters, digits, `.`, `_` or `-`. Anything else is exit 3.
|
||||
|
||||
## State
|
||||
|
||||
`state` is `settled` (decided; the default), `assumed` (picked to keep going, still open: shown dashed) or `draft` (dimmed). Mark assumptions honestly so a half-finished doc does not read as decisions.
|
||||
|
||||
## Doc fields
|
||||
|
||||
- `note`: one line saying what changed; write one whenever you change a doc.
|
||||
- `stale`: `true` while answers the doc does not reflect have landed.
|
||||
- `saved`: the path of the file the doc mirrors, when one exists; leave it off docs that exist only here.
|
||||
- `version`: moves by itself when content changes and never goes back; leave it out.
|
||||
@@ -1,132 +1,47 @@
|
||||
# Finishing a Web Console Session
|
||||
# Finishing a Session
|
||||
|
||||
Part of the web console contract (`console.md`). Read before your first `finish`
|
||||
post, and when a send carries `__commit` or a finished screen's `__dashboard`.
|
||||
A stop request or the mid-workflow way home is `console-stop.md`.
|
||||
The console points here on `__commit`, or on `__dashboard` from a finished screen. Read it before your first `finish` post too. A stop request or the way home mid-workflow is `console-stop.md`.
|
||||
|
||||
Three steps, in this order. **Post the finish, keep waiting for a press —
|
||||
there is no timeout — and stop the server when the session ends.** A pause
|
||||
(below) still stops straight away.
|
||||
Stopping first leaves the person staring at a page that says "leave this tab
|
||||
open, the next question will appear here on its own" about a session that is
|
||||
over, and the one thing they need is a command in a terminal they are not
|
||||
looking at. Post it on every session end, not only the last one: an off-ramp
|
||||
that routes elsewhere, a checkpoint that saves and stops, a stop request.
|
||||
Three steps, in order: post the finish, keep waiting for a button (no timeout), `stop` the server. Every session end posts one, not only the last. A pause (below) stops at once.
|
||||
|
||||
**Nothing of yours may still be running.** Before the finish, every
|
||||
subagent or background job you started this session must have reported
|
||||
back. They run inside your terminal's process, not the console's: the page
|
||||
cannot see them, and the moment it says the session ended, the person is
|
||||
free to close that terminal and kill them mid-write. While you wait, post
|
||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||
and update the count as each returns. Never write a `finish.body` that says
|
||||
work "is running in the background" or "will finish on its own". Mark every
|
||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
||||
never ends on a row still running: post each one's `done` in the same turn its
|
||||
notice arrives, and a `finish` is refused (exit `3`, naming the helper) while
|
||||
any row is still `running`.
|
||||
Every helper or background job you started must have reported back first. While you wait, post `{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`. Mark each reported helper `done` or `failed` in the turn its notice arrives: a `finish` is refused while any row is `running`. Never write a `finish.body` saying work "is running in the background".
|
||||
|
||||
## 1. Post the finish
|
||||
|
||||
The same closer you are about to print in the terminal, as data:
|
||||
`{"settle":true,"finish":{"headline":"The map is written","body":"Everything is on disk under `specs/lunch-vote/pathfinder/`.","command":"/plan2code-0-pathfinder specs/lunch-vote/pathfinder","doc":"map","dashboard":true}}`
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"settle": true,
|
||||
"finish": {
|
||||
"headline": "The map is written",
|
||||
"body": "Everything you decided is on disk under `specs/lunch-vote/pathfinder/`, one file per decision. The **The map** tab has the whole picture.",
|
||||
"command": "/plan2code-0-pathfinder specs/lunch-vote/pathfinder",
|
||||
"doc": "map",
|
||||
"dashboard": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | | |
|
||||
| --- | --- | --- |
|
||||
| `headline` | required | What just happened, in plain words. Becomes the card's title. |
|
||||
| `command` | optional | The exact thing they run next, when there is one — the same string as your Trail Footer's Form A. Rendered with a Copy button that is always on show. Leave it out when nothing is left to run: the page shows an "All done" line with `/plan2code` instead. **No placeholders**: a rendered command is copied and run verbatim, and a patch carrying `<` or `>` in it is rejected. |
|
||||
| `dashboard` | optional | `true` puts a **Back to the dashboard** button on the finished screen. Set it on every ending except a pause, and keep waiting for the press (below). |
|
||||
| `body` | optional | Markdown. Where the files landed, what to read first. |
|
||||
| `where` | optional | Overrides "Run this in the terminal where you started Plan2Code, in a new conversation:". |
|
||||
| `doc` | optional | Id of the document to offer as a Markdown download on the way out. Defaults to the first one. |
|
||||
| `console` | optional | Whether the copied text asks the next session to use the web console. Leave it out: it follows from the command. |
|
||||
| `commit` | optional | `true` on a finished `quick-task`, `implement`, `implement-review`, `review` or `finalize` whose finish prints a git command puts a **Commit it now** button on the finished screen. The press arrives as `__commit` (below). |
|
||||
| `changelog` | optional | `true` on a finished `quick-task` or `finalize` that also carries `commit: true` puts an **Update CHANGELOG first** button beside **Commit it now**. Refused (exit 3) on any other workflow, `implement` included. The press arrives as `__changelog` (below). |
|
||||
| `review` | optional | A finished `quick-task` only: `true` or `{ "label": "..." }` puts a **Review it now** button on the finished screen (`notes/quick-task.md`, `building-review.md`). `implement` offers the review on its sign-off card instead — before approval, where it can still change the outcome. |
|
||||
|
||||
**Continue here.** Nothing to set: when `command` starts with a Plan2Code skill
|
||||
(`/plan2code-2-document specs/lunch-vote/PLAN-DRAFT-20261019.md`, with or
|
||||
without `--web`) and the finish is not a pause, the page puts a **Continue
|
||||
here** button beside the Next step block, unless the session meter is red
|
||||
(then the fresh-session advice stands alone). A finish whose command is a git
|
||||
commit, or that has none, gets no button. You write nothing new; you only
|
||||
handle the `__launch` it sends (below). The `spec` it carries is the
|
||||
`specs/<name>` folder the command mentions.
|
||||
|
||||
**Write the bare command.** Every Plan2Code skill has a console — the
|
||||
dashboard and every skill behind it — so for any of them the page
|
||||
appends ` --web` to what it shows and copies, so someone who worked here
|
||||
lands back here instead of being asked the interface question as though
|
||||
they were new. Every one of those skills takes that flag in its argument as
|
||||
the answer. Do not write `Use the web console for this session.` into the
|
||||
command; if it is there, the page swaps it for `--web`. A command that is not
|
||||
a Plan2Code skill gets nothing appended. Set `"console": false` if they have
|
||||
asked to go back to the terminal.
|
||||
|
||||
The page then says the session is finished rather than paused, offers the
|
||||
command, tells them they can close the tab, and stops treating the server going
|
||||
away as a fault. Send is disabled, and anything they staged and never sent is
|
||||
named rather than quietly lost.
|
||||
|
||||
Settle whatever the session ends on. An item still `open` when the finish
|
||||
lands freezes exactly as it stands: a send it carries shows as the final word
|
||||
on it, and one that was never answered shows as a question that ran out of
|
||||
time. If their last send was a verdict you are closing on — the review's
|
||||
`approve`, the plan's `yes`, the fixes pick — the finish post is the same post
|
||||
that settles it (`"settle": true`).
|
||||
|
||||
Post it even when you are also printing the footer in the terminal. Someone who
|
||||
has spent the whole session in the browser has no reason to look anywhere else.
|
||||
|
||||
The chat stays open after a finish for as long as you are still listening (the
|
||||
review and dashboard buttons live as long as you do); the page only turns Send
|
||||
off once you have gone quiet. So while you wait for a button press, answer any
|
||||
chat `wait` delivers (`console-chat.md`).
|
||||
|
||||
## 2. After the finish: the buttons
|
||||
|
||||
A **pause** is an ending that keeps a place to come back to: a stop request,
|
||||
an abort that keeps its place to resume, or a checkpoint that saves and ends
|
||||
(Plan's Large checkpoint). A pause's headline starts with "Paused", it never
|
||||
carries `dashboard`, and you post it without `--wait` and `stop` at once.
|
||||
|
||||
Every other finish carries `"dashboard": true` and goes up with `post --wait`;
|
||||
keep waiting in the usual slices. There is no timeout after a finish: the
|
||||
buttons live exactly as long as you are listening, so a press an hour later
|
||||
works like a press a minute later.
|
||||
|
||||
| What arrives | What you do |
|
||||
| Field | Use |
|
||||
| --- | --- |
|
||||
| An action `{ "i": "__dashboard", "type": "dashboard" }` | Run the `resume` it carries (`open --resume <sid> --no-open --workflow dashboard`; it re-runs the project scan and clears the page, the finish included), read the dashboard skill (`skillFile`, or `~/.agents/skills/plan2code/SKILL.md`), then post its `menu` with `--wait` and carry on as the dashboard from its "Coming back from another skill", in this same conversation. |
|
||||
| An action `{ "i": "__changelog", "type": "changelog" }` | Update CHANGELOG first: run the `resume` it carries (`open --resume <sid> --no-open --workflow changelog`; no `finish`, no `stop`; the hop gives Changelog a clean page, the finish included), then open the Changelog skill (`skillFile`, or `~/.agents/skills/plan2code-changelog/SKILL.md`) with your file-read tool and follow it from the top (`notes/changelog.md`). Its "Commit this now?" yes carries on to Git. Leave the commit command you printed in the finish where it is for the terminal. |
|
||||
| An action `{ "i": "__launch", "type": "launch", "skill": ..., "workflow": ..., "spec": ... }` | Continue here: the same hop as a dashboard pick (`console-launches.md` → A pick). Run the `resume` it carries (the hop gives the next skill a clean page, the finish included), read its `skillFile` with your file-read tool (never a skill-invocation tool), and follow it from the top in this same conversation. No `stop`. A hop into a different skill gives it a clean page, the finish included; when the `resume` keeps your own workflow (a phase finish whose next step is the same Implement), nothing clears the page, so your first post of the new run carries `"finish": null`. |
|
||||
| An action `__review` or `__done` | As `building-review.md` says (quick task only). |
|
||||
| An action `{ "i": "__commit", "type": "commit" }` | Commit it now: run the `resume` it carries (`open --resume <sid> --no-open --workflow git`; no `finish`, no `stop`; the resume gives Git a clean page, the finish included, as a dashboard launch does), then open the Git skill (`skillFile`, or `~/.agents/skills/plan2code-git/SKILL.md`) with your file-read tool and follow it, starting with the commit flow over the board (the person pressed Commit it now), then the board with Push lit. Leave the commit command you printed in the finish where it is for the terminal. |
|
||||
| `wait` exit `20` | The server is gone. `open --resume <sid> --workflow <yours>` (it gets a new link: give it to them; the browser opens it), then keep waiting: their Ask messages and the dashboard button still need you. Give up only when the resume itself fails. |
|
||||
| The session ends without a press (the terminal closes, the conversation ends) | The server sweeps itself once its idle window passes, and the page swaps the buttons for the matching commands — nothing pressable dies silently. A press that lands in the meantime is kept on disk (`pendingResult`) for a resumed session. |
|
||||
| `headline` | required: what happened, in plain words |
|
||||
| `command` | the exact next thing to run (your Trail Footer's Form A), copied verbatim: no `<` or `>` (refused). Leave it out when nothing is left to run. Write it bare: the page appends `--web` itself, and swaps a written `Use the web console for this session.` for it. `"console":false` if they asked to go back to the terminal |
|
||||
| `dashboard` | `true` on every ending except a pause: the **Back to the dashboard** button |
|
||||
| `body` | markdown: where files landed, what to read first |
|
||||
| `where` | overrides "Run this in the terminal where you started Plan2Code, in a new conversation:" |
|
||||
| `doc` | id of the doc to offer as a download (default: the first) |
|
||||
| `commit` | `true` when the finish prints a git command (`quick-task`, `implement`, `implement-review`, `review`, `finalize`): **Commit it now** |
|
||||
| `changelog` | `true` with `commit:true` on `quick-task` or `finalize`: **Update CHANGELOG first** (exit 3 on any other workflow) |
|
||||
| `review` | `quick-task` only: `true` or `{"label":"..."}` puts **Review it now** on the screen (`building-review.md`) |
|
||||
|
||||
A finish whose `command` starts with a Plan2Code skill and is not a pause gets a **Continue here** button (unless the meter is red). You only handle the `__launch` it sends.
|
||||
|
||||
Settle whatever the session ends on in the same post (`"settle":true`): an item still `open` freezes as it stands. Post the finish even when you also print the footer in the terminal. Answer any chat `wait` delivers while you wait for a button (`console-chat.md`).
|
||||
|
||||
## 2. The buttons
|
||||
|
||||
A **pause** (a stop request, an abort that keeps its place, a checkpoint that saves and ends) has a headline starting "Paused", no `dashboard`, and is posted without `--wait`: `stop` at once. Every other finish goes up with `post --wait`; keep waiting in the usual slices.
|
||||
|
||||
| Arrives | Do |
|
||||
| --- | --- |
|
||||
| `__dashboard` | Run its `resume` (it re-scans and clears the page, the finish included), read the dashboard skill (`skillFile`, or `~/.agents/skills/plan2code/SKILL.md`), post its `menu` with `--wait`, and carry on as the dashboard in this conversation |
|
||||
| `__changelog` | Run its `resume` (no `finish`, no `stop`), read the Changelog skill (`skillFile`, or `~/.agents/skills/plan2code-changelog/SKILL.md`) and follow it (`notes/changelog.md`). Leave the commit command where it is |
|
||||
| `__launch` | Continue here: run its `resume`, read `skillFile` with your file-read tool (never a skill-invocation tool), follow it from the top. No `stop`. Into a different skill the page is cleared; when the `resume` keeps your own workflow (a phase finish into the same Implement), your first post of the new run carries `"finish":null` |
|
||||
| `__review` or `__done` | `building-review.md` (quick task only) |
|
||||
| `__commit` | Run its `resume` (`--workflow git`; no `finish`, no `stop`), read the Git skill (`skillFile`, or `~/.agents/skills/plan2code-git/SKILL.md`), start with its commit flow over the board (they pressed Commit it now), then the board with Push lit. Leave the printed commit command where it is |
|
||||
| `wait` exit 20 | `open --resume <sid> --workflow <yours>`, give the new link, keep waiting; give up only if the resume fails |
|
||||
| Session ends without a press | Nothing for you: an unfetched press stays on disk (`pendingResult`) for a resumed session |
|
||||
|
||||
## 3. Stop the server
|
||||
|
||||
```
|
||||
node "<CONSOLE>" stop --session <sid>
|
||||
```
|
||||
`node "<CONSOLE>" stop --session <sid>`
|
||||
|
||||
If you forget, it shuts itself down after 30 minutes of silence. Stop it anyway.
|
||||
The page keeps the hand-off on screen after the server has gone: everything it
|
||||
needs is already in `state.json`, and the Copy button is the one action that
|
||||
still works on a page whose server has died.
|
||||
|
||||
`node "<CONSOLE>" status` lists sessions for this project, including any whose
|
||||
answers were submitted but never picked up.
|
||||
A session with no finish is refused (exit 3); `--force` stops it anyway (`console-trouble.md`). `node "<CONSOLE>" status` lists this project's sessions, including any whose answers were never picked up.
|
||||
@@ -1,113 +1,25 @@
|
||||
# Launches: the Dashboard on the Web Console
|
||||
# Launches (the Dashboard)
|
||||
|
||||
Part of the web console contract (`console.md`). Read when you are the
|
||||
dashboard. The dashboard skill's own prompt (`plan2code/SKILL.md`) has the
|
||||
menu judgment and the launch steps; this is what the page does around them.
|
||||
Read when you are the dashboard. The dashboard skill's own prompt (`plan2code/SKILL.md`) has the menu judgment and launch steps; this is what the page does around them.
|
||||
|
||||
## A launch
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [{ "i": "__launch", "type": "launch",
|
||||
"skill": "plan2code-3-implement", "workflow": "implement",
|
||||
"spec": "specs/lunch-vote" }],
|
||||
"reply": "Start Implement (/plan2code-3-implement) for specs/lunch-vote, right here in this session.",
|
||||
"resume": "node \"…/console.mjs\" open --resume <sid> --no-open --workflow implement --spec specs/lunch-vote",
|
||||
"skillFile": "…/plan2code-3-implement/SKILL.md" }
|
||||
```
|
||||
A pick arrives with `session:[{"i":"__launch","skill":"plan2code-3-implement","workflow":"implement","spec":"specs/lunch-vote"}]`, plus `resume` and `skillFile`. `spec` is present only when the skill takes one and the person picked it. Run `resume` first, before reading anything: it reuses the live server and turns the page from the menu into the skill's starting screen while you read. Then read `skillFile` (absent outside an install: `~/.agents/skills/<skill>/SKILL.md`) with your own file-read tool and follow it from the top. Never hand it to a skill-invocation tool: every skill below the dashboard ships `disable-model-invocation: true`, and the call errors out.
|
||||
|
||||
`spec` is the picker's selected spec dir, present only when the launched skill
|
||||
takes a spec (or is Quick Task on a `diagnosed` spec) and the person picked one. `resume` is the one command to run
|
||||
first, before reading anything: it reuses the live server and turns the page
|
||||
from the menu into the skill's starting screen while you read. `skillFile` is
|
||||
the skill to read next (absent outside an install: then
|
||||
`~/.agents/skills/<skill>/SKILL.md`).
|
||||
A session handed to you is resumed, never re-opened (`--title` and `--spec` are honored on resume). A resume to or from `dashboard`, or into `git` from any skill, clears the page; a skill run inline from another (a quick task's review) never resumes. Its Interface step is already answered by the launch, and you have read the card: read only the notes or building files its Interface names. Post before anything slow.
|
||||
|
||||
**A session handed to you is resumed, never re-opened.** A fresh `open` would
|
||||
strand the page the person is watching on the dashboard's session while your
|
||||
questions went to a page nobody has open. `--title` and `--spec` are honored on
|
||||
resume. A resume to or from `dashboard`, or into `git` from any skill, clears
|
||||
the page: the last skill's questions, sections, docs, headline and finish are
|
||||
dropped, so the new skill starts blank and posts its own. A skill run inline
|
||||
from another (a quick task's review) never resumes, and keeps the page it was
|
||||
handed.
|
||||
## What the page knows
|
||||
|
||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
||||
> own file-read tool and follow it from the top.** Every Plan2Code skill below
|
||||
> the dashboard ships `disable-model-invocation: true` on purpose, and calling
|
||||
> one through a skill-invocation tool errors out and strands the hand-off.
|
||||
`state.scan` is `{hasAgents,isGit,pending,specs:[{dir,name,state,detail,touched}],handoffs,handoffsDir}`, a snapshot of the last `open` (a spec created mid-session appears at the next dashboard resume). `pending` is the count a commit would take (`null` when git cannot say). The `menu` you post (`note`, `recommend`, `details`) describes the initially selected spec; leave any field out and the page falls back to that spec's own next step, and derives them again when the person switches specs. Post it with `--wait`.
|
||||
|
||||
Its Interface step is already answered by having been launched. You have read
|
||||
`console.md` already: do not read it again; read only the notes or building
|
||||
files its Interface names.
|
||||
A `__stop` before a pick ends the session the usual way: `finish` (headline "Paused", `"command":"/plan2code"`), then `stop` (`console-stop.md`).
|
||||
|
||||
From the click until the resume lands, the page shows a getting-ready screen;
|
||||
from the resume until the skill's first payload, its starting screen. Resume
|
||||
first, and post before anything slow.
|
||||
|
||||
## What the page already knows
|
||||
|
||||
`state.scan` is `{ hasAgents, isGit, pending, specs: [{ dir, name, state, detail, touched }], handoffs, handoffsDir }`,
|
||||
a snapshot of the last `open` (a spec created mid-session appears the next time
|
||||
the session resumes as a dashboard). `pending` is how many files a commit would
|
||||
take (`null` when git cannot say): the Git card never grays out, shows the count
|
||||
when there is one, and outside a repository says Git can start one. The picker
|
||||
grays the cards that do not fit the selected spec — or hides them, while the
|
||||
**Hide unavailable workflows** switch under it is on (the default).
|
||||
|
||||
The `menu` you post (`note`, `recommend`, `details`) describes the initially
|
||||
selected spec; leave any field out and the page falls back to that spec's own
|
||||
next step, and it derives both again from the scan when the person switches
|
||||
specs or starts fresh. Post it with `--wait`; waiting on the menu is the
|
||||
person's turn by itself.
|
||||
|
||||
A `__stop` before a pick ends the session the usual way: `finish` (paused
|
||||
headline, `"command": "/plan2code"`) then `stop` (`console-stop.md`).
|
||||
|
||||
`handoffs` is this checkout's unused handoffs, newest first (`[{ id, title,
|
||||
next, written, spec, skill, workflow }]`, read from `~/.plan2code/handoffs/`
|
||||
by `open`, a dashboard only), and `handoffsDir` is that folder. The picker shows
|
||||
them as dashed **Handoff** chips after the specs.
|
||||
`handoffs` is this checkout's unused handoffs, newest first (`[{id,title,next,written,spec,skill,workflow}]`, read from `~/.plan2code/handoffs/`), shown as dashed Handoff chips.
|
||||
|
||||
## A pick-up
|
||||
|
||||
Selecting a handoff chip shows a preview and hides the skill cards. **Pick it up
|
||||
here** sends a hop like a launch, naming only the id:
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [{ "i": "__pickup", "type": "pickup", "handoff": "2026-10-17-1152-handoff" }],
|
||||
"reply": "Pick up the handoff \"Lunch vote\" right here in this session.",
|
||||
"resume": "node \"…/console.mjs\" open --resume <sid> --no-open --workflow quick-task --spec specs/lunch-vote",
|
||||
"skillFile": "…/plan2code-quick-task/SKILL.md",
|
||||
"handoffFile": "~/.plan2code/handoffs/2026-10-17-1152-handoff.md" }
|
||||
```
|
||||
|
||||
`wait` has already read the handoff's stored skill and spec, marked the handoff
|
||||
used (the next scan no longer lists it) and put the command in `resume`. Run
|
||||
`resume`, read `skillFile` with your file-read tool, then read `handoffFile`,
|
||||
follow the skill from where its real work starts, and carry on from the
|
||||
handoff's **Next task**. When the send carries `"fallback": true` the named
|
||||
skill or spec was gone, or the Handoff skill wrote it: say so in one line,
|
||||
since Quick Task is picking it up.
|
||||
The handoff's document stays on disk until the 30-day sweep.
|
||||
**Pick it up here** sends `session:[{"i":"__pickup","handoff":"2026-10-17-1152-handoff"}]` with `resume`, `skillFile` and `handoffFile`. `wait` already read the handoff's stored skill and spec and marked it used. Run `resume`, read `skillFile`, then `handoffFile`, follow the skill from where its real work starts, and carry on from the handoff's **Next task**. With `"fallback":true` (the named skill or spec was gone, or the Handoff skill wrote it) say so in one line, since Quick Task is picking it up.
|
||||
|
||||
## A delete
|
||||
|
||||
The ✕ on a picker chip, after the page's two-step confirm (what goes, then
|
||||
the spec's name typed), sends `{ "i": "__delete", "type": "delete", "spec":
|
||||
"specs/<name>" }` with a `reply` saying it is for good. It is no hop: it
|
||||
carries no `resume`, and you stay the dashboard. The console never writes into
|
||||
a project, so the page only asks; delete through
|
||||
`node "<CONSOLE>" delete-spec --spec <spec>`, never your own `rm`. It takes
|
||||
only an existing `specs/<name>` folder inside the worktree (never a link,
|
||||
never deeper, never `specs--completed/`), exits 3 with `message` on a refusal
|
||||
having touched nothing, and drops the workspace remembered for that spec.
|
||||
Then `open --resume <sid> --no-open --workflow dashboard` to rescan, and post
|
||||
the menu again with `--wait`, its note saying what went or why it did not.
|
||||
The page shows the chip as "Deleting…" until that rescan lands.
|
||||
|
||||
A handoff's **Delete** sends the same `__delete`, with `handoff` (its id) where a
|
||||
spec has `spec`. Delete it through
|
||||
`node "<CONSOLE>" delete-handoff --handoff <id>` (exit 3 with `message` when it
|
||||
refuses, nothing touched), then rescan and post the menu as for a spec.
|
||||
The ✕ on a chip (after the page's two-step confirm) sends `session:[{"i":"__delete","type":"delete","spec":"specs/<name>"}]` (a handoff has `handoff` where a spec has `spec`). It is no hop: no `resume`, you stay the dashboard. Delete through `node "<CONSOLE>" delete-spec --spec <spec>` or `delete-handoff --handoff <id>`, never your own `rm`; exit 3 with `message` means refused with nothing touched. Then `open --resume <sid> --no-open --workflow dashboard` to rescan, and post the menu again with `--wait`, its note saying what went or why not.
|
||||
@@ -1,56 +1,12 @@
|
||||
# The Session Meter on the Web Console
|
||||
# The Session Meter
|
||||
|
||||
Part of the web console contract (`console.md`). Your workflow notes give the
|
||||
exact `run` to post; read this only if one is refused.
|
||||
Read only if a `run` was refused; your workflow notes give the exact `run` to post.
|
||||
|
||||
### Session meter
|
||||
The meter is advice and never blocks. The console scores these launches itself when their session opens (post nothing for them): Plan, Revise plan, Document, Review, Quick task, Init, Init update, Finalize, Git, Changelog, X-ray, Diagnose. It also counts answers: every 2 cards answered in a send add a point; notes, Quick questions and buttons do not count.
|
||||
|
||||
The page's top bar shows a meter of how much work this console session has
|
||||
done (green, yellow, red), so the person knows when a fresh session would be
|
||||
sharper. It is advice only and never blocks anything. The console counts
|
||||
launches itself: Plan, Revise plan, Document, Review, Quick task, Init, Init
|
||||
update, Finalize, Git, Changelog, X-ray and Diagnose score when their session opens, and there is nothing to
|
||||
post for them.
|
||||
Per-unit work is yours: `{"run":{"event":"implement-phase","id":"phase-2","tasks":9}}`, one `run` per post, never reaching the page state.
|
||||
|
||||
It counts answers itself too: every card the person answers in a send adds to
|
||||
the skill run's tally when `wait` hands the send to you, and every 2 answers
|
||||
score a point, so a long back-and-forth weighs more than a short one. Notes,
|
||||
Quick questions and buttons such as Stop or the dashboard do not count.
|
||||
|
||||
Per-unit work is yours to report, with `run` in any post:
|
||||
|
||||
```jsonc
|
||||
{ "run": { "event": "implement-phase", "id": "phase-2", "tasks": 9 } }
|
||||
```
|
||||
|
||||
- `event` is one of `pathfinder-chart`, `pathfinder-question` (scores
|
||||
nothing now: answers count instead), `pathfinder-research`, `plan`,
|
||||
`revise-plan`, `document`, `implement-phase`, `implement-review-phase`,
|
||||
`review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`,
|
||||
`git`, `changelog`, `xray`, `diagnose`, `git-commits` and `git-conflict` (Git's own, see
|
||||
`notes/git.md`).
|
||||
An unknown event is exit `3`. Post only the events your notes name: a skill
|
||||
that scores when its session opens (the list above this one) already has its
|
||||
points, and a `run` for it scores the same work twice.
|
||||
- `id` names the unit: a question's file slug, `phase-N`, `map`. The same id
|
||||
posted again in the same skill run is ignored, so a repeated post never
|
||||
counts twice. It must be non-empty.
|
||||
- `tasks` goes only with `implement-phase` and `implement-review-phase`: the
|
||||
number of tasks the phase completed (marked `[x]`; blocked `[!]` tasks do
|
||||
not count), a whole number from 1 to 999. A built phase scores by its size,
|
||||
one point per 3 tasks rounded up, and Implement + Review one more for the
|
||||
review. Always send it: without it a phase scores a flat 2 (or 3), however
|
||||
big it was. On any other event it is exit `3`. The console already counts a
|
||||
build's tasks from `headline.cleared` as they are ticked off; the phase's
|
||||
`run` takes that count over with the final score, so it never counts twice.
|
||||
- `commits` goes only with `git-commits`: how many commits Git just made, a
|
||||
whole number from 1 to 999. A Git run scores one point per 2 commits,
|
||||
rounded down; on any other event it is exit `3`.
|
||||
- One `run` per post. Which events a workflow reports is in its own notes
|
||||
(`notes/pathfinder.md`, `notes/git.md`; `building.md` for Implement and for
|
||||
the review run on the page after a build).
|
||||
|
||||
`run` never reaches the page state: `post` (and `open --file`) lift it into the
|
||||
session's ledger.
|
||||
|
||||
---
|
||||
- `event`: `pathfinder-chart`, `pathfinder-question` (scores nothing now), `pathfinder-research`, `plan`, `revise-plan`, `document`, `implement-phase`, `implement-review-phase`, `review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`, `git-commits`, `git-conflict`. An unknown event is exit 3. Post only the events your notes name: a launch the console scores already has its points.
|
||||
- `id`: the unit (a question's slug, `phase-N`, `map`), non-empty. The same id in the same skill run is ignored.
|
||||
- `tasks`: only with `implement-phase` and `implement-review-phase`; the tasks completed (`[x]`, not blocked), a whole number 1 to 999. A phase scores one point per 3 tasks rounded up (Implement + Review one more for the review); without it, a flat 2 (or 3). It takes over the count from `headline.cleared`, never adding to it.
|
||||
- `commits`: only with `git-commits`; commits made, 1 to 999, one point per 2 rounded down.
|
||||
+26
-115
@@ -1,132 +1,43 @@
|
||||
# Stop Requests on the Web Console
|
||||
# Stop Requests
|
||||
|
||||
Part of the web console contract (`console.md`). Read when a send carries
|
||||
`__stop` or `__dashboard`, or your workflow notes say to post a `stopWarning`.
|
||||
The console points here when a send carries `__stop`, or `__dashboard` with no `finish` up. Your workflow notes also say when to post a `stopWarning`.
|
||||
|
||||
## Stop requests
|
||||
## `__stop`
|
||||
|
||||
The page has a **Stop session** button. Pressing it sends, in one submit, any
|
||||
answers the person had staged plus one more action:
|
||||
The person is ending the session: act on it in this turn. It arrives in `session` (`[{"i":"__stop"}]`) with any answers they had staged in `reply`.
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [ /* staged answers and notes, as usual */,
|
||||
{ "i": "__stop", "type": "stop" } ],
|
||||
"reply": "...the answer lines...\nStop here and save my place, so I can pick this up later." }
|
||||
```
|
||||
1. Handle the answers under the workflow's own rules and record only what is final: a confirmed recap, an approval verdict, a finished checklist. A pick that still owes its recap is not an answer yet: save it where the workflow keeps unfinished work (Pathfinder: the question's `## Evidence`, with the probes outstanding and your recommendation) and never write a provisional `## Answer`. Do not claim a question they picked from a menu in the same send. Settle only the final cards (`"settle":[...]`).
|
||||
2. Save your place the way the workflow does when a session ends.
|
||||
3. Post `finish` (`console-finish.md`) without `--wait`: a headline starting "Paused", a body naming what was saved and anything open (name a question left mid-way), and the resume command. If `stopWarning` is set, clear it in the same patch (`"stopWarning":""`): a finish posted while it is set is refused.
|
||||
4. `stop` the server.
|
||||
|
||||
`__stop` is not an item and matches nothing; like every `__` action it is
|
||||
about the session. It arrives through `wait` with exit `0`, like any send. It is
|
||||
the person ending the session, so act on it in this turn:
|
||||
Publish no new questions and do not ask whether they are sure: the page asked. Stop is only offered on their turn; the exception is an agent that stopped checking in, then the request waits on disk.
|
||||
|
||||
1. **Handle the answers under the workflow's own rules, and record only what is
|
||||
final.** A confirmed recap, an approval verdict, a finished checklist with its
|
||||
values. A pick that still owes its recap is not an answer yet: save it where
|
||||
the workflow keeps unfinished work (Pathfinder: the question's `## Evidence`,
|
||||
with the probes still outstanding and your recommendation for each) and never
|
||||
write a provisional `## Answer`. Do not claim a question the person picked
|
||||
from a menu in the same send. Settle only the final cards (`"settle": [...]`).
|
||||
2. **Save your place** the way the workflow does when a session ends.
|
||||
3. **Post `finish`** (`console-finish.md`) with a headline starting "Paused"
|
||||
(the page and `open --resume` both key off that word), a body naming what
|
||||
was saved and anything still open, and the resume command, without
|
||||
`--wait`. Name a question that was left mid-way, so they can ask for it by
|
||||
name next time.
|
||||
4. **`stop`** the server.
|
||||
## `__stop` with a handoff
|
||||
|
||||
Do not publish new questions and do not ask whether they are sure: the page
|
||||
already asked.
|
||||
`{"session":[{"i":"__stop","handoff":true}],"handoffSkill":"…/plan2code-handoff/SKILL.md"}`. In order:
|
||||
|
||||
The page only offers Stop on the person's turn. From the moment they press Send
|
||||
until your reply lands, the button is disabled, so a stop never arrives while
|
||||
you are halfway through writing their last answers. The one exception is an
|
||||
agent that has stopped checking in: then Stop comes back, and the request waits
|
||||
on disk for whichever session collects it next.
|
||||
1. Handle the answers as above.
|
||||
2. Save your place as above.
|
||||
3. `node "<CONSOLE>" handoff new --workflow <yours> --skill <your skill> [--spec <spec>] --title "<short title>" --from-stop` prints the `path` to write.
|
||||
4. Open `handoffSkill` with your file-read tool and write the document it describes to that `path`. Skip its questions and its "Where to write it" step: infer the Next task from where the work stands and say so in the document. With no `handoffSkill`, use `~/.agents/skills/plan2code-handoff/SKILL.md`.
|
||||
5. Post `finish` as above, its body naming the handoff path and saying the dashboard will offer it; clear any `stopWarning` in the same patch.
|
||||
6. `stop` the server.
|
||||
|
||||
## Stop with a handoff
|
||||
## `__dashboard` with no finish up (home, mid-workflow)
|
||||
|
||||
Off the dashboard, the Stop dialog offers **Stop with a handoff** first and
|
||||
**Just stop and save** second. The handoff choice sends the same `__stop`, with
|
||||
`handoff: true`, and `wait` adds `handoffSkill` (the Handoff skill's `SKILL.md`,
|
||||
present in a built skill):
|
||||
Same rules as Stop: their turn only, staged answers ride along.
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [ /* staged answers and notes, as usual */,
|
||||
{ "i": "__stop", "type": "stop", "handoff": true } ],
|
||||
"reply": "...the answer lines...\nStop here, save my place and write a handoff, so the dashboard can pick this up later.",
|
||||
"handoffSkill": "…/plan2code-handoff/SKILL.md" }
|
||||
```
|
||||
1. Handle the answers as above.
|
||||
2. Save your place as above. A workflow with nothing to save (a quick task not yet built) just goes home.
|
||||
3. Run the `resume` the send carried, read the dashboard skill (`skillFile`, or `~/.agents/skills/plan2code/SKILL.md`), post its `menu` with `--wait`, and carry on as the dashboard in this conversation.
|
||||
|
||||
Act on it in this turn, in this order:
|
||||
No `finish` and no `stop`: the menu is the ending. Say what you saved in one terminal line.
|
||||
|
||||
1. **Handle the answers** exactly as in "Stop requests" step 1.
|
||||
2. **Save your place** exactly as step 2 there.
|
||||
3. **Make the handoff file:**
|
||||
`node "<CONSOLE>" handoff new --workflow <yours> --skill <your skill> [--spec <spec>] --title "<short title>" --from-stop`
|
||||
It prints the `path` to write.
|
||||
4. **Write the handoff.** Open `handoffSkill` with your file-read tool (never a
|
||||
skill-invocation tool) and write the document it describes to that `path`.
|
||||
Skip its questions and its "Where to write it" step: infer the Next task
|
||||
from where the work stands, and say in the document that it was inferred.
|
||||
5. **Post `finish`** (`console-finish.md`) with a headline starting "Paused", a
|
||||
`body` that names the handoff path and says the dashboard will offer it, and
|
||||
the resume command, without `--wait`.
|
||||
6. **`stop`** the server.
|
||||
## `stopWarning`
|
||||
|
||||
With no `handoffSkill` (a source checkout), use the structure in
|
||||
`~/.agents/skills/plan2code-handoff/SKILL.md`. Do not ask whether they are
|
||||
sure: the page already asked.
|
||||
|
||||
## Back to the dashboard, mid-workflow
|
||||
|
||||
On every workflow but the dashboard, a triangle left of Stop session takes the
|
||||
person back to the dashboard. It follows Stop's rules exactly: only on their
|
||||
turn, a confirm first (with your `stopWarning`), and the staged answers ride
|
||||
along in the same submit:
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [ /* staged answers and notes, as usual */,
|
||||
{ "i": "__dashboard", "type": "dashboard" } ],
|
||||
"reply": "...the answer lines...\nSave my place and take me back to the dashboard, right here in this session.",
|
||||
"resume": "node \"…/console.mjs\" open --resume <sid> --no-open --workflow dashboard" }
|
||||
```
|
||||
|
||||
It is the same `__dashboard` a finished screen sends; with no `finish` on the
|
||||
page it means "stop, then go home". Act on it in this turn:
|
||||
|
||||
1. **Handle the answers** exactly as step 1 above.
|
||||
2. **Save your place** exactly as step 2 above.
|
||||
3. **Go home:** run the `resume` the send carried (it turns the page back into
|
||||
the dashboard and drops this skill's page), read the dashboard skill
|
||||
(`skillFile`, or `~/.agents/skills/plan2code/SKILL.md`), then post its
|
||||
`menu` with `--wait` and carry on as the dashboard from its "Coming back
|
||||
from another skill", in this same conversation.
|
||||
|
||||
No `finish` and no `stop` in between: the menu is the ending. Say what you
|
||||
saved in one terminal line, since no finish card will. A workflow with nothing
|
||||
to save (a quick task not yet built) just goes home.
|
||||
|
||||
## Saying what stopping would cost
|
||||
|
||||
Some points in a workflow have nothing on disk yet, and stopping there loses the
|
||||
answers given so far: Pathfinder before its map exists, Planning before a
|
||||
checkpoint. The page cannot know where you are, so tell it:
|
||||
|
||||
```jsonc
|
||||
{ "stopWarning": "The map is not written yet, so stopping now loses today's answers." }
|
||||
```
|
||||
|
||||
It is shown in the page's Stop dialog, and the button changes from "Stop and
|
||||
save" to "Stop anyway". Post `"stopWarning": ""` once stopping is safe again.
|
||||
For `plan` sessions the page assumes a warning until you post that empty string.
|
||||
Where stopping loses answers (Pathfinder before its map exists, Plan before a checkpoint), post `{"stopWarning":"The map is not written yet, so stopping now loses today's answers."}`. The Stop dialog shows it and says "Stop anyway". Post `"stopWarning":""` once stopping is safe, or in the same patch as a paused `finish`. For `plan` the page assumes a warning until you post the empty string.
|
||||
|
||||
## Picking up a paused session
|
||||
|
||||
`open --resume <sid>` (or `open --session <sid>`) clears a paused `finish`
|
||||
itself, and the questions left open at the pause with it: the finish body
|
||||
already said what was still open, so re-ask whatever the new session needs in
|
||||
your own words rather than leaving the old asks on the page as duplicates.
|
||||
Settled items stay. For any other ending you are deliberately taking back, post
|
||||
`"finish": null` in your first patch.
|
||||
`open --resume <sid>` clears a paused `finish` and the questions left open at it; re-ask what you need in your own words. Settled items stay. For any other ending you are taking back, post `"finish":null` in your first patch.
|
||||
@@ -1,101 +1,39 @@
|
||||
# Standing Instructions: Helpers on the Web Console
|
||||
# Helpers (Subagents)
|
||||
|
||||
Part of the web console contract (`console.md`). Read when a `Subagents:` block
|
||||
arrives, or when your workflow notes say to report helpers.
|
||||
|
||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
||||
`review`, `pathfinder`, `plan`, `revise-plan`), the person can turn **helpers** (subagents) on or off
|
||||
from the top bar's Subagents button. Their pick is saved per project and per
|
||||
skill, on until switched off, and reaches you as a standing instruction, only when it
|
||||
changes.
|
||||
The console points here when a `Subagents:` block reaches you. On the skills that offer it (`implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, `plan`, `revise-plan`) the person turns helpers on or off from the top bar's Subagents button, per project and skill. It 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:` lines last in `reply` (on `wait` exit 0, `chat` exit 0 and `open`). A change alone never ends a slice.
|
||||
|
||||
```
|
||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
||||
Report each helper on the page (console-subagents.md); questions for the person stay with you.
|
||||
If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.
|
||||
Match each helper's strength and effort to its job, as helper-strength.md says; when your tools cannot set them, start the helper without them.
|
||||
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. Pick each helper's strength and effort from helper-strength.md's table: light for a 1-2 file task the task file spells out, standard for multi-file or debugging work.
|
||||
Helper strength: balanced (the table in helper-strength.md as written).
|
||||
At most 3 helpers at once.
|
||||
Subagents: on, balanced strength, at most 3 helpers at once (a console setting, not typed by the person).
|
||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. ...
|
||||
```
|
||||
|
||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…", "strength": "balanced" }`.
|
||||
The `Helper strength:` line carries the person's profile, and replaces the
|
||||
Balanced default when they pick another:
|
||||
The indented lines are the skill's own instruction (or the person's); follow them. The latest block replaces an earlier one. Off arrives as one line: `Subagents: off. Start no new helpers for the rest of this session.` Nothing arrives: keep doing what the skill says. After a dashboard launch, no block means off for this skill. It never answers a card and is never recorded under `specs/`.
|
||||
|
||||
- `balanced`: the table in `helper-strength.md` as written (the default).
|
||||
- `thrifty`: one step lighter in strength and effort; reviews never below standard.
|
||||
- `best`: strongest and high effort for every helper except lookups, which stay light.
|
||||
- `session`: set no model or effort on any helper.
|
||||
The standing rules:
|
||||
|
||||
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.
|
||||
- **Strength:** start each helper at the strength and effort
|
||||
`helper-strength.md` (in the skill's `references/`) gives for its job,
|
||||
following its fallback order. Read it when you first start a helper.
|
||||
- **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.
|
||||
- **On:** hand independent work to helpers if your tools allow it, at most the stated number at once (advisory: your harness's limit applies). If your tools cannot start helpers at all, report one working-alone entry (below).
|
||||
- **Strength:** start each helper at the strength and effort `helper-strength.md` (in the skill's `references/`) gives for its job, following its fallback order; read it when you first start a helper. The word in the first line is the person's profile:
|
||||
- `balanced`: the table as written (default).
|
||||
- `thrifty`: one step lighter in strength and effort; reviews never below standard.
|
||||
- `best`: strongest and high effort for every helper except lookups, which stay light.
|
||||
- `session`: set no model or effort on any helper.
|
||||
When your tools cannot set them, start the helper without.
|
||||
- **Off:** start no new helpers; let running ones finish and report them.
|
||||
- **Pathfinder:** research questions always use helpers and are always reported, whatever the switch says. The switch governs recon, sketches and lookups.
|
||||
- Helpers add no session meter points: post no `run` for them.
|
||||
|
||||
## 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:
|
||||
Post them at your check-ins so the Subagents tab shows them (one post per change worth seeing, not a stream):
|
||||
|
||||
```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.", "strength": "light", "effort": "low" }
|
||||
] }
|
||||
```
|
||||
`{"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.","state":"done","result":"All 9 pass.","strength":"light","effort":"low"}]}`
|
||||
|
||||
- `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. `strength` (`light`,
|
||||
`standard`, `strongest` or `inherit`) and `effort` (`low`, `medium` or
|
||||
`high`) are optional: report what the helper actually ran with, and
|
||||
`inherit` when its strength could not be set. Anything else is exit `3`, and
|
||||
the house rules on completion markers and metric-like words cover `title`,
|
||||
`ask` and `result`.
|
||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
||||
too; a resume into the same skill keeps it.
|
||||
- One post per change worth seeing, not a stream.
|
||||
- Questions for the person stay with you, never with a helper: most harnesses
|
||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
||||
session.
|
||||
- **No way to start helpers at all?** Post one `{ "id": "alone", "alone": true }`
|
||||
entry for the skill run instead. The tab then says you are working alone.
|
||||
It is a claim about your tools, not about the moment — post it only when no
|
||||
helper mechanism exists. Reporting a real helper removes it, so an early
|
||||
`alone` can never hide a later helper. At most one `alone` entry.
|
||||
- **Pathfinder:** research questions always use helpers and are always
|
||||
reported, whatever the switch says. The switch governs recon, sketches and
|
||||
lookups beside the conversation.
|
||||
- Helpers add no session meter points. Post no `run` for them.
|
||||
- Before any `finish`, mark every reported helper `done` or `failed`
|
||||
(`console-finish.md`).
|
||||
- Required: `id`, `title` (80 characters at most), `ask` (400), `state` (`running`, `done`, `failed`). `result` (200 at most) is the line you add once it ends. `strength` (`light`, `standard`, `strongest`, `inherit`) and `effort` (`low`, `medium`, `high`) are optional: report what it actually ran with, `inherit` when its strength could not be set. Anything else is exit 3.
|
||||
- Merged by `id`: post it again with the new `state` and `result`. `"helpers":null` clears the list. A dashboard hop clears it; a resume into the same skill keeps it.
|
||||
- Questions for the person stay with you: a helper cannot ask.
|
||||
- No way to start helpers at all: post `{"helpers":[{"id":"alone","alone":true}]}` once for the skill run. Reporting a real helper removes it. At most one.
|
||||
- Before any `finish`, mark every reported helper `done` or `failed` (`console-finish.md`).
|
||||
@@ -1,20 +1,15 @@
|
||||
# When Things Go Wrong on the Web Console
|
||||
# When Things Go Wrong
|
||||
|
||||
Part of the web console contract (`console.md`). Read when something goes wrong.
|
||||
|
||||
| Situation | What to do |
|
||||
| Situation | Do |
|
||||
| --- | --- |
|
||||
| `open` fails | Say so in one line, carry on in the terminal. Never block on this. |
|
||||
| `wait` returns `20` | `open --resume <sid>`, give them the new link. Nothing they typed is lost. |
|
||||
| They close the tab | Nothing happens. Drafts are saved. Reopening the link restores everything. |
|
||||
| Your session ends mid-flight | Their answers still land on disk. A fresh session runs `status` (or `open --resume`, which reports `pendingResult: true`), and `wait` returns them. An uncollected result is never discarded. |
|
||||
| They ask to go back to the terminal | `stop` the session and continue. The files under `specs/` are unchanged. |
|
||||
| The session ends and they are still in the browser | Post `finish` **before** `stop`, and wait for the dashboard button first unless it is a pause (`console-finish.md`). Without it their last screen says the next question is coming, and then says contact was lost. |
|
||||
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
||||
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
||||
| Picking up a paused session | `open --resume <sid>` clears a paused `finish` and the questions left open at it; re-ask what you still need (`console-stop.md` → Picking up a paused session). |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
||||
| A patch is refused (exit `3`) | stderr names every problem; nothing was written. Fix them and post again. A `version` refusal means the payload is stale: drop `version` and let it move by itself. |
|
||||
| A doc block's `file` is refused | It must be a file inside the project, under 512 KB; `select` only takes `tasks`. |
|
||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||
| `open` fails, or `node` is missing or older than 18 | Say so in one line and carry on in the terminal; install nothing |
|
||||
| `wait` returns 20 | `open --resume <sid>`, give the new link; nothing they typed is lost |
|
||||
| They close the tab | Nothing: drafts are saved and the link restores everything |
|
||||
| Your session ends mid-flight | Their answers stay on disk; a fresh session runs `status` (or `open --resume`, which reports `pendingResult:true`) and `wait` returns them |
|
||||
| They ask to go back to the terminal | `finish`, then `stop`, and continue; files under `specs/` are unchanged |
|
||||
| The page is dead, the server will not answer, or the session is abandoned with no finish | `stop --session <sid> --force` (a plain `stop` with no finish is refused, exit 3) |
|
||||
| Picking up a paused session | `open --resume <sid>` clears the paused `finish` and its open questions; re-ask what you need (`console-stop.md`) |
|
||||
| The same result arrives twice | Your harness killed `wait` after the hand-over. Handle it once; most of a repeated patch is harmless since items merge by id, but `thread` appends: leave out entries you already sent |
|
||||
| The same chat arrives twice | Replies merge by `id`: re-post the same reply if it is not on the page yet; do not answer a second time |
|
||||
| A patch is refused (exit 3) | stderr names the item, the field and the fix; nothing was written. Correct it and post again. A `version` refusal means a stale payload: drop `version` |
|
||||
| A doc block's `file` is refused | It must be a file inside the project, under 512 KB; `select` only takes `tasks` |
|
||||
@@ -1,80 +1,25 @@
|
||||
# The Workspace on the Web Console
|
||||
# The Workspace
|
||||
|
||||
Part of the web console contract (`console.md`). Read when `open` lists more
|
||||
than one folder, a `Workspace:` line arrives, or someone writes `@name`.
|
||||
The console points here when a `Workspace:` change arrives. Read it also when `open` lists more than one folder or someone writes `@name`.
|
||||
|
||||
The person can add folders beside the one the session started in (a shared
|
||||
library, a design folder), from the footer's folder label. Together they are
|
||||
the session's **workspace**: context for every skill run in this console
|
||||
session, each folder addressed by a short `@name`. It outlives dashboard hops,
|
||||
and it is remembered: every change is saved to `workspaces.json` beside
|
||||
`looks.json` (never into the project), keyed by the folder the session runs
|
||||
in and then by spec. A session with a spec opens on that spec's list, one with
|
||||
none on the project's; a spec with nothing saved starts as a copy of the
|
||||
project's list. The dashboard's picker swaps the list as the selection moves,
|
||||
and a `specDir` you post mid-run takes the current list with it. There is
|
||||
nothing for you to load: `open` prints the list, and a switch of spec on a
|
||||
resume reaches you as ordinary workspace changes on your next `wait`.
|
||||
The person can add folders beside the one the session started in (a shared library, a design folder). Together they are the session's workspace: context for every skill run in it, each folder addressed by a short `@name`. It follows dashboard hops. There is nothing to load: `open` prints the list, and a spec switch on a resume reaches you as ordinary changes.
|
||||
|
||||
## What you are told
|
||||
|
||||
`open` (fresh or `--resume`) prints the whole list under `workspace`:
|
||||
`open` prints `workspace` when it holds more than the folder you started in: `{"folders":[{"name":"shop","path":"/home/sam/code/shop","original":true},{"name":"shared","path":"/home/sam/code/shared-ui","description":"Button and form styles"}],"missing":["old-docs"]}` (`missing` only when a folder is no longer on disk).
|
||||
|
||||
```jsonc
|
||||
{ "ok": true, "sid": "…", "url": "…",
|
||||
"workspace": {
|
||||
"folders": [
|
||||
{ "name": "shop", "path": "/home/sam/code/shop", "original": true },
|
||||
{ "name": "shared", "path": "/home/sam/code/shared-ui", "description": "Button and form styles" }
|
||||
],
|
||||
"missing": ["old-docs"]
|
||||
} }
|
||||
```
|
||||
|
||||
`missing` (only when there is one) names folders no longer on disk. After
|
||||
`open`, you hear only of changes, each exactly once:
|
||||
|
||||
- `wait` exit `0` carries them beside a send or chat as `workspace: [...]`
|
||||
(`{ kind, name, path, description?, from? }`, `kind` one of `added`,
|
||||
`renamed`, `described`, `removed`, `missing`, `found`), with one
|
||||
`Workspace: …` line each at the end of `reply`
|
||||
(`Workspace: added @shared — /home/sam/code/shared-ui`). A change alone never
|
||||
ends a slice: exit `10` counts it as `pendingWorkspace` and it rides on the
|
||||
next send.
|
||||
- `chat` hands changes over at once, with or without a Quick question, as
|
||||
`{ chat, workspace, reply }`.
|
||||
|
||||
Act on a change in the same turn it arrives: drop a removed folder, use the
|
||||
new name after a rename, note a missing one. No reply is needed unless the
|
||||
person asked something.
|
||||
After `open`, you hear only of changes, each once, as `Workspace:` lines last in `reply` of `wait` exit 0 or `chat`: `Workspace: added @shared`, then the folder path. The kinds are added, renamed, described, removed, missing and found. A change alone never ends a slice. Act on it in the same turn: drop a removed folder, use a new name, note a missing one. No reply is needed unless they asked something.
|
||||
|
||||
## Rules
|
||||
|
||||
- **Resolve `@name` from the workspace list.** `@shared` in an answer, a note
|
||||
or a Quick question means that folder's `path`. An `@name` not in the list
|
||||
is ordinary text.
|
||||
- **Added folders are read-only reference.** Read them freely; edit one only
|
||||
when the person asks for that change in this conversation. Chat edits still
|
||||
need approval (`console-chat.md` → Edits need approval first).
|
||||
- **Read an added folder's `AGENTS.md` before you first use it** (`CLAUDE.md`
|
||||
when there is no `AGENTS.md`), once per folder per skill run. It says how
|
||||
that folder is laid out; the original folder's `AGENTS.md` still governs
|
||||
this project and the work.
|
||||
- Resolve `@name` from the list: `@shared` in an answer, note or Quick question means that folder's `path`. An `@name` not in the list is ordinary text.
|
||||
- Added folders are read-only reference. Edit one only when they ask for that change in this conversation (chat edits still need approval, `console-chat.md`).
|
||||
- Read an added folder's `AGENTS.md` (`CLAUDE.md` without one) before first using it, once per folder per skill run. The original folder's `AGENTS.md` still governs the project.
|
||||
|
||||
## When a folder cannot be read
|
||||
## A folder you cannot read
|
||||
|
||||
When a read of an added folder genuinely fails (refused, not found), post, once
|
||||
per folder:
|
||||
When a read of an added folder fails (refused, not found), post once per folder, and print one terminal line saying which and why:
|
||||
|
||||
```jsonc
|
||||
{ "folderIssue": { "name": "shared", "reason": "Permission was refused", "hint": "/add-dir /home/sam/code/shared-ui" } }
|
||||
```
|
||||
`{"folderIssue":{"name":"shared","reason":"Permission was refused","hint":"/add-dir /home/sam/code/shared-ui"}}`
|
||||
|
||||
and print one terminal line saying which folder and why. The page marks the
|
||||
folder and tells the person once. `hint` is optional: an agent that knows it
|
||||
is Claude Code puts `/add-dir <path>` there. Your harness asking the person
|
||||
for permission is not a failure; report only a read that failed after it.
|
||||
|
||||
A `folderIssue` needs non-empty `name` and `reason` strings, and `hint`, when
|
||||
present, is one too; anything else is exit `3`. It goes to the session's
|
||||
ledger, never into the page state.
|
||||
`name` and `reason` are required non-empty strings; `hint` is optional (Claude Code: `/add-dir <path>`). Your harness asking the person for permission is not a failure; report only a read that failed after it.
|
||||
+64
-391
@@ -1,431 +1,104 @@
|
||||
# The Web Console
|
||||
# The Web Console (the card)
|
||||
|
||||
A local page in the person's browser where they answer your questions, read what
|
||||
you have drafted, and approve things, instead of typing into the terminal.
|
||||
A local page where the person answers your questions, reads your drafts and approves things. Read this card once per session. Read a topic file only when your workflow notes or the console's `read` output name it.
|
||||
|
||||
> **Not open yet?** `node "<CONSOLE>" open --workflow <yours>` first (launched
|
||||
> from the dashboard: its `resume` instead), then read on.
|
||||
`<CONSOLE>` is `<SKILL_ROOT>/references/web-console/console.mjs` (globally `~/.agents/skills/<skill-name>/references/web-console/`; `~/.plan2code/console/console-dir` may hold the folder). Always quote the path. `node "<CONSOLE>" help <topic>` prints any topic file.
|
||||
|
||||
**Read this file once per conversation.** Every Plan2Code skill ships the same
|
||||
copy (`version.json` beside it says which). If you already read it in this
|
||||
conversation — from the dashboard, or from another skill's copy — do not read it
|
||||
again after a hop; carry on. The topic files below are read only when their
|
||||
moment comes, also once each.
|
||||
## Start
|
||||
|
||||
**`<SKILL_ROOT>`** means the directory holding this skill's `SKILL.md`, and
|
||||
`<CONSOLE>` means `<SKILL_ROOT>/references/web-console/console.mjs` (globally:
|
||||
`~/.agents/skills/<skill-name>/references/web-console/`; an earlier session may
|
||||
have left the directory in `~/.plan2code/console/console-dir`). `node
|
||||
"<CONSOLE>" help <topic>` prints any topic file below. Always quote the path:
|
||||
install paths contain spaces. Requires Node 18+; nothing to install.
|
||||
`node "<CONSOLE>" open --workflow <w>` (add `--spec specs/<idea>` when known). `<w>` is one of `dashboard`, `init`, `init-update`, `pathfinder`, `quick-task`, `plan`, `revise-plan`, `document`, `implement`, `implement-review`, `review`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`. Launched from the dashboard? The session is open: run the `resume` command the launch carried instead.
|
||||
|
||||
**The console changes where you ask, not what you ask.** Every rule of this
|
||||
workflow still applies: the same questions, the same order, the same gates, the
|
||||
same cap of three questions at a time, the same recap before anything is recorded.
|
||||
You are not allowed to answer your own questions just because a form makes it easy.
|
||||
Keep `sid`: every later command takes `--session <sid>`. `open` failing: carry on in the terminal. When `open` adds `remote` and a `note`, give the link, ask whether it opened, and move to the terminal if not. Tell the person the link (with `"inApp":true`, never print it: only how many questions are waiting) and end every terminal message with the latest `terminalLine`, verbatim.
|
||||
|
||||
> **The one rule that keeps the page alive: while the session is open, every
|
||||
> turn ends on a `wait` (or `post --wait`) call, never on text.** Exit `10` means
|
||||
> "nobody has answered yet", not "done": relay one line and wait again in the
|
||||
> same turn, as many times as it takes. A turn that ends without a `wait`
|
||||
> running strands the person's next click.
|
||||
|
||||
## What to read, and when
|
||||
|
||||
All beside this file. Read one when its moment first comes, not before; when
|
||||
several are due at once (a build's start), read them in one batch.
|
||||
|
||||
| File (`help` topic) | Read it when |
|
||||
| --- | --- |
|
||||
| `building.md` (`building`) | You run `implement`, `implement-review` or `quick-task`: right after `open`, then `notes/implement.md` or `notes/quick-task.md`. |
|
||||
| `building-review.md` (`building-review`) | A build's review is asked for on the page (a `review` verdict, `__review`, Implement + Review's Stage 2). |
|
||||
| `notes/<workflow>.md` (`<workflow>`) | Right after `open`: `init` (also init-update), `pathfinder`, `plan`, `revise-plan`, `document`, `implement` (also implement-review), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`. The dashboard's is `console-launches.md`. |
|
||||
| `console-launches.md` (`launches`) | You are the dashboard. |
|
||||
| `console-finish.md` (`finish`) | Before your first `finish` post, and when a send carries `__commit`, or `__dashboard` from a finished screen. |
|
||||
| `console-stop.md` (`stop`) | A send carries `__stop`, or `__dashboard` with no finish up; or your notes say to post a `stopWarning`. |
|
||||
| `console-chat.md` (`chat`) | The first time `wait` or `chat` hands you a Quick question (`chat: [...]`). |
|
||||
| `console-workspace.md` (`workspace`) | `open` lists more than one folder, a `Workspace:` line arrives, or someone writes `@name`. |
|
||||
| `console-subagents.md` (`subagents`) | A `Subagents:` block arrives, or your workflow notes say to report helpers. |
|
||||
| `console-meter.md` (`meter`) | Only if a `run` is refused: your notes give the exact `run` to post. |
|
||||
| `console-attachments.md` (`attachments`) | A file you write under `specs/` cites a note's attachment. |
|
||||
| `console-trouble.md` (`trouble`) | Something goes wrong: `open` fails, a repeat delivery, a dead server. |
|
||||
|
||||
---
|
||||
|
||||
## Starting it
|
||||
|
||||
It needs Node 18+ on PATH (anything older exits naming the version), the
|
||||
person's own machine (the page is on `127.0.0.1`; in a cloud VM or remote
|
||||
sandbox do not offer it), and a foreground command of a minute at a time. When
|
||||
`open` thinks the machine is remote (SSH, a dev container, a Codespace) it adds
|
||||
`"remote"` and a `note`: give them the link, ask whether it opened, and move to
|
||||
the terminal if not. If anything fails, say so in one line and carry on in the
|
||||
terminal — that path loses nothing, and they can switch either way at any time.
|
||||
|
||||
1. `node "<CONSOLE>" open --workflow <w>`, where `<w>` is one of `dashboard`,
|
||||
`init`, `init-update`, `pathfinder`, `quick-task`, `plan`, `revise-plan`,
|
||||
`document`, `implement`, `implement-review`, `review`, `finalize`,
|
||||
`handoff`, `git`, `changelog`, `xray`, `diagnose`. Get it right: the page decides from it what
|
||||
to offer and what stopping costs. `--title` defaults to the folder name;
|
||||
`--spec specs/<idea>` when you already know the spec. It prints
|
||||
`{"ok":true,"sid":"...","session":"...","url":"...","terminalLine":"→ Look at the web console: ..."}`
|
||||
and opens the browser itself. `swept` is housekeeping, `workspace` and
|
||||
`subagents` are explained in their topic files.
|
||||
2. Pass each patch on stdin with `--file -` (The turn, below). Where you cannot
|
||||
(PowerShell), write it to a file in the `session` folder `open` printed —
|
||||
never into the project or `~/.plan2code/console/` itself — and pass that
|
||||
path. `open --file <payload>` opens with a first payload the same way.
|
||||
3. Post the first questions as soon as you have them. If getting there takes a
|
||||
while, post `{"agent":{"status":"working","activity":"Reading the plan"}}`
|
||||
first so the page says what you are doing.
|
||||
4. Tell the person, in one line, the link and how many questions are waiting.
|
||||
While the session is open, end every terminal message with the latest
|
||||
`terminalLine`, verbatim. When `open` printed `"inApp":true` the page is
|
||||
already in the desktop app's window: never print the link (here, after a
|
||||
resume or anywhere else), only the count; `terminalLine` leaves it out too.
|
||||
|
||||
Keep `sid`: every later command takes `--session <sid>`.
|
||||
|
||||
---
|
||||
Right after `open`, read `building.md` (implement, implement-review, quick-task only) and `notes/<workflow>.md`.
|
||||
|
||||
## The turn
|
||||
|
||||
```
|
||||
node "<CONSOLE>" post --session <sid> --file - --wait 240 <<'EOF'
|
||||
{ "settle": true, "items": [ ... ] }
|
||||
{"settle":true,"items":[...]}
|
||||
EOF
|
||||
```
|
||||
|
||||
`--file -` reads the patch from stdin: in bash or zsh a quoted heredoc
|
||||
(`<<'EOF'`) saves writing a file first. PowerShell has no heredoc and its pipe
|
||||
can mangle non-ASCII text, so there write the patch to a file in the session
|
||||
folder and pass `--file <path>`. `post --wait <N>` posts, then waits up to `N`
|
||||
seconds in the same command: use it for every post that hands the turn to the
|
||||
person, so a turn costs one command. It prints the post's line (its `open` is
|
||||
the required questions still open; optional cards and notices are not
|
||||
counted), then the wait's; the exit code is the wait's, and exit `3` means the post was refused
|
||||
and nothing waited. `--wait` with no number takes `--seconds`, else 240, so
|
||||
always give one; slices under 5 seconds count as 5. Plain
|
||||
`wait --session <sid> --seconds <N>` waits without posting.
|
||||
Keep the heredoc quoted (`<<'EOF'`). PowerShell has no heredoc: write the patch to a file in the `session` folder `open` printed (never in the project) and pass `--file <path>`. Size the `--wait` slice to your shell limit: 5 minutes or more `240` (tool timeout 300000 ms), about 2 minutes `90`, 60 seconds or unsure `45`.
|
||||
|
||||
**Size the slice to your shell timeout**, comfortably below its limit, so the
|
||||
command returns by itself rather than being killed:
|
||||
With nothing to post, `node "<CONSOLE>" wait --session <sid> --seconds 240` waits alone (same slice sizes).
|
||||
|
||||
| Your limit on one command | Use |
|
||||
| --- | --- |
|
||||
| 5 minutes or more | `240`, with the tool timeout set to 300000 ms |
|
||||
| about 2 minutes | `90` |
|
||||
| 60 seconds, or you cannot tell | `45` |
|
||||
**Every turn ends on a `wait` (or `post --wait`), never on text.**
|
||||
|
||||
Killing a wait mid-slice loses nothing; a result is marked collected only after
|
||||
it is printed, so the worst case is a repeat, never a lost answer.
|
||||
|
||||
| Exit | Meaning | What you do |
|
||||
| Exit | Meaning | Do |
|
||||
| --- | --- | --- |
|
||||
| `0` | They pressed Send, asked a Quick question, or both. stdout is the result. | Handle it (below), then post once, with `--wait`. |
|
||||
| `10` | Nobody has answered yet. | Relay one line, the `message` followed by the `terminalLine`, and wait again in the same turn. |
|
||||
| `20` | The server is gone. | `open --resume <sid> --workflow <yours>` (no `--no-open`: the restart has a new link, and the browser opens it), give them the new link, keep waiting. |
|
||||
| `30` | They pressed Cancel. | Stop. Ask what they want, in the terminal. |
|
||||
| `3` | (`post --wait` only) the post was refused; stderr says why. | Fix the patch and post again. |
|
||||
| `2` | Bad usage: a flag missing its value, or a patch that is not one readable JSON object. Nothing was posted. | Fix the command or the patch and run it again. |
|
||||
| 0 | A send arrived | Handle it (below), then one `post --wait` |
|
||||
| 10 | Nobody answered yet | Relay one line of your own, ending with the latest `terminalLine`, and wait again, same turn, without limit |
|
||||
| 20 | `{"gone":true,"fix":...}` | Run its `fix` (replace `<yours>` with your workflow), give the new link, keep waiting |
|
||||
| 30 | They canceled | Stop; ask what they want in the terminal |
|
||||
| 3 | Patch refused | stderr names the item, the field and the fix; correct it and post again |
|
||||
| 2 | Patch unreadable | stderr gives line, column and the spot; fix it and post again |
|
||||
|
||||
Do not poll faster, do not spin on `status`, and never stop after some number
|
||||
of slices: people step away and come back. After a finish, keep waiting the
|
||||
same way (`console-finish.md`). **Collect promptly:** a sent question is locked
|
||||
on the page, and a second send is blocked, until your next post lands.
|
||||
## A send
|
||||
|
||||
### Handling a send
|
||||
`reply` is what they would have typed: one line per question, parts joined with `; `. Act on it as their typed answer, in that turn, with no summary back. Open every `Image:` and `File:` path in it with your file-read tool before you answer.
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [
|
||||
{ "i": "q2", "type": "answer", "kind": "choice", "k": "A" },
|
||||
{ "i": "q3", "type": "comment", "text": "Please keep the header row.",
|
||||
"images": [{ "path": "/home/sam/.plan2code/console/sessions/<sid>/uploads/3f2b9c1e.jpg", "name": "header.png" }] }
|
||||
],
|
||||
"reply": "File format: a\nNote on What to call it: Please keep the header row.\n Image: /home/sam/.plan2code/console/sessions/<sid>/uploads/3f2b9c1e.jpg (header.png)" }
|
||||
```
|
||||
Other fields, when present: `session` (actions about the session, dispatch on `i`: `__launch` and `__pickup` run `resume`, then read `skillFile` and follow it in this conversation; `__stop`, `__dashboard`, `__commit`, `__changelog`, `__delete`, `__brief`, `__review`, `__done`, `__git` are covered by the topic file `read` names, or by your notes), `chat` (the seq numbers of Quick questions that need a reply), `read` (open each path now, before acting), `resume`, `skillFile`, `handoffFile`, `fallback` (hop fields: run `resume` as given).
|
||||
|
||||
**`reply` is the important field**: what they would have typed in the terminal,
|
||||
one line per question, every part of an answer joined by `; `. Treat it as their
|
||||
typed answer and follow the workflow from there; `actions` has the same with
|
||||
structure. Collecting it already set the page to "working" for you: do not post
|
||||
a status first. Act on it in that turn — no asking whether to proceed, no
|
||||
summary back.
|
||||
## A patch
|
||||
|
||||
A `comment` may carry `images` and `files` (`[{ path, name }]`), listed under the
|
||||
note in `reply` as `Image:` / `File:` lines. **Open every path with your
|
||||
file-read tool before you answer** — or say you could not read it. They live in
|
||||
the session's `uploads/`; never copy one into the project yourself
|
||||
(`console-attachments.md`).
|
||||
One-line JSON, only what changed; the patch merges (`items`, `topics`, `docs` and blocks by `id`; `thread` appends; `null` deletes a key). The console fills `status:"open"`, `required:true`, `allowOther:true`, empty `options` and `thread`, and option keys `A`, `B`, `C` by position, so leave them out.
|
||||
|
||||
An action whose `i` starts with `__` is about the session, not a question:
|
||||
`{"title":"Audit export","headline":{"stage":"Working","cleared":4,"total":9,"confidence":"One area still needs work."},"items":[...],"agent":{"status":"working","activity":"Reading the plan"}}`
|
||||
|
||||
| Action | Read |
|
||||
| --- | --- |
|
||||
| `__stop` (plain, or with `handoff: true`), `__dashboard` (no finish up) | `console-stop.md` |
|
||||
| `__commit`, `__dashboard` (from a finished screen) | `console-finish.md` |
|
||||
| `__launch` | `console-launches.md` |
|
||||
| `__delete` | `console-launches.md` (the dashboard only) |
|
||||
| `__brief` | `notes/pathfinder.md` |
|
||||
| `__review`, `__done` | `building-review.md` |
|
||||
| `__git` | `notes/git.md` |
|
||||
`headline.cleared`/`total` drive the progress bar: always fill them. `agent.activity` is one plain sentence; add `quietMinutes` (1 to 60) when a stretch may go silent. Say `status:"working"` only while you work on with nothing for the person to answer. A new open question hands the turn over by itself; with only a doc or notice up, post `"agent":{"status":"waiting"}` yourself before you wait.
|
||||
|
||||
A hop (`__launch`, `__dashboard`, `__commit`) arrives with `resume`, the exact
|
||||
command that resumes the session under the new workflow — run it as given —
|
||||
and, in an installed skill, `skillFile`, the `SKILL.md` to follow next.
|
||||
Every item: `id` (new for each question, whole session), `kind`, `title` (2 to 4 plain words), `body` (markdown: the question and why it matters), optional `topic`, `doc`, `required:false` (adds Skip), `token` (`{"A":"approved"}`: the typed word an answer stands for).
|
||||
|
||||
Then, in ONE post (with `--wait`):
|
||||
- `choice`: `{"id":"q1","kind":"choice","title":"Export format","body":"Which format?","options":[{"text":"CSV","detail":"Opens in Excel","recommended":true},{"text":"JSON","detail":"For scripts"}]}`. Back: `{k}` or `{text}`; `allowOther:false` drops the free-text row.
|
||||
- `text`: `{"id":"q2","kind":"text","title":"Who uses it","body":"Who, and for what?","placeholder":"For example: reviewers, in Excel every Monday."}`. Back: `{text}`. `pattern` plus `patternHint` checks shape (kebab-case). The placeholder is an offer, so write a whole answer. On the fresh-idea card in Pathfinder, Plan and Quick Task add `"templates":"idea"` (also when the idea came as the argument, with a one-line summary in `placeholder`; a resumed map, PLAN-DRAFT or checkpoint gets no idea card; never mention templates in the terminal); a Notebook tab fills a box marked `"fill":"note"`.
|
||||
- `confirm`: `{"id":"q3","kind":"confirm","title":"Keep going","body":"Continue?","yesLabel":"Yes","noLabel":"Not yet"}`. Back: `{yes,text?}`.
|
||||
- `recap`: `{"id":"q4","kind":"recap","title":"What we heard","body":"Is this right?","summary":"- ..."}`. Back: `{ok,text?}`.
|
||||
- `menu`: `{"id":"q5","kind":"menu","title":"Next step","body":"What now?","options":[{"text":"Plan it"}],"command":"/plan2code-1-plan"}`. Back: `{k}`.
|
||||
|
||||
- settle what they answered: `"settle": true` (below)
|
||||
- reply to every note in that item's `thread`
|
||||
- reply to any Quick question (`console-chat.md`)
|
||||
- publish the next batch of questions
|
||||
|
||||
You never post the status for a turn: a post that asks a new question, and any
|
||||
`wait` started with a question open (or a finish, the dashboard menu, the git
|
||||
board), hands the turn over by itself (`agent.status` becomes `waiting`). Say
|
||||
`"agent": { "status": "working" }` only while you work on with nothing for them
|
||||
to answer, and `"agent": { "status": "waiting" }` yourself when you go back to
|
||||
waiting with nothing open for them (only a doc or a notice on the page, a
|
||||
brief just delivered): `wait` leaves a working agent working then, since
|
||||
that is also how an agent waiting out its subagents looks.
|
||||
|
||||
### Replying to a note
|
||||
|
||||
```jsonc
|
||||
{ "items": [{ "id": "p4", "thread": [
|
||||
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
|
||||
] }] }
|
||||
```
|
||||
|
||||
`{ "who": "agent", "text": "<markdown>" }` — `text`, not `md`. The server already
|
||||
wrote their note into the thread: send only your new entries (`thread`
|
||||
appends). Answer what they asked in the thread, even when you also change a doc
|
||||
or re-ask; "I've updated the doc" alone leaves their question unanswered.
|
||||
|
||||
### Recording the answer
|
||||
|
||||
`"settle": true` marks every card from their latest send `answered`, with the
|
||||
answer they sent. `"settle": ["q2"]` names the cards instead — use it when only
|
||||
some are final (a pick that still owes its recap stays open). A card the same
|
||||
post reopens is never settled. To record a
|
||||
reading of your own, also send the item with its `answer` (it wins):
|
||||
`{ "k": "A" }`, `{ "ks": ["A","C"] }`, `{ "text": "audit-export" }`,
|
||||
`{ "yes": true }`, `{ "verdict": "changes", "text": "..." }`,
|
||||
`{ "done": [0,1], "state": "done" }`, `{ "rows": [...] }`. A settled card turns
|
||||
into a record ("A · Continue without it"), so settle every card you are done
|
||||
with — one left open stays on the page as a question still owed.
|
||||
|
||||
---
|
||||
|
||||
## Posting an update
|
||||
|
||||
```
|
||||
node "<CONSOLE>" post --session <sid> --file <patch.json | -> [--wait <N>]
|
||||
```
|
||||
|
||||
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` /
|
||||
`docs` and a doc's `blocks` merge by `id` (an unknown id is added), `thread`
|
||||
appends. **Send only what changed.** Never write a timestamp: the server stamps
|
||||
them. A refused patch is exit `3` with the reason on stderr; nothing is
|
||||
written.
|
||||
|
||||
While you work through a long stretch, say so:
|
||||
`{"agent":{"status":"working","activity":"Reading the plan"}}` — one plain
|
||||
sentence, shown in place of "thinking". The page calls a working agent stuck
|
||||
after two silent minutes: expecting longer, add `"quietMinutes": <1-60>` to
|
||||
`agent`. It only counts while you are working, so set it once.
|
||||
|
||||
`run` (session meter, `console-meter.md`), `folderIssue`
|
||||
(`console-workspace.md`) and `helpers` (`console-subagents.md`) are top-level
|
||||
keys too; `run` and `folderIssue` go to the session's ledger, never the page.
|
||||
|
||||
---
|
||||
|
||||
## The payload
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"title": "Audit export",
|
||||
"headline": { "stage": "Working", "cleared": 4, "total": 9,
|
||||
"confidence": "Looking solid, but one area still needs work.",
|
||||
"note": "optional sentence shown above the list" },
|
||||
"topics": [ { "id": "t2", "title": "How it behaves", "status": "current" } ],
|
||||
"items": [ /* the kinds below */ ],
|
||||
"docs": [ /* Documents, below */ ],
|
||||
"finish": { /* only at the end: console-finish.md */ },
|
||||
"agent": { "status": "waiting" }
|
||||
}
|
||||
```
|
||||
|
||||
Fill in `headline.cleared` / `total`: the progress bar is the first thing anyone
|
||||
looks at. `confidence` is a plain-English sentence, never raw scores. Post
|
||||
`"specDir": "specs/<idea>"` once the folder exists (or pass `--spec` to
|
||||
`open`): the page builds a resume command from it if you ever cannot answer a
|
||||
stop. `stopWarning` is in `console-stop.md`.
|
||||
|
||||
### Every item
|
||||
|
||||
**Every new question gets a new `id`**, for the whole session.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"id": "q7",
|
||||
"topic": "t2",
|
||||
"kind": "choice",
|
||||
"title": "Export format", // 2-4 plain words a newcomer understands
|
||||
"body": "The question, in markdown, with why it matters.",
|
||||
"required": true, // false adds a "Skip this one" link
|
||||
"doc": "report", // optional: a "Read ... in full" button for that doc
|
||||
"status": "open", // open | answered | reopened | skipped
|
||||
"token": { "A": "approved" } // optional: the typed word an answer stands for
|
||||
}
|
||||
```
|
||||
|
||||
`token` is only needed where the terminal word differs from the option's `k`
|
||||
or verdict `id`: without it, `reply` uses the key itself.
|
||||
|
||||
### The kinds
|
||||
|
||||
| `kind` | Use it for | Extra fields | You get back |
|
||||
| Kind | Use | Extra fields | Back |
|
||||
| --- | --- | --- | --- |
|
||||
| `choice` | one of several | `options[]`, `allowOther` | `{ k }` **or** `{ text }` |
|
||||
| `multi` | any number of several | `options[]`, `presets[]` | `{ ks[], text? }` |
|
||||
| `text` | free text | `placeholder`, `help`, `pattern`, `patternHint`, `templates` | `{ text }` |
|
||||
| `confirm` | yes or no | `yesLabel`, `noLabel`, `danger`, `consequences` | `{ yes, text? }` |
|
||||
| `recap` | play decisions back for agreement | `summary` (markdown) | `{ ok, text? }` |
|
||||
| `review` | read something, then approve | `doc` (always), `summary`, `verdicts[]` (each `{ id, label, danger? }`: `label`, not `text`), `nothingYet` (the line under the buttons; defaults to "Nothing has been changed yet…", so `false` when the change is already on disk) | `{ verdict, text? }` |
|
||||
| `checklist` | steps only they can do | `steps[]`, `valuesLabel` | `{ done?[], state?, text? }` (each left out when nothing was ticked or picked) |
|
||||
| `menu` | what to do next | `options[]`, `command` | `{ k }` |
|
||||
| `list` | reorder or edit a breakdown | `rows[{id,title,body}]` | `{ rows[] }`, or `{ text }` when they changed nothing; `reply` names renames, additions and removals |
|
||||
| `notice` | something to read, no answer | — | nothing |
|
||||
| `multi` | any number of several | `options`, `presets:[{label,ks}]` | `{ks,text?}` |
|
||||
| `review` | read, then approve | `doc` (required), `summary`, `verdicts:[{id,label,danger?}]`, `nothingYet` (false once the change is on disk) | `{verdict,text?}` |
|
||||
| `checklist` | steps only they can do | `steps`, `valuesLabel` | `{done?,state?,text?}` |
|
||||
| `list` | reorder or edit a breakdown | `rows:[{id,title,body}]` | `{rows}` or `{text}` |
|
||||
| `notice` | read, no answer | none | none |
|
||||
|
||||
An option is `{ "k": "A", "text": "short label", "detail": "the trade-off", "recommended": true }`.
|
||||
`detail` is the difference between a person choosing and a person guessing.
|
||||
Items show in the order sent: send them in the order you want them answered.
|
||||
|
||||
- **`choice`**: one of the two, never both. The page offers "Something else, in
|
||||
your own words" in the same radio group; read `k` if it is there, otherwise
|
||||
`text`. `"allowOther": false` drops it when the options are the whole set.
|
||||
- **`multi`**: `text` joins the ticks rather than replacing them. `presets`
|
||||
(`[{ "label": "Critical and warnings", "ks": ["1","2"] }]`) only tick boxes.
|
||||
- **`pattern`** is a JavaScript regex checked as they type, with `patternHint`
|
||||
shown when it fails. Use it for anything with a shape, above all kebab-case.
|
||||
- **A placeholder is an offer.** The **Autofill suggestion** button drops it
|
||||
into the box as a real answer (a lead-in like "For example:" is stripped), so
|
||||
write a whole example in their voice, one that satisfies any `pattern`.
|
||||
- **Starter templates:** on the `text` card that asks for a **fresh idea** in
|
||||
Pathfinder, Plan and Quick Task, add `"templates": "idea"` (any other kind or
|
||||
value is exit 3). Launched with notes or an idea as the argument? Still set
|
||||
it, with a one-line summary in `placeholder`. A resumed map, PLAN-DRAFT or
|
||||
checkpoint gets no idea card. Only the box's text comes back; never mention
|
||||
templates in the terminal.
|
||||
- **Fill from a Notebook tab:** on a `text` item, `"fill": "note"` (its only
|
||||
value; any other kind or value is exit 3) has the page fill the first open one
|
||||
once, with the tab's text and ticked pictures, when the person started from a
|
||||
Notebook tab. You read it only when they send that box (Send, or Stop or
|
||||
Back to the dashboard, which carry ready answers).
|
||||
- **Recommend only when you genuinely know better and can say why.** "Which
|
||||
format survives Excel?" is yours; "Who is this for?" is not — there a
|
||||
recommendation is an anchor people rubber-stamp. At most one per question.
|
||||
**Documents:** the first patch that carries `docs` is answered with a `read` pointer to `console-docs.md`.
|
||||
|
||||
Items appear in the order you send them, and the person walks the open ones with
|
||||
Previous / Next: send them in the order you want them answered.
|
||||
## Settling and notes
|
||||
|
||||
### Documents
|
||||
`"settle":true` marks every card in their latest send answered with what they sent; `"settle":["q2"]` names cards. A card the same post reopens is never settled. To record your own reading, send the item with `answer` (`{k}`, `{ks}`, `{text}`, `{yes}`, `{verdict,text}`, `{rows}`).
|
||||
|
||||
```jsonc
|
||||
"docs": [{
|
||||
"id": "map", "title": "What we've agreed",
|
||||
"note": "what changed in this version",
|
||||
"saved": "specs/lunch-vote/pathfinder/map.md",
|
||||
"blocks": [
|
||||
{ "id": "b1", "state": "settled", "md": "## Where we're headed\n\n..." },
|
||||
{ "id": "b2", "state": "assumed", "md": "### File format\n\nAssuming CSV..." },
|
||||
{ "id": "b3", "state": "draft", "md": "### Still to work out\n\n- ..." },
|
||||
{ "id": "b4", "file": "specs/lunch-vote/overview.md" }
|
||||
]
|
||||
}]
|
||||
```
|
||||
Every note in an item's `thread` gets a reply: `{"id":"p4","thread":[{"who":"agent","text":"..."}]}`. Send only new entries.
|
||||
|
||||
Each doc is a tab. Patch blocks as decisions land: `{ "id": "b2", "state":
|
||||
"settled" }` settles b2 and keeps its text, blocks you leave out stay, a new id
|
||||
goes at the end, `{ "id": "b3", "_delete": true }` removes one (a doc entry
|
||||
with `"_delete": true` removes the whole tab).
|
||||
## What the console refuses (exit 3)
|
||||
|
||||
- **`state`**: `settled` (decided), `assumed` (picked to keep going, still open:
|
||||
shown dashed, "Assumed for now"), `draft` (dimmed). Marking assumptions
|
||||
honestly is what stops a half-finished doc reading as decisions.
|
||||
- **`file`** instead of `md`: the console reads the block's text from that file
|
||||
(relative to the project, never outside it). Re-send the block, or the doc
|
||||
with `"refresh": true`, after the file changes. `"select": "tasks"` keeps only
|
||||
its `- [ ] **Task N.M:**` lines. Never paste a file you could name.
|
||||
- **`image`** instead of `md`: `{ "id", "image": "shots/run.png", "alt": "..." }`
|
||||
shows a PNG, JPEG or WebP (5 MB at most) saved directly in the session's
|
||||
`shots/` folder (the `session` path `open` printed), named with letters,
|
||||
digits, `.`, `_` or `-`; anything else is exit `3`.
|
||||
- **`version`** moves by itself: a known doc whose content changed is the next
|
||||
version. Send one only to jump; it never goes back. Write a one-line `note`
|
||||
when you change a doc, and `"stale": true` while answers it does not reflect
|
||||
have landed.
|
||||
- **`saved`** is the path of the file the doc mirrors, when one exists: the page
|
||||
shows the path instead of a download. Leave it off docs that exist only here.
|
||||
- more than three open required questions at once (optional cards and notices do not count)
|
||||
- internal vocabulary in a title (grill, frontier, fog, HITL, AFK, durable, `Locked:`, `Blocked by:`, `State:`)
|
||||
- more than one recommended option on a question
|
||||
- loop completion markers (`TASK_COMPLETE`, `PHASE_COMPLETE` and the rest)
|
||||
- a bare Requirements, Feasibility, Integration or Risk followed by a number (hyphenate or reword)
|
||||
- a doc `version` that goes back (leave `version` out)
|
||||
- a finish `command` with `<` or `>` in it
|
||||
- a note left without a reply
|
||||
- a `finish` while `stopWarning` is set or a helper is still `running`
|
||||
- a `stop` with no `finish` (`stop --session <sid> --force` for a dead page)
|
||||
|
||||
---
|
||||
It cannot see these two: every turn ends on a `wait`, and no new open question after a `finish`.
|
||||
|
||||
## House rules the server enforces
|
||||
Ending: every session end posts `finish` (`{"settle":true,"finish":{"headline":"Phase 3 is done","body":"...","command":"/plan2code-3-implement specs/x/overview.md","dashboard":true}}`, with `--wait`, then keep waiting for the button), then `stop`. A pause (headline starting "Paused") has no `dashboard` and stops at once. Your notes give your workflow's finish; read `console-finish.md` for every field.
|
||||
|
||||
A patch that breaks one is refused, exit `3`, with the reason:
|
||||
## Read when
|
||||
|
||||
1. **At most three questions open at once.**
|
||||
2. **No internal vocabulary in a title**: *grill*, *frontier*, *fog*, *HITL*,
|
||||
*durable*, `Locked:`, `Blocked by:`.
|
||||
3. **At most one recommended option per question.**
|
||||
4. **No loop completion markers** (`TASK_COMPLETE`, `PHASE_COMPLETE` and the rest).
|
||||
5. **No bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a
|
||||
number** (the metrics collector scrapes that): hyphenate or reword. Rules 4
|
||||
and 5 skip `file` blocks: those words are already on disk.
|
||||
6. **Chat replies hold together** (`console-chat.md`).
|
||||
7. **`run`, `folderIssue` and `helpers` are well formed** (their topic files).
|
||||
8. **A doc's `version` never goes back.**
|
||||
9. **A finish `command` has no placeholders** (`<` or `>`).
|
||||
10. **Every note gets a reply.** A card whose thread ends with the person's own
|
||||
words stays that way until a patch adds an agent reply to it; settling or
|
||||
reopening it does not count. Exempt once the item is deleted, or the whole
|
||||
session is ending.
|
||||
|
||||
---
|
||||
|
||||
## Ending
|
||||
|
||||
Every session end — done, a pause, a stop request, an off-ramp — posts a
|
||||
`finish` **before** `stop`, and every ending but a pause keeps waiting for the
|
||||
person's last button. Read `console-finish.md` before your first finish post:
|
||||
it has the fields, the dashboard button and the order. Before any finish, every
|
||||
subagent or background job you started must have reported back.
|
||||
|
||||
---
|
||||
|
||||
## Worked example
|
||||
|
||||
The first questions of a pathfinder session, piped in with `post --file - --wait 240`:
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "Audit export",
|
||||
"headline": { "stage": "Charting", "cleared": 0, "total": 6 },
|
||||
"items": [
|
||||
{ "id": "q1", "kind": "choice", "title": "What you end up with",
|
||||
"body": "When this is done, what exists that does not exist now?",
|
||||
"options": [
|
||||
{ "k": "A", "text": "A plan, ready to build from", "detail": "We write the decisions down. Nothing is built yet.", "recommended": true },
|
||||
{ "k": "B", "text": "A change already made", "detail": "Small enough to just do. We would skip planning entirely." }
|
||||
] },
|
||||
{ "id": "q2", "kind": "text", "title": "Who uses it",
|
||||
"body": "Who uses the result, and what do they do with it the day it lands?",
|
||||
"placeholder": "For example: compliance reviewers, who open it in Excel every Monday." }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
It lands and waits in one command; the new questions make it the person's turn.
|
||||
| File | When |
|
||||
| --- | --- |
|
||||
| `notes/<workflow>.md` | right after `open` |
|
||||
| `building.md` | right after `open`: implement, implement-review, quick-task |
|
||||
| `console-launches.md` | you are the dashboard |
|
||||
| `console-meter.md` | a `run` was refused |
|
||||
| `console-attachments.md` | a file you write under `specs/` cites a note's attachment |
|
||||
| `console-trouble.md` | something breaks (a failed `open`, a repeat delivery, a dead server) |
|
||||
+22
-18
@@ -4,7 +4,7 @@ import path from "node:path";
|
||||
|
||||
import { CHAT_LIMIT } from "./public/chat.js";
|
||||
import { appendJsonLine, nowIso, readJson, readJsonLines, writeJsonAtomic } from "./files.mjs";
|
||||
import { isPlainObject, proseProblems } from "./patches.mjs";
|
||||
import { isPlainObject, proseProblems, rule } from "./patches.mjs";
|
||||
|
||||
/* ------------------------------------------------------- the chat inbox */
|
||||
|
||||
@@ -143,12 +143,12 @@ export function chatReplyLines(entries) {
|
||||
const lines = [];
|
||||
for (const e of entries) {
|
||||
if (e.kind === "message") {
|
||||
lines.push(`Quick question: ${indent(e.text, " ")}`);
|
||||
lines.push(`Quick question (${e.seq}): ${indent(e.text, " ")}`);
|
||||
if (e.about && e.about.label) lines.push(` About: ${indent(e.about.label, " ")}`);
|
||||
for (const img of e.images || []) lines.push(` Image: ${img.path} (${img.name})`);
|
||||
for (const f of e.files || []) lines.push(` File: ${f.path} (${f.name})`);
|
||||
} else if (e.kind === "decision") {
|
||||
lines.push(`${e.decision === "approve" ? "Approved" : "Declined"}: edit ${e.re}`);
|
||||
lines.push(`${e.decision === "approve" ? "Approved" : "Declined"} (${e.seq}): edit ${e.re}`);
|
||||
if (e.text) lines.push(` Note: ${indent(e.text, " ")}`);
|
||||
} else if (e.kind === "reset") {
|
||||
lines.push("New conversation started. Treat earlier chat as closed.");
|
||||
@@ -181,7 +181,8 @@ function underSpec(file, specDir) {
|
||||
export function validateChat(state, entries) {
|
||||
const replies = state?.chat?.replies;
|
||||
if (replies == null) return [];
|
||||
if (!Array.isArray(replies)) return ['"chat.replies" must be an array'];
|
||||
const right = { chat: { replies: [{ re: 12, md: "..." }] } };
|
||||
if (!Array.isArray(replies)) return [rule("", "chat.replies", "must be an array", right)];
|
||||
const problems = [];
|
||||
const targets = new Set(
|
||||
entries.filter((e) => e.kind === "message" || e.kind === "decision").map((e) => e.seq)
|
||||
@@ -189,34 +190,36 @@ export function validateChat(state, entries) {
|
||||
const ids = new Set();
|
||||
for (const r of replies) {
|
||||
if (!isPlainObject(r)) {
|
||||
problems.push("every chat reply must be an object");
|
||||
problems.push(rule("", "chat.replies", "every reply must be an object", right));
|
||||
continue;
|
||||
}
|
||||
const name = typeof r.id === "string" && r.id.trim() ? r.id : "(no id)";
|
||||
if (name === "(no id)") problems.push('every chat reply needs a non-empty string "id"');
|
||||
else if (ids.has(r.id)) problems.push(`duplicate chat reply id "${r.id}"`);
|
||||
const at = `chat reply "${name}"`;
|
||||
if (name === "(no id)") problems.push(rule(at, "id", 'needs a non-empty string "id" (or "re", which names it)', right));
|
||||
else if (ids.has(r.id)) problems.push(rule(at, "id", "is used twice", right));
|
||||
ids.add(r.id);
|
||||
if (!Number.isInteger(r.re) || !targets.has(r.re)) {
|
||||
problems.push(`chat reply "${name}" needs "re": the seq of the message or decision it answers`);
|
||||
problems.push(rule(at, "re", "needs the seq of the message or decision it answers", right));
|
||||
}
|
||||
if (!Number.isInteger(r.conversation)) problems.push(`chat reply "${name}" needs an integer "conversation"`);
|
||||
if (typeof r.md !== "string" || !r.md.trim()) problems.push(`chat reply "${name}" needs its answer in "md"`);
|
||||
if (!Number.isInteger(r.conversation)) problems.push(rule(at, "conversation", "needs an integer", right));
|
||||
if (typeof r.md !== "string" || !r.md.trim()) problems.push(rule(at, "md", "needs the answer", right));
|
||||
|
||||
const p = r.proposal;
|
||||
if (p != null) {
|
||||
if (!isPlainObject(p)) problems.push(`chat reply "${name}" "proposal" must be an object`);
|
||||
const proposalRight = { chat: { replies: [{ re: 12, md: "...", proposal: { summary: "Rename the helper", files: ["src/util.mjs"] } }] } };
|
||||
if (!isPlainObject(p)) problems.push(rule(at, "proposal", "must be an object", proposalRight));
|
||||
else {
|
||||
if (typeof p.summary !== "string" || !p.summary.trim()) {
|
||||
problems.push(`chat reply "${name}" proposal needs a plain-English "summary"`);
|
||||
problems.push(rule(at, "proposal.summary", "needs a plain-English summary", proposalRight));
|
||||
}
|
||||
if (!Array.isArray(p.files) || !p.files.length) {
|
||||
problems.push(`chat reply "${name}" proposal needs "files": the project files it would change`);
|
||||
problems.push(rule(at, "proposal.files", "needs the project files it would change", proposalRight));
|
||||
} else {
|
||||
for (const f of p.files) {
|
||||
if (!projectRelative(f)) {
|
||||
problems.push(`chat reply "${name}" proposal file "${f}" must be a project-relative path`);
|
||||
problems.push(rule(at, "proposal.files", `"${f}" must be a project-relative path`, proposalRight));
|
||||
} else if (state.specDir && underSpec(f, state.specDir)) {
|
||||
problems.push(`a chat edit cannot touch the running skill's own files under ${state.specDir}/`);
|
||||
problems.push(rule(at, "proposal.files", `a chat edit cannot touch the running skill's own files under ${state.specDir}/`, proposalRight));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -226,12 +229,13 @@ export function validateChat(state, entries) {
|
||||
if (r.changed != null) {
|
||||
const count = (n) => Number.isInteger(n) && n >= 0;
|
||||
if (!Array.isArray(r.changed) || !r.changed.every((c) => isPlainObject(c) && typeof c.file === "string" && count(c.added) && count(c.removed))) {
|
||||
problems.push(`chat reply "${name}" "changed" must be a list of { file, added, removed }`);
|
||||
problems.push(rule(at, "changed", "must be a list of { file, added, removed }", { changed: [{ file: "src/util.mjs", added: 3, removed: 1 }] }));
|
||||
}
|
||||
}
|
||||
|
||||
problems.push(...proseProblems(String(r.md ?? ""), `${at} md`));
|
||||
if (isPlainObject(p) && typeof p.summary === "string") problems.push(...proseProblems(p.summary, `${at} proposal.summary`));
|
||||
}
|
||||
|
||||
const prose = JSON.stringify(replies.map((r) => [r && r.md, r && r.proposal && r.proposal.summary]));
|
||||
problems.push(...proseProblems(prose, "a chat reply"));
|
||||
return problems;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// Plan2Code Web Console - the Implementation Loop's setup, remembered per project.
|
||||
|
||||
import path from "node:path";
|
||||
|
||||
import { ensureDir, HOME_DIR, readJson, withStateLock, writeJsonAtomic } from "./files.mjs";
|
||||
import { foldKey } from "./workspace.mjs";
|
||||
|
||||
// One file for the person, beside workspaces.json and looks.json, keyed by the
|
||||
// folder a session runs in (FR-4: one entry per project, used for any spec):
|
||||
//
|
||||
// { "schema": 1, "projects": { "<folded worktree>": { ...setup, "saved": "<iso>" } } }
|
||||
//
|
||||
// Never under specs/: the server never writes into a project. The quick check
|
||||
// is stored text only; nothing in the console ever runs it.
|
||||
export const LOOP_SETUP_FILE = path.join(HOME_DIR, "loop-setup.json");
|
||||
export const LOOP_SETUP_LOCK = "loop-setup.json.lock";
|
||||
|
||||
const LEVELS = ["critical", "warning", "suggestion"];
|
||||
const FIX_MODES = ["levels", "smart"];
|
||||
const ON_QUESTION = ["pause", "stop", "guess"];
|
||||
const AFTER_LAST = ["offer-finalize", "run-finalize"];
|
||||
const NOTIFY_KINDS = ["query", "discord", "slack", "teams", "google-chat", "json"];
|
||||
// The kinds where the person names the parameter or field that holds the message.
|
||||
const NAMED_KINDS = ["query", "json"];
|
||||
|
||||
export const LOOP_DEFAULTS = Object.freeze({
|
||||
review: true,
|
||||
fixMode: "smart",
|
||||
fix: Object.freeze([...LEVELS]),
|
||||
commit: true,
|
||||
onQuestion: "guess",
|
||||
afterLast: "offer-finalize",
|
||||
quickCheck: "",
|
||||
retryOnce: true,
|
||||
silenceMinutes: 20,
|
||||
notifyKind: "query",
|
||||
notifyUrl: "",
|
||||
notifyParam: "message",
|
||||
});
|
||||
|
||||
/** An http or https address in printable ASCII, with a host and no user name or password (the app's `valid_url`). */
|
||||
function isNotifyUrl(text) {
|
||||
if (text.length > 2000 || !/^https?:\/\/[^/?#@]+([/?#][!-~]*)?$/i.test(text) || /[^!-~]/.test(text)) return false;
|
||||
try {
|
||||
return Boolean(new URL(text).hostname);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Problems with a setup entry, as sentences naming the field; empty when it is good. */
|
||||
export function loopSetupProblems(entry) {
|
||||
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return ["the setup must be an object"];
|
||||
const problems = [];
|
||||
for (const key of Object.keys(entry)) {
|
||||
if (!Object.hasOwn(LOOP_DEFAULTS, key)) problems.push(`"${key}" is not a setup field`);
|
||||
}
|
||||
for (const key of ["review", "commit", "retryOnce"]) {
|
||||
if (typeof entry[key] !== "boolean") problems.push(`"${key}" must be true or false`);
|
||||
}
|
||||
if (!Array.isArray(entry.fix) || !entry.fix.every((l) => LEVELS.includes(l)) || new Set(entry.fix).size !== entry.fix.length) {
|
||||
problems.push(`"fix" must list distinct levels from ${LEVELS.join(", ")}`);
|
||||
}
|
||||
if (!FIX_MODES.includes(entry.fixMode)) problems.push(`"fixMode" must be one of ${FIX_MODES.join(", ")}`);
|
||||
if (!ON_QUESTION.includes(entry.onQuestion)) problems.push(`"onQuestion" must be one of ${ON_QUESTION.join(", ")}`);
|
||||
if (!AFTER_LAST.includes(entry.afterLast)) problems.push(`"afterLast" must be one of ${AFTER_LAST.join(", ")}`);
|
||||
if (typeof entry.quickCheck !== "string" || /[\r\n]/.test(entry.quickCheck) || entry.quickCheck.length > 500) {
|
||||
problems.push('"quickCheck" must be one line of at most 500 characters (empty for none)');
|
||||
}
|
||||
if (!Number.isInteger(entry.silenceMinutes) || entry.silenceMinutes < 1 || entry.silenceMinutes > 60) {
|
||||
problems.push('"silenceMinutes" must be a whole number from 1 to 60');
|
||||
}
|
||||
if (typeof entry.notifyUrl !== "string" || (entry.notifyUrl !== "" && !isNotifyUrl(entry.notifyUrl))) {
|
||||
problems.push('"notifyUrl" must be an http or https web address, without a user name or password (empty for none)');
|
||||
}
|
||||
if (!NOTIFY_KINDS.includes(entry.notifyKind)) problems.push(`"notifyKind" must be one of ${NOTIFY_KINDS.join(", ")}`);
|
||||
// The name only matters beside an address and for a kind that uses it: the field is hidden otherwise.
|
||||
if (typeof entry.notifyParam !== "string" || (entry.notifyUrl && NAMED_KINDS.includes(entry.notifyKind) && !/^[A-Za-z0-9._~-]{1,64}$/.test(entry.notifyParam))) {
|
||||
problems.push('"notifyParam" must be 1 to 64 letters, digits, or - _ . ~');
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
function readStore() {
|
||||
const saved = readJson(LOOP_SETUP_FILE, null);
|
||||
const ok = saved && saved.schema === 1 && saved.projects && typeof saved.projects === "object" && !Array.isArray(saved.projects);
|
||||
return ok ? saved : { schema: 1, projects: {} };
|
||||
}
|
||||
|
||||
/**
|
||||
* The setup for this project: the saved entry over the defaults, or the
|
||||
* defaults alone. `remembered` says which, so the setup screen can tell a
|
||||
* first visit from a returning one. A missing, unreadable or foreign-schema
|
||||
* file reads as empty. An entry saved before `fixMode` existed fixed by level,
|
||||
* so it keeps doing that rather than taking the newer default.
|
||||
*/
|
||||
export function readLoopSetup(project) {
|
||||
const saved = readStore().projects[foldKey(project)];
|
||||
if (saved && typeof saved === "object") return { ...LOOP_DEFAULTS, fix: [...LOOP_DEFAULTS.fix], fixMode: "levels", ...saved, remembered: true };
|
||||
return { ...LOOP_DEFAULTS, fix: [...LOOP_DEFAULTS.fix], remembered: false };
|
||||
}
|
||||
|
||||
/** Validate and save this project's setup; throws an Error listing the problems. */
|
||||
export function saveLoopSetup(project, entry) {
|
||||
const problems = loopSetupProblems(entry);
|
||||
if (problems.length) {
|
||||
const err = new Error(`the loop setup is not valid: ${problems.join("; ")}`);
|
||||
err.problems = problems;
|
||||
throw err;
|
||||
}
|
||||
ensureDir(path.dirname(LOOP_SETUP_FILE));
|
||||
return withStateLock(
|
||||
path.dirname(LOOP_SETUP_FILE),
|
||||
() => {
|
||||
const store = readStore();
|
||||
// Only the known fields are kept, in the defaults' order.
|
||||
const known = Object.fromEntries(Object.keys(LOOP_DEFAULTS).map((key) => [key, entry[key]]));
|
||||
store.projects[foldKey(project)] = { ...known, saved: new Date().toISOString() };
|
||||
writeJsonAtomic(LOOP_SETUP_FILE, { schema: 1, projects: store.projects });
|
||||
return readLoopSetup(project);
|
||||
},
|
||||
LOOP_SETUP_LOCK,
|
||||
);
|
||||
}
|
||||
@@ -1,27 +1,14 @@
|
||||
# Changelog on the Web Console
|
||||
# Changelog
|
||||
|
||||
Workflow notes for `changelog`, part of the web console contract (`console.md`).
|
||||
`changelog`: post `activity` while you read the history and diff. One card per step, each only when needed:
|
||||
|
||||
Open with `--workflow changelog` (launched from the dashboard: resume the
|
||||
session instead). Post `activity` while you read the history and the diff. One
|
||||
card per step, each asked only when the step needs it:
|
||||
|
||||
| Step | On the page |
|
||||
| Step | Card |
|
||||
| --- | --- |
|
||||
| Version | A `choice`, "Which version?": the computed version (recommended) with its reason in `body` (main is at X, the branch has Y), "Keep Y" when the branch's own entry could stay, and "Another version" (`allowOther`). A `choice` does not check what is typed, so check it yourself: anything that is not `X.Y.Z` gets the card again with a `thread` reply saying so. Left out when the entry is already right. |
|
||||
| Entries | A `list` titled "Entries to add": one row per suggested entry, `title` the entry line itself (the part they can edit) and `body` its section (`Added`, `Fixed`…). Removable and reorderable; `reply` names renames, additions and removals. A row they add has no section: ask, or file it where it reads best and say so. |
|
||||
| The result | The final entry as a doc (`id: "entry"`, marked `"saved": "CHANGELOG.md"` once written) plus a `review` card with verdicts `write` ("Write it"), `change` and `stop`. |
|
||||
| package.json | A `confirm` with the `old → new` in `consequences`. |
|
||||
| Commit this now? | A `confirm`, "Commit this now?". |
|
||||
| Version | `choice` "Which version?": the computed version (recommended, reason in `body`), "Keep Y" when the branch's entry could stay, "Another version" (`allowOther`). Typed text is unchecked: anything but `X.Y.Z` gets the card again with a `thread` reply. Skipped when the entry is right. |
|
||||
| Entries | `list` "Entries to add": `title` the entry line, `body` its section. `reply` names renames, additions, removals. A row they add has no section: ask, or file it and say so. |
|
||||
| Result | Doc `entry` (`"saved":"CHANGELOG.md"` once written) plus a `review` with verdicts `write`, `change`, `stop`. |
|
||||
| package.json | `confirm`, `old → new` in `consequences`. |
|
||||
| Commit now? | `confirm` "Commit this now?" |
|
||||
|
||||
A yes to "Commit this now?" ends no session (no `finish`, no `stop`): settle
|
||||
the card, resume as `git` (`open --resume <sid> --no-open --workflow git`),
|
||||
then read `~/.agents/skills/plan2code-git/SKILL.md` with your file-read tool
|
||||
and start with its commit flow, in this same session, as a dashboard launch
|
||||
does (`console-launches.md`); the resume clears Changelog's page for it.
|
||||
Entered from **Update CHANGELOG first** on a finished Quick Task or Finalize
|
||||
(`console-finish.md`): the hop is the same as a dashboard launch, and nothing
|
||||
else changes. The yes above is the exit to Git as always, so the person lands in
|
||||
the commit flow with the CHANGELOG already updated.
|
||||
Finish, on a no: `"dashboard": true` and the version and entries in `body`,
|
||||
with no `command`. A stop's finish is the bare `/plan2code-changelog`.
|
||||
A yes ends no session (no `finish`): settle the card, resume as `git` (`open --resume <sid> --no-open --workflow git`), read `~/.agents/skills/plan2code-git/SKILL.md` and start its commit flow.
|
||||
A no finishes with `"dashboard":true`, version and entries in `body`, no `command`. A stop's `command` is `/plan2code-changelog`.
|
||||
@@ -1,83 +1,38 @@
|
||||
# Diagnose on the Web Console
|
||||
|
||||
Workflow notes for `diagnose`, part of the web console contract (`console.md`).
|
||||
# Diagnose
|
||||
|
||||
## The bug
|
||||
|
||||
A typed argument that already describes the bug skips the cards it answers.
|
||||
Otherwise ask in one batch (at most three open), posted with `--wait`:
|
||||
An argument that already describes the bug skips the cards it answers. Otherwise one `--wait` batch, no `templates`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"title": "Diagnose a bug",
|
||||
"headline": { "stage": "The bug", "cleared": 0, "total": 3 },
|
||||
"items": [
|
||||
{ "id": "bug", "kind": "text", "title": "What is wrong",
|
||||
"body": "The bug, in a sentence or two.",
|
||||
"placeholder": "The CSV export drops the last row when the report has more than 100 rows." },
|
||||
{ "id": "expected", "kind": "text", "title": "Expected and actual",
|
||||
"body": "What should happen, and what happens instead.",
|
||||
"placeholder": "Expected 150 rows in the file; it has 149, and the last order is missing." },
|
||||
{ "id": "see-it", "kind": "text", "title": "How to see it",
|
||||
"body": "The steps, command, page or input that shows it, and since when if you know.",
|
||||
"placeholder": "Run npm run export -- --month 2026-09 and count the rows. It worked last month." }
|
||||
]
|
||||
}
|
||||
{"title":"Diagnose a bug","headline":{"stage":"The bug","cleared":0,"total":3},"items":[{"id":"bug","kind":"text","title":"What is wrong","body":"The bug, in a sentence or two."},{"id":"expected","kind":"text","title":"Expected and actual","body":"What should happen, and what happens instead."},{"id":"see-it","kind":"text","title":"How to see it","body":"The steps, command, page or input that shows it, and since when if known."}]}
|
||||
```
|
||||
|
||||
No `"templates"` on these cards: the starter templates are for a fresh idea,
|
||||
and a bug report is not one. A follow-up the answers leave open is a new card
|
||||
with a new id.
|
||||
A follow-up the answers leave open is a new card with a new id.
|
||||
|
||||
## The cause
|
||||
|
||||
Post the cause as a doc, `id` `"cause"`, as soon as there is something to show,
|
||||
and grow it as evidence lands, with `"agent": { "status": "working",
|
||||
"activity": "..." }` while you reproduce and narrow:
|
||||
Doc `cause`, posted as soon as there is something to show and grown as evidence lands, with `agent` `working` while you reproduce:
|
||||
|
||||
```jsonc
|
||||
"docs": [{ "id": "cause", "title": "The cause", "note": "Reproduced; narrowing", "blocks": [
|
||||
{ "id": "repro", "state": "settled", "md": "## Reproduction\n\n`node scripts/export-check.mjs` fails: 149 rows, expected 150." },
|
||||
{ "id": "found", "state": "settled", "md": "## The cause\n\n`src/export.ts` `writeRows()`: the loop stops at `rows.length - 1`. **Proven** by the reproduction." },
|
||||
{ "id": "fix", "state": "settled", "md": "## Suggested fix\n\nLoop to `rows.length`. **Size:** Small (Quick Task)." }
|
||||
]}]
|
||||
{"docs":[{"id":"cause","title":"The cause","note":"Reproduced; narrowing","blocks":[{"id":"repro","state":"settled","md":"## Reproduction\n\n..."},{"id":"found","state":"settled","md":"## The cause\n\n..."},{"id":"fix","state":"settled","md":"## Suggested fix\n\n... **Size:** Small (Quick Task)."}]}]}
|
||||
```
|
||||
|
||||
- **Unproven** guesses are `assumed` blocks, one per guess, ranked, each with
|
||||
its evidence and what would confirm it. A guess the evidence proves becomes
|
||||
`settled`; one it rules out is removed (`"_delete": true`).
|
||||
- Keeping a failing test inside the project is a `confirm` card pointing at
|
||||
the doc (`"doc": "cause"`), `yesLabel` "Keep it", `noLabel` "Throw it away".
|
||||
- Unproven guesses are `assumed` blocks, ranked, each with its evidence and what would confirm it. Proven: `settled`. Ruled out: `"_delete":true`.
|
||||
- Keeping a failing test in the project: `confirm` with `"doc":"cause"`, `yesLabel` "Keep it", `noLabel` "Throw it away".
|
||||
|
||||
## The bug name
|
||||
|
||||
With the cause written, ask the folder name, posted with `--wait`:
|
||||
After the cause, `--wait`:
|
||||
|
||||
```jsonc
|
||||
{ "id": "name", "kind": "text", "title": "Name for the write-up", "doc": "cause",
|
||||
"body": "The diagnosis is saved as `specs/<name>/DIAGNOSIS-<date>.md`. Lowercase words joined by dashes.",
|
||||
"placeholder": "csv-export-drops-rows",
|
||||
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$",
|
||||
"patternHint": "Lowercase letters, numbers and dashes, like csv-export-drops-rows." }
|
||||
{"id":"name","kind":"text","title":"Name for the write-up","doc":"cause","body":"Saved as `specs/<name>/DIAGNOSIS-<date>.md`. Lowercase words joined by dashes.","placeholder":"csv-export-drops-rows","pattern":"^[a-z0-9]+(-[a-z0-9]+)*$","patternHint":"Lowercase letters, numbers and dashes."}
|
||||
```
|
||||
|
||||
Once written, re-send the doc with
|
||||
`"saved": "specs/<name>/DIAGNOSIS-<date>.md"` and its blocks replaced by one
|
||||
`file` block for that path (delete the old ids).
|
||||
Once written, re-send `cause` with `"saved":"specs/<name>/DIAGNOSIS-<date>.md"` and one `file` block for that path (delete the old block ids).
|
||||
|
||||
## The finish
|
||||
|
||||
`command` is `/plan2code-quick-task specs/<name>` (small fix) or
|
||||
`/plan2code-1-plan specs/<name>` (big fix) with the real folder filled in
|
||||
(`/plan2code-quick-task specs/csv-export-drops-rows`), never a placeholder: a
|
||||
copied command must reach the diagnosis. `body` names the cause, how sure, and that the
|
||||
next step reads the diagnosis first. `doc` is `"cause"`. `"dashboard": true`,
|
||||
then keep waiting for the press (`console-finish.md`): back on the dashboard
|
||||
the folder shows as "Bug diagnosed", with that card lit.
|
||||
`command` is `/plan2code-quick-task specs/<name>` (small fix) or `/plan2code-1-plan specs/<name>` (big fix), real folder filled in. `body`: the cause, how sure, and that the next step reads the diagnosis first. `"doc":"cause"`, `"dashboard":true`. Nothing kept (did not reproduce, no guess held): no `command`, say so in `body`.
|
||||
|
||||
Nothing kept (the bug did not reproduce and no guess held up): leave
|
||||
`command` out and say so in `body`.
|
||||
|
||||
A stop before the file is written ends on a finish whose `body` says nothing
|
||||
was kept (and names any throwaway script or kept test you wrote), with
|
||||
`"command": "/plan2code-diagnose"` (`console-stop.md`).
|
||||
A stop before the file is written: `body` says nothing was kept (and names any throwaway script or kept test), `"command":"/plan2code-diagnose"`.
|
||||
@@ -1,12 +1,3 @@
|
||||
# Documentation on the Web Console
|
||||
# Documentation
|
||||
|
||||
Workflow notes for `document`, part of the web console contract (`console.md`).
|
||||
|
||||
The questions are few — which draft, a clarification, the sign-off — but the
|
||||
docs are the point: post each phase file as a doc as it is written, so a
|
||||
browser-only person watches the spec take shape. Each one mirrors a file on
|
||||
disk, so carry its `saved` path, and post it as a `file` block
|
||||
(`{ "id": "body", "file": "specs/<feature>/phase-2.md" }`) rather than pasting
|
||||
the text you just wrote. Pass `--spec specs/<feature>` once the folder is known;
|
||||
it is what the resume command needs. Finish commands follow the pipeline: the
|
||||
sign-off's is `/plan2code-3-implement specs/<feature>/overview.md`.
|
||||
Post each phase file as a doc as it is written, as a `file` block (`{"id":"body","file":"specs/<feature>/phase-2.md"}`) carrying its `saved` path. Pass `--spec specs/<feature>` once the folder is known. The sign-off's finish `command` is `/plan2code-3-implement specs/<feature>/overview.md`.
|
||||
@@ -1,34 +1,14 @@
|
||||
# Finalize on the Web Console
|
||||
# Finalize
|
||||
|
||||
Workflow notes for `finalize`, part of the web console contract (`console.md`).
|
||||
|
||||
Finalize is a run of reports and gates, and each maps onto a kind you already
|
||||
know:
|
||||
|
||||
| Step | On the page |
|
||||
| Step | Card |
|
||||
| --- | --- |
|
||||
| 1, Task Completion Audit | The audit table as a doc (`id: "audit"`). If incomplete or blocked tasks exist (`totals.incomplete + totals.blocked > 0`), a `choice` with the three options — return to implementation, mark partially complete, abandon — with the counts against the thresholds in `body`. |
|
||||
| 2, Implementation Verification | The verification results as a doc. Nothing to ask unless an issue needs their decision. |
|
||||
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`, as a `file` block on `overview.md`) so the page reader sees it land. |
|
||||
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
|
||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||
| 6, Spec Cleanup | A `review` item before moving anything (`doc`: Step 3's summary), verdicts `yes` ("Archive it"), `show` ("Show me it working", token `show me`) and `no`, the archive paths in `body`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). On `show`, run it as `notes/implement.md` → Show me it working says (the summary line goes into `overview.md`'s Completion Summary), then reopen the card without `show`. |
|
||||
| 1, Audit | Table as doc `audit`. If `totals.incomplete + totals.blocked > 0`, a `choice` (return, mark partial, abandon) with counts against thresholds in `body`. |
|
||||
| 2, Verification | Results as a doc; ask only on an issue. Unless Full Suite is `Never` or `At Phase N`: `confirm` "Run the full suite" (`yesLabel` "Run it", `noLabel` "Skip it", reason in `body`); a failure is the building notes' `choice`. |
|
||||
| 3, Summary | Written to `overview.md`; mirror it as a doc (`saved`, `file` block). |
|
||||
| 4, Docs review | Proposed-updates table as a doc, plus a `multi` of documents (ticked = approved); a `review` if all-or-nothing. |
|
||||
| 5, Feedback | `required:false`: rating as `choice` 1 to 10 or `text`, three reasons as `text`, maintainer consent as `confirm`. |
|
||||
| 6, Cleanup | `review` (`doc` Step 3's summary), verdicts `yes` ("Archive it"), `show` (token `show me`), `no`; archive paths in `body`, and a line that remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). On `show`, see `notes/implement.md`, then reopen without `show`. |
|
||||
|
||||
Post `activity` as each step starts, before its doc or question lands — reading
|
||||
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
|
||||
implementation — the same way Review does. A step with no card of its own
|
||||
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
|
||||
Finalize".
|
||||
Post `activity` as each step starts. Pass `--spec specs/<feature>` or post `specDir`.
|
||||
|
||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||
Stopping mid-finalize loses nothing — the specs are untouched until Step 3's
|
||||
summary write — so a stop's finish just says where it paused and uses
|
||||
`"command": "/plan2code-4-finalize specs/<feature>/overview.md"`. On success
|
||||
the finish's `command` is the suggested commit when Step 4 doc updates landed
|
||||
(with `"where": "When you are happy with it, commit it from your terminal:"`), otherwise leave `command` out.
|
||||
When the finish prints that suggested commit, it also carries `"commit": true`,
|
||||
so the finished screen offers **Commit it now** (`console-finish.md`), and
|
||||
`"changelog": true` beside it, for **Update CHANGELOG first** (it hops into
|
||||
Changelog and on to Git). Both only when the finish prints a commit. The
|
||||
completion summary is printed to a terminal the browser user is not watching,
|
||||
so put it in `finish.body`.
|
||||
Finish: the completion summary goes in `body`. `command` is the suggested commit when Step 4 updates landed (`"where":"When you are happy with it, commit it from your terminal:"`, `"commit":true`, `"changelog":true`), else none. A stop loses nothing before Step 3's write: `command` `/plan2code-4-finalize specs/<feature>/overview.md`.
|
||||
@@ -1,124 +1,58 @@
|
||||
# Git on the Web Console
|
||||
# Git
|
||||
|
||||
Workflow notes for `git`, part of the web console contract (`console.md`).
|
||||
Launched from the dashboard or a hand-off: resume the session. The main column is the git board, from `state.git`. **Never post `git`** (exit 3). Your cards sit in the board's card slot.
|
||||
|
||||
Open with `--workflow git` (launched from the dashboard, or by a **Commit it
|
||||
now** or Changelog hand-off: resume the session instead). Like the dashboard,
|
||||
the main column is drawn by the page itself: the git board, from `state.git`,
|
||||
which `open` and every `reread` snapshot through `git-repo.mjs`. **You never
|
||||
post `git`** (exit 3: `state.git` is the console's own). Your cards sit in
|
||||
the board's card slot, under its tab strip.
|
||||
|
||||
**A click** arrives as one session action, one per send, and the board locks
|
||||
until your next post lands:
|
||||
A click arrives as one session action per send, and the board locks until your next post lands:
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [{ "i": "__git", "type": "git", "op": "create",
|
||||
"name": "feature/export-csv", "from": "origin/main",
|
||||
"then": "commit", "files": ["src/a.js"], "ignore": ["dist/"] }],
|
||||
"reply": "Create feature/export-csv from origin/main. ..." }
|
||||
{"reply":"Create feature/export-csv from origin/main.","session":[{"i":"__git","op":"create","name":"feature/export-csv","from":"origin/main","then":"commit","files":["src/a.js"],"ignore":["dist/"]}]}
|
||||
```
|
||||
|
||||
| `op` | Fields |
|
||||
| --- | --- |
|
||||
| `refresh`, `pull`, `push`, `abort`, `continue`, `done` | none (a `refresh` with no remote is "look again": `plan refresh` gives no commands, so just post `reread`) |
|
||||
| `publish` | `remote?` (left out when there are several: `plan publish` asks which) |
|
||||
| `switch`, `delete` | `branch` (a remote-only row is `<remote>/<name>`) |
|
||||
| `create` | `name`, `from`; `then: "commit"` with `files` (and `ignore`, when any) when it came from the commit panel's branch offer |
|
||||
| `refresh`, `pull`, `push`, `abort`, `continue`, `done` | none (`refresh` with no remote: `plan refresh` gives no commands, just post `reread`) |
|
||||
| `publish` | `remote?` (absent with several: `plan publish` asks) |
|
||||
| `switch`, `delete` | `branch` (remote-only row is `<remote>/<name>`) |
|
||||
| `create` | `name`, `from`; `then:"commit"` with `files` (and `ignore`) from the commit panel's branch offer |
|
||||
| `cleanup` | `branches[]` |
|
||||
| `commit` | `files[]` (paths and untracked folders), `ignore[]` (folders to add to `.gitignore`). `files[]` may be empty when `ignore[]` is not: the board's held-back offer (**Add … to .gitignore**). Then add the paths to `.gitignore` and commit only `.gitignore`. |
|
||||
| `pr-host` | `host`, `kind` (already saved by the page's `POST /pr-host`) |
|
||||
| `commit` | `files[]`, `ignore[]` (folders for `.gitignore`). `files[]` may be empty when `ignore[]` is not (held-back offer): add the paths to `.gitignore` and commit only `.gitignore`. |
|
||||
| `pr-host` | `host`, `kind` (already saved by `POST /pr-host`) |
|
||||
|
||||
`reply` is the plain instruction the terminal would get, so it reads like any
|
||||
answer. `__git` names no question, like `__stop`.
|
||||
|
||||
**After an action**, in ONE post (with `--wait`):
|
||||
**After an action**, ONE post with `--wait`:
|
||||
|
||||
```jsonc
|
||||
{ "reread": true,
|
||||
"items": [{ "id": "git-result", "kind": "notice", "status": "open",
|
||||
"title": "Pushed 2 commits to origin/feature/x",
|
||||
"body": "a1b2c3d, e4f5a6b. [Open pull request](https://github.com/...)" }],
|
||||
"board": { "describe": "export-csv-button" } }
|
||||
{"reread":true,"items":[{"id":"git-result","kind":"notice","title":"Pushed 2 commits to origin/feature/x","body":"a1b2c3d, e4f5a6b. [Open pull request](https://github.com/...)"}],"board":{"describe":"export-csv-button"}}
|
||||
```
|
||||
|
||||
- `reread` is `true`, or `{ "refreshFailed": true }` after a Refresh that
|
||||
failed (the board then says so beside the last refreshed time and keeps the
|
||||
last data). It goes only with the `git` workflow; anywhere else, or in any
|
||||
other shape, it is exit `3`. The console takes the snapshot inside the same
|
||||
locked write as your cards, so the result line and the fresh board land
|
||||
together.
|
||||
- `git-result` is a `notice` replaced every action (same id). The board shows
|
||||
it under its header, not in the card slot: what happened, with short hashes
|
||||
and, after a push or publish, the `pr-url` link. On a failure it quotes
|
||||
git's stderr verbatim with `classify-error`'s `next`.
|
||||
- `board.describe` is yours: a short kebab-case description of the changes
|
||||
still on the tree, which the Create prompt pre-fills. Post it with the
|
||||
reread whenever changes remain; leave it out otherwise.
|
||||
- The board is the person's to click whenever you wait, so `wait` hands the
|
||||
turn back by itself; no `agent` status is needed.
|
||||
- `reread` is `true`, or `{"refreshFailed":true}` after a failed Refresh. Only with the `git` workflow, else exit 3.
|
||||
- `git-result` is one `notice` replaced every action: what happened, short hashes, the `pr-url` link after a push or publish. A failure quotes git's stderr verbatim with `classify-error`'s `next`.
|
||||
- `board.describe`: short kebab-case description of the changes still on the tree (prefills Create); leave out when none remain.
|
||||
|
||||
**Cards per `plan`.** `git.mjs plan <op>` decides whether to ask:
|
||||
**Cards per `plan`** (`git.mjs plan <op>`):
|
||||
|
||||
| `plan` says | On the page |
|
||||
| --- | --- |
|
||||
| `confirm` | A `confirm` card with its `title`, `body`, `danger` and `consequences` verbatim (the consequences end with the exact command). Where the plan names files, add them as `files: [{ "path", "state" }]`. |
|
||||
| `card.kind: "switch"` | A `choice`, "Bring your changes?": exactly the `options` given, labeled **Switch and bring them** (`bring`), **Commit first** (`commit-first`), **Cancel** (`cancel`); the files in `body`, and `reason` when git would refuse (then there is no `bring`). `allowOther: false`. |
|
||||
| `card.kind: "dirty"` | The same `choice` for a pull that needs a clean tree: **Commit first** / **Cancel**, `reason` in `body`. |
|
||||
| `card.kind: "remote"` | A `choice`, "Publish to which remote?": one option per remote, `preset` recommended. Then `plan publish --remote <it>` and its `confirm`. |
|
||||
| `ask: false` | No card: run it on the click. |
|
||||
| exit 4 or 5 | No card and nothing run: the `message` and `next` as the `git-result` notice. |
|
||||
| `confirm` | `confirm` with `title`, `body`, `danger`, `consequences` verbatim; named files as `files:[{"path","state"}]`. |
|
||||
| `card.kind:"switch"` | `choice` "Bring your changes?", exactly the given `options`: **Switch and bring them** (`bring`), **Commit first** (`commit-first`), **Cancel** (`cancel`); files in `body`, `reason` when git refuses (no `bring` then). `allowOther:false`. |
|
||||
| `card.kind:"dirty"` | Same `choice`, **Commit first** / **Cancel**, `reason` in `body`. |
|
||||
| `card.kind:"remote"` | `choice` "Publish to which remote?", one option per remote, `preset` recommended; then `plan publish --remote <it>` and its `confirm`. |
|
||||
| `ask:false` | No card: run on the click. |
|
||||
| exit 4 or 5 | Nothing run: `message` and `next` as the `git-result` notice. |
|
||||
|
||||
An `auth` failure gets a `notice` card saying the tool never handles logins,
|
||||
with `next`. The commit flow's own cards (message, groups, `git init`,
|
||||
`.gitignore`) are the rows below.
|
||||
An `auth` failure: a `notice` saying the tool never handles logins, with `next`.
|
||||
|
||||
| Commit step | On the page |
|
||||
| --- | --- |
|
||||
| One commit | A `text` card whose `placeholder` is the drafted subject and whose `pattern` caps it at 100 characters, then a `confirm` "Commit this?" with the files in `consequences` and, as `files: [{ "path": "src/a.js", "state": "modified" }]` (states: modified, new, deleted, renamed), a collapsed **Show the N files** table on the card. With the subject given as the argument there is no card. |
|
||||
| A split | The groups as a doc (`id: "commits"`: each group's subject and files, and any file that mixes concerns) plus a `review` card with verdicts `approve`, `change` and `single` ("One commit instead"). Asked even when the subject came as the argument. |
|
||||
| Push | Not asked after a commit on the board: the board lights Push. `commit and push` (or a Push click) asks `plan push` / `plan publish`'s `confirm`. |
|
||||
| `git init` | A `confirm` naming the folder and its first branch (`init-check`'s `branch`, `danger: false`), its `consequences` `init-check`'s `commands`. Run those, not a bare `git init`. |
|
||||
| `.gitignore` | The proposed file, or the lines a `commit`'s `ignore[]` adds, as a doc plus a `review` card. |
|
||||
| One commit | `text` card, `placeholder` the drafted subject, `pattern` capping it at 100 characters, then `confirm` "Commit this?" with files in `consequences` and `files:[{"path","state"}]` (modified, new, deleted, renamed). No card when the subject was the argument. |
|
||||
| A split | Doc `commits` (each group's subject and files, files mixing concerns) plus `review` with verdicts `approve`, `change`, `single` ("One commit instead"). Asked even with a subject argument. |
|
||||
| Push | Not asked after a board commit (the board lights Push). `commit and push` or a Push click asks `plan push` / `plan publish`'s `confirm`. |
|
||||
| `git init` | `confirm` naming folder and first branch (`init-check`'s `branch`, `danger:false`), `consequences` its `commands`. Run those, not a bare `git init`. |
|
||||
| `.gitignore` | The proposed file, or a `commit`'s `ignore[]` lines, as a doc plus `review`. |
|
||||
|
||||
Risky files (`sensitive`, `large`) are named in the card's `body`. On the
|
||||
board there is no branch-offer card: the commit panel's **You're on main**
|
||||
line asks it, and the answer arrives as `create` with `then: "commit"`.
|
||||
Risky files (`sensitive`, `large`) go in the card's `body`. There is no branch-offer card: the commit panel's **You're on main** asks, answered as `create` with `then:"commit"`.
|
||||
|
||||
**Conflict help.** A pull, rebase or merge stopped on conflicts asks first, a
|
||||
`choice` "Resolve them for me?": **Yes**, **I'll fix it**, **Abort pull**.
|
||||
On yes, every stop is a doc (`id: "conflict"`, replaced per stop, its version moving by itself: step N of M,
|
||||
the commit being replayed, each file with a one-line reason, then a per-file
|
||||
diff) plus a `review` card, fresh id per stop, `"nothingYet": false` (the resolution is already on disk), with the verdicts `continue`
|
||||
("Continue"), `change` ("Change it") and `abort` ("Abort pull", `danger`).
|
||||
Only **Continue** runs `plan continue`'s commands; **Abort pull** runs
|
||||
`plan abort` and the board is back on the exact original HEAD. A file you
|
||||
cannot resolve with confidence is named and left with its markers; **I'll fix
|
||||
it** leaves the markers too. The board's banner always offers Continue: a
|
||||
`continue` click is the person saying the files are fixed, so run `plan
|
||||
continue`; when it refuses (exit 5, markers left), post a `reread` with its
|
||||
`message` as the `git-result` notice, which also refreshes the banner's file
|
||||
list. Nothing is pushed during conflict help. At the end, a `notice`
|
||||
summary (commits replayed, each resolved file with its reason, "N commits
|
||||
ready to push").
|
||||
**Conflict help.** A pull, rebase or merge stopped on conflicts: `choice` "Resolve them for me?": **Yes**, **I'll fix it**, **Abort pull**. On yes, each stop is doc `conflict` (replaced per stop: step N of M, the commit replayed, each file with a one-line reason, per-file diff) plus a `review` with a fresh id per stop, `"nothingYet":false`, verdicts `continue`, `change`, `abort` ("Abort pull", `danger`). Only **Continue** runs `plan continue`'s commands; **Abort pull** runs `plan abort`. A file you cannot resolve confidently keeps its markers, as does **I'll fix it**. A `continue` click from the board's banner means the files are fixed: run `plan continue`; on exit 5 (markers left) post a `reread` with its `message` as the `git-result`. End with a `notice` summary (commits replayed, each resolved file with its reason, "N commits ready to push").
|
||||
|
||||
**Meter events** (`console-meter.md`). Git scores on launch.
|
||||
Post `run: { "event": "git-commits", "id": "<first short hash>", "commits": N }`
|
||||
after each commit step (N commits made), and `run: { "event": "git-conflict",
|
||||
"id": "conflict-<n>" }` once per conflict help, resolved or aborted.
|
||||
**Meter.** Post `run:{"event":"git-commits","id":"<first short hash>","commits":N}` after each commit step, and `run:{"event":"git-conflict","id":"conflict-<n>"}` once per conflict help.
|
||||
|
||||
**Finishing** (`console-finish.md`). **Done with git** (`op: "done"`). A `done`
|
||||
that arrives while one of your cards is still open is the person canceling it:
|
||||
record that card as canceled (`{ "items": [{ "id": "<id>", "status":
|
||||
"answered", "answer": { "text": "Canceled by Done with git" } }] }`, not
|
||||
`settle`, which refuses a card nothing was sent to) in the same post as the
|
||||
finish, or, with nothing done, before resuming as the dashboard. Never run what
|
||||
the card was asking for. With something done this session: a `finish` with a
|
||||
headline, the commits with hashes, pushes and branches created or deleted in
|
||||
`body`, no `command`, and `"dashboard": true`; keep waiting for the press. Done
|
||||
with nothing done: no finish screen — resume as `dashboard` at once (`open
|
||||
--resume <sid> --no-open --workflow dashboard`), read the dashboard skill
|
||||
(`~/.agents/skills/plan2code/SKILL.md`), post its `menu` with `--wait` and
|
||||
carry on from its "Coming back from another skill". A stop's finish is a pause,
|
||||
headline "Paused …", the bare `/plan2code-git`, then `stop`.
|
||||
**Finishing.** **Done with git** is `op:"done"`. A `done` while one of your cards is open cancels it: record it `{"items":[{"id":"<id>","status":"answered","answer":{"text":"Canceled by Done with git"}}]}` (not `settle`) in the finish post, or, with nothing done, before resuming as the dashboard. Never run what that card asked. Something done: `finish` with a headline and the commits (hashes), pushes and branches created or deleted in `body`, no `command`, `"dashboard":true`. Nothing done: no finish screen; resume as `dashboard` (`open --resume <sid> --no-open --workflow dashboard`), read `~/.agents/skills/plan2code/SKILL.md`, post its `menu` with `--wait`, carry on from "Coming back from another skill". A stop's finish is a pause, "Paused ...", bare `/plan2code-git`.
|
||||
@@ -1,11 +1,3 @@
|
||||
# Handoff on the Web Console
|
||||
# Handoff
|
||||
|
||||
Workflow notes for `handoff`, part of the web console contract (`console.md`).
|
||||
|
||||
One gate: the next-task confirmation, then the document itself as a doc —
|
||||
that is what the person is there to download. Give it no `saved` and paste it
|
||||
as `md`: the handoff file lives in `~/.plan2code/handoffs/`, outside the project,
|
||||
where a `file` block is refused, and the download is the point. The finish carries no
|
||||
`command`: the doc download is the point, and the dashboard button and the
|
||||
"All done" line cover what comes next. Unless it is a pause, the finish carries
|
||||
`"dashboard": true` and you keep waiting for the press (`console-finish.md`).
|
||||
One gate (next-task confirmation), then the document as a doc with `md`, no `saved` (the file lives outside the project, where a `file` block is refused). The finish has no `command`; unless it is a pause it carries `"dashboard":true`.
|
||||
@@ -1,193 +1,63 @@
|
||||
# Implement on the Web Console
|
||||
# Implement
|
||||
|
||||
Workflow notes for `implement` and `implement-review`, part of the web console
|
||||
contract (`console.md`). Read `building.md` first.
|
||||
`implement` and `implement-review`. Read `building.md` first.
|
||||
|
||||
## The first post of a phase
|
||||
## First post of a phase
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "stage": "Phase 3: API layer", "cleared": 0, "total": 9 },
|
||||
"docs": [
|
||||
{ "id": "phase", "title": "Phase 3 tasks", "blocks": [
|
||||
{ "id": "tasks", "file": "specs/<feature>/phase-3.md", "select": "tasks" }
|
||||
]},
|
||||
{ "id": "phasefile", "title": "phase-3.md", "blocks": [
|
||||
{ "id": "body", "file": "specs/<feature>/phase-3.md" }
|
||||
]}
|
||||
],
|
||||
"agent": { "status": "working", "activity": "Checking the prerequisites", "quietMinutes": 15 }
|
||||
}
|
||||
{"headline":{"stage":"Phase 3: API layer","cleared":0,"total":9},"docs":[{"id":"phase","title":"Phase 3 tasks","blocks":[{"id":"tasks","file":"specs/<feature>/phase-3.md","select":"tasks"}]},{"id":"phasefile","title":"phase-3.md","blocks":[{"id":"body","file":"specs/<feature>/phase-3.md"}]}],"agent":{"status":"working","activity":"Checking the prerequisites","quietMinutes":15}}
|
||||
```
|
||||
|
||||
`phase` is the task list, `phasefile` the whole `phase-X.md` as its own tab —
|
||||
the person can read the prerequisites and task specs while you build. Both are
|
||||
read from disk by the console: never paste the file. It renders as markdown, so
|
||||
the file's checkboxes show as ticks exactly as they stand on disk.
|
||||
|
||||
A later phase in the same session posts the same two docs with the new phase's
|
||||
title and file: their content changed, so their versions move up by themselves
|
||||
(a doc's version never goes back, and you no longer have to track it). Leave
|
||||
`version` out.
|
||||
`phase` is the task list, `phasefile` the whole file. A later phase posts the same two docs with the new title and file.
|
||||
|
||||
## After every task
|
||||
|
||||
In the same breath as writing the task's checkbox to disk:
|
||||
With the checkbox write:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "cleared": 4 },
|
||||
"docs": [ { "id": "phase", "refresh": true }, { "id": "phasefile", "refresh": true } ],
|
||||
"agent": { "activity": "Task 5 of 9: the rate limiter" }
|
||||
}
|
||||
{"headline":{"cleared":4},"docs":[{"id":"phase","refresh":true},{"id":"phasefile","refresh":true}],"agent":{"activity":"Task 5 of 9: the rate limiter"}}
|
||||
```
|
||||
|
||||
`refresh` re-reads the file the checkbox write just changed, so both tabs tick
|
||||
in place; the Phase Completion Summary lands in `phasefile` the same way at the
|
||||
end. Then the `chat` check (`building.md` → Quick questions between tasks).
|
||||
|
||||
---
|
||||
The Phase Completion Summary lands in `phasefile` the same way. Then the `chat` check.
|
||||
|
||||
## Sign-off
|
||||
|
||||
Put the Completion Report on the page as a doc, then ask for approval as a
|
||||
`review` item pointing at it. The review offer rides on this card, as a verdict
|
||||
ahead of the approval buttons — not on the finish after it, where it could
|
||||
only ever be offered once nothing could come of it:
|
||||
Loop mode (`notes/loop.md`) posts `loopOutcome` instead. Otherwise the Completion Report is a doc and the approval a `review` pointing at it; the review offer is a verdict here, not on the finish:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"docs": [{ "id": "report", "title": "Completion report", "blocks": [
|
||||
{ "id": "summary", "state": "settled", "md": "## Summary\n\n..." },
|
||||
{ "id": "files", "state": "settled", "md": "## Files\n\n..." },
|
||||
{ "id": "verify", "state": "settled", "md": "## How to check it\n\n..." }
|
||||
]}],
|
||||
"items": [{
|
||||
"id": "signoff", "kind": "review", "title": "Approve this phase", "doc": "report",
|
||||
"body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, see it running, or say what to change.",
|
||||
"verdicts": [
|
||||
{ "id": "review", "label": "Review the code first" },
|
||||
{ "id": "approve", "label": "Approve this phase" },
|
||||
{ "id": "show", "label": "Show me it working" },
|
||||
{ "id": "changes", "label": "I want changes" }
|
||||
],
|
||||
"token": { "approve": "approved", "changes": "needs changes", "show": "show me" },
|
||||
"nothingYet": "Nothing is marked complete until you approve.",
|
||||
"gate": { "id": "signoff", "authoritative": true }
|
||||
}]
|
||||
}
|
||||
{"docs":[{"id":"report","title":"Completion report","blocks":[{"id":"summary","state":"settled","md":"## Summary\n\n..."},{"id":"files","state":"settled","md":"## Files\n\n..."},{"id":"verify","state":"settled","md":"## How to check it\n\n..."}]}],"items":[{"id":"signoff","kind":"review","title":"Approve this phase","doc":"report","body":"Phase 3 is built. Read the report, try the checks, then approve it, review the code first, see it running, or say what to change.","verdicts":[{"id":"review","label":"Review the code first"},{"id":"approve","label":"Approve this phase"},{"id":"show","label":"Show me it working"},{"id":"changes","label":"I want changes"}],"token":{"approve":"approved","changes":"needs changes","show":"show me"},"nothingYet":"Nothing is marked complete until you approve.","gate":{"id":"signoff","authoritative":true}}]}
|
||||
```
|
||||
|
||||
Posted with `--wait`. `reply` carries `Approve this phase: approved`, which is
|
||||
the terminal's `approved`. If the note that came with an approval asks for a
|
||||
change, treat it as "describe any issues": do the change first and ask again.
|
||||
`changes` means exactly what it says: address it, update the report, and reopen
|
||||
the item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||
person asking for the code review before they approve anything — read
|
||||
`building-review.md`. `show` is the terminal's `show me`: see below.
|
||||
Posted with `--wait`. An approval whose note asks for a change: do the change first and ask again. `changes`: address it, update the report, reopen the item with a `thread` reply. `review`: read `building-review.md`. `show`: below.
|
||||
|
||||
A later phase in the same session asks with a new id (`signoff-phase-2`, title "Approve Phase 2"); the old card is a record.
|
||||
|
||||
### Show me it working
|
||||
|
||||
On `show`, run the workflow's **Show me it working** paragraph (start the app,
|
||||
look at the change, stop it, one summary line in `phase-X.md`). Save each
|
||||
screenshot under the session's `shots/` folder, never under `specs/`, and post
|
||||
them as image blocks in a `shown` doc (`console.md` → Documents), with what was
|
||||
run in a `md` block above them; no browser tool means that block alone says
|
||||
what the command printed. Then reopen the same card (`"status": "reopened"`)
|
||||
without the `show` verdict, a `thread` reply naming what was seen. The same
|
||||
holds on Finalize's card and the one `building-review.md` reopens; Quick
|
||||
Task's card is settled instead (`notes/quick-task.md`).
|
||||
|
||||
`gate` marks the one approval that counts. The server refuses a second open
|
||||
authoritative gate, which is what keeps a composed workflow from asking for
|
||||
sign-off twice. A later phase in the same session asks with a new id
|
||||
(`signoff-phase-2`, its title naming the phase, "Approve Phase 2", so the rail tells
|
||||
the two apart), since the last phase's approved card is a record: the same
|
||||
id posted again would only edit that record.
|
||||
|
||||
---
|
||||
On `show`, run the workflow's **Show me it working** paragraph. Save screenshots under the session's `shots/`, never `specs/`, and post them as image blocks in a `shown` doc with what was run in a `md` block above (no browser tool: that block alone says what the command printed). Then reopen the same card without the `show` verdict, with a `thread` reply naming what was seen. Same on Finalize's card and the one `building-review.md` reopens; Quick Task's card is settled instead.
|
||||
|
||||
## After approval: the finish
|
||||
|
||||
Do everything the workflow does on approval (the checkboxes, the summary, the
|
||||
upcoming phases, the commit command) and print it in the terminal as usual.
|
||||
Then post the finish, wait for the dashboard button as `console-finish.md`
|
||||
says, and `stop`:
|
||||
Do what the workflow does on approval and print it in the terminal as usual, then:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"settle": true,
|
||||
"run": { "event": "implement-phase", "id": "phase-3", "tasks": 9 },
|
||||
"finish": {
|
||||
"headline": "Phase 3 is done",
|
||||
"body": "9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -A && git commit -m \"...\" -m \"AI Assisted\"\n```",
|
||||
"command": "/plan2code-3-implement specs/lunch-vote/overview.md",
|
||||
"doc": "report",
|
||||
"commit": true,
|
||||
"dashboard": true
|
||||
}
|
||||
}
|
||||
{"settle":true,"run":{"event":"implement-phase","id":"phase-3","tasks":9},"finish":{"headline":"Phase 3 is done","body":"9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -A && git commit -m \"...\" -m \"AI Assisted\"\n```","command":"/plan2code-3-implement specs/lunch-vote/overview.md","doc":"report","commit":true,"dashboard":true}}
|
||||
```
|
||||
|
||||
`"commit": true` is there because the body prints a git command: the finished
|
||||
screen gets a **Commit it now** button, and its `__commit` press is handled as
|
||||
`console-finish.md` says (resume as `git` and open its commit flow, same
|
||||
session). Leave it out when the body prints no commit.
|
||||
`commit:true` only when the body prints a commit. `command` is the next step: `/plan2code-3-implement specs/<feature>/overview.md`, or `/plan2code-4-finalize specs/<feature>/overview.md` after the last phase. No `review` on the finish.
|
||||
|
||||
`finish.command` is the next pipeline step, the same one the terminal names:
|
||||
the next `/plan2code-3-implement specs/<feature>/overview.md`, or
|
||||
`/plan2code-4-finalize specs/<feature>/overview.md` after the last phase. An `implement` finish never carries `review`: the offer was on the
|
||||
sign-off card, and approving past it was the answer. `implement-review` ends
|
||||
the same way; that phase was reviewed already.
|
||||
|
||||
`run` gives the approved phase its final score on the session meter
|
||||
(`console-meter.md`), in the same post that records the approval; it takes over
|
||||
what the build already counted from `cleared`, never adds to it:
|
||||
`implement-phase` for Implement, `implement-review-phase` for Implement +
|
||||
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
|
||||
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
|
||||
twelve-task phase weighs four times a three-task one; leave `tasks` out and
|
||||
every phase weighs the same. A review run on the page after a build reports its
|
||||
own (`building-review.md`).
|
||||
|
||||
---
|
||||
`run` takes over what `cleared` counted, never adds: `implement-phase` (Implement) or `implement-review-phase` (Implement + Review), id `phase-N`, `tasks` the completed ones (`[x]`, not `[!]`); without `tasks` every phase weighs the same.
|
||||
|
||||
## Manual check-off (`next.action` is `checkoff`)
|
||||
|
||||
No phase to build: the open tasks under approved phases are asked about one
|
||||
at a time, one `confirm` item each, posted with `--wait`:
|
||||
Open tasks under approved phases, one `confirm` each, `--wait`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "stage": "Manual check-off", "cleared": 0, "total": 2 },
|
||||
"items": [{
|
||||
"id": "checkoff-3.4", "kind": "confirm", "title": "Task 3.4",
|
||||
"body": "**Configure the SSO app in Okta**\n\nBLOCKED: needs admin access. User action: create the app and paste its client id into `.env`.\n\nIs this done?",
|
||||
"yesLabel": "Done, check it off", "noLabel": "Not yet"
|
||||
}]
|
||||
}
|
||||
{"headline":{"stage":"Manual check-off","cleared":0,"total":2},"items":[{"id":"checkoff-3.4","kind":"confirm","title":"Task 3.4","body":"**Configure the SSO app in Okta**\n\nBLOCKED: needs admin access.\n\nIs this done?","yesLabel":"Done, check it off","noLabel":"Not yet"}]}
|
||||
```
|
||||
|
||||
`yes` → `specs.mjs tick`, then `"headline": { "cleared": N }` with the next
|
||||
item. When the last one is answered, post the finish: `command` is
|
||||
`/plan2code-4-finalize specs/<feature>/overview.md` when `tick` said
|
||||
`remaining` is empty, otherwise the same `/plan2code-3-implement` command,
|
||||
and `body` lists what is still open. No `run` (nothing was built), no
|
||||
`commit` unless a body prints one.
|
||||
|
||||
---
|
||||
Yes: `specs.mjs tick`, `{"headline":{"cleared":N}}` with the next item. After the last: finish with `command` `/plan2code-4-finalize specs/<feature>/overview.md` when `tick` said `remaining` is empty, else `/plan2code-3-implement ...`; `body` lists what is open. No `run`, no `commit` unless the body prints one.
|
||||
|
||||
## Implement + Review (`implement-review`)
|
||||
|
||||
The same build, then Stage 2 publishes the findings exactly as
|
||||
`building-review.md` → The findings (the `review` doc and the `fixes` item).
|
||||
Stage 3 fixes, with no "Check the fixes" item: Stage 4 is the only gate. The
|
||||
post that starts Stage 2's review carries `"run": { "event": "review", "id":
|
||||
"review" }`: in this workflow it scores the review stage's 1 point on the meter
|
||||
as it begins, and the phase's final `run` leaves that point out. Stage 4 is the
|
||||
sign-off above (`show` included) **without the review verdict** — the phase was already reviewed
|
||||
— with the review results and unresolved findings in the report doc, header
|
||||
"Reviewed and ready for sign-off" in the item's `body`. The finish never
|
||||
carries `review`, and its post carries `"run": { "event":
|
||||
"implement-review-phase", "id": "phase-N", "tasks": N }` with the count of
|
||||
completed tasks.
|
||||
Stage 2 publishes findings as in `building-review.md` (The findings). Stage 3 has no "Check the fixes" item. The post starting Stage 2 carries `"run":{"event":"review","id":"review"}` (scores 1 point; the final `run` leaves it out). Stage 4 is the sign-off above, `show` included, without the `review` verdict, with review results and unresolved findings in the report and "Reviewed and ready for sign-off" in `body`. Its finish `run` is `implement-review-phase`.
|
||||
@@ -1,14 +1,3 @@
|
||||
# Init and Init Update on the Web Console
|
||||
# Init and Init Update
|
||||
|
||||
Workflow notes for `init` and `init-update`, part of the web console contract
|
||||
(`console.md`).
|
||||
|
||||
Setup conversations: every confirmation and Q&A item goes through the page.
|
||||
For `init` and `init-update` the finished AGENTS.md also lands as a doc so a
|
||||
browser-only person can read what was written — marked `"saved": "AGENTS.md"`,
|
||||
since the file itself is already on disk (or as a `file` block:
|
||||
`{ "id": "body", "file": "AGENTS.md" }`, instead of pasting it). A completed run
|
||||
finishes with **no** `command`: the page shows the "All done" line. Nothing is
|
||||
on disk to resume mid-run, so a stop's finish command is the bare
|
||||
`/plan2code-init` or `/plan2code-init-update` — the skill starts over
|
||||
either way.
|
||||
Post the finished AGENTS.md as a doc (`"saved":"AGENTS.md"` or a `file` block). A completed run finishes with no `command`; a stop's is the bare `/plan2code-init` or `/plan2code-init-update`.
|
||||
@@ -0,0 +1,168 @@
|
||||
# Loop Mode on the Web Console
|
||||
|
||||
Workflow notes for Implement and Implement + Review started by the desktop app's
|
||||
Implementation Loop with `--loop`, part of the web console contract
|
||||
(`console.md`). Read `building.md` and `notes/implement.md` first: this note says
|
||||
only where loop mode differs. The app judges the result, so you report and never
|
||||
approve.
|
||||
|
||||
## Flags
|
||||
|
||||
- `--loop`: this run is one phase of an unattended loop. The skill's first step
|
||||
already ran a plain `open`; run it again now, before any post, as
|
||||
`node "<CONSOLE>" open --workflow <implement|implement-review> --spec specs/<feature> --loop`.
|
||||
Inside the app it resumes the app's session and locks the page; without it,
|
||||
`loopOutcome` and `handledBy` are refused. If it exits 3, the run is not inside
|
||||
the app: say "Loop mode runs only inside the Plan2Code desktop app." in the
|
||||
terminal and continue as an ordinary run with the person's sign-off. Skip
|
||||
nothing below unless that `open` succeeded.
|
||||
- `--fix <levels>`: a comma list from `critical`, `warning`, `suggestion`, the
|
||||
levels to fix in the one fix round. Absent means findings are reported, not
|
||||
fixed.
|
||||
- `--fix smart`: Smart pick. A triage step chooses which findings to fix, in
|
||||
place of a level list (see Triage). The one fix round and the fresh re-check
|
||||
are unchanged.
|
||||
- `--guess`: when a task needs a decision the spec does not make, take the best
|
||||
guess, mark the task `[?]` with a one-line note as an indented line right under
|
||||
it in the phase file (` - Assumed: what you chose and why`), and carry on. The
|
||||
app copies that note into the person's report. Without `--guess`, ask the question as an ordinary open card
|
||||
(see Questions and cards).
|
||||
|
||||
## What changes in loop mode
|
||||
|
||||
- Pick the phase without asking (Choosing the phase).
|
||||
- No sign-off card, no "Approve this phase", no Show me it working, no Continue
|
||||
offer.
|
||||
- Never run `specs.mjs mark --to done`, and never set `[x]` on the phase in
|
||||
`overview.md`. Tasks inside the phase file are still checked off as they
|
||||
finish: `[x]`, `[!]` when blocked, `[?]` when assumed.
|
||||
- Never run `git` in any form (no add, commit, stash, checkout), and never
|
||||
`commit-msg.mjs`.
|
||||
- No Stop-with-handoff, no `__dashboard`, no finish screen: the app ends the
|
||||
session.
|
||||
- Where the prompt would stop and ask, report instead of posting a card:
|
||||
- A spec conflict: list it in `conflicts`, report `failed`, reason `conflict`.
|
||||
- A blocked prerequisite or task: mark the task `[!]`, list it in
|
||||
`tasks.blocked`, report `failed`, reason `blocked`.
|
||||
- Failing tests: try one fix, then report `tests.passed: false`, `failed`,
|
||||
reason `tests`. Never post the Fix now, Document or Investigate options.
|
||||
- A waiting `**Plan change:**` line in the phase's Notes: do not ask Revise
|
||||
first or Resume; report `failed`, reason `other`, and say so in `summary`.
|
||||
- Run only the tests the phase file names, as the Implement prompt's tests rule
|
||||
says: a phase task or a task's `Test:` line (a `## Phase Testing` block counts
|
||||
when it lists them as tasks). Never the full suite unless the phase file names it.
|
||||
|
||||
## Headline stages
|
||||
|
||||
Post `headline.stage` as each begins, using only these words: `Build`, `Review`,
|
||||
`Fixes`, `Re-check`, `Reporting`. The app's strip reads them, and any other word
|
||||
shows as Build, so do not invent new ones in loop mode. Keep `cleared` and
|
||||
`total` as in any build.
|
||||
|
||||
## Choosing the phase
|
||||
|
||||
Run `node "<S>/specs.mjs" status specs/<feature>`. A phase whose checklist marker
|
||||
is `[/]` goes first; otherwise take `next.phase.number` (the first of
|
||||
`next.options` when `next.action` is `choose`). Never post the "Resume?" question
|
||||
or the parallel-phase pick. Set the phase in progress with
|
||||
`specs.mjs mark <spec> --phase N --to in-progress`, exactly as an ordinary run
|
||||
does: that mark is allowed, and only `--to done` is the app's. When `next.action`
|
||||
is `none` or `checkoff` (no open phase), post a `loopOutcome` with
|
||||
`result: "failed"`, `reason: "other"` and
|
||||
`summary: "No open phase left in this spec"`.
|
||||
|
||||
## Questions and cards the loop handles
|
||||
|
||||
- A real question (a decision the spec does not make, without `--guess`) is an
|
||||
ordinary open card, waited on with `post --wait` as usual. The app sees it open
|
||||
and holds or stops the loop. Do not mark it `handledBy`.
|
||||
- The review stage's findings pick and the fix confirmation are answered by this
|
||||
run itself from `--fix` (with `--fix smart`, from the triage). Post them for the record as settled items with
|
||||
`"handledBy": "loop"` and the answer filled in, so the page shows "The loop
|
||||
handles this", for example
|
||||
`{ "id": "fixes", "kind": "multi", "title": "Which to fix", "options": [ ... ], "status": "answered", "answer": { "ks": ["1", "2"] }, "handledBy": "loop" }`.
|
||||
- Ask (chat) questions do not arrive while the loop drives. If one does, answer
|
||||
it briefly as usual.
|
||||
|
||||
## Review, one fix round and the re-check
|
||||
|
||||
Implement + Review only. Run the review as `building-review.md` describes. Fix
|
||||
only the findings at the `--fix` levels, in one round. Then start one fresh
|
||||
reviewer helper (a new subagent with no memory of the fix round, or a fresh read
|
||||
when helpers are off) that re-checks only the fixes: each finding at a chosen
|
||||
level is fixed, and nothing new was introduced. Count what is left, by level,
|
||||
after the re-check. Suggestions left or newly found on the re-check are listed
|
||||
but never fail the phase. Do not run a second fix round.
|
||||
|
||||
## Triage (`--fix smart`)
|
||||
|
||||
Implement + Review only, after the review lists its findings and before the fix
|
||||
round. Start one fresh triage helper (a new subagent with no memory of the build
|
||||
or the review, or a fresh read when helpers are off). Its brief holds the
|
||||
findings, the phase's tasks in `phase-X.md` and the project's `AGENTS.md`. For
|
||||
each finding it answers `fix` or `skip` with one line of reason, at most 200
|
||||
characters. Skip is for a finding that is not real once the code is read, is
|
||||
outside this phase's tasks, contradicts `AGENTS.md` or the spec, or asks for a
|
||||
change out of proportion to the gain. Every skip carries a reason.
|
||||
|
||||
The app stops the phase on any skipped Critical, so the triage must not skip a
|
||||
Critical it merely dislikes: skip one only when it is plainly not a defect, and
|
||||
say why. Post the triage's answers for the record as the settled `fixes` item (its `ks` are the findings marked `fix`, posted before the fix round)
|
||||
(`handledBy: "loop"`), with one `thread` entry per skip carrying its reason.
|
||||
|
||||
Then run the one fix round on the findings marked `fix`, and the fresh re-check
|
||||
of only those fixes, as above. `left` counts the picked findings still open after
|
||||
the re-check. Smart pick always reports `triage.ran: true` and `review.recheck: true`, even when no finding was raised or none was picked (an empty re-check). The triage runs under the `Review` stage; the stage words do not
|
||||
change.
|
||||
|
||||
## Reporting the outcome
|
||||
|
||||
At the end of the run, post once a top-level `loopOutcome`:
|
||||
|
||||
```json
|
||||
{ "loopOutcome": {
|
||||
"phase": 2, "result": "passed", "reason": null,
|
||||
"summary": "Built the setup screen; 6 of 6 tasks",
|
||||
"tests": { "ran": true, "passed": true, "summary": "14 pass" },
|
||||
"decisions": ["Kept the old /votes route so existing callers still work"],
|
||||
"review": { "ran": true, "recheck": true,
|
||||
"fixed": [ { "level": "warning", "title": "Close the file handle", "file": "src/z.js" } ],
|
||||
"triage": { "ran": true, "skipped": [ { "level": "warning", "title": "Rename the helper", "file": "src/y.js", "reason": "Outside this phase's tasks" } ] },
|
||||
"left": { "critical": 0, "warning": 0, "suggestion": 2 },
|
||||
"unfixed": [ { "level": "suggestion", "title": "Name the timer", "file": "src/x.js" } ] },
|
||||
"tasks": { "blocked": [], "assumed": ["2.4"] },
|
||||
"conflicts": [],
|
||||
"subject": "Add the loop setup screen" } }
|
||||
```
|
||||
|
||||
- `result` is `"passed"` only when every task is `[x]` (or `[?]` with `--guess`),
|
||||
the named tests pass, and, with review, no Critical or Warning is left at a
|
||||
chosen level (every level in Smart pick) after the re-check, and, in Smart pick,
|
||||
the triage skipped no Critical (otherwise `failed`, reason `findings`). Otherwise `"failed"`, with the first matching
|
||||
`reason`: `tests`, `findings`, `blocked`, `conflict` or `other`. A passed
|
||||
outcome has `"reason": null`.
|
||||
- `review.triage` is present only with `--fix smart`: `ran: true` and `skipped` listing
|
||||
every skipped finding with its reason (an empty list when nothing was skipped).
|
||||
A picked Critical or Warning still left after the re-check fails the phase with
|
||||
reason `findings`. `unfixed` lists only picked findings still open after the
|
||||
re-check; skipped findings go only in `triage.skipped` (the app adds them to the
|
||||
summary), and the 50-entry limits of the two lists are separate.
|
||||
- `review.fixed` lists every finding the fix round fixed (an empty list when none,
|
||||
or with no review), at most 50.
|
||||
- `decisions` lists, at most 50, one line of at most 200 characters each, every
|
||||
other judgment call this run made on the person's behalf that the spec did not
|
||||
settle and the `Assumed:` notes do not already cover: a library or approach
|
||||
chosen between real options, scope left out or added, a behavior changed outside
|
||||
the task. The person reads these to check the work, so say what you chose and
|
||||
why, and leave nothing out because it seems small. Do not list the routine steps
|
||||
of building. An empty list means you made none.
|
||||
- `review.ran` and `review.recheck` are `false` when the run did no review or no
|
||||
re-check (plain Implement, or no `--fix` level; never with `--fix smart`). `tasks.blocked` and
|
||||
`tasks.assumed` list task ids like `"2.4"`. `conflicts` holds one line per
|
||||
spec conflict.
|
||||
- `subject` is one imperative line under 100 characters saying what changed (it
|
||||
becomes the commit subject). `summary` is one line under 200 characters.
|
||||
|
||||
Then post `{"agent":{"status":"waiting"}}` and keep waiting with the usual
|
||||
bounded `wait` slices until the app ends the session. Never end the turn on text.
|
||||
If the post is refused (exit 3), fix the field it names and post again.
|
||||
@@ -1,77 +1,26 @@
|
||||
# Pathfinder on the Web Console
|
||||
# Pathfinder
|
||||
|
||||
Workflow notes for `pathfinder`, part of the web console contract (`console.md`).
|
||||
|
||||
- Every probe, recap and menu goes through the page.
|
||||
- Post `"stopWarning"` while no map exists (Steps 0 to 4) and `"stopWarning": ""`
|
||||
once it does, and `"specDir": "specs/<idea>"` when the folder is created
|
||||
(`console-stop.md` → Saying what stopping would cost).
|
||||
- The menu after a decision is a `menu` card: its `options` are `trail --form C`'s, and the `Start fresh` one keeps its `"fresh": true` (the page words it "Start New Session" under the desktop app and asks the app for one on Send). Set the card's `command` to the resume command printed under `OR START FRESH`: the page copies it first. A declined confirm leaves you the pick: carry on as for any `Start fresh`.
|
||||
- The fresh-idea card carries `"templates": "idea"` and `"fill": "note"` (`console.md` → The kinds): the page fills that box from a Notebook tab when the person started with one.
|
||||
- A doc that is a file exactly as written (the map once it is on disk, a
|
||||
brief) goes up as a `file` block (`{ "id": "body", "file":
|
||||
"specs/<idea>/pathfinder/map.md" }`) rather than pasted. Keep `md` blocks
|
||||
where a block's `assumed` / `draft` state carries meaning.
|
||||
- Chart Step 8's research subagents must all report back before the
|
||||
finish (`console-finish.md` → Nothing of yours may still be running); the
|
||||
finish body then names what each one found.
|
||||
- Report every research subagent as a helper, whatever the Subagents switch
|
||||
says (`console-subagents.md` → Reporting helpers).
|
||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||
sees the Trail Footer, and without this their last screen promises a question
|
||||
that is never coming.
|
||||
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
|
||||
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
|
||||
subagent reports back, or when you resolve a `research` question yourself
|
||||
(`console-meter.md`). Other questions score through their answers, so there is
|
||||
nothing to post for them.
|
||||
- The scope probe is **Leave for later**: "Which of these features are we
|
||||
leaving out this time?" as a `multi` with a recommended preset. Every option
|
||||
names a feature, and its `detail` ends "(Leaving this out = …)". Never phrase
|
||||
an option as a rule to keep.
|
||||
- Post `"stopWarning"` while no map exists (Steps 0 to 4), `""` once it does, and `"specDir":"specs/<idea>"` when the folder is created.
|
||||
- The menu after a decision is a `menu` card: `options` are `trail --form C`'s, the `Start fresh` one keeps `"fresh":true`. Set the card's `command` to the resume command printed under `OR START FRESH`. A declined confirm leaves you the pick: carry on as for `Start fresh`.
|
||||
- The fresh-idea card carries `"templates":"idea"`, `"fill":"note"`.
|
||||
- A doc that is a file as written (the map, a brief) is a `file` block (`{"id":"body","file":"specs/<idea>/pathfinder/map.md"}`). Keep `md` where `assumed` / `draft` state matters.
|
||||
- Step 8 research subagents all report before the finish; the finish `body` names what each found. Report every one as a helper, whatever the Subagents switch says.
|
||||
- Every session end `finish`es with Form A's command as `command`.
|
||||
- Post `run` `pathfinder-chart` (id `map`) when a map is first written, and `pathfinder-research` (id the question's file slug; on `github`, `q<issue-number>`) as each research subagent reports or when you resolve a `research` question yourself. Other questions score through answers.
|
||||
- The scope probe is **Leave for later**: "Which of these features are we leaving out this time?" as a `multi` with a recommended preset. Each option names a feature, its `detail` ends "(Leaving this out = ...)". Never phrase an option as a rule to keep.
|
||||
|
||||
## Briefs
|
||||
|
||||
The page shows a **Write a brief** button when `workflow` is `pathfinder`,
|
||||
because that is the workflow with a brief playbook. The person picks a range and
|
||||
presses it; nothing else about the session changes.
|
||||
|
||||
It arrives through the wait loop like any other send:
|
||||
The page shows **Write a brief** for this workflow. It arrives as a send:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"type": "submit",
|
||||
"actions": [{ "i": "__brief", "type": "brief", "range": "since 2026-09-15" }],
|
||||
"reply": "Write a brief covering everything since 2026-09-15."
|
||||
}
|
||||
{"reply":"Write a brief covering everything since 2026-09-15.","session":[{"i":"__brief","range":"since 2026-09-15"}]}
|
||||
```
|
||||
|
||||
`range` is one of `today`, `this week`, `since <YYYY-MM-DD>` or `full`, which is
|
||||
the range grammar the brief playbook already parses. `reply` says the same thing
|
||||
in words, so a workflow that only reads `reply` needs no new code path. The
|
||||
`__brief` id is not an item and matches nothing; it marks the action as being
|
||||
about the session rather than about a question.
|
||||
|
||||
Run your normal brief procedure, write the file where it belongs, and then put
|
||||
the same report on the page as a doc, as a `file` block on the file you wrote:
|
||||
`range` is `today`, `this week`, `since <YYYY-MM-DD>` or `full`. `__brief` matches no item. Run your brief procedure, write the file, then post it as one `file` block in doc `brief` (reused, so a second replaces the first; Save as HTML appears only on that id):
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"docs": [{
|
||||
"id": "brief",
|
||||
"title": "Brief",
|
||||
"note": "Covers this week",
|
||||
"blocks": [{ "id": "body", "file": "specs/<idea>/pathfinder/briefs/<the brief>.md" }]
|
||||
}]
|
||||
}
|
||||
{"docs":[{"id":"brief","title":"Brief","note":"Covers this week","blocks":[{"id":"body","file":"specs/<idea>/pathfinder/briefs/<the brief>.md"}]}]}
|
||||
```
|
||||
|
||||
One block holding the whole report is right here: a brief is read start to
|
||||
finish, not block by block, and it gets Save as HTML, Print and Download buttons
|
||||
that work on the document as a whole. Save as HTML appears only on the doc with
|
||||
the id `brief`. Reuse the id `brief` so a second brief replaces the first
|
||||
rather than growing a row of tabs; its version moves up by itself.
|
||||
|
||||
Say in chat where the file went, as you always would. The page is a second copy
|
||||
for reading and printing, never the record.
|
||||
Say in chat where the file went.
|
||||
@@ -1,22 +1,6 @@
|
||||
# Planning on the Web Console
|
||||
# Planning
|
||||
|
||||
Workflow notes for `plan`, part of the web console contract (`console.md`).
|
||||
|
||||
- Open with `--workflow plan`, first thing. Every question and sign-off gate
|
||||
goes through the page, phase breakdowns as an editable `list`.
|
||||
- The fresh-idea card carries `"templates": "idea"` and `"fill": "note"` (`console.md` → The kinds): the page fills that box from a Notebook tab when the person started with one.
|
||||
- Planning has no mid-session save before the Large checkpoint or Phase 7, so for
|
||||
a stop before then say plainly in `finish.body` that nothing was kept, and use
|
||||
`"command": "/plan2code-1-plan"`. After the checkpoint, post
|
||||
`"stopWarning": ""` (`console-stop.md`).
|
||||
- At every session end, post `finish` BEFORE `stop`; on completion that is
|
||||
`"command": "/plan2code-2-document"`, and at the Large checkpoint it is
|
||||
`/plan2code-1-plan`. The closing message is printed to a terminal the
|
||||
browser user is not watching.
|
||||
- The Large checkpoint finish is a pause: a headline starting "Paused", no
|
||||
`dashboard`, and `stop` at once.
|
||||
- Plan offers the Subagents switch. A `Subagents:` block may arrive on `open`
|
||||
output or a `wait` / `chat` pickup: follow `console-subagents.md` and the
|
||||
skill's Helpers section, and report each helper as `helpers`. Post a helper
|
||||
as `done` or `failed` before the sign-off it feeds, and every one before a
|
||||
`finish`. Questions, sign-offs and the PLAN-DRAFT stay with you.
|
||||
- Phase breakdowns are an editable `list`. The fresh-idea card carries `"templates":"idea"`, `"fill":"note"`.
|
||||
- Nothing is saved before the Large checkpoint or Phase 7: a stop before then has `finish.body` say nothing was kept, `"command":"/plan2code-1-plan"`. After the checkpoint post `"stopWarning":""`.
|
||||
- Completion finish `command`: `/plan2code-2-document`. The Large checkpoint finish is a pause: headline starts "Paused", `command` `/plan2code-1-plan`, no `dashboard`.
|
||||
- Helpers are reported as `helpers`, each `done` or `failed` before the sign-off it feeds. Questions, sign-offs and the PLAN-DRAFT stay with you.
|
||||
@@ -1,106 +1,34 @@
|
||||
# Quick Task on the Web Console
|
||||
# Quick Task
|
||||
|
||||
Workflow notes for `quick-task`, part of the web console contract
|
||||
(`console.md`). Read `building.md` first.
|
||||
Read `building.md` first.
|
||||
|
||||
## Quick task (`quick-task`)
|
||||
|
||||
- Open with the first clarifying question. Clarifying questions go out as
|
||||
`text` or `choice`, at most three at a time. The first, asking what to build,
|
||||
carries `"templates": "idea"` and `"fill": "note"` (`console.md` → The kinds): the page fills that box from a Notebook tab when the person started with one.
|
||||
- Post `"stopWarning": "A quick task saves nothing until it is built, so stopping now loses what we have worked out."`
|
||||
at the start, and `"stopWarning": ""` once the build is under way.
|
||||
- **Scope check:** a `choice`, "Too big for a quick task?", options
|
||||
`1` Continue (lightweight format) and `2` Escalate to a full plan, with the
|
||||
measured counts against the thresholds in `body`.
|
||||
- **Feature name** (escalating): `text` with
|
||||
`"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"` and a kebab-case placeholder.
|
||||
- **The plan:** a `plan` doc titled "Plan", one block per section, with the
|
||||
Steps written as a checklist so the build can tick them in place, and a
|
||||
`review` item "Build this plan?" (`"doc": "plan"`) with verdicts `yes`
|
||||
("Build it"), `modify` ("Change the plan"), `escalate` ("Plan it properly
|
||||
instead") and `abort` ("Stop here", `"danger": true`):
|
||||
- Clarifying questions are `text` or `choice`. The first (what to build) carries `"templates":"idea"`, `"fill":"note"`.
|
||||
- Post `"stopWarning":"A quick task saves nothing until it is built, so stopping now loses what we have worked out."` at the start and `""` once the build is under way.
|
||||
- **Scope check:** `choice` "Too big for a quick task?": `1` Continue (lightweight format), `2` Escalate to a full plan; measured counts against thresholds in `body`.
|
||||
- **Feature name** (escalating): `text`, `"pattern":"^[a-z0-9]+(-[a-z0-9]+)*$"`, kebab-case placeholder.
|
||||
- **The plan:** doc `plan`, one block per section, Steps as a checklist, plus `review` "Build this plan?" (`"doc":"plan"`) with verdicts `yes` ("Build it"), `modify` ("Change the plan"), `escalate` ("Plan it properly instead"), `abort` ("Stop here", `danger`):
|
||||
|
||||
```jsonc
|
||||
{ "id": "plan", "title": "Plan", "blocks": [
|
||||
{ "id": "summary", "state": "settled", "md": "## Summary\n\n..." },
|
||||
{ "id": "files", "state": "settled", "md": "## Files to change\n\n- `src/a.ts` - ..." },
|
||||
{ "id": "steps", "state": "settled", "md": "## Steps\n\n- [ ] **1.** Step one\n- [ ] **2.** Step two\n- [ ] **3.** Step three\n- [ ] **4.** Step four" },
|
||||
{ "id": "verify", "state": "settled", "md": "## Verify\n\n- [ ] ..." }
|
||||
]}
|
||||
{"id":"plan","title":"Plan","blocks":[{"id":"summary","state":"settled","md":"## Summary\n\n..."},{"id":"files","state":"settled","md":"## Files to change\n\n- `src/a.ts` - ..."},{"id":"steps","state":"settled","md":"## Steps\n\n- [ ] **1.** Step one\n- [ ] **2.** Step two"},{"id":"verify","state":"settled","md":"## Verify\n\n- [ ] ..."}]}
|
||||
```
|
||||
|
||||
A `modify` reposts the changed blocks, Steps still a checklist; the version
|
||||
moves up by itself.
|
||||
- **Building** after `yes`: the Plan tab is the build's live task list, the
|
||||
way an Implement phase has its tasks tab. There is no separate progress tab.
|
||||
Settle the verdict (`"settle": true`) in the post that starts the build; the
|
||||
plan's steps are the tasks and `total` is their number:
|
||||
A `modify` reposts the changed blocks.
|
||||
- **Building** after `yes`: the Plan tab is the live task list; steps are the tasks. Settle the verdict in the post that starts it:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"stopWarning": "",
|
||||
"settle": true,
|
||||
"headline": { "stage": "Building", "cleared": 0, "total": 4 },
|
||||
"agent": { "status": "working", "activity": "Task 1 of 4: step one", "quietMinutes": 10 }
|
||||
}
|
||||
{"stopWarning":"","settle":true,"headline":{"stage":"Building","cleared":0,"total":4},"agent":{"status":"working","activity":"Task 1 of 4: step one","quietMinutes":10}}
|
||||
```
|
||||
|
||||
Then post after every step, as `building.md` → While you build says, in the
|
||||
same breath as finishing it: repost the plan's `steps` block alone (blocks
|
||||
merge by id, so Summary, Files and Verify stay as they are) with that step
|
||||
ticked; raise `headline.cleared`; set `agent.activity` to the next step
|
||||
("Task 2 of 4: step two"). The plan lives only on the page, so this block is
|
||||
`md`, not `file`:
|
||||
After each step (`building.md` → While you build), repost the `steps` block alone, as `md` since the plan lives only on the page:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "cleared": 1 },
|
||||
"docs": [{ "id": "plan", "blocks": [
|
||||
{ "id": "steps", "state": "settled", "md": "## Steps\n\n- [x] **1.** Step one\n- [ ] **2.** Step two\n- [ ] **3.** Step three\n- [ ] **4.** Step four" }
|
||||
]}],
|
||||
"agent": { "activity": "Task 2 of 4: step two" }
|
||||
}
|
||||
{"headline":{"cleared":1},"docs":[{"id":"plan","blocks":[{"id":"steps","state":"settled","md":"## Steps\n\n- [x] **1.** Step one\n- [ ] **2.** Step two"}]}],"agent":{"activity":"Task 2 of 4: step two"}}
|
||||
```
|
||||
|
||||
A step that cannot be done is `- [!]` with the reason after it, and is not
|
||||
counted in `cleared`. A step added mid-build goes into the list and raises
|
||||
`headline.total` in the same post. Tick each step the moment it is done,
|
||||
never in a batch at the end: the person is watching the Plan tab fill in.
|
||||
Check for a Quick question between steps, and do not call `wait` until the
|
||||
build is done. Tick the Verify block's boxes too as the checks pass, in the
|
||||
post that reports them.
|
||||
- **See it running, before the finish:** a finished screen freezes every open
|
||||
card, so ask first. Once the build is done, post a `review` item "See it
|
||||
running" (`"doc": "plan"`, verdicts `show` ("Show me it working") and `fine`
|
||||
("No need, finish up"), token `show me` / `no`) with `--wait`. On `show`, run
|
||||
it as `notes/implement.md` → Show me it working says, its one line going into
|
||||
the work summary (the finish's `body`); then, or on `fine`, settle the card in
|
||||
the same post as the finish.
|
||||
- **Archive a fixed bug, before the finish:** launched on a diagnosed folder
|
||||
and now Fixed with nothing past the diagnosis, post a `confirm` card
|
||||
"Archive this bug?" in the same post as "See it running": the dry run's
|
||||
`files` in `body`, `yesLabel` "Archive it", `noLabel` "Keep it in specs/",
|
||||
and `consequences` naming `specs--completed/<bug>/`. On yes, run
|
||||
`node "<S>/specs.mjs" archive <spec>` (the skill file says where `<S>` is),
|
||||
and say where it went in the finish's `body`. On no, the
|
||||
dashboard lists the folder as "Bug fixed", never pre-selected.
|
||||
- **The finish after the build:** `command` is the commit command, filled in,
|
||||
in the project's commit format (AGENTS.md), with
|
||||
`"where": "When you are happy with it, commit it from your terminal:"`, and
|
||||
`review` on offer — the **Review it now** button, since a quick task has no
|
||||
sign-off card to put it on — `"commit": true` (the **Commit it now** button;
|
||||
`console-finish.md`), `"changelog": true` (**Update CHANGELOG first**, beside
|
||||
it; it hops into Changelog and on to Git) and `"dashboard": true`, so the finished screen
|
||||
also offers **Back to the dashboard**. Review and dashboard are required: a finish without
|
||||
`dashboard` leaves the person on a dead end. Keep waiting for whichever
|
||||
button is pressed, and everything after that is `building-review.md`.
|
||||
- **Escalated / aborted:** settle the verdict the same way in the finish post —
|
||||
finish with `"command": "/plan2code-1-plan"` and the
|
||||
PLAN-DRAFT's path in `body`, no review; or `"command": "/plan2code-quick-task"`.
|
||||
Both set `"dashboard": true`: an abort of a quick task saves nothing to
|
||||
resume, so it is not a pause.
|
||||
A step that cannot be done is `- [!]` with the reason, not counted in `cleared`. A step added mid-build raises `headline.total` in the same post. Tick Verify boxes in the post that reports the checks. Do not `wait` until the build is done.
|
||||
- **See it running, before the finish:** once built, post `review` "See it running" (`"doc":"plan"`, verdicts `show` ("Show me it working"), `fine` ("No need, finish up"), tokens `show me` / `no`) with `--wait`. On `show`, see `notes/implement.md` → Show me it working; its one line goes in the finish `body`. Settle the card in the finish post.
|
||||
- **Archive a fixed bug:** launched on a diagnosed folder and now Fixed with nothing past the diagnosis, post `confirm` "Archive this bug?" in the same post as "See it running": dry run's `files` in `body`, `yesLabel` "Archive it", `noLabel` "Keep it in specs/", `consequences` naming `specs--completed/<bug>/`. Yes: `node "<S>/specs.mjs" archive <spec>`, and say where it went in the finish `body`.
|
||||
- **Finish after the build:** `command` is the filled-in commit command in the project's format (AGENTS.md), `"where":"When you are happy with it, commit it from your terminal:"`, with `review` (**Review it now**), `"commit":true`, `"changelog":true` and `"dashboard":true`. Review and dashboard are required. Whichever button is pressed, what follows is `building-review.md`.
|
||||
- **Escalated / aborted:** settle the verdict in the finish post: `"command":"/plan2code-1-plan"` with the PLAN-DRAFT's path in `body`, no review; or `"command":"/plan2code-quick-task"`. Both `"dashboard":true`.
|
||||
|
||||
## Stop requests during a build
|
||||
|
||||
See `building.md` → Stop requests during a build.
|
||||
Stop requests during a build: `building.md`.
|
||||
@@ -1,34 +1,9 @@
|
||||
# Review on the Web Console
|
||||
# Review
|
||||
|
||||
Workflow notes for `review`, part of the web console contract (`console.md`).
|
||||
A review run from a build's review button stays in the build's session, under
|
||||
its workflow: `building-review.md` governs it instead.
|
||||
Standalone with nothing named: first a `choice` "What should I review?" from a quick scan (branch changes, uncommitted changes, specs, files you name; each with its size). A build's review skips it. Launched from the dashboard: `open --resume <sid> --no-open --workflow review`. Post `activity` while you read.
|
||||
|
||||
Scope questions up front — run standalone with nothing named, the first is
|
||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
||||
uncommitted changes, specs, files you name; each option with its size),
|
||||
never an assumed target; a build's review skips it (`building-review.md`). Then the
|
||||
findings report as a doc (`id: "report"`), then the pick-what-gets-fixed menu
|
||||
as a `multi` or `choice` keyed by finding id, carrying `"doc": "report"` so the
|
||||
card links straight to the findings. Settle that item (`"settle": true`) in the
|
||||
same post that takes the picks up: left open it stays on the page as a question
|
||||
still owed, next to whatever you ask next. Post `activity` while you read — a
|
||||
real review is long stretches of you working, and the page should say so rather
|
||||
than hint at questions.
|
||||
Findings are doc `report`; the fix menu is a `multi` or `choice` keyed by finding id with `"doc":"report"`, settled (`"settle":true`) in the post that takes the picks up.
|
||||
|
||||
When the session was launched from the dashboard, resume the session you were
|
||||
handed (`open --resume <sid> --no-open --workflow review`), never a fresh
|
||||
`open`.
|
||||
Closing gate: `review` "Check the fixes", `"doc":"report"`, `"nothingYet":false`, verdicts `approve`, `changes`.
|
||||
|
||||
Review Mode's closing gate ("Reply approved to commit, or request changes")
|
||||
is a `review` item titled "Check the fixes", `doc: "report"`, `"nothingYet":
|
||||
false` (the fixes are already on disk), verdicts `approve` and `changes`.
|
||||
|
||||
On completion the finish's `command` is the suggested commit when fixes
|
||||
landed — filled in, in the AGENTS.md format, with
|
||||
`"where": "When you are happy with it, commit it from your terminal:"` —
|
||||
otherwise leave `command` out; with one, `"commit": true` puts **Commit it
|
||||
now** beside it. The completion finish carries `"dashboard": true`
|
||||
so the finished screen offers **Back to the dashboard**; keep waiting for the
|
||||
press. A stop mid-review loses nothing on disk, so its finish is the bare
|
||||
`/plan2code-review` (a pause, so no dashboard button).
|
||||
Completion finish: `command` is the suggested commit when fixes landed (AGENTS.md format, `"where":"When you are happy with it, commit it from your terminal:"`, `"commit":true`), else none; `"dashboard":true`. A stop's `command` is the bare `/plan2code-review`, no dashboard.
|
||||
@@ -1,26 +1,12 @@
|
||||
# Revision on the Web Console
|
||||
# Revision
|
||||
|
||||
Workflow notes for `revise-plan`, part of the web console contract (`console.md`).
|
||||
|
||||
Revision is a short run of gates, and each maps onto a kind you already know:
|
||||
|
||||
| Step | On the page |
|
||||
| Step | Card |
|
||||
| --- | --- |
|
||||
| 1, Change Analysis | A `recap` item, "Is this the change?", with the affected-areas table in `summary`. Found a waiting `**Plan change:**` brief? Quote it at the top of that `summary` and post no open "what should change" card first. With none waiting, the first card is a `text` item titled "What should change", `"fill": "note"`, asking what to change; its answer feeds the "Is this the change?" recap. |
|
||||
| 2, Impact Assessment | The Revision Impact Summary as a doc (`id: "impact"`), and a `review` item "Approve the spec changes" pointing at it: verdicts `approve` ("Approve these spec changes"), `refine` ("Refine the plan") and `abort` ("Abort", `"danger": true`), `nothingYet`: "No spec file changes until you approve." |
|
||||
| 3 to 5 | Nothing to ask. Post `activity` while you edit, then the Revision Complete summary as a doc. |
|
||||
| 6, Cleanup | A `confirm` per rename or removal, the paths in `consequences`. |
|
||||
| 1, Change Analysis | `recap` "Is this the change?", affected-areas table in `summary`. A waiting `**Plan change:**` brief is quoted atop `summary` and no "what should change" card goes first; with none, the first card is `text` "What should change", `"fill":"note"`. |
|
||||
| 2, Impact | Doc `impact`, plus `review` "Approve the spec changes": verdicts `approve`, `refine`, `abort` (`danger`), `nothingYet` "No spec file changes until you approve." |
|
||||
| 3 to 5 | Nothing to ask: `activity` while you edit, then the Revision Complete summary as a doc. |
|
||||
| 6, Cleanup | `confirm` per rename or removal, paths in `consequences`. |
|
||||
|
||||
Revision's own rule holds on the page too: **no option, verdict or label ever
|
||||
offers to execute or implement.** Pass `--spec specs/<feature>` to `open`, or
|
||||
post `specDir` once you know it. The finish command is
|
||||
`/plan2code-3-implement specs/<feature>/overview.md`; an abort's is
|
||||
`/plan2code-1b-revise-plan specs/<feature>/overview.md`.
|
||||
No option, verdict, label, or helper `title`, `ask` or `result` ever offers to execute or implement. Pass `--spec specs/<feature>` to `open` or post `specDir`. Finish `command`: `/plan2code-3-implement specs/<feature>/overview.md`; abort: `/plan2code-1b-revise-plan specs/<feature>/overview.md`.
|
||||
|
||||
Revision offers the Subagents switch. A `Subagents:` block may arrive on
|
||||
`open` output or a `wait` / `chat` pickup: follow `console-subagents.md` and
|
||||
the skill's Helpers section, and report each helper as `helpers`. Lookup
|
||||
helpers report back before the Step 2 review item goes up; phase-file helpers
|
||||
report back before the Step 4 check. Every gate stays with you, and a helper's
|
||||
`title`, `ask` and `result` follow the same rule as every label: nothing
|
||||
offers to execute or implement.
|
||||
Helpers: lookup helpers report before the Step 2 review goes up; phase-file helpers before the Step 4 check.
|
||||
@@ -1,73 +1,37 @@
|
||||
# X-ray on the Web Console
|
||||
|
||||
Workflow notes for `xray`, part of the web console contract (`console.md`).
|
||||
# X-ray
|
||||
|
||||
## The mode question
|
||||
|
||||
A typed argument that names the mode and area skips it. Otherwise ask both in
|
||||
one batch, posted with `--wait`:
|
||||
An argument naming mode and area skips it. Otherwise one `--wait` batch:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"title": "Codebase X-ray",
|
||||
"headline": { "stage": "Choosing", "cleared": 0, "total": 2 },
|
||||
"items": [
|
||||
{ "id": "mode", "kind": "choice", "title": "What you want to know", "allowOther": false,
|
||||
"body": "Explain one area, or rank what makes this code hard to change.",
|
||||
"options": [
|
||||
{ "k": "1", "text": "Explain an area", "detail": "How it works and why it is that way, citing files and the commits behind it." },
|
||||
{ "k": "2", "text": "Find the rough spots", "detail": "Ranked spots that make change hard. You pick the ones worth fixing; they become a brief for Pathfinder or Plan." }
|
||||
] },
|
||||
{ "id": "area", "kind": "text", "title": "Which area", "required": false,
|
||||
"body": "A folder, file or feature. Needed to explain; leave it empty to survey the whole repository.",
|
||||
"placeholder": "src/exporter, the code that builds the CSV reports" }
|
||||
]
|
||||
}
|
||||
{"title":"Codebase X-ray","headline":{"stage":"Choosing","cleared":0,"total":2},"items":[{"id":"mode","kind":"choice","title":"What you want to know","allowOther":false,"body":"Explain one area, or rank what makes this code hard to change.","options":[{"text":"Explain an area","detail":"How it works and why, citing files and commits."},{"text":"Find the rough spots","detail":"Ranked spots that make change hard. You pick the ones worth fixing; they become a brief for Pathfinder or Plan."}]},{"id":"area","kind":"text","title":"Which area","required":false,"body":"A folder, file or feature. Needed to explain; empty surveys the whole repository."}]}
|
||||
```
|
||||
|
||||
Explain picked with the area left empty: ask for it again as a required `text`
|
||||
card. No recommendation on the mode: only the person knows what they came for.
|
||||
Explain with the area empty: ask again as a required `text`.
|
||||
|
||||
## Explain mode
|
||||
|
||||
The answer is a doc, `id` `"answer"`, one block per section (`In one paragraph`,
|
||||
`How it works`, `Why it is this way`, `Worth knowing`), with the `Sources:` line
|
||||
at the top of the first. Then the save offer as a `confirm` card pointing at it:
|
||||
Doc `answer`, one block per section (`In one paragraph`, `How it works`, `Why it is this way`, `Worth knowing`), `Sources:` line atop the first. Then:
|
||||
|
||||
```jsonc
|
||||
{ "id": "keep", "kind": "confirm", "title": "Keep this answer", "doc": "answer",
|
||||
"body": "Save it as `specs/exporter/XRAY-exporter-20261016.md`, as input for Pathfinder or Plan?",
|
||||
"yesLabel": "Save it", "noLabel": "No, just reading" }
|
||||
{"id":"keep","kind":"confirm","title":"Keep this answer","doc":"answer","body":"Save it as `specs/exporter/XRAY-exporter-20261016.md`, as input for Pathfinder or Plan?","yesLabel":"Save it","noLabel":"No, just reading"}
|
||||
```
|
||||
|
||||
Ask the folder name in the same batch as a `text` card with `pattern`
|
||||
`^[a-z0-9]+(-[a-z0-9]+)*$` when it is not obvious. Once written, re-send the doc
|
||||
with `"saved": "specs/<name>/XRAY-<area-slug>-<date>.md"`.
|
||||
When the folder name is not obvious, ask it in the same batch as a `text` with `pattern` `^[a-z0-9]+(-[a-z0-9]+)*$`. Once written, re-send the doc with `"saved":"specs/<name>/XRAY-<area-slug>-<date>.md"`.
|
||||
|
||||
## Rough-spots mode
|
||||
|
||||
The ranked list is a doc, `id` `"spots"`, one block per spot (its files, why it
|
||||
hurts, the "to change X today" example). The pick is one `multi` card pointing
|
||||
at it, posted with `--wait`:
|
||||
Doc `spots`, one block per spot (files, why it hurts, the "to change X today" example). Pick, `--wait`:
|
||||
|
||||
```jsonc
|
||||
{ "id": "pick", "kind": "multi", "title": "Worth fixing", "doc": "spots", "required": false,
|
||||
"body": "Tick the spots worth fixing. Add a note for any of them in the box (\"1: the exporter part only\"). Only ticked spots go into the brief.",
|
||||
"options": [
|
||||
{ "k": "1", "text": "Exporter and its formatter always change together", "detail": "src/export.ts, src/format.ts: together in 14 of 16 commits." }
|
||||
] }
|
||||
{"id":"pick","kind":"multi","title":"Worth fixing","doc":"spots","required":false,"body":"Tick the spots worth fixing. Only ticked spots go into the brief.","options":[{"text":"Exporter and its formatter always change together"}]}
|
||||
```
|
||||
|
||||
Nothing ticked: nothing is written. Otherwise write the brief, then add it as a
|
||||
second doc with `"saved": "specs/<name>/ARCHITECTURE-BRIEF-<date>.md"` and a
|
||||
`file` block.
|
||||
Nothing ticked: nothing written. Otherwise write the brief and add it as a second doc with `"saved":"specs/<name>/ARCHITECTURE-BRIEF-<date>.md"` and a `file` block.
|
||||
|
||||
## The finish
|
||||
|
||||
`command` is `/plan2code-0-pathfinder` (big or unclear) or `/plan2code-1-plan`
|
||||
(settled), never with a placeholder; leave it out when nothing was kept. `doc`
|
||||
is the brief or the saved answer when there is one. `"dashboard": true`, then
|
||||
keep waiting for the press (`console-finish.md`).
|
||||
`command` is `/plan2code-0-pathfinder` (big or unclear) or `/plan2code-1-plan` (settled); none when nothing was kept. `doc` is the brief or saved answer. `"dashboard":true`.
|
||||
|
||||
A stop before anything was written ends on a finish whose `body` says nothing
|
||||
was kept, with `"command": "/plan2code-xray"` (`console-stop.md`).
|
||||
A stop before anything was written: `body` says nothing was kept, `"command":"/plan2code-xray"`.
|
||||
+497
-120
@@ -15,10 +15,24 @@ export function isPlainObject(v) {
|
||||
return v !== null && typeof v === "object" && !Array.isArray(v);
|
||||
}
|
||||
|
||||
/**
|
||||
* One form for every refusal, so a retry can be written from the message alone:
|
||||
* `item "q2" options: <what is wrong>. Like this: <the field done right>` for a
|
||||
* card, `finish: <what is wrong>. Like this: ...` for the rest. `where` is the
|
||||
* thing named (`item "q2"`, `doc "report"`), or "" for a top-level field;
|
||||
* `right` is a value, written as minified JSON, and left out when there is no
|
||||
* sensible example.
|
||||
*/
|
||||
export function rule(where, field, wrong, right) {
|
||||
const head = [where, field].filter(Boolean).join(" ");
|
||||
const text = String(wrong).replace(/\.\s*$/, "");
|
||||
return `${head}: ${text}.${right === undefined ? "" : ` Like this: ${JSON.stringify(right)}`}`;
|
||||
}
|
||||
|
||||
// Reject prototype-pollution attempts before they reach the merge.
|
||||
function guard(obj, where) {
|
||||
if (isPlainObject(obj) && Object.prototype.hasOwnProperty.call(obj, "__proto__")) {
|
||||
throw new Error(`"__proto__" is not a valid key (in ${where})`);
|
||||
throw new Error(rule("", where, '"__proto__" is not a valid key'));
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
@@ -40,7 +54,7 @@ function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||
for (const entry of patchList) {
|
||||
guard(entry, where);
|
||||
const id = entry[idKey];
|
||||
if (!id) throw new Error(`every ${where} entry needs "${idKey}"`);
|
||||
if (!id) throw new Error(rule("", where, `every entry needs "${idKey}"`, { [idKey]: where === "items" ? "q7" : "a1" }));
|
||||
const i = out.findIndex((x) => x[idKey] === id);
|
||||
if (entry._delete) {
|
||||
if (i !== -1) out.splice(i, 1);
|
||||
@@ -50,6 +64,16 @@ function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||
return out;
|
||||
}
|
||||
|
||||
// Every default the console fills, so a patch leaves these out (overview.md,
|
||||
// Data Model; the card in console.md lists the same ones, keep the two in step):
|
||||
// new item status "open", required true, allowOther true, options [], thread []
|
||||
// new doc version 1, stale false, blocks [] (DOC_DEFAULTS, below)
|
||||
// a block's state: the page reads a missing one as "settled"
|
||||
// a review item's verdicts: the page offers approve / changes when it has none
|
||||
// option k: "A", "B", "C"... by position, when no option of the item has
|
||||
// one (letterOptions(), below)
|
||||
// Not defaulted, by choice: a topic's status, and `settle: true` on every post
|
||||
// (it would close a pick that still owes its recap).
|
||||
const ITEM_DEFAULTS = {
|
||||
status: "open",
|
||||
required: true,
|
||||
@@ -58,6 +82,36 @@ const ITEM_DEFAULTS = {
|
||||
thread: [],
|
||||
};
|
||||
|
||||
// A, B, C... Z, then AA, AB... by position.
|
||||
function optionKey(i) {
|
||||
return i < 26 ? String.fromCharCode(65 + i) : String.fromCharCode(64 + Math.floor(i / 26)) + String.fromCharCode(65 + (i % 26));
|
||||
}
|
||||
|
||||
/**
|
||||
* Give the options a patch sends their keys by position when none has one.
|
||||
* Every option keyed is left alone; some keyed and some not is refused, naming
|
||||
* the item. Only the options in this patch: stored ones are never re-lettered.
|
||||
*/
|
||||
function letterOptions(patchList) {
|
||||
return patchList.map((entry) => {
|
||||
if (!isPlainObject(entry) || !entry.id || !Array.isArray(entry.options) || !entry.options.length) return entry;
|
||||
if (!entry.options.every(isPlainObject)) return entry;
|
||||
const keyed = entry.options.filter((o) => o.k != null && o.k !== "").length;
|
||||
if (keyed === entry.options.length) return entry;
|
||||
if (keyed > 0) {
|
||||
throw new Error(
|
||||
rule(
|
||||
`item "${entry.id}"`,
|
||||
"options",
|
||||
'some options have "k" and some do not. Give every option a "k", or none to have them lettered A, B, C',
|
||||
{ options: [{ text: "CSV" }, { text: "Excel" }] },
|
||||
),
|
||||
);
|
||||
}
|
||||
return { ...entry, options: entry.options.map((o, i) => ({ ...o, k: optionKey(i) })) };
|
||||
});
|
||||
}
|
||||
|
||||
// The question a card asks. If a patch rewrites any of these on a known id, it
|
||||
// is a new question wearing an old id.
|
||||
const QUESTION_FIELDS = ["kind", "title", "body", "options", "steps", "rows", "summary", "doc", "verdicts"];
|
||||
@@ -73,6 +127,28 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
||||
const merged = mergeKeyed(currentItems, patchList, "id", ITEM_DEFAULTS, "items");
|
||||
for (const entry of patchList) {
|
||||
const prev = (before || []).find((x) => x.id === entry.id);
|
||||
// A whole new question under an answered card's id is not a typo fix: the
|
||||
// card would stay answered and nothing would be left for the person, who
|
||||
// sees a dead page. Refuse it so the agent picks a new id on the spot.
|
||||
if (
|
||||
prev &&
|
||||
(prev.status === "answered" || prev.status === "skipped") &&
|
||||
!("status" in entry) &&
|
||||
!("answer" in entry) &&
|
||||
"title" in entry &&
|
||||
entry.title !== prev.title &&
|
||||
(("body" in entry && entry.body !== prev.body) ||
|
||||
("options" in entry && JSON.stringify(entry.options) !== JSON.stringify(prev.options)))
|
||||
) {
|
||||
throw new Error(
|
||||
rule(
|
||||
`item "${entry.id}"`,
|
||||
"id",
|
||||
`was already used for the answered question "${prev.title}", so this new question ("${entry.title}") would stay answered and the person would see nothing to answer. Give it a new id, or set status to "reopened" to ask the old one again`,
|
||||
{ id: "q12", kind: entry.kind || prev.kind, title: entry.title },
|
||||
),
|
||||
);
|
||||
}
|
||||
if (!prev || (prev.submitted === undefined && prev.answer === undefined)) continue;
|
||||
const rewritten = QUESTION_FIELDS.some(
|
||||
(f) => f in entry && JSON.stringify(entry[f]) !== JSON.stringify(prev[f]),
|
||||
@@ -111,24 +187,23 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
||||
// at all is refused. The person's own notes are recorded by the server when
|
||||
// they send, so an agent that echoes one back is not shown it twice.
|
||||
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
|
||||
const THREAD_RIGHT = { thread: [{ who: "agent", text: "..." }] };
|
||||
|
||||
function normalizeThreads(patchList, currentItems) {
|
||||
return patchList.map((entry) => {
|
||||
if (!isPlainObject(entry) || entry.thread == null) return entry;
|
||||
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
|
||||
if (!Array.isArray(entry.thread)) throw new Error(rule(`item "${entry.id}"`, "thread", "must be an array", THREAD_RIGHT));
|
||||
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
|
||||
const said = new Set(
|
||||
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
|
||||
);
|
||||
const thread = [];
|
||||
for (const m of entry.thread) {
|
||||
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
|
||||
if (!isPlainObject(m)) throw new Error(rule(`item "${entry.id}"`, "thread", "entries must be objects", THREAD_RIGHT));
|
||||
guard(m, "thread");
|
||||
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
|
||||
if (!key) {
|
||||
throw new Error(
|
||||
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
|
||||
);
|
||||
throw new Error(rule(`item "${entry.id}"`, "thread", 'an entry has no "text"; the page shows nothing else', THREAD_RIGHT));
|
||||
}
|
||||
const { from, role, md, body, content, ...rest } = m;
|
||||
const who = (m.who || from || role) === "user" ? "user" : "agent";
|
||||
@@ -153,8 +228,12 @@ function mergeDocs(current, patchList) {
|
||||
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."
|
||||
rule(
|
||||
`doc "${entry.id}"`,
|
||||
"version",
|
||||
`the page is at version ${prev.version}; this patch sends ${entry.version}. Versions only go up: leave it out, or bump it, and check the payload is the current one`,
|
||||
{ version: prev.version + 1 },
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -186,7 +265,7 @@ function mergeDocs(current, patchList) {
|
||||
function settleItems(items, settle, patchItems, collected) {
|
||||
if (settle === undefined || settle === false) return items;
|
||||
if (settle !== true && !(Array.isArray(settle) && settle.every((id) => typeof id === "string"))) {
|
||||
throw new Error('"settle" must be true or a list of item ids');
|
||||
throw new Error(rule("", "settle", "must be true or a list of item ids", { settle: ["q2"] }));
|
||||
}
|
||||
const sent = (items || []).filter((i) => i && i.submitted && typeof i.submitted === "object");
|
||||
let ids;
|
||||
@@ -202,7 +281,7 @@ function settleItems(items, settle, patchItems, collected) {
|
||||
// The same patch reopening it has already let go of what was sent; the
|
||||
// reopen wins below, so naming it is not an error.
|
||||
const reopening = (patchItems || []).some((e) => e && e.id === id && (e.status === "open" || e.status === "reopened"));
|
||||
if (!reopening && !sent.some((i) => i.id === id)) throw new Error(`settle: "${id}" has nothing sent to settle`);
|
||||
if (!reopening && !sent.some((i) => i.id === id)) throw new Error(rule("", "settle", `"${id}" has nothing sent to settle`, { settle: true }));
|
||||
}
|
||||
ids = settle;
|
||||
}
|
||||
@@ -267,14 +346,16 @@ export function resolveDocFiles(patch, state, worktree) {
|
||||
if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch;
|
||||
const root = path.resolve(worktree || state.worktree || process.cwd());
|
||||
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
|
||||
const read = (file, select, docId) => {
|
||||
if (typeof file !== "string" || !file.trim()) throw new Error(`doc "${docId}": a block's "file" must be a path`);
|
||||
const FILE_RIGHT = { id: "b4", file: "specs/<idea>/overview.md" };
|
||||
const read = (file, select, docId, blockId) => {
|
||||
const bad = (wrong) => new Error(rule(`doc "${docId}" block "${blockId}"`, "file", wrong, FILE_RIGHT));
|
||||
if (typeof file !== "string" || !file.trim()) throw bad("must be a path");
|
||||
const abs = path.resolve(root, file);
|
||||
let real;
|
||||
try {
|
||||
real = fs.realpathSync.native(abs);
|
||||
} catch {
|
||||
throw new Error(`doc "${docId}": no file at ${file}`);
|
||||
throw bad(`no file at ${file}`);
|
||||
}
|
||||
const rootReal = (() => {
|
||||
try {
|
||||
@@ -286,15 +367,15 @@ export function resolveDocFiles(patch, state, worktree) {
|
||||
// path.relative, not a prefix test: a worktree at a drive root ends in a
|
||||
// separator already, and win32's relative() folds case itself.
|
||||
const rel = path.relative(fold(rootReal), fold(real));
|
||||
if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error(`doc "${docId}": ${file} is outside the project`);
|
||||
if (rel.startsWith("..") || path.isAbsolute(rel)) throw bad(`${file} is outside the project`);
|
||||
const stat = fs.statSync(real);
|
||||
if (!stat.isFile()) throw new Error(`doc "${docId}": ${file} is not a file`);
|
||||
if (stat.size > DOC_FILE_MAX) throw new Error(`doc "${docId}": ${file} is larger than ${DOC_FILE_MAX / 1024} KB`);
|
||||
if (!stat.isFile()) throw bad(`${file} is not a file`);
|
||||
if (stat.size > DOC_FILE_MAX) throw bad(`${file} is larger than ${DOC_FILE_MAX / 1024} KB`);
|
||||
const text = fs.readFileSync(real, "utf8").replace(/\r\n/g, "\n");
|
||||
if (select === undefined) return text;
|
||||
if (select !== "tasks") throw new Error(`doc "${docId}": "select" only takes "tasks"`);
|
||||
if (select !== "tasks") throw new Error(rule(`doc "${docId}" block "${blockId}"`, "select", 'only takes "tasks"', { id: blockId, file, select: "tasks" }));
|
||||
const tasks = text.split("\n").filter((l) => TASK_LINE_RE.test(l)).map((l) => l.trim());
|
||||
if (!tasks.length) throw new Error(`doc "${docId}": ${file} has no task lines to select`);
|
||||
if (!tasks.length) throw new Error(rule(`doc "${docId}" block "${blockId}"`, "select", `${file} has no task lines to select`, { id: blockId, file }));
|
||||
return tasks.join("\n");
|
||||
};
|
||||
const docs = patch.docs.map((entry) => {
|
||||
@@ -307,9 +388,9 @@ export function resolveDocFiles(patch, state, worktree) {
|
||||
const again = ((prev && prev.blocks) || [])
|
||||
.filter((b) => b && typeof b.file === "string" && !named.has(b.id))
|
||||
.map((b) => ({ id: b.id, file: b.file, ...(b.select ? { select: b.select } : {}) }));
|
||||
if (!again.length && !blocks) throw new Error(`doc "${entry.id}": "refresh" found no file blocks to re-read`);
|
||||
if (!again.length && !blocks) throw new Error(rule(`doc "${entry.id}"`, "refresh", "found no file blocks to re-read", { id: entry.id, blocks: [FILE_RIGHT] }));
|
||||
blocks = [...(blocks || []), ...again];
|
||||
} else if (refresh !== undefined) throw new Error(`doc "${entry.id}": "refresh" must be true`);
|
||||
} else if (refresh !== undefined) throw new Error(rule(`doc "${entry.id}"`, "refresh", "must be true", { id: entry.id, refresh: true }));
|
||||
if (!blocks) return rest;
|
||||
const prevBlocks = (state.docs || []).find((d) => d && d.id === entry.id)?.blocks || [];
|
||||
return {
|
||||
@@ -325,7 +406,7 @@ export function resolveDocFiles(patch, state, worktree) {
|
||||
// A file named again without `select` is the whole file, now and on
|
||||
// every refresh: an older select must not linger in the merge.
|
||||
const select = "select" in b ? b.select : null;
|
||||
return { state: prevBlock?.state || "settled", ...b, select, md: read(b.file, select ?? undefined, entry.id) };
|
||||
return { state: prevBlock?.state || "settled", ...b, select, md: read(b.file, select ?? undefined, entry.id, b.id) };
|
||||
}),
|
||||
};
|
||||
});
|
||||
@@ -358,14 +439,16 @@ export function resolveDocImages(patch, state, dir) {
|
||||
if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch;
|
||||
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
|
||||
const shotsDir = path.join(path.resolve(dir), SHOTS_DIR_NAME);
|
||||
const check = (image, docId) => {
|
||||
if (typeof image !== "string" || !image.trim()) throw new Error(`doc "${docId}": an image block's "image" must be a path`);
|
||||
const where = `doc "${docId}": image ${image}`;
|
||||
const IMAGE_RIGHT = { id: "b5", image: "shots/run.png", alt: "..." };
|
||||
const check = (image, docId, blockId) => {
|
||||
const at = `doc "${docId}" block "${blockId}"`;
|
||||
if (typeof image !== "string" || !image.trim()) throw new Error(rule(at, "image", "must be a path", IMAGE_RIGHT));
|
||||
const bad = (wrong) => new Error(rule(at, "image", `${image} ${wrong}`, IMAGE_RIGHT));
|
||||
let real;
|
||||
try {
|
||||
real = fs.realpathSync.native(path.resolve(dir, image));
|
||||
} catch {
|
||||
throw new Error(`${where} does not exist. Save it under the session's ${SHOTS_DIR_NAME}/ folder first.`);
|
||||
throw bad(`does not exist. Save it under the session's ${SHOTS_DIR_NAME}/ folder first`);
|
||||
}
|
||||
let realShots;
|
||||
try {
|
||||
@@ -375,15 +458,15 @@ export function resolveDocImages(patch, state, dir) {
|
||||
}
|
||||
const name = path.basename(real);
|
||||
if (fold(path.dirname(real)) !== fold(realShots)) {
|
||||
throw new Error(`${where} is outside the session's ${SHOTS_DIR_NAME}/ folder (${shotsDir}); only pictures saved there can be shown.`);
|
||||
throw bad(`is outside the session's ${SHOTS_DIR_NAME}/ folder (${shotsDir}); only pictures saved there can be shown`);
|
||||
}
|
||||
if (!SHOT_NAME.test(name)) throw new Error(`${where}: name it with letters, digits, dots, dashes or underscores, ending .png, .jpg, .jpeg or .webp`);
|
||||
if (!SHOT_NAME.test(name)) throw bad("needs a plain name: letters, digits, dots, dashes or underscores, ending .png, .jpg, .jpeg or .webp");
|
||||
const stat = fs.statSync(real);
|
||||
if (!stat.isFile()) throw new Error(`${where} is not a file`);
|
||||
if (stat.size > SHOT_MAX) throw new Error(`${where} is larger than ${SHOT_MAX / 1024 / 1024} MB`);
|
||||
if (!stat.isFile()) throw bad("is not a file");
|
||||
if (stat.size > SHOT_MAX) throw bad(`is larger than ${SHOT_MAX / 1024 / 1024} MB`);
|
||||
const ext = path.extname(name).slice(1).toLowerCase();
|
||||
const want = ext === "jpg" ? "jpeg" : ext;
|
||||
if (shotType(fs.readFileSync(real)) !== want) throw new Error(`${where} is not a ${want.toUpperCase()} image (its bytes say otherwise)`);
|
||||
if (shotType(fs.readFileSync(real)) !== want) throw bad(`is not a ${want.toUpperCase()} image (its bytes say otherwise)`);
|
||||
return `${SHOTS_DIR_NAME}/${name}`;
|
||||
};
|
||||
const docs = patch.docs.map((entry) => {
|
||||
@@ -399,10 +482,10 @@ export function resolveDocImages(patch, state, dir) {
|
||||
return ("md" in b || "file" in b) && prevBlock && typeof prevBlock.image === "string" ? { ...b, image: null, alt: null } : b;
|
||||
}
|
||||
if (("md" in b && b.md != null) || ("file" in b && b.file != null)) {
|
||||
throw new Error(`doc "${entry.id}": block "${b.id}" is an image; it cannot also carry "md" or "file"`);
|
||||
throw new Error(rule(`doc "${entry.id}" block "${b.id}"`, "image", 'an image block cannot also carry "md" or "file"', IMAGE_RIGHT));
|
||||
}
|
||||
if (b.alt != null && typeof b.alt !== "string") throw new Error(`doc "${entry.id}": block "${b.id}" "alt" must be text`);
|
||||
return { state: prevBlock?.state || "settled", ...b, image: check(b.image, entry.id), md: null, file: null };
|
||||
if (b.alt != null && typeof b.alt !== "string") throw new Error(rule(`doc "${entry.id}" block "${b.id}"`, "alt", "must be text", IMAGE_RIGHT));
|
||||
return { state: prevBlock?.state || "settled", ...b, image: check(b.image, entry.id, b.id), md: null, file: null };
|
||||
}),
|
||||
};
|
||||
});
|
||||
@@ -418,12 +501,18 @@ export function resolveDocImages(patch, state, dir) {
|
||||
* back into the agent's context on every turn, and the state grows with the
|
||||
* session.
|
||||
*/
|
||||
const HELPERS_RIGHT = { helpers: [{ id: "h1", title: "Read the plan", ask: "Summarize the plan", state: "running" }] };
|
||||
const CHAT_RIGHT = { chat: { replies: [{ re: 12, md: "..." }] } };
|
||||
|
||||
export function applyPatch(state, patch) {
|
||||
guard(patch, "patch");
|
||||
patch = liftActivity(patch);
|
||||
const { settle, ...rest } = patch;
|
||||
patch = rest;
|
||||
const next = { ...state };
|
||||
// `loop` is the page lock and the in-app gate: only `open` (--loop) sets or
|
||||
// clears it, never a patch.
|
||||
if (Object.hasOwn(patch, "loop")) throw new Error(rule("", "loop", "is set by open --loop, not by a patch"));
|
||||
for (const [k, v] of Object.entries(patch)) {
|
||||
if (v === null) {
|
||||
delete next[k];
|
||||
@@ -435,18 +524,18 @@ export function applyPatch(state, patch) {
|
||||
next[k] = mergeOne(next[k], v, k);
|
||||
break;
|
||||
case "items":
|
||||
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
|
||||
if (!Array.isArray(v)) throw new Error(rule("", "items", "must be an array", { items: [{ id: "q7", kind: "text", title: "Name" }] }));
|
||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(letterOptions(v), state.items));
|
||||
break;
|
||||
case "topics":
|
||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||
if (!Array.isArray(v)) throw new Error(rule("", "topics", "must be an array", { topics: [{ id: "t2", title: "How it behaves", status: "current" }] }));
|
||||
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 }');
|
||||
if (!Array.isArray(v)) throw new Error(rule("", "helpers", "must be an array", HELPERS_RIGHT));
|
||||
if (!v.every(isPlainObject)) throw new Error(rule("", "helpers", "entries must be objects, each { id, title, ask, state }", HELPERS_RIGHT));
|
||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
||||
// A real helper report supersedes the working-alone marker, whether it
|
||||
// arrives after one or beside one.
|
||||
@@ -454,19 +543,19 @@ export function applyPatch(state, patch) {
|
||||
next.helpers = next.helpers.filter((h) => !(isPlainObject(h) && h.alone === true));
|
||||
break;
|
||||
case "docs":
|
||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||
if (!Array.isArray(v)) throw new Error(rule("", "docs", "must be an array", { docs: [{ id: "report", title: "Report", blocks: [{ id: "b1", md: "..." }] }] }));
|
||||
next.docs = mergeDocs(next.docs, v);
|
||||
break;
|
||||
case "chat": {
|
||||
// The agent's side of the Quick question chat. The person's side is
|
||||
// the inbox, which only the server writes; nothing else lives here.
|
||||
if (!isPlainObject(v)) throw new Error('"chat" must be an object');
|
||||
if (!isPlainObject(v)) throw new Error(rule("", "chat", "must be an object", CHAT_RIGHT));
|
||||
guard(v, "chat");
|
||||
const extra = Object.keys(v).filter((key) => key !== "replies");
|
||||
if (extra.length) throw new Error(`"chat" only takes "replies" (not ${extra.map((key) => `"${key}"`).join(", ")})`);
|
||||
if (extra.length) throw new Error(rule("", "chat", `only takes "replies" (not ${extra.map((key) => `"${key}"`).join(", ")})`, CHAT_RIGHT));
|
||||
const chat = { ...(next.chat || {}) };
|
||||
if (v.replies != null) {
|
||||
if (!Array.isArray(v.replies)) throw new Error('"chat.replies" must be an array');
|
||||
if (!Array.isArray(v.replies)) throw new Error(rule("", "chat.replies", "must be an array", CHAT_RIGHT));
|
||||
// A reply with no id is named for the message it answers (`r<seq>`),
|
||||
// so a repeat delivery re-posted the same way replaces, never doubles.
|
||||
const named = v.replies.map((r) =>
|
||||
@@ -477,11 +566,28 @@ export function applyPatch(state, patch) {
|
||||
next.chat = chat;
|
||||
break;
|
||||
}
|
||||
case "loopOutcome":
|
||||
// The skill's one report of a phase built under the loop. The shape is
|
||||
// checked by validate(); here only who may send it, and how often.
|
||||
if (!state.loop?.driving) throw new Error(rule("", "loopOutcome", "is only accepted in a loop session"));
|
||||
if (state.loopOutcome !== undefined) throw new Error(rule("", "loopOutcome", "was already posted for this session"));
|
||||
next.loopOutcome = v;
|
||||
break;
|
||||
case "loopEnd":
|
||||
// The app's word on how the loop ended; a later one replaces the earlier.
|
||||
next.loopEnd = v;
|
||||
break;
|
||||
default:
|
||||
next[k] = v;
|
||||
}
|
||||
}
|
||||
if (settle !== undefined) next.items = settleItems(next.items || [], settle, patch.items, state.collected);
|
||||
// A question put to the person over a standing ending means the work went
|
||||
// on past it: the finish card would grey the form out, and the person has
|
||||
// no way to answer. The ending comes down unless this patch posts its own.
|
||||
if (next.finish && !Object.hasOwn(patch, "finish") && asksSomething(patch.items, state.items)) {
|
||||
delete next.finish;
|
||||
}
|
||||
return stampTimes(state, settleAgent(next, patch, state));
|
||||
}
|
||||
|
||||
@@ -570,105 +676,154 @@ const METRICS_BAIT = /\b(Requirements?|Feasibility|Integration|Risk)[:\s|]+\d{1,
|
||||
// reaches state.json (a post's `run` / `folderIssue`). Problems as sentences.
|
||||
export function proseProblems(prose, subject = "text") {
|
||||
const problems = [];
|
||||
if (FORBIDDEN_TOKENS.test(prose)) {
|
||||
problems.push(`${subject} contains a loop completion marker (${prose.match(FORBIDDEN_TOKENS)[0]}); the loop scans for these`);
|
||||
}
|
||||
if (METRICS_BAIT.test(prose)) {
|
||||
const marker = prose.match(FORBIDDEN_TOKENS);
|
||||
if (marker) {
|
||||
problems.push(
|
||||
`${subject} contains "${prose.match(METRICS_BAIT)[0]}" — the metrics collector scrapes that pattern. ` +
|
||||
`Hyphenate it (Requirements-clarity 22/25) or reword.`
|
||||
rule("", subject, `contains a loop completion marker (${marker[0]}); the loop scans for these. Reword it`, marker[0].toLowerCase().replaceAll("_", " ")),
|
||||
);
|
||||
}
|
||||
const bait = prose.match(METRICS_BAIT);
|
||||
if (bait) {
|
||||
problems.push(
|
||||
rule("", subject, `contains ${JSON.stringify(bait[0])}; the metrics collector scrapes that pattern. Hyphenate it or reword`, `${bait[1]}-score ${bait[0].match(/\d+$/)[0]}`),
|
||||
);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// Every string under a value, with where it sits: `${base}` then .key and [i]
|
||||
// steps, so a scan can say which field an offending word is in.
|
||||
function walkStrings(value, base, visit) {
|
||||
if (typeof value === "string") visit(value, base);
|
||||
else if (Array.isArray(value)) value.forEach((v, i) => walkStrings(v, `${base}[${i}]`, visit));
|
||||
else if (isPlainObject(value)) for (const [k, v] of Object.entries(value)) walkStrings(v, base ? `${base}.${k}` : k, visit);
|
||||
}
|
||||
|
||||
export const MAX_OPEN_REQUIRED = 3;
|
||||
|
||||
const OPTIONS_RIGHT = { options: [{ text: "CSV" }, { text: "Excel" }] };
|
||||
const OPTION_RIGHT = { text: "CSV", detail: "Opens in any spreadsheet" };
|
||||
const VERDICTS_RIGHT = {
|
||||
verdicts: [
|
||||
{ id: "approve", label: "Approve" },
|
||||
{ id: "changes", label: "Request changes" },
|
||||
],
|
||||
};
|
||||
const TITLE_RIGHT = { title: "Export format" };
|
||||
const FINISH_RIGHT = { finish: { headline: "Paused: waiting on you", command: "/plan2code-1-plan" } };
|
||||
const HELPER_RIGHT = { helpers: [{ id: "h1", title: "Read the plan", ask: "Summarize the plan", state: "running" }] };
|
||||
|
||||
// `problem` with the field done right appended, for a message that came from
|
||||
// shared code (public/subagents.js) and has no example of its own.
|
||||
const likeThis = (problem, right) => rule("", "", problem, right).replace(/^: /, "");
|
||||
|
||||
/**
|
||||
* Validate a merged state before it is written.
|
||||
*
|
||||
* Returns an array of human-readable problems. An empty array means the patch
|
||||
* is good. These checks turn four prose rules into mechanical ones.
|
||||
* Returns an array of human-readable problems, each in rule()'s form: the item
|
||||
* or field it is about, what is wrong, and the field done right. An empty array
|
||||
* means the patch is good. These checks turn four prose rules into mechanical
|
||||
* ones.
|
||||
*/
|
||||
export function validate(state) {
|
||||
const problems = [];
|
||||
|
||||
if (!Array.isArray(state.items)) return ['"items" must be an array'];
|
||||
if (!Array.isArray(state.items)) {
|
||||
return [rule("", "items", "must be an array", { items: [{ id: "q7", kind: "text", title: "Name" }] })];
|
||||
}
|
||||
|
||||
const ids = new Set();
|
||||
for (const item of state.items) {
|
||||
if (!item.id) problems.push("every item needs an id");
|
||||
if (ids.has(item.id)) problems.push(`duplicate item id "${item.id}"`);
|
||||
const at = `item "${item.id}"`;
|
||||
if (!item.id) problems.push(rule("", "items", 'an entry has no "id". Every new question gets a new id', { id: "q7" }));
|
||||
if (ids.has(item.id)) problems.push(rule(at, "id", "is used twice. Every new question gets a new id", { id: "q8" }));
|
||||
ids.add(item.id);
|
||||
|
||||
if (!ITEM_KINDS.has(item.kind)) {
|
||||
problems.push(`item "${item.id}" has unknown kind "${item.kind}" (one of: ${[...ITEM_KINDS].join(", ")})`);
|
||||
problems.push(rule(at, "kind", `unknown kind "${item.kind}" (one of: ${[...ITEM_KINDS].join(", ")})`, { kind: "choice" }));
|
||||
}
|
||||
if (typeof item.title !== "string" || !item.title.trim()) {
|
||||
problems.push(`item "${item.id}" needs a plain-English title`);
|
||||
problems.push(rule(at, "title", "needs a plain-English title", TITLE_RIGHT));
|
||||
} else {
|
||||
for (const re of JARGON) {
|
||||
if (re.test(item.title)) {
|
||||
problems.push(
|
||||
`item "${item.id}" title contains internal vocabulary (${re.source}). Titles are read by people who have never seen this workflow.`
|
||||
rule(
|
||||
at,
|
||||
"title",
|
||||
`contains internal vocabulary (${re.source}). Titles are read by people who have never seen this workflow`,
|
||||
TITLE_RIGHT,
|
||||
),
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ((item.kind === "choice" || item.kind === "multi") && !Array.isArray(item.options)) {
|
||||
problems.push(`item "${item.id}" is a ${item.kind} and needs "options"`);
|
||||
problems.push(rule(at, "options", `is a ${item.kind} and needs "options"`, OPTIONS_RIGHT));
|
||||
}
|
||||
if ((item.kind === "choice" || item.kind === "multi") && Array.isArray(item.options)) {
|
||||
for (const o of item.options) {
|
||||
if (!o || typeof o.k !== "string" || !o.k.trim()) {
|
||||
problems.push(`item "${item.id}" has an option with no "k" (its key, like "A")`);
|
||||
item.options.forEach((o, i) => {
|
||||
if (!isPlainObject(o) || typeof o.k !== "string" || !o.k.trim()) {
|
||||
problems.push(
|
||||
rule(at, "options", `option ${i + 1} has no usable "k" (its key, a string like "A"). Give every option a "k", or none to have them lettered A, B, C`, OPTIONS_RIGHT),
|
||||
);
|
||||
} else if (typeof o.text !== "string" || !o.text.trim()) {
|
||||
problems.push(
|
||||
`item "${item.id}" option "${o.k}" needs "text" (the label) and optionally "detail". Options use "text"/"detail", not "label"/"desc".`
|
||||
rule(at, "options", `option "${o.k}" needs "text" (the label) and optionally "detail". Options use "text"/"detail", not "label"/"desc"`, OPTION_RIGHT),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if (item.verdicts != null) {
|
||||
if (!Array.isArray(item.verdicts) || !item.verdicts.length) {
|
||||
problems.push(`item "${item.id}" "verdicts" must be a non-empty array of { id, label }`);
|
||||
problems.push(rule(at, "verdicts", "must be a non-empty array of { id, label }", VERDICTS_RIGHT));
|
||||
} else {
|
||||
for (const v of item.verdicts) {
|
||||
if (!v || typeof v.id !== "string" || !v.id.trim()) {
|
||||
problems.push(`item "${item.id}" has a verdict with no "id"`);
|
||||
problems.push(rule(at, "verdicts", 'a verdict has no "id"', VERDICTS_RIGHT));
|
||||
} else if (typeof v.label !== "string" || !v.label.trim()) {
|
||||
problems.push(
|
||||
`item "${item.id}" verdict "${v.id}" needs a "label" (the button text). Verdicts use "label", not "text".`
|
||||
);
|
||||
problems.push(rule(at, "verdicts", `verdict "${v.id}" needs a "label" (the button text). Verdicts use "label", not "text"`, VERDICTS_RIGHT));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (item.templates != null && (item.kind !== "text" || item.templates !== "idea")) {
|
||||
problems.push(`item "${item.id}" has "templates": only a text item can carry it, and its only value is "idea".`);
|
||||
problems.push(rule(at, "templates", 'only a text item can carry it, and its only value is "idea"', { kind: "text", templates: "idea" }));
|
||||
}
|
||||
// The box the page fills from a Notebook tab picked at Start.
|
||||
if (item.fill != null && (item.kind !== "text" || item.fill !== "note")) {
|
||||
problems.push(`item "${item.id}" has "fill": only a text item can carry it, and its only value is "note".`);
|
||||
problems.push(rule(at, "fill", 'only a text item can carry it, and its only value is "note"', { kind: "text", fill: "note" }));
|
||||
}
|
||||
// The page compiles it as the person types, and a pattern that does not
|
||||
// compile throws there, on every keystroke, with nothing on screen to say why.
|
||||
if (item.pattern != null) {
|
||||
const patternRight = { pattern: "^[a-z0-9-]+$", patternHint: "kebab-case" };
|
||||
if (typeof item.pattern !== "string") {
|
||||
problems.push(`item "${item.id}" "pattern" must be a string holding a JavaScript regular expression`);
|
||||
problems.push(rule(at, "pattern", "must be a string holding a JavaScript regular expression", patternRight));
|
||||
} else {
|
||||
try {
|
||||
new RegExp(item.pattern);
|
||||
} catch (e) {
|
||||
problems.push(`item "${item.id}" "pattern" is not a valid JavaScript regular expression: ${e.message}`);
|
||||
problems.push(rule(at, "pattern", `is not a valid JavaScript regular expression: ${e.message}`, patternRight));
|
||||
}
|
||||
}
|
||||
}
|
||||
const recs = (item.options || []).filter((o) => o.recommended);
|
||||
if (recs.length > 1) problems.push(`item "${item.id}" marks ${recs.length} options recommended; at most one`);
|
||||
const recs = (item.options || []).filter((o) => o && o.recommended);
|
||||
if (recs.length > 1) {
|
||||
problems.push(rule(at, "options", `${recs.length} options are marked recommended; at most one`, [{ text: "A", recommended: true }, { text: "B" }]));
|
||||
}
|
||||
// Which cards the Implementation Loop answers itself; the page draws them.
|
||||
if (item.handledBy != null) {
|
||||
if (item.handledBy !== "loop") problems.push(rule(at, "handledBy", 'can only be "loop"', { handledBy: "loop" }));
|
||||
else if (!state.loop?.driving) problems.push(rule(at, "handledBy", "is only valid in a loop session", { handledBy: null }));
|
||||
}
|
||||
}
|
||||
|
||||
// The loop's two reports: the skill's outcome and the app's ending.
|
||||
if (state.loopOutcome !== undefined) problems.push(...loopOutcomeProblems(state.loopOutcome));
|
||||
if (state.loopEnd !== undefined) problems.push(...loopEndProblems(state.loopEnd, state));
|
||||
|
||||
// A note on a card is unanswered the moment no agent words follow it in its
|
||||
// thread. Once that is true, no patch may move past it except one that
|
||||
// finally replies: deleting the item drops it from state.items before this
|
||||
@@ -679,7 +834,12 @@ export function validate(state) {
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const last = thread[thread.length - 1];
|
||||
if (isPlainObject(last) && last.who === "user") {
|
||||
problems.push(`item "${item.id}" has an unanswered note from the person; reply in its thread before this patch`);
|
||||
problems.push(
|
||||
rule(`item "${item.id}"`, "thread", "has an unanswered note from the person; reply in its thread in this patch", {
|
||||
id: item.id,
|
||||
thread: [{ who: "agent", text: "..." }],
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -688,7 +848,9 @@ export function validate(state) {
|
||||
// yet counts as open (and keeps Stop live for a question nobody can see).
|
||||
if (state.workflow === "dashboard" && state.items.some((i) => isOpen(i))) {
|
||||
problems.push(
|
||||
'The dashboard draws no question cards: post its "menu" (and "agent"), and launch the skill a question belongs to.'
|
||||
rule("", "items", "the dashboard draws no question cards. Post its menu (and agent), and launch the skill a question belongs to", {
|
||||
menu: { note: "...", recommend: "plan2code-init" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -697,9 +859,13 @@ export function validate(state) {
|
||||
const openRequired = state.items.filter((i) => i.required !== false && i.kind !== "notice" && isOpen(i));
|
||||
if (openRequired.length > MAX_OPEN_REQUIRED) {
|
||||
problems.push(
|
||||
`${openRequired.length} questions are open at once. The cap is ${MAX_OPEN_REQUIRED} ` +
|
||||
`(the ceiling is the person's attention, not the screen's). ` +
|
||||
`Send the rest after these are answered, or mark some "required": false.`
|
||||
rule(
|
||||
"",
|
||||
"items",
|
||||
`${openRequired.length} questions are open at once (${openRequired.map((i) => i.id).join(", ")}). The cap is ${MAX_OPEN_REQUIRED} ` +
|
||||
`(the ceiling is the person's attention, not the screen's). Send the rest after these are answered, or mark some "required": false`,
|
||||
{ id: openRequired[openRequired.length - 1].id, required: false },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -709,55 +875,68 @@ export function validate(state) {
|
||||
// and the page points at the dashboard instead of a next step.
|
||||
const fin = state.finish;
|
||||
if (fin != null) {
|
||||
// The page would warn about losing work after the session ended (FR-13).
|
||||
if (typeof state.stopWarning === "string" && state.stopWarning.trim()) {
|
||||
problems.push(
|
||||
rule("", "finish", `"stopWarning" is still set ("${state.stopWarning}"), so the page would warn about losing work after the session ended. Clear it in the same patch`, {
|
||||
stopWarning: "",
|
||||
finish: { headline: "Paused: <what is saved>", command: "/<the skill to resume>" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (typeof fin !== "object" || Array.isArray(fin)) {
|
||||
problems.push('"finish" must be an object');
|
||||
problems.push(rule("", "finish", "must be an object", FINISH_RIGHT));
|
||||
} else {
|
||||
if (typeof fin.headline !== "string" || !fin.headline.trim()) {
|
||||
problems.push('"finish" needs a plain-English "headline" saying what just happened');
|
||||
problems.push(rule("", "finish.headline", "needs a plain-English headline saying what just happened", { finish: { headline: "Phase 3 is done" } }));
|
||||
}
|
||||
if (fin.command != null && (typeof fin.command !== "string" || !fin.command.trim())) {
|
||||
problems.push('"finish.command" must be a non-empty string, or left out when there is nothing to run');
|
||||
problems.push(rule("", "finish.command", "must be a non-empty string, or left out when there is nothing to run", { finish: { command: "/plan2code-1-plan" } }));
|
||||
} else if (fin.command != null && (fin.command.includes("<") || fin.command.includes(">"))) {
|
||||
// A rendered command is copied and run verbatim. A leftover
|
||||
// placeholder reaches someone who has no way to know what fills it.
|
||||
problems.push(`"finish.command" still has a placeholder in it ("${fin.command}"). Fill it in.`);
|
||||
problems.push(
|
||||
rule("", "finish.command", `still has a placeholder in it ("${fin.command}"). Fill it in`, {
|
||||
finish: { command: "/plan2code-3-implement specs/lunch-vote/overview.md" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (fin.console != null && typeof fin.console !== "boolean") {
|
||||
problems.push('"finish.console" must be true or false (or left out, to follow the command)');
|
||||
problems.push(rule("", "finish.console", "must be true or false (or left out, to follow the command)", { finish: { console: true } }));
|
||||
}
|
||||
if (fin.dashboard != null && typeof fin.dashboard !== "boolean") {
|
||||
problems.push('"finish.dashboard" must be true or false (or left out: no dashboard button)');
|
||||
problems.push(rule("", "finish.dashboard", "must be true or false (or left out: no dashboard button)", { finish: { dashboard: true } }));
|
||||
}
|
||||
if (fin.commit != null && typeof fin.commit !== "boolean") {
|
||||
problems.push('"finish.commit" must be true or false (or left out: no commit button)');
|
||||
problems.push(rule("", "finish.commit", "must be true or false (or left out: no commit button)", { finish: { commit: true } }));
|
||||
}
|
||||
// (The pause test is the page's finishPaused() in public/answers.js: keep them in step.)
|
||||
// Update CHANGELOG first: only the builds that end on a commit and have
|
||||
// no sign-off to put it on. An implementation phase never offers it. A
|
||||
// pause ignores it.
|
||||
if (fin.changelog != null && typeof fin.changelog !== "boolean") {
|
||||
problems.push('"finish.changelog" must be true or false (or left out: no changelog button)');
|
||||
problems.push(rule("", "finish.changelog", "must be true or false (or left out: no changelog button)", { finish: { changelog: true } }));
|
||||
} else if (fin.changelog === true && !/^\s*paused\b/i.test(String(fin.headline || "")) && !["quick-task", "finalize"].includes(state.workflow)) {
|
||||
problems.push('"finish.changelog" is only for a finished quick-task or finalize');
|
||||
problems.push(rule("", "finish.changelog", "is only for a finished quick-task or finalize", { finish: { changelog: null } }));
|
||||
}
|
||||
// The review offer on a finished build: true, or an object carrying the
|
||||
// button's heading. The heading is read by the person, so it faces the
|
||||
// same vocabulary check as a title.
|
||||
if (fin.review != null && typeof fin.review !== "boolean") {
|
||||
if (typeof fin.review !== "object" || Array.isArray(fin.review)) {
|
||||
problems.push('"finish.review" must be true, false, or { "label": "..." }');
|
||||
problems.push(rule("", "finish.review", 'must be true, false, or { "label": "..." }', { finish: { review: { label: "Review the code" } } }));
|
||||
} else if (fin.review.label != null) {
|
||||
if (typeof fin.review.label !== "string") {
|
||||
problems.push('"finish.review.label" must be a string');
|
||||
problems.push(rule("", "finish.review.label", "must be a string", { finish: { review: { label: "Review the code" } } }));
|
||||
} else {
|
||||
const hit = JARGON.find((re) => re.test(fin.review.label));
|
||||
if (hit) problems.push(`"finish.review.label" contains internal vocabulary (${hit.source})`);
|
||||
if (hit) problems.push(rule("", "finish.review.label", `contains internal vocabulary (${hit.source})`, { finish: { review: { label: "Review the code" } } }));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const re of JARGON) {
|
||||
if (typeof fin.headline === "string" && re.test(fin.headline)) {
|
||||
problems.push(`"finish.headline" contains internal vocabulary (${re.source})`);
|
||||
problems.push(rule("", "finish.headline", `contains internal vocabulary (${re.source})`, { finish: { headline: "Phase 3 is done" } }));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -769,15 +948,15 @@ export function validate(state) {
|
||||
// huge number would hide a session that really has died.
|
||||
const quiet = state.agent && state.agent.quietMinutes;
|
||||
if (quiet != null && (typeof quiet !== "number" || !(quiet > 0) || quiet > 60)) {
|
||||
problems.push('"agent.quietMinutes" must be a number of minutes between 1 and 60 (or null to clear it)');
|
||||
problems.push(rule("", "agent.quietMinutes", "must be a number of minutes between 1 and 60 (or null to clear it)", { agent: { quietMinutes: 15 } }));
|
||||
}
|
||||
// The page reads exactly two: anything else would leave it guessing whose
|
||||
// turn it is.
|
||||
if (state.agent && state.agent.status != null && !["working", "waiting"].includes(state.agent.status)) {
|
||||
problems.push(`"agent.status" must be "working" or "waiting" (not "${state.agent.status}")`);
|
||||
problems.push(rule("", "agent.status", `must be "working" or "waiting" (not "${state.agent.status}")`, { agent: { status: "working" } }));
|
||||
}
|
||||
if (state.agent && state.agent.activity != null && typeof state.agent.activity !== "string") {
|
||||
problems.push('"agent.activity" must be a short sentence saying what you are doing');
|
||||
problems.push(rule("", "agent.activity", "must be a short sentence saying what you are doing", { agent: { activity: "Reading the plan" } }));
|
||||
}
|
||||
|
||||
// Open gates only: an approval already given (last phase's sign-off) is a
|
||||
@@ -785,9 +964,12 @@ export function validate(state) {
|
||||
const gates = state.items.filter((i) => i.gate && i.gate.authoritative && isOpen(i));
|
||||
if (gates.length > 1) {
|
||||
problems.push(
|
||||
`${gates.length} authoritative approval gates are open (${gates
|
||||
.map((g) => g.id)
|
||||
.join(", ")}). Only one workflow may own sign-off at a time.`
|
||||
rule(
|
||||
"",
|
||||
"items",
|
||||
`${gates.length} authoritative approval gates are open (${gates.map((g) => g.id).join(", ")}). Only one workflow may own sign-off at a time`,
|
||||
{ id: gates[gates.length - 1].id, gate: null },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -797,35 +979,43 @@ export function validate(state) {
|
||||
for (const b of (isPlainObject(d) && Array.isArray(d.blocks) ? d.blocks : [])) {
|
||||
if (!isPlainObject(b) || typeof b.image !== "string" || typeof b.alt !== "string") continue;
|
||||
const hit = JARGON.find((re) => re.test(b.alt));
|
||||
if (hit) problems.push(`doc "${d.id}" image "${b.id}" alt text contains internal vocabulary (${hit.source})`);
|
||||
if (hit) {
|
||||
problems.push(
|
||||
rule(`doc "${d.id}" block "${b.id}"`, "alt", `contains internal vocabulary (${hit.source})`, { id: b.id, image: b.image, alt: "The finished screen" }),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Scan what the AGENT wrote, never what the person typed. `submitted` is the
|
||||
// server's record of an answer someone pressed Send on; if their own words
|
||||
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
||||
// would be rejected and the session would wedge with no way out.
|
||||
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
|
||||
...rest,
|
||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
||||
}));
|
||||
// would be rejected and the session would wedge with no way out. Scanned one
|
||||
// string at a time so a refusal names the item and field it found the word in.
|
||||
const scan = (value, prefix) =>
|
||||
walkStrings(value, "", (str, where) => problems.push(...proseProblems(str, [prefix, where].filter(Boolean).join(" "))));
|
||||
for (const { submitted, sentNote, thread, ...rest } of state.items) {
|
||||
const item = {
|
||||
...rest,
|
||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
||||
};
|
||||
scan(item, `item "${item.id}"`);
|
||||
}
|
||||
// A doc block read from a file (`file`) is the file's own words, already on
|
||||
// disk: the agent cannot reword it, and refusing it would wedge every post
|
||||
// that refreshes it. Only what the agent typed is scanned.
|
||||
const typedDocs = (state.docs || []).map((d) =>
|
||||
isPlainObject(d) && Array.isArray(d.blocks) ? { ...d, blocks: d.blocks.filter((b) => !(isPlainObject(b) && typeof b.file === "string")) } : d
|
||||
);
|
||||
const prose =
|
||||
JSON.stringify(authored) +
|
||||
JSON.stringify(typedDocs) +
|
||||
JSON.stringify(state.finish || {}) +
|
||||
JSON.stringify(state.menu || {});
|
||||
problems.push(...proseProblems(prose));
|
||||
for (const d of state.docs || []) {
|
||||
if (!isPlainObject(d)) continue;
|
||||
const typed = Array.isArray(d.blocks) ? { ...d, blocks: d.blocks.filter((b) => !(isPlainObject(b) && typeof b.file === "string")) } : d;
|
||||
scan(typed, `doc "${d.id}"`);
|
||||
}
|
||||
scan(state.finish || {}, "finish");
|
||||
scan(state.menu || {}, "menu");
|
||||
|
||||
// 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));
|
||||
problems.push(...checkHelpers(state.helpers).map((p) => likeThis(p, HELPER_RIGHT)));
|
||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
||||
if (!isPlainObject(helper)) continue;
|
||||
for (const field of ["title", "ask", "result"]) {
|
||||
@@ -839,9 +1029,13 @@ export function validate(state) {
|
||||
// A finish ends the session, and a helper still shown as running would sit
|
||||
// on the Subagents tab, spinning, after everything is over.
|
||||
if (state.finish != null && Array.isArray(state.helpers)) {
|
||||
const running = state.helpers.filter((h) => isPlainObject(h) && h.state === "running").map((h) => `"${h.id}"`);
|
||||
const running = state.helpers.filter((h) => isPlainObject(h) && h.state === "running").map((h) => h.id);
|
||||
if (running.length) {
|
||||
problems.push(`"finish" while helper ${running.join(", ")} still shows as running: post each one as done or failed first, or in the same patch`);
|
||||
problems.push(
|
||||
rule("", "finish", `helper ${running.map((id) => `"${id}"`).join(", ")} still shows as running: post each one as done or failed first, or in the same patch`, {
|
||||
helpers: [{ id: running[0], state: "done" }],
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -852,6 +1046,182 @@ export function isOpen(item) {
|
||||
return item.status === "open" || item.status === "reopened";
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ the loop's reports */
|
||||
|
||||
const LOOP_LEVELS = ["critical", "warning", "suggestion"];
|
||||
const LOOP_REASONS = ["tests", "findings", "blocked", "conflict", "other"];
|
||||
const LOOP_CAN = ["resume", "fix", "finalize"];
|
||||
const TASK_ID = /^\d+\.\d+$/;
|
||||
|
||||
// A one-line path that stays inside the project: not absolute, no `..` step.
|
||||
const relativePath = (f) =>
|
||||
typeof f === "string" && f.length > 0 && !/[\r\n]/.test(f) && !path.isAbsolute(f) && !/^[A-Za-z]:/.test(f) && !f.replaceAll("\\", "/").split("/").includes("..");
|
||||
const isNonNegInt = (n) => Number.isInteger(n) && n >= 0;
|
||||
const isPosInt = (n) => Number.isInteger(n) && n > 0;
|
||||
// One line of 1..max characters.
|
||||
const oneLine = (s, max) => typeof s === "string" && s.length >= 1 && s.length <= max && !/[\r\n]/.test(s);
|
||||
|
||||
/**
|
||||
* Problems with a `loopOutcome` (what the skill reports after building a phase
|
||||
* under the loop), as sentences naming the field; an empty array when it is
|
||||
* good. Rules are the overview's API section; house rules 4 and 5 apply to
|
||||
* every string.
|
||||
*/
|
||||
export function loopOutcomeProblems(o) {
|
||||
const p = [];
|
||||
const bad = (field, rule) => p.push(`loopOutcome.${field} ${rule}`);
|
||||
if (!isPlainObject(o)) return ["loopOutcome must be an object"];
|
||||
const prose = (field, s) => {
|
||||
if (typeof s === "string") p.push(...proseProblems(s, `loopOutcome.${field}`));
|
||||
};
|
||||
if (!isPosInt(o.phase)) bad("phase", "must be a positive integer");
|
||||
if (o.result !== "passed" && o.result !== "failed") bad("result", 'must be "passed" or "failed"');
|
||||
if (o.result === "passed") {
|
||||
if (o.reason !== null) bad("reason", "must be null when the phase passed");
|
||||
} else if (o.result === "failed" && !LOOP_REASONS.includes(o.reason)) {
|
||||
bad("reason", `must be one of ${LOOP_REASONS.join(", ")} when the phase failed`);
|
||||
}
|
||||
if (!oneLine(o.summary, 200)) bad("summary", "must be one line of 1 to 200 characters");
|
||||
else prose("summary", o.summary);
|
||||
|
||||
if (!isPlainObject(o.tests)) bad("tests", "must be an object { ran, passed, summary }");
|
||||
else {
|
||||
if (typeof o.tests.ran !== "boolean") bad("tests.ran", "must be true or false");
|
||||
if (typeof o.tests.passed !== "boolean") bad("tests.passed", "must be true or false");
|
||||
if (typeof o.tests.summary !== "string" || /[\r\n]/.test(o.tests.summary)) bad("tests.summary", "must be a one-line string");
|
||||
else prose("tests.summary", o.tests.summary);
|
||||
}
|
||||
|
||||
if (!isPlainObject(o.review)) bad("review", "must be an object { ran, recheck, left, unfixed }");
|
||||
else {
|
||||
const r = o.review;
|
||||
if (typeof r.ran !== "boolean") bad("review.ran", "must be true or false");
|
||||
if (typeof r.recheck !== "boolean") bad("review.recheck", "must be true or false");
|
||||
if (!isPlainObject(r.left)) bad("review.left", "must be an object { critical, warning, suggestion }");
|
||||
else for (const level of LOOP_LEVELS) if (!isNonNegInt(r.left[level])) bad(`review.left.${level}`, "must be a non-negative integer");
|
||||
if (r.triage !== undefined) {
|
||||
const t = r.triage;
|
||||
if (!isPlainObject(t)) bad("review.triage", "must be an object { ran, skipped } when present");
|
||||
else {
|
||||
if (typeof t.ran !== "boolean") bad("review.triage.ran", "must be true or false");
|
||||
if (!Array.isArray(t.skipped)) bad("review.triage.skipped", "must be an array");
|
||||
else {
|
||||
if (t.skipped.length > 50) bad("review.triage.skipped", "can hold at most 50 entries");
|
||||
t.skipped.forEach((u, i) => {
|
||||
const at = `review.triage.skipped[${i}]`;
|
||||
if (!isPlainObject(u)) return bad(at, "must be an object { level, title, file, reason }");
|
||||
if (!LOOP_LEVELS.includes(u.level)) bad(`${at}.level`, `must be one of ${LOOP_LEVELS.join(", ")}`);
|
||||
if (typeof u.title !== "string" || !u.title.trim() || /[\r\n]/.test(u.title)) bad(`${at}.title`, "must be a non-empty one-line string");
|
||||
else prose(`${at}.title`, u.title);
|
||||
if (typeof u.file !== "string" || /[\r\n]/.test(u.file)) bad(`${at}.file`, "must be a one-line string");
|
||||
else prose(`${at}.file`, u.file);
|
||||
if (!oneLine(u.reason, 200)) bad(`${at}.reason`, "must be one line of 1 to 200 characters");
|
||||
else prose(`${at}.reason`, u.reason);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(r.fixed)) bad("review.fixed", "must be an array (empty when nothing was fixed)");
|
||||
else {
|
||||
if (r.fixed.length > 50) bad("review.fixed", "can hold at most 50 entries");
|
||||
r.fixed.forEach((u, i) => {
|
||||
if (!isPlainObject(u)) return bad(`review.fixed[${i}]`, "must be an object { level, title, file? }");
|
||||
if (!LOOP_LEVELS.includes(u.level)) bad(`review.fixed[${i}].level`, `must be one of ${LOOP_LEVELS.join(", ")}`);
|
||||
if (typeof u.title !== "string" || !u.title.trim() || /[\r\n]/.test(u.title)) bad(`review.fixed[${i}].title`, "must be a non-empty one-line string");
|
||||
else prose(`review.fixed[${i}].title`, u.title);
|
||||
if (u.file !== undefined && (typeof u.file !== "string" || /[\r\n]/.test(u.file))) bad(`review.fixed[${i}].file`, "must be a one-line string when present");
|
||||
else prose(`review.fixed[${i}].file`, u.file);
|
||||
});
|
||||
}
|
||||
if (!Array.isArray(r.unfixed)) bad("review.unfixed", "must be an array");
|
||||
else {
|
||||
if (r.unfixed.length > 50) bad("review.unfixed", "can hold at most 50 entries");
|
||||
r.unfixed.forEach((u, i) => {
|
||||
if (!isPlainObject(u)) return bad(`review.unfixed[${i}]`, "must be an object { level, title, file? }");
|
||||
if (!LOOP_LEVELS.includes(u.level)) bad(`review.unfixed[${i}].level`, `must be one of ${LOOP_LEVELS.join(", ")}`);
|
||||
if (typeof u.title !== "string" || !u.title.trim()) bad(`review.unfixed[${i}].title`, "must be a non-empty string");
|
||||
else prose(`review.unfixed[${i}].title`, u.title);
|
||||
if (u.file !== undefined && typeof u.file !== "string") bad(`review.unfixed[${i}].file`, "must be a string when present");
|
||||
else prose(`review.unfixed[${i}].file`, u.file);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!isPlainObject(o.tasks)) bad("tasks", "must be an object { blocked, assumed }");
|
||||
else {
|
||||
for (const key of ["blocked", "assumed"]) {
|
||||
const list = o.tasks[key];
|
||||
if (!Array.isArray(list) || !list.every((t) => typeof t === "string" && TASK_ID.test(t))) {
|
||||
bad(`tasks.${key}`, 'must be an array of task ids like "2.4"');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(o.conflicts) || !o.conflicts.every((c) => typeof c === "string" && !/[\r\n]/.test(c))) {
|
||||
bad("conflicts", "must be an array of one-line strings");
|
||||
} else o.conflicts.forEach((c, i) => prose(`conflicts[${i}]`, c));
|
||||
|
||||
if (!Array.isArray(o.decisions)) bad("decisions", "must be an array of one-line strings (empty when there were none)");
|
||||
else {
|
||||
if (o.decisions.length > 50) bad("decisions", "can hold at most 50 entries");
|
||||
o.decisions.forEach((d, i) => {
|
||||
if (!oneLine(d, 200)) bad(`decisions[${i}]`, "must be one line of 1 to 200 characters");
|
||||
else prose(`decisions[${i}]`, d);
|
||||
});
|
||||
}
|
||||
|
||||
if (!oneLine(o.subject, 100)) bad("subject", "must be one line of 1 to 100 characters");
|
||||
else prose("subject", o.subject);
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Problems with a `loopEnd` (the app's word on how the loop ended), given the
|
||||
* merged state so `evidence` can be checked against the docs on the page.
|
||||
*/
|
||||
export function loopEndProblems(e, state) {
|
||||
const p = [];
|
||||
const bad = (field, rule) => p.push(`loopEnd.${field} ${rule}`);
|
||||
if (!isPlainObject(e)) return ["loopEnd must be an object"];
|
||||
const prose = (field, s) => {
|
||||
if (typeof s === "string") p.push(...proseProblems(s, `loopEnd.${field}`));
|
||||
};
|
||||
if (e.kind !== "stopped" && e.kind !== "finished") bad("kind", 'must be "stopped" or "finished"');
|
||||
if (!oneLine(e.line, 200)) bad("line", "must be one line of 1 to 200 characters");
|
||||
else prose("line", e.line);
|
||||
if (e.evidence !== undefined) {
|
||||
if (typeof e.evidence !== "string" || !(state?.docs || []).some((d) => d && d.id === e.evidence)) {
|
||||
bad("evidence", "must be the id of a doc on the page");
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(e.phases)) bad("phases", "must be an array");
|
||||
else {
|
||||
e.phases.forEach((ph, i) => {
|
||||
if (!isPlainObject(ph)) return bad(`phases[${i}]`, "must be an object { n, name, commit, unfixed, retries }");
|
||||
if (!isPosInt(ph.n)) bad(`phases[${i}].n`, "must be a positive integer");
|
||||
if (typeof ph.name !== "string" || /[\r\n]/.test(ph.name)) bad(`phases[${i}].name`, "must be a one-line string");
|
||||
else prose(`phases[${i}].name`, ph.name);
|
||||
if (ph.commit !== null && !(typeof ph.commit === "string" && /^[0-9a-f]{4,40}$/i.test(ph.commit))) bad(`phases[${i}].commit`, "must be a short hex hash or null");
|
||||
if (!isNonNegInt(ph.unfixed)) bad(`phases[${i}].unfixed`, "must be a non-negative integer");
|
||||
if (!isNonNegInt(ph.retries)) bad(`phases[${i}].retries`, "must be a non-negative integer");
|
||||
for (const key of ["fixed", "skipped", "left", "assumed", "decisions"]) {
|
||||
if (ph[key] !== undefined && !isNonNegInt(ph[key])) bad(`phases[${i}].${key}`, "must be a non-negative integer when present");
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!Array.isArray(e.uncommitted) || !e.uncommitted.every(relativePath)) {
|
||||
bad("uncommitted", "must be an array of relative paths (no leading slash or drive, no .. step, one line each)");
|
||||
} else if (e.uncommitted.length > 200) bad("uncommitted", "can hold at most 200 paths");
|
||||
else e.uncommitted.forEach((f, i) => prose(`uncommitted[${i}]`, f));
|
||||
if (!Array.isArray(e.can) || !e.can.every((c) => LOOP_CAN.includes(c))) {
|
||||
bad("can", `must be an array with entries from ${LOOP_CAN.join(", ")}`);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
// Loop mode adds three optional keys that a blank state does not hold (absent,
|
||||
// not null): `loop: { driving: true }` (set by `open --loop`), `loopOutcome`
|
||||
// (the skill's report) and `loopEnd` (the app's).
|
||||
export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
return {
|
||||
schema: SCHEMA,
|
||||
@@ -877,10 +1247,17 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
* starts from a blank page: the last skill's questions, sections, docs,
|
||||
* helpers, headline and ending are its record on disk, not the next skill's
|
||||
* opening.
|
||||
* Only the session's identity carries across. `workspace.json`,
|
||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||
* and the meter outlive every hop.
|
||||
* Only the session's identity and the Ask tab's conversation carry across:
|
||||
* the agent's chat replies stay beside the messages in `chat.ndjson`, which
|
||||
* a hop never touches, or every question asked before it would read as
|
||||
* unanswered. `workspace.json`, `ledger.ndjson` and the cursors live beside
|
||||
* `state.json`, so the workspace and the meter outlive every hop.
|
||||
*/
|
||||
export function switchWorkflow(state, { workflow, title, specDir }) {
|
||||
return { ...blankState({ sid: state.sid, project: state.project, workflow, title, specDir }), created: state.created };
|
||||
const next = { ...blankState({ sid: state.sid, project: state.project, workflow, title, specDir }), created: state.created };
|
||||
// A blank state holds no `loop`, `loopOutcome` or `loopEnd`, so a hop never
|
||||
// carries them over; `open --loop` stamps `loop` again after the switch.
|
||||
for (const key of ["loop", "loopOutcome", "loopEnd"]) delete next[key];
|
||||
if (state.chat) next.chat = state.chat;
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// Plan2Code Web Console - pointers: which topic file the console names, and when.
|
||||
//
|
||||
// The card (console.md) leaves a topic out and the console's own output names
|
||||
// its file at the moment that topic is due: `read: [<absolute path>]`, once per
|
||||
// session per topic, and again after a resume. What was printed lives in the
|
||||
// session folder (pointers.json), never in state.json, which rides every frame
|
||||
// to the page, and never on the page's stream.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { HERE, readJson, writeJsonAtomic } from "./files.mjs";
|
||||
|
||||
const POINTERS_FILE = "pointers.json";
|
||||
|
||||
// Topic -> the file that explains it, beside console.mjs.
|
||||
export const POINTER_FILES = {
|
||||
finish: "console-finish.md",
|
||||
stop: "console-stop.md",
|
||||
docs: "console-docs.md",
|
||||
chat: "console-chat.md",
|
||||
workspace: "console-workspace.md",
|
||||
subagents: "console-subagents.md",
|
||||
review: "building-review.md",
|
||||
};
|
||||
|
||||
function printedTopics(dir) {
|
||||
const saved = readJson(path.join(dir, POINTERS_FILE), {});
|
||||
return saved && Array.isArray(saved.printed) ? saved.printed.filter((t) => typeof t === "string") : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* The absolute paths of the topic files in `topics` not yet printed in this
|
||||
* session, in the order given and each once. An unreadable or missing memory
|
||||
* reads as nothing printed yet.
|
||||
*/
|
||||
export function duePointers(dir, topics) {
|
||||
const done = new Set(printedTopics(dir));
|
||||
const out = [];
|
||||
for (const topic of new Set(topics || [])) {
|
||||
if (Object.hasOwn(POINTER_FILES, topic) && !done.has(topic)) out.push(path.join(HERE, POINTER_FILES[topic]));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Record that these topics were printed. Called after the print, the order
|
||||
* advanceCursor() uses: a kill in between repeats a pointer, never loses one.
|
||||
* Never fatal.
|
||||
*/
|
||||
export function rememberPointers(dir, topics) {
|
||||
const known = (topics || []).filter((t) => Object.hasOwn(POINTER_FILES, t));
|
||||
if (!known.length) return;
|
||||
try {
|
||||
const printed = [...new Set([...printedTopics(dir), ...known])];
|
||||
writeJsonAtomic(path.join(dir, POINTERS_FILE), { printed });
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/** Forget what was printed (a resume starts the reading over). */
|
||||
export function resetPointers(dir) {
|
||||
try {
|
||||
fs.rmSync(path.join(dir, POINTERS_FILE), { force: true });
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The verdict a review card was answered with, wherever the action keeps it.
|
||||
function verdictOf(action) {
|
||||
if (typeof action.verdict === "string" && action.verdict) return action.verdict;
|
||||
const answer = action.answer;
|
||||
return answer && typeof answer === "object" && typeof answer.verdict === "string" && answer.verdict ? answer.verdict : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The topics a collected send makes due. Pure: no I/O.
|
||||
*
|
||||
* `result` is the send (result.json; an empty object for a chat-only pickup),
|
||||
* `state` the session state as read before the page is set back to working,
|
||||
* `changes` the standing-instruction flags from owedFlags(), and `chat` the
|
||||
* Quick question entries delivered with it.
|
||||
*/
|
||||
export function pointersForSend(result, state, changes, chat = []) {
|
||||
const topics = [];
|
||||
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
|
||||
const items = (state && Array.isArray(state.items) && state.items) || [];
|
||||
for (const a of actions) {
|
||||
if (!a || typeof a !== "object") continue;
|
||||
if (a.i === "__commit") topics.push("finish");
|
||||
else if (a.i === "__dashboard") topics.push(state && state.finish ? "finish" : "stop");
|
||||
else if (a.i === "__stop") topics.push("stop");
|
||||
else if (a.i === "__review") topics.push("review");
|
||||
else if (a.type === "answer" && typeof a.i === "string" && !a.i.startsWith("__")) {
|
||||
const item = items.find((x) => x && x.id === a.i);
|
||||
if (item && item.kind === "review" && verdictOf(a)) topics.push("review");
|
||||
}
|
||||
}
|
||||
if ((chat || []).some((e) => e && e.kind === "message")) topics.push("chat");
|
||||
if (changes && changes.workspaceChanged) topics.push("workspace");
|
||||
if (changes && changes.subagentsChanged) topics.push("subagents");
|
||||
return [...new Set(topics)];
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
// No DOM, no `local`, no fetch. If a function in here needs any of those, it
|
||||
// belongs in app.js instead.
|
||||
|
||||
import { FIXED_REASON, SKILLS, labelFor, skillByName, skillFor } from "./skills.js";
|
||||
import { FIXED_REASON, FLOW_SKILLS, SKILLS, labelFor, skillByName, skillFor } from "./skills.js";
|
||||
import { SPEC_STATES, stateFor } from "./spec-states.js";
|
||||
|
||||
/* ----------------------------------------------------- the sent answer */
|
||||
@@ -257,7 +257,7 @@ export function suggestionFrom(item) {
|
||||
// The badge each workflow wears. Shared with the server, which writes it into
|
||||
// the page it serves so the first paint already names the session instead of
|
||||
// flashing a placeholder until the script arrives. Derived from skills.js.
|
||||
export const WORKFLOW_LABEL = Object.fromEntries(SKILLS.map((s) => [s.workflow, s.label]));
|
||||
export const WORKFLOW_LABEL = Object.fromEntries(FLOW_SKILLS.map((s) => [s.workflow, s.label]));
|
||||
|
||||
export function workflowLabel(workflow) {
|
||||
return labelFor(workflow) || workflow || "Session";
|
||||
@@ -267,7 +267,7 @@ export function workflowLabel(workflow) {
|
||||
// skill as `additionalReferences`). Any other next step has no browser page
|
||||
// to open, and asking for one would send the next session looking for
|
||||
// something that is not there. Derived from skills.js: every entry is one.
|
||||
export const CONSOLE_WORKFLOWS = SKILLS.map((s) => s.command);
|
||||
export const CONSOLE_WORKFLOWS = FLOW_SKILLS.map((s) => s.command);
|
||||
|
||||
// Rides on the end of the command as part of the skill's argument. Every
|
||||
// console skill takes it as the answer to "web console or terminal?" instead
|
||||
@@ -550,7 +550,7 @@ export const CATALOG_GROUPS = [
|
||||
// action so the launched skill knows which spec it was picked for. Derived from
|
||||
// skills.js: the entries with a card, in their order, each card's fields
|
||||
// beside the skill's name, command and workflow.
|
||||
export const SKILL_CATALOG = SKILLS.filter((s) => s.card).map((s) => ({
|
||||
export const SKILL_CATALOG = FLOW_SKILLS.filter((s) => s.card).map((s) => ({
|
||||
skill: s.skill,
|
||||
command: s.command,
|
||||
workflow: s.workflow,
|
||||
@@ -558,6 +558,15 @@ export const SKILL_CATALOG = SKILLS.filter((s) => s.card).map((s) => ({
|
||||
...s.card,
|
||||
}));
|
||||
|
||||
// The desktop app's Implementation Loop card: not a skill, so not in
|
||||
// SKILL_CATALOG. The dashboard draws it after its group's other cards, and its
|
||||
// click opens the setup screen instead of launching anything.
|
||||
const LOOP_SKILL = SKILLS.find((s) => s.appOnly && s.card);
|
||||
export const LOOP_ENTRY = LOOP_SKILL
|
||||
? { skill: LOOP_SKILL.skill, command: "Desktop app only", workflow: null, appOnly: true, ...LOOP_SKILL.card }
|
||||
: null;
|
||||
export const OUTSIDE_APP_LINE = "Runs only in the Plan2Code desktop app.";
|
||||
|
||||
// A workflow by the name its dashboard card gives it ("Implement"), for the
|
||||
// screens that speak of it as a thing being started rather than as a badge.
|
||||
export function workflowTitle(workflow) {
|
||||
@@ -674,7 +683,7 @@ export function cardAvailability(entry, scan, sel, lookup = stateFor) {
|
||||
const hasAgents = Boolean(scan && scan.hasAgents);
|
||||
const state = sel && sel.state && sel.state !== "unrecognized" ? sel.state : null;
|
||||
const next = sel ? Boolean(state) && NEXT_FOR_STATE[state] === entry.skill : entry.skill === "plan2code-0-pathfinder";
|
||||
const rule = skillByName(entry.skill);
|
||||
const rule = skillByName(entry.skill) || (entry.appOnly ? LOOP_SKILL : null);
|
||||
if (!rule || !rule.states) return ON;
|
||||
|
||||
// The three cards whose rules read the scan rather than the spec.
|
||||
|
||||
@@ -36,6 +36,40 @@ export function onAppMessage(kind, handler) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hear the app's answers to the Implementation Loop's named requests:
|
||||
* `loop-facts` (what agent a loop would use), `loop-start-result`,
|
||||
* `loop-notify-test-result` and the three stop-screen results. `store` is the page object and `redraw` its
|
||||
* render; they are handed in so this file keeps importing nothing.
|
||||
*/
|
||||
export function wireLoopMessages(store, redraw) {
|
||||
onAppMessage("loop-facts", (data) => {
|
||||
store.loopFacts = data.facts && typeof data.facts === "object" ? data.facts : null;
|
||||
redraw();
|
||||
});
|
||||
onAppMessage("loop-start-result", (data) => {
|
||||
// Cancel in the app's confirm: nothing started, so the setup is as it was.
|
||||
if (data.ok === true && data.started === false) {
|
||||
store.loopStart = null;
|
||||
if (store.loopSetup) store.loopSetup.starting = false;
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
store.loopStart = { ok: data.ok === true, error: data.ok === true ? null : String(data.error || "The app did not start the loop.") };
|
||||
redraw();
|
||||
});
|
||||
onAppMessage("loop-notify-test-result", (data) => {
|
||||
store.loopNotifyTest = { waiting: false, ok: data.ok === true, sent: data.sent === true, error: data.ok === true ? null : String(data.error || "The app could not send the test.") };
|
||||
redraw();
|
||||
});
|
||||
for (const kind of ["loop-resume-result", "loop-fix-result", "loop-finalize-result"]) {
|
||||
onAppMessage(kind, (data) => {
|
||||
store.loopAction = { kind, ok: data.ok === true, error: data.ok === true ? null : String(data.error || "The app could not do that.") };
|
||||
redraw();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask the app for what its bar's New Session button does, confirm and all.
|
||||
* `command`, when there is one, goes on the clipboard first so it can be
|
||||
|
||||
@@ -22,7 +22,8 @@ import {
|
||||
adopt, banner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter,
|
||||
renderSidebar, renderWhere, save, startClock, startLooks, stagedPayload, syncWorkspaceScope,
|
||||
wakeHoldsChime, wireAsk, wireCards, wireChrome, wireCleanup, wireDashboard, wireDocs, wireEnding,
|
||||
wireActivities, wireHelp, wireLooks, wireNotepad, wireWorkspace,
|
||||
wireActivities, wireLoopSetup, wireHelp, launchSkill, openHelpOn, openLoopSetup, wireLooks, wireNotepad, wirePrefs, wireWorkspace,
|
||||
openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen,
|
||||
} from "./screens/core.js";
|
||||
import { sound } from "./sound.js";
|
||||
|
||||
@@ -34,7 +35,10 @@ import { sound } from "./sound.js";
|
||||
// last the session itself (its first state and the stream). The draft's save
|
||||
// and the few calls a screen makes into another are handed to state.js first.
|
||||
onSave(save);
|
||||
useHooks({ banner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope });
|
||||
useHooks({
|
||||
launchSkill, openHelpOn, openLoopSetup, banner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope,
|
||||
openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen,
|
||||
});
|
||||
|
||||
const boot = bootData();
|
||||
startLooks(boot);
|
||||
@@ -46,11 +50,13 @@ wireHelp();
|
||||
wireDashboard();
|
||||
wireEnding();
|
||||
wireLooks();
|
||||
wirePrefs();
|
||||
wireCleanup();
|
||||
wireDocs();
|
||||
wireAsk();
|
||||
wireNotepad();
|
||||
wireActivities();
|
||||
wireLoopSetup();
|
||||
wireChrome();
|
||||
startClock();
|
||||
|
||||
|
||||
@@ -210,6 +210,24 @@ export function shouldChime(prevDot, nextDot) {
|
||||
// The page's own "has drifted away" threshold for an agent that is waiting.
|
||||
const ADRIFT_MS = 3 * 60 * 1000;
|
||||
|
||||
// How long an agent answering an Ask message may go without checking in. It
|
||||
// is out of `wait` while it answers, and an approved edit can run for minutes.
|
||||
export const ASK_BUSY_MS = 10 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Whether the agent has picked up an Ask message (or an edit decision) and
|
||||
* not replied to it yet: busy with it, not gone.
|
||||
*/
|
||||
export function chatAnswering(frameChat) {
|
||||
const chat = chatOf(frameChat);
|
||||
const messages = Array.isArray(chat.messages) ? chat.messages : [];
|
||||
const pickedUp = Number.isInteger(chat.pickedUp) ? chat.pickedUp : 0;
|
||||
for (const [seq, answered] of answeredFlags(messages)) {
|
||||
if (!answered && seq <= pickedUp) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether nobody is there to answer a chat message. A finished session's agent
|
||||
* is often still listening through its last wait (the review and dashboard
|
||||
@@ -217,10 +235,10 @@ const ADRIFT_MS = 3 * 60 * 1000;
|
||||
* not end the chat — going quiet does. Offline once the agent has been silent
|
||||
* longer than the page would tolerate before calling it stuck (working) or
|
||||
* adrift (anything else), which is also the only signal left once the server
|
||||
* is gone.
|
||||
* is gone. An Ask message in hand (`answering`) stretches either to ASK_BUSY_MS.
|
||||
*/
|
||||
export function chatOffline({ finish, agent, agentLastSeenMs, now }) {
|
||||
export function chatOffline({ finish, agent, agentLastSeenMs, now, answering = false }) {
|
||||
const silent = now - agentLastSeenMs;
|
||||
if (agent && agent.status === "working") return silent > quietLimitMs(agent, STALE_MS);
|
||||
return silent > quietLimitMs(agent, ADRIFT_MS);
|
||||
const limit = quietLimitMs(agent, agent && agent.status === "working" ? STALE_MS : ADRIFT_MS);
|
||||
return silent > (answering ? Math.max(limit, ASK_BUSY_MS) : limit);
|
||||
}
|
||||
@@ -22,6 +22,7 @@ export const HELP_TABS = Object.freeze([
|
||||
tab("dashboard", "The dashboard", true),
|
||||
tab("meter", "Session meter", false),
|
||||
tab("build", "Watching a build", false),
|
||||
tab("loop", "Implementation Loop", true),
|
||||
tab("git", "The git board", false),
|
||||
tab("subagents", "Helpers (subagents)", false),
|
||||
tab("ask", "Ask a quick question", false),
|
||||
@@ -53,20 +54,6 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
||||
return "about";
|
||||
}
|
||||
|
||||
// The tab index a key moves to, or -1 when the key is not a tab key.
|
||||
export function helpKeyTarget(key, index, count) {
|
||||
switch (key) {
|
||||
case "ArrowDown":
|
||||
case "ArrowRight":
|
||||
return (index + 1) % count;
|
||||
case "ArrowUp":
|
||||
case "ArrowLeft":
|
||||
return (index - 1 + count) % count;
|
||||
case "Home":
|
||||
return 0;
|
||||
case "End":
|
||||
return count - 1;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
// The tab index a key moves to, or -1 when the key is not a tab key: the
|
||||
// shared tab helper's, under the name Help and the git board import.
|
||||
export { tabKeyTarget as helpKeyTarget } from "./tabs.js";
|
||||
+755
-183
File diff suppressed because it is too large.
Load diff
@@ -9,7 +9,7 @@ import { normalizeRole, ROLE_NOT_SET } from "./starters.js";
|
||||
import { bootData, hooks } from "./state.js";
|
||||
import { el } from "./render.js";
|
||||
import { tellApp } from "./app-bridge.js";
|
||||
import { ACTIVITIES, bestKey, memoKey } from "./activities.js";
|
||||
import { ACTIVITIES, bestKeys, memoKey, musicKey, musicLevel } from "./activities.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -31,13 +31,20 @@ export const DEFAULT_LOOKS = {
|
||||
...soundPrefs(null),
|
||||
width: DEFAULT_CARD_WIDTH,
|
||||
hideUnavailable: true,
|
||||
// Activities: the top bar's die, the game last picked, and one best score
|
||||
// per listed game (activityBestSnake), each a flat key for cleanLooks().
|
||||
// Activities: the top bar's die, whether its games play sounds (under Play
|
||||
// sounds, which silences them too), the game last picked, and one best score
|
||||
// per listed game (activityBestSnake) or, for a game with courses, per
|
||||
// course (activityBestGolfPirate), each a flat key for cleanLooks().
|
||||
hideActivities: false,
|
||||
activitySounds: true,
|
||||
// Whether a game plays its chiptune music too: off until asked for.
|
||||
gameMusic: false,
|
||||
lastActivity: "",
|
||||
...Object.fromEntries(ACTIVITIES.map((a) => [bestKey(a.id), 0])),
|
||||
...Object.fromEntries(ACTIVITIES.flatMap((a) => bestKeys(a).map((key) => [key, 0]))),
|
||||
// And one memo per game (activityMemoSnake): Snake's surprises found.
|
||||
...Object.fromEntries(ACTIVITIES.map((a) => [memoKey(a.id), 0])),
|
||||
// And, for a game with music, its music volume (activityMusicDrive), 0 to 100.
|
||||
...Object.fromEntries(ACTIVITIES.filter((a) => a.music !== undefined).map((a) => [musicKey(a.id), a.music])),
|
||||
};
|
||||
|
||||
export let looks = { ...DEFAULT_LOOKS };
|
||||
@@ -55,14 +62,18 @@ export function adoptLooks(saved) {
|
||||
if (typeof looks.hideUnavailable !== "boolean") looks.hideUnavailable = DEFAULT_LOOKS.hideUnavailable;
|
||||
looks.width = cardWidth(looks.width);
|
||||
if (typeof looks.hideActivities !== "boolean") looks.hideActivities = DEFAULT_LOOKS.hideActivities;
|
||||
if (typeof looks.activitySounds !== "boolean") looks.activitySounds = DEFAULT_LOOKS.activitySounds;
|
||||
if (typeof looks.gameMusic !== "boolean") looks.gameMusic = DEFAULT_LOOKS.gameMusic;
|
||||
if (typeof looks.lastActivity !== "string") looks.lastActivity = DEFAULT_LOOKS.lastActivity;
|
||||
// A best score is a whole number of points, never below none.
|
||||
for (const a of ACTIVITIES) {
|
||||
const key = bestKey(a.id);
|
||||
const n = Number(looks[key]);
|
||||
looks[key] = Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
||||
for (const key of bestKeys(a)) {
|
||||
const n = Number(looks[key]);
|
||||
looks[key] = Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
||||
}
|
||||
const memo = Number(looks[memoKey(a.id)]);
|
||||
looks[memoKey(a.id)] = Number.isFinite(memo) && memo > 0 ? Math.floor(memo) : 0;
|
||||
if (a.music !== undefined) looks[musicKey(a.id)] = Math.round(musicLevel(a, looks[musicKey(a.id)]) * 100);
|
||||
}
|
||||
if (saved && typeof saved === "object" && Object.hasOwn(saved, "role")) looks.role = normalizeRole(saved.role);
|
||||
else delete looks.role;
|
||||
@@ -117,8 +128,9 @@ export async function syncLooks() {
|
||||
setTimeout(hooks.maybeWelcome, 0);
|
||||
}
|
||||
|
||||
// Fire-and-forget mirror. A failed POST costs nothing the next session would
|
||||
// notice on this port; the localStorage copy still covers the reload case.
|
||||
// The mirror on the server. A failed POST costs nothing the next session would
|
||||
// notice on this port; the localStorage copy still covers the reload case. It
|
||||
// resolves with whether the write landed, for Preferences' Saved mark.
|
||||
function pushLooks() {
|
||||
try {
|
||||
// Only what this tab changed since it last synced, so a tab with stale
|
||||
@@ -127,19 +139,29 @@ function pushLooks() {
|
||||
for (const [k, v] of Object.entries(looks)) if (!syncedLooks || syncedLooks[k] !== v) set[k] = v;
|
||||
const before = syncedLooks;
|
||||
const partial = Boolean(before);
|
||||
if (partial && !Object.keys(set).length) return;
|
||||
if (partial && !Object.keys(set).length) return Promise.resolve({ ok: true });
|
||||
syncedLooks = { ...looks };
|
||||
const body = partial ? { set } : { looks };
|
||||
// A write that did not land must be sent again with the next change.
|
||||
const undo = () => (syncedLooks = before);
|
||||
fetch("/looks", {
|
||||
const failed = (error) => {
|
||||
undo();
|
||||
return { ok: false, error: error || "Could not save." };
|
||||
};
|
||||
return fetch("/looks", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
.then((res) => res.ok || undo())
|
||||
.catch(undo);
|
||||
} catch {}
|
||||
.then(async (res) => {
|
||||
if (res.ok) return { ok: true };
|
||||
const reply = await res.json().catch(() => ({}));
|
||||
return failed(reply.error);
|
||||
})
|
||||
.catch(() => failed());
|
||||
} catch {
|
||||
return Promise.resolve({ ok: false, error: "Could not save." });
|
||||
}
|
||||
}
|
||||
|
||||
const systemDark = () => matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
@@ -174,16 +196,26 @@ export function applyLooks() {
|
||||
ACCENT_VARS.forEach((name, i) => root.style.setProperty(name, shades[i]));
|
||||
}
|
||||
|
||||
// Resolves { ok: true } once the server has it (or there was nothing new to
|
||||
// send), or { ok: false, error } when the write did not land.
|
||||
export function saveLooks() {
|
||||
try {
|
||||
localStorage.setItem(LOOKS_KEY, JSON.stringify(looks));
|
||||
} catch {}
|
||||
pushLooks();
|
||||
const pushed = pushLooks();
|
||||
applyLooks();
|
||||
// A width change reflows the card without resizing the column, so the
|
||||
// column's observer never hears of it: refit the growing box here.
|
||||
hooks.fitGrowBox();
|
||||
renderSwatches();
|
||||
return pushed;
|
||||
}
|
||||
|
||||
// Told of each swatch's save, for Preferences' Saved mark: set by the dialog's
|
||||
// screen, since this module never imports one.
|
||||
let swatchSaved = null;
|
||||
export function onSwatchSaved(fn) {
|
||||
swatchSaved = fn;
|
||||
}
|
||||
|
||||
// Built once, repainted in place. Rebuilding the row on every choice destroyed
|
||||
@@ -200,7 +232,8 @@ export function renderSwatches() {
|
||||
b.setAttribute("aria-label", a.name);
|
||||
b.addEventListener("click", () => {
|
||||
looks.accent = id;
|
||||
saveLooks();
|
||||
const saved = saveLooks();
|
||||
if (swatchSaved) swatchSaved(saved);
|
||||
});
|
||||
box.appendChild(b);
|
||||
}
|
||||
@@ -231,15 +264,27 @@ export function renderSwatches() {
|
||||
}
|
||||
$("looks-role").value = looks.role ?? ROLE_NOT_SET;
|
||||
$("looks-activities").checked = !looks.hideActivities;
|
||||
// Like a cue, the game sounds keep their tick while Play sounds is off.
|
||||
$("looks-activity-sounds").checked = looks.activitySounds;
|
||||
$("looks-activity-sounds").disabled = !looks.sound;
|
||||
$("looks-game-music").checked = looks.gameMusic;
|
||||
$("looks-game-music").disabled = !looks.sound;
|
||||
}
|
||||
|
||||
// "Back to default": every look returns to its default, but the role is
|
||||
// marked as asked, the welcome stays seen, and the Activities' best scores
|
||||
// and last pick stay (only Reset best scores clears those).
|
||||
export function resetLooks() {
|
||||
// and last pick stay (only Reset best scores clears those). Given `keys` (one
|
||||
// Preferences tab's, prefsResetScope() in prefs.js), only those change: the
|
||||
// role is cleared but marked as asked, the rest take their defaults, and
|
||||
// every other key stays as it is.
|
||||
export function resetLooks(keys) {
|
||||
if (keys) {
|
||||
for (const key of keys) looks[key] = key === "role" ? ROLE_NOT_SET : DEFAULT_LOOKS[key];
|
||||
return;
|
||||
}
|
||||
const kept = { lastActivity: looks.lastActivity };
|
||||
for (const a of ACTIVITIES) {
|
||||
kept[bestKey(a.id)] = looks[bestKey(a.id)];
|
||||
for (const key of bestKeys(a)) kept[key] = looks[key];
|
||||
kept[memoKey(a.id)] = looks[memoKey(a.id)];
|
||||
}
|
||||
looks = { ...DEFAULT_LOOKS, ...kept, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen };
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// access at module scope, and its one import is the data-only skills.js: the
|
||||
// server, console.mjs, the page and `node --test` all import this file.
|
||||
|
||||
import { SKILLS, isMetered, isPhased } from "./skills.js";
|
||||
import { FLOW_SKILLS, isMetered, isPhased } from "./skills.js";
|
||||
|
||||
// The weights (FR-12): the events that are not a skill's own launch live
|
||||
// here, and each skill's weight is its `weight` in skills.js. Tune there or here.
|
||||
@@ -24,7 +24,7 @@ const EVENT_WEIGHTS = {
|
||||
"git-conflict": 1,
|
||||
};
|
||||
// A skill's fields as a table by workflow, leaving out the entries without one.
|
||||
const bySkill = (field) => Object.fromEntries(SKILLS.filter((s) => s[field] !== null).map((s) => [s.workflow, s[field]]));
|
||||
const bySkill = (field) => Object.fromEntries(FLOW_SKILLS.filter((s) => s[field] !== null).map((s) => [s.workflow, s[field]]));
|
||||
export const WEIGHTS = Object.freeze({ ...EVENT_WEIGHTS, ...bySkill("weight") });
|
||||
|
||||
// Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder,
|
||||
@@ -32,7 +32,7 @@ export const WEIGHTS = Object.freeze({ ...EVENT_WEIGHTS, ...bySkill("weight") })
|
||||
// reports; dashboard and handoff never score; git, changelog, xray and diagnose score 1 on
|
||||
// launch (Git then adds its commit tally and conflict help). Derived from
|
||||
// skills.js (`metered`).
|
||||
export const LAUNCH_COUNTED = Object.freeze(new Set(SKILLS.filter((s) => isMetered(s.workflow)).map((s) => s.workflow)));
|
||||
export const LAUNCH_COUNTED = Object.freeze(new Set(FLOW_SKILLS.filter((s) => isMetered(s.workflow)).map((s) => s.workflow)));
|
||||
|
||||
// Git's commits weigh what they add up to: each `git-commits` run carries
|
||||
// `commits`, and a skill run scores one point per COMMITS_PER_POINT commits,
|
||||
@@ -65,7 +65,7 @@ export const MAX_TASKS = 999;
|
||||
// bonus. The phase's `run` then takes the row over with its final score, so
|
||||
// the total only ever climbs. Workflows whose headline counts tasks, derived
|
||||
// from skills.js (`phased`):
|
||||
export const PROGRESS_WORKFLOWS = Object.freeze(new Set(SKILLS.filter((s) => isPhased(s.workflow)).map((s) => s.workflow)));
|
||||
export const PROGRESS_WORKFLOWS = Object.freeze(new Set(FLOW_SKILLS.filter((s) => isPhased(s.workflow)).map((s) => s.workflow)));
|
||||
|
||||
// Implement + Review reviews every phase as a stage of the build. A `review`
|
||||
// run inside it is that stage, so it scores the phase's TASK_BONUS when it
|
||||
@@ -120,7 +120,7 @@ export const ANSWERS_PER_POINT = 2;
|
||||
|
||||
// The skill names the answers row uses ("7 answers in Plan"), derived from
|
||||
// skills.js (`name`).
|
||||
const WORKFLOW_NAMES = Object.freeze(Object.fromEntries(SKILLS.map((s) => [s.workflow, s.name])));
|
||||
const WORKFLOW_NAMES = Object.freeze(Object.fromEntries(FLOW_SKILLS.map((s) => [s.workflow, s.name])));
|
||||
|
||||
// The skill run an entry belongs to, from its ledger id ("L3:..." -> "L3").
|
||||
const launchOf = (id) => (typeof id === "string" && id.includes(":") ? id.slice(0, id.indexOf(":")) : "L0");
|
||||
|
||||
@@ -240,6 +240,7 @@ export const CARD_WIDTHS = {
|
||||
narrow: { label: "Narrow", px: 720 },
|
||||
comfortable: { label: "Comfortable", px: 880 },
|
||||
wide: { label: "Wide", px: 1080 },
|
||||
ultrawide: { label: "Ultra wide", px: 1440 },
|
||||
};
|
||||
|
||||
export const DEFAULT_CARD_WIDTH = "comfortable";
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Plan2Code Web Console - what the User Preferences dialog is.
|
||||
//
|
||||
// Its tabs in order, which one opens, and what Back to default resets on
|
||||
// each. No DOM access at module scope, and its one import is the data-only
|
||||
// palette.js: the page and `node --test` both import this file.
|
||||
|
||||
import { SOUND_EVENTS, soundKey } from "./palette.js";
|
||||
|
||||
const tab = (id, label, hint, sections) => Object.freeze({ id, label, hint, sections: Object.freeze(sections) });
|
||||
|
||||
// Each section id names one fieldset in the dialog (its data-section).
|
||||
export const PREFS_TABS = Object.freeze([
|
||||
tab("appearance", "Appearance", "Theme, width, color, role", ["theme", "width", "accent", "role"]),
|
||||
tab("agents", "Agents & models", "Your CLIs and models", ["agents"]),
|
||||
tab("system", "System", "Cleanup, desktop app", ["cleanup", "desktop"]),
|
||||
tab("sounds", "Sounds & activities", "What plays", ["sounds", "activities"]),
|
||||
]);
|
||||
|
||||
// The tab the dialog opens on: the one asked for when there is such a tab,
|
||||
// else Appearance. Nothing is remembered between opens.
|
||||
export function prefsOpenTab(asked) {
|
||||
return PREFS_TABS.some((t) => t.id === asked) ? asked : "appearance";
|
||||
}
|
||||
|
||||
// The looks keys Back to default resets on a tab, or null where it has
|
||||
// nothing to reset (and is hidden).
|
||||
export function prefsResetScope(tab) {
|
||||
if (tab === "appearance") return ["theme", "width", "accent", "role"];
|
||||
if (tab === "sounds") return ["sound", ...Object.keys(SOUND_EVENTS).map(soundKey), "hideActivities", "activitySounds", "gameMusic"];
|
||||
return null;
|
||||
}
|
||||
@@ -406,7 +406,7 @@ export function isMac() {
|
||||
// backdrop is the <dialog> itself to the event, and so is its own padding, so
|
||||
// the point has to fall outside its box -- for the press as well as the
|
||||
// release, or selecting text inside and letting go outside would close it.
|
||||
export function lightDismiss(dlg) {
|
||||
export function lightDismiss(dlg, beforeClose) {
|
||||
const outside = (e) => {
|
||||
const r = dlg.getBoundingClientRect();
|
||||
return e.target === dlg && (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom);
|
||||
@@ -414,7 +414,11 @@ export function lightDismiss(dlg) {
|
||||
let pressedOutside = false;
|
||||
dlg.addEventListener("pointerdown", (e) => (pressedOutside = outside(e)));
|
||||
dlg.addEventListener("click", (e) => {
|
||||
if (pressedOutside && outside(e)) dlg.close();
|
||||
if (pressedOutside && outside(e)) {
|
||||
// `beforeClose` may hold the close: false, or a Promise of false.
|
||||
if (!beforeClose) dlg.close();
|
||||
else Promise.resolve(beforeClose()).then((go) => go !== false && dlg.close());
|
||||
}
|
||||
pressedOutside = false;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,713 @@
|
||||
// Plan2Code Web Console - User Preferences' Agents & models tab.
|
||||
//
|
||||
// A summary table of every agent (the built-in CLIs, the ones the person
|
||||
// added, and a row kept for the v3 orchestrator) whose Edit opens that agent's
|
||||
// full form. Nothing saves as it changes: a form edits a draft, and its Save
|
||||
// sends the saved list with only that draft swapped in, so a half-typed
|
||||
// command line never reaches agents.json or models.json.
|
||||
|
||||
import { el } from "../render.js";
|
||||
import { hooks } from "../state.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// The CLIs the launcher reads a model list for, in table order (routes.mjs MODEL_CLIS).
|
||||
const MODEL_CLIS = ["claude", "devin", "codex"];
|
||||
|
||||
// What the table calls each built-in, and the command it runs (the launcher's CLIS ids).
|
||||
const BUILT_IN = { claude: "Claude", devin: "Devin", codex: "Codex" };
|
||||
|
||||
// The last server reply for each list. Unknown keys on an agent ride along untouched.
|
||||
let saved = { agents: [], user: emptyLists(), shipped: emptyLists() };
|
||||
|
||||
// At most one per form being edited: "cli:<cli>" for a built-in's own models,
|
||||
// "agent:<id>" for an added agent, "agent:new" for one being added.
|
||||
const drafts = new Map();
|
||||
|
||||
// The form on screen (a drafts key), or null while the summary shows.
|
||||
let openKey = null;
|
||||
|
||||
// The server's complaint about the open form, { field, error }, and a 409's
|
||||
// warnings while Save anyway is on offer.
|
||||
let formError = null;
|
||||
let formReplace = null;
|
||||
|
||||
// Delete agent waiting for its second click; the arguments fold's state, kept across redraws.
|
||||
let confirming = false;
|
||||
let argsOpen = false;
|
||||
|
||||
// The badge each summary row last showed, by row key: { command, state }.
|
||||
const found = new Map();
|
||||
|
||||
// Each open of the tab loads afresh: only the newest load's answers are drawn.
|
||||
let loadSeq = 0;
|
||||
|
||||
function emptyLists() {
|
||||
return Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
|
||||
}
|
||||
|
||||
// Whether the status line says "Deleted.", which the next form opened clears
|
||||
// (load warnings stay until the next open).
|
||||
let deletedNote = false;
|
||||
|
||||
function setAgentsStatus(text, isError, { deleted = false } = {}) {
|
||||
const status = $("agents-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
deletedNote = deleted;
|
||||
}
|
||||
|
||||
function newAgent() {
|
||||
return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] };
|
||||
}
|
||||
|
||||
function normalizeAgent(agent) {
|
||||
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = [];
|
||||
return agent;
|
||||
}
|
||||
|
||||
const cliOf = (key) => key.slice("cli:".length);
|
||||
const agentId = (key) => key.slice("agent:".length);
|
||||
|
||||
function savedEntry(key) {
|
||||
if (key.startsWith("cli:")) return saved.user[cliOf(key)] || [];
|
||||
if (key === "agent:new") return newAgent();
|
||||
return saved.agents.find((a) => a.id === agentId(key));
|
||||
}
|
||||
|
||||
// JSON with object keys sorted, so a label removed and typed back counts as unchanged.
|
||||
function canonical(value) {
|
||||
return JSON.stringify(value, (_, v) =>
|
||||
v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v
|
||||
);
|
||||
}
|
||||
|
||||
function isDirty(key) {
|
||||
return drafts.has(key) && canonical(drafts.get(key)) !== canonical(savedEntry(key));
|
||||
}
|
||||
|
||||
function nameOf(key) {
|
||||
if (key.startsWith("cli:")) return BUILT_IN[cliOf(key)];
|
||||
const draft = drafts.get(key);
|
||||
return String((draft && draft.name) || "").trim() || savedEntry(key)?.name || "a new agent";
|
||||
}
|
||||
|
||||
const modelNames = (list) => list.map((m) => m.label || m.id);
|
||||
|
||||
/* ------------------------------------------------------------- summary */
|
||||
|
||||
// One row per agent, in order: the built-ins, the added agents, the orchestrator.
|
||||
function summaryRows() {
|
||||
return [
|
||||
...MODEL_CLIS.map((cli) => ({
|
||||
key: "cli:" + cli,
|
||||
name: BUILT_IN[cli],
|
||||
command: cli,
|
||||
models: [...saved.shipped[cli], ...saved.user[cli]],
|
||||
noneShip: saved.shipped[cli].length === 0,
|
||||
})),
|
||||
...saved.agents.map((a) => ({ key: "agent:" + a.id, name: a.name, command: a.command, models: a.models })),
|
||||
];
|
||||
}
|
||||
|
||||
function renderSummary() {
|
||||
const body = $("agents-table").tBodies[0];
|
||||
body.replaceChildren();
|
||||
const check = [];
|
||||
for (const row of summaryRows()) {
|
||||
const tr = el("tr");
|
||||
tr.dataset.key = row.key;
|
||||
const name = el("td", "prefs-agents-name");
|
||||
name.append(el("span", null, row.name), el("code", null, row.command));
|
||||
if (row.noneShip) name.append(el("span", "help", `No models ship for ${row.name} yet; add your own in Edit.`));
|
||||
const models = el("td", "prefs-agents-models");
|
||||
const names = modelNames(row.models);
|
||||
models.textContent = names.length ? `${names.length}: ${names.join(", ")}` : "None";
|
||||
const badge = el("span", "prefs-badge");
|
||||
const last = found.get(row.key);
|
||||
if (last && last.command === row.command) drawBadge(badge, last.state);
|
||||
else {
|
||||
badge.textContent = "Checking...";
|
||||
check.push(row);
|
||||
}
|
||||
const edit = el("button", "btn small", "Edit");
|
||||
edit.type = "button";
|
||||
edit.setAttribute("aria-label", "Edit " + row.name);
|
||||
edit.addEventListener("click", () => openForm(row.key));
|
||||
const editCell = el("td", "prefs-agents-edit");
|
||||
editCell.append(edit);
|
||||
const badgeCell = el("td");
|
||||
badgeCell.append(badge);
|
||||
tr.append(name, models, badgeCell, editCell);
|
||||
body.appendChild(tr);
|
||||
}
|
||||
const soon = el("tr", "prefs-agents-soon");
|
||||
const soonName = el("td", "prefs-agents-name");
|
||||
soonName.append(el("span", null, "v3 orchestrator"), el("span", "help", "Nothing to set yet."));
|
||||
soon.append(soonName, el("td", "prefs-agents-models"), el("td"), el("td"));
|
||||
body.appendChild(soon);
|
||||
if (check.length) checkFound(check, loadSeq);
|
||||
}
|
||||
|
||||
const BADGES = {
|
||||
ok: "Found",
|
||||
missing: "Not found on PATH",
|
||||
unknown: "Not checked",
|
||||
};
|
||||
|
||||
function drawBadge(badge, state) {
|
||||
badge.textContent = BADGES[state];
|
||||
badge.classList.remove("ok", "missing");
|
||||
if (state !== "unknown") badge.classList.add(state);
|
||||
}
|
||||
|
||||
// Whether each row's command is on PATH, all at once. /agents/test only
|
||||
// resolves the command and never runs it.
|
||||
async function checkFound(rows, seq) {
|
||||
await Promise.all(
|
||||
rows.map(async (row) => {
|
||||
let state = "unknown";
|
||||
try {
|
||||
const res = await fetch("/agents/test", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ command: row.command }),
|
||||
});
|
||||
if (res.ok) state = (await res.json()).found ? "ok" : "missing";
|
||||
} catch {}
|
||||
if (seq !== loadSeq) return;
|
||||
found.set(row.key, { command: row.command, state });
|
||||
const badge = $("agents-table").querySelector(`tr[data-key="${CSS.escape(row.key)}"] .prefs-badge`);
|
||||
if (badge) drawBadge(badge, state);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- the form */
|
||||
|
||||
function showSummary(on) {
|
||||
$("agents-table").hidden = !on;
|
||||
$("agents-add").hidden = !on;
|
||||
$("agents-intro").hidden = !on;
|
||||
$("agents-form").hidden = on;
|
||||
}
|
||||
|
||||
function openForm(key) {
|
||||
if (deletedNote) setAgentsStatus("", false);
|
||||
openKey = key;
|
||||
formError = null;
|
||||
formReplace = null;
|
||||
confirming = false;
|
||||
argsOpen = key === "agent:new";
|
||||
if (!drafts.has(key)) drafts.set(key, structuredClone(key === "agent:new" ? newAgent() : savedEntry(key)));
|
||||
showSummary(false);
|
||||
drawForm();
|
||||
$("agents-form").querySelector("input")?.focus();
|
||||
}
|
||||
|
||||
// Back on the summary, focus goes to the row just left (its Edit), or to Add
|
||||
// agent when that row is gone (a new agent not saved, one just deleted).
|
||||
function closeForm() {
|
||||
const left = openKey;
|
||||
if (openKey) drafts.delete(openKey);
|
||||
openKey = null;
|
||||
formError = null;
|
||||
formReplace = null;
|
||||
confirming = false;
|
||||
$("agents-form").replaceChildren();
|
||||
showSummary(true);
|
||||
renderSummary();
|
||||
const row = left && $("agents-table").querySelector(`tr[data-key="${CSS.escape(left)}"] .prefs-agents-edit button`);
|
||||
(row || $("agents-add")).focus();
|
||||
}
|
||||
|
||||
function edited() {
|
||||
if (openKey) renderDirty(openKey);
|
||||
}
|
||||
|
||||
function agentField(label, field, child) {
|
||||
const wrap = el("div", "agent-field");
|
||||
wrap.dataset.field = field;
|
||||
wrap.append(el("span", null, label), child);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function agentInput(agent, key, label, placeholder, trim) {
|
||||
const input = el("input");
|
||||
input.value = agent[key] || "";
|
||||
input.placeholder = placeholder;
|
||||
input.setAttribute("aria-label", label);
|
||||
input.dataset.field = key;
|
||||
input.addEventListener("input", () => {
|
||||
agent[key] = trim ? input.value.trim() : input.value;
|
||||
edited();
|
||||
});
|
||||
return input;
|
||||
}
|
||||
|
||||
// A list of text rows (arguments), with Remove on each and an Add under them.
|
||||
function agentArgsEditor(agent, key, label, placeholder, addLabel) {
|
||||
const box = el("div", "agent-rows");
|
||||
box.dataset.field = key;
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
agent[key].forEach((value, i) => {
|
||||
const row = el("div", "agent-row");
|
||||
const input = el("input");
|
||||
input.value = value;
|
||||
input.placeholder = placeholder;
|
||||
input.setAttribute("aria-label", label);
|
||||
input.dataset.field = key;
|
||||
input.addEventListener("input", () => {
|
||||
agent[key][i] = input.value.trim();
|
||||
edited();
|
||||
});
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
remove.addEventListener("click", () => {
|
||||
agent[key].splice(i, 1);
|
||||
draw();
|
||||
edited();
|
||||
});
|
||||
row.append(input, remove);
|
||||
box.appendChild(row);
|
||||
});
|
||||
const add = el("button", "btn small ghost", addLabel);
|
||||
add.type = "button";
|
||||
add.addEventListener("click", () => {
|
||||
agent[key].push("");
|
||||
draw();
|
||||
edited();
|
||||
box.querySelector(".agent-row:last-of-type input")?.focus();
|
||||
});
|
||||
box.appendChild(add);
|
||||
};
|
||||
draw();
|
||||
return agentField(label, key, box);
|
||||
}
|
||||
|
||||
// A models list: an id and a name for the menu on each row. An added agent's
|
||||
// rows drop a blank name; a built-in's keep it, as models.json does.
|
||||
function agentModelsEditor(list, { label: fieldLabel = "Models", optionalName = true } = {}) {
|
||||
const box = el("div", "agent-rows");
|
||||
box.dataset.field = "models";
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
list.forEach((m, i) => {
|
||||
const row = el("div", "agent-row model");
|
||||
const id = el("input");
|
||||
id.value = m.id || "";
|
||||
id.placeholder = optionalName ? "Model id, for {model}" : "Model id";
|
||||
id.setAttribute("aria-label", "Model id");
|
||||
id.dataset.field = "models";
|
||||
const label = el("input");
|
||||
label.value = m.label || "";
|
||||
label.placeholder = optionalName ? "Name shown in the menu (optional)" : "Name shown in the menu";
|
||||
label.setAttribute("aria-label", "Name shown in the menu");
|
||||
label.dataset.field = "models";
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
id.addEventListener("input", () => {
|
||||
m.id = id.value.trim();
|
||||
edited();
|
||||
});
|
||||
label.addEventListener("input", () => {
|
||||
const text = label.value.trim();
|
||||
if (text || !optionalName) m.label = text;
|
||||
else delete m.label;
|
||||
edited();
|
||||
});
|
||||
remove.addEventListener("click", () => {
|
||||
list.splice(i, 1);
|
||||
draw();
|
||||
edited();
|
||||
});
|
||||
row.append(id, label, remove);
|
||||
box.appendChild(row);
|
||||
});
|
||||
const add = el("button", "btn small ghost", "Add a model");
|
||||
add.type = "button";
|
||||
add.addEventListener("click", () => {
|
||||
list.push(optionalName ? { id: "" } : { id: "", label: "" });
|
||||
draw();
|
||||
edited();
|
||||
box.querySelector(".agent-row:last-of-type input")?.focus();
|
||||
});
|
||||
box.appendChild(add);
|
||||
};
|
||||
draw();
|
||||
return agentField(fieldLabel, "models", box);
|
||||
}
|
||||
|
||||
// The command's Test: where it would run from. Never saves.
|
||||
function agentTest(agent) {
|
||||
const wrap = el("div", "prefs-agents-test");
|
||||
const test = el("button", "btn small", "Test");
|
||||
test.type = "button";
|
||||
const result = el("span", "help agent-test-result");
|
||||
result.setAttribute("role", "status");
|
||||
test.addEventListener("click", async () => {
|
||||
const command = String(agent.command || "").trim();
|
||||
if (!command) {
|
||||
result.textContent = "Type a command first.";
|
||||
return;
|
||||
}
|
||||
result.textContent = "Looking...";
|
||||
try {
|
||||
const res = await fetch("/agents/test", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ command }),
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok) result.textContent = body.error || "Could not test.";
|
||||
else result.textContent = body.found ? "Found at " + body.path : "Not found on PATH";
|
||||
} catch {
|
||||
result.textContent = "Could not test.";
|
||||
}
|
||||
});
|
||||
wrap.append(test, result);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function builtInFields(cli, draft) {
|
||||
const shipped = el("div", "models-list prefs-agents-shipped");
|
||||
shipped.setAttribute("aria-label", "Comes with Plan2Code");
|
||||
for (const m of saved.shipped[cli]) {
|
||||
const row = el("div", "models-row locked");
|
||||
row.append(el("span", null, m.id), el("span", null, m.label || ""));
|
||||
shipped.appendChild(row);
|
||||
}
|
||||
const note = el("div", "models-note");
|
||||
note.innerHTML =
|
||||
"<ul>" +
|
||||
"<li>Restart <code>plan2code</code> to see a change in its model menu.</li>" +
|
||||
"<li>At any time, run <code>plan2code --model <id></code>, or pick your model inside your agent before running a skill.</li>" +
|
||||
"<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>" +
|
||||
"<li>Devin models are limited to Low, Medium and High effort.</li>" +
|
||||
"</ul>";
|
||||
const comes = el("div", "agent-field");
|
||||
comes.append(el("span", null, "Comes with Plan2Code"));
|
||||
if (saved.shipped[cli].length) comes.append(shipped);
|
||||
else comes.append(el("p", "help prefs-agents-none", `No models ship for ${BUILT_IN[cli]} yet; add your own below.`));
|
||||
return [note, comes, agentModelsEditor(draft, { label: "Models you added", optionalName: false })];
|
||||
}
|
||||
|
||||
function addedFields(draft) {
|
||||
const command = agentField("Command", "command", agentInput(draft, "command", "Command", "Program to run, such as myagent", true));
|
||||
command.append(agentTest(draft));
|
||||
const fold = el("details", "prefs-agents-args");
|
||||
fold.open = argsOpen;
|
||||
fold.addEventListener("toggle", () => (argsOpen = fold.open));
|
||||
fold.append(
|
||||
el("summary", null, "Command-line arguments"),
|
||||
agentArgsEditor(draft, "args", "Arguments", "--message={prompt}", "Add an argument"),
|
||||
agentArgsEditor(draft, "bypassArgs", "Bypass arguments", "--yes-always", "Add an argument"),
|
||||
agentArgsEditor(draft, "modelArgs", "Model arguments", "--model={model}", "Add an argument"),
|
||||
);
|
||||
return [
|
||||
agentField("Name", "name", agentInput(draft, "name", "Name", "Name shown in the menu", true)),
|
||||
command,
|
||||
agentField("Start prompt", "prompt", agentInput(draft, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
|
||||
agentModelsEditor(draft.models),
|
||||
fold,
|
||||
];
|
||||
}
|
||||
|
||||
// Save, Discard and the Unsaved badge (shown only while the draft differs),
|
||||
// the Saved mark's spot, Save anyway after a 409, and Delete agent with its
|
||||
// confirm on the form itself (never the browser's confirm()).
|
||||
function formFoot(key) {
|
||||
const foot = el("div", "agent-foot prefs-agents-foot");
|
||||
const save = el("button", "btn small primary prefs-agents-save", "Save");
|
||||
save.type = "button";
|
||||
save.addEventListener("click", () => saveForm(key));
|
||||
const discard = el("button", "btn small ghost prefs-agents-discard", "Discard");
|
||||
discard.type = "button";
|
||||
discard.addEventListener("click", () => discardOpen());
|
||||
const badge = el("span", "prefs-unsaved-badge", "Unsaved");
|
||||
foot.append(save, discard, badge);
|
||||
if (formReplace) {
|
||||
const anyway = el("button", "btn small danger prefs-agents-replace", "Save anyway");
|
||||
anyway.type = "button";
|
||||
anyway.addEventListener("click", () => saveForm(key, { replace: true }));
|
||||
foot.append(anyway);
|
||||
}
|
||||
if (key.startsWith("agent:") && key !== "agent:new") {
|
||||
if (confirming) {
|
||||
const yes = el("button", "btn small danger", "Yes, delete");
|
||||
yes.type = "button";
|
||||
yes.addEventListener("click", () => deleteAgent(key));
|
||||
const keep = el("button", "btn small ghost", "Keep");
|
||||
keep.type = "button";
|
||||
keep.addEventListener("click", () => {
|
||||
confirming = false;
|
||||
drawForm();
|
||||
});
|
||||
foot.append(el("span", "help", "Delete this agent?"), yes, keep);
|
||||
} else {
|
||||
const del = el("button", "btn small ghost danger prefs-agents-delete", "Delete agent");
|
||||
del.type = "button";
|
||||
del.addEventListener("click", () => {
|
||||
confirming = true;
|
||||
drawForm();
|
||||
});
|
||||
foot.append(del);
|
||||
}
|
||||
}
|
||||
return foot;
|
||||
}
|
||||
|
||||
function renderDirty(key) {
|
||||
const foot = $("agents-form").querySelector(".prefs-agents-foot");
|
||||
if (!foot || key !== openKey) return;
|
||||
const dirty = isDirty(key);
|
||||
for (const sel of [".prefs-agents-save", ".prefs-agents-discard", ".prefs-unsaved-badge"]) foot.querySelector(sel).hidden = !dirty;
|
||||
}
|
||||
|
||||
// Which field or button has focus, so a redraw (an id assigned, an error
|
||||
// marked) puts the person back where they were: { nth, start, end }. What
|
||||
// they typed is already in the draft the redraw reads.
|
||||
const FORM_FOCUSABLE = "input, button, summary";
|
||||
|
||||
function formFocus(form) {
|
||||
const active = document.activeElement;
|
||||
if (!active || !form.contains(active)) return null;
|
||||
const at = { nth: [...form.querySelectorAll(FORM_FOCUSABLE)].indexOf(active) };
|
||||
if (active instanceof HTMLInputElement) Object.assign(at, { start: active.selectionStart, end: active.selectionEnd });
|
||||
return at;
|
||||
}
|
||||
|
||||
function restoreFormFocus(form, at) {
|
||||
if (!at) return;
|
||||
const target = form.querySelectorAll(FORM_FOCUSABLE)[at.nth];
|
||||
// A button the redraw hid (Save, once saved) hands focus to the heading.
|
||||
if (!target || target.closest("[hidden]")) return form.querySelector(".prefs-agents-title")?.focus();
|
||||
target.focus();
|
||||
if (target instanceof HTMLInputElement && at.start !== undefined) {
|
||||
try {
|
||||
target.setSelectionRange(at.start, at.end);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
function drawForm() {
|
||||
const form = $("agents-form");
|
||||
const key = openKey;
|
||||
const draft = drafts.get(key);
|
||||
const focus = formFocus(form);
|
||||
form.replaceChildren();
|
||||
const back = el("button", "btn small ghost prefs-agents-back", "Back to summary");
|
||||
back.type = "button";
|
||||
back.addEventListener("click", async () => {
|
||||
if (await hooks.confirmUnsaved()) closeForm();
|
||||
});
|
||||
const title = el("h3", "prefs-agents-title");
|
||||
title.tabIndex = -1;
|
||||
if (key.startsWith("cli:")) title.append(el("span", null, BUILT_IN[cliOf(key)]), el("code", null, cliOf(key)));
|
||||
else title.append(el("span", null, key === "agent:new" ? "New agent" : savedEntry(key).name));
|
||||
const fields = el("div", "prefs-agents-fields");
|
||||
fields.append(...(key.startsWith("cli:") ? builtInFields(cliOf(key), draft) : addedFields(draft)));
|
||||
form.append(back, title, fields);
|
||||
if (formError) {
|
||||
for (const input of form.querySelectorAll("input")) {
|
||||
if (input.dataset.field === formError.field) input.classList.add("invalid");
|
||||
}
|
||||
form.append(el("p", "agent-error", formError.error));
|
||||
}
|
||||
if (formReplace) form.append(el("p", "agent-error", formReplace.join(" ")));
|
||||
form.append(formFoot(key));
|
||||
renderDirty(key);
|
||||
restoreFormFocus(form, focus);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- saving */
|
||||
|
||||
// The list as the server wants it: blank rows and models without an id dropped.
|
||||
function cleanAgent(a) {
|
||||
return {
|
||||
...a,
|
||||
args: a.args.filter((v) => v !== ""),
|
||||
bypassArgs: a.bypassArgs.filter((v) => v !== ""),
|
||||
modelArgs: a.modelArgs.filter((v) => v !== ""),
|
||||
models: a.models.filter((m) => m.id),
|
||||
};
|
||||
}
|
||||
|
||||
async function postJson(url, payload) {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { res, body: await res.json() };
|
||||
}
|
||||
|
||||
// The form's foot, for the Saved mark (or the error in its place).
|
||||
const formMark = (result) => hooks.markSaved($("agents-form").querySelector(".prefs-agents-foot"), result);
|
||||
|
||||
// Fresh from what was just saved: the form redraws on a clean draft.
|
||||
function savedAs(key) {
|
||||
drafts.delete(openKey);
|
||||
openKey = key;
|
||||
drafts.set(key, structuredClone(savedEntry(key)));
|
||||
formError = null;
|
||||
formReplace = null;
|
||||
drawForm();
|
||||
}
|
||||
|
||||
async function saveModelsFor(cli) {
|
||||
const sent = drafts.get("cli:" + cli).filter((m) => m.id);
|
||||
try {
|
||||
const { res, body } = await postJson("/models", { models: { ...saved.user, [cli]: sent } });
|
||||
if (!res.ok) {
|
||||
formMark({ ok: false, error: body.error || "Could not save." });
|
||||
return false;
|
||||
}
|
||||
saved.user[cli] = (body.user && body.user[cli]) || sent;
|
||||
} catch {
|
||||
formMark({ ok: false, error: "Could not save." });
|
||||
return false;
|
||||
}
|
||||
savedAs("cli:" + cli);
|
||||
formMark({ ok: true, text: "Saved. Restart plan2code to use it." });
|
||||
return true;
|
||||
}
|
||||
|
||||
async function saveAgentFor(key, { replace = false } = {}) {
|
||||
const draft = drafts.get(key);
|
||||
const isNew = key === "agent:new";
|
||||
if (isNew && (!String(draft.name || "").trim() || !String(draft.command || "").trim())) {
|
||||
formError = { field: String(draft.name || "").trim() ? "command" : "name", error: "Give it a name and a command first." };
|
||||
drawForm();
|
||||
return false;
|
||||
}
|
||||
const at = isNew ? saved.agents.length : saved.agents.findIndex((a) => a.id === agentId(key));
|
||||
const agents = saved.agents.map((a) => cleanAgent(a));
|
||||
agents.splice(at, isNew ? 0 : 1, cleanAgent(draft));
|
||||
try {
|
||||
const { res, body } = await postJson("/agents", replace ? { agents, replace: true } : { agents });
|
||||
if (res.status === 409) {
|
||||
formError = { field: null, error: body.error || "Not saved." };
|
||||
formReplace = Array.isArray(body.warnings) ? body.warnings : [];
|
||||
drawForm();
|
||||
return false;
|
||||
}
|
||||
if (!res.ok) {
|
||||
formError = { field: body.index === at ? body.field : null, error: body.error || "Could not save." };
|
||||
formReplace = null;
|
||||
drawForm();
|
||||
return false;
|
||||
}
|
||||
saved.agents = (Array.isArray(body.agents) ? body.agents : agents).map(normalizeAgent);
|
||||
} catch {
|
||||
formMark({ ok: false, error: "Could not save." });
|
||||
return false;
|
||||
}
|
||||
const id = saved.agents[at].id;
|
||||
found.delete(key);
|
||||
found.delete("agent:" + id);
|
||||
savedAs("agent:" + id);
|
||||
formMark({ ok: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
function saveForm(key, options) {
|
||||
return key.startsWith("cli:") ? saveModelsFor(cliOf(key)) : saveAgentFor(key, options);
|
||||
}
|
||||
|
||||
async function deleteAgent(key) {
|
||||
const agents = saved.agents.filter((a) => a.id !== agentId(key)).map(cleanAgent);
|
||||
confirming = false;
|
||||
try {
|
||||
const { res, body } = await postJson("/agents", { agents });
|
||||
if (!res.ok) {
|
||||
formError = { field: null, error: body.error || "Could not delete." };
|
||||
drawForm();
|
||||
return;
|
||||
}
|
||||
saved.agents = (Array.isArray(body.agents) ? body.agents : agents).map(normalizeAgent);
|
||||
} catch {
|
||||
formError = { field: null, error: "Could not delete." };
|
||||
drawForm();
|
||||
return;
|
||||
}
|
||||
found.delete(key);
|
||||
closeForm();
|
||||
setAgentsStatus("Deleted.", false, { deleted: true });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- the dialog's side */
|
||||
|
||||
// An open form whose draft differs from what is saved.
|
||||
export function hasUnsaved() {
|
||||
return openKey !== null && isDirty(openKey);
|
||||
}
|
||||
|
||||
// What the unsaved prompt calls the open form.
|
||||
export function unsavedName() {
|
||||
return openKey ? nameOf(openKey) : "";
|
||||
}
|
||||
|
||||
export function saveOpen() {
|
||||
return openKey ? saveForm(openKey) : Promise.resolve(true);
|
||||
}
|
||||
|
||||
export function discardOpen() {
|
||||
if (!openKey) return;
|
||||
if (openKey === "agent:new") return closeForm();
|
||||
drafts.set(openKey, structuredClone(savedEntry(openKey)));
|
||||
formError = null;
|
||||
formReplace = null;
|
||||
confirming = false;
|
||||
drawForm();
|
||||
}
|
||||
|
||||
// Back into the form after Keep editing or a failed Save: the marked field, else the first.
|
||||
export function focusOpen() {
|
||||
const form = $("agents-form");
|
||||
(form.querySelector("input.invalid") || form.querySelector("input"))?.focus();
|
||||
}
|
||||
|
||||
// Each time the dialog opens: the summary, from the server.
|
||||
export async function loadAgentsView() {
|
||||
const seq = ++loadSeq;
|
||||
openKey = null;
|
||||
drafts.clear();
|
||||
found.clear();
|
||||
formError = null;
|
||||
formReplace = null;
|
||||
confirming = false;
|
||||
$("agents-form").replaceChildren();
|
||||
showSummary(true);
|
||||
setAgentsStatus("", false);
|
||||
const [agents, models] = await Promise.all([
|
||||
fetch("/agents").then((r) => (r.ok ? r.json() : null)).catch(() => null),
|
||||
fetch("/models").then((r) => (r.ok ? r.json() : null)).catch(() => null),
|
||||
]);
|
||||
if (seq !== loadSeq) return;
|
||||
const problems = [];
|
||||
if (agents) {
|
||||
saved.agents = (Array.isArray(agents.agents) ? agents.agents : []).map(normalizeAgent);
|
||||
if (Array.isArray(agents.warnings)) problems.push(...agents.warnings);
|
||||
} else {
|
||||
saved.agents = [];
|
||||
problems.push("Agents could not be loaded.");
|
||||
}
|
||||
saved.user = emptyLists();
|
||||
saved.shipped = emptyLists();
|
||||
if (models) {
|
||||
for (const cli of MODEL_CLIS) {
|
||||
if (Array.isArray(models.user?.[cli])) saved.user[cli] = models.user[cli];
|
||||
if (Array.isArray(models.shipped?.[cli])) saved.shipped[cli] = models.shipped[cli];
|
||||
}
|
||||
} else {
|
||||
problems.push("Models could not be loaded.");
|
||||
}
|
||||
setAgentsStatus(problems.join(" "), problems.length > 0);
|
||||
renderSummary();
|
||||
}
|
||||
|
||||
export function wireAgentsView() {
|
||||
$("agents-add").addEventListener("click", () => openForm("agent:new"));
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
// Plan2Code Web Console - the Ask chat, the Subagents tab, and attaching files to notes.
|
||||
|
||||
import { page, saveNow, redraw, freshChat, hooks, scrollMemory, setDraft } from "../state.js";
|
||||
import { chatOffline, chatView, sendState as chatSendState, newestReplyId, CHAT_MAX_CHARS, nextAbout, CHAT_MAX_ATTACHMENTS, contextOptions } from "../chat.js";
|
||||
import { finish, activity, agentAdrift, isDashboard, selSpec, byId, isOpen } from "../selectors.js";
|
||||
import { chatAnswering, chatOffline, chatView, sendState as chatSendState, newestReplyId, CHAT_MAX_CHARS, nextAbout, CHAT_MAX_ATTACHMENTS, contextOptions } from "../chat.js";
|
||||
import { finish, activity, agentAdrift, isDashboard, selSpec, byId, isOpen, loopAskLocked, loopDriving } from "../selectors.js";
|
||||
import { el, md, isMac, lightDismiss, shortTime } from "../render.js";
|
||||
import { startersFor } from "../starters.js";
|
||||
import { looks } from "../looks.js";
|
||||
@@ -37,6 +37,7 @@ function askFrame() {
|
||||
agent: page.S.agent,
|
||||
agentLastSeenMs: Date.parse(page.agentLastSeen),
|
||||
now: Date.now(),
|
||||
answering: chatAnswering(base),
|
||||
});
|
||||
return { ...base, offline };
|
||||
}
|
||||
@@ -45,7 +46,13 @@ export function askState() {
|
||||
const frame = askFrame();
|
||||
const shown = chatView(frame, { pendingSends: page.local.chat.pending, agentActivity: activity() });
|
||||
const pendingSendCount = shown.rows.filter((r) => r.pending && !r.failed).length;
|
||||
return { frame, view: shown, send: chatSendState({ frameChat: frame, gone: page.gone, pendingSendCount }) };
|
||||
const send = chatSendState({ frameChat: frame, gone: page.gone, pendingSendCount });
|
||||
// The Implementation Loop locks Ask like everything else it drives (FR-15),
|
||||
// unless a question waits for the person (FR-14).
|
||||
if (send.canType && loopAskLocked()) {
|
||||
return { frame, view: shown, send: { state: "ok", text: "Ask is off while the loop builds.", canType: false } };
|
||||
}
|
||||
return { frame, view: shown, send };
|
||||
}
|
||||
|
||||
// The conversation a send belongs to. The page's own record wins over the
|
||||
@@ -760,7 +767,8 @@ export function renderSubagentsButton() {
|
||||
btn.setAttribute("aria-pressed", String(Boolean(page.subagentsFrame.on)));
|
||||
btn.title = label;
|
||||
btn.setAttribute("aria-label", label);
|
||||
btn.disabled = page.gone;
|
||||
// The Subagents switch is the person's setting for the next agent; the loop's phases are already started.
|
||||
btn.disabled = page.gone || loopDriving();
|
||||
}
|
||||
|
||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
||||
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
byId,
|
||||
docs,
|
||||
isGitBoard,
|
||||
loopDriving,
|
||||
loopWaiting,
|
||||
} from "../selectors.js";
|
||||
import {
|
||||
lastOpenCard,
|
||||
@@ -316,14 +318,38 @@ function inFlightFor(item) {
|
||||
return sub ? { value: sub, summary: "" } : null;
|
||||
}
|
||||
|
||||
// While the Implementation Loop drives, an open card is a record, not a form
|
||||
// (FR-15): "handled" when the loop answers it itself, "locked" otherwise. The
|
||||
// one exception (FR-14) is a required question the loop does not handle, which
|
||||
// stays a live form while it waits for the person.
|
||||
function loopLockFor(item) {
|
||||
if (!loopDriving() || !isOpen(item) || finish()) return null;
|
||||
if (item.handledBy === "loop") return "handled";
|
||||
return loopWaiting() && item.required !== false ? null : "locked";
|
||||
}
|
||||
|
||||
function renderLoopLocked(card, item, why) {
|
||||
const box = el("div", "answered is-loop " + (why === "handled" ? "is-handled" : "is-locked"));
|
||||
if (why === "handled") {
|
||||
box.appendChild(el("p", "answered-head loop-tag", "The loop handles this"));
|
||||
box.appendChild(el("p", "answered-lock", "The Implementation Loop answers this one itself, so there is nothing to do here."));
|
||||
} else {
|
||||
box.appendChild(el("p", "answered-lock", "The Implementation Loop is building. This unlocks by itself if it needs you."));
|
||||
}
|
||||
card.appendChild(box);
|
||||
lockedOptions(card, item, []);
|
||||
}
|
||||
|
||||
export function renderCard(item) {
|
||||
const staged = page.local.staged[item.id];
|
||||
const flight = inFlightFor(item);
|
||||
const loopLock = loopLockFor(item);
|
||||
const card = el(
|
||||
"article",
|
||||
"card question" +
|
||||
(!isOpen(item) || finish() ? " is-answered" : staged ? " is-staged" : "") +
|
||||
(flight ? " is-inflight" : "")
|
||||
(flight ? " is-inflight" : "") +
|
||||
(loopLock ? " is-loop-" + loopLock : "")
|
||||
);
|
||||
|
||||
// Which question this card is for, so a render can tell whether the card it
|
||||
@@ -348,6 +374,8 @@ export function renderCard(item) {
|
||||
// send can no longer go anywhere and the form would be a trap.
|
||||
if (!isOpen(item) || finish()) {
|
||||
renderSettled(card, item);
|
||||
} else if (loopLock) {
|
||||
renderLoopLocked(card, item, loopLock);
|
||||
} else if (flight) {
|
||||
renderInFlight(card, item, flight);
|
||||
} else {
|
||||
@@ -355,7 +383,7 @@ export function renderCard(item) {
|
||||
if (build) build(card, item, staged);
|
||||
}
|
||||
|
||||
if (item.required === false && isOpen(item) && !flight && !finish()) {
|
||||
if (item.required === false && isOpen(item) && !flight && !finish() && !loopLock) {
|
||||
const skipped = Boolean(staged && staged.skipped);
|
||||
// A small accent chip, like a comment box's quick answer ("No changes"),
|
||||
// rather than an underlined link that reads as fine print.
|
||||
@@ -372,7 +400,7 @@ export function renderCard(item) {
|
||||
}
|
||||
}
|
||||
|
||||
if (isOpen(item) && !flight && !finish()) markGrowBox(card);
|
||||
if (isOpen(item) && !flight && !finish() && !loopLock) markGrowBox(card);
|
||||
return card;
|
||||
}
|
||||
|
||||
@@ -835,6 +863,28 @@ function buildChoice(card, item, staged) {
|
||||
}
|
||||
otherOption(list, item, staged, name);
|
||||
card.appendChild(list);
|
||||
clearRow(card, item);
|
||||
}
|
||||
|
||||
// Takes a one-answer question back to how it arrived: no pick, and nothing in
|
||||
// "Something else" (its draft too, or the render would put the words straight
|
||||
// back). A radio group cannot be unticked by clicking it again, so without
|
||||
// this a stray pick could only be swapped for another one. Only the builders
|
||||
// call it, and they only run for a form that has not been sent.
|
||||
function clearRow(card, item) {
|
||||
const row = el("div", "btn-row options-clear");
|
||||
const b = el("button", "btn small ghost", "Clear");
|
||||
b.type = "button";
|
||||
// An id so focus survives the render the click sets off (see withFocus).
|
||||
b.id = "clear-" + item.id;
|
||||
b.setAttribute("aria-label", "Clear your answer to this question");
|
||||
b.addEventListener("click", () => {
|
||||
const other = "other-" + item.id;
|
||||
if (page.local.drafts[other]) setDraft(other, "");
|
||||
stage(item.id, null);
|
||||
});
|
||||
row.appendChild(b);
|
||||
card.appendChild(row);
|
||||
}
|
||||
|
||||
function buildMulti(card, item, staged) {
|
||||
@@ -1335,6 +1385,7 @@ function buildMenu(card, item, staged) {
|
||||
list.appendChild(li);
|
||||
}
|
||||
card.appendChild(list);
|
||||
clearRow(card, item);
|
||||
|
||||
if (item.command) {
|
||||
const note = el("div", "card-note");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Plan2Code Web Console - User Preferences, Cleanup tab.
|
||||
// Plan2Code Web Console - User Preferences, the Cleanup section on the System tab.
|
||||
|
||||
import { formatBytes } from "../answers.js";
|
||||
import { el } from "../render.js";
|
||||
@@ -123,7 +123,7 @@ async function deleteCleanup() {
|
||||
setCleanupStatus((failed ? done + " " + failed + " could not be removed." : done) + keptLine, Boolean(failed));
|
||||
}
|
||||
|
||||
// The Cleanup tab's buttons, and starting over whenever Preferences closes.
|
||||
// The Cleanup section's buttons, and starting over whenever Preferences closes.
|
||||
export function wireCleanup() {
|
||||
$("cleanup-scan").addEventListener("click", scanCleanup);
|
||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
||||
|
||||
@@ -50,7 +50,7 @@ import { faviconState, setFavicon } from "../favicon.js";
|
||||
import { helperRows, showTab } from "../subagents.js";
|
||||
import { FOOTER_TIERS, footerLabel } from "../workspace.js";
|
||||
import {
|
||||
activity, agentAdrift, agentWorking, asked, awaitingReply, byId, dashboardLive, docs, doingNow,
|
||||
activity, agentAdrift, agentWorking, askBusy, loopDriving, loopWaiting, loopWaitingKey, asked, awaitingReply, byId, dashboardLive, docs, doingNow,
|
||||
finish, gitAwaiting, isDashboard, isGitBoard, isOpen, isSpecFileView, items, loadOverview, myTurn, openItems,
|
||||
patience, pressStranded, reviewPending, scan, selSpec, sendCollected, specFileTabs, stagedCount, stranded,
|
||||
topics, workingMs, WORKING_GRACE_MS,
|
||||
@@ -58,6 +58,7 @@ import {
|
||||
} from "../selectors.js";
|
||||
import { sound } from "../sound.js";
|
||||
import { renderConfirm, renderDashboard } from "./dashboard.js";
|
||||
import { renderLoopSetup } from "./loop-setup.js";
|
||||
import { renderLaunching, renderWaiting } from "./starting.js";
|
||||
import { attachFiles, heldNotes, noteImages, pendingNotes, removeImage } from "../uploads.js";
|
||||
import { closeMentions } from "../mention-box.js";
|
||||
@@ -69,13 +70,13 @@ import { renderWorkspace, tellFolderIssues } from "./workspace.js";
|
||||
import { openHelpOn } from "./help-dialog.js";
|
||||
import { linkLeavesPage, startNewSession, tellApp } from "../app-bridge.js";
|
||||
import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js";
|
||||
import { renderHandoff, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js";
|
||||
import { renderHandoff, renderLoopEnd, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js";
|
||||
import { renderNotepadButton } from "./notepad.js";
|
||||
import { renderActivities } from "./activities.js";
|
||||
|
||||
// What the entry needs from the screens at start-up, handed on from here: only
|
||||
// the core imports a screen.
|
||||
export { wakeHoldsChime, wireDashboard } from "./dashboard.js";
|
||||
export { launchSkill, wakeHoldsChime, wireDashboard } from "./dashboard.js";
|
||||
export { fillSky } from "./starting.js";
|
||||
export { fitGrowBox, wireCards } from "./cards.js";
|
||||
export { wireDocs } from "./docs.js";
|
||||
@@ -84,9 +85,12 @@ export { syncWorkspaceScope, wireWorkspace } from "./workspace.js";
|
||||
export { maybeWelcome, openHelpOn, wireHelp } from "./help-dialog.js";
|
||||
export { wireCleanup } from "./cleanup.js";
|
||||
export { startLooks, wireLooks } from "./looks.js";
|
||||
export { confirmUnsaved, markSaved, openPrefs, wirePrefs } from "./prefs-dialog.js";
|
||||
export { discardOpen, focusOpen, hasUnsaved, loadAgentsView, saveOpen, unsavedName, wireAgentsView } from "./agents-view.js";
|
||||
export { wireEnding } from "./ending.js";
|
||||
export { wireNotepad } from "./notepad.js";
|
||||
export { wireActivities } from "./activities.js";
|
||||
export { openLoopSetup, wireLoopSetup } from "./loop-setup.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -293,6 +297,11 @@ export function adopt(body) {
|
||||
page.inApp = Boolean(body.inApp);
|
||||
// Help's `.for-app` / `.for-browser` wording switches on this (help.css).
|
||||
document.documentElement.classList.toggle("in-app", page.inApp);
|
||||
// The Implementation Loop's lock: `loop: { driving: true }` on the state,
|
||||
// ended by the app's `loopEnd`. Screens ask loopDriving(); the class is for
|
||||
// the stylesheet.
|
||||
page.loop = (body.state && body.state.loop && body.state.loop.driving === true) || body.loop === true ? { driving: true } : null;
|
||||
document.documentElement.classList.toggle("loop-driving", loopDriving());
|
||||
// Always replaced: an absent key means no update.
|
||||
page.updateFrame = body.update || null;
|
||||
// Always replaced too: an older server sends none, and then there is no switch.
|
||||
@@ -318,8 +327,9 @@ export function adopt(body) {
|
||||
// session; what this page kept for the last skill -- the question on
|
||||
// screen, the open tab, anything staged or typed against its item ids --
|
||||
// goes too. The launch in flight and the dashboard's spec pick are about the
|
||||
// hand-off itself, so they stay. A skill run inline from another (a quick
|
||||
// task's review) keeps all of it.
|
||||
// hand-off itself, so they stay, and so does the Ask tab: the conversation
|
||||
// outlives the hop. A skill run inline from another (a quick task's review)
|
||||
// keeps all of it.
|
||||
if (startsClean(prevWorkflow, page.S.workflow)) {
|
||||
// The pick rides into the skill it launched, never back home: arriving at
|
||||
// the dashboard, the picker starts on the most recently touched spec still
|
||||
@@ -331,13 +341,15 @@ export function adopt(body) {
|
||||
const keepNote = Boolean(ns) && page.S.workflow !== "dashboard" && page.S.workflow === ns.workflow;
|
||||
page.local = {
|
||||
...fresh(),
|
||||
chat: page.local.chat,
|
||||
launching: page.local.launching,
|
||||
...(keepPick ? { specSel: page.local.specSel } : {}),
|
||||
...(keepNote ? { noteSend: ns } : {}),
|
||||
};
|
||||
save();
|
||||
page.selected = null;
|
||||
page.view = "questions";
|
||||
// Someone reading the Ask tab across the hop stays on it.
|
||||
if (page.view !== "ask") page.view = "questions";
|
||||
// And forget which tab is drawn, or the next render would store the old
|
||||
// skill's offset straight back under a tab id the new one may reuse.
|
||||
scrollMemory.clear();
|
||||
@@ -394,7 +406,10 @@ export function adopt(body) {
|
||||
// session under its own workflow, so `dashboard` stops being what the state
|
||||
// says it is. A finish while still on the dashboard is the launch declined
|
||||
// or the session ended; either way the menu is not mid-handoff any more.
|
||||
if (!isDashboard() || finish()) page.dashPick = null;
|
||||
if (!isDashboard() || finish()) {
|
||||
page.dashPick = null;
|
||||
page.loopSetup = null;
|
||||
}
|
||||
// A launch (or an ending) mid wake-up: cut it short rather than play on
|
||||
// over a page that is no longer the menu.
|
||||
if (page.wake && (!isDashboard() || finish())) page.wake.abort.abort();
|
||||
@@ -505,7 +520,7 @@ export function adopt(body) {
|
||||
}
|
||||
|
||||
// The chat's half of adopt(). A new conversation (New conversation pressed in
|
||||
// any tab, or a skill switch) is a clean page: nothing typed or waiting for
|
||||
// any tab) is a clean page: nothing typed or waiting for
|
||||
// the old one carries over. Conversations only ever count up, so a frame that
|
||||
// names an older one than this page already moved to is a late frame, not a
|
||||
// switch. Sends the server has now echoed stop being pending.
|
||||
@@ -515,8 +530,7 @@ function adoptChat() {
|
||||
if (page.local.chat.conversation == null) page.local.chat.conversation = conv;
|
||||
else if (conv > page.local.chat.conversation) {
|
||||
// What they were typing, and what they had attached to it, is theirs:
|
||||
// a new conversation started elsewhere (another tab, a skill switch)
|
||||
// must not wipe a message they have not sent yet.
|
||||
// a new conversation started elsewhere (another tab) must not wipe a message they have not sent yet.
|
||||
page.local.chat = { ...freshChat(), history: page.local.chat.history, draft: page.local.chat.draft, images: page.local.chat.images, about: null, conversation: conv };
|
||||
page.chatError = "";
|
||||
page.askRowCount = 0;
|
||||
@@ -996,13 +1010,20 @@ function renderMeter() {
|
||||
// a command to copy into a new conversation.
|
||||
const fresh = $("meter-fresh");
|
||||
fresh.hidden = page.meterFrame.level === "green";
|
||||
// The loop's agents run on; a new session mid-loop is the loop banner's Stop.
|
||||
const built = fresh.querySelector(".meter-fresh-btn");
|
||||
if (built) {
|
||||
built.disabled = loopDriving();
|
||||
built.title = loopDriving() ? "The loop is building. Stop it from the banner at the top of the window." : "";
|
||||
}
|
||||
if (fresh.hidden || fresh.dataset.built) return;
|
||||
fresh.dataset.built = "1";
|
||||
if (page.inApp) {
|
||||
// The same press as the app bar's New Session, confirm and all.
|
||||
const press = el("button", "btn small primary meter-fresh-btn", "Start a New Session");
|
||||
press.type = "button";
|
||||
press.addEventListener("click", () => tellApp("new-session"));
|
||||
press.addEventListener("click", () => !loopDriving() && tellApp("new-session"));
|
||||
press.disabled = loopDriving();
|
||||
fresh.append(press);
|
||||
return;
|
||||
}
|
||||
@@ -1050,7 +1071,9 @@ function renderChrome() {
|
||||
// The menu has no questions to count: an empty bar there reads as a stall.
|
||||
document.querySelector(".progress-block").hidden = (isDashboard() || page.S.workflow === "git") && !finish();
|
||||
$("progress-text").textContent = total
|
||||
? `${done} of ${total} ${building ? "done" : "answered"}`
|
||||
? loopDriving() && building
|
||||
? `${done} of ${total} tasks in this phase`
|
||||
: `${done} of ${total} ${building ? "done" : "answered"}`
|
||||
: h.stage || "Getting started";
|
||||
$("confidence").textContent = h.confidence || "";
|
||||
$("progress-fill").style.width = pct + "%";
|
||||
@@ -1087,6 +1110,10 @@ let moodVar = 0;
|
||||
const STRANDED_LINE =
|
||||
"Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval.";
|
||||
|
||||
// The agent is out of `wait` answering an Ask message (askBusy()), so a send
|
||||
// waits for it to finish that first.
|
||||
const ASK_BUSY_LINE = "Plan2Code is answering your Ask message. Your answers are saved, and it picks them up after that.";
|
||||
|
||||
// A finished screen's press that nothing is collecting (pressStranded()).
|
||||
const PRESS_STRANDED_LINE =
|
||||
"Plan2Code is not running. Your choice is saved and waiting for it. If the terminal is idle, type **continue** there and it will pick it up; it may also be waiting for your permission approval.";
|
||||
@@ -1252,6 +1279,9 @@ export function renderStatus() {
|
||||
const hint = quiet && page.inApp ? APPROVAL_HINT_IN_APP : quiet;
|
||||
return say("work", hint || activity() || "Plan2Code is thinking…", fmtMs(workingMs()), true, Boolean(hint));
|
||||
}
|
||||
// Only once something is waiting on it, and nothing else is theirs to answer:
|
||||
// with a card still open, "Sent. N still for you" is the truer line.
|
||||
if (askBusy() && !myTurn().length && (page.pendingResult || awaitingReply().length)) return say("work", ASK_BUSY_LINE, "", true);
|
||||
// Between pressing Send and the agent picking it up, the agent's own status
|
||||
// is still "waiting" because it has not started yet. Reading that as "your
|
||||
// turn" told someone who had just answered everything that the ball was back
|
||||
@@ -1520,6 +1550,7 @@ function paintMain(main) {
|
||||
// falls through to the ordinary path below, which hands it the card.
|
||||
if (isDashboard() && !finish()) {
|
||||
if (page.local.launching) renderLaunching(main);
|
||||
else if (page.loopSetup) renderLoopSetup(main);
|
||||
else if (page.dashPick) {
|
||||
// A spec-switch under an open confirm can gray the pick out. Rather
|
||||
// than offer START on a card that cannot launch, drop back to the
|
||||
@@ -1559,6 +1590,15 @@ function paintMain(main) {
|
||||
return;
|
||||
}
|
||||
|
||||
// How the Implementation Loop ended, from the app's `loopEnd`: its own
|
||||
// screen, ahead of any card the last phase left behind.
|
||||
if (page.S.loopEnd && !finish()) {
|
||||
const card = renderLoopEnd(page.S.loopEnd);
|
||||
card.classList.add("is-primary");
|
||||
main.appendChild(card);
|
||||
return;
|
||||
}
|
||||
|
||||
const list = asked();
|
||||
if (!list.length) {
|
||||
// A session can end before it asked anything at all (a build that needed
|
||||
@@ -1620,6 +1660,9 @@ export function renderFooter() {
|
||||
if (foot) foot.classList.toggle("is-dash", Boolean(isDashboard() && !finish()));
|
||||
// A finished dashboard keeps its summary line but still has nothing to send.
|
||||
if (foot) foot.classList.toggle("is-dash-done", Boolean(isDashboard() && finish()));
|
||||
// A loop at work has nothing for the person to send, so no Send to suggest
|
||||
// otherwise; it comes back the moment a question waits.
|
||||
if (foot) foot.classList.toggle("is-loop-idle", loopDriving() && !loopWaiting() && !finish());
|
||||
|
||||
const summary = $("footer-summary");
|
||||
const notes = pendingNotes();
|
||||
@@ -1904,13 +1947,16 @@ export async function send() {
|
||||
e.status = res.status;
|
||||
throw e;
|
||||
}
|
||||
// Ask locks again once the loop's question is answered (FR-14); it opens
|
||||
// for the next, different one.
|
||||
if (loopWaiting()) page.local.askLockedAfterSend = loopWaitingKey();
|
||||
markSent(payload);
|
||||
banner("Sent. Plan2Code is picking it up now.", "good");
|
||||
setTimeout(() => banner(null), 4000);
|
||||
// A menu option the agent marked `fresh` is a clean start, which under the
|
||||
// app is the bar's New Session; the agent still gets the pick, so a
|
||||
// declined confirm carries on with its usual finish.
|
||||
const freshMenu = page.inApp ? freshMenuPick(actions) : null;
|
||||
const freshMenu = page.inApp && !loopDriving() ? freshMenuPick(actions) : null;
|
||||
if (freshMenu) startNewSession(freshMenu.command ? handoffText({ command: freshMenu.command }) : "");
|
||||
} catch (err) {
|
||||
if (err && err.pending) {
|
||||
@@ -2108,8 +2154,9 @@ export function wireChrome() {
|
||||
// Escape is the confirm pane's Back — but not while a dialog has it. Native
|
||||
// dialogs close themselves on the same key; backing out of the pick at the
|
||||
// same time would be two undos for one press.
|
||||
if (e.key === "Escape" && page.dashPick && isDashboard() && !finish() && !document.querySelector("dialog[open]")) {
|
||||
if (e.key === "Escape" && (page.dashPick || page.loopSetup) && isDashboard() && !finish() && !document.querySelector("dialog[open]")) {
|
||||
page.dashPick = null;
|
||||
page.loopSetup = null;
|
||||
redraw();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -9,11 +9,12 @@ import {
|
||||
handoffList,
|
||||
loadOverview,
|
||||
finish,
|
||||
loopDriving,
|
||||
} from "../selectors.js";
|
||||
import { hooks, page, redraw, saveNow } from "../state.js";
|
||||
import { el, approvalTip, mdInto, releasesLink, copyButton, lightDismiss } from "../render.js";
|
||||
import { needsRoleNudge, ROLE_NOT_SET } from "../starters.js";
|
||||
import { looks, renderSwatches, saveLooks } from "../looks.js";
|
||||
import { looks, saveLooks } from "../looks.js";
|
||||
import { RED_BANNER, RED_BANNER_IN_APP } from "../meter.js";
|
||||
import {
|
||||
dashNoteKind,
|
||||
@@ -23,6 +24,8 @@ import {
|
||||
CATALOG_GROUPS,
|
||||
SKILL_CATALOG,
|
||||
catalogEntry,
|
||||
LOOP_ENTRY,
|
||||
OUTSIDE_APP_LINE,
|
||||
launchVariant,
|
||||
SPEC_STATE_LABELS,
|
||||
chipDetail,
|
||||
@@ -74,7 +77,6 @@ function roleNudge() {
|
||||
const setUp = el("button", "btn small primary", "Set up preferences");
|
||||
setUp.type = "button";
|
||||
setUp.addEventListener("click", () => {
|
||||
renderSwatches();
|
||||
// Closed without a role is a "Not now" too: having been to the dialog,
|
||||
// they were asked, and the banner does not come back (Help says so).
|
||||
$("looks-modal").addEventListener(
|
||||
@@ -88,7 +90,7 @@ function roleNudge() {
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
$("looks-modal").showModal();
|
||||
hooks.openPrefs("appearance");
|
||||
});
|
||||
const notNow = el("button", "btn tiny ghost", "Not now");
|
||||
notNow.type = "button";
|
||||
@@ -243,12 +245,16 @@ export function renderDashboard(main) {
|
||||
let shown = 0;
|
||||
for (const g of CATALOG_GROUPS) {
|
||||
const entries = SKILL_CATALOG.filter((e) => e.group === g.id && (!hide || available(e)));
|
||||
if (!entries.length) continue;
|
||||
shown += entries.length;
|
||||
// The desktop app's Implementation Loop card closes its group. Outside the
|
||||
// app it is always drawn, grayed, so the feature can be found.
|
||||
const loopCard = LOOP_ENTRY && LOOP_ENTRY.group === g.id && (!page.inApp || !hide || available(LOOP_ENTRY));
|
||||
if (!entries.length && !loopCard) continue;
|
||||
shown += entries.length + (loopCard ? 1 : 0);
|
||||
const section = el("section", "dash-group");
|
||||
section.appendChild(el("h3", "dash-group-title", g.title));
|
||||
const grid = el("div", "dash-grid");
|
||||
for (const e of entries) grid.appendChild(dashCard(e, menu));
|
||||
if (loopCard) grid.appendChild(dashCard(LOOP_ENTRY, menu));
|
||||
section.appendChild(grid);
|
||||
wrap.appendChild(section);
|
||||
}
|
||||
@@ -664,7 +670,7 @@ async function readHandoff(h) {
|
||||
}
|
||||
|
||||
function dashCard(entry, menu) {
|
||||
const presentation = cardPresentation(entry, scan(), selSpec(), menu);
|
||||
const presentation = entry.appOnly ? loopPresentation(entry, menu) : cardPresentation(entry, scan(), selSpec(), menu);
|
||||
// The agent's `recommend` and detail describe the initially selected spec.
|
||||
// Other picker choices derive both from the scan, so stale context never
|
||||
// follows a person to a different spec or to "start from scratch". A grayed
|
||||
@@ -675,7 +681,7 @@ function dashCard(entry, menu) {
|
||||
"dash-card" + (presentation.recommended ? " is-suggested" : "") + (going ? " is-going" : "")
|
||||
);
|
||||
b.type = "button";
|
||||
b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || !presentation.on;
|
||||
b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || loopDriving() || !presentation.on;
|
||||
if (!presentation.on && presentation.reason) b.title = presentation.reason;
|
||||
|
||||
const head = el("span", "dash-card-head");
|
||||
@@ -693,12 +699,39 @@ function dashCard(entry, menu) {
|
||||
b.appendChild(foot);
|
||||
|
||||
b.addEventListener("click", () => {
|
||||
// The loop card opens its own setup screen instead of a confirm pane.
|
||||
if (entry.appOnly) return hooks.openLoopSetup(selSpec());
|
||||
page.dashPick = entry;
|
||||
redraw();
|
||||
});
|
||||
if (entry.appOnly) b.appendChild(loopHelpLink());
|
||||
return b;
|
||||
}
|
||||
|
||||
// The loop card is lit only inside the desktop app and, there, by the same
|
||||
// rule as Implement (a documented or building spec). Never recommended or
|
||||
// pre-selected: a person opts into running unattended.
|
||||
function loopPresentation(entry, menu) {
|
||||
if (!page.inApp) return { on: false, reason: OUTSIDE_APP_LINE, recommended: false, detail: "" };
|
||||
return { ...cardPresentation(entry, scan(), selSpec(), menu), recommended: false };
|
||||
}
|
||||
|
||||
// "How the loop works" on the card: a link inside a button is not allowed, so
|
||||
// it is a span that acts like one and keeps the click from opening the setup.
|
||||
function loopHelpLink() {
|
||||
const a = el("span", "dash-card-link", "How the loop works");
|
||||
a.setAttribute("role", "link");
|
||||
a.tabIndex = 0;
|
||||
const open = (e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
hooks.openHelpOn("loop");
|
||||
};
|
||||
a.addEventListener("click", open);
|
||||
a.addEventListener("keydown", (e) => (e.key === "Enter" || e.key === " ") && open(e));
|
||||
return a;
|
||||
}
|
||||
|
||||
// "Start with a note from your Notebook": the switch a lit card's confirm
|
||||
// pane offers when noteSwitchShows() says so. The pane is rebuilt on every
|
||||
// state frame, so what the person did lives here, keyed to the card and the
|
||||
@@ -806,8 +839,18 @@ function drawNoteBox(entry, box, cmdNote) {
|
||||
again();
|
||||
if (state.on && (state.tabs === null || state.failed)) refreshNoteTabs(state, true);
|
||||
});
|
||||
label.append(toggle, el("span", null, "Start with a note from your Notebook"));
|
||||
box.appendChild(label);
|
||||
label.append(toggle, el("span", "confirm-note-switch-text", "Start with a note from your Notebook"));
|
||||
// A callout row, so the switch stands out under the card's long text; the
|
||||
// hint sits outside the label to keep the checkbox's name short.
|
||||
const head = el("div", "confirm-note-head" + (state.on ? " is-on" : ""));
|
||||
head.appendChild(label);
|
||||
if (!state.on) {
|
||||
const hint = el("span", "confirm-note-hint", "Hand it a tab you wrote earlier, with its pictures.");
|
||||
hint.id = "confirm-note-hint";
|
||||
toggle.setAttribute("aria-describedby", hint.id);
|
||||
head.appendChild(hint);
|
||||
}
|
||||
box.appendChild(head);
|
||||
|
||||
const picked = state.on && state.tabs ? state.tabs.find((t) => t.id === state.picked && t.read) : null;
|
||||
cmdNote.textContent = picked ? " + note: " + picked.name : "";
|
||||
@@ -834,11 +877,11 @@ function drawNoteBox(entry, box, cmdNote) {
|
||||
b.setAttribute("aria-pressed", String(t.id === state.picked));
|
||||
b.appendChild(el("span", "confirm-note-tab-name", t.name));
|
||||
if (t.sent) {
|
||||
const badge = el("span", "notepad-sent-badge", "sent");
|
||||
const badge = el("span", "notepad-sent-badge", "previously sent");
|
||||
badge.setAttribute("aria-hidden", "true");
|
||||
b.appendChild(badge);
|
||||
}
|
||||
b.setAttribute("aria-label", t.name + (t.sent ? ", sent" : "") + (empty ? ", empty" : ""));
|
||||
b.setAttribute("aria-label", t.name + (t.sent ? ", previously sent" : "") + (empty ? ", empty" : ""));
|
||||
if (empty) b.title = t.read ? "This tab has no text or pictures." : "This tab could not be read.";
|
||||
b.addEventListener("click", () => {
|
||||
if (state.picked === t.id) return;
|
||||
@@ -985,7 +1028,6 @@ export function renderConfirm(main, entry) {
|
||||
const cmdNote = el("span", "confirm-cmd-note");
|
||||
cmdNote.hidden = true;
|
||||
if (noteSwitchShows(entry, scan(), selSpec())) {
|
||||
pane.appendChild(el("hr", "confirm-rule"));
|
||||
const box = el("div", "confirm-note-box");
|
||||
// Which control in the box has the focus, so a rebuild of the whole pane
|
||||
// can hand it back (see the end of this function).
|
||||
@@ -1032,7 +1074,7 @@ export function renderConfirm(main, entry) {
|
||||
// A pick is a send like a brief or a stop: it names no question, so `__launch`
|
||||
// marks the action as being about the session, and it reaches the agent
|
||||
// through the same wait loop. The dashboard reads `skill` off it.
|
||||
async function launchSkill(entry) {
|
||||
export async function launchSkill(entry) {
|
||||
if (page.gone || page.pendingResult || page.local.launching || finish()) return;
|
||||
const target = launchTarget(entry, selSpec());
|
||||
// The card was clickable, so this should never fire — but a spec picked in
|
||||
|
||||
@@ -42,9 +42,14 @@ import {
|
||||
agentWorking,
|
||||
awaitingReply,
|
||||
isDashboard,
|
||||
loopDriving,
|
||||
} from "../selectors.js";
|
||||
|
||||
// What the session buttons say while the Implementation Loop drives: its own
|
||||
// strip in the app's top bar stops it, not this page.
|
||||
const LOOP_LOCK_TITLE = "The loop is building. Stop it from the banner at the top of the window.";
|
||||
import { docSavedNote, downloadDoc } from "../doc-files.js";
|
||||
import { startNewSession } from "../app-bridge.js";
|
||||
import { startNewSession, tellApp } from "../app-bridge.js";
|
||||
import { pendingNotes } from "../uploads.js";
|
||||
|
||||
// The end of the session, and the only screen in this page whose job is to
|
||||
@@ -152,7 +157,110 @@ function closeGuideHeld() {
|
||||
return ["review", "commit", "changelog", "dashboard", "launch"].includes(page.local.afterBuild) || reviewPending() === "asked";
|
||||
}
|
||||
|
||||
// Which stop-screen button was pressed and is waiting on the app's answer, so a
|
||||
// second press cannot send the same request twice.
|
||||
let loopPressed = null;
|
||||
|
||||
const LOOP_BUTTONS = [
|
||||
["resume", "loop-resume", "Resume the loop", "primary"],
|
||||
["fix", "loop-fix", "Fix it by hand", ""],
|
||||
["finalize", "loop-finalize", "Finalize", "primary"],
|
||||
];
|
||||
|
||||
function shortHash(h) {
|
||||
return typeof h === "string" ? h.slice(0, 7) : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* How the Implementation Loop ended, drawn from the app's `loopEnd`: a stop
|
||||
* (why, what was committed, what is left uncommitted, what can be done next) or
|
||||
* a finish (every phase built, its commit, and a count of each kind of decision
|
||||
* its agent made; the report behind the button holds them all).
|
||||
*/
|
||||
export function renderLoopEnd(end) {
|
||||
const card = el("article", "card handoff loop-end");
|
||||
const finished = end.kind === "finished";
|
||||
card.appendChild(el("p", "card-kicker", finished ? "Loop finished" : "Loop stopped"));
|
||||
card.appendChild(el("h2", null, finished ? "Every phase is built" : end.line));
|
||||
if (finished && end.line) card.appendChild(el("p", "loop-line", end.line));
|
||||
|
||||
const evidence = end.evidence && docs().find((d) => d.id === end.evidence);
|
||||
if (evidence) {
|
||||
const read = el("button", "btn small", finished ? "Read the full report" : "Read why, and the report so far");
|
||||
read.type = "button";
|
||||
read.addEventListener("click", () => {
|
||||
page.view = "doc:" + evidence.id;
|
||||
redraw();
|
||||
});
|
||||
card.appendChild(read);
|
||||
}
|
||||
|
||||
const phases = Array.isArray(end.phases) ? end.phases : [];
|
||||
if (phases.length) {
|
||||
const table = el("table", "loop-end-phases");
|
||||
const head = el("tr");
|
||||
const cols = finished ? ["Phase", "Commit", "Fixed", "Not fixed", "Left open", "Assumed", "Other decisions", "Retries"] : ["Phase", "Commit"];
|
||||
for (const c of cols) head.appendChild(el("th", null, c));
|
||||
table.appendChild(head);
|
||||
for (const ph of phases) {
|
||||
const row = el("tr");
|
||||
row.appendChild(el("td", null, `Phase ${ph.n}: ${ph.name}`));
|
||||
const commit = el("td");
|
||||
if (ph.commit) commit.appendChild(el("code", null, shortHash(ph.commit)));
|
||||
else commit.textContent = "not committed";
|
||||
row.appendChild(commit);
|
||||
if (finished) {
|
||||
for (const count of [ph.fixed, ph.skipped, ph.left, ph.assumed, ph.decisions, ph.retries]) {
|
||||
row.appendChild(el("td", null, String(count ?? 0)));
|
||||
}
|
||||
}
|
||||
table.appendChild(row);
|
||||
}
|
||||
card.appendChild(table);
|
||||
}
|
||||
|
||||
const files = Array.isArray(end.uncommitted) ? end.uncommitted : [];
|
||||
if (files.length) {
|
||||
card.appendChild(el("h3", null, "Uncommitted in this phase"));
|
||||
const list = el("ul", "loop-end-files");
|
||||
const fill = (items, into) => items.forEach((f) => into.appendChild(el("li", null, f)));
|
||||
fill(files.slice(0, 10), list);
|
||||
if (files.length > 10) {
|
||||
const more = el("details");
|
||||
more.appendChild(el("summary", null, `${files.length - 10} more files`));
|
||||
const rest = el("ul", "loop-end-files");
|
||||
fill(files.slice(10), rest);
|
||||
more.appendChild(rest);
|
||||
card.append(list, more);
|
||||
} else {
|
||||
card.appendChild(list);
|
||||
}
|
||||
}
|
||||
|
||||
const can = Array.isArray(end.can) ? end.can : [];
|
||||
const actions = el("div", "loop-end-actions");
|
||||
for (const [key, message, label, kind] of LOOP_BUTTONS) {
|
||||
if (!can.includes(key)) continue;
|
||||
const b = el("button", "btn" + (kind ? " " + kind : ""), label);
|
||||
b.type = "button";
|
||||
b.disabled = page.gone || (loopPressed === message && !page.loopAction);
|
||||
b.addEventListener("click", () => {
|
||||
loopPressed = message;
|
||||
page.loopAction = null;
|
||||
tellApp(message);
|
||||
redraw();
|
||||
});
|
||||
actions.appendChild(b);
|
||||
}
|
||||
if (actions.childElementCount) card.appendChild(actions);
|
||||
if (page.loopAction && !page.loopAction.ok) {
|
||||
card.appendChild(el("p", "loop-error", page.loopAction.error));
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
export function renderHandoff(fin) {
|
||||
if (page.S && page.S.loopEnd) return renderLoopEnd(page.S.loopEnd);
|
||||
const card = el("article", "card handoff");
|
||||
card.appendChild(el("p", "card-kicker", finishPaused(fin) ? "Session paused" : "Session ended"));
|
||||
card.appendChild(el("h2", null, fin.headline));
|
||||
@@ -586,8 +694,8 @@ export function renderStopButton() {
|
||||
const gate = turnGate({ gone: page.gone, pendingResult: page.pendingResult, waiting: agentHasTheBall() });
|
||||
// A way home in flight holds Stop back too, unless the agent went quiet
|
||||
// after collecting it: Stop's resume screen is then the only way out.
|
||||
b.disabled = Boolean(gate) || (Boolean(page.local.homeward) && !agentAdrift());
|
||||
b.title = {
|
||||
b.disabled = Boolean(gate) || (Boolean(page.local.homeward) && !agentAdrift()) || loopDriving();
|
||||
b.title = loopDriving() ? LOOP_LOCK_TITLE : {
|
||||
gone: "Not connected right now.",
|
||||
pending: "Your last answers are still being picked up. You can stop once they have been.",
|
||||
waiting: "Plan2Code is working on your answers. You can stop once it replies.",
|
||||
@@ -617,8 +725,8 @@ export function renderHomeButton() {
|
||||
warned: Boolean(page.S) && Boolean(stopWarning()),
|
||||
});
|
||||
b.hidden = st.hidden;
|
||||
b.disabled = st.disabled;
|
||||
b.title = st.title;
|
||||
b.disabled = st.disabled || loopDriving();
|
||||
b.title = loopDriving() ? LOOP_LOCK_TITLE : st.title;
|
||||
}
|
||||
|
||||
function openHomeConfirm() {
|
||||
|
||||
@@ -4,7 +4,8 @@ import { looksReady, looks, saveLooks } from "../looks.js";
|
||||
import { page } from "../state.js";
|
||||
import { isDashboard, finish, agentAdrift } from "../selectors.js";
|
||||
import { releasesLink, el, copyButton, lightDismiss } from "../render.js";
|
||||
import { HELP_TABS, helpTabFor, helpKeyTarget } from "../help.js";
|
||||
import { HELP_TABS, helpTabFor } from "../help.js";
|
||||
import { wireTabs } from "../tabs.js";
|
||||
import { CATALOG_GROUPS, SKILL_CATALOG } from "../answers.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
@@ -196,6 +197,8 @@ function renderAppWording(root) {
|
||||
}
|
||||
|
||||
let helpBuilt = false;
|
||||
// The tabs, wired by tabs.js once the content is built.
|
||||
let helpTabs = null;
|
||||
|
||||
async function renderHelpVersion() {
|
||||
const slot = $("help-version");
|
||||
@@ -261,43 +264,31 @@ function buildHelp() {
|
||||
const code = row.querySelector("code");
|
||||
row.appendChild(copyButton(code.textContent, "btn small handoff-copy", code));
|
||||
}
|
||||
for (const t of HELP_TABS) {
|
||||
const btn = el("button", "help-tab");
|
||||
btn.type = "button";
|
||||
btn.id = "help-tab-" + t.id;
|
||||
btn.setAttribute("role", "tab");
|
||||
btn.setAttribute("aria-controls", "help-panel-" + t.id);
|
||||
btn.setAttribute("aria-selected", "false");
|
||||
btn.tabIndex = -1;
|
||||
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
svg.setAttribute("class", "help-tab-icon");
|
||||
svg.setAttribute("aria-hidden", "true");
|
||||
const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
|
||||
use.setAttribute("href", "#hi-" + t.id);
|
||||
svg.appendChild(use);
|
||||
btn.appendChild(svg);
|
||||
btn.appendChild(el("span", null, t.label));
|
||||
btn.addEventListener("click", () => selectHelpTab(t.id));
|
||||
tabs.appendChild(btn);
|
||||
const panel = panels.querySelector(`section.help-panel[data-tab="${t.id}"]`);
|
||||
panel.id = "help-panel-" + t.id;
|
||||
panel.setAttribute("role", "tabpanel");
|
||||
panel.setAttribute("aria-labelledby", "help-tab-" + t.id);
|
||||
panel.tabIndex = 0;
|
||||
panel.hidden = true;
|
||||
}
|
||||
helpTabs = wireTabs({
|
||||
tabs: HELP_TABS,
|
||||
list: tabs,
|
||||
panels,
|
||||
prefix: "help",
|
||||
tabClass: "help-tab",
|
||||
renderTab: (t, btn) => {
|
||||
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
svg.setAttribute("class", "help-tab-icon");
|
||||
svg.setAttribute("aria-hidden", "true");
|
||||
const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
|
||||
use.setAttribute("href", "#hi-" + t.id);
|
||||
svg.appendChild(use);
|
||||
btn.appendChild(svg);
|
||||
btn.appendChild(el("span", null, t.label));
|
||||
},
|
||||
onSelect: () => {
|
||||
$("help-panels").scrollTop = 0;
|
||||
},
|
||||
});
|
||||
helpBuilt = true;
|
||||
}
|
||||
|
||||
export function selectHelpTab(id) {
|
||||
for (const t of HELP_TABS) {
|
||||
const on = t.id === id;
|
||||
const btn = $("help-tab-" + t.id);
|
||||
btn.setAttribute("aria-selected", String(on));
|
||||
btn.tabIndex = on ? 0 : -1;
|
||||
$("help-panel-" + t.id).hidden = !on;
|
||||
}
|
||||
$("help-panels").scrollTop = 0;
|
||||
helpTabs.select(id);
|
||||
}
|
||||
|
||||
export function openHelp() {
|
||||
@@ -372,14 +363,6 @@ export function wireHelp() {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
if (!e.target.classList || !e.target.classList.contains("help-tab")) return;
|
||||
const current = HELP_TABS.findIndex((t) => "help-tab-" + t.id === e.target.id);
|
||||
const n = helpKeyTarget(e.key, current, HELP_TABS.length);
|
||||
if (n < 0) return;
|
||||
e.preventDefault();
|
||||
selectHelpTab(HELP_TABS[n].id);
|
||||
$("help-tab-" + HELP_TABS[n].id).focus();
|
||||
});
|
||||
}
|
||||
@@ -1,444 +1,19 @@
|
||||
// Plan2Code Web Console - User Preferences: looks, sounds and the launcher's model menus.
|
||||
// Plan2Code Web Console - User Preferences: the look and sound controls. The
|
||||
// Agents & models tab is agents-view.js's.
|
||||
|
||||
import { adoptLooks, applyLooks, loadLooks, looks, renderSwatches, resetLooks, saveLooks, syncLooks } from "../looks.js";
|
||||
import { adoptLooks, applyLooks, loadLooks, looks, renderSwatches, saveLooks, syncLooks } from "../looks.js";
|
||||
import { dropHeldSound, releaseHeldSound, sound, soundOn } from "../sound.js";
|
||||
import { hushTones, tone, unlockTones } from "../tones.js";
|
||||
import { hushMusic } from "../music.js";
|
||||
import { SOUND_EVENTS, soundKey } from "../palette.js";
|
||||
import { ROLES, ROLE_NOT_SET, ROLE_NOT_SET_LABEL, needsRoleNudge, normalizeRole } from "../starters.js";
|
||||
import { isDashboard } from "../selectors.js";
|
||||
import { el, lightDismiss } from "../render.js";
|
||||
import { page, redraw } from "../state.js";
|
||||
import { el } from "../render.js";
|
||||
import { hooks, page, redraw } from "../state.js";
|
||||
import { framed, onAppMessage, tellApp } from "../app-bridge.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
function setModelsStatus(text, isError) {
|
||||
const status = $("models-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
// Models: the launcher's menu. The built-in list ships with every install and is read-only
|
||||
// here; what the person adds is saved to the server, which the launcher reads on its next run.
|
||||
let modelsData = null;
|
||||
|
||||
// The CLIs the launcher reads a model list for, in tab order (routes.mjs MODEL_CLIS).
|
||||
const MODEL_CLIS = ["claude", "devin", "codex"];
|
||||
|
||||
let modelsTab = "claude";
|
||||
|
||||
function renderModels() {
|
||||
for (const cli of MODEL_CLIS) {
|
||||
$("models-tab-" + cli).setAttribute("aria-pressed", String(cli === modelsTab));
|
||||
}
|
||||
const shipped = $("models-shipped");
|
||||
const user = $("models-user");
|
||||
shipped.replaceChildren();
|
||||
user.replaceChildren();
|
||||
if (!modelsData) {
|
||||
setModelsStatus("Models could not be loaded.", true);
|
||||
return;
|
||||
}
|
||||
for (const m of modelsData.shipped[modelsTab] || []) {
|
||||
const row = el("div", "models-row locked");
|
||||
row.append(el("span", null, m.id), el("span", null, m.label || ""));
|
||||
shipped.appendChild(row);
|
||||
}
|
||||
const mine = modelsData.user[modelsTab];
|
||||
mine.forEach((m, i) => {
|
||||
const row = el("div", "models-row");
|
||||
const id = el("input");
|
||||
id.value = m.id;
|
||||
id.placeholder = "Model id";
|
||||
id.setAttribute("aria-label", "Model id");
|
||||
const label = el("input");
|
||||
label.value = m.label;
|
||||
label.placeholder = "Name shown in the menu";
|
||||
label.setAttribute("aria-label", "Name shown in the menu");
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
id.addEventListener("change", () => { m.id = id.value.trim(); saveModels(); });
|
||||
label.addEventListener("change", () => { m.label = label.value.trim(); saveModels(); });
|
||||
remove.addEventListener("click", () => {
|
||||
mine.splice(i, 1);
|
||||
saveModels();
|
||||
renderModels();
|
||||
});
|
||||
row.append(id, label, remove);
|
||||
user.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
async function saveModels() {
|
||||
try {
|
||||
const res = await fetch("/models", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ models: modelsData.user }),
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok) return setModelsStatus(body.error || "Could not save.", true);
|
||||
setModelsStatus("Saved. Restart plan2code to use it.", false);
|
||||
} catch {
|
||||
setModelsStatus("Could not save.", true);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadModelsData() {
|
||||
try {
|
||||
const res = await fetch("/models");
|
||||
if (res.ok) modelsData = await res.json();
|
||||
} catch {}
|
||||
renderModels();
|
||||
}
|
||||
|
||||
// Agents: CLIs Plan2Code did not find on its own, saved whole to ~/.plan2code/agents.json.
|
||||
// Each card edits its entry in place (unknown keys ride along untouched); every change
|
||||
// saves the whole list. A new card is not sent until it has a name and a command.
|
||||
let agentsData = [];
|
||||
|
||||
// The server's complaint about one card, drawn on it: { index, field, error } (index into agentsData).
|
||||
let agentsError = null;
|
||||
|
||||
// The entry whose Delete is waiting for a second click.
|
||||
let agentsConfirming = null;
|
||||
|
||||
// Every change saves, so two saves can be in flight at once: only the newest one's answer is drawn.
|
||||
let agentsSaveSeq = 0;
|
||||
|
||||
// The list as last loaded or saved, as sent: a change that leaves it the same (a field of a new
|
||||
// card still held back) sends nothing.
|
||||
let agentsLastSent = null;
|
||||
|
||||
function setAgentsStatus(text, isError) {
|
||||
const status = $("agents-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
function newAgent() {
|
||||
return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] };
|
||||
}
|
||||
|
||||
function agentField(label, field, child) {
|
||||
const wrap = el("div", "agent-field");
|
||||
wrap.dataset.field = field;
|
||||
wrap.append(el("span", null, label), child);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function agentInput(agent, key, label, placeholder, trim) {
|
||||
const input = el("input");
|
||||
input.value = agent[key] || "";
|
||||
input.placeholder = placeholder;
|
||||
input.setAttribute("aria-label", label);
|
||||
input.dataset.field = key;
|
||||
input.addEventListener("change", () => {
|
||||
agent[key] = trim ? input.value.trim() : input.value;
|
||||
saveAgents();
|
||||
});
|
||||
return input;
|
||||
}
|
||||
|
||||
// A list of text rows (arguments), with Remove on each and an Add under them.
|
||||
function agentArgsEditor(agent, key, label, placeholder, addLabel) {
|
||||
const box = el("div", "agent-rows");
|
||||
box.dataset.field = key;
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
agent[key].forEach((value, i) => {
|
||||
const row = el("div", "agent-row");
|
||||
const input = el("input");
|
||||
input.value = value;
|
||||
input.placeholder = placeholder;
|
||||
input.setAttribute("aria-label", label);
|
||||
input.dataset.field = key;
|
||||
input.addEventListener("change", () => { agent[key][i] = input.value.trim(); saveAgents(); });
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
remove.addEventListener("click", () => {
|
||||
agent[key].splice(i, 1);
|
||||
draw();
|
||||
saveAgents();
|
||||
});
|
||||
row.append(input, remove);
|
||||
box.appendChild(row);
|
||||
});
|
||||
const add = el("button", "btn small ghost", addLabel);
|
||||
add.type = "button";
|
||||
add.addEventListener("click", () => {
|
||||
agent[key].push("");
|
||||
draw();
|
||||
box.querySelector(".agent-row:last-of-type input")?.focus();
|
||||
});
|
||||
box.appendChild(add);
|
||||
};
|
||||
draw();
|
||||
return agentField(label, key, box);
|
||||
}
|
||||
|
||||
// The models list: an id and an optional name for the menu on each row.
|
||||
function agentModelsEditor(agent) {
|
||||
const box = el("div", "agent-rows");
|
||||
box.dataset.field = "models";
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
agent.models.forEach((m, i) => {
|
||||
const row = el("div", "agent-row model");
|
||||
const id = el("input");
|
||||
id.value = m.id || "";
|
||||
id.placeholder = "Model id, for {model}";
|
||||
id.setAttribute("aria-label", "Model id");
|
||||
id.dataset.field = "models";
|
||||
const label = el("input");
|
||||
label.value = m.label || "";
|
||||
label.placeholder = "Name shown in the menu (optional)";
|
||||
label.setAttribute("aria-label", "Name shown in the menu");
|
||||
label.dataset.field = "models";
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
id.addEventListener("change", () => { m.id = id.value.trim(); saveAgents(); });
|
||||
label.addEventListener("change", () => {
|
||||
const text = label.value.trim();
|
||||
if (text) m.label = text;
|
||||
else delete m.label;
|
||||
saveAgents();
|
||||
});
|
||||
remove.addEventListener("click", () => {
|
||||
agent.models.splice(i, 1);
|
||||
draw();
|
||||
saveAgents();
|
||||
});
|
||||
row.append(id, label, remove);
|
||||
box.appendChild(row);
|
||||
});
|
||||
const add = el("button", "btn small ghost", "Add a model");
|
||||
add.type = "button";
|
||||
add.addEventListener("click", () => {
|
||||
agent.models.push({ id: "" });
|
||||
draw();
|
||||
box.querySelector(".agent-row:last-of-type input")?.focus();
|
||||
});
|
||||
box.appendChild(add);
|
||||
};
|
||||
draw();
|
||||
return agentField("Models", "models", box);
|
||||
}
|
||||
|
||||
// Test, and Delete with its confirm step on the card itself (never the browser's confirm()).
|
||||
function agentFoot(agent) {
|
||||
const foot = el("div", "agent-foot");
|
||||
const test = el("button", "btn small", "Test");
|
||||
test.type = "button";
|
||||
const result = el("span", "help agent-test-result");
|
||||
result.setAttribute("role", "status");
|
||||
test.addEventListener("click", async () => {
|
||||
const command = String(agent.command || "").trim();
|
||||
if (!command) {
|
||||
result.textContent = "Type a command first.";
|
||||
return;
|
||||
}
|
||||
result.textContent = "Looking...";
|
||||
try {
|
||||
const res = await fetch("/agents/test", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ command }),
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok) result.textContent = body.error || "Could not test.";
|
||||
else result.textContent = body.found ? "Found at " + body.path : "Not found on PATH";
|
||||
} catch {
|
||||
result.textContent = "Could not test.";
|
||||
}
|
||||
});
|
||||
foot.append(test);
|
||||
if (agentsConfirming === agent) {
|
||||
const ask = el("span", "help", "Delete this agent?");
|
||||
const yes = el("button", "btn small danger", "Yes, delete");
|
||||
yes.type = "button";
|
||||
const keep = el("button", "btn small ghost", "Keep");
|
||||
keep.type = "button";
|
||||
yes.addEventListener("click", async () => {
|
||||
agentsConfirming = null;
|
||||
agentsData.splice(agentsData.indexOf(agent), 1);
|
||||
agentsError = null;
|
||||
renderAgents();
|
||||
await saveAgents();
|
||||
});
|
||||
keep.addEventListener("click", () => {
|
||||
agentsConfirming = null;
|
||||
renderAgents();
|
||||
});
|
||||
foot.append(ask, yes, keep);
|
||||
} else {
|
||||
const del = el("button", "btn small ghost danger", "Delete");
|
||||
del.type = "button";
|
||||
del.addEventListener("click", () => {
|
||||
agentsConfirming = agent;
|
||||
renderAgents();
|
||||
});
|
||||
foot.append(del);
|
||||
}
|
||||
foot.append(result);
|
||||
return foot;
|
||||
}
|
||||
|
||||
// Which field or button has focus, so a redraw (an id assigned, an error marked) puts the
|
||||
// person back where they were, with what they had typed: { card, nth, value, start, end }.
|
||||
const AGENT_FOCUSABLE = "input, button";
|
||||
|
||||
function agentsFocus(list) {
|
||||
const active = document.activeElement;
|
||||
const card = active && list.contains(active) ? active.closest(".agent-card") : null;
|
||||
if (!card) return null;
|
||||
const at = { card: [...list.children].indexOf(card), nth: [...card.querySelectorAll(AGENT_FOCUSABLE)].indexOf(active) };
|
||||
if (active instanceof HTMLInputElement) Object.assign(at, { value: active.value, start: active.selectionStart, end: active.selectionEnd });
|
||||
return at;
|
||||
}
|
||||
|
||||
function restoreAgentsFocus(list, at) {
|
||||
const card = at && list.children[at.card];
|
||||
const target = card && card.querySelectorAll(AGENT_FOCUSABLE)[at.nth];
|
||||
if (!target) return;
|
||||
if (!(target instanceof HTMLInputElement) || at.value === undefined) {
|
||||
target.focus();
|
||||
return;
|
||||
}
|
||||
const drawn = target.value;
|
||||
target.value = at.value;
|
||||
target.focus();
|
||||
try {
|
||||
target.setSelectionRange(at.start, at.end);
|
||||
} catch {}
|
||||
// Text typed before the redraw is not in agentsData yet, and the browser fires no change
|
||||
// for a value set from script, so leaving the field sends it on.
|
||||
if (at.value !== drawn) target.addEventListener("blur", () => target.dispatchEvent(new Event("change")), { once: true });
|
||||
}
|
||||
|
||||
function renderAgents() {
|
||||
const list = $("agents-list");
|
||||
const focus = agentsFocus(list);
|
||||
list.replaceChildren();
|
||||
agentsData.forEach((agent, i) => {
|
||||
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) {
|
||||
if (!Array.isArray(agent[key])) agent[key] = [];
|
||||
}
|
||||
const card = el("div", "agent-card");
|
||||
const top = el("div", "agent-top");
|
||||
top.append(
|
||||
agentField("Name", "name", agentInput(agent, "name", "Name", "Name shown in the menu", true)),
|
||||
agentField("Command", "command", agentInput(agent, "command", "Command", "Program to run, such as myagent", true)),
|
||||
);
|
||||
card.append(
|
||||
top,
|
||||
agentArgsEditor(agent, "args", "Arguments", "--message={prompt}", "Add an argument"),
|
||||
agentField("Start prompt", "prompt", agentInput(agent, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
|
||||
agentArgsEditor(agent, "bypassArgs", "Bypass arguments", "--yes-always", "Add an argument"),
|
||||
agentArgsEditor(agent, "modelArgs", "Model arguments", "--model={model}", "Add an argument"),
|
||||
agentModelsEditor(agent),
|
||||
);
|
||||
if (agentsError && agentsError.index === i) {
|
||||
card.classList.add("invalid");
|
||||
for (const input of card.querySelectorAll("input")) {
|
||||
if (input.dataset.field === agentsError.field) input.classList.add("invalid");
|
||||
}
|
||||
card.appendChild(el("p", "agent-error", agentsError.error));
|
||||
}
|
||||
card.appendChild(agentFoot(agent));
|
||||
list.appendChild(card);
|
||||
});
|
||||
restoreAgentsFocus(list, focus);
|
||||
}
|
||||
|
||||
// The list as the server wants it: blank rows dropped, and a new card without both a name and
|
||||
// a command (one still being typed) left out, so its first field is not refused as half an
|
||||
// agent. `kept` maps each sent entry back to its place.
|
||||
function agentsPayload() {
|
||||
const kept = [];
|
||||
const agents = [];
|
||||
agentsData.forEach((a, i) => {
|
||||
if (!a.id && (!String(a.name || "").trim() || !String(a.command || "").trim())) return;
|
||||
kept.push(i);
|
||||
agents.push({
|
||||
...a,
|
||||
args: a.args.filter((v) => v !== ""),
|
||||
bypassArgs: a.bypassArgs.filter((v) => v !== ""),
|
||||
modelArgs: a.modelArgs.filter((v) => v !== ""),
|
||||
models: a.models.filter((m) => m.id),
|
||||
});
|
||||
});
|
||||
return { kept, agents };
|
||||
}
|
||||
|
||||
// `replace` is the person's Save anyway, over a file holding entries this page could not read.
|
||||
async function saveAgents({ replace = false } = {}) {
|
||||
const { kept, agents } = agentsPayload();
|
||||
const sent = JSON.stringify(agents);
|
||||
if (!replace && agentsError === null && sent === agentsLastSent) return;
|
||||
const seq = ++agentsSaveSeq;
|
||||
try {
|
||||
const res = await fetch("/agents", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(replace ? { agents, replace: true } : { agents }),
|
||||
});
|
||||
const body = await res.json();
|
||||
if (seq !== agentsSaveSeq) return;
|
||||
if (res.status === 409) {
|
||||
const warnings = Array.isArray(body.warnings) ? body.warnings : [];
|
||||
setAgentsStatus([body.error || "Not saved.", ...warnings].join(" "), true);
|
||||
$("agents-replace").hidden = false;
|
||||
return;
|
||||
}
|
||||
$("agents-replace").hidden = true;
|
||||
if (!res.ok) {
|
||||
const at = Number.isInteger(body.index) ? kept[body.index] : undefined;
|
||||
agentsError = at === undefined ? null : { index: at, field: body.field, error: body.error || "Could not save." };
|
||||
setAgentsStatus(at === undefined ? body.error || "Could not save." : "Not saved. Fix the marked agent.", true);
|
||||
renderAgents();
|
||||
return;
|
||||
}
|
||||
// Ids are assigned on the first save: take the server's entries, and redraw only then
|
||||
// (or to clear a mark), so typing in another card is not interrupted.
|
||||
const fresh = agents.some((a) => !a.id) || agentsError !== null;
|
||||
agentsError = null;
|
||||
agentsLastSent = sent;
|
||||
setAgentsStatus("Saved.", false);
|
||||
if (fresh) {
|
||||
kept.forEach((at, n) => { agentsData[at] = body.agents[n]; });
|
||||
agentsLastSent = JSON.stringify(agentsPayload().agents);
|
||||
renderAgents();
|
||||
}
|
||||
} catch {
|
||||
if (seq === agentsSaveSeq) setAgentsStatus("Could not save.", true);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAgents() {
|
||||
agentsError = null;
|
||||
agentsConfirming = null;
|
||||
agentsLastSent = null;
|
||||
$("agents-replace").hidden = true;
|
||||
try {
|
||||
const res = await fetch("/agents");
|
||||
if (res.ok) {
|
||||
const body = await res.json();
|
||||
agentsData = Array.isArray(body.agents) ? body.agents : [];
|
||||
for (const agent of agentsData) {
|
||||
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = [];
|
||||
}
|
||||
agentsLastSent = JSON.stringify(agentsPayload().agents);
|
||||
const warnings = Array.isArray(body.warnings) ? body.warnings : [];
|
||||
setAgentsStatus(warnings.join(" "), warnings.length > 0);
|
||||
} else {
|
||||
setAgentsStatus("Agents could not be loaded.", true);
|
||||
}
|
||||
} catch {
|
||||
setAgentsStatus("Agents could not be loaded.", true);
|
||||
}
|
||||
renderAgents();
|
||||
}
|
||||
|
||||
// Following the system, the saved looks painted before anything is drawn, and
|
||||
// the sound cues let go on the next touch. `boot` is the page's boot data.
|
||||
export function startLooks(boot) {
|
||||
@@ -461,25 +36,15 @@ export function startLooks(boot) {
|
||||
}
|
||||
}
|
||||
|
||||
// Preferences' buttons and fields.
|
||||
// The fieldset a control sits in, for the Saved mark beside its legend.
|
||||
const fieldsetOf = (node) => node.closest("fieldset");
|
||||
|
||||
// Preferences' look and sound fields. Opening and closing the dialog, its tabs
|
||||
// and Back to default are prefs-dialog.js's.
|
||||
export function wireLooks() {
|
||||
lightDismiss($("looks-modal"));
|
||||
$("btn-looks").addEventListener("click", () => {
|
||||
renderSwatches();
|
||||
setModelsStatus("", false);
|
||||
loadModelsData();
|
||||
loadAgents();
|
||||
$("looks-modal").showModal();
|
||||
});
|
||||
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
||||
$("looks-modal").addEventListener("close", () => {
|
||||
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) redraw();
|
||||
});
|
||||
$("looks-reset").addEventListener("click", () => {
|
||||
resetLooks();
|
||||
saveLooks();
|
||||
redraw();
|
||||
});
|
||||
for (const [value, label] of [[ROLE_NOT_SET, ROLE_NOT_SET_LABEL], ...ROLES.map((r) => [r.id, r.label])]) {
|
||||
const option = el("option", null, label);
|
||||
option.value = value;
|
||||
@@ -487,7 +52,7 @@ export function wireLooks() {
|
||||
}
|
||||
$("looks-role").addEventListener("change", (e) => {
|
||||
looks.role = normalizeRole(e.target.value);
|
||||
saveLooks();
|
||||
hooks.markSaved(fieldsetOf(e.target), saveLooks());
|
||||
// The dashboard banner, and the starter templates and Ask starters on any
|
||||
// page, all order themselves by the role.
|
||||
if (page.S) redraw();
|
||||
@@ -495,13 +60,13 @@ export function wireLooks() {
|
||||
for (const radio of document.querySelectorAll('input[name="looks-theme"]')) {
|
||||
radio.addEventListener("change", () => {
|
||||
looks.theme = radio.value;
|
||||
saveLooks();
|
||||
hooks.markSaved(fieldsetOf(radio), saveLooks());
|
||||
});
|
||||
}
|
||||
for (const radio of document.querySelectorAll('input[name="looks-width"]')) {
|
||||
radio.addEventListener("change", () => {
|
||||
looks.width = radio.value;
|
||||
saveLooks();
|
||||
hooks.markSaved(fieldsetOf(radio), saveLooks());
|
||||
});
|
||||
}
|
||||
$("looks-sound").addEventListener("change", (e) => {
|
||||
@@ -509,15 +74,31 @@ export function wireLooks() {
|
||||
// Held cues are moments, not mail: muted, they are dropped rather than
|
||||
// saved up to fire all at once the next time sound comes back on.
|
||||
if (!looks.sound) dropHeldSound();
|
||||
saveLooks();
|
||||
hooks.markSaved(fieldsetOf(e.target), saveLooks());
|
||||
// Turning them on is the one change you can hear: the question chime, or
|
||||
// the first cue still ticked when that one is not.
|
||||
const preview = ["question", ...Object.keys(SOUND_EVENTS)].find(soundOn);
|
||||
if (preview) sound(preview);
|
||||
});
|
||||
// The games' sounds: off silences a game playing now; on plays a blip.
|
||||
$("looks-activity-sounds").addEventListener("change", (e) => {
|
||||
looks.activitySounds = e.target.checked;
|
||||
if (!looks.activitySounds) hushTones();
|
||||
hooks.markSaved(fieldsetOf(e.target), saveLooks());
|
||||
if (looks.activitySounds) {
|
||||
unlockTones();
|
||||
tone("go");
|
||||
}
|
||||
});
|
||||
// The games' music: off stops a track playing now.
|
||||
$("looks-game-music").addEventListener("change", (e) => {
|
||||
looks.gameMusic = e.target.checked;
|
||||
if (!looks.gameMusic) hushMusic();
|
||||
hooks.markSaved(fieldsetOf(e.target), saveLooks());
|
||||
});
|
||||
$("looks-activities").addEventListener("change", (e) => {
|
||||
looks.hideActivities = !e.target.checked;
|
||||
saveLooks();
|
||||
hooks.markSaved(fieldsetOf(e.target), saveLooks());
|
||||
// The die comes and goes with the next render, which also closes an open
|
||||
// Activities window, paused.
|
||||
redraw();
|
||||
@@ -527,40 +108,12 @@ export function wireLooks() {
|
||||
const event = box.dataset.sound;
|
||||
looks[soundKey(event)] = box.checked;
|
||||
if (!box.checked) dropHeldSound(event);
|
||||
saveLooks();
|
||||
hooks.markSaved(fieldsetOf(box), saveLooks());
|
||||
// Ticking one plays it, so the label has a sound to go with it.
|
||||
if (box.checked) sound(event);
|
||||
});
|
||||
}
|
||||
|
||||
for (const cli of MODEL_CLIS) {
|
||||
$("models-tab-" + cli).addEventListener("click", () => {
|
||||
modelsTab = cli;
|
||||
renderModels();
|
||||
});
|
||||
}
|
||||
$("models-add").addEventListener("click", () => {
|
||||
if (!modelsData) return;
|
||||
modelsData.user[modelsTab].push({ id: "", label: "" });
|
||||
renderModels();
|
||||
$("models-user").querySelector(".models-row:last-child input")?.focus();
|
||||
});
|
||||
$("agents-add").addEventListener("click", () => {
|
||||
agentsData.push(newAgent());
|
||||
renderAgents();
|
||||
$("agents-list").querySelector(".agent-card:last-child input")?.focus();
|
||||
});
|
||||
$("agents-replace").addEventListener("click", () => {
|
||||
$("agents-replace").hidden = true;
|
||||
saveAgents({ replace: true });
|
||||
});
|
||||
$("models-reset").addEventListener("click", () => {
|
||||
if (!modelsData) return;
|
||||
modelsData.user = Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
|
||||
saveModels();
|
||||
renderModels();
|
||||
});
|
||||
|
||||
// Desktop app: the taskbar switch, kept by the app in its own app.json. The
|
||||
// app says what it holds once the page is up; checked until it does.
|
||||
if (framed()) {
|
||||
|
||||
@@ -0,0 +1,550 @@
|
||||
// Plan2Code Web Console - the Implementation Loop's setup screen, drawn by the page from the console's saved setup and the app's facts; defines only.
|
||||
//
|
||||
// The dashboard's loop card opens this in place of the cards. Nothing here
|
||||
// runs an agent: Start saves the setup through POST /loop-setup, then asks the
|
||||
// desktop app (`loop-start { spec }`), which reads the setup itself and
|
||||
// confirms in its own window. The quick check is typed text the page never
|
||||
// runs or sends to the app.
|
||||
|
||||
import { el } from "../render.js";
|
||||
import { hooks, page, redraw } from "../state.js";
|
||||
import { SKILL_CATALOG } from "../answers.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { tellApp, wireLoopMessages } from "../app-bridge.js";
|
||||
|
||||
const LEVELS = [
|
||||
["critical", "Critical"],
|
||||
["warning", "Warning"],
|
||||
["suggestion", "Suggestion"],
|
||||
];
|
||||
|
||||
const ON_QUESTION = [
|
||||
["guess", "Take the agent's best guess", "The agent picks the likeliest answer and records the assumption."],
|
||||
["pause", "Pause and wait for me", "The loop holds and calls you; nothing is lost while you are away."],
|
||||
["stop", "Stop the loop", "The loop ends at that phase and tells you what it asked."],
|
||||
];
|
||||
|
||||
const AFTER_LAST = [
|
||||
["offer-finalize", "Stop and offer Finalize", "You press Finalize when you have looked it over."],
|
||||
["run-finalize", "Run Finalize automatically", "Finalize starts by itself once every phase is built."],
|
||||
];
|
||||
|
||||
const DEFAULT_NOTIFY_PARAM = "message";
|
||||
// What the setup can send a notification to. `name` is the label for the field
|
||||
// the person names, on the kinds that have one.
|
||||
const NOTIFY_KINDS = [
|
||||
{ id: "query", label: "A web address, with the message in its query string", placeholder: "https://example.com/hook", hint: "The app calls this address with a GET.", name: "Query string name for the message" },
|
||||
{ id: "discord", label: "Discord webhook", placeholder: "https://discord.com/api/webhooks/...", hint: "In Discord: Edit Channel, Integrations, Webhooks, then Copy Webhook URL." },
|
||||
{ id: "slack", label: "Slack webhook", placeholder: "https://hooks.slack.com/services/...", hint: "An Incoming Webhook URL from your Slack app's settings." },
|
||||
{ id: "teams", label: "Microsoft Teams webhook", placeholder: "https://...", hint: 'In Teams: Workflows, the template "Post to a channel when a webhook request is received", then copy its URL.' },
|
||||
{ id: "google-chat", label: "Google Chat webhook", placeholder: "https://chat.googleapis.com/v1/spaces/...", hint: "In the space: Apps & integrations, Webhooks, then copy the URL." },
|
||||
{ id: "json", label: "A web address, with the message in a JSON body", placeholder: "https://example.com/hook", hint: "The app sends a POST with a JSON object holding the message, for any other service.", name: "JSON field name for the message" },
|
||||
];
|
||||
const SMART_DETAIL = "A fresh agent reads the review's findings and fixes the ones worth fixing. A skipped Critical stops the phase.";
|
||||
|
||||
/** Called by the page's start-up: hear the app's answers to the loop's requests. */
|
||||
export function wireLoopSetup() {
|
||||
wireLoopMessages(page, redraw);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the setup screen for `spec` (the picker's selected spec object). The
|
||||
* saved setup and the read-only facts come from the console; the agent, model
|
||||
* and permission facts come from the app.
|
||||
*/
|
||||
export async function openLoopSetup(spec) {
|
||||
if (!spec || !spec.dir || page.gone || page.pendingResult || page.local.launching) return;
|
||||
const dir = spec.dir;
|
||||
page.loopStart = null;
|
||||
page.loopNotifyTest = null;
|
||||
page.loopSetup = { spec: dir, loaded: false, failed: false, form: null, facts: null, problems: [], starting: false };
|
||||
tellApp("loop-facts");
|
||||
redraw();
|
||||
const mine = page.loopSetup;
|
||||
let res;
|
||||
try {
|
||||
res = await fetch("/loop-setup?spec=" + encodeURIComponent(dir), { cache: "no-store" });
|
||||
} catch {
|
||||
res = null;
|
||||
}
|
||||
if (page.loopSetup !== mine) return;
|
||||
if (!res || !res.ok) {
|
||||
mine.failed = true;
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
const answer = await res.json().catch(() => null);
|
||||
if (page.loopSetup !== mine) return;
|
||||
if (!answer) {
|
||||
mine.failed = true;
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
const { phasesLeft, branch, pending, suggestedQuickCheck, remembered, saved, ...setup } = answer;
|
||||
mine.form = {
|
||||
review: setup.review !== false,
|
||||
fixMode: setup.fixMode === "levels" ? "levels" : "smart",
|
||||
fix: Array.isArray(setup.fix) ? [...setup.fix] : LEVELS.map(([k]) => k),
|
||||
commit: setup.commit !== false,
|
||||
onQuestion: setup.onQuestion || "guess",
|
||||
afterLast: setup.afterLast || "offer-finalize",
|
||||
quickCheck: typeof setup.quickCheck === "string" ? setup.quickCheck : "",
|
||||
retryOnce: setup.retryOnce !== false,
|
||||
silenceMinutes: Number.isInteger(setup.silenceMinutes) ? setup.silenceMinutes : 20,
|
||||
notifyKind: NOTIFY_KINDS.some((k) => k.id === setup.notifyKind) ? setup.notifyKind : "query",
|
||||
notifyUrl: typeof setup.notifyUrl === "string" ? setup.notifyUrl : "",
|
||||
notifyParam: setup.notifyParam || DEFAULT_NOTIFY_PARAM,
|
||||
};
|
||||
// A first visit with nothing typed starts from the project's own check.
|
||||
if (!remembered && !mine.form.quickCheck && suggestedQuickCheck) mine.form.quickCheck = suggestedQuickCheck;
|
||||
mine.facts = {
|
||||
phasesLeft: Array.isArray(phasesLeft) ? phasesLeft : [],
|
||||
branch: typeof branch === "string" ? branch : "",
|
||||
pending: Number.isInteger(pending) ? pending : null,
|
||||
};
|
||||
mine.loaded = true;
|
||||
redraw();
|
||||
}
|
||||
|
||||
function close() {
|
||||
page.loopSetup = null;
|
||||
page.loopStart = null;
|
||||
redraw();
|
||||
}
|
||||
|
||||
/**
|
||||
* Why Start is grayed, or "" when it can go (FR-5), in the spec's order.
|
||||
* Exported for the page's unit tests.
|
||||
*/
|
||||
export function startBlock(form, facts, appFacts) {
|
||||
if (!form || !facts) return "Loading the setup...";
|
||||
if (form.commit && facts.pending !== null && facts.pending > 0) {
|
||||
return `Commit each phase needs a clean tree: ${facts.pending} uncommitted ${facts.pending === 1 ? "change" : "changes"}.`;
|
||||
}
|
||||
if (!appFacts) return "Asking the app...";
|
||||
if (appFacts.permissionMode === "checked") return "The loop needs permission checks off. Start a New Session with checks off first.";
|
||||
if (appFacts.promptSupport === false) return "This agent cannot be started with a first prompt.";
|
||||
if (!facts.phasesLeft.length) return "Nothing left to build in this spec.";
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* What is wrong with the web address fields as typed, or "". The server checks
|
||||
* again on save; this is the line that shows while typing.
|
||||
*/
|
||||
export function notifyProblem(url, param, kind = "query") {
|
||||
const address = url.trim();
|
||||
if (!address) return "";
|
||||
if (!/^https?:\/\//i.test(address)) return "The web address must start with http:// or https://.";
|
||||
let good = /^https?:\/\/[^/?#@]+([/?#][!-~]*)?$/i.test(address) && !/[^!-~]/.test(address);
|
||||
if (good) {
|
||||
try {
|
||||
good = Boolean(new URL(address).hostname);
|
||||
} catch {
|
||||
good = false;
|
||||
}
|
||||
}
|
||||
if (!good) return "That is not a web address the app can call. Leave out any user name or password, and percent-encode spaces and accents.";
|
||||
const named = NOTIFY_KINDS.some((k) => k.id === kind && k.name);
|
||||
if (named && !/^[A-Za-z0-9._~-]{1,64}$/.test(param.trim() || DEFAULT_NOTIFY_PARAM)) return "The name can only use letters, digits, and - _ . ~";
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The chat service a pasted address belongs to, or "". A webhook needs a POST:
|
||||
* a GET to a Discord webhook answers 200 and posts nothing, so staying on the
|
||||
* query string kind would look like it worked.
|
||||
*/
|
||||
export function kindForUrl(url) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(url.trim());
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
const under = (domain) => host === domain || host.endsWith(`.${domain}`);
|
||||
if ((under("discord.com") || under("discordapp.com")) && parsed.pathname.startsWith("/api/webhooks/")) return "discord";
|
||||
if (host === "hooks.slack.com") return "slack";
|
||||
if (host === "chat.googleapis.com") return "google-chat";
|
||||
if (under("logic.azure.com") || under("powerplatform.com") || under("powerautomate.com")) return "teams";
|
||||
return "";
|
||||
}
|
||||
|
||||
function field(label, hint) {
|
||||
const box = el("div", "loop-field");
|
||||
box.appendChild(el("p", "loop-label", label));
|
||||
if (hint) box.appendChild(el("p", "loop-hint", hint));
|
||||
return box;
|
||||
}
|
||||
|
||||
function toggle(id, text, checked, onChange) {
|
||||
const label = el("label", "loop-switch");
|
||||
const input = el("input");
|
||||
input.type = "checkbox";
|
||||
input.id = id;
|
||||
input.checked = checked;
|
||||
input.addEventListener("change", () => onChange(input.checked));
|
||||
label.append(input, el("span", null, text));
|
||||
return label;
|
||||
}
|
||||
|
||||
function radios(name, options, current, onChange) {
|
||||
const group = el("div", "loop-radios");
|
||||
group.setAttribute("role", "radiogroup");
|
||||
for (const [value, text, detail] of options) {
|
||||
const label = el("label", "loop-radio");
|
||||
const input = el("input");
|
||||
input.type = "radio";
|
||||
input.name = name;
|
||||
input.id = `loop-${name}-${value}`;
|
||||
input.checked = current === value;
|
||||
input.addEventListener("change", () => input.checked && onChange(value));
|
||||
const body = el("span", "loop-radio-body");
|
||||
body.appendChild(el("span", "loop-radio-text", text));
|
||||
if (detail) body.appendChild(el("span", "loop-radio-detail", detail));
|
||||
label.append(input, body);
|
||||
group.appendChild(label);
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
function factRow(list, label, value) {
|
||||
const row = el("div", "loop-fact");
|
||||
row.appendChild(el("dt", null, label));
|
||||
row.appendChild(el("dd", null, value));
|
||||
list.appendChild(row);
|
||||
}
|
||||
|
||||
function agentLine(facts, doing) {
|
||||
if (!facts) return "Asking the app...";
|
||||
const bits = [facts.agentLabel || facts.agent || "the app's agent"];
|
||||
bits.push(facts.model ? `model ${facts.model}` : "default model");
|
||||
bits.push(facts.effort ? `effort ${facts.effort}` : "default effort");
|
||||
return `${bits.join(", ")} (the app's launch choice, for ${doing})`;
|
||||
}
|
||||
|
||||
export function renderLoopSetup(main) {
|
||||
const s = page.loopSetup;
|
||||
const pane = el("div", "dash-confirm loop-setup");
|
||||
pane.appendChild(el("p", "card-kicker", "Step 3 · Implementation Loop"));
|
||||
pane.appendChild(el("h2", "dash-title", "Set up the loop"));
|
||||
const specLine = el("p", "confirm-spec");
|
||||
specLine.append(el("span", null, "for "), el("code", null, s.spec));
|
||||
pane.appendChild(specLine);
|
||||
|
||||
if (s.failed) {
|
||||
pane.appendChild(el("p", "loop-error", "The setup could not be read. Go back and try again."));
|
||||
} else if (!s.loaded) {
|
||||
const wait = el("p", "dash-working");
|
||||
wait.append(el("span", "spinner tiny"), el("span", null, "Loading the setup..."));
|
||||
pane.appendChild(wait);
|
||||
} else {
|
||||
drawBody(pane, s);
|
||||
}
|
||||
|
||||
const actions = el("div", "confirm-actions");
|
||||
const back = el("button", "btn ghost", "Back");
|
||||
back.type = "button";
|
||||
back.addEventListener("click", close);
|
||||
actions.appendChild(back);
|
||||
const help = el("button", "linky loop-help", "How the loop works");
|
||||
help.type = "button";
|
||||
help.addEventListener("click", () => hooks.openHelpOn("loop"));
|
||||
actions.appendChild(help);
|
||||
pane.appendChild(actions);
|
||||
main.appendChild(pane);
|
||||
}
|
||||
|
||||
function drawBody(pane, s) {
|
||||
const f = s.form;
|
||||
const redo = () => {
|
||||
s.problems = [];
|
||||
redraw();
|
||||
};
|
||||
|
||||
// What the app will do, in three plain lines (FR-3).
|
||||
const lines = el("div", "loop-lines");
|
||||
for (const text of [
|
||||
"The app builds each remaining phase in a fresh agent session, one after another, while you are away.",
|
||||
"After each phase it checks the work, marks it done and, if you chose, commits it to this branch. It never pushes.",
|
||||
"You can watch, play an Activity or stop it at any time from the banner at the top of the window.",
|
||||
]) {
|
||||
lines.appendChild(el("p", "loop-line", text));
|
||||
}
|
||||
pane.appendChild(lines);
|
||||
|
||||
// The read-only facts (FR-3).
|
||||
const facts = el("dl", "loop-facts");
|
||||
const left = s.facts.phasesLeft;
|
||||
factRow(facts, "Phases left", left.length ? left.map((p) => `Phase ${p.n}: ${p.name}`).join("\n") : "None");
|
||||
factRow(facts, "Building", agentLine(page.loopFacts, "building"));
|
||||
factRow(facts, "Reviewing", f.review ? agentLine(page.loopFacts, "reviewing") : "Review is off");
|
||||
factRow(facts, "Branch", s.facts.branch || "unknown");
|
||||
factRow(facts, "Uncommitted changes", s.facts.pending === null ? "unknown" : String(s.facts.pending));
|
||||
pane.appendChild(facts);
|
||||
|
||||
// The fields (FR-2, FR-4).
|
||||
const form = el("div", "loop-form");
|
||||
|
||||
const review = field("Review");
|
||||
review.appendChild(toggle("loop-review", "Review each phase with a fresh agent before it counts", f.review, (v) => ((f.review = v), redo())));
|
||||
form.appendChild(review);
|
||||
|
||||
if (f.review) {
|
||||
const fix = field("Fix findings");
|
||||
fix.appendChild(
|
||||
radios(
|
||||
"fixmode",
|
||||
[
|
||||
["smart", "Smart pick", SMART_DETAIL],
|
||||
["levels", "By level", "The agent fixes every finding at the levels you tick."],
|
||||
],
|
||||
f.fixMode,
|
||||
(v) => ((f.fixMode = v), redo())
|
||||
)
|
||||
);
|
||||
if (f.fixMode === "levels") {
|
||||
const row = el("div", "loop-ticks");
|
||||
for (const [key, text] of LEVELS) {
|
||||
row.appendChild(
|
||||
toggle(`loop-fix-${key}`, text, f.fix.includes(key), (on) => {
|
||||
f.fix = LEVELS.map(([k]) => k).filter((k) => (k === key ? on : f.fix.includes(k)));
|
||||
redo();
|
||||
})
|
||||
);
|
||||
}
|
||||
fix.appendChild(row);
|
||||
}
|
||||
form.appendChild(fix);
|
||||
}
|
||||
|
||||
const ask = field("When a phase asks something");
|
||||
ask.appendChild(radios("onquestion", ON_QUESTION, f.onQuestion, (v) => ((f.onQuestion = v), redo())));
|
||||
form.appendChild(ask);
|
||||
|
||||
const after = field("After the last phase");
|
||||
after.appendChild(radios("afterlast", AFTER_LAST, f.afterLast, (v) => ((f.afterLast = v), redo())));
|
||||
form.appendChild(after);
|
||||
|
||||
const notify = field(
|
||||
"Send a notification",
|
||||
"When the loop waits on your answer or ends, except when you stop it yourself, the app sends a short message saying which. Leave the address empty to send nothing."
|
||||
);
|
||||
const kindLabel = el("label", "loop-number");
|
||||
kindLabel.appendChild(el("span", null, "Send to"));
|
||||
const kindSelect = el("select", "loop-text");
|
||||
kindSelect.id = "loop-notify-kind";
|
||||
for (const kind of NOTIFY_KINDS) {
|
||||
const option = el("option", null, kind.label);
|
||||
option.value = kind.id;
|
||||
kindSelect.appendChild(option);
|
||||
}
|
||||
kindSelect.value = f.notifyKind;
|
||||
kindLabel.appendChild(kindSelect);
|
||||
const kindHint = el("p", "loop-hint");
|
||||
const notifyInput = el("input", "loop-text");
|
||||
notifyInput.type = "text";
|
||||
notifyInput.inputMode = "url";
|
||||
notifyInput.id = "loop-notify-url";
|
||||
notifyInput.value = f.notifyUrl;
|
||||
notifyInput.maxLength = 2000;
|
||||
notifyInput.setAttribute("aria-label", "Web address to call");
|
||||
const paramRow = el("div");
|
||||
const paramLabel = el("label", "loop-number");
|
||||
const paramText = el("span");
|
||||
paramLabel.appendChild(paramText);
|
||||
const paramInput = el("input", "loop-text loop-param");
|
||||
paramInput.type = "text";
|
||||
paramInput.id = "loop-notify-param";
|
||||
paramInput.value = f.notifyParam;
|
||||
paramInput.placeholder = DEFAULT_NOTIFY_PARAM;
|
||||
paramInput.maxLength = 64;
|
||||
paramLabel.appendChild(paramInput);
|
||||
paramRow.appendChild(paramLabel);
|
||||
const notifyWarn = el("p", "loop-warn");
|
||||
const testRow = el("div", "loop-test");
|
||||
const testButton = el("button", "btn", "Send a test");
|
||||
testButton.type = "button";
|
||||
testButton.id = "loop-notify-test";
|
||||
testButton.addEventListener("click", () => sendTest(s));
|
||||
testRow.appendChild(testButton);
|
||||
const testLine = notifyTestLine();
|
||||
if (testLine) testRow.appendChild(testLine);
|
||||
const showNotify = () => {
|
||||
const kind = NOTIFY_KINDS.find((k) => k.id === f.notifyKind);
|
||||
kindSelect.value = kind.id;
|
||||
kindHint.textContent = kind.hint;
|
||||
notifyInput.placeholder = kind.placeholder;
|
||||
paramText.textContent = kind.name || "";
|
||||
paramRow.hidden = !kind.name || f.notifyUrl.trim() === "";
|
||||
const problem = notifyProblem(f.notifyUrl, f.notifyParam, kind.id);
|
||||
notifyWarn.textContent = problem;
|
||||
notifyWarn.hidden = !problem;
|
||||
testButton.disabled = Boolean(problem) || f.notifyUrl.trim() === "" || Boolean(page.loopNotifyTest && page.loopNotifyTest.waiting) || s.starting;
|
||||
};
|
||||
// What a test said was about the address as it was.
|
||||
const forgetTest = () => {
|
||||
if (page.loopNotifyTest && !page.loopNotifyTest.waiting) {
|
||||
page.loopNotifyTest = null;
|
||||
testRow.querySelector("p")?.remove();
|
||||
}
|
||||
};
|
||||
notifyInput.addEventListener("input", () => {
|
||||
f.notifyUrl = notifyInput.value;
|
||||
forgetTest();
|
||||
// A pasted webhook picks its own kind, unless the person chose one here.
|
||||
const service = kindForUrl(f.notifyUrl);
|
||||
if (service && f.notifyKind === "query" && !s.notifyKindChosen) f.notifyKind = service;
|
||||
showNotify();
|
||||
});
|
||||
kindSelect.addEventListener("change", () => {
|
||||
f.notifyKind = kindSelect.value;
|
||||
forgetTest();
|
||||
s.notifyKindChosen = true;
|
||||
showNotify();
|
||||
});
|
||||
paramInput.addEventListener("input", () => {
|
||||
f.notifyParam = paramInput.value;
|
||||
forgetTest();
|
||||
showNotify();
|
||||
});
|
||||
showNotify();
|
||||
notify.append(kindLabel, notifyInput, kindHint, paramRow, notifyWarn, testRow);
|
||||
form.appendChild(notify);
|
||||
|
||||
const check = field("Quick check", "A command the app runs after each phase, such as npm run build. The page never runs it.");
|
||||
const checkInput = el("input", "loop-text");
|
||||
checkInput.type = "text";
|
||||
checkInput.id = "loop-quickcheck";
|
||||
checkInput.value = f.quickCheck;
|
||||
checkInput.placeholder = "npm run build";
|
||||
checkInput.maxLength = 500;
|
||||
checkInput.setAttribute("aria-label", "Quick check command");
|
||||
const checkWarn = el("p", "loop-warn", "No check runs after each phase.");
|
||||
checkWarn.hidden = f.quickCheck.trim() !== "";
|
||||
checkInput.addEventListener("input", () => {
|
||||
f.quickCheck = checkInput.value.replace(/[\r\n]+/g, " ");
|
||||
checkWarn.hidden = f.quickCheck.trim() !== "";
|
||||
});
|
||||
check.append(checkInput, checkWarn);
|
||||
form.appendChild(check);
|
||||
|
||||
const retry = field("If a phase crashes or goes quiet");
|
||||
retry.appendChild(toggle("loop-retry", "Retry it once", f.retryOnce, (v) => ((f.retryOnce = v), redo())));
|
||||
const silence = el("label", "loop-number");
|
||||
silence.appendChild(el("span", null, "Count the agent as stuck after this many minutes with no activity"));
|
||||
const silenceInput = el("input", "loop-text loop-narrow");
|
||||
silenceInput.type = "number";
|
||||
silenceInput.id = "loop-silence";
|
||||
silenceInput.min = "1";
|
||||
silenceInput.max = "60";
|
||||
silenceInput.step = "1";
|
||||
silenceInput.value = String(f.silenceMinutes);
|
||||
silenceInput.addEventListener("input", () => {
|
||||
f.silenceMinutes = Number(silenceInput.value);
|
||||
});
|
||||
silence.appendChild(silenceInput);
|
||||
retry.appendChild(silence);
|
||||
retry.appendChild(el("p", "loop-hint", "No activity means no file changes, in the project or the agent's session, so allow for your slowest build or test run. Waiting on your answer does not count."));
|
||||
form.appendChild(retry);
|
||||
|
||||
const commit = field("Commit");
|
||||
commit.appendChild(toggle("loop-commit", "Commit each phase to the current branch", f.commit, (v) => ((f.commit = v), redo())));
|
||||
form.appendChild(commit);
|
||||
|
||||
pane.appendChild(form);
|
||||
|
||||
// Start and the one line saying why it is grayed (FR-5).
|
||||
const block = startBlock(f, s.facts, page.loopFacts);
|
||||
const gated = Boolean(block);
|
||||
const foot = el("div", "loop-start");
|
||||
if (gated) {
|
||||
const why = el("p", "loop-why", block);
|
||||
why.setAttribute("role", "status");
|
||||
foot.appendChild(why);
|
||||
if (f.commit && s.facts.pending > 0) foot.appendChild(gitButton());
|
||||
}
|
||||
if (s.problems.length) {
|
||||
const bad = el("ul", "loop-problems");
|
||||
for (const p of s.problems) bad.appendChild(el("li", null, p));
|
||||
foot.appendChild(bad);
|
||||
}
|
||||
const waiting = s.starting && !page.loopStart;
|
||||
if (waiting) foot.appendChild(el("p", "loop-why", "Waiting for the app's confirm..."));
|
||||
if (page.loopStart && !page.loopStart.ok) foot.appendChild(el("p", "loop-error", page.loopStart.error));
|
||||
if (page.loopStart && page.loopStart.ok) foot.appendChild(el("p", "loop-why", "The loop is starting..."));
|
||||
const start = el("button", "btn primary", "Start the loop");
|
||||
start.type = "button";
|
||||
start.id = "loop-start";
|
||||
start.disabled = gated || waiting || page.gone || page.pendingResult || Boolean(page.loopStart && page.loopStart.ok);
|
||||
start.addEventListener("click", () => startLoop(s));
|
||||
foot.appendChild(start);
|
||||
pane.appendChild(foot);
|
||||
}
|
||||
|
||||
/** The line beside Send a test, or null with nothing to say. */
|
||||
function notifyTestLine() {
|
||||
const test = page.loopNotifyTest;
|
||||
if (!test) return null;
|
||||
if (test.waiting) return el("p", "loop-why", "Waiting for the app's confirm...");
|
||||
if (!test.ok) return el("p", "loop-error", test.error);
|
||||
if (test.sent) return el("p", "loop-why", "Sent, and the address answered OK. Check that the message arrived.");
|
||||
return null;
|
||||
}
|
||||
|
||||
function gitButton() {
|
||||
const b = el("button", "btn", "Open the Git board");
|
||||
b.type = "button";
|
||||
b.addEventListener("click", () => {
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-git");
|
||||
if (entry) hooks.launchSkill(entry);
|
||||
});
|
||||
return b;
|
||||
}
|
||||
|
||||
/** The form as the console saves it. */
|
||||
function setupBody(f) {
|
||||
return { ...f, quickCheck: f.quickCheck.trim(), notifyUrl: f.notifyUrl.trim(), notifyParam: f.notifyParam.trim() || DEFAULT_NOTIFY_PARAM };
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a test: save, so the app can read what is on screen, then ask it. The
|
||||
* message names nothing: the app takes the address from the saved setup and
|
||||
* confirms it in its own dialog, as it does for Start.
|
||||
*/
|
||||
async function sendTest(s) {
|
||||
const f = s.form;
|
||||
if (!f.notifyUrl.trim() || notifyProblem(f.notifyUrl, f.notifyParam, f.notifyKind) || (page.loopNotifyTest && page.loopNotifyTest.waiting)) return;
|
||||
s.problems = [];
|
||||
page.loopNotifyTest = { waiting: true };
|
||||
redraw();
|
||||
const { status, body: answer } = await postJson("/loop-setup", setupBody(f));
|
||||
if (page.loopSetup !== s) return;
|
||||
if (status !== 200 || !answer || answer.ok !== true) {
|
||||
page.loopNotifyTest = null;
|
||||
s.problems = Array.isArray(answer && answer.problems) && answer.problems.length ? answer.problems : ["The setup could not be saved. Try again."];
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
tellApp("loop-notify-test");
|
||||
}
|
||||
|
||||
async function startLoop(s) {
|
||||
const f = s.form;
|
||||
if (startBlock(f, s.facts, page.loopFacts) || (s.starting && !page.loopStart)) return;
|
||||
s.problems = [];
|
||||
page.loopStart = null;
|
||||
s.starting = true;
|
||||
redraw();
|
||||
const { status, body: answer } = await postJson("/loop-setup", setupBody(f));
|
||||
if (page.loopSetup !== s) return;
|
||||
if (status !== 200 || !answer || answer.ok !== true) {
|
||||
s.starting = false;
|
||||
s.problems = Array.isArray(answer && answer.problems) && answer.problems.length ? answer.problems : ["The setup could not be saved. Try again."];
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
tellApp("loop-start", { spec: s.spec });
|
||||
redraw();
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// Plan2Code Web Console - the User Preferences dialog: its tabs, the one way
|
||||
// to open and close it, the Saved mark, Back to default for the tab on screen
|
||||
// and the prompt that stops an unsaved agent edit being lost.
|
||||
|
||||
import { onSwatchSaved, renderSwatches, resetLooks, saveLooks } from "../looks.js";
|
||||
import { PREFS_TABS, prefsOpenTab, prefsResetScope } from "../prefs.js";
|
||||
import { wireTabs } from "../tabs.js";
|
||||
import { el, lightDismiss } from "../render.js";
|
||||
import { hooks, redraw } from "../state.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
let prefsTabs = null;
|
||||
|
||||
// Back to default only where the tab has looks to reset.
|
||||
function showResetFor(id) {
|
||||
$("looks-reset").hidden = prefsResetScope(id) === null;
|
||||
}
|
||||
|
||||
// The small mark at the top right of a fieldset, level with its legend:
|
||||
// "Saved", fading, or the error in its place, kept until that fieldset saves
|
||||
// again. `result` is what saveLooks() resolves, or a Promise of it; a `text`
|
||||
// in it replaces the word Saved.
|
||||
const markTimers = new WeakMap();
|
||||
|
||||
function clearMark(mark) {
|
||||
clearTimeout(markTimers.get(mark));
|
||||
if (mark.classList.contains("is-saved")) mark.textContent = "";
|
||||
}
|
||||
|
||||
export async function markSaved(fieldset, result) {
|
||||
if (!fieldset) return;
|
||||
let mark = fieldset.querySelector(":scope > .prefs-saved");
|
||||
if (!mark) {
|
||||
mark = el("span", "prefs-saved");
|
||||
mark.setAttribute("role", "status");
|
||||
// Gone after the fade, or after the same time when motion is reduced and
|
||||
// no animation runs to say so (the timer below).
|
||||
mark.addEventListener("animationend", () => clearMark(mark));
|
||||
fieldset.appendChild(mark);
|
||||
}
|
||||
const { ok, error, text } = (await result) || { ok: true };
|
||||
// A newer save owns the mark: an earlier one's timer must not blank it.
|
||||
clearTimeout(markTimers.get(mark));
|
||||
mark.classList.remove("is-saved", "error");
|
||||
// Restart the fade when the same fieldset saves twice in a row.
|
||||
void mark.offsetWidth;
|
||||
if (ok) {
|
||||
mark.textContent = text || "Saved";
|
||||
mark.classList.add("is-saved");
|
||||
markTimers.set(mark, setTimeout(() => clearMark(mark), 2200));
|
||||
} else {
|
||||
mark.textContent = error || "Could not save.";
|
||||
mark.classList.add("error");
|
||||
}
|
||||
}
|
||||
|
||||
// Every way in: the gear, the dashboard's Set up preferences, or a caller
|
||||
// naming the tab it wants. Agents and models load each time it opens.
|
||||
export function openPrefs(tab) {
|
||||
renderSwatches();
|
||||
hooks.loadAgentsView();
|
||||
prefsTabs.select(prefsOpenTab(tab));
|
||||
$("looks-modal").showModal();
|
||||
$("prefs-tab-" + prefsTabs.current()).focus();
|
||||
}
|
||||
|
||||
// The unsaved prompt on screen: { resolve, promise, from }, or null. `from`
|
||||
// is what had focus when it asked (the tab, Close, Back to summary, a field).
|
||||
let asking = null;
|
||||
|
||||
// Everything in the dialog but the prompt, kept out of reach while it asks.
|
||||
const behindPrompt = () => [$("looks-title"), $("looks-modal").querySelector(".prefs-body"), $("looks-modal").querySelector(".modal-actions")];
|
||||
|
||||
function endAsking(go) {
|
||||
$("prefs-unsaved").hidden = true;
|
||||
for (const node of behindPrompt()) node.inert = false;
|
||||
const { resolve, from } = asking;
|
||||
asking = null;
|
||||
// Keep editing (or a failed Save) goes back into the form; going on hands
|
||||
// focus back to what asked, so the action it carries on with owns it.
|
||||
if (!go) hooks.focusOpen();
|
||||
else if (from && from.isConnected && !from.closest("[hidden]")) from.focus();
|
||||
resolve(go);
|
||||
}
|
||||
|
||||
// Before anything leaves an agent form with an unsaved edit (Close, Esc, a
|
||||
// backdrop click, another tab, Back to summary): Save, Discard or Keep
|
||||
// editing, asked inside the dialog. Resolves true when it may go on.
|
||||
export function confirmUnsaved() {
|
||||
if (!hooks.hasUnsaved()) return Promise.resolve(true);
|
||||
if (asking) return asking.promise;
|
||||
let resolve;
|
||||
const promise = new Promise((r) => (resolve = r));
|
||||
asking = { resolve, promise, from: document.activeElement };
|
||||
$("prefs-unsaved-name").textContent = hooks.unsavedName();
|
||||
for (const node of behindPrompt()) node.inert = true;
|
||||
$("prefs-unsaved").hidden = false;
|
||||
$("prefs-unsaved-save").disabled = false;
|
||||
$("prefs-unsaved-save").focus();
|
||||
return promise;
|
||||
}
|
||||
|
||||
// Plain true while nothing is unsaved, so a tab switch or a close happens in
|
||||
// this same tick.
|
||||
const guard = () => (hooks.hasUnsaved() || asking ? confirmUnsaved() : true);
|
||||
|
||||
async function closePrefs() {
|
||||
if (await guard()) $("looks-modal").close();
|
||||
}
|
||||
|
||||
function wireUnsaved() {
|
||||
const box = el("div", "prefs-unsaved");
|
||||
box.id = "prefs-unsaved";
|
||||
box.hidden = true;
|
||||
box.setAttribute("role", "alertdialog");
|
||||
box.setAttribute("aria-labelledby", "prefs-unsaved-title");
|
||||
box.setAttribute("aria-describedby", "prefs-unsaved-text");
|
||||
const inner = el("div", "prefs-unsaved-box");
|
||||
const title = el("h3", null, "Unsaved changes");
|
||||
title.id = "prefs-unsaved-title";
|
||||
const text = el("p");
|
||||
text.id = "prefs-unsaved-text";
|
||||
const name = el("strong");
|
||||
name.id = "prefs-unsaved-name";
|
||||
text.append("You have unsaved changes to ", name, ".");
|
||||
const save = el("button", "btn small primary", "Save");
|
||||
save.type = "button";
|
||||
save.id = "prefs-unsaved-save";
|
||||
const discard = el("button", "btn small ghost", "Discard");
|
||||
discard.type = "button";
|
||||
const keep = el("button", "btn small ghost", "Keep editing");
|
||||
keep.type = "button";
|
||||
save.addEventListener("click", async () => {
|
||||
save.disabled = true;
|
||||
const ok = await hooks.saveOpen();
|
||||
save.disabled = false;
|
||||
if (asking) endAsking(ok);
|
||||
});
|
||||
discard.addEventListener("click", () => {
|
||||
hooks.discardOpen();
|
||||
endAsking(true);
|
||||
});
|
||||
keep.addEventListener("click", () => endAsking(false));
|
||||
const actions = el("div", "prefs-unsaved-actions");
|
||||
actions.append(save, discard, keep);
|
||||
inner.append(title, text, actions);
|
||||
box.append(inner);
|
||||
$("looks-modal").append(box);
|
||||
}
|
||||
|
||||
export function wirePrefs() {
|
||||
const dlg = $("looks-modal");
|
||||
wireUnsaved();
|
||||
lightDismiss(dlg, guard);
|
||||
$("looks-done").addEventListener("click", closePrefs);
|
||||
// Esc: held while a form has an unsaved edit, and Keep editing while the prompt asks.
|
||||
dlg.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Escape") return;
|
||||
if (asking) {
|
||||
e.preventDefault();
|
||||
endAsking(false);
|
||||
} else if (hooks.hasUnsaved()) {
|
||||
e.preventDefault();
|
||||
closePrefs();
|
||||
}
|
||||
});
|
||||
dlg.addEventListener("cancel", (e) => {
|
||||
if (!asking && !hooks.hasUnsaved()) return;
|
||||
e.preventDefault();
|
||||
if (!asking) closePrefs();
|
||||
});
|
||||
hooks.wireAgentsView();
|
||||
prefsTabs = wireTabs({
|
||||
tabs: PREFS_TABS,
|
||||
list: $("prefs-tabs"),
|
||||
panels: $("prefs-panels"),
|
||||
prefix: "prefs",
|
||||
tabClass: "prefs-tab",
|
||||
beforeSelect: () => guard(),
|
||||
// The hint describes the tab rather than naming it, so a screen reader's
|
||||
// tab name stays the label, at any width.
|
||||
renderTab: (t, btn) => {
|
||||
const hint = el("span", "prefs-tab-hint", t.hint);
|
||||
hint.id = "prefs-hint-" + t.id;
|
||||
hint.setAttribute("aria-hidden", "true");
|
||||
btn.append(el("span", "prefs-tab-label", t.label), hint);
|
||||
btn.setAttribute("aria-describedby", hint.id);
|
||||
},
|
||||
onSelect: (id) => {
|
||||
showResetFor(id);
|
||||
$("looks-modal").querySelector(".prefs-body").scrollTop = 0;
|
||||
},
|
||||
});
|
||||
$("btn-looks").addEventListener("click", () => openPrefs());
|
||||
$("looks-reset").addEventListener("click", () => {
|
||||
const tab = prefsTabs.current();
|
||||
const keys = prefsResetScope(tab);
|
||||
if (!keys) return;
|
||||
resetLooks(keys);
|
||||
const saved = saveLooks();
|
||||
redraw();
|
||||
markSaved($("prefs-panel-" + tab).querySelector("fieldset"), saved);
|
||||
});
|
||||
onSwatchSaved((saved) => markSaved($("looks-swatches").closest("fieldset"), saved));
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { page, redraw } from "../state.js";
|
||||
import { el, approvalTip } from "../render.js";
|
||||
import { startPose, startingHint, staleLaunchFeedback, workflowTitle } from "../answers.js";
|
||||
import { skillByName } from "../skills.js";
|
||||
import { agentAdrift, doingNow, docs } from "../selectors.js";
|
||||
import { agentAdrift, doingNow, docs, loopDriving } from "../selectors.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -132,10 +132,12 @@ function renderStarting(main) {
|
||||
const elapsed = startingElapsed();
|
||||
const pane = posePane(main, "launching starting", page.S.workflow);
|
||||
pane.appendChild(el("p", "card-kicker", "Starting up"));
|
||||
pane.appendChild(el("h2", "launch-title", `Starting ${workflowTitle(page.S.workflow)}`));
|
||||
const looping = loopDriving();
|
||||
pane.appendChild(el("h2", "launch-title", looping ? "The loop is starting this phase" : `Starting ${workflowTitle(page.S.workflow)}`));
|
||||
pane.appendChild(el("p", "launch-quip", START_QUIPS[Math.floor(elapsed / 2600) % START_QUIPS.length]));
|
||||
pane.appendChild(el("p", "launch-hint", startingHint(elapsed)));
|
||||
pane.appendChild(approvalTip());
|
||||
// A loop runs with permission checks off, so no approval will come.
|
||||
if (!looping) pane.appendChild(approvalTip());
|
||||
startLaunchTicker();
|
||||
}
|
||||
|
||||
@@ -180,8 +182,17 @@ function startLaunchTicker() {
|
||||
}
|
||||
}
|
||||
|
||||
// A phase that has reported is not starting: the app is checking the report,
|
||||
// running the quick check and committing, which can take minutes.
|
||||
function renderLoopChecking(main) {
|
||||
const pane = posePane(main, "waiting-pane", page.S.workflow);
|
||||
pane.appendChild(el("h2", null, "The loop is checking this phase"));
|
||||
pane.appendChild(el("p", null, "The agent has reported. The app is checking that against the spec before it moves on, so you don't need to do anything."));
|
||||
}
|
||||
|
||||
export function renderWaiting(main) {
|
||||
const doing = doingNow();
|
||||
if (!doing && loopDriving() && page.S.loopOutcome) return renderLoopChecking(main);
|
||||
// Nothing asked and nothing said yet: the session is still starting.
|
||||
if (!doing) return renderStarting(main);
|
||||
// The same Planny the session started with, still at it: the spinner that
|
||||
@@ -199,7 +210,9 @@ export function renderWaiting(main) {
|
||||
}
|
||||
pane.appendChild(title);
|
||||
pane.appendChild(el("p", null, doing));
|
||||
const ask = "If Plan2Code needs you, the question appears here on its own.";
|
||||
const ask = loopDriving()
|
||||
? "The loop is running this phase by itself, so you don't need to do anything. If it needs you, the question appears here."
|
||||
: "If Plan2Code needs you, the question appears here on its own.";
|
||||
if (!docs().length) {
|
||||
pane.appendChild(el("p", null, ask));
|
||||
return;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { hooks, page } from "../state.js";
|
||||
import { copyButton, el, lightDismiss, selectContents } from "../render.js";
|
||||
import { selSpec, specList, workspaceFolders } from "../selectors.js";
|
||||
import { loopDriving, selSpec, specList, workspaceFolders } from "../selectors.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { nameProblem } from "../workspace.js";
|
||||
|
||||
@@ -114,6 +114,12 @@ export function renderWorkspace() {
|
||||
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
|
||||
$("workspace-browse").hidden = Boolean(page.wsFrame && page.wsFrame.remote);
|
||||
$("workspace-scope").textContent = workspaceScopeText();
|
||||
// The loop's agents were started with this workspace; changing it now would
|
||||
// reach nobody (FR-15). Reading and copying paths stays.
|
||||
const locked = loopDriving();
|
||||
for (const id of ["workspace-add", "workspace-browse", "workspace-path"]) $(id).disabled = locked || (id === "workspace-add" && wsBusy);
|
||||
for (const rm of list.querySelectorAll(".ws-remove")) rm.disabled = locked;
|
||||
if (locked) setAddMsg("The workspace is fixed while the loop builds.");
|
||||
}
|
||||
|
||||
function workspaceRow(f) {
|
||||
@@ -281,7 +287,7 @@ function paintWorkspaceRow(li, f) {
|
||||
// sent when the person took a suggested name after a clash.
|
||||
async function addWorkspaceFolder(path, name) {
|
||||
const trimmed = String(path || "").trim();
|
||||
if (!trimmed || wsBusy) return;
|
||||
if (!trimmed || wsBusy || loopDriving()) return;
|
||||
wsBusy = true;
|
||||
$("workspace-add").disabled = true;
|
||||
const { status, body } = await postJson("/workspace/add", name ? { path: trimmed, name } : { path: trimmed });
|
||||
@@ -318,7 +324,7 @@ async function addWorkspaceFolder(path, name) {
|
||||
|
||||
async function browseWorkspace() {
|
||||
const b = $("workspace-browse");
|
||||
if (b.disabled) return;
|
||||
if (b.disabled || loopDriving()) return;
|
||||
b.disabled = true;
|
||||
setAddMsg("Waiting for the folder picker…");
|
||||
const { status, body } = await postJson("/workspace/browse", {});
|
||||
|
||||
@@ -7,6 +7,7 @@ import { page, redraw } from "./state.js";
|
||||
import { boardAwaiting } from "./git-board.js";
|
||||
import { defaultSpec, reviewOffer, dashboardOffer, submittedAwaiting, quietLimitMs } from "./answers.js";
|
||||
import { activityLabel, workingLine } from "./labels.js";
|
||||
import { ASK_BUSY_MS, chatAnswering } from "./chat.js";
|
||||
|
||||
export const WORKING_GRACE_MS = 5 * 60 * 1000;
|
||||
|
||||
@@ -18,6 +19,33 @@ export const WORKING_GRACE_MS = 5 * 60 * 1000;
|
||||
// many missed pokes, not a slow one.
|
||||
const ADRIFT_MS = 3 * 60 * 1000;
|
||||
|
||||
// The Implementation Loop is driving this page: the app started the session
|
||||
// with `open --loop`, and no `loopEnd` has been posted yet. Locks the page
|
||||
// (FR-15); the stop and finish screens end it.
|
||||
export const loopDriving = () => Boolean(page.S && page.S.loop && page.S.loop.driving === true && !page.S.loopEnd);
|
||||
|
||||
// Driving, and a required question the loop does not handle itself is open:
|
||||
// the one case where its card (and Ask) unlock (FR-14).
|
||||
export const loopWaiting = () =>
|
||||
loopDriving() &&
|
||||
openItems().some((i) => i.required !== false && i.handledBy !== "loop");
|
||||
|
||||
// The ids of the cards the loop is waiting on the person for, as one string:
|
||||
// what `local.askLockedAfterSend` remembers, so Ask locks again after a Send
|
||||
// and stays locked until a different question waits (FR-14).
|
||||
export const loopWaitingKey = () =>
|
||||
loopWaiting()
|
||||
? openItems()
|
||||
.filter((i) => i.required !== false && i.handledBy !== "loop")
|
||||
.map((i) => i.id)
|
||||
.sort()
|
||||
.join("|")
|
||||
: "";
|
||||
|
||||
// Ask is off while the loop drives, except while a question waits and no Send
|
||||
// has answered that same question yet.
|
||||
export const loopAskLocked = () => loopDriving() && !(loopWaiting() && page.local.askLockedAfterSend !== loopWaitingKey());
|
||||
|
||||
export const items = () => (page.S && Array.isArray(page.S.items) ? page.S.items : []);
|
||||
|
||||
export const topics = () => (page.S && Array.isArray(page.S.topics) ? page.S.topics : []);
|
||||
@@ -200,12 +228,19 @@ export const doingNow = () => workingLine(page.S && page.S.agent, page.S && page
|
||||
// well clear of its idle deadline, so the server happily outlives the agent
|
||||
// for hours. Until now nothing said so unless the agent had also declared
|
||||
// itself "working", and the normal state while someone answers is "waiting".
|
||||
//
|
||||
// An agent answering an Ask message is out of `wait` too, and busy rather than
|
||||
// gone, so it gets ASK_BUSY_MS before anything calls it adrift.
|
||||
export function agentAdrift() {
|
||||
if (!page.agentLastSeen || page.gone || finish()) return false;
|
||||
const silent = Date.now() - Date.parse(page.agentLastSeen);
|
||||
return silent > (page.pendingResult ? uncollectedLimit() : patience(ADRIFT_MS));
|
||||
const limit = page.pendingResult ? uncollectedLimit() : patience(ADRIFT_MS);
|
||||
return silent > (chatAnswering(page.chatFrame) ? Math.max(limit, ASK_BUSY_MS) : limit);
|
||||
}
|
||||
|
||||
// Answering an Ask message, and not yet quiet for long enough to doubt it.
|
||||
export const askBusy = () => chatAnswering(page.chatFrame) && !agentAdrift();
|
||||
|
||||
// With answers sent and nothing collecting them, the agent's quiet allowance
|
||||
// stops counting: those answers are what it is meant to come back for. An
|
||||
// agent that said it is waiting pings from `wait` every five seconds, so a
|
||||
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
WORKING_GRACE_MS,
|
||||
openItems,
|
||||
agentAdrift,
|
||||
loopDriving,
|
||||
loopWaiting,
|
||||
} from "./selectors.js";
|
||||
import { finishPaused } from "./answers.js";
|
||||
import { page } from "./state.js";
|
||||
@@ -24,6 +26,11 @@ export function sendState() {
|
||||
? { disabled: true, why: "This session is paused.", short: "Session paused" }
|
||||
: { disabled: true, why: "This session is finished.", short: "Session finished" };
|
||||
if (page.gone) return { disabled: true, why: "Not connected right now.", short: "Not connected" };
|
||||
// The Implementation Loop answers for the agent: nothing to send until it
|
||||
// stops to ask the person something (FR-15, FR-14).
|
||||
if (loopDriving() && !loopWaiting()) {
|
||||
return { disabled: true, why: "The loop is building. Cards unlock when it needs you.", short: "The loop is building" };
|
||||
}
|
||||
// A send is still being collected. Blocking here is what keeps someone from
|
||||
// writing over answers nobody has read yet.
|
||||
if (page.pendingResult) {
|
||||
|
||||
@@ -43,6 +43,11 @@
|
||||
// `spec: true` when it takes the picked spec), or null; an
|
||||
// optional `help` is Help's line for the card when it differs
|
||||
// from `blurb`
|
||||
// appOnly the entry is a card the desktop app alone offers (the
|
||||
// Implementation Loop): no workflow, no installed skill, and no
|
||||
// list derived from the workflows (WORKFLOWS, the meter, the
|
||||
// resume command, Help's card list) holds it. `skill` is an id
|
||||
// only; `workflow` is null. Use FLOW_SKILLS for those lists.
|
||||
|
||||
// Shared by Implement and Implement + Review.
|
||||
const BUILD_HELPERS =
|
||||
@@ -235,6 +240,32 @@ export const SKILLS = Object.freeze([
|
||||
// No card of its own: Implement's card launches it when Review is ticked.
|
||||
card: null,
|
||||
}),
|
||||
// The desktop app's Implementation Loop: a card, not a skill. It has no
|
||||
// SKILL.md and no console workflow; it drives Implement (or Implement +
|
||||
// Review) once per phase, each in a fresh agent. Drawn by the dashboard in
|
||||
// the app only.
|
||||
skill({
|
||||
skill: "plan2code-loop",
|
||||
workflow: null,
|
||||
appOnly: true,
|
||||
label: "Implementation Loop",
|
||||
name: "Implementation Loop",
|
||||
pose: null,
|
||||
builds: false, phased: false, metered: false, templates: false,
|
||||
weight: null, started: null, ran: null, resume: null,
|
||||
subagents: null,
|
||||
states: ["documented", "building"],
|
||||
greyed: BUILD_GREYED,
|
||||
card: {
|
||||
group: "pipeline",
|
||||
chip: "Step 3",
|
||||
spec: true,
|
||||
title: "Implementation Loop",
|
||||
blurb: "Build every remaining phase unattended, one fresh agent per phase.",
|
||||
about:
|
||||
"Builds every remaining phase of the spec without you at the keyboard. Each phase gets a fresh agent that builds it and reviews it. The app checks the result against the spec, runs your quick check, commits, and moves on. It stops at the first phase that goes wrong and tells you why. Desktop app only.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-4-finalize",
|
||||
workflow: "finalize",
|
||||
@@ -413,11 +444,15 @@ export const SKILLS = Object.freeze([
|
||||
}),
|
||||
]);
|
||||
|
||||
const BY_WORKFLOW = new Map(SKILLS.map((s) => [s.workflow, s]));
|
||||
const BY_SKILL = new Map(SKILLS.map((s) => [s.skill, s]));
|
||||
// The entries that are skills with a workflow, in SKILLS order: what every
|
||||
// list derived from the workflows is built from (an `appOnly` card is not one).
|
||||
export const FLOW_SKILLS = Object.freeze(SKILLS.filter((s) => !s.appOnly));
|
||||
|
||||
const BY_WORKFLOW = new Map(FLOW_SKILLS.map((s) => [s.workflow, s]));
|
||||
const BY_SKILL = new Map(FLOW_SKILLS.map((s) => [s.skill, s]));
|
||||
|
||||
// Every workflow name the console knows, in SKILLS order.
|
||||
export const WORKFLOWS = Object.freeze(SKILLS.map((s) => s.workflow));
|
||||
export const WORKFLOWS = Object.freeze(FLOW_SKILLS.map((s) => s.workflow));
|
||||
|
||||
/** Whether a name is one of WORKFLOWS (`open --workflow`, `handoff new --workflow`). */
|
||||
export function isWorkflow(name) {
|
||||
|
||||
@@ -111,6 +111,21 @@ export const page = {
|
||||
// false until the first frame lands, same as every other flag here, and
|
||||
// from an older server that sends none.
|
||||
inApp: false,
|
||||
// The Implementation Loop, as the desktop app drives it: `loop` is the
|
||||
// state's `{ driving: true }` or null (it locks the page, selectors.js
|
||||
// loopDriving); `loopFacts` is what the app answered to `loop-facts`
|
||||
// (agent, model, effort, permission mode, prompt support); `loopStart` is
|
||||
// `{ ok, error }` once the app answered a `loop-start`; `loopAction` is the
|
||||
// same for the stop screen's Resume, Fix and Finalize; `loopNotifyTest` is
|
||||
// Send a test's `{ waiting }`, then `{ ok, sent, error }` once the app answered.
|
||||
loop: null,
|
||||
// The setup screen the dashboard's Implementation Loop card opened, or null
|
||||
// (screens/loop-setup.js owns the shape).
|
||||
loopSetup: null,
|
||||
loopFacts: null,
|
||||
loopStart: null,
|
||||
loopNotifyTest: null,
|
||||
loopAction: null,
|
||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
||||
// revision }), or null before a server that sends it.
|
||||
subagentsFrame: null,
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
rule, so it needs saying here. */
|
||||
.footer[hidden] { display: none; }
|
||||
|
||||
.dash { max-width: 860px; padding-top: 8px; }
|
||||
/* The menu follows the Card width setting like the question column does. */
|
||||
.dash { max-width: min(var(--card-width), 100%); padding-top: 8px; }
|
||||
.dash-title { margin: 6px 0 8px; font: 600 clamp(26px, 4vw, 36px)/1.1 var(--serif); }
|
||||
.dash-note { margin: 0 0 26px; font-size: 14.5px; color: var(--ink-2); }
|
||||
/* The first-run role nudge: one line above the title, wrapping on a narrow
|
||||
@@ -379,10 +380,10 @@
|
||||
/* ------------------------------------------------- dashboard confirm */
|
||||
|
||||
/* The beat between "I clicked a card" and "it is running": what the pick is,
|
||||
what it will do, and a START that means it. Narrower than the menu, centered
|
||||
like the launching pane it precedes. */
|
||||
what it will do, and a START that means it. As wide as the menu (the page
|
||||
width setting), centered like the launching pane it precedes. */
|
||||
.dash-confirm {
|
||||
max-width: 560px;
|
||||
max-width: min(var(--card-width), 100%);
|
||||
margin: 3vh auto 0;
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
@@ -406,6 +407,9 @@
|
||||
|
||||
.confirm-head { display: flex; align-items: center; gap: 8px; margin-top: 4px; }
|
||||
.dash-confirm .dash-title { margin: 2px 0 0; }
|
||||
/* The pane is as wide as the menu, but prose is not: its lines stop at a
|
||||
readable measure while the controls below keep the full width. */
|
||||
.confirm-about, .confirm-detail, .confirm-spec { max-width: 70ch; }
|
||||
.confirm-about { margin: 0; font-size: 14.5px; line-height: 1.55; color: var(--ink-2); }
|
||||
.confirm-detail { margin: 0; font-size: 13px; color: var(--accent); }
|
||||
.confirm-spec { margin: 0; font-size: 13px; color: var(--ink-2); }
|
||||
@@ -428,9 +432,23 @@
|
||||
|
||||
/* "Start with a note from your Notebook": the switch, then the tabs beside a
|
||||
preview of the picked one, its pictures each with a tick. */
|
||||
.confirm-note-box { display: grid; gap: 8px; }
|
||||
.confirm-note-switch { display: flex; gap: 8px; align-items: center; color: var(--ink-2); cursor: pointer; }
|
||||
.confirm-note-switch input { accent-color: var(--accent, currentColor); }
|
||||
/* Stretched past the confirm's centering, and left aligned: a note reads as
|
||||
a document, not a caption. */
|
||||
/* Its own frame sets it apart from the text above, so no rule: just room. */
|
||||
.confirm-note-box { display: grid; gap: 8px; justify-self: stretch; text-align: left; margin-top: 12px; }
|
||||
.confirm-note-head {
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--accent-line);
|
||||
border-left: 3px solid var(--accent);
|
||||
border-radius: 8px;
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
.confirm-note-head.is-on { padding: 8px 12px; }
|
||||
.confirm-note-switch { display: flex; gap: 10px; align-items: center; color: var(--ink); font-weight: 600; cursor: pointer; }
|
||||
.confirm-note-switch input { width: 18px; height: 18px; margin: 0; flex: none; accent-color: var(--accent, currentColor); }
|
||||
.confirm-note-hint { padding-left: 28px; font-size: 12.5px; color: var(--ink-2); }
|
||||
.confirm-note { display: grid; grid-template-columns: minmax(130px, 200px) minmax(0, 1fr); gap: 10px; }
|
||||
.confirm-note > .confirm-note-msg { grid-column: 1 / -1; }
|
||||
.confirm-note-msg { margin: 0; font-size: 13px; color: var(--ink-3); }
|
||||
@@ -480,7 +498,7 @@
|
||||
/* ------------------------------------------------------- launching pane */
|
||||
|
||||
.launching {
|
||||
max-width: 560px;
|
||||
max-width: min(var(--card-width), 100%);
|
||||
margin: 4vh auto 0;
|
||||
text-align: center;
|
||||
display: grid;
|
||||
@@ -539,5 +557,54 @@
|
||||
}
|
||||
.launch-hint { margin: 0; font-size: 12.5px; color: var(--ink-3); max-width: 46ch; }
|
||||
/* A line, never a banner: no border, no background, no icon. */
|
||||
.approval-tip { margin: 18px 0 0; font-size: 12.5px; line-height: 1.5; color: var(--ink-3); }
|
||||
.approval-tip { max-width: 70ch; margin: 18px 0 0; font-size: 12.5px; line-height: 1.5; color: var(--ink-3); }
|
||||
|
||||
|
||||
/* --------------------------------------------- the Implementation Loop */
|
||||
|
||||
/* The card's own link; a span, since a link may not sit inside a button. */
|
||||
.dash-card-link { font-size: 12px; color: var(--accent); text-decoration: underline; cursor: pointer; justify-self: start; }
|
||||
|
||||
/* The setup screen: the confirm pane's width, with a left-aligned form. */
|
||||
.loop-setup { justify-items: stretch; text-align: left; gap: 14px; }
|
||||
.loop-setup .card-kicker, .loop-setup .dash-title, .loop-setup .confirm-spec { justify-self: start; }
|
||||
.loop-lines { display: grid; gap: 4px; }
|
||||
.loop-line { margin: 0; font-size: 14px; line-height: 1.5; color: var(--ink-2); max-width: 75ch; }
|
||||
.loop-facts { display: grid; gap: 6px; margin: 0; padding: 12px 14px; background: var(--panel-2); border: 1px solid var(--rule); border-radius: 8px; }
|
||||
.loop-fact { display: grid; grid-template-columns: minmax(130px, 200px) 1fr; gap: 10px; font-size: 13px; }
|
||||
.loop-fact dt { color: var(--ink-3); }
|
||||
.loop-fact dd { margin: 0; color: var(--ink); overflow-wrap: anywhere; white-space: pre-line; }
|
||||
.loop-form { display: grid; gap: 16px; }
|
||||
.loop-field { display: grid; gap: 6px; }
|
||||
.loop-label { margin: 0; font-weight: 600; font-size: 13.5px; }
|
||||
.loop-hint { margin: 0; font-size: 12.5px; color: var(--ink-3); }
|
||||
.loop-switch, .loop-radio { display: flex; gap: 8px; align-items: flex-start; cursor: pointer; font-size: 14px; color: var(--ink-2); }
|
||||
.loop-switch input, .loop-radio input { accent-color: var(--accent, currentColor); margin-top: 3px; }
|
||||
.loop-radios { display: grid; gap: 6px; }
|
||||
.loop-radio-body { display: grid; gap: 1px; }
|
||||
.loop-radio-detail { font-size: 12.5px; color: var(--ink-3); }
|
||||
.loop-ticks { display: flex; flex-wrap: wrap; gap: 6px 18px; margin-left: 4px; }
|
||||
.loop-text { font: inherit; font-size: 14px; padding: 6px 10px; color: var(--ink); background: var(--panel-2); border: 1px solid var(--rule); border-radius: 6px; max-width: 520px; width: 100%; }
|
||||
.loop-text.loop-narrow { width: 90px; }
|
||||
.loop-text.loop-param { width: 180px; }
|
||||
.loop-test { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
|
||||
.loop-test p { margin: 0; font-size: 12.5px; }
|
||||
.loop-number { display: flex; align-items: center; gap: 10px; font-size: 14px; color: var(--ink-2); }
|
||||
.loop-warn { margin: 0; font-size: 12.5px; color: var(--warn); }
|
||||
.loop-start { display: grid; gap: 8px; justify-items: start; }
|
||||
.loop-why { margin: 0; font-size: 13px; color: var(--ink-2); }
|
||||
.loop-error { margin: 0; font-size: 13px; color: var(--warn); }
|
||||
.loop-problems { margin: 0; padding-left: 18px; font-size: 13px; color: var(--warn); }
|
||||
.loop-help { margin-left: auto; }
|
||||
|
||||
/* A card the loop holds: a record with a tag, no inputs. */
|
||||
.card.is-loop-handled .loop-tag { margin: 0 0 4px; font-weight: 600; color: var(--accent); }
|
||||
.card.is-loop-locked .answered { opacity: 0.85; }
|
||||
|
||||
/* The stop and finish screens the loop's end draws. */
|
||||
.loop-end { display: grid; gap: 14px; }
|
||||
.loop-end-phases { width: 100%; border-collapse: collapse; font-size: 13.5px; }
|
||||
.loop-end-phases th, .loop-end-phases td { text-align: left; padding: 5px 10px 5px 0; border-bottom: 1px solid var(--rule); vertical-align: top; }
|
||||
.loop-end-phases code { font-family: var(--mono); font-size: 12px; }
|
||||
.loop-end-files { margin: 0; padding-left: 18px; font-family: var(--mono); font-size: 12px; color: var(--ink-2); }
|
||||
.loop-end-actions { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
@@ -6,8 +6,8 @@
|
||||
appearance: none;
|
||||
flex: none;
|
||||
margin-left: 14px;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
@@ -17,7 +17,7 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
.icon-btn:hover { background: var(--panel-2); border-color: var(--rule); }
|
||||
.icon-btn svg { width: 17px; height: 17px; }
|
||||
.icon-btn svg { width: 22px; height: 22px; }
|
||||
.icon-btn .ab-ring { fill: none; stroke: var(--ink-3); stroke-width: 1.4; }
|
||||
.icon-btn .ab-mark { fill: none; stroke: var(--ink-2); stroke-width: 1.5; stroke-linecap: round; }
|
||||
.icon-btn .ab-dot { fill: var(--ink-2); }
|
||||
|
||||
@@ -210,10 +210,12 @@
|
||||
flex: none;
|
||||
margin: 0 2px 0 2px;
|
||||
padding: 1px 5px;
|
||||
border: 1px solid var(--rule-2);
|
||||
border: 1px solid var(--accent-line);
|
||||
border-radius: 999px;
|
||||
color: var(--ink-3);
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
font-size: 10.5px;
|
||||
font-weight: 600;
|
||||
line-height: 1.3;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@@ -74,6 +74,7 @@
|
||||
/* ------------------------------------------------------------ options */
|
||||
|
||||
.options { list-style: none; margin: 20px 0 0; padding: 0; display: grid; gap: 9px; }
|
||||
.options-clear { margin-top: 10px; }
|
||||
|
||||
.option {
|
||||
display: flex;
|
||||
@@ -772,6 +773,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
.modal.looks { max-width: 720px; }
|
||||
.modal.looks .modal-ranges + .modal-ranges { margin-top: 18px; }
|
||||
.looks-row { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.looks-row.four { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.looks-row .help { grid-column: 1 / -1; }
|
||||
/* The Desktop app group exists only inside the app; elsewhere it stays hidden
|
||||
in spite of the grid above. */
|
||||
@@ -783,7 +785,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
.looks-sound-events.is-off label { cursor: default; }
|
||||
.looks-sound-events.is-off label:hover { border-color: var(--rule-2); }
|
||||
@media (max-width: 720px) {
|
||||
.looks-row { grid-template-columns: 1fr; }
|
||||
.looks-row, .looks-row.four { grid-template-columns: 1fr; }
|
||||
}
|
||||
/* User Preferences itself (not the dialogs borrowing .looks): wider, and only
|
||||
the body scrolls, so Back to default and Done never leave the screen. */
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/* prefs.css: User Preferences' tabs (the side list, the narrow strip), the Saved
|
||||
mark, the Agents & models table and form, and the unsaved prompt. */
|
||||
|
||||
/* --------------------------------------------------------- tabs and panels */
|
||||
|
||||
.prefs-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 200px minmax(0, 1fr);
|
||||
gap: 20px;
|
||||
align-items: start;
|
||||
}
|
||||
.prefs-tabs {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
.prefs-tab {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 2px;
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border: 0;
|
||||
border-left: 3px solid transparent;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: var(--ink-2);
|
||||
font: inherit;
|
||||
font-size: 13.5px;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.prefs-tab:hover { background: var(--panel-2); color: var(--ink); }
|
||||
.prefs-tab[aria-selected="true"] { background: var(--accent-soft); color: var(--accent); border-left-color: var(--accent); font-weight: 600; }
|
||||
.prefs-tab:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; }
|
||||
.prefs-tab-label { display: block; line-height: 1.3; }
|
||||
.prefs-tab-hint { display: block; font-size: 12px; line-height: 1.35; color: var(--ink-3); }
|
||||
|
||||
.prefs-panels { min-width: 0; }
|
||||
.prefs-panel[hidden] { display: none; }
|
||||
|
||||
/* --------------------------------------------------------- Saved mark */
|
||||
|
||||
/* At the fieldset's top right, level with its legend. Out of the flow: the
|
||||
fieldsets are grids (the shared range and row classes), where an in-flow mark
|
||||
would take a cell and push the choices about. It fades out after about
|
||||
2 s when the JS adds `is-saved`; an `error` stays put and never fades. */
|
||||
.prefs-panel fieldset { position: relative; }
|
||||
.prefs-saved {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
max-width: 60%;
|
||||
font-size: 12px;
|
||||
line-height: 1.3;
|
||||
text-align: right;
|
||||
color: var(--ok);
|
||||
opacity: 0;
|
||||
}
|
||||
.prefs-saved.is-saved { opacity: 1; }
|
||||
.prefs-saved.error { color: var(--danger, #d64545); opacity: 1; }
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
@keyframes prefs-saved-fade {
|
||||
0%, 70% { opacity: 1; }
|
||||
100% { opacity: 0; }
|
||||
}
|
||||
.prefs-saved.is-saved { animation: prefs-saved-fade 2s ease-out forwards; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.prefs-saved.is-saved { opacity: 1; }
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- Agents & models */
|
||||
|
||||
.prefs-agents { display: grid; gap: 10px; }
|
||||
.prefs-agents > .help { margin: 0; }
|
||||
.prefs-agents [hidden] { display: none; }
|
||||
#agents-status:empty { display: none; }
|
||||
#agents-status.error { color: var(--danger, #d64545); }
|
||||
#agents-add { justify-self: start; }
|
||||
|
||||
.prefs-agents-table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
|
||||
.prefs-agents-table th {
|
||||
text-align: left;
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
color: var(--ink-3);
|
||||
padding: 4px 8px;
|
||||
border-bottom: 1px solid var(--rule-2);
|
||||
}
|
||||
.prefs-agents-table td { padding: 8px; border-bottom: 1px solid var(--rule-2); vertical-align: top; }
|
||||
.prefs-agents-name span, .prefs-agents-name code { display: block; }
|
||||
.prefs-agents-name code { font-size: 12px; color: var(--ink-3); }
|
||||
.prefs-agents-name .help { margin-top: 2px; font-size: 12px; }
|
||||
.prefs-agents-models { color: var(--ink-2); overflow-wrap: anywhere; }
|
||||
.prefs-agents-edit { text-align: right; }
|
||||
.prefs-agents-soon td { color: var(--ink-3); font-style: italic; }
|
||||
|
||||
.prefs-badge, .prefs-unsaved-badge {
|
||||
display: inline-block;
|
||||
font-size: 11.5px;
|
||||
line-height: 1.5;
|
||||
padding: 0 7px;
|
||||
border-radius: 10px;
|
||||
background: var(--panel-2);
|
||||
color: var(--ink-3);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.prefs-badge.ok { color: var(--ok); }
|
||||
.prefs-badge.missing { color: var(--warn); }
|
||||
.prefs-unsaved-badge { background: none; border: 1px solid var(--warn); color: var(--warn); }
|
||||
|
||||
.prefs-agents-form { display: grid; gap: 10px; }
|
||||
.prefs-agents-back { justify-self: start; }
|
||||
.prefs-agents-title { display: flex; align-items: baseline; gap: 8px; margin: 0; font-size: 15px; }
|
||||
.prefs-agents-title code { font-size: 12px; color: var(--ink-3); }
|
||||
.prefs-agents-title:focus { outline: none; }
|
||||
.prefs-agents-fields { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px 14px; }
|
||||
.prefs-agents-fields > .models-note,
|
||||
.prefs-agents-fields > [data-field="models"],
|
||||
.prefs-agents-fields > .prefs-agents-args,
|
||||
.prefs-agents-fields > .agent-field:has(> .models-list),
|
||||
.prefs-agents-fields > .agent-field:has(> .prefs-agents-none) { grid-column: 1 / -1; }
|
||||
.prefs-agents-form input { min-width: 0; }
|
||||
.prefs-agents-form input.invalid { border-color: var(--danger, #d64545); }
|
||||
.prefs-agents-test { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.prefs-agents-test .help { margin: 0; }
|
||||
.prefs-agents-none { margin: 0; }
|
||||
.prefs-agents-args { display: grid; gap: 8px; }
|
||||
.prefs-agents-args > summary { cursor: pointer; color: var(--accent); font-size: 13px; }
|
||||
.prefs-agents-args[open] > summary { margin-bottom: 4px; }
|
||||
.prefs-agents-args > .agent-field + .agent-field { margin-top: 8px; }
|
||||
/* The Saved mark sits in the form's foot, in the flow, after the buttons. */
|
||||
.prefs-agents-foot > .prefs-saved { position: static; max-width: none; text-align: left; }
|
||||
|
||||
/* --------------------------------------------------------- unsaved prompt */
|
||||
|
||||
/* Over the dialog, inside it: never the browser's confirm(). */
|
||||
.prefs-unsaved {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 5;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 16px;
|
||||
background: color-mix(in srgb, var(--bg, #000) 55%, transparent);
|
||||
}
|
||||
.prefs-unsaved[hidden] { display: none; }
|
||||
.prefs-unsaved-box {
|
||||
max-width: 380px;
|
||||
padding: 16px 18px;
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: 10px;
|
||||
background: var(--panel);
|
||||
box-shadow: 0 8px 30px rgb(0 0 0 / 0.25);
|
||||
}
|
||||
.prefs-unsaved-box h3 { margin: 0 0 6px; font-size: 15px; }
|
||||
.prefs-unsaved-box p { margin: 0 0 12px; }
|
||||
.prefs-unsaved-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
|
||||
/* --------------------------------------------------------- narrow screens */
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.prefs-layout { grid-template-columns: 1fr; gap: 12px; }
|
||||
.prefs-tabs {
|
||||
flex-direction: row;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
padding: 0 0 4px;
|
||||
-webkit-mask-image: linear-gradient(to right, #000 calc(100% - 32px), transparent);
|
||||
mask-image: linear-gradient(to right, #000 calc(100% - 32px), transparent);
|
||||
}
|
||||
.prefs-tab {
|
||||
width: auto;
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
border-left: 0;
|
||||
border-bottom: 3px solid transparent;
|
||||
border-radius: 6px 6px 0 0;
|
||||
}
|
||||
.prefs-tab[aria-selected="true"] { border-bottom-color: var(--accent); }
|
||||
.prefs-tab-hint { display: none; }
|
||||
.prefs-agents-models { display: none; }
|
||||
.prefs-agents-fields { grid-template-columns: 1fr; }
|
||||
}
|
||||
@@ -96,8 +96,6 @@
|
||||
}
|
||||
|
||||
/* User Preferences: the launcher's model menu. */
|
||||
.models-tabs { display: flex; gap: 6px; }
|
||||
.models-tabs .btn[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
|
||||
.models-note { font-size: 0.9em; opacity: 0.85; }
|
||||
.models-note p, .models-note ul { margin: 0 0 6px; }
|
||||
.models-note ul { padding-left: 18px; }
|
||||
@@ -108,13 +106,6 @@
|
||||
.models-row input { min-width: 0; }
|
||||
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.models-actions .help.error { color: var(--danger, #d64545); }
|
||||
.agents-list { display: grid; gap: 10px; }
|
||||
.agents-list:empty { display: none; }
|
||||
.agent-card { display: grid; gap: 8px; padding: 10px; border: 1px solid var(--rule-2); border-radius: 8px; }
|
||||
.agent-card.invalid { border-color: var(--danger, #d64545); }
|
||||
.agent-card input { min-width: 0; }
|
||||
.agent-card input.invalid { border-color: var(--danger, #d64545); }
|
||||
.agent-top { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 6px; }
|
||||
.agent-field { display: grid; gap: 4px; min-width: 0; }
|
||||
.agent-field > span, .agent-field > label { font-size: 0.85em; opacity: 0.85; }
|
||||
.agent-rows { display: grid; gap: 4px; }
|
||||
@@ -124,7 +115,6 @@
|
||||
.agent-foot .help { margin: 0; }
|
||||
.agent-foot .agent-test-result { flex: 1 1 auto; }
|
||||
.agent-error { margin: 0; color: var(--danger, #d64545); font-size: 0.9em; }
|
||||
#agents-replace[hidden] { display: none; }
|
||||
|
||||
/* User Preferences: Cleanup's list of what would go, shown before anything
|
||||
is deleted. */
|
||||
|
||||
@@ -178,7 +178,7 @@ h1 {
|
||||
grows to fill the row, so the icon buttons would sit beside the title. The
|
||||
first takes the slack instead; with the block shown its flex already eats
|
||||
the space, so this costs nothing. */
|
||||
#btn-about { margin-left: auto; }
|
||||
#btn-looks { margin-left: auto; }
|
||||
|
||||
.progress-label {
|
||||
display: flex;
|
||||
@@ -516,6 +516,8 @@ h1 {
|
||||
.footer.is-dash .footer-actions { display: none; }
|
||||
.footer.is-dash .footer-where { grid-column: 2; }
|
||||
.footer.is-dash-done .footer-actions { display: none; }
|
||||
.footer.is-loop-idle .footer-summary,
|
||||
.footer.is-loop-idle .footer-actions { visibility: hidden; }
|
||||
.hint { font-size: 12.5px; color: var(--ink-3); display: flex; align-items: center; gap: 7px; }
|
||||
/* A label, not a sentence: the full reason rides in the hint's tooltip, and
|
||||
the dock already carries the ticking clock this would otherwise repeat. */
|
||||
@@ -544,7 +546,7 @@ kbd {
|
||||
justify-items: center;
|
||||
}
|
||||
.waiting-pane h2 { font: 600 23px/1.3 var(--serif); color: var(--ink); margin: 0; }
|
||||
.waiting-pane p { margin: 0; }
|
||||
.waiting-pane p { max-width: 70ch; margin: 0; }
|
||||
/* The words that open the tasks tab: bold in the highlight color, a button
|
||||
that reads as part of the sentence. */
|
||||
.waiting-jump {
|
||||
|
||||
@@ -46,6 +46,7 @@
|
||||
which validates the saved choice and paints data-width on first load. */
|
||||
:root[data-width="narrow"] { --card-width: 720px; }
|
||||
:root[data-width="wide"] { --card-width: 1080px; }
|
||||
:root[data-width="ultrawide"] { --card-width: 1440px; }
|
||||
|
||||
/* Dark is written twice on purpose, and the duplication is the whole mechanism.
|
||||
The first copy follows the system unless the person has explicitly asked for
|
||||
|
||||
@@ -89,7 +89,9 @@ export function cleanSetting(input) {
|
||||
|
||||
/* ------------------------------------------------------------ the lines */
|
||||
|
||||
// The non-editable part of every "on" block (FR-8).
|
||||
// The non-editable part an "on" block used to carry (FR-8). The block now says
|
||||
// state, strength and limit in one line; these sentences move to
|
||||
// console-subagents.md (Phase 5). Still exported for the suites that read them.
|
||||
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-subagents.md); questions for the person stay with you.",
|
||||
@@ -99,7 +101,7 @@ export const FRAME_LINES = Object.freeze([
|
||||
|
||||
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
|
||||
|
||||
// The profile line each strength adds to an "on" block.
|
||||
// The profile sentence each strength used to add to an "on" block; see FRAME_LINES.
|
||||
export const STRENGTH_LINES = Object.freeze({
|
||||
balanced: "Helper strength: balanced (the table in helper-strength.md as written).",
|
||||
thrifty: "Helper strength: thrifty (one step lighter in strength and effort than the table; reviews never below standard).",
|
||||
@@ -109,20 +111,20 @@ export const STRENGTH_LINES = Object.freeze({
|
||||
|
||||
// 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, strength }) {
|
||||
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
|
||||
export function onLines({ max, instruction, strength }) {
|
||||
const own = String(instruction || "")
|
||||
.split("\n")
|
||||
.map((line) => line.trimEnd())
|
||||
.filter((line) => line.trim());
|
||||
const word = STRENGTHS.includes(strength) ? strength : DEFAULT_STRENGTH;
|
||||
return [
|
||||
`Subagents: on (${label}) — a console setting, not typed by the person.`,
|
||||
...[...FRAME_LINES, ...own, STRENGTH_LINES[strength] || STRENGTH_LINES[DEFAULT_STRENGTH], `At most ${max} helpers at once.`].map((line) => " " + line),
|
||||
`Subagents: on, ${word} strength, at most ${max} helpers at once (a console setting, not typed by the person).`,
|
||||
...own.map((line) => " " + line),
|
||||
];
|
||||
}
|
||||
|
||||
export function offLine(revision) {
|
||||
return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`;
|
||||
export function offLine() {
|
||||
return "Subagents: off. Start no new helpers for the rest of this session.";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// Plan2Code Web Console - tabs shared by Help and User Preferences.
|
||||
//
|
||||
// The WAI-ARIA tabs pattern over panels built once in the markup and shown or
|
||||
// hidden: role="tab" buttons linked to their role="tabpanel", roving
|
||||
// tabindex, automatic activation, arrow keys plus Home and End. No DOM access
|
||||
// at module scope: `node --test` imports tabKeyTarget from here.
|
||||
|
||||
// The tab index a key moves to, or -1 when the key is not a tab key.
|
||||
export function tabKeyTarget(key, index, count) {
|
||||
switch (key) {
|
||||
case "ArrowDown":
|
||||
case "ArrowRight":
|
||||
return (index + 1) % count;
|
||||
case "ArrowUp":
|
||||
case "ArrowLeft":
|
||||
return (index - 1 + count) % count;
|
||||
case "Home":
|
||||
return 0;
|
||||
case "End":
|
||||
return count - 1;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// Below Help's breakpoint the side list becomes a strip across the top.
|
||||
const NARROW = "(max-width: 720px)";
|
||||
|
||||
// `tabs` is [{ id, label, hint? }], `list` the role="tablist" element and
|
||||
// `panels` the element holding one child per tab marked data-tab="<id>".
|
||||
// `beforeSelect(from, to)` returning false, or a Promise of false, holds the
|
||||
// switch; `onSelect(id)` runs after one.
|
||||
export function wireTabs({ tabs, list, panels, prefix, tabClass, renderTab, beforeSelect, onSelect }) {
|
||||
const tabId = (id) => `${prefix}-tab-${id}`;
|
||||
const panelId = (id) => `${prefix}-panel-${id}`;
|
||||
let selected = null;
|
||||
|
||||
for (const t of tabs) {
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
btn.className = tabClass;
|
||||
btn.id = tabId(t.id);
|
||||
btn.setAttribute("role", "tab");
|
||||
btn.setAttribute("aria-controls", panelId(t.id));
|
||||
btn.setAttribute("aria-selected", "false");
|
||||
btn.tabIndex = -1;
|
||||
if (renderTab) renderTab(t, btn);
|
||||
else {
|
||||
const label = document.createElement("span");
|
||||
label.textContent = t.label;
|
||||
btn.appendChild(label);
|
||||
}
|
||||
btn.addEventListener("click", () => select(t.id));
|
||||
list.appendChild(btn);
|
||||
const panel = panels.querySelector(`[data-tab="${t.id}"]`);
|
||||
panel.id = panelId(t.id);
|
||||
panel.setAttribute("role", "tabpanel");
|
||||
panel.setAttribute("aria-labelledby", tabId(t.id));
|
||||
panel.tabIndex = 0;
|
||||
panel.hidden = true;
|
||||
}
|
||||
|
||||
list.addEventListener("keydown", (e) => {
|
||||
const current = tabs.findIndex((t) => tabId(t.id) === e.target.id);
|
||||
if (current < 0) return;
|
||||
const n = tabKeyTarget(e.key, current, tabs.length);
|
||||
if (n < 0) return;
|
||||
e.preventDefault();
|
||||
select(tabs[n].id, { focus: true });
|
||||
});
|
||||
|
||||
const narrow = matchMedia(NARROW);
|
||||
const orient = () => list.setAttribute("aria-orientation", narrow.matches ? "horizontal" : "vertical");
|
||||
orient();
|
||||
narrow.addEventListener("change", orient);
|
||||
|
||||
async function select(id, { focus = false } = {}) {
|
||||
if (beforeSelect && selected !== null && selected !== id) {
|
||||
// Awaited only when it is a Promise, so a plain answer switches in this
|
||||
// same tick and a caller can focus the new tab straight after.
|
||||
let go = beforeSelect(selected, id);
|
||||
if (go && typeof go.then === "function") go = await go;
|
||||
if (go === false) {
|
||||
// Held: focus stays on the tab still selected.
|
||||
if (focus) document.getElementById(tabId(selected)).focus();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (const t of tabs) {
|
||||
const on = t.id === id;
|
||||
const btn = document.getElementById(tabId(t.id));
|
||||
btn.setAttribute("aria-selected", String(on));
|
||||
btn.tabIndex = on ? 0 : -1;
|
||||
document.getElementById(panelId(t.id)).hidden = !on;
|
||||
}
|
||||
selected = id;
|
||||
if (onSelect) onSelect(id);
|
||||
if (focus) document.getElementById(tabId(id)).focus();
|
||||
return true;
|
||||
}
|
||||
|
||||
return { select, current: () => selected };
|
||||
}
|
||||
@@ -1,6 +1,18 @@
|
||||
// Plan2Code Web Console - the tones: short synthesized blips for the activities, silent when Play sounds is off; defines only.
|
||||
|
||||
import { looks } from "./looks.js";
|
||||
import snakeSfx from "./activities/snake-sfx.js";
|
||||
import golfSfx from "./activities/golf-sfx.js";
|
||||
import trailsSfx from "./activities/trails-sfx.js";
|
||||
import bugsSfx from "./activities/bugs-sfx.js";
|
||||
import driveSfx from "./activities/drive-sfx.js";
|
||||
import stackSfx from "./activities/stack-sfx.js";
|
||||
import bumperSfx from "./activities/bumper-sfx.js";
|
||||
import rapidsSfx from "./activities/rapids-sfx.js";
|
||||
import fuseSfx from "./activities/fuse-sfx.js";
|
||||
import hopSfx from "./activities/hop-sfx.js";
|
||||
import bounceSfx from "./activities/bounce-sfx.js";
|
||||
import ghoulSfx from "./activities/ghoul-sfx.js";
|
||||
|
||||
/* ------------------------------------------------------------- tones
|
||||
|
||||
@@ -14,7 +26,7 @@ import { looks } from "./looks.js";
|
||||
Every sound here is short (a quarter second at most) and quiet, so a cue
|
||||
never outlasts the moment it belongs to. A tone either sweeps from one
|
||||
pitch to another, or plays `notes` one after another in its time. */
|
||||
const TONES = Object.freeze({
|
||||
const BLIPS = Object.freeze({
|
||||
eat: Object.freeze({ type: "triangle", from: 660, to: 880, seconds: 0.12 }),
|
||||
crash: Object.freeze({ type: "sawtooth", from: 220, to: 80, seconds: 0.2 }),
|
||||
// The 3, 2, 1 before a round starts or plays on: a tick per number, then a
|
||||
@@ -52,8 +64,337 @@ const TONES = Object.freeze({
|
||||
shield: Object.freeze({ type: "sine", from: 1200, to: 500, seconds: 0.14 }),
|
||||
zap: Object.freeze({ type: "sawtooth", from: 1400, to: 200, seconds: 0.15 }),
|
||||
best: Object.freeze({ type: "triangle", notes: Object.freeze([784, 988, 1175, 1568]), seconds: 0.25 }),
|
||||
// Stack Deploy: a block landing (a low thunk), the overhang sliced off,
|
||||
// and a perfect drop's chime. The game pitches the thunk and the chime up
|
||||
// a step of a scale for each perfect in a row.
|
||||
thunk: Object.freeze({ type: "triangle", from: 240, to: 110, seconds: 0.1 }),
|
||||
slice: Object.freeze({ type: "square", from: 560, to: 280, seconds: 0.06 }),
|
||||
perfect: Object.freeze({ type: "triangle", notes: Object.freeze([660, 990]), seconds: 0.14 }),
|
||||
// Bumper Ring: two cars meeting (a short thud the game pitches up and
|
||||
// makes louder the harder the hit) and a rival revving up a dash.
|
||||
ram: Object.freeze({ type: "square", from: 190, to: 70, seconds: 0.09 }),
|
||||
rev: Object.freeze({ type: "sawtooth", from: 90, to: 260, seconds: 0.18 }),
|
||||
// Hot Potato: the fuse's tick (the game ticks it quicker and pitches it
|
||||
// up as the fuse burns down) and the pop of the bomb changing hands.
|
||||
tick: Object.freeze({ type: "square", from: 1500, to: 1100, seconds: 0.03 }),
|
||||
pop: Object.freeze({ type: "sine", from: 480, to: 1400, seconds: 0.07 }),
|
||||
// Crossing Rush: a hop (the game pitches it up a step for each quick hop
|
||||
// forward in a row), the boing of being sent back, a crossing's bell while
|
||||
// a train is coming, and the Horn.
|
||||
hop: Object.freeze({ type: "triangle", from: 520, to: 780, seconds: 0.05 }),
|
||||
boing: Object.freeze({ type: "sine", from: 260, to: 720, seconds: 0.2 }),
|
||||
bell: Object.freeze({ type: "triangle", notes: Object.freeze([1320, 990]), seconds: 0.16 }),
|
||||
horn: Object.freeze({ type: "square", notes: Object.freeze([370, 466]), seconds: 0.22 }),
|
||||
// Bounce Road: the engine's hum (a soft, low blip the game plays every few
|
||||
// frames while you pick up speed, pitched up with your speed: a triangle,
|
||||
// since a sawtooth blipped that often is a buzz), a jump's spring (pitched
|
||||
// with your speed) and a rival flattened under your wheels (pitched up a
|
||||
// step for each in a chain); all soft triangles, never a buzz. A low
|
||||
// thump rumbles while your wheels run on the verge.
|
||||
beat: Object.freeze({ type: "sine", from: 95, to: 55, seconds: 0.11 }),
|
||||
engine: Object.freeze({ type: "triangle", from: 82, to: 90, seconds: 0.08 }),
|
||||
spring: Object.freeze({ type: "triangle", from: 330, to: 990, seconds: 0.14 }),
|
||||
squash: Object.freeze({ type: "triangle", from: 620, to: 150, seconds: 0.13 }),
|
||||
// Rapids Run: a shot (a short, soft triangle, since it repeats about seven
|
||||
// times a second while fire is held, and the game plays it quietly), a
|
||||
// charge buoy taken (a rising sine), the low battery's two-note beep (the
|
||||
// game beeps quicker the lower it runs), a dam bursting open (a low
|
||||
// triangle rumble) and a bank skimmed at speed (a quick sine whoosh the
|
||||
// game pitches up the more you have skimmed); all soft triangles and
|
||||
// sines, never a buzz.
|
||||
pew: Object.freeze({ type: "triangle", from: 1320, to: 880, seconds: 0.04 }),
|
||||
charge: Object.freeze({ type: "sine", from: 440, to: 1320, seconds: 0.14 }),
|
||||
lowcell: Object.freeze({ type: "sine", notes: Object.freeze([660, 440]), seconds: 0.16 }),
|
||||
dambreak: Object.freeze({ type: "triangle", from: 300, to: 60, seconds: 0.25 }),
|
||||
skim: Object.freeze({ type: "sine", from: 1500, to: 1800, seconds: 0.05 }),
|
||||
// Ghoul Rush: the flashlight blaster's bolt (a short, soft triangle, since
|
||||
// it repeats every 100 ms while fire is held; the game nudges its pitch a
|
||||
// little each time), a ghoul torn apart (pitched up a step for each kill
|
||||
// in the chain), a stomp's crunch, a ghost's moan, a boss's low roar, a
|
||||
// soul's thin whisper (pitched up for souls taken in quick succession), a
|
||||
// zombie groaning behind a wall door, a bat's screech, the key turning
|
||||
// (a minor rise), the door through to the next room (a falling minor
|
||||
// run), a board creaking (a crawler coming up, a chandelier or a crumbling
|
||||
// board about to go), a hellhound's growl, a wraith's shriek, a widow's
|
||||
// skitter, a bloater's wet spit, and thunder rolling outside.
|
||||
ghoulBlast: Object.freeze({ type: "triangle", from: 980, to: 620, seconds: 0.05 }),
|
||||
ghoulStomp: Object.freeze({ type: "sawtooth", from: 220, to: 70, seconds: 0.09 }),
|
||||
ghoulBoo: Object.freeze({ type: "sine", from: 330, to: 196, seconds: 0.25 }),
|
||||
ghoulRoar: Object.freeze({ type: "sawtooth", from: 120, to: 48, seconds: 0.25 }),
|
||||
ghoulCandy: Object.freeze({ type: "sine", from: 1480, to: 1760, seconds: 0.09 }),
|
||||
zombiePop: Object.freeze({ type: "sawtooth", from: 260, to: 60, seconds: 0.12 }),
|
||||
zombieGroan: Object.freeze({ type: "sawtooth", from: 110, to: 72, seconds: 0.25 }),
|
||||
batSwoop: Object.freeze({ type: "square", from: 2200, to: 1400, seconds: 0.08 }),
|
||||
doorUnlock: Object.freeze({ type: "triangle", notes: Object.freeze([494, 587, 740]), seconds: 0.2 }),
|
||||
doorThrough: Object.freeze({ type: "triangle", notes: Object.freeze([659, 587, 494, 440]), seconds: 0.25 }),
|
||||
creakBoard: Object.freeze({ type: "triangle", from: 180, to: 120, seconds: 0.18 }),
|
||||
ghoulGrowl: Object.freeze({ type: "sawtooth", from: 95, to: 70, seconds: 0.22 }),
|
||||
ghoulShriek: Object.freeze({ type: "sawtooth", from: 1900, to: 2600, seconds: 0.2 }),
|
||||
ghoulSkitter: Object.freeze({ type: "square", notes: Object.freeze([2400, 2100, 2500, 2200]), seconds: 0.1 }),
|
||||
ghoulSpit: Object.freeze({ type: "square", from: 340, to: 110, seconds: 0.1 }),
|
||||
ghoulThunder: Object.freeze({ type: "sawtooth", from: 70, to: 30, seconds: 0.25 }),
|
||||
});
|
||||
|
||||
/* --------------------------------------------------------- rich tones
|
||||
|
||||
The shared sound kit every game may borrow, richer than a single blip:
|
||||
a spec here may be `layers`, parts that play together (each its own
|
||||
`delay` and `gain`), and a part may be noise ("noise" is white, "pink"
|
||||
and "brown" darker) shaped by a `filter` ({ type, from, to, q }) that
|
||||
sweeps its cutoff, wobble with `vibrato` ({ rate, depth }, depth a share
|
||||
of the pitch) or swell in over `attack` seconds. Noise is what makes a
|
||||
crash, a splash, a skid or an explosion sound like one rather than like
|
||||
a beep. These run up to a second, still quiet, and a game's own extras
|
||||
live in its `activities/<id>-sfx.js` (merged in below). */
|
||||
const part = (spec) => Object.freeze({ ...spec, ...(spec.notes ? { notes: Object.freeze(spec.notes) } : {}), ...(spec.filter ? { filter: Object.freeze(spec.filter) } : {}), ...(spec.vibrato ? { vibrato: Object.freeze(spec.vibrato) } : {}) });
|
||||
const layered = (...parts) => Object.freeze({ layers: Object.freeze(parts.map(part)) });
|
||||
|
||||
const RICH = Object.freeze({
|
||||
// Hits, crashes and explosions.
|
||||
explode: layered(
|
||||
{ type: "brown", seconds: 0.8, filter: { type: "lowpass", from: 2400, to: 90, q: 0.7 } },
|
||||
{ type: "sine", from: 140, to: 32, seconds: 0.55, gain: 0.9 },
|
||||
{ type: "noise", seconds: 0.12, gain: 0.35, filter: { type: "highpass", from: 3000, to: 1500 } },
|
||||
),
|
||||
blast: layered(
|
||||
{ type: "brown", seconds: 0.38, filter: { type: "lowpass", from: 1800, to: 140 } },
|
||||
{ type: "sine", from: 110, to: 40, seconds: 0.26, gain: 0.8 },
|
||||
),
|
||||
smash: layered(
|
||||
{ type: "noise", seconds: 0.36, filter: { type: "bandpass", from: 1800, to: 500, q: 1.1 } },
|
||||
{ type: "square", from: 180, to: 55, seconds: 0.2, gain: 0.45, filter: { type: "lowpass", from: 1400, to: 300 } },
|
||||
{ type: "noise", seconds: 0.28, delay: 0.04, gain: 0.25, filter: { type: "highpass", from: 5000, to: 3000 } },
|
||||
),
|
||||
thud: layered(
|
||||
{ type: "sine", from: 130, to: 48, seconds: 0.14 },
|
||||
{ type: "brown", seconds: 0.09, gain: 0.6, filter: { type: "lowpass", from: 500, to: 150 } },
|
||||
),
|
||||
clank: layered(
|
||||
{ type: "square", from: 820, to: 790, seconds: 0.08, gain: 0.45, filter: { type: "lowpass", from: 3000, to: 1500 } },
|
||||
{ type: "triangle", from: 1230, to: 1210, seconds: 0.22, gain: 0.5 },
|
||||
{ type: "noise", seconds: 0.04, gain: 0.4, filter: { type: "bandpass", from: 3200, to: 2600, q: 2 } },
|
||||
),
|
||||
crunch: layered(
|
||||
{ type: "noise", seconds: 0.18, filter: { type: "bandpass", from: 900, to: 280, q: 1.8 } },
|
||||
{ type: "sawtooth", from: 150, to: 60, seconds: 0.12, gain: 0.4, filter: { type: "lowpass", from: 900, to: 200 } },
|
||||
),
|
||||
squish: layered(
|
||||
{ type: "noise", seconds: 0.13, filter: { type: "lowpass", from: 1600, to: 200, q: 3 } },
|
||||
{ type: "sine", from: 420, to: 110, seconds: 0.11, gain: 0.6 },
|
||||
),
|
||||
splat: layered(
|
||||
{ type: "pink", seconds: 0.16, filter: { type: "bandpass", from: 1300, to: 380, q: 1.4 } },
|
||||
{ type: "sine", from: 300, to: 85, seconds: 0.12, gain: 0.6 },
|
||||
),
|
||||
hit: layered(
|
||||
{ type: "square", from: 320, to: 120, seconds: 0.07, gain: 0.6, filter: { type: "lowpass", from: 2400, to: 600 } },
|
||||
{ type: "noise", seconds: 0.05, gain: 0.5, filter: { type: "bandpass", from: 2200, to: 1400, q: 1.5 } },
|
||||
),
|
||||
// Movement: air, tires and landings.
|
||||
whoosh: layered({ type: "pink", seconds: 0.3, attack: 0.08, filter: { type: "bandpass", from: 400, to: 2600, q: 1.4 } }),
|
||||
swoosh: layered({ type: "pink", seconds: 0.26, attack: 0.04, filter: { type: "bandpass", from: 2600, to: 450, q: 1.4 } }),
|
||||
skid: layered(
|
||||
{ type: "noise", seconds: 0.38, attack: 0.02, filter: { type: "bandpass", from: 2300, to: 1700, q: 7 } },
|
||||
{ type: "triangle", from: 1500, to: 1280, seconds: 0.34, gain: 0.25, vibrato: { rate: 31, depth: 0.02 } },
|
||||
),
|
||||
brake: layered({ type: "noise", seconds: 0.3, attack: 0.03, filter: { type: "bandpass", from: 3100, to: 2500, q: 10 } }),
|
||||
zoom: layered(
|
||||
{ type: "sawtooth", from: 240, to: 130, seconds: 0.5, attack: 0.2, gain: 0.5, filter: { type: "lowpass", from: 1100, to: 380 } },
|
||||
{ type: "pink", seconds: 0.5, attack: 0.2, gain: 0.6, filter: { type: "bandpass", from: 900, to: 380, q: 1.2 } },
|
||||
),
|
||||
jump: layered(
|
||||
{ type: "triangle", from: 300, to: 760, seconds: 0.13 },
|
||||
{ type: "pink", seconds: 0.12, gain: 0.3, filter: { type: "highpass", from: 1400, to: 2600 } },
|
||||
),
|
||||
land: layered(
|
||||
{ type: "sine", from: 170, to: 60, seconds: 0.1 },
|
||||
{ type: "brown", seconds: 0.1, gain: 0.6, filter: { type: "lowpass", from: 700, to: 200 } },
|
||||
),
|
||||
shift: layered(
|
||||
{ type: "noise", seconds: 0.035, gain: 0.5, filter: { type: "bandpass", from: 2400, to: 2000, q: 3 } },
|
||||
{ type: "square", from: 160, to: 140, seconds: 0.05, gain: 0.4, filter: { type: "lowpass", from: 900, to: 500 } },
|
||||
),
|
||||
boost: layered(
|
||||
{ type: "sawtooth", from: 110, to: 460, seconds: 0.48, gain: 0.6, filter: { type: "lowpass", from: 400, to: 3200, q: 4 } },
|
||||
{ type: "pink", seconds: 0.48, gain: 0.45, filter: { type: "highpass", from: 1200, to: 4200 } },
|
||||
),
|
||||
riser: layered(
|
||||
{ type: "sawtooth", from: 200, to: 1200, seconds: 0.62, attack: 0.3, gain: 0.5, filter: { type: "lowpass", from: 600, to: 4200 } },
|
||||
{ type: "noise", seconds: 0.62, attack: 0.3, gain: 0.35, filter: { type: "bandpass", from: 500, to: 4000, q: 1 } },
|
||||
),
|
||||
honk: layered(
|
||||
{ type: "square", from: 392, to: 388, seconds: 0.24, gain: 0.55, filter: { type: "lowpass", from: 1600, to: 1400 } },
|
||||
{ type: "square", from: 494, to: 490, seconds: 0.24, gain: 0.55, filter: { type: "lowpass", from: 1600, to: 1400 } },
|
||||
),
|
||||
trainHorn: layered(
|
||||
{ type: "sawtooth", from: 311, to: 305, seconds: 0.85, attack: 0.05, gain: 0.4, filter: { type: "lowpass", from: 1500, to: 1200 } },
|
||||
{ type: "sawtooth", from: 370, to: 364, seconds: 0.85, attack: 0.05, gain: 0.4, filter: { type: "lowpass", from: 1500, to: 1200 } },
|
||||
{ type: "sawtooth", from: 466, to: 458, seconds: 0.85, attack: 0.05, gain: 0.3, filter: { type: "lowpass", from: 1500, to: 1200 } },
|
||||
),
|
||||
rumble: layered({ type: "brown", seconds: 0.06, filter: { type: "lowpass", from: 320, to: 200 } }),
|
||||
rumbleLong: layered(
|
||||
{ type: "brown", seconds: 1, attack: 0.2, filter: { type: "lowpass", from: 420, to: 160 } },
|
||||
{ type: "sine", from: 52, to: 44, seconds: 1, attack: 0.2, gain: 0.6 },
|
||||
),
|
||||
// Water.
|
||||
splashBig: layered(
|
||||
{ type: "noise", seconds: 0.42, filter: { type: "bandpass", from: 3200, to: 700, q: 0.7 } },
|
||||
{ type: "sine", from: 380, to: 95, seconds: 0.16, gain: 0.45 },
|
||||
{ type: "pink", seconds: 0.3, delay: 0.08, gain: 0.35, filter: { type: "highpass", from: 2500, to: 1500 } },
|
||||
),
|
||||
bubble: layered({ type: "sine", from: 300, to: 950, seconds: 0.06 }),
|
||||
slap: layered({ type: "pink", seconds: 0.15, filter: { type: "bandpass", from: 950, to: 480, q: 1.5 } }),
|
||||
// Rewards and the round.
|
||||
coinUp: layered(
|
||||
{ type: "square", notes: [988, 1319], seconds: 0.11, gain: 0.55, filter: { type: "lowpass", from: 5000, to: 5000 } },
|
||||
{ type: "triangle", from: 2637, to: 2637, seconds: 0.26, delay: 0.05, gain: 0.3 },
|
||||
),
|
||||
sparkle: layered(
|
||||
{ type: "triangle", notes: [1568, 2093, 2637, 3136], seconds: 0.22, gain: 0.5 },
|
||||
{ type: "noise", seconds: 0.22, gain: 0.15, filter: { type: "highpass", from: 6000, to: 8000 } },
|
||||
),
|
||||
powerUp: layered(
|
||||
{ type: "square", notes: [523, 659, 784, 1047, 1319], seconds: 0.36, gain: 0.45, filter: { type: "lowpass", from: 3000, to: 3000 } },
|
||||
{ type: "triangle", notes: [262, 330, 392, 523, 659], seconds: 0.36, gain: 0.6 },
|
||||
),
|
||||
powerDown: layered(
|
||||
{ type: "square", notes: [784, 659, 523, 392], seconds: 0.36, gain: 0.45, filter: { type: "lowpass", from: 2400, to: 1200 } },
|
||||
),
|
||||
extraLife: layered(
|
||||
{ type: "triangle", notes: [659, 784, 1319, 1047, 1175, 1568], seconds: 0.48 },
|
||||
{ type: "square", notes: [330, 392, 659, 523, 587, 784], seconds: 0.48, gain: 0.25, filter: { type: "lowpass", from: 2000, to: 2000 } },
|
||||
),
|
||||
fanfare: layered(
|
||||
{ type: "square", notes: [523, 523, 523, 659, 784, 784], seconds: 0.6, gain: 0.4, filter: { type: "lowpass", from: 2600, to: 2600 } },
|
||||
{ type: "triangle", notes: [262, 262, 262, 330, 392, 392], seconds: 0.6, gain: 0.7 },
|
||||
),
|
||||
victory: layered(
|
||||
{ type: "triangle", notes: [784, 988, 1175, 1568], seconds: 0.44 },
|
||||
{ type: "square", notes: [392, 494, 587, 784], seconds: 0.44, gain: 0.3, filter: { type: "lowpass", from: 2400, to: 2400 } },
|
||||
{ type: "noise", seconds: 0.3, delay: 0.3, gain: 0.12, filter: { type: "highpass", from: 7000, to: 9000 } },
|
||||
),
|
||||
gameOver: layered(
|
||||
{ type: "triangle", notes: [392, 370, 349, 330], seconds: 0.9 },
|
||||
{ type: "sawtooth", notes: [196, 185, 175, 165], seconds: 0.9, gain: 0.35, filter: { type: "lowpass", from: 900, to: 500 } },
|
||||
),
|
||||
lifeLost: layered(
|
||||
{ type: "square", from: 520, to: 120, seconds: 0.42, gain: 0.6, vibrato: { rate: 12, depth: 0.04 }, filter: { type: "lowpass", from: 2000, to: 600 } },
|
||||
),
|
||||
click: layered({ type: "square", from: 1200, to: 1150, seconds: 0.02, gain: 0.4 }),
|
||||
tickSoft: layered({ type: "noise", seconds: 0.025, filter: { type: "bandpass", from: 4200, to: 3800, q: 4 } }),
|
||||
warn: layered(
|
||||
{ type: "square", notes: [880, 660, 880, 660], seconds: 0.42, gain: 0.5, filter: { type: "lowpass", from: 2000, to: 2000 } },
|
||||
),
|
||||
// Sci-fi and combat.
|
||||
laser: layered(
|
||||
{ type: "square", from: 1800, to: 280, seconds: 0.12, gain: 0.5, filter: { type: "lowpass", from: 4500, to: 1200 } },
|
||||
{ type: "sawtooth", from: 900, to: 140, seconds: 0.12, gain: 0.3, filter: { type: "lowpass", from: 3000, to: 800 } },
|
||||
),
|
||||
zapBig: layered(
|
||||
{ type: "sawtooth", from: 2400, to: 80, seconds: 0.26, gain: 0.55, filter: { type: "lowpass", from: 5000, to: 600 } },
|
||||
{ type: "noise", seconds: 0.2, gain: 0.4, filter: { type: "bandpass", from: 3000, to: 500, q: 1 } },
|
||||
),
|
||||
shieldUp: layered(
|
||||
{ type: "sine", from: 300, to: 1200, seconds: 0.32, vibrato: { rate: 18, depth: 0.05 } },
|
||||
{ type: "triangle", from: 600, to: 2400, seconds: 0.32, gain: 0.3 },
|
||||
),
|
||||
warp: layered(
|
||||
{ type: "sine", from: 400, to: 1600, seconds: 0.34, vibrato: { rate: 24, depth: 0.08 } },
|
||||
{ type: "pink", seconds: 0.34, gain: 0.3, filter: { type: "bandpass", from: 600, to: 3600, q: 3 } },
|
||||
),
|
||||
bossIntro: layered(
|
||||
{ type: "sawtooth", from: 55, to: 52, seconds: 1, attack: 0.25, gain: 0.6, filter: { type: "lowpass", from: 300, to: 900, q: 3 } },
|
||||
{ type: "brown", seconds: 1, attack: 0.25, gain: 0.6, filter: { type: "lowpass", from: 220, to: 160 } },
|
||||
{ type: "square", notes: [110, 104, 98], seconds: 1, gain: 0.3, filter: { type: "lowpass", from: 600, to: 600 } },
|
||||
),
|
||||
// Spooky.
|
||||
doorCreak: layered(
|
||||
{ type: "sawtooth", from: 150, to: 92, seconds: 0.62, attack: 0.05, gain: 0.5, vibrato: { rate: 23, depth: 0.09 }, filter: { type: "bandpass", from: 900, to: 700, q: 3 } },
|
||||
),
|
||||
gust: layered({ type: "pink", seconds: 0.9, attack: 0.35, filter: { type: "bandpass", from: 300, to: 850, q: 1.2 } }),
|
||||
heartbeat: layered(
|
||||
{ type: "sine", from: 72, to: 45, seconds: 0.1 },
|
||||
{ type: "sine", from: 66, to: 42, seconds: 0.11, delay: 0.18, gain: 0.8 },
|
||||
),
|
||||
wail: layered({ type: "sine", from: 560, to: 880, seconds: 0.65, attack: 0.15, vibrato: { rate: 6, depth: 0.03 } }),
|
||||
// Crowds and wood.
|
||||
rattle: layered(
|
||||
{ type: "triangle", notes: [1200, 900, 1100, 820], seconds: 0.16, gain: 0.6 },
|
||||
{ type: "noise", seconds: 0.12, gain: 0.3, filter: { type: "bandpass", from: 3200, to: 2400, q: 2 } },
|
||||
),
|
||||
cheer: layered(
|
||||
{ type: "pink", seconds: 1, attack: 0.25, filter: { type: "bandpass", from: 900, to: 1400, q: 0.8 } },
|
||||
{ type: "noise", seconds: 1, attack: 0.25, gain: 0.2, filter: { type: "highpass", from: 3000, to: 3500 } },
|
||||
),
|
||||
aww: layered({ type: "pink", seconds: 0.85, attack: 0.1, filter: { type: "bandpass", from: 950, to: 480, q: 1.3 } }),
|
||||
applause: layered(
|
||||
...[0, 0.05, 0.11, 0.14, 0.2, 0.27, 0.31, 0.38, 0.43, 0.5].map((delay, i) => ({ type: "noise", seconds: 0.035, delay, gain: 0.6 + (i % 3) * 0.15, filter: { type: "bandpass", from: 1400 + (i % 4) * 300, to: 1200, q: 1.5 } })),
|
||||
),
|
||||
knock: layered(
|
||||
{ type: "triangle", from: 600, to: 560, seconds: 0.06 },
|
||||
{ type: "noise", seconds: 0.03, gain: 0.5, filter: { type: "bandpass", from: 1800, to: 1500, q: 2 } },
|
||||
),
|
||||
crumble: layered(
|
||||
{ type: "brown", seconds: 0.55, filter: { type: "lowpass", from: 900, to: 100 } },
|
||||
...[0, 0.07, 0.15, 0.24].map((delay) => ({ type: "noise", seconds: 0.04, delay, gain: 0.35, filter: { type: "bandpass", from: 1600, to: 900, q: 2 } })),
|
||||
),
|
||||
hiss: layered({ type: "noise", seconds: 0.4, attack: 0.03, gain: 0.6, filter: { type: "highpass", from: 3000, to: 5200 } }),
|
||||
squeak: layered({ type: "sine", from: 1800, to: 2400, seconds: 0.05 }),
|
||||
});
|
||||
|
||||
/* --------------------------------------------------------------- hums
|
||||
|
||||
A hum is a sound that runs for as long as a game keeps asking for it: a
|
||||
car's engine, a boat's outboard, the river, a light cycle, a fuse's hiss.
|
||||
A game calls hum(id, name, level, pitch) every frame it wants it, `id`
|
||||
telling one voice from another (your car and a rival's), and pitch
|
||||
following its speed. A hum not asked for again within HUM_HOLD_MS fades
|
||||
out by itself, so a paused, closed or finished game falls quiet without
|
||||
saying so; hushTones() quiets them all at once. Each hum is oscillators
|
||||
(`parts`, each its own frequency and gain) and noise (`noise`) through one
|
||||
filter whose cutoff follows the pitch by `follow` (1 tracks it exactly, 0
|
||||
holds still), pulsed by `pulse` ({ rate, depth }, the rate following the
|
||||
pitch): an engine's firing strokes or a train's clatter. */
|
||||
const hums = (table) => Object.freeze(Object.fromEntries(Object.entries(table).map(([k, v]) => [k, Object.freeze(v)])));
|
||||
|
||||
const HUMS = hums({
|
||||
car: { parts: [{ type: "sawtooth", freq: 46 }, { type: "sawtooth", freq: 46.5, gain: 0.7 }, { type: "square", freq: 23, gain: 0.5 }], noise: { color: "brown", gain: 0.2 }, filter: { type: "lowpass", freq: 360, q: 4, follow: 0.9 }, pulse: { rate: 11, depth: 0.45 }, peak: 0.06 },
|
||||
toycar: { parts: [{ type: "square", freq: 90 }, { type: "square", freq: 90.8, gain: 0.5 }], filter: { type: "lowpass", freq: 850, q: 2, follow: 1 }, pulse: { rate: 20, depth: 0.5 }, peak: 0.04 },
|
||||
electric: { parts: [{ type: "sawtooth", freq: 60 }, { type: "sine", freq: 120, gain: 0.5 }, { type: "sine", freq: 620, gain: 0.12 }], filter: { type: "lowpass", freq: 520, q: 2, follow: 0.8 }, peak: 0.045 },
|
||||
outboard: { parts: [{ type: "sawtooth", freq: 38 }, { type: "square", freq: 76, gain: 0.4 }], noise: { color: "brown", gain: 0.35 }, filter: { type: "lowpass", freq: 430, q: 3, follow: 0.9 }, pulse: { rate: 16, depth: 0.6 }, peak: 0.06 },
|
||||
river: { noise: { color: "brown", gain: 1 }, filter: { type: "lowpass", freq: 650, q: 0.5, follow: 1 }, pulse: { rate: 0.4, depth: 0.3 }, peak: 0.05 },
|
||||
wind: { noise: { color: "pink", gain: 1 }, filter: { type: "bandpass", freq: 600, q: 0.8, follow: 1 }, pulse: { rate: 0.3, depth: 0.4 }, peak: 0.04 },
|
||||
cycle: { parts: [{ type: "sawtooth", freq: 98 }, { type: "sawtooth", freq: 98.6 }, { type: "sawtooth", freq: 196.3, gain: 0.3 }], filter: { type: "lowpass", freq: 1100, q: 6, follow: 0.8 }, peak: 0.03 },
|
||||
fuse: { noise: { color: "noise", gain: 1 }, filter: { type: "highpass", freq: 3500, q: 0.7, follow: 0.5 }, pulse: { rate: 23, depth: 0.55 }, peak: 0.03 },
|
||||
haunt: { parts: [{ type: "sine", freq: 55 }, { type: "sine", freq: 55.8 }, { type: "triangle", freq: 82.4, gain: 0.3 }], filter: { type: "lowpass", freq: 400, q: 1, follow: 0.5 }, pulse: { rate: 0.3, depth: 0.5 }, peak: 0.045 },
|
||||
squeal: { parts: [{ type: "triangle", freq: 1450, gain: 0.2 }], noise: { color: "noise", gain: 1 }, filter: { type: "bandpass", freq: 1900, q: 9, follow: 1 }, peak: 0.035 },
|
||||
meter: { parts: [{ type: "triangle", freq: 220 }, { type: "square", freq: 220.5, gain: 0.25 }], filter: { type: "lowpass", freq: 1200, q: 1, follow: 1 }, peak: 0.025 },
|
||||
swarm: { parts: [{ type: "sawtooth", freq: 180 }, { type: "sawtooth", freq: 183 }, { type: "sawtooth", freq: 177 }], filter: { type: "bandpass", freq: 900, q: 2, follow: 1 }, pulse: { rate: 30, depth: 0.5 }, peak: 0.02 },
|
||||
train: { parts: [{ type: "square", freq: 60, gain: 0.4 }], noise: { color: "brown", gain: 1 }, filter: { type: "lowpass", freq: 520, q: 1, follow: 0.7 }, pulse: { rate: 4, depth: 0.7 }, peak: 0.05 },
|
||||
crowd: { noise: { color: "pink", gain: 1 }, filter: { type: "bandpass", freq: 1100, q: 0.6, follow: 0.6 }, pulse: { rate: 0.5, depth: 0.4 }, peak: 0.02 },
|
||||
});
|
||||
|
||||
// Every game's own extras, merged after the shared kit; a name may be
|
||||
// defined only once across them all (the activities suite checks).
|
||||
const GAME_SFX = Object.freeze([snakeSfx, golfSfx, trailsSfx, bugsSfx, driveSfx, stackSfx, bumperSfx, rapidsSfx, fuseSfx, hopSfx, bounceSfx, ghoulSfx]);
|
||||
|
||||
// A game file holds plain objects; they are frozen here, all the way down.
|
||||
const deepFreeze = (o) => {
|
||||
if (o && typeof o === "object") Object.values(o).forEach(deepFreeze);
|
||||
return Object.freeze(o);
|
||||
};
|
||||
|
||||
export const TONE_TABLES = Object.freeze([BLIPS, RICH, ...GAME_SFX.map((s) => deepFreeze(s.tones || {}))]);
|
||||
export const HUM_TABLES = Object.freeze([HUMS, ...GAME_SFX.map((s) => deepFreeze(s.hums || {}))]);
|
||||
// And each game's chiptune tracks, which music.js plays.
|
||||
export const MUSIC_TABLES = Object.freeze(GAME_SFX.map((s) => deepFreeze(s.music || {})));
|
||||
|
||||
const TONES = Object.freeze(Object.assign({}, ...TONE_TABLES));
|
||||
const ALL_HUMS = Object.freeze(Object.assign({}, ...HUM_TABLES));
|
||||
|
||||
export const toneNames = () => Object.keys(TONES);
|
||||
export const humNames = () => Object.keys(ALL_HUMS);
|
||||
|
||||
// Peak gain, kept modest so a blip sits under the page rather than over it.
|
||||
const PEAK = 0.08;
|
||||
|
||||
@@ -62,8 +403,18 @@ const PEAK = 0.08;
|
||||
const ATTACK = 0.01;
|
||||
const FLOOR = 0.0001;
|
||||
|
||||
// At most this many parts of rich tones sounding at once: a frantic moment
|
||||
// drops one rather than piling up enough voices to stutter the page.
|
||||
const MAX_VOICES = 48;
|
||||
|
||||
let ctx = null;
|
||||
|
||||
let bus = null;
|
||||
|
||||
const noiseBuffers = new Map();
|
||||
|
||||
let voiceEnds = [];
|
||||
|
||||
// Made on first use, not at load, so importing this file in Node is harmless.
|
||||
// A missing AudioContext or a constructor that throws both give null.
|
||||
function audioContext() {
|
||||
@@ -77,6 +428,68 @@ function audioContext() {
|
||||
return ctx;
|
||||
}
|
||||
|
||||
// Everything plays through one gentle compressor, so an explosion over an
|
||||
// engine over a shot never clips; a context without one plays straight out.
|
||||
function out(c) {
|
||||
if (bus) return bus;
|
||||
if (typeof c.createDynamicsCompressor !== "function") return c.destination;
|
||||
const comp = c.createDynamicsCompressor();
|
||||
comp.threshold.value = -20;
|
||||
comp.knee.value = 12;
|
||||
comp.ratio.value = 4;
|
||||
comp.attack.value = 0.003;
|
||||
comp.release.value = 0.2;
|
||||
comp.connect(c.destination);
|
||||
bus = comp;
|
||||
return bus;
|
||||
}
|
||||
|
||||
// Two seconds of noise per color, made once and looped from a random point.
|
||||
function noiseBuffer(c, color) {
|
||||
if (noiseBuffers.has(color)) return noiseBuffers.get(color);
|
||||
const length = Math.floor(c.sampleRate * 2);
|
||||
const buf = c.createBuffer(1, length, c.sampleRate);
|
||||
const data = buf.getChannelData(0);
|
||||
let b0 = 0, b1 = 0, b2 = 0, last = 0;
|
||||
for (let i = 0; i < length; i++) {
|
||||
const w = Math.random() * 2 - 1;
|
||||
if (color === "pink") {
|
||||
b0 = 0.99765 * b0 + w * 0.099046;
|
||||
b1 = 0.963 * b1 + w * 0.2965164;
|
||||
b2 = 0.57 * b2 + w * 1.0526913;
|
||||
data[i] = (b0 + b1 + b2 + w * 0.1848) * 0.2;
|
||||
} else if (color === "brown") {
|
||||
last = (last + 0.02 * w) / 1.02;
|
||||
data[i] = last * 3.5;
|
||||
} else data[i] = w;
|
||||
}
|
||||
noiseBuffers.set(color, buf);
|
||||
return buf;
|
||||
}
|
||||
|
||||
const NOISES = new Set(["noise", "pink", "brown"]);
|
||||
|
||||
// Room for `n` more parts that end at `end`, or false while the page is busy.
|
||||
function room(c, n, end) {
|
||||
const now = c.currentTime;
|
||||
voiceEnds = voiceEnds.filter((t) => t > now);
|
||||
if (voiceEnds.length + n > MAX_VOICES) return false;
|
||||
for (let i = 0; i < n; i++) voiceEnds.push(end);
|
||||
return true;
|
||||
}
|
||||
|
||||
// The running context, its output and its noise, for music.js, which plays
|
||||
// through the same compressor; null while audio cannot play.
|
||||
export function audioOut() {
|
||||
try {
|
||||
const c = audioContext();
|
||||
if (!c || c.state !== "running") return null;
|
||||
return { c, out: out(c), noise: (color) => noiseBuffer(c, color) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Called from the click that opens Activities. A browser keeps a new context
|
||||
// suspended until a gesture, and a rejected resume is not an error the page
|
||||
// can act on, so every failure is swallowed.
|
||||
@@ -99,15 +512,70 @@ function blip(c, type, from, to, t0, seconds, peak) {
|
||||
gain.gain.exponentialRampToValueAtTime(peak, t0 + ATTACK);
|
||||
gain.gain.exponentialRampToValueAtTime(FLOOR, end);
|
||||
osc.connect(gain);
|
||||
gain.connect(c.destination);
|
||||
gain.connect(out(c));
|
||||
osc.start(t0);
|
||||
osc.stop(end);
|
||||
}
|
||||
|
||||
// One part of a rich tone from t0: an oscillator (sweeping, or stepping
|
||||
// through `notes`) or a noise, through its filter if it has one, under an
|
||||
// envelope that swells in over `attack` and dies away by its end.
|
||||
function voice(c, p, t0, peak, k) {
|
||||
const end = t0 + p.seconds;
|
||||
const gain = c.createGain();
|
||||
const top = Math.max(FLOOR * 10, peak * (p.gain ?? 1));
|
||||
gain.gain.setValueAtTime(FLOOR, t0);
|
||||
gain.gain.exponentialRampToValueAtTime(top, t0 + Math.min(p.attack ?? ATTACK, p.seconds * 0.8));
|
||||
gain.gain.exponentialRampToValueAtTime(FLOOR, end);
|
||||
let src;
|
||||
if (NOISES.has(p.type)) {
|
||||
src = c.createBufferSource();
|
||||
src.buffer = noiseBuffer(c, p.type);
|
||||
src.loop = true;
|
||||
} else {
|
||||
src = c.createOscillator();
|
||||
src.type = p.type;
|
||||
if (p.notes) {
|
||||
const each = p.seconds / p.notes.length;
|
||||
p.notes.forEach((f, i) => src.frequency.setValueAtTime(f * k, t0 + i * each));
|
||||
} else {
|
||||
src.frequency.setValueAtTime(p.from * k, t0);
|
||||
src.frequency.exponentialRampToValueAtTime(p.to * k, end);
|
||||
}
|
||||
if (p.vibrato) {
|
||||
const lfo = c.createOscillator();
|
||||
const depth = c.createGain();
|
||||
lfo.frequency.value = p.vibrato.rate;
|
||||
depth.gain.value = (p.notes ? p.notes[0] : p.from) * k * p.vibrato.depth;
|
||||
lfo.connect(depth);
|
||||
depth.connect(src.frequency);
|
||||
lfo.start(t0);
|
||||
lfo.stop(end);
|
||||
}
|
||||
}
|
||||
let head = src;
|
||||
if (p.filter) {
|
||||
const f = c.createBiquadFilter();
|
||||
f.type = p.filter.type;
|
||||
f.Q.value = p.filter.q ?? 1;
|
||||
f.frequency.setValueAtTime(Math.min(20000, p.filter.from * k), t0);
|
||||
f.frequency.exponentialRampToValueAtTime(Math.min(20000, (p.filter.to ?? p.filter.from) * k), end);
|
||||
head.connect(f);
|
||||
head = f;
|
||||
}
|
||||
head.connect(gain);
|
||||
gain.connect(out(c));
|
||||
if (NOISES.has(p.type)) src.start(t0, Math.random() * 1.5);
|
||||
else src.start(t0);
|
||||
src.stop(end);
|
||||
}
|
||||
|
||||
// Plays one named blip, at `level` (0 to 1) of the usual loudness: a soft
|
||||
// putt sounds soft. An unknown name, Play sounds off, or a context that is
|
||||
// missing, suspended or closed all mean silence, not an error.
|
||||
export function tone(name, level = 1) {
|
||||
// putt sounds soft. `pitch` scales every frequency (2 is an octave up, kept
|
||||
// between two octaves down and two up), so a game can climb a scale on one
|
||||
// blip. An unknown name, Play sounds off, or a context that is missing,
|
||||
// suspended or closed all mean silence, not an error.
|
||||
export function tone(name, level = 1, pitch = 1) {
|
||||
try {
|
||||
const spec = Object.hasOwn(TONES, name) ? TONES[name] : null;
|
||||
if (!spec || !looks.sound) return;
|
||||
@@ -115,8 +583,144 @@ export function tone(name, level = 1) {
|
||||
if (!c || c.state !== "running") return;
|
||||
const peak = Math.max(FLOOR * 10, PEAK * Math.min(1, Number(level) || 0));
|
||||
const t0 = c.currentTime;
|
||||
if (!spec.notes) return blip(c, spec.type, spec.from, spec.to, t0, spec.seconds, peak);
|
||||
const k = Math.min(4, Math.max(0.25, Number(pitch) || 1));
|
||||
if (spec.layers) {
|
||||
const last = Math.max(...spec.layers.map((p) => (p.delay || 0) + p.seconds));
|
||||
if (!room(c, spec.layers.length, t0 + last)) return;
|
||||
return spec.layers.forEach((p) => voice(c, p, t0 + (p.delay || 0), peak, k));
|
||||
}
|
||||
if (!spec.notes) return blip(c, spec.type, spec.from * k, spec.to * k, t0, spec.seconds, peak);
|
||||
const each = spec.seconds / spec.notes.length;
|
||||
spec.notes.forEach((f, i) => blip(c, spec.type, f, f, t0 + i * each, each, peak));
|
||||
spec.notes.forEach((f, i) => blip(c, spec.type, f * k, f * k, t0 + i * each, each, peak));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ the hum voices */
|
||||
|
||||
// A hum not asked for again within this long fades out by itself.
|
||||
const HUM_HOLD_MS = 150;
|
||||
|
||||
// At most this many hums at once; a new one past it is not started.
|
||||
const MAX_HUMS = 6;
|
||||
|
||||
// How quickly a hum's pitch and loudness follow what the game asks, in
|
||||
// seconds: quick enough to rev, slow enough never to zipper.
|
||||
const GLIDE = 0.05;
|
||||
|
||||
const live = new Map();
|
||||
|
||||
let watchdog = null;
|
||||
|
||||
function startHum(c, spec) {
|
||||
const amp = c.createGain();
|
||||
const level = c.createGain();
|
||||
level.gain.value = 0;
|
||||
amp.connect(level);
|
||||
level.connect(out(c));
|
||||
let head = amp;
|
||||
let filter = null;
|
||||
if (spec.filter) {
|
||||
filter = c.createBiquadFilter();
|
||||
filter.type = spec.filter.type;
|
||||
filter.Q.value = spec.filter.q ?? 1;
|
||||
filter.frequency.value = spec.filter.freq;
|
||||
filter.connect(amp);
|
||||
head = filter;
|
||||
}
|
||||
const oscs = (spec.parts || []).map((p) => {
|
||||
const o = c.createOscillator();
|
||||
const g = c.createGain();
|
||||
o.type = p.type;
|
||||
o.frequency.value = p.freq;
|
||||
g.gain.value = p.gain ?? 1;
|
||||
o.connect(g);
|
||||
g.connect(head);
|
||||
o.start();
|
||||
return o;
|
||||
});
|
||||
const sources = [...oscs];
|
||||
if (spec.noise) {
|
||||
const n = c.createBufferSource();
|
||||
const g = c.createGain();
|
||||
n.buffer = noiseBuffer(c, spec.noise.color);
|
||||
n.loop = true;
|
||||
g.gain.value = spec.noise.gain ?? 1;
|
||||
n.connect(g);
|
||||
g.connect(head);
|
||||
n.start(0, Math.random() * 1.5);
|
||||
sources.push(n);
|
||||
}
|
||||
let lfo = null;
|
||||
if (spec.pulse) {
|
||||
lfo = c.createOscillator();
|
||||
const depth = c.createGain();
|
||||
lfo.frequency.value = spec.pulse.rate;
|
||||
depth.gain.value = spec.pulse.depth / 2;
|
||||
amp.gain.value = 1 - spec.pulse.depth / 2;
|
||||
lfo.connect(depth);
|
||||
depth.connect(amp.gain);
|
||||
lfo.start();
|
||||
sources.push(lfo);
|
||||
}
|
||||
return { spec, level, filter, oscs, lfo, sources, seen: 0 };
|
||||
}
|
||||
|
||||
function stopHum(c, id, v) {
|
||||
live.delete(id);
|
||||
try {
|
||||
const t = c.currentTime;
|
||||
v.level.gain.cancelScheduledValues(t);
|
||||
v.level.gain.setTargetAtTime(0, t, 0.06);
|
||||
v.sources.forEach((s) => s.stop(t + 0.5));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function watch() {
|
||||
if (watchdog) return;
|
||||
watchdog = setInterval(() => {
|
||||
const now = performance.now();
|
||||
for (const [id, v] of live) if (!looks.sound || now - v.seen > HUM_HOLD_MS) stopHum(ctx, id, v);
|
||||
if (!live.size) {
|
||||
clearInterval(watchdog);
|
||||
watchdog = null;
|
||||
}
|
||||
}, 50);
|
||||
}
|
||||
|
||||
// Keeps the hum `id` sounding as `name` for another moment, at `level` (0 to
|
||||
// 1) of its loudness and `pitch` (1 is its own, kept between 0.25 and 4).
|
||||
// Asking under a different name restarts it as that one. Like tone(), it is
|
||||
// silence, never an error, while Play sounds is off or the audio is not
|
||||
// running.
|
||||
export function hum(id, name, level = 1, pitch = 1) {
|
||||
try {
|
||||
const spec = Object.hasOwn(ALL_HUMS, name) ? ALL_HUMS[name] : null;
|
||||
const c = audioContext();
|
||||
if (!spec || !looks.sound || !c || c.state !== "running") return;
|
||||
let v = live.get(id);
|
||||
if (v && v.spec !== spec) {
|
||||
stopHum(c, id, v);
|
||||
v = null;
|
||||
}
|
||||
if (!v) {
|
||||
if (live.size >= MAX_HUMS) return;
|
||||
v = startHum(c, spec);
|
||||
live.set(id, v);
|
||||
watch();
|
||||
}
|
||||
v.seen = performance.now();
|
||||
const t = c.currentTime;
|
||||
const k = Math.min(4, Math.max(0.25, Number(pitch) || 1));
|
||||
const loud = spec.peak * Math.min(1, Math.max(0, Number(level) || 0));
|
||||
v.level.gain.setTargetAtTime(loud, t, GLIDE);
|
||||
v.oscs.forEach((o, i) => o.frequency.setTargetAtTime(spec.parts[i].freq * k, t, GLIDE));
|
||||
if (v.filter) v.filter.frequency.setTargetAtTime(Math.min(18000, spec.filter.freq * k ** (spec.filter.follow ?? 1)), t, GLIDE);
|
||||
if (v.lfo) v.lfo.frequency.setTargetAtTime(spec.pulse.rate * k, t, GLIDE);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Quiets every hum at once: the window stopped ticking a game.
|
||||
export function hushTones() {
|
||||
if (!ctx) return;
|
||||
for (const [id, v] of live) stopHum(ctx, id, v);
|
||||
}
|
||||
@@ -31,6 +31,8 @@ import { checkDocument, cleanupFindings, readSpecFile, removeCleanup } from "./s
|
||||
import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs";
|
||||
import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs";
|
||||
import { specKey } from "./workspace.mjs";
|
||||
import { readLoopSetup, saveLoopSetup } from "./loop-setup.mjs";
|
||||
import { phaseChecklist } from "./spec-files.mjs";
|
||||
import {
|
||||
PR_HOST_KINDS,
|
||||
readSubagentSetting,
|
||||
@@ -115,6 +117,8 @@ const ROUTES = [
|
||||
{ match: (p) => Object.hasOwn(WORKSPACE_EDITS, p), method: "POST", origin: true, run: workspaceEdit },
|
||||
{ path: "/workspace/scope", method: "POST", origin: true, run: workspaceScope },
|
||||
{ path: "/workspace/browse", method: "POST", origin: true, run: workspaceBrowse },
|
||||
{ path: "/loop-setup", method: "GET", run: loopSetupGet },
|
||||
{ path: "/loop-setup", method: "POST", origin: true, run: loopSetupPost },
|
||||
{ path: "/cancel", method: "POST", origin: true, run: cancel },
|
||||
{ path: "/ping", method: "POST", run: ping },
|
||||
{ path: "/bye", origin: true, run: bye },
|
||||
@@ -418,7 +422,7 @@ function draft(req, res, ctx) {
|
||||
* Whittle a POSTed settings object down to what a settings file may hold.
|
||||
* The page only sends { theme, accent } today, but the file is shared and
|
||||
* forward-compatible: any flat string/number/boolean may live in it. Nested
|
||||
* objects, arrays and a hundred-key dump may not — this is a preference file,
|
||||
* objects, arrays and a two-hundred-key dump may not: this is a preference file,
|
||||
* not free storage, and it is read back into the page unfiltered.
|
||||
*/
|
||||
function cleanLooks(input) {
|
||||
@@ -428,7 +432,9 @@ function cleanLooks(input) {
|
||||
if (k === "__proto__" || k.length > 64) continue;
|
||||
const t = typeof v;
|
||||
if (t === "number" || t === "boolean" || (t === "string" && v.length <= 256)) out[k] = v;
|
||||
if (Object.keys(out).length > 40) return null;
|
||||
// The Activities' best scores alone take a key per game and per golf
|
||||
// course, so the cap leaves room for them all.
|
||||
if (Object.keys(out).length > 120) return null;
|
||||
}
|
||||
return Object.keys(out).length ? out : null;
|
||||
}
|
||||
@@ -632,7 +638,7 @@ function agentsTest(req, res) {
|
||||
});
|
||||
}
|
||||
|
||||
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
|
||||
// User Preferences -> System -> Cleanup. `{ scan: true }` lists what is not needed in
|
||||
// ~/.plan2code and the project's old completed specs; `{ delete: [id] }`
|
||||
// removes those of the ids a fresh scan still finds. Never this session,
|
||||
// never a path the page sent.
|
||||
@@ -1310,6 +1316,57 @@ function chatDecision(req, res, ctx) {
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------------------------------------------- the Implementation Loop */
|
||||
|
||||
// The Implementation Loop's setup for this project (loop-setup.mjs): what was
|
||||
// saved over the defaults. The quick check is text the console only stores.
|
||||
const loopProject = (ctx) => (ctx.readState() || {}).project || ctx.project || ctx.worktree() || "";
|
||||
|
||||
// `?spec=specs/<name>` adds the setup screen's read-only facts (FR-3): the
|
||||
// phases not yet marked done, the branch and the count of uncommitted files.
|
||||
// The server reads the project here and never writes it.
|
||||
function loopSetupGet(req, res, ctx, url) {
|
||||
const answer = readLoopSetup(loopProject(ctx));
|
||||
const spec = url && url.searchParams.get("spec");
|
||||
if (spec === null || spec === undefined) return json(res, 200, answer);
|
||||
if (!/^specs\/[^/\\]+$/.test(spec) || /^specs\/\./.test(spec)) return json(res, 400, { error: "spec must be a folder directly under specs/" });
|
||||
const state = ctx.readState() || {};
|
||||
let phasesLeft = [];
|
||||
try {
|
||||
const overview = fs.readFileSync(path.join(loopProject(ctx), spec, "overview.md"), "utf8");
|
||||
phasesLeft = phaseChecklist(overview)
|
||||
.filter((p) => p.marker !== "x" && p.marker !== "X")
|
||||
.map((p) => ({ n: p.number, name: p.name }));
|
||||
} catch {
|
||||
/* no overview.md: nothing to build */
|
||||
}
|
||||
const pending = state.scan && Number.isInteger(state.scan.pending) ? state.scan.pending : null;
|
||||
// What to prefill an empty quick check with: the project's own build, then
|
||||
// lint, script. Text only; nothing here runs it.
|
||||
let suggestedQuickCheck = "";
|
||||
try {
|
||||
const scripts = JSON.parse(fs.readFileSync(path.join(loopProject(ctx), "package.json"), "utf8")).scripts || {};
|
||||
const name = ["build", "lint"].find((n) => typeof scripts[n] === "string");
|
||||
if (name) suggestedQuickCheck = "npm run " + name;
|
||||
} catch {
|
||||
/* no package.json, or not JSON: no suggestion */
|
||||
}
|
||||
return json(res, 200, { ...answer, phasesLeft, branch: state.branch || "", pending, suggestedQuickCheck });
|
||||
}
|
||||
|
||||
function loopSetupPost(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { ok: false, problems: ["the setup must be a JSON object"] });
|
||||
try {
|
||||
return json(res, 200, { ok: true, setup: saveLoopSetup(loopProject(ctx), body) });
|
||||
} catch (e) {
|
||||
if (Array.isArray(e.problems)) return json(res, 400, { ok: false, problems: e.problems });
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- the workspace */
|
||||
|
||||
// The Workspace: the original folder plus any the person adds as context.
|
||||
|
||||
+15
-26
@@ -46,9 +46,8 @@ import {
|
||||
import { serverWorkspace } from "./workspace.mjs";
|
||||
import { serverSubagents } from "./settings.mjs";
|
||||
import { inAppSignal } from "./in-app.mjs";
|
||||
import { chatOffline } from "./public/chat.js";
|
||||
import { chatAnswering, chatOffline } from "./public/chat.js";
|
||||
import { meterView } from "./public/meter.js";
|
||||
import { startsClean } from "./public/hops.js";
|
||||
import { SERVABLE, asset } from "./static.mjs";
|
||||
import { handle } from "./routes.mjs";
|
||||
import { checkForUpdate } from "./update-check.mjs";
|
||||
@@ -175,12 +174,17 @@ function chatPickedUp() {
|
||||
return cursorSeen.seq;
|
||||
}
|
||||
|
||||
function chatOfflineNow(state) {
|
||||
// The frame's chat block without `offline`. A caller that already built it
|
||||
// (stateFrame) passes it in rather than building it twice.
|
||||
const chatNow = (state) => ({ ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp() });
|
||||
|
||||
function chatOfflineNow(state, chat = chatNow(state)) {
|
||||
return chatOffline({
|
||||
finish: state && state.finish,
|
||||
agent: state && state.agent,
|
||||
agentLastSeenMs: agentSeenAt,
|
||||
now: Date.now(),
|
||||
answering: chatAnswering(chat),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -214,31 +218,15 @@ const workspace = serverWorkspace({
|
||||
});
|
||||
|
||||
/**
|
||||
* Open a conversation when there is none, and a new one whenever the page
|
||||
* passes through the dashboard. The reset line carries the workflow it was
|
||||
* opened under, so a server that restarts across a hop still sees the switch.
|
||||
* A resume that keeps its workflow keeps its conversation.
|
||||
* Open a conversation when there is none. A hop to another skill keeps it:
|
||||
* the person is still talking to the same agent, and switchWorkflow() carries
|
||||
* the agent's replies across, so only New conversation starts a new one.
|
||||
*/
|
||||
function ensureConversation(state) {
|
||||
if (!state) return;
|
||||
const last = currentConversation(readChat(DIR));
|
||||
let entry = null;
|
||||
if (!last.conversation) {
|
||||
entry = appendChat(DIR, { kind: "reset", conversation: 1, workflow: state.workflow, reason: "start" });
|
||||
} else if (
|
||||
// The same hops `open --resume` treats as a fresh start, by the rule in
|
||||
// public/hops.js (a blank page, the agent's replies included). Without a
|
||||
// new conversation, the old questions would show as unanswered again.
|
||||
startsClean(last.workflow, state.workflow)
|
||||
) {
|
||||
entry = appendChat(DIR, {
|
||||
kind: "reset",
|
||||
conversation: last.conversation + 1,
|
||||
workflow: state.workflow,
|
||||
reason: "switch",
|
||||
});
|
||||
}
|
||||
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
||||
if (currentConversation(readChat(DIR)).conversation) return;
|
||||
const entry = appendChat(DIR, { kind: "reset", conversation: 1, workflow: state.workflow, reason: "start" });
|
||||
appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ subagents */
|
||||
@@ -259,13 +247,14 @@ const IN_APP = Boolean(inAppSignal());
|
||||
// stream (see /events).
|
||||
function stateFrame(state) {
|
||||
const { pending, stop } = resultFlags();
|
||||
const chat = chatNow(state);
|
||||
return {
|
||||
rev,
|
||||
state,
|
||||
agentLastSeen: agentLastSeen(),
|
||||
pendingResult: pending,
|
||||
pendingStop: stop,
|
||||
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
||||
chat: { ...chat, offline: chatOfflineNow(state, chat) },
|
||||
workspace: workspace.workspaceView(),
|
||||
meter: meterView(ledgerEntries()),
|
||||
subagents: subagents.view(state),
|
||||
|
||||
@@ -279,12 +279,15 @@ 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
|
||||
// looks, the folders remembered per project and spec, the Implementation
|
||||
// Loop's setup per project and its report while a build is under way, the Subagents switch
|
||||
// saved per project and workflow, what each unknown git host is, the pointer
|
||||
// to this console's directory, and the cached release check.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
||||
"looks.json",
|
||||
"workspaces.json",
|
||||
"loop-setup.json",
|
||||
"loop-reports.json",
|
||||
"subagents.json",
|
||||
"pr-hosts.json",
|
||||
"console-dir",
|
||||
|
||||
@@ -38,6 +38,40 @@ export function statusOf(text) {
|
||||
return m ? m[2] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Phase Checklist rows of an overview.md as `[{ number, marker, name }]`
|
||||
* (the first "Phase N" on each checkbox line names the phase), in file order;
|
||||
* empty when there is no checklist. Read-only facts for the loop's setup
|
||||
* screen: the scripts that write the marks stay src/skill-scripts/specs.mjs.
|
||||
*/
|
||||
export function phaseChecklist(overview) {
|
||||
const lines = (overview || "").split(/\r?\n/);
|
||||
const at = lines.findIndex((l) => /^#{1,6}\s+.*Phase Checklist/i.test(l));
|
||||
if (at < 0) return [];
|
||||
// The section runs to the next heading of the same or a higher level, so a
|
||||
// sub-heading inside the checklist does not cut it short.
|
||||
const level = lines[at].match(/^#+/)[0].length;
|
||||
const rows = [];
|
||||
for (let i = at + 1; i < lines.length; i++) {
|
||||
const heading = lines[i].match(/^(#+)\s/);
|
||||
if (heading && heading[1].length <= level) break;
|
||||
const box = lines[i].match(CHECKBOX_RE);
|
||||
if (!box) continue;
|
||||
const text = lines[i]
|
||||
.replace(CHECKBOX_RE, "")
|
||||
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
|
||||
.replace(/[*_`]/g, "")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
const num = text.match(/\bPhase\s+(\d+)\b/i);
|
||||
if (!num) continue;
|
||||
const after = text.slice(num.index + num[0].length).replace(/^\s*[:\-–—]\s*/, "");
|
||||
const name = after.split(/\s+[-–—]\s+|\s+\(|\s+_\(|:\s|\s+see\s+phase-/i)[0].replace(/\s*phase-\d+\.md\s*$/i, "").trim();
|
||||
rows.push({ number: Number(num[1]), marker: box[1], name: name.replace(/\s*\[Milestone[^\]]*\]\s*$/i, "") || `Phase ${num[1]}` });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* A phase file's tasks by where they stand. The task lines when the file has
|
||||
* them, so an Acceptance Criteria checkbox is not counted as a task; every
|
||||
|
||||
+122
-2
@@ -40,6 +40,8 @@ export const SERVABLE = new Set([
|
||||
"boot.js",
|
||||
"chat.js",
|
||||
"help.js",
|
||||
"tabs.js",
|
||||
"prefs.js",
|
||||
"starters.js",
|
||||
"workspace.js",
|
||||
"meter.js",
|
||||
@@ -60,12 +62,15 @@ export const SERVABLE = new Set([
|
||||
"favicon.png",
|
||||
"screens/core.js",
|
||||
"screens/ending.js",
|
||||
"screens/loop-setup.js",
|
||||
"screens/docs.js",
|
||||
"screens/cards.js",
|
||||
"screens/starting.js",
|
||||
"screens/dashboard.js",
|
||||
"screens/git-host.js",
|
||||
"screens/looks.js",
|
||||
"screens/agents-view.js",
|
||||
"screens/prefs-dialog.js",
|
||||
"screens/cleanup.js",
|
||||
"screens/help-dialog.js",
|
||||
"screens/workspace.js",
|
||||
@@ -78,7 +83,119 @@ export const SERVABLE = new Set([
|
||||
"activities/golf-holes.js",
|
||||
"activities/golf-draw.js",
|
||||
"activities/golf-decor.js",
|
||||
"activities/golf-kit.js",
|
||||
"activities/golf-paint.js",
|
||||
"activities/golf-looks.js",
|
||||
"activities/golf-course-pirate.js",
|
||||
"activities/golf-course-cave.js",
|
||||
"activities/golf-course-dino.js",
|
||||
"activities/golf-course-candy.js",
|
||||
"activities/golf-course-space.js",
|
||||
"activities/golf-course-frost.js",
|
||||
"activities/golf-look-dino.js",
|
||||
"activities/golf-look-candy.js",
|
||||
"activities/golf-look-space.js",
|
||||
"activities/golf-look-frost.js",
|
||||
"activities/trails.js",
|
||||
"activities/bugs.js",
|
||||
"activities/drive.js",
|
||||
"activities/stack.js",
|
||||
"activities/bumper.js",
|
||||
"activities/bumper-draw.js",
|
||||
"activities/rapids.js",
|
||||
"activities/rapids-draw.js",
|
||||
"activities/fuse.js",
|
||||
"activities/fuse-draw.js",
|
||||
"activities/hop.js",
|
||||
"activities/hop-draw.js",
|
||||
"activities/bounce.js",
|
||||
"activities/bounce-draw.js",
|
||||
"activities/bounce-roads.js",
|
||||
"activities/bounce-road.js",
|
||||
"activities/bounce-rivals.js",
|
||||
"activities/bounce-scenery.js",
|
||||
"activities/bounce-cars.js",
|
||||
"activities/ghoul.js",
|
||||
"activities/ghoul-draw.js",
|
||||
"activities/ghoul-rooms.js",
|
||||
"activities/ghoul-bones.js",
|
||||
"activities/ghoul-bones-draw.js",
|
||||
"activities/ghoul-graveyard.js",
|
||||
"activities/ghoul-graveyard-draw.js",
|
||||
"activities/ghoul-grounds.js",
|
||||
"activities/ghoul-grounds-draw.js",
|
||||
"activities/ghoul-chapel.js",
|
||||
"activities/ghoul-chapel-draw.js",
|
||||
"activities/ghoul-sanatorium.js",
|
||||
"activities/ghoul-sanatorium-draw.js",
|
||||
"activities/ghoul-village.js",
|
||||
"activities/ghoul-village-draw.js",
|
||||
"activities/ghoul-village-world.js",
|
||||
"activities/ghoul-village-wolf.js",
|
||||
"activities/ghoul-mine.js",
|
||||
"activities/ghoul-mine-draw.js",
|
||||
"activities/ghoul-mine-world.js",
|
||||
"activities/ghoul-mine-tommy.js",
|
||||
"activities/ghoul-cart.js",
|
||||
"activities/ghoul-cart-draw.js",
|
||||
"activities/ghoul-sled.js",
|
||||
"activities/ghoul-sled-draw.js",
|
||||
"activities/ghoul-carnival.js",
|
||||
"activities/ghoul-carnival-draw.js",
|
||||
"activities/ghoul-carnival-world.js",
|
||||
"activities/ghoul-frozen.js",
|
||||
"activities/ghoul-frozen-draw.js",
|
||||
"activities/ghoul-frozen-world.js",
|
||||
"activities/ghoul-flare.js",
|
||||
"activities/ghoul-picker-draw.js",
|
||||
"activities/ghoul-powers.js",
|
||||
"activities/ghoul-arms.js",
|
||||
"activities/ghoul-arms-draw.js",
|
||||
"activities/ghoul-rockets.js",
|
||||
"activities/ghoul-rockets-draw.js",
|
||||
"activities/ghoul-pans.js",
|
||||
"activities/ghoul-run.js",
|
||||
"activities/ghoul-dice.js",
|
||||
"activities/ghoul-dice-draw.js",
|
||||
"activities/ghoul-gameover-draw.js",
|
||||
"activities/ghoul-bonus.js",
|
||||
"activities/ghoul-bonus-draw.js",
|
||||
"activities/ghoul-monsters-draw.js",
|
||||
"activities/pills.js",
|
||||
"activities/snake-sfx.js",
|
||||
"activities/golf-sfx.js",
|
||||
"activities/trails-sfx.js",
|
||||
"activities/bugs-sfx.js",
|
||||
"activities/drive-sfx.js",
|
||||
"activities/stack-sfx.js",
|
||||
"activities/bumper-sfx.js",
|
||||
"activities/rapids-sfx.js",
|
||||
"activities/fuse-sfx.js",
|
||||
"activities/hop-sfx.js",
|
||||
"activities/bounce-sfx.js",
|
||||
"activities/ghoul-sfx.js",
|
||||
"activities/ghoul-sfx-graveyard.js",
|
||||
"activities/ghoul-sfx-grounds.js",
|
||||
"activities/ghoul-sfx-chapel.js",
|
||||
"activities/ghoul-sfx-sanatorium.js",
|
||||
"activities/ghoul-sfx-village.js",
|
||||
"activities/ghoul-sfx-mine.js",
|
||||
"activities/ghoul-sfx-carnival.js",
|
||||
"activities/ghoul-sfx-frozen.js",
|
||||
"activities/ghoul-sfx-sled.js",
|
||||
"activities/ghoul-ride-core.js",
|
||||
"activities/ghoul-ride-scenes.js",
|
||||
"activities/ghoul-ride.js",
|
||||
"activities/ghoul-ride-gfx.js",
|
||||
"activities/ghoul-ride-draw-kinds.js",
|
||||
"activities/ghoul-ride-draw-sets.js",
|
||||
"activities/ghoul-ride-draw-hud.js",
|
||||
"activities/ghoul-ride-draw.js",
|
||||
"activities/ghoul-ride-voices.js",
|
||||
"activities/ghoul-sfx-ride.js",
|
||||
"activities/ghoul-sfx-arms.js",
|
||||
"tones.js",
|
||||
"music.js",
|
||||
"notepad-tabs.js",
|
||||
"net.js",
|
||||
"notepad.js",
|
||||
@@ -95,7 +212,7 @@ export const SERVABLE = new Set([
|
||||
// Layers first, then one file per screen, then responsive and print last so
|
||||
// its overrides still come after everything they override. The files are not
|
||||
// on SERVABLE: they reach the page only through /app.css.
|
||||
export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "poses.css", "docs.css", "ask.css", "ending.css", "help.css", "looks.css", "notepad.css", "activities.css", "git.css", "responsive.css"];
|
||||
export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "poses.css", "docs.css", "ask.css", "ending.css", "help.css", "looks.css", "prefs.css", "notepad.css", "activities.css", "git.css", "responsive.css"];
|
||||
|
||||
// The files joined with one newline between them (each file's own last newline
|
||||
// is that one), as the server serves them before the accent rules. The test
|
||||
@@ -117,10 +234,13 @@ export function joinedStyles() {
|
||||
// other means (preload hints, the inline boot state) rather than by caching.
|
||||
const assets = new Map();
|
||||
|
||||
// `npm run play` sets this so an edit to a page file shows on the next reload.
|
||||
const FRESH = process.env.PLAN2CODE_CONSOLE_DEV === "1";
|
||||
|
||||
export const etagOf = (body) => `"${crypto.createHash("sha1").update(body).digest("base64url").slice(0, 20)}"`;
|
||||
|
||||
export function asset(rel) {
|
||||
let a = assets.get(rel);
|
||||
let a = FRESH ? undefined : assets.get(rel);
|
||||
if (!a) {
|
||||
let body = rel === "app.css" ? joinedStyles() : fs.readFileSync(path.join(PUBLIC_DIR, rel));
|
||||
if (rel === "app.css") body = Buffer.concat([body, Buffer.from(accentCss())]);
|
||||
|
||||
Reference in new issue
Block a user