mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 20:45:33 -08:00
Sync upstream into v2.7.0: the git board skill replaces git-commit (ticket-free), and console docs and tests are split up
AI Assisted
This commit is contained in:
1 parent
6114914dd6
commit
f328406bb5
103 files changed
+17636
-9991
No files matched your search
@@ -0,0 +1,148 @@
|
||||
# The Review, Mid-Session, on the Web Console
|
||||
|
||||
Part of the build contract (`building.md`). Read when the person asks for the
|
||||
review on the page: the `review` verdict on Implement's sign-off card, the
|
||||
**Review it now** button on a finished quick task, or Implement + Review's
|
||||
Stage 2.
|
||||
|
||||
The same focused review runs from either of two doors:
|
||||
|
||||
- **`implement`:** the `review` verdict on the sign-off card, before anything
|
||||
is approved. A note sent with it is theirs — read it as focus for the
|
||||
review. Settle the card with it in the same post that goes back to work:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"settle": true,
|
||||
"headline": { "stage": "Reviewing Phase 3", "cleared": 0, "total": 0 },
|
||||
"run": { "event": "review", "id": "review" },
|
||||
"agent": { "status": "working", "activity": "Reviewing the 7 files this phase changed", "quietMinutes": 15 }
|
||||
}
|
||||
```
|
||||
|
||||
- **`quick-task`:** the **Review it now** button on the finished screen, which
|
||||
`finish.review` puts there. It arrives through the wait loop as an action
|
||||
`{ "i": "__review", "type": "review" }`, like any send. Take it up with the
|
||||
same post minus `settle`, plus `"finish": null` — that takes the session off
|
||||
its ending and back to work.
|
||||
|
||||
Either way, the post that takes the review up carries `"run": { "event":
|
||||
"review", "id": "review" }`: the review runs inside this skill's session, so no
|
||||
launch scores it on the session meter. Never resume the session under
|
||||
`--workflow review` for it as well, or it counts twice.
|
||||
|
||||
A finish carrying `review` keeps the session alive for the answer, so a
|
||||
`quick-task` that just posted one keeps waiting — there is no timeout after
|
||||
a finish.
|
||||
A quick-task finish carries both `review` and `"dashboard": true` and waits
|
||||
for whichever comes first:
|
||||
|
||||
| What arrives | What you do |
|
||||
| --- | --- |
|
||||
| An action `{ "i": "__review", "type": "review" }` | Take the review up (below). |
|
||||
| An action `{ "i": "__dashboard", "type": "dashboard" }` | Take the session back as the dashboard (`console-finish.md` → After the finish). |
|
||||
| An action `{ "i": "__done", "type": "done" }` | `stop` the server. The session is over. |
|
||||
| `wait` exit `20` | The server is gone. Resume it (`open --resume <sid> --workflow <yours>`), give them the new link, and keep waiting. |
|
||||
| The session ends without a press (the terminal closes) | The server sweeps itself after its idle window; the page then shows the terminal command for a review instead of a button that would go nowhere. |
|
||||
|
||||
**Read references/review.md** and run Review Mode with these overrides:
|
||||
|
||||
- **Scope is Focused, and already decided:** the exact change set of this
|
||||
session (files created or modified by the phase or the quick task, plus the
|
||||
tests and docs changed for it). Do not ask about scope. Use overview.md and
|
||||
the phase file for spec compliance; they do not widen the scope.
|
||||
- **No commit instructions and no next-conversation routing** mid-review. The
|
||||
way back out carries both.
|
||||
- The page takes the whole report, so the "top 10 of 15+" rule does not apply,
|
||||
and tables go in the doc.
|
||||
|
||||
## The findings
|
||||
|
||||
The full Review Mode report as a doc, and the fix choice as one `multi` item,
|
||||
posted with `--wait`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"docs": [{ "id": "review", "title": "Review findings", "blocks": [
|
||||
{ "id": "report", "state": "settled", "md": "## Overview\n\n...\n\n## Findings\n\n| # | Severity | Issue | File |\n..." }
|
||||
]}],
|
||||
"items": [{
|
||||
"id": "fixes", "kind": "multi", "title": "Which to fix", "required": false, "doc": "review",
|
||||
"body": "Tick what should be fixed now. Anything left unticked is written up as still open. Nothing changes until you send.",
|
||||
"options": [
|
||||
{ "k": "1", "text": "Critical: token is logged in plain text", "detail": "src/auth.ts:42. Fix: redact before logging." },
|
||||
{ "k": "2", "text": "Warning: missing null check on the user lookup", "detail": "src/users.ts:88. Fix: ..." },
|
||||
{ "k": "3", "text": "Suggestion: repeated query could be batched", "detail": "src/report.ts:17. Fix: ..." }
|
||||
],
|
||||
"presets": [
|
||||
{ "label": "Critical and warnings", "ks": ["1", "2"] },
|
||||
{ "label": "All of them", "ks": ["1", "2", "3"] }
|
||||
]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
`"doc": "review"` puts a **Read "Review findings" in full** button on the
|
||||
card, so the report is one click from the list rather than behind a tab
|
||||
nobody notices. Always carry it.
|
||||
|
||||
Read the reply as Review Mode's fix choice: `Which to fix: 1, 2` is `S 1,2`,
|
||||
every finding ticked is `A`, and `skip` (or nothing ticked) is "fix none,
|
||||
keep them as unresolved". Leave out `presets` a set would not change (no
|
||||
warnings, one finding). With **zero findings** there is no item: say so in the
|
||||
doc and go straight to the way back out.
|
||||
|
||||
## Fixing
|
||||
|
||||
Settle the `fixes` item (`"settle": true`) in the same post that goes back to
|
||||
work. The server records their send on the item, but only you decide it is
|
||||
settled; left open it stays on the page as an outstanding question, beside the
|
||||
card you ask next. A send with nothing ticked settles as `{ "ks": [] }`. Then
|
||||
follow Review Mode's Post-Fix Flow, posting `activity` per fix ("Fix 2 of 3: the
|
||||
null check") and `quietMinutes` as in a build.
|
||||
|
||||
## The way back out
|
||||
|
||||
**`implement` — back to the sign-off.** The review was the preamble to an
|
||||
approval that has not happened yet, so this is where it lands. Fold the review
|
||||
results and any still-open findings into the report doc, then reopen the
|
||||
sign-off **without the review verdict** — re-offering a review that just ran
|
||||
reads as though nothing happened — and post the build's `headline` back (the
|
||||
review set it to its own stage):
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "cleared": 9, "total": 9 },
|
||||
"items": [{ "id": "signoff", "status": "reopened",
|
||||
"body": "Reviewed and ready for sign-off. The review found 3 issues: 2 fixed, 1 still open in the Review findings tab. The report is updated.",
|
||||
"verdicts": [
|
||||
{ "id": "approve", "label": "Approve this phase" },
|
||||
{ "id": "changes", "label": "I want changes" }
|
||||
],
|
||||
"thread": [{ "who": "agent", "text": "Review done: 2 of 3 findings fixed; the rest is written up in the findings tab." }]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
Review Mode's own closing gate ("Reply approved to commit") is this card:
|
||||
approving the phase now covers the fixes too, so there is no separate "Check
|
||||
the fixes" step. On approval, continue at `notes/implement.md` → After
|
||||
approval: the finish.
|
||||
|
||||
**`quick-task` — the closing gate, then the finish.** Review Mode's closing
|
||||
gate ("Reply approved to commit, or request changes") becomes a `review` item
|
||||
titled "Check the fixes", `doc: "review"`, `"nothingYet": false` (the fixes are already made), verdicts `approve` ("The fixes look
|
||||
right") and `changes`, token `approved` / `needs changes`. When it clears,
|
||||
settle it (`"settle": true`) in the same post as the new finish, post the finish
|
||||
**without** `review` (and with `dashboard: true`), then keep waiting for its
|
||||
buttons as `console-finish.md` says; `stop` only on `__done`. An item left open survives on the page as
|
||||
a question still owed, above the ending itself:
|
||||
|
||||
- `headline`: "The review is done"
|
||||
- `body`: findings by severity, what was fixed, what is still open, and the
|
||||
commit command for the fixes, in the project's commit format.
|
||||
- `command`: one commit for the whole quick task, its changes and the fixes
|
||||
together, in the project's commit format (not a second command beside the
|
||||
first), with `commit: true` so **Commit it now** is still on offer.
|
||||
- `headline`: the quick task's own again, e.g. `{ "cleared": 4, "total": 4 }`.
|
||||
- `doc`: `"review"`.
|
||||
+51
-407
@@ -1,10 +1,12 @@
|
||||
# Build Sessions on the Web Console
|
||||
|
||||
For `/plan2code-3-implement`, `/plan2code-3-implement-review` and
|
||||
`/plan2code-quick-task`. Read `console.md` first: everything there still
|
||||
applies (the wait loop, one post per send, `finish` before `stop`, the house
|
||||
rules). This file adds what a build needs, because a build is mostly you
|
||||
working, and the page has to be told so.
|
||||
`/plan2code-quick-task`. Everything in `console.md` still applies (the turn,
|
||||
one post per send, `finish` before `stop`, the house rules). This file adds what
|
||||
a build needs, because a build is mostly you working, and the page has to be
|
||||
told so. Then read your workflow's own notes: `notes/implement.md` (Implement
|
||||
and Implement + Review) or `notes/quick-task.md`. `building-review.md` is read
|
||||
only when a review is asked for on the page.
|
||||
|
||||
**The console changes where you ask, not what you build.** Every rule of the
|
||||
workflow stands: the same specs, the same checkbox writes to disk after every
|
||||
@@ -18,10 +20,6 @@ task, the same sign-off wording, the same "no git commands". The files under
|
||||
Open first, before reading the spec — the page shows a starting screen while
|
||||
you work out the phase:
|
||||
|
||||
```
|
||||
node "<CONSOLE>" open --workflow implement
|
||||
```
|
||||
|
||||
| Workflow you are running | `--workflow` | `--spec` |
|
||||
| --- | --- | --- |
|
||||
| `/plan2code-3-implement` | `implement` | `specs/<feature>` |
|
||||
@@ -32,103 +30,59 @@ node "<CONSOLE>" open --workflow implement
|
||||
answer a stop yourself. Pass it to `open` when you already know the spec;
|
||||
otherwise post `"specDir": "specs/<feature>"` and a real `title` ("<feature>:
|
||||
Phase 3") in your first update, once the phase is chosen, or with the phase
|
||||
question as its first item if there is one to ask. `--file` works on `open`
|
||||
too, but opening bare and posting the task list as your first update gets
|
||||
them the page while you are still composing.
|
||||
question as its first item if there is one to ask.
|
||||
|
||||
**Launched from the dashboard?** Then the session is already open and the
|
||||
person is watching it — `open --resume <sid> --no-open --workflow <yours>`
|
||||
(plus `--spec` once known) instead of a fresh `open`, exactly as console.md →
|
||||
Launches says. Everything below is unchanged; the only difference is whose
|
||||
session it was a minute ago.
|
||||
|
||||
The first payload for a phase you are about to build:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "stage": "Phase 3: API layer", "cleared": 0, "total": 9 },
|
||||
"docs": [
|
||||
{ "id": "phase", "title": "Phase 3 tasks", "version": 1, "blocks": [
|
||||
{ "id": "tasks", "state": "settled", "md": "- [ ] **Task 3.1:** ...\n- [ ] **Task 3.2:** ..." }
|
||||
]},
|
||||
{ "id": "phasefile", "title": "phase-3.md", "version": 1, "blocks": [
|
||||
{ "id": "body", "state": "settled", "md": "...the whole phase-3.md file, verbatim..." }
|
||||
]}
|
||||
],
|
||||
"agent": { "status": "working", "activity": "Checking the prerequisites", "quietMinutes": 15 }
|
||||
}
|
||||
```
|
||||
|
||||
`headline.cleared` / `total` are tasks done out of tasks in the phase: the
|
||||
progress bar is the first thing someone watching a build looks at. The session
|
||||
meter counts the build's tasks from `cleared` as it rises, so keep it current,
|
||||
and start every phase (a second one in the same run too) at `"cleared": 0`.
|
||||
|
||||
`"version": 1` is for the first phase of a session only. A doc's version
|
||||
never goes back (console.md → House rules, rule 9), so a later phase in the
|
||||
same session reposts `phase` and `phasefile` at one more than the version the
|
||||
page holds, with the new phase's title and content. The same goes for
|
||||
`report` at sign-off and `review` in a mid-session review: version 1 the
|
||||
first time, then up from wherever the page has it.
|
||||
|
||||
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
||||
the person can read the prerequisites and task specs while you build. Re-post
|
||||
it whenever the file changes, which is every task: the checkbox write that
|
||||
ticks the list above ticks the file too, and the Phase Completion Summary
|
||||
lands in it at the end. It renders as markdown, so the file's checkboxes show
|
||||
as ticks exactly as they stand on disk.
|
||||
person is watching it — run the `resume` the launch carried (`open --resume
|
||||
<sid> --no-open --workflow <yours>`, plus `--spec` once known) instead of a
|
||||
fresh `open`, exactly as `console-launches.md` says. Everything below is
|
||||
unchanged; the only difference is whose session it was a minute ago.
|
||||
|
||||
---
|
||||
|
||||
## While you build
|
||||
|
||||
Post after every task, in the same breath as writing its checkbox to disk.
|
||||
Write the patch file into the session's own folder (the `session` path `open`
|
||||
printed), never into the project or into `~/.plan2code/console/` directly:
|
||||
Post after every task, in the same breath as writing its checkbox to disk,
|
||||
with no `--wait`. Your notes file shows the exact post; every one carries:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "cleared": 4 },
|
||||
"docs": [
|
||||
{ "id": "phase", "version": 5, "blocks": [ { "id": "tasks", "state": "settled", "md": "...the whole list, 4 ticked..." } ] },
|
||||
{ "id": "phasefile", "version": 5, "blocks": [ { "id": "body", "state": "settled", "md": "...phase-3.md as it now stands on disk..." } ] }
|
||||
],
|
||||
"agent": { "activity": "Task 5 of 9: the rate limiter" }
|
||||
}
|
||||
```
|
||||
|
||||
- **`activity`** is one plain sentence saying what you are doing now. The page
|
||||
shows it beside Planny and in place of "questions coming". No internal
|
||||
- **`headline.cleared` / `total`**: tasks done out of tasks in the run. The
|
||||
progress bar is the first thing someone watching a build looks at, and on
|
||||
Implement (and Implement + Review) the session meter counts the build's tasks
|
||||
from `cleared` as it rises; a quick task scores once, when it opens. Start every
|
||||
phase (a second one in the same run too) at `"cleared": 0`. If the task list
|
||||
grows mid-build, raise `headline.total` in the same post.
|
||||
- **`agent.activity`**: one plain sentence saying what you are doing now. The
|
||||
page shows it beside Planny and in place of "questions coming". No internal
|
||||
vocabulary, no loop completion markers. Number tasks by their position in
|
||||
the phase, of the phase's task count (`Task 5 of 9`), not by the file's
|
||||
`5.5`-style labels: the phase is already in the headline. The page rewrites
|
||||
the old form as a safety net.
|
||||
- **`quietMinutes`** is how long you might go without posting (1 to 60). The
|
||||
page calls a working agent stuck after two minutes of silence unless you say
|
||||
otherwise, and a build task can honestly take twenty. Set it to the longest
|
||||
gap you expect, usually 10 to 30. Every post is also a heartbeat. **Clear it
|
||||
(`"quietMinutes": null`) whenever you go back to waiting**: it only counts
|
||||
while you are `working`, but leaving it set invites a stale value later.
|
||||
- `blocks` inside a doc are replaced whole, so post the whole task list each
|
||||
time. It is small. The same goes for `phasefile`: re-read `phase-X.md` and
|
||||
post it fresh, because the checkbox write just changed it.
|
||||
- If the task list grows mid-build, raise `headline.total` in the same post;
|
||||
the page never shows more done than the total, but the bar reads truer when
|
||||
you keep it current.
|
||||
- Do not call `wait` while building. There is nothing to collect, and the page
|
||||
holds anything the person sends until you next look.
|
||||
the run, of the task count (`Task 5 of 9`), not by the file's `5.5`-style
|
||||
labels: the phase is already in the headline. The page rewrites the old form
|
||||
as a safety net.
|
||||
- **`agent.quietMinutes`** (on the post that starts the build): how long you
|
||||
might go without posting (1 to 60; the page always allows at least two). The page calls a working agent stuck
|
||||
after two minutes of silence unless you say otherwise, and a build task can
|
||||
honestly take twenty. Set it to the longest gap you expect, usually 10 to 30.
|
||||
Every post is also a heartbeat. It only counts while you are working, so it
|
||||
holds across the questions you ask: set it once.
|
||||
- **The task list re-read from disk** (Implement): the doc blocks that mirror
|
||||
the spec are `file` blocks, so a progress post re-reads them with
|
||||
`"refresh": true` rather than repeating the text. A quick task's plan lives
|
||||
only on the page, so its steps block stays `md` (`notes/quick-task.md`).
|
||||
Versions move by themselves.
|
||||
|
||||
Do not call `wait` while building. There is nothing to collect, and the page
|
||||
holds anything the person sends until you next look.
|
||||
|
||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
||||
`chat` check between tasks. Follow console.md → Standing instructions for
|
||||
handing independent tasks to helpers and reporting them as `helpers`. Keep the
|
||||
`chat` check between tasks. Follow `console-subagents.md` for handing
|
||||
independent tasks to helpers and reporting them as `helpers`. Keep the
|
||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
||||
with you.
|
||||
|
||||
### Quick questions between tasks
|
||||
|
||||
The person can ask a Quick question on the Ask tab at any point in a build
|
||||
(console.md → Quick questions). After each task's progress post, check for
|
||||
one before starting the next task:
|
||||
(`console-chat.md`). After each task's progress post, check for one before
|
||||
starting the next task:
|
||||
|
||||
```
|
||||
node "<CONSOLE>" chat --session <sid>
|
||||
@@ -136,9 +90,9 @@ node "<CONSOLE>" chat --session <sid>
|
||||
|
||||
| Exit | What you do |
|
||||
| --- | --- |
|
||||
| `0` | Answer everything waiting, under console.md → Quick questions, in one post, then start the next task. A `workspace` list in the output is a change to the session's folders (console.md → Workspace): take it into account from the next task on; it needs no reply. |
|
||||
| `0` | Answer everything waiting, under `console-chat.md`, in one post, then start the next task. A `workspace` list in the output is a change to the session's folders (`console-workspace.md`): take it into account from the next task on; it needs no reply. |
|
||||
| `10` | Nothing waiting. Carry on. |
|
||||
| `20` | The server is gone: `open --resume <sid>` as usual, then carry on. |
|
||||
| `20` | The server is gone: `open --resume <sid> --workflow <yours>`, give them the new link, then carry on. |
|
||||
|
||||
This is an instant check, not a wait: it never sleeps and never touches card
|
||||
sends. It does not replace `wait` at a gate, and no build calls `wait`
|
||||
@@ -150,11 +104,11 @@ not questions. Put them in the phase doc as they happen, and in the report.
|
||||
|
||||
### When the workflow asks something
|
||||
|
||||
Publish it, set `"agent": { "status": "waiting", "quietMinutes": null }` in
|
||||
the SAME post, and go into the wait loop. When the answer lands, set `working`
|
||||
again and carry on.
|
||||
Publish it with `post --wait`: a new question hands the turn over by itself
|
||||
(status `waiting`). When the answer lands, collecting it
|
||||
sets you `working` again; carry on.
|
||||
|
||||
A question stops the build. Never leave yourself `working` with a question
|
||||
A question stops the build. Never post `"status": "working"` with a question
|
||||
open, and never "carry on while you decide": the page reads `working` as "not
|
||||
your turn", and the person is left looking at a question they cannot answer.
|
||||
If there is other work the answer does not touch, finish it before you ask,
|
||||
@@ -174,320 +128,10 @@ Titles stay plain: "Which phase next", "Tests are failing", "Keep going?".
|
||||
|
||||
---
|
||||
|
||||
## Sign-off
|
||||
|
||||
Put the Completion Report on the page as a doc, then ask for approval as a
|
||||
`review` item pointing at it. The review offer rides on this card, as a verdict
|
||||
ahead of the approval buttons — not on the finish after it, where it could
|
||||
only ever be offered once nothing could come of it:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"docs": [{ "id": "report", "title": "Completion report", "version": 1, "blocks": [
|
||||
{ "id": "summary", "state": "settled", "md": "## Summary\n\n..." },
|
||||
{ "id": "files", "state": "settled", "md": "## Files\n\n..." },
|
||||
{ "id": "verify", "state": "settled", "md": "## How to check it\n\n..." }
|
||||
]}],
|
||||
"items": [{
|
||||
"id": "signoff", "kind": "review", "title": "Approve this phase", "doc": "report",
|
||||
"body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, or say what to change.",
|
||||
"verdicts": [
|
||||
{ "id": "review", "label": "Review the code first" },
|
||||
{ "id": "approve", "label": "Approve this phase" },
|
||||
{ "id": "changes", "label": "I want changes" }
|
||||
],
|
||||
"token": { "review": "review", "approve": "approved", "changes": "needs changes" },
|
||||
"nothingYet": "Nothing is marked complete until you approve.",
|
||||
"gate": { "id": "signoff", "authoritative": true },
|
||||
"fallbackText": "Reply \"approved\" to mark this phase complete, \"review\" to run the code review first, or describe any issues."
|
||||
}],
|
||||
"agent": { "status": "waiting", "quietMinutes": null }
|
||||
}
|
||||
```
|
||||
|
||||
`reply` carries `Approve this phase: approved`, which is the terminal's
|
||||
`approved`. If the note that came with an approval asks for a change, treat it
|
||||
as "describe any issues": do the change first and ask again. `changes` means
|
||||
exactly what it says: address it, bump the report's version (a later phase's
|
||||
report starts above the last one's, too), and reopen the
|
||||
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||
person asking for the code review before they approve anything — see "The
|
||||
review, mid-session" below.
|
||||
|
||||
`gate` marks the one approval that counts. The server refuses a second open
|
||||
authoritative gate, which is what keeps a composed workflow from asking for
|
||||
sign-off twice.
|
||||
|
||||
---
|
||||
|
||||
## After approval: the finish
|
||||
|
||||
Do everything the workflow does on approval (the checkboxes, the summary, the
|
||||
upcoming phases, the commit command) and print it in the terminal as usual.
|
||||
Then post the finish, wait for the dashboard button as console.md → Finishing
|
||||
says, and `stop`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"items": [{ "id": "signoff", "status": "answered", "answer": { "verdict": "approve" } }],
|
||||
"run": { "event": "implement-phase", "id": "phase-3", "tasks": 9 },
|
||||
"finish": {
|
||||
"headline": "Phase 3 is done",
|
||||
"body": "9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -A && git commit -m \"...\" -m \"AI Assisted\"\n```",
|
||||
"command": "/plan2code-3-implement specs/lunch-vote/overview.md",
|
||||
"doc": "report",
|
||||
"commit": true,
|
||||
"dashboard": true
|
||||
},
|
||||
"agent": { "status": "waiting" }
|
||||
}
|
||||
```
|
||||
|
||||
`"commit": true` is there because the body prints a git command: the finished
|
||||
screen gets a **Commit it now** button, and its `__commit` press is handled as
|
||||
console.md → Finishing says (resume as `git-commit`, same session). Leave it out
|
||||
when the body prints no commit.
|
||||
|
||||
`finish.command` is the next pipeline step, the same one the terminal names:
|
||||
the next `/plan2code-3-implement`, or `/plan2code-4-finalize` after the last
|
||||
phase. An `implement` finish never carries `review`: the offer was on the
|
||||
sign-off card, and approving past it was the answer. `implement-review` ends
|
||||
the same way; that phase was reviewed already. Only a finished `quick-task`
|
||||
still offers the review on its finish — see below.
|
||||
|
||||
`run` gives the approved phase its final score on the session meter (console.md →
|
||||
Posting an update → Session meter), in the same post that records the approval;
|
||||
it takes over what the build already counted from `cleared`, never adds to it:
|
||||
`implement-phase` for Implement, `implement-review-phase` for Implement +
|
||||
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
|
||||
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
|
||||
twelve-task phase weighs four times a three-task one; leave `tasks` out and
|
||||
every phase weighs the same. Quick task and a standalone Review are counted when
|
||||
their session opens, so they post no `run` for that; a review run on the page
|
||||
after a build reports its own (below).
|
||||
|
||||
---
|
||||
|
||||
## The review, mid-session
|
||||
|
||||
The same focused review runs from either of two doors:
|
||||
|
||||
- **`implement`:** the `review` verdict on the sign-off card, before anything
|
||||
is approved. A note sent with it is theirs — read it as focus for the
|
||||
review. Settle the card with it in the same post that goes back to work:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"items": [{ "id": "signoff", "status": "answered", "answer": { "verdict": "review" } }],
|
||||
"headline": { "stage": "Reviewing Phase 3", "cleared": 0, "total": 0 },
|
||||
"run": { "event": "review", "id": "review" },
|
||||
"agent": { "status": "working", "activity": "Reviewing the 7 files this phase changed", "quietMinutes": 15 }
|
||||
}
|
||||
```
|
||||
|
||||
- **`quick-task`:** the **Review it now** button on the finished screen, which
|
||||
`finish.review` puts there. It arrives through the wait loop as an action
|
||||
`{ "i": "__review", "type": "review" }`, like any send. Take it up with the
|
||||
same post minus the `items` line, plus `"finish": null` — that takes the
|
||||
session off its ending and back to work.
|
||||
|
||||
Either way, the post that takes the review up carries `"run": { "event":
|
||||
"review", "id": "review" }`: the review runs inside this skill's session, so no
|
||||
launch scores it on the session meter. Never resume the session under
|
||||
`--workflow review` for it as well, or it counts twice.
|
||||
|
||||
A finish carrying `review` keeps the session alive for the answer, so a
|
||||
`quick-task` that just posted one keeps waiting, for up to about ten minutes.
|
||||
A quick-task finish carries both `review` and `"dashboard": true` and waits
|
||||
for whichever comes first:
|
||||
|
||||
| What arrives | What you do |
|
||||
| --- | --- |
|
||||
| An action `{ "i": "__review", "type": "review" }` | Take the review up (below). |
|
||||
| An action `{ "i": "__dashboard", "type": "dashboard" }` | Take the session back as the dashboard (console.md → Finishing). |
|
||||
| An action `{ "i": "__done", "type": "done" }` | `stop` the server. The session is over. |
|
||||
| `wait` exit `20` | The server is gone, not necessarily the tab. Resume it (`open --resume <sid> --no-open --workflow <yours>`) and keep waiting. |
|
||||
| Nothing after about ten minutes | `stop` the server. The page then shows the terminal command for a review instead of a button that would go nowhere. |
|
||||
|
||||
**Read references/review.md** and run Review Mode with these overrides:
|
||||
|
||||
- **Scope is Focused, and already decided:** the exact change set of this
|
||||
session (files created or modified by the phase or the quick task, plus the
|
||||
tests and docs changed for it). Do not ask about scope. Use overview.md and
|
||||
the phase file for spec compliance; they do not widen the scope.
|
||||
- **No commit instructions and no next-conversation routing** mid-review. The
|
||||
way back out carries both.
|
||||
- The page takes the whole report, so the "top 10 of 15+" rule does not apply,
|
||||
and tables go in the doc.
|
||||
|
||||
### The findings
|
||||
|
||||
The full Review Mode report as a doc, and the fix choice as one `multi` item:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"docs": [{ "id": "review", "title": "Review findings", "version": 1, "blocks": [
|
||||
{ "id": "report", "state": "settled", "md": "## Overview\n\n...\n\n## Findings\n\n| # | Severity | Issue | File |\n..." }
|
||||
]}],
|
||||
"items": [{
|
||||
"id": "fixes", "kind": "multi", "title": "Which to fix", "required": false, "doc": "review",
|
||||
"body": "Tick what should be fixed now. Anything left unticked is written up as still open. Nothing changes until you send.",
|
||||
"options": [
|
||||
{ "k": "1", "text": "Critical: token is logged in plain text", "detail": "src/auth.ts:42. Fix: redact before logging." },
|
||||
{ "k": "2", "text": "Warning: missing null check on the user lookup", "detail": "src/users.ts:88. Fix: ..." },
|
||||
{ "k": "3", "text": "Suggestion: repeated query could be batched", "detail": "src/report.ts:17. Fix: ..." }
|
||||
],
|
||||
"presets": [
|
||||
{ "label": "Critical and warnings", "ks": ["1", "2"] },
|
||||
{ "label": "All of them", "ks": ["1", "2", "3"] }
|
||||
],
|
||||
"token": { "1": "1", "2": "2", "3": "3" },
|
||||
"fallbackText": "Reply H to fix Critical + Warning findings, A to fix all findings, or S 1,3,5 to fix specific findings."
|
||||
}],
|
||||
"agent": { "status": "waiting", "quietMinutes": null }
|
||||
}
|
||||
```
|
||||
|
||||
`"doc": "review"` puts a **Read "Review findings" in full** button on the
|
||||
card, so the report is one click from the list rather than behind a tab
|
||||
nobody notices. Always carry it.
|
||||
|
||||
Read the reply as Review Mode's fix choice: `Which to fix: 1, 2` is `S 1,2`,
|
||||
every finding ticked is `A`, and `skip` (or nothing ticked) is "fix none,
|
||||
keep them as unresolved". Leave out `presets` a set would not change (no
|
||||
warnings, one finding). With **zero findings** there is no item: say so in the
|
||||
doc and go straight to the way back out.
|
||||
|
||||
### Fixing
|
||||
|
||||
Settle the `fixes` item in the same post that goes back to work —
|
||||
`"status": "answered"` with the `answer` they sent (`{ "ks": ["1", "2"] }`,
|
||||
or `{ "ks": [] }` when nothing was ticked). The server records their send on
|
||||
the item, but only you decide it is settled; left open it stays on the page
|
||||
as an outstanding question, beside the card you ask next. Then follow Review
|
||||
Mode's Post-Fix Flow, posting `activity` per fix ("Fix 2 of 3: the null
|
||||
check") and `quietMinutes` as in a build.
|
||||
|
||||
### The way back out
|
||||
|
||||
**`implement` — back to the sign-off.** The review was the preamble to an
|
||||
approval that has not happened yet, so this is where it lands. Fold the review
|
||||
results and any still-open findings into the report doc and bump it, then
|
||||
reopen the sign-off **without the review verdict** — re-offering a review that
|
||||
just ran reads as though nothing happened:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"items": [{ "id": "signoff", "status": "reopened",
|
||||
"body": "Reviewed and ready for sign-off. The review found 3 issues: 2 fixed, 1 still open in the Review findings tab. The report is updated.",
|
||||
"verdicts": [
|
||||
{ "id": "approve", "label": "Approve this phase" },
|
||||
{ "id": "changes", "label": "I want changes" }
|
||||
],
|
||||
"thread": [{ "who": "agent", "text": "Review done: 2 of 3 findings fixed; the rest is written up in the findings tab." }]
|
||||
}],
|
||||
"agent": { "status": "waiting", "quietMinutes": null }
|
||||
}
|
||||
```
|
||||
|
||||
Review Mode's own closing gate ("Reply approved to commit") is this card:
|
||||
approving the phase now covers the fixes too, so there is no separate "Check
|
||||
the fixes" step. On approval, continue at "After approval: the finish".
|
||||
|
||||
**`quick-task` — the closing gate, then the finish.** Review Mode's closing
|
||||
gate ("Reply approved to commit, or request changes") becomes a `review` item
|
||||
titled "Check the fixes", `doc: "review"`, verdicts `approve` ("The fixes look
|
||||
right") and `changes`, token `approved` / `needs changes`. When it clears,
|
||||
settle it in the same post as the new finish — `"status": "answered"` plus
|
||||
`"answer": { "verdict": "approve" }` (or `"changes"`) — post the finish
|
||||
**without** `review`, then `stop`. An item left open survives on the page as
|
||||
a question still owed, above the ending itself:
|
||||
|
||||
- `headline`: "The review is done"
|
||||
- `body`: findings by severity, what was fixed, what is still open, and the
|
||||
commit command for the fixes, in the project's commit format.
|
||||
- `command`: the same next step as the finish before it.
|
||||
- `doc`: `"review"`.
|
||||
|
||||
---
|
||||
|
||||
## Implement + Review (`implement-review`)
|
||||
|
||||
The same build, then Stage 2 publishes the findings exactly as above (the
|
||||
`review` doc and the `fixes` item). Stage 3 fixes, with no "Check the fixes"
|
||||
item: Stage 4 is the only gate. The post that starts Stage 2's review carries
|
||||
`"run": { "event": "review", "id": "review" }`, as above: in this workflow it
|
||||
scores the review stage's 1 point on the meter as it begins, and the phase's
|
||||
final `run` leaves that point out. Stage 4 is the sign-off above **without the
|
||||
review verdict** — the phase was already reviewed — with the review results
|
||||
and unresolved findings in the report doc, header "Reviewed and ready for
|
||||
sign-off" in the item's `body`. The finish never carries `review`, and its
|
||||
post carries `"run": { "event": "implement-review-phase", "id": "phase-N", "tasks": N }`
|
||||
with the count of completed tasks.
|
||||
|
||||
---
|
||||
|
||||
## Quick task (`quick-task`)
|
||||
|
||||
- Open with the first clarifying question. Clarifying questions go out as
|
||||
`text` or `choice`, at most three at a time.
|
||||
- Post `"stopWarning": "A quick task saves nothing until it is built, so stopping now loses what we have worked out."`
|
||||
at the start, and `"stopWarning": ""` once the build is under way.
|
||||
- **Scope check:** a `choice`, "Too big for a quick task?", options
|
||||
`1` Continue (lightweight format) and `2` Escalate to a full plan, with the
|
||||
measured counts against the thresholds in `body`.
|
||||
- **Feature name** (escalating): `text` with
|
||||
`"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"` and a kebab-case placeholder.
|
||||
- **The plan:** a `plan` doc (Summary, Files to change, Steps, Verify) and a
|
||||
`review` item "Build this plan?" with verdicts `yes` ("Build it"), `modify`
|
||||
("Change the plan"), `escalate` ("Plan it properly instead") and `abort`
|
||||
("Stop here", `"danger": true`), token equal to the ids.
|
||||
- **Building** after `yes`: settle the verdict (`"status": "answered"` plus
|
||||
`"answer": { "verdict": "yes" }`) in the post that starts the build, and
|
||||
open a **Build progress** tab in that same post, the way an Implement phase
|
||||
gets its tasks tab. The plan's steps are the task list and `total` is their
|
||||
number:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"stopWarning": "",
|
||||
"items": [{ "id": "<the Build this plan? item's id>", "status": "answered", "answer": { "verdict": "yes" } }],
|
||||
"headline": { "stage": "Building", "cleared": 0, "total": 4 },
|
||||
"docs": [{ "id": "tasks", "title": "Build progress", "version": 1, "blocks": [
|
||||
{ "id": "tasks", "state": "settled", "md": "- [ ] Step one\n- [ ] Step two\n- [ ] Step three\n- [ ] Step four" }
|
||||
]}],
|
||||
"agent": { "status": "working", "activity": "Step 1 of 4: step one", "quietMinutes": 10 }
|
||||
}
|
||||
```
|
||||
|
||||
Then post after every step, exactly as "While you build": bump the doc's
|
||||
`version` and repost the whole list with that step ticked, raise
|
||||
`headline.cleared`, and set `agent.activity` to the next step ("Step 2 of 4:
|
||||
step two"). Never go silent for the whole build: a quick task with many steps
|
||||
is the case this tab is for. Check for a Quick question between steps, and do
|
||||
not call `wait` until the build is done.
|
||||
- **The finish after the build:** `command` is the commit command, filled in,
|
||||
in the project's commit format (AGENTS.md), with
|
||||
`"where": "When you are happy with it, commit it from your terminal:"`, and
|
||||
`review` on offer — the **Review it now** button, since a quick task has no
|
||||
sign-off card to put it on — `"commit": true` (the **Commit it now** button;
|
||||
console.md → Finishing) and `"dashboard": true`, so the finished screen
|
||||
also offers **Back to the dashboard**. Review and dashboard are required: a finish without
|
||||
`dashboard` leaves the person on a dead end. Keep waiting for whichever
|
||||
button is pressed, and everything after that is "The review, mid-session"
|
||||
above.
|
||||
- **Escalated / aborted:** settle the verdict the same way in the finish post —
|
||||
finish with `"command": "/plan2code-1-plan"` and the
|
||||
PLAN-DRAFT's path in `body`, no review; or `"command": "/plan2code-quick-task"`.
|
||||
Both set `"dashboard": true`: an abort of a quick task saves nothing to
|
||||
resume, so it is not a pause.
|
||||
|
||||
---
|
||||
|
||||
## Stop requests during a build
|
||||
|
||||
The Stop button only works on the person's turn, so it never lands mid-task.
|
||||
When `__stop` arrives:
|
||||
When `__stop` arrives (`console-stop.md`):
|
||||
|
||||
- **implement / implement-review:** Implementation Mode's abort, without the
|
||||
"are you sure" (the page asked): the phase stays `[/]`, list completed and
|
||||
@@ -498,8 +142,8 @@ When `__stop` arrives:
|
||||
- **quick-task:** say in `finish.body` what was worked out, and that nothing was
|
||||
saved unless it was built; `"command": "/plan2code-quick-task"`.
|
||||
|
||||
A mid-build `__dashboard` (the top bar's triangle, console.md → Stop requests →
|
||||
"Back to the dashboard, mid-workflow") lands the same way, only on the person's
|
||||
A mid-build `__dashboard` (the top bar's triangle, `console-stop.md` → "Back
|
||||
to the dashboard, mid-workflow") lands the same way, only on the person's
|
||||
turn. Save exactly as for `__stop` above (an implement phase stays `[/]`), but
|
||||
post no finish and do not `stop`: resume as the dashboard instead, with one
|
||||
terminal line naming what was saved and the resume command.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Keeping Attachments
|
||||
|
||||
Part of the web console contract (`console.md`). Read when a file you write
|
||||
under `specs/<idea>/` cites a note's attachment.
|
||||
|
||||
Note attachments are swept with the session. Before a file under `specs/<idea>/`
|
||||
cites one, keep it:
|
||||
|
||||
```
|
||||
node "<CONSOLE>" keep --session <sid> --upload <path> --name <name> --spec specs/<idea> --from <the file you are writing>
|
||||
```
|
||||
|
||||
It prints `{ ok, path, link, image, reused }`: paste `link` as it is
|
||||
(`` for an image, `[name](link)` otherwise) and name the kept file
|
||||
in your next update. Uncited and Quick-question attachments stay where they
|
||||
are. Exit 3 means refused: say so, link nothing.
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
# Quick Questions on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Read the first time `wait` or
|
||||
`chat` hands you a Quick question.
|
||||
|
||||
The page has an **Ask** tab, always the last one, on every workflow. There the
|
||||
person can ask anything, about this project's files or in general, at any
|
||||
time, without waiting for a card. Their messages reach you at your next
|
||||
check-in, through the `wait` you already run (and, in a build, the instant
|
||||
`chat` check). Chat rides its own channel: a message never blocks a card send,
|
||||
and a card send never blocks a message. The page handles its own refusals, so
|
||||
you never see them: `too-long` past 4,000 characters, `limit` after 10
|
||||
messages, `offline` when no agent has checked in for a few minutes (a finish alone does
|
||||
not end the chat: you may still be waiting on its buttons),
|
||||
`stale` after a new conversation started.
|
||||
|
||||
## How chat arrives
|
||||
|
||||
- `wait` exit `0` may carry `chat: [...]` beside `actions`, or, when no card
|
||||
was sent, be `type: "chat"` with `actions: []`. No exit code changes.
|
||||
- `reply` gains one block per entry after the card lines:
|
||||
|
||||
```
|
||||
Quick question: Where does the export go?
|
||||
About: Export format
|
||||
Image: /home/sam/.plan2code/console/sessions/<sid>/uploads/3f2b9c1e.jpg (shot.png)
|
||||
File: /home/sam/.plan2code/console/sessions/<sid>/uploads/9e4b2d7a.json (config.json)
|
||||
Declined: edit r7
|
||||
Note: keep the old name working too (only a decline carries one)
|
||||
New conversation started. Treat earlier chat as closed.
|
||||
```
|
||||
|
||||
Typed text past its first line is indented, so only a real entry ever
|
||||
starts a line.
|
||||
- Each `chat` entry carries `seq`, `conversation` and `kind`: `message`
|
||||
(`text`, optional `about`, `images` and `files`), `decision` (`re`,
|
||||
`decision` `approve` or `decline`, optional `text`) or `reset`.
|
||||
- `about` is set only when the person attached it with **+ Add context**. The
|
||||
page never adds one on its own, so a message without it is a general
|
||||
question, not one about the card on screen.
|
||||
- Open every `Image:` and `File:` path with your file-read tool before you
|
||||
answer, as for notes.
|
||||
- `node "<CONSOLE>" chat --session <sid>` checks right now and never sleeps:
|
||||
exit `0` with `{ chat, reply, terminalLine }`, `10` with `{ chat: [] }` when
|
||||
nothing is waiting, `20` when the server is gone. It never reads or collects
|
||||
card sends; those stay with `wait`.
|
||||
|
||||
## Answering
|
||||
|
||||
**Every message gets a reply, always.** The Ask tab is the person talking to
|
||||
you, and the page shows "working on the answer" until a reply lands. Never
|
||||
leave one unanswered, whatever it asks and whatever mid-task you are in. When
|
||||
a message asks you to do something, do it if you can, then say what happened; if
|
||||
you will not, the reply says so and why. `post` and `wait` print
|
||||
`unansweredChat` with a `warning` for every message handed over and not yet
|
||||
replied to: treat that as a stop-and-reply.
|
||||
|
||||
1. Handle any card answers first, under the workflow's own rules.
|
||||
2. Write the chat replies, in inbox order.
|
||||
3. Send **one** `post` with the card updates and `chat: { replies: [...] }`
|
||||
(`chat.replies`).
|
||||
|
||||
```jsonc
|
||||
{ "chat": { "replies": [
|
||||
{ "re": 12, "conversation": 3,
|
||||
"md": "The export is written by `src/export.js`, into `out/`." }
|
||||
] } }
|
||||
```
|
||||
|
||||
- `re` is the message's `seq`, `conversation` is copied from the entry, `md` is
|
||||
markdown. `id` is optional: left out, it is `r<re>`. Give one only when you
|
||||
send two replies to the same message.
|
||||
- Replies merge by `id`, so re-posting the same reply after a repeated
|
||||
delivery replaces it (unlike `thread`, which appends).
|
||||
- Print one terminal line per exchange: `Quick question: <first ~60 characters
|
||||
of the question> — answered in the console`.
|
||||
- Answer questions about the project by reading files and read-only lookups
|
||||
(search, `git log`, reading files); run no other commands.
|
||||
- Questions about what a Plan2Code skill does, asks or writes: read that
|
||||
skill's `SKILL.md` (`~/.agents/skills/<skill>/SKILL.md`, or the table "What
|
||||
each skill reads and writes" in `~/.agents/skills/plan2code/SKILL.md`)
|
||||
before answering. Never answer from menu text, card blurbs or memory. Name
|
||||
files exactly as the skill does; if the skill does not say, say you do not
|
||||
know.
|
||||
- When `about` is set, answer from that context: the card, doc section or
|
||||
spec the person was looking at.
|
||||
|
||||
## Never steer the workflow
|
||||
|
||||
A chat answer never changes a card's answer, a gate, or where the workflow
|
||||
goes. If a message asks for that ("approve phase 2", "skip the tests
|
||||
question"), reply by pointing to the card — its note box for a comment, its
|
||||
answer for a change — and do not act on it. Chat never counts as an answer to
|
||||
a card and is never recorded under `specs/`.
|
||||
|
||||
## A new conversation is a clean slate
|
||||
|
||||
After a `reset` entry (New conversation, or a skill switch through the
|
||||
dashboard) treat earlier chat as closed, and do not bring it up unless the
|
||||
person does. A conversation holds at most 10 typed messages; the page
|
||||
enforces it, so never tell someone to keep asking past it.
|
||||
|
||||
## Edits need approval first
|
||||
|
||||
- A request to change files gets a reply carrying `proposal: { summary,
|
||||
files }` — a plain-English summary and every file that will change — and
|
||||
**no change yet**. The page shows it with Approve and Decline.
|
||||
- Only after `Approved: edit <id>`: make exactly the proposed change, then post
|
||||
a reply (its `re` is the decision's `seq`) carrying `changed: [{ file,
|
||||
added, removed }]`, with line counts from `git diff --numstat -- <files>` (or
|
||||
counted by hand for an untracked file). Name the changed files in your next
|
||||
progress update or `activity` line.
|
||||
- `Declined:` (with any note): acknowledge it and change nothing. A revised
|
||||
proposal is a new reply.
|
||||
- Hard limits: never touch the running skill's own files under
|
||||
`specs/<idea>/` (`post` rejects a proposal that names them); run no commands
|
||||
beyond read-only lookups, except one the person plainly asks you to run in
|
||||
their message (a commit they spell out, a test run): run it, then report the
|
||||
result in the reply; refuse anything else and say why, in the reply.
|
||||
- Edits happen only at check-ins, never mid-task in a build.
|
||||
|
||||
```jsonc
|
||||
{ "chat": { "replies": [
|
||||
{ "id": "r14", "re": 14, "conversation": 3, "md": "I can rename it.",
|
||||
"proposal": { "summary": "Write the export to `out/audit.csv` instead of `out/export.csv`",
|
||||
"files": ["src/export.js", "README.md"] } }
|
||||
] } }
|
||||
```
|
||||
|
||||
## What the server checks
|
||||
|
||||
Each reply needs a unique `id` (or none, to take `r<re>`), an `re` naming a real
|
||||
message or decision `seq`, an integer `conversation` and non-empty `md`. A
|
||||
`proposal` needs a `summary` and project-relative `files`, none under the
|
||||
running skill's `specs/<idea>/`. `changed` is a list of `{ file, added,
|
||||
removed }`. The house rules on completion markers and metric-like words cover
|
||||
reply text too.
|
||||
|
||||
## The same chat twice
|
||||
|
||||
Replies merge by `id`, so re-post the same reply if it is not on the page yet;
|
||||
do not answer the question a second time.
|
||||
@@ -0,0 +1,118 @@
|
||||
# Finishing a Web Console Session
|
||||
|
||||
Part of the web console contract (`console.md`). Read before your first `finish`
|
||||
post, and when a send carries `__commit` or a finished screen's `__dashboard`.
|
||||
A stop request or the mid-workflow way home is `console-stop.md`.
|
||||
|
||||
Three steps, in this order. **Post the finish, keep waiting for a press —
|
||||
there is no timeout — and stop the server when the session ends.** A pause
|
||||
(below) still stops straight away.
|
||||
Stopping first leaves the person staring at a page that says "leave this tab
|
||||
open, the next question will appear here on its own" about a session that is
|
||||
over, and the one thing they need is a command in a terminal they are not
|
||||
looking at. Post it on every session end, not only the last one: an off-ramp
|
||||
that routes elsewhere, a checkpoint that saves and stops, a stop request.
|
||||
|
||||
**Nothing of yours may still be running.** Before the finish, every
|
||||
subagent or background job you started this session must have reported
|
||||
back. They run inside your terminal's process, not the console's: the page
|
||||
cannot see them, and the moment it says the session ended, the person is
|
||||
free to close that terminal and kill them mid-write. While you wait, post
|
||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||
and update the count as each returns. Never write a `finish.body` that says
|
||||
work "is running in the background" or "will finish on its own". Mark every
|
||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
||||
never ends on a row still running.
|
||||
|
||||
## 1. Post the finish
|
||||
|
||||
The same closer you are about to print in the terminal, as data:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"settle": true,
|
||||
"finish": {
|
||||
"headline": "The map is written",
|
||||
"body": "Everything you decided is on disk under `specs/lunch-vote/pathfinder/`, one file per decision. The **The map** tab has the whole picture.",
|
||||
"command": "/plan2code-0-pathfinder specs/lunch-vote/pathfinder",
|
||||
"doc": "map",
|
||||
"dashboard": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | | |
|
||||
| --- | --- | --- |
|
||||
| `headline` | required | What just happened, in plain words. Becomes the card's title. |
|
||||
| `command` | optional | The exact thing they run next, when there is one — the same string as your Trail Footer's Form A. Rendered with a Copy button that is always on show. Leave it out when nothing is left to run: the page shows an "All done" line with `/plan2code` instead. **No placeholders**: a rendered command is copied and run verbatim, and a patch carrying `<` or `>` in it is rejected. |
|
||||
| `dashboard` | optional | `true` puts a **Back to the dashboard** button on the finished screen. Set it on every ending except a pause, and keep waiting for the press (below). |
|
||||
| `body` | optional | Markdown. Where the files landed, what to read first. |
|
||||
| `where` | optional | Overrides "Run this in the terminal where you started Plan2Code, in a new conversation:". |
|
||||
| `doc` | optional | Id of the document to offer as a Markdown download on the way out. Defaults to the first one. |
|
||||
| `console` | optional | Whether the copied text asks the next session to use the web console. Leave it out: it follows from the command. |
|
||||
| `commit` | optional | `true` on a finished `quick-task`, `implement`, `implement-review`, `review` or `finalize` whose finish prints a git command puts a **Commit it now** button on the finished screen. The press arrives as `__commit` (below). |
|
||||
| `review` | optional | A finished `quick-task` only: `true` or `{ "label": "..." }` puts a **Review it now** button on the finished screen (`notes/quick-task.md`, `building-review.md`). `implement` offers the review on its sign-off card instead — before approval, where it can still change the outcome. |
|
||||
|
||||
**Write the bare command.** Every Plan2Code skill has a console — the
|
||||
dashboard and all twelve skills behind it — so for any of them the page
|
||||
appends ` --web` to what it shows and copies, so someone who worked here
|
||||
lands back here instead of being asked the interface question as though
|
||||
they were new. Every one of those skills takes that flag in its argument as
|
||||
the answer. Do not write `Use the web console for this session.` into the
|
||||
command; if it is there, the page swaps it for `--web`. A command that is not
|
||||
a Plan2Code skill gets nothing appended. Set `"console": false` if they have
|
||||
asked to go back to the terminal.
|
||||
|
||||
The page then says the session is finished rather than paused, offers the
|
||||
command, tells them they can close the tab, and stops treating the server going
|
||||
away as a fault. Send is disabled, and anything they staged and never sent is
|
||||
named rather than quietly lost.
|
||||
|
||||
Settle whatever the session ends on. An item still `open` when the finish
|
||||
lands freezes exactly as it stands: a send it carries shows as the final word
|
||||
on it, and one that was never answered shows as a question that ran out of
|
||||
time. If their last send was a verdict you are closing on — the review's
|
||||
`approve`, the plan's `yes`, the fixes pick — the finish post is the same post
|
||||
that settles it (`"settle": true`).
|
||||
|
||||
Post it even when you are also printing the footer in the terminal. Someone who
|
||||
has spent the whole session in the browser has no reason to look anywhere else.
|
||||
|
||||
The chat stays open after a finish for as long as you are still listening (the
|
||||
review and dashboard buttons live as long as you do); the page only turns Send
|
||||
off once you have gone quiet. So while you wait for a button press, answer any
|
||||
chat `wait` delivers (`console-chat.md`).
|
||||
|
||||
## 2. After the finish: the buttons
|
||||
|
||||
A **pause** is an ending that keeps a place to come back to: a stop request,
|
||||
an abort that keeps its place to resume, or a checkpoint that saves and ends
|
||||
(Plan's Large checkpoint). A pause's headline starts with "Paused", it never
|
||||
carries `dashboard`, and you post it without `--wait` and `stop` at once.
|
||||
|
||||
Every other finish carries `"dashboard": true` and goes up with `post --wait`;
|
||||
keep waiting in the usual slices. There is no timeout after a finish: the
|
||||
buttons live exactly as long as you are listening, so a press an hour later
|
||||
works like a press a minute later.
|
||||
|
||||
| What arrives | What you do |
|
||||
| --- | --- |
|
||||
| An action `{ "i": "__dashboard", "type": "dashboard" }` | Run the `resume` it carries (`open --resume <sid> --no-open --workflow dashboard`; it re-runs the project scan and clears the page, the finish included), read the dashboard skill (`skillFile`, or `~/.agents/skills/plan2code/SKILL.md`), then post its `menu` with `--wait` and carry on as the dashboard from its "Coming back from another skill", in this same conversation. |
|
||||
| An action `__review` or `__done` | As `building-review.md` says (quick task only). |
|
||||
| An action `{ "i": "__commit", "type": "commit" }` | Commit it now: run the `resume` it carries (`open --resume <sid> --no-open --workflow git`; no `finish`, no `stop`; the resume gives Git a clean page, the finish included, as a dashboard launch does), then open the Git skill (`skillFile`, or `~/.agents/skills/plan2code-git/SKILL.md`) with your file-read tool and follow it, starting with the commit flow over the board (the person pressed Commit it now), then the board with Push lit. Leave the commit command you printed in the finish where it is for the terminal. |
|
||||
| `wait` exit `20` | The server is gone. `open --resume <sid> --workflow <yours>` (it gets a new link: give it to them; the browser opens it), then keep waiting: their Ask messages and the dashboard button still need you. Give up only when the resume itself fails. |
|
||||
| The session ends without a press (the terminal closes, the conversation ends) | The server sweeps itself once its idle window passes, and the page swaps the buttons for the matching commands — nothing pressable dies silently. A press that lands in the meantime is kept on disk (`pendingResult`) for a resumed session. |
|
||||
|
||||
## 3. Stop the server
|
||||
|
||||
```
|
||||
node "<CONSOLE>" stop --session <sid>
|
||||
```
|
||||
|
||||
If you forget, it shuts itself down after 30 minutes of silence. Stop it anyway.
|
||||
The page keeps the hand-off on screen after the server has gone: everything it
|
||||
needs is already in `state.json`, and the Copy button is the one action that
|
||||
still works on a page whose server has died.
|
||||
|
||||
`node "<CONSOLE>" status` lists sessions for this project, including any whose
|
||||
answers were submitted but never picked up.
|
||||
@@ -0,0 +1,65 @@
|
||||
# Launches: the Dashboard on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Read when you are the
|
||||
dashboard. The dashboard skill's own prompt (`plan2code/SKILL.md`) has the
|
||||
menu judgment and the launch steps; this is what the page does around them.
|
||||
|
||||
## A launch
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [{ "i": "__launch", "type": "launch",
|
||||
"skill": "plan2code-3-implement", "workflow": "implement",
|
||||
"spec": "specs/lunch-vote" }],
|
||||
"reply": "Start Implement (/plan2code-3-implement) for specs/lunch-vote, right here in this session.",
|
||||
"resume": "node \"…/console.mjs\" open --resume <sid> --no-open --workflow implement --spec specs/lunch-vote",
|
||||
"skillFile": "…/plan2code-3-implement/SKILL.md" }
|
||||
```
|
||||
|
||||
`spec` is the picker's selected spec dir, present only when the launched skill
|
||||
takes a spec and the person picked one. `resume` is the one command to run
|
||||
first, before reading anything: it reuses the live server and turns the page
|
||||
from the menu into the skill's starting screen while you read. `skillFile` is
|
||||
the skill to read next (absent outside an install: then
|
||||
`~/.agents/skills/<skill>/SKILL.md`).
|
||||
|
||||
**A session handed to you is resumed, never re-opened.** A fresh `open` would
|
||||
strand the page the person is watching on the dashboard's session while your
|
||||
questions went to a page nobody has open. `--title` and `--spec` are honored on
|
||||
resume. A resume to or from `dashboard`, or into `git` from any skill, clears
|
||||
the page: the last skill's questions, sections, docs, headline and finish are
|
||||
dropped, so the new skill starts blank and posts its own. A skill run inline
|
||||
from another (a quick task's review) never resumes, and keeps the page it was
|
||||
handed.
|
||||
|
||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
||||
> own file-read tool and follow it from the top.** Every Plan2Code skill below
|
||||
> the dashboard ships `disable-model-invocation: true` on purpose, and calling
|
||||
> one through a skill-invocation tool errors out and strands the hand-off.
|
||||
|
||||
Its Interface step is already answered by having been launched. You have read
|
||||
`console.md` already: do not read it again; read only the notes or building
|
||||
files its Interface names.
|
||||
|
||||
From the click until the resume lands, the page shows a getting-ready screen;
|
||||
from the resume until the skill's first payload, its starting screen. Resume
|
||||
first, and post before anything slow.
|
||||
|
||||
## What the page already knows
|
||||
|
||||
`state.scan` is `{ hasAgents, isGit, pending, specs: [{ dir, name, state, detail, touched }] }`,
|
||||
a snapshot of the last `open` (a spec created mid-session appears the next time
|
||||
the session resumes as a dashboard). `pending` is how many files a commit would
|
||||
take (`null` when git cannot say): the Git card never greys out, shows the count
|
||||
when there is one, and outside a repository says Git can start one. The picker
|
||||
greys the cards that do not fit the selected spec — or hides them, while the
|
||||
**Hide unavailable workflows** switch under it is on (the default).
|
||||
|
||||
The `menu` you post (`note`, `recommend`, `details`) describes the initially
|
||||
selected spec; leave any field out and the page falls back to that spec's own
|
||||
next step, and it derives both again from the scan when the person switches
|
||||
specs or starts fresh. Post it with `--wait`; waiting on the menu is the
|
||||
person's turn by itself.
|
||||
|
||||
A `__stop` before a pick ends the session the usual way: `finish` (paused
|
||||
headline, `"command": "/plan2code"`) then `stop` (`console-stop.md`).
|
||||
@@ -0,0 +1,56 @@
|
||||
# The Session Meter on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Your workflow notes give the
|
||||
exact `run` to post; read this only if one is refused.
|
||||
|
||||
### Session meter
|
||||
|
||||
The page's top bar shows a meter of how much work this console session has
|
||||
done (green, yellow, red), so the person knows when a fresh session would be
|
||||
sharper. It is advice only and never blocks anything. The console counts
|
||||
launches itself: Plan, Revise plan, Document, Review, Quick task, Init, Init
|
||||
update, Finalize, Git and Changelog score when their session opens, and there is nothing to
|
||||
post for them.
|
||||
|
||||
It counts answers itself too: every card the person answers in a send adds to
|
||||
the skill run's tally when `wait` hands the send to you, and every 2 answers
|
||||
score a point, so a long back-and-forth weighs more than a short one. Notes,
|
||||
Quick questions and buttons such as Stop or the dashboard do not count.
|
||||
|
||||
Per-unit work is yours to report, with `run` in any post:
|
||||
|
||||
```jsonc
|
||||
{ "run": { "event": "implement-phase", "id": "phase-2", "tasks": 9 } }
|
||||
```
|
||||
|
||||
- `event` is one of `pathfinder-chart`, `pathfinder-question` (scores
|
||||
nothing now: answers count instead), `pathfinder-research`, `plan`,
|
||||
`revise-plan`, `document`, `implement-phase`, `implement-review-phase`,
|
||||
`review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`,
|
||||
`git`, `changelog`, `git-commits` and `git-conflict` (Git's own, see
|
||||
`notes/git.md`).
|
||||
An unknown event is exit `3`. Post only the events your notes name: a skill
|
||||
that scores when its session opens (the list above this one) already has its
|
||||
points, and a `run` for it scores the same work twice.
|
||||
- `id` names the unit: a question's file slug, `phase-N`, `map`. The same id
|
||||
posted again in the same skill run is ignored, so a repeated post never
|
||||
counts twice. It must be non-empty.
|
||||
- `tasks` goes only with `implement-phase` and `implement-review-phase`: the
|
||||
number of tasks the phase completed (marked `[x]`; blocked `[!]` tasks do
|
||||
not count), a whole number from 1 to 999. A built phase scores by its size,
|
||||
one point per 3 tasks rounded up, and Implement + Review one more for the
|
||||
review. Always send it: without it a phase scores a flat 2 (or 3), however
|
||||
big it was. On any other event it is exit `3`. The console already counts a
|
||||
build's tasks from `headline.cleared` as they are ticked off; the phase's
|
||||
`run` takes that count over with the final score, so it never counts twice.
|
||||
- `commits` goes only with `git-commits`: how many commits Git just made, a
|
||||
whole number from 1 to 999. A Git run scores one point per 2 commits,
|
||||
rounded down; on any other event it is exit `3`.
|
||||
- One `run` per post. Which events a workflow reports is in its own notes
|
||||
(`notes/pathfinder.md`, `notes/git.md`; `building.md` for Implement and for
|
||||
the review run on the page after a build).
|
||||
|
||||
`run` never reaches the page state: `post` (and `open --file`) lift it into the
|
||||
session's ledger.
|
||||
|
||||
---
|
||||
@@ -0,0 +1,97 @@
|
||||
# Stop Requests on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Read when a send carries
|
||||
`__stop` or `__dashboard`, or your workflow notes say to post a `stopWarning`.
|
||||
|
||||
## Stop requests
|
||||
|
||||
The page has a **Stop session** button. Pressing it sends, in one submit, any
|
||||
answers the person had staged plus one more action:
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [ /* staged answers and notes, as usual */,
|
||||
{ "i": "__stop", "type": "stop" } ],
|
||||
"reply": "...the answer lines...\nStop here and save my place, so I can pick this up later." }
|
||||
```
|
||||
|
||||
`__stop` is not an item and matches nothing; like every `__` action it is
|
||||
about the session. It arrives through `wait` with exit `0`, like any send. It is
|
||||
the person ending the session, so act on it in this turn:
|
||||
|
||||
1. **Handle the answers under the workflow's own rules, and record only what is
|
||||
final.** A confirmed recap, an approval verdict, a finished checklist with its
|
||||
values. A pick that still owes its recap is not an answer yet: save it where
|
||||
the workflow keeps unfinished work (Pathfinder: the question's `## Evidence`,
|
||||
with the probes still outstanding and your recommendation for each) and never
|
||||
write a provisional `## Answer`. Do not claim a question the person picked
|
||||
from a menu in the same send. Settle only the final cards (`"settle": [...]`).
|
||||
2. **Save your place** the way the workflow does when a session ends.
|
||||
3. **Post `finish`** (`console-finish.md`) with a headline starting "Paused"
|
||||
(the page and `open --resume` both key off that word), a body naming what
|
||||
was saved and anything still open, and the resume command, without
|
||||
`--wait`. Name a question that was left mid-way, so they can ask for it by
|
||||
name next time.
|
||||
4. **`stop`** the server.
|
||||
|
||||
Do not publish new questions and do not ask whether they are sure: the page
|
||||
already asked.
|
||||
|
||||
The page only offers Stop on the person's turn. From the moment they press Send
|
||||
until your reply lands, the button is disabled, so a stop never arrives while
|
||||
you are halfway through writing their last answers. The one exception is an
|
||||
agent that has stopped checking in: then Stop comes back, and the request waits
|
||||
on disk for whichever session collects it next.
|
||||
|
||||
## Back to the dashboard, mid-workflow
|
||||
|
||||
On every workflow but the dashboard, a triangle left of Stop session takes the
|
||||
person back to the dashboard. It follows Stop's rules exactly: only on their
|
||||
turn, a confirm first (with your `stopWarning`), and the staged answers ride
|
||||
along in the same submit:
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [ /* staged answers and notes, as usual */,
|
||||
{ "i": "__dashboard", "type": "dashboard" } ],
|
||||
"reply": "...the answer lines...\nSave my place and take me back to the dashboard, right here in this session.",
|
||||
"resume": "node \"…/console.mjs\" open --resume <sid> --no-open --workflow dashboard" }
|
||||
```
|
||||
|
||||
It is the same `__dashboard` a finished screen sends; with no `finish` on the
|
||||
page it means "stop, then go home". Act on it in this turn:
|
||||
|
||||
1. **Handle the answers** exactly as step 1 above.
|
||||
2. **Save your place** exactly as step 2 above.
|
||||
3. **Go home:** run the `resume` the send carried (it turns the page back into
|
||||
the dashboard and drops this skill's page), read the dashboard skill
|
||||
(`skillFile`, or `~/.agents/skills/plan2code/SKILL.md`), then post its
|
||||
`menu` with `--wait` and carry on as the dashboard from its "Coming back
|
||||
from another skill", in this same conversation.
|
||||
|
||||
No `finish` and no `stop` in between: the menu is the ending. Say what you
|
||||
saved in one terminal line, since no finish card will. A workflow with nothing
|
||||
to save (a quick task not yet built) just goes home.
|
||||
|
||||
## Saying what stopping would cost
|
||||
|
||||
Some points in a workflow have nothing on disk yet, and stopping there loses the
|
||||
answers given so far: Pathfinder before its map exists, Planning before a
|
||||
checkpoint. The page cannot know where you are, so tell it:
|
||||
|
||||
```jsonc
|
||||
{ "stopWarning": "The map is not written yet, so stopping now loses today's answers." }
|
||||
```
|
||||
|
||||
It is shown in the page's Stop dialog, and the button changes from "Stop and
|
||||
save" to "Stop anyway". Post `"stopWarning": ""` once stopping is safe again.
|
||||
For `plan` sessions the page assumes a warning until you post that empty string.
|
||||
|
||||
## Picking up a paused session
|
||||
|
||||
`open --resume <sid>` (or `open --session <sid>`) clears a paused `finish`
|
||||
itself, and the questions left open at the pause with it: the finish body
|
||||
already said what was still open, so re-ask whatever the new session needs in
|
||||
your own words rather than leaving the old asks on the page as duplicates.
|
||||
Settled items stay. For any other ending you are deliberately taking back, post
|
||||
`"finish": null` in your first patch.
|
||||
@@ -0,0 +1,85 @@
|
||||
# Standing Instructions: Helpers on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Read when a `Subagents:` block
|
||||
arrives, or when your workflow notes say to report helpers.
|
||||
|
||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
||||
from the top bar's Subagents button. Their pick is saved per project and per
|
||||
skill, on until switched off, and reaches you as a standing instruction, only when it
|
||||
changes.
|
||||
|
||||
## What arrives
|
||||
|
||||
A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`,
|
||||
after the card lines, the `Quick question:` blocks and the `Workspace:` lines.
|
||||
It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting
|
||||
change alone never ends a `wait` slice: it waits for the next send, or for
|
||||
your next `chat` check.
|
||||
|
||||
```
|
||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
||||
Report each helper on the page (console-subagents.md); questions for the person stay with you.
|
||||
If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.
|
||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.
|
||||
At most 3 helpers at once.
|
||||
```
|
||||
|
||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
||||
An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …`
|
||||
with the whole block again; switching off arrives as one line:
|
||||
`Subagents: off (revision 4) — don't start new helpers for the rest of this session.`
|
||||
|
||||
It is a console setting, not something the person typed. It never answers a
|
||||
card, and it is never recorded under `specs/`.
|
||||
|
||||
## Obeying it
|
||||
|
||||
- **On:** hand independent work to helpers if your tools allow it, at most
|
||||
`max` at once, following the instruction lines. `max` is advisory: your
|
||||
harness's own limit still applies.
|
||||
- **A higher revision replaces a lower one.** Follow the latest block only.
|
||||
- **Off:** start no new helpers for the rest of the session. Let running ones
|
||||
finish and report them.
|
||||
- **Nothing arrives:** keep doing what the skill says.
|
||||
- **Scope is the skill run it arrived in.** After a dashboard launch, no block
|
||||
means the switch is off for this skill, even if an earlier skill in the same
|
||||
conversation was told "on": `open` starts the count again, and a launch with
|
||||
the switch off sends nothing.
|
||||
|
||||
## Reporting helpers
|
||||
|
||||
Post them, at your check-ins, so the page's Subagents tab can show them. The
|
||||
page never hears from a helper directly:
|
||||
|
||||
```jsonc
|
||||
{ "helpers": [
|
||||
{ "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" },
|
||||
{ "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." }
|
||||
] }
|
||||
```
|
||||
|
||||
- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and
|
||||
`state` (`running`, `done` or `failed`) are required; `result` (at most 200)
|
||||
is the one line you add once a helper ends. Anything else is exit `3`, and
|
||||
the house rules on completion markers and metric-like words cover `title`,
|
||||
`ask` and `result`.
|
||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
||||
too; a resume into the same skill keeps it.
|
||||
- One post per change worth seeing, not a stream.
|
||||
- Questions for the person stay with you, never with a helper: most harnesses
|
||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
||||
session.
|
||||
- **No way to start helpers at all?** Post one `{ "id": "alone", "alone": true }`
|
||||
entry for the skill run instead. The tab then says you are working alone.
|
||||
It is a claim about your tools, not about the moment — post it only when no
|
||||
helper mechanism exists. Reporting a real helper removes it, so an early
|
||||
`alone` can never hide a later helper. At most one `alone` entry.
|
||||
- **Pathfinder:** research questions always use helpers and are always
|
||||
reported, whatever the switch says. The switch governs recon, sketches and
|
||||
lookups beside the conversation.
|
||||
- Helpers add no session meter points. Post no `run` for them.
|
||||
- Before any `finish`, mark every reported helper `done` or `failed`
|
||||
(`console-finish.md`).
|
||||
@@ -0,0 +1,20 @@
|
||||
# When Things Go Wrong on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Read when something goes wrong.
|
||||
|
||||
| Situation | What to do |
|
||||
| --- | --- |
|
||||
| `open` fails | Say so in one line, carry on in the terminal. Never block on this. |
|
||||
| `wait` returns `20` | `open --resume <sid>`, give them the new link. Nothing they typed is lost. |
|
||||
| They close the tab | Nothing happens. Drafts are saved. Reopening the link restores everything. |
|
||||
| Your session ends mid-flight | Their answers still land on disk. A fresh session runs `status` (or `open --resume`, which reports `pendingResult: true`), and `wait` returns them. An uncollected result is never discarded. |
|
||||
| They ask to go back to the terminal | `stop` the session and continue. The files under `specs/` are unchanged. |
|
||||
| The session ends and they are still in the browser | Post `finish` **before** `stop`, and wait for the dashboard button first unless it is a pause (`console-finish.md`). Without it their last screen says the next question is coming, and then says contact was lost. |
|
||||
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
||||
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
||||
| Picking up a paused session | `open --resume <sid>` clears a paused `finish` and the questions left open at it; re-ask what you still need (`console-stop.md` → Picking up a paused session). |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
||||
| A patch is refused (exit `3`) | stderr names every problem; nothing was written. Fix them and post again. A `version` refusal means the payload is stale: drop `version` and let it move by itself. |
|
||||
| A doc block's `file` is refused | It must be a file inside the project, under 512 KB; `select` only takes `tasks`. |
|
||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||
@@ -0,0 +1,80 @@
|
||||
# The Workspace on the Web Console
|
||||
|
||||
Part of the web console contract (`console.md`). Read when `open` lists more
|
||||
than one folder, a `Workspace:` line arrives, or someone writes `@name`.
|
||||
|
||||
The person can add folders beside the one the session started in (a shared
|
||||
library, a design folder), from the footer's folder label. Together they are
|
||||
the session's **workspace**: context for every skill run in this console
|
||||
session, each folder addressed by a short `@name`. It outlives dashboard hops,
|
||||
and it is remembered: every change is saved to `workspaces.json` beside
|
||||
`looks.json` (never into the project), keyed by the folder the session runs
|
||||
in and then by spec. A session with a spec opens on that spec's list, one with
|
||||
none on the project's; a spec with nothing saved starts as a copy of the
|
||||
project's list. The dashboard's picker swaps the list as the selection moves,
|
||||
and a `specDir` you post mid-run takes the current list with it. There is
|
||||
nothing for you to load: `open` prints the list, and a switch of spec on a
|
||||
resume reaches you as ordinary workspace changes on your next `wait`.
|
||||
|
||||
## What you are told
|
||||
|
||||
`open` (fresh or `--resume`) prints the whole list under `workspace`:
|
||||
|
||||
```jsonc
|
||||
{ "ok": true, "sid": "…", "url": "…",
|
||||
"workspace": {
|
||||
"folders": [
|
||||
{ "name": "shop", "path": "/home/sam/code/shop", "original": true },
|
||||
{ "name": "shared", "path": "/home/sam/code/shared-ui", "description": "Button and form styles" }
|
||||
],
|
||||
"missing": ["old-docs"]
|
||||
} }
|
||||
```
|
||||
|
||||
`missing` (only when there is one) names folders no longer on disk. After
|
||||
`open`, you hear only of changes, each exactly once:
|
||||
|
||||
- `wait` exit `0` carries them beside a send or chat as `workspace: [...]`
|
||||
(`{ kind, name, path, description?, from? }`, `kind` one of `added`,
|
||||
`renamed`, `described`, `removed`, `missing`, `found`), with one
|
||||
`Workspace: …` line each at the end of `reply`
|
||||
(`Workspace: added @shared — /home/sam/code/shared-ui`). A change alone never
|
||||
ends a slice: exit `10` counts it as `pendingWorkspace` and it rides on the
|
||||
next send.
|
||||
- `chat` hands changes over at once, with or without a Quick question, as
|
||||
`{ chat, workspace, reply }`.
|
||||
|
||||
Act on a change in the same turn it arrives: drop a removed folder, use the
|
||||
new name after a rename, note a missing one. No reply is needed unless the
|
||||
person asked something.
|
||||
|
||||
## Rules
|
||||
|
||||
- **Resolve `@name` from the workspace list.** `@shared` in an answer, a note
|
||||
or a Quick question means that folder's `path`. An `@name` not in the list
|
||||
is ordinary text.
|
||||
- **Added folders are read-only reference.** Read them freely; edit one only
|
||||
when the person asks for that change in this conversation. Chat edits still
|
||||
need approval (`console-chat.md` → Edits need approval first).
|
||||
- **Read an added folder's `AGENTS.md` before you first use it** (`CLAUDE.md`
|
||||
when there is no `AGENTS.md`), once per folder per skill run. It says how
|
||||
that folder is laid out; the original folder's `AGENTS.md` still governs
|
||||
this project and the work.
|
||||
|
||||
## When a folder cannot be read
|
||||
|
||||
When a read of an added folder genuinely fails (refused, not found), post, once
|
||||
per folder:
|
||||
|
||||
```jsonc
|
||||
{ "folderIssue": { "name": "shared", "reason": "Permission was refused", "hint": "/add-dir /home/sam/code/shared-ui" } }
|
||||
```
|
||||
|
||||
and print one terminal line saying which folder and why. The page marks the
|
||||
folder and tells the person once. `hint` is optional: an agent that knows it
|
||||
is Claude Code puts `/add-dir <path>` there. Your harness asking the person
|
||||
for permission is not a failure; report only a read that failed after it.
|
||||
|
||||
A `folderIssue` needs non-empty `name` and `reason` strings, and `hint`, when
|
||||
present, is one too; anything else is exit `3`. It goes to the session's
|
||||
ledger, never into the page state.
|
||||
+251
-1292
File diff suppressed because it is too large.
Load diff
+352
-36
@@ -64,6 +64,7 @@ import {
|
||||
readChat,
|
||||
readJson,
|
||||
readLedger,
|
||||
readPrHosts,
|
||||
readSubagentCursor,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
@@ -86,6 +87,7 @@ import {
|
||||
terminalLine,
|
||||
updateState,
|
||||
UPLOAD_MAX_AGE_MS,
|
||||
resolveDocFiles,
|
||||
validate,
|
||||
validateChat,
|
||||
workspaceForAgent,
|
||||
@@ -94,7 +96,8 @@ import {
|
||||
writeSubagentCursor,
|
||||
writeWorkspaceCursor,
|
||||
} from "./lib.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { snapshot } from "./git-repo.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_COMMITS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { blockFor, offered } from "./public/subagents.js";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
|
||||
@@ -165,9 +168,19 @@ async function cmdOpen() {
|
||||
// Going through the dashboard is a fresh start: a skill launched from
|
||||
// the menu gets a clean page, not the last skill's questions and tabs
|
||||
// under its own name. The staged draft goes too, since its item ids
|
||||
// belonged to the old questions. A skill run inline from another (a
|
||||
// quick task's review) never passes the dashboard, so it keeps the page.
|
||||
const hop = switching && (args.workflow === "dashboard" || state.workflow === "dashboard");
|
||||
// belonged to the old questions. Git counts as a launch from anywhere:
|
||||
// Commit it now on a finished screen and Changelog's "Commit this now?"
|
||||
// both stand in for its dashboard card, and a finish left
|
||||
// behind would keep the page on the old ending above the new questions
|
||||
// (or the new board). A hop also drops the last run's state.git, since
|
||||
// switchWorkflow() starts from a blank state.
|
||||
// A skill run inline from another (a quick task's review) never switches
|
||||
// through here, so it keeps the page.
|
||||
const hop =
|
||||
switching &&
|
||||
(args.workflow === "dashboard" ||
|
||||
state.workflow === "dashboard" ||
|
||||
args.workflow === "git");
|
||||
if (hop) fs.rmSync(path.join(dir, "draft.json"), { force: true });
|
||||
reshape = (s) => {
|
||||
// Resuming takes a pause back down. A paused finish is a bookmark --
|
||||
@@ -180,6 +193,15 @@ async function cmdOpen() {
|
||||
// --file applies, so a patch can still post a finish of its own.
|
||||
if (s.finish && /^\s*paused\b/i.test(String(s.finish.headline || ""))) {
|
||||
delete s.finish;
|
||||
// A new agent picking the session up: its own working turn, timed
|
||||
// from now, not the paused run's last status.
|
||||
s.agent = { status: "working", since: nowIso() };
|
||||
// The old run's warning about what a stop would lose is about its
|
||||
// unsaved work; the new run posts its own when it has some.
|
||||
delete s.stopWarning;
|
||||
// So is its count: the open questions it counted are dropped below,
|
||||
// and the page falls back to its own tally until the new run posts.
|
||||
s.headline = { stage: "", cleared: 0, total: 0, confidence: "", note: "" };
|
||||
// The questions still open at the pause were the old session's asks,
|
||||
// already narrated in the finish body so the next session can name
|
||||
// them. Whatever the resumed session still needs it asks again, in its
|
||||
@@ -229,15 +251,26 @@ async function cmdOpen() {
|
||||
// now, before anything is written, and appended once the launch is.
|
||||
let openRun;
|
||||
let openIssue;
|
||||
let openReread;
|
||||
let patch = null;
|
||||
if (args.file) {
|
||||
patch = readJson(path.resolve(args.file));
|
||||
if (!patch) die(`could not read --file ${args.file} as JSON`, 2);
|
||||
patch = readPatch(args.file);
|
||||
if (!patch) die(`could not read --file ${args.file} as one JSON object`, 2);
|
||||
({ run: openRun, folderIssue: openIssue } = patch);
|
||||
delete patch.run;
|
||||
delete patch.folderIssue;
|
||||
openReread = liftReread(patch, args.workflow || state.workflow);
|
||||
}
|
||||
const base = reshape;
|
||||
if (patch) {
|
||||
// Against the page as this open leaves it (a hop starts blank), so a
|
||||
// refresh never re-reads the last skill's files into the new page.
|
||||
try {
|
||||
patch = resolveDocFiles(patch, base(structuredClone(state)), worktree);
|
||||
} catch (e) {
|
||||
die(e.message, 3);
|
||||
}
|
||||
}
|
||||
const settle = (s) => {
|
||||
s = base(s);
|
||||
// On every open, so a resume from another worktree refreshes both.
|
||||
@@ -268,7 +301,13 @@ async function cmdOpen() {
|
||||
// poll tick. No page can reach it before it is listening, and the state is
|
||||
// on disk long before a browser gets there.
|
||||
const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null;
|
||||
const reusable = existing && pidAlive(existing.pid) ? healthOk(existing) : Promise.resolve(false);
|
||||
// A live pid gets a second, longer look before it is given up on, as `stop`
|
||||
// gives one: a server busy right after a post can miss the first, and a
|
||||
// second server for the same session strands the page on the first.
|
||||
const reusable =
|
||||
existing && pidAlive(existing.pid)
|
||||
? healthOk(existing).then((ok) => ok || healthOk(existing, 5000))
|
||||
: Promise.resolve(false);
|
||||
let boot = null;
|
||||
if (!existing) boot = await startServer(project, worktree, sid, dir);
|
||||
|
||||
@@ -279,6 +318,9 @@ async function cmdOpen() {
|
||||
// own top level: `project` is the common-dir key so linked worktrees share
|
||||
// sessions, but each shows the specs on its own disk.
|
||||
const scan = state.workflow === "dashboard" ? scanProject(worktree) : null;
|
||||
// The git board's data, the same way: the console's own read-only snapshot
|
||||
// (git-repo.mjs), taken before the lock so no git process runs under it.
|
||||
const gitSnap = state.workflow === "git" ? snapshot(worktree, { prHosts: readPrHosts() }) : null;
|
||||
|
||||
// Under the state lock, which a send on the page takes too: the result and
|
||||
// the state are read fresh here and the state is rebuilt from that read, so
|
||||
@@ -289,6 +331,9 @@ async function cmdOpen() {
|
||||
written = updateState(dir, (fresh) => {
|
||||
const next = fresh ? reshape(fresh) : state;
|
||||
if (scan) next.scan = scan;
|
||||
// A launch or hop starts the board fresh; a plain resume (a server
|
||||
// restart) keeps the last word on whether a Refresh failed.
|
||||
if (gitSnap) next.git = launched ? gitBlock(gitSnap, openReread ?? { refreshFailed: false }) : gitBlock(gitSnap, openReread, fresh?.git);
|
||||
|
||||
// Clear a result the agent already collected, and ONLY that one.
|
||||
//
|
||||
@@ -556,6 +601,26 @@ async function awaitHandle(started) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// A patch from a file, or from stdin with `--file -`: a heredoc piped into
|
||||
// the command saves the agent writing a file first, one tool call a turn.
|
||||
// A file PowerShell wrote comes with a BOM (Out-File / Set-Content in 5.1) or
|
||||
// in UTF-16 (its `>`), and both are the documented Windows route, so both read.
|
||||
function readPatch(file) {
|
||||
try {
|
||||
const buf = fs.readFileSync(file === "-" ? 0 : path.resolve(file));
|
||||
let text;
|
||||
if (buf[0] === 0xff && buf[1] === 0xfe) text = buf.subarray(2).toString("utf16le");
|
||||
else if (buf[0] === 0xfe && buf[1] === 0xff) text = Buffer.from(buf.subarray(2)).swap16().toString("utf16le");
|
||||
else text = buf.toString("utf8");
|
||||
// A patch is one JSON object: an array, string or number would merge
|
||||
// into the state as junk keys ("0", "1"...) and still report ok.
|
||||
const patch = JSON.parse(text.replace(/^\uFEFF/, ""));
|
||||
return patch && typeof patch === "object" && !Array.isArray(patch) ? patch : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function failValidation(problems) {
|
||||
process.stderr.write("console: the payload was rejected, nothing was written.\n");
|
||||
for (const p of problems) process.stderr.write(" - " + p + "\n");
|
||||
@@ -566,23 +631,44 @@ function failValidation(problems) {
|
||||
|
||||
/* ----------------------------------------------------------------- post */
|
||||
|
||||
function cmdPost() {
|
||||
async function cmdPost() {
|
||||
// `post --wait <seconds>` is a post and then a wait in one command: one tool
|
||||
// call per turn instead of two. A rejected post never waits (exit 3).
|
||||
if (args.wait !== undefined && args.wait !== true && !Number.isFinite(Number.parseFloat(args.wait))) {
|
||||
die("post --wait takes the slice in seconds, as wait --seconds does", 2);
|
||||
}
|
||||
if (!postOnce()) return;
|
||||
if (args.wait === undefined) return;
|
||||
// A bare --wait takes the slice from --seconds, as wait does.
|
||||
args.seconds = args.wait === true ? args.seconds : args.wait;
|
||||
return cmdWait();
|
||||
}
|
||||
|
||||
function postOnce() {
|
||||
const dir = mustSession();
|
||||
const file = args.file;
|
||||
if (!file) die("post needs --file <path to a JSON patch>", 2);
|
||||
const patch = readJson(path.resolve(file));
|
||||
if (!patch) die(`could not read --file ${file} as JSON`, 2);
|
||||
let patch = readPatch(file);
|
||||
if (!patch) die(`could not read --file ${file} as one JSON object`, 2);
|
||||
|
||||
const statePath = path.join(dir, "state.json");
|
||||
const before = readJson(statePath);
|
||||
if (!before) die("that session has no state", 1);
|
||||
try {
|
||||
patch = resolveDocFiles(patch, before, before.worktree || repoRoots().worktree);
|
||||
} catch (e) {
|
||||
die(e.message, 3);
|
||||
}
|
||||
|
||||
// Meter and folder reports go to the ledger, never into state.json. Checked
|
||||
// here, before anything is written: a rejected post appends nothing.
|
||||
const { run, folderIssue } = patch;
|
||||
delete patch.run;
|
||||
delete patch.folderIssue;
|
||||
const reread = liftReread(patch, before.workflow);
|
||||
const ledgerLines = ledgerFromPost(dir, run, folderIssue, before.workflow);
|
||||
// Taken before the lock: git processes must not run while it is held.
|
||||
const snap = reread === undefined ? null : snapshot(before.worktree || repoRoots().worktree, { prHosts: readPrHosts() });
|
||||
|
||||
// The patch is applied to a fresh read under the state lock, never to the
|
||||
// read above: a send the person made in between is in the file, and a write
|
||||
@@ -604,6 +690,14 @@ function cmdPost() {
|
||||
refused = [e.message, 3];
|
||||
return null;
|
||||
}
|
||||
// The result card and the fresh board land in this one write.
|
||||
if (snap) {
|
||||
next.git = gitBlock(snap, reread, fresh.git);
|
||||
// The footer names the branch too: after a switch or a create it is
|
||||
// the new one, and mid-rebase the one being rebased.
|
||||
const onBranch = snap.head && (snap.head.branch || snap.head.rebasing);
|
||||
if (onBranch) next.branch = onBranch;
|
||||
}
|
||||
problems = validate(next);
|
||||
if (!problems.length && patch.chat) problems = validateChat(next, readChat(dir));
|
||||
return problems.length ? null : next;
|
||||
@@ -625,9 +719,9 @@ function cmdPost() {
|
||||
}
|
||||
appendEvent(dir, { type: "post", items: (patch.items || []).length });
|
||||
|
||||
const open = next.items.filter((i) => isOpen(i) && i.required !== false).length;
|
||||
const open = next.items.filter((i) => isOpen(i) && i.required !== false && i.kind !== "notice").length;
|
||||
// Only a live server's link: no handle, no line, never a dead link.
|
||||
const handle = listHandles(projectRoot()).find((h) => h.sid === path.basename(dir));
|
||||
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === path.basename(dir));
|
||||
print({
|
||||
ok: true,
|
||||
items: next.items.length,
|
||||
@@ -636,6 +730,40 @@ function cmdPost() {
|
||||
...unansweredNote(dir, next),
|
||||
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* A patch's `reread`, the agent's "re-read the repo" signal on the git board
|
||||
* (FR-10), lifted out of the patch, or exit 3 when it is malformed or not on a
|
||||
* git session. state.git itself is the console's own: a patch never carries it.
|
||||
*/
|
||||
function liftReread(patch, workflow) {
|
||||
if (Object.hasOwn(patch, "git")) die("state.git is the console's own: post reread instead", 3);
|
||||
const { reread } = patch;
|
||||
delete patch.reread;
|
||||
if (reread === undefined) return undefined;
|
||||
const flagOnly =
|
||||
reread && typeof reread === "object" && !Array.isArray(reread) && Object.keys(reread).length === 1 && typeof reread.refreshFailed === "boolean";
|
||||
if (reread !== true && !flagOnly) die("reread must be true or { refreshFailed: true|false }", 3);
|
||||
if (workflow !== "git") die("reread only goes with the git workflow", 3);
|
||||
return reread;
|
||||
}
|
||||
|
||||
/**
|
||||
* The new state.git from a snapshot. The agent's refreshFailed wins; without
|
||||
* one, a newer FETCH_HEAD means a refresh worked, and anything else keeps the
|
||||
* last word on it.
|
||||
*/
|
||||
function gitBlock(snap, reread, previous) {
|
||||
let refreshFailed;
|
||||
if (reread && typeof reread === "object") refreshFailed = reread.refreshFailed;
|
||||
else if (snap.lastFetch && (!previous?.lastFetch || Date.parse(snap.lastFetch) > Date.parse(previous.lastFetch))) refreshFailed = false;
|
||||
else refreshFailed = Boolean(previous?.refreshFailed);
|
||||
// A failed fetch still touches FETCH_HEAD, so its time is not a refresh:
|
||||
// the board keeps saying when the last one that worked was.
|
||||
if (refreshFailed === true && reread && typeof reread === "object") return { ...snap, lastFetch: previous?.lastFetch ?? null, refreshFailed };
|
||||
return { ...snap, refreshFailed };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -656,7 +784,19 @@ function ledgerFromPost(dir, run, issue, workflow) {
|
||||
if (!TASK_EVENTS.has(event)) die(`run: tasks only goes with ${[...TASK_EVENTS].join(" or ")}`, 3);
|
||||
if (!isTaskCount(run.tasks)) die(`run: tasks must be a whole number from 1 to ${MAX_TASKS}`, 3);
|
||||
}
|
||||
lines.push({ kind: "run", id: `${launch}:${run.id}`, event, workflow, ...(run.tasks !== undefined ? { tasks: run.tasks } : {}) });
|
||||
if (run.commits !== undefined) {
|
||||
if (event !== "git-commits") die("run: commits only goes with git-commits", 3);
|
||||
const ok = Number.isInteger(run.commits) && run.commits >= 1 && run.commits <= MAX_COMMITS;
|
||||
if (!ok) die(`run: commits must be a whole number from 1 to ${MAX_COMMITS}`, 3);
|
||||
}
|
||||
lines.push({
|
||||
kind: "run",
|
||||
id: `${launch}:${run.id}`,
|
||||
event,
|
||||
workflow,
|
||||
...(run.tasks !== undefined ? { tasks: run.tasks } : {}),
|
||||
...(run.commits !== undefined ? { commits: run.commits } : {}),
|
||||
});
|
||||
}
|
||||
if (issue !== undefined) {
|
||||
const text = (v) => typeof v === "string" && v.trim() !== "";
|
||||
@@ -690,7 +830,7 @@ async function cmdWait() {
|
||||
}
|
||||
const seconds = Math.max(5, given === undefined ? 240 : asked);
|
||||
const sid = path.basename(dir);
|
||||
const project = projectRoot();
|
||||
const project = sessionProject(dir);
|
||||
const resultPath = path.join(dir, "result.json");
|
||||
const chatPath = path.join(dir, CHAT_FILE);
|
||||
const deadline = Date.now() + seconds * 1000;
|
||||
@@ -703,6 +843,7 @@ async function cmdWait() {
|
||||
if (existing && !existing.consumedAt) return consume(dir, resultPath, existing, liveUrl(), pendingChat());
|
||||
const earlyChat = pendingChat();
|
||||
if (earlyChat.length) return deliverChat(dir, sid, earlyChat, liveUrl());
|
||||
markWaiting(dir);
|
||||
|
||||
// A stat every 50ms, and a read only when the file has moved. The old tick
|
||||
// was a full read and parse every 400ms, which put up to 0.4s between the
|
||||
@@ -713,6 +854,17 @@ async function cmdWait() {
|
||||
// that merely does not answer must fail three checks in a row, each with a
|
||||
// longer look, before the slice ends with exit 20.
|
||||
let healthMisses = 0;
|
||||
// The check in flight, if any. Aborted on every way out, so a fetch left
|
||||
// running never holds the process (and the agent) past the print.
|
||||
let health = null;
|
||||
const healthStop = new AbortController();
|
||||
try {
|
||||
return await pollSlice();
|
||||
} finally {
|
||||
healthStop.abort();
|
||||
}
|
||||
|
||||
async function pollSlice() {
|
||||
// Null, not the current stamp: a result written between the check above and
|
||||
// this line would otherwise read as already seen and wait out the slice.
|
||||
let seen = null;
|
||||
@@ -735,7 +887,10 @@ async function cmdWait() {
|
||||
if (entries.length) return deliverChat(dir, sid, entries, liveUrl());
|
||||
}
|
||||
|
||||
if (Date.now() - healthAt > 5000) {
|
||||
// The health check runs beside the polling, never in its way: awaited
|
||||
// inline, a slow /health (a busy server, just after a send) held a
|
||||
// finished send back for up to the whole fetch timeout.
|
||||
if (!health && Date.now() - healthAt > 5000) {
|
||||
healthAt = Date.now();
|
||||
const handle = listHandles(project).find((h) => h.sid === sid);
|
||||
if (!handle || !pidAlive(handle.pid)) {
|
||||
@@ -743,18 +898,25 @@ async function cmdWait() {
|
||||
process.exitCode = 20;
|
||||
return;
|
||||
}
|
||||
if (await healthOk(handle, 4000)) healthMisses = 0;
|
||||
const check = { done: false, ok: false };
|
||||
health = check;
|
||||
healthOk(handle, 4000, healthStop.signal).then((ok) => Object.assign(check, { done: true, ok }));
|
||||
}
|
||||
if (health && health.done) {
|
||||
const { ok } = health;
|
||||
health = null;
|
||||
if (ok) healthMisses = 0;
|
||||
else if (++healthMisses >= 3) {
|
||||
print(serverGone(sid));
|
||||
process.exitCode = 20;
|
||||
return;
|
||||
} else healthAt = Date.now() - 3000; // look again in about 2s, not 5s
|
||||
}
|
||||
sleepSync(50);
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
|
||||
const state = readJson(path.join(dir, "state.json")) || {};
|
||||
const items = (state.items || []).filter((i) => i.required !== false);
|
||||
const items = (state.items || []).filter((i) => i.required !== false && i.kind !== "notice");
|
||||
const answered = items.filter((i) => !isOpen(i)).length;
|
||||
const draft = readJson(path.join(dir, "draft.json"), {});
|
||||
const staged = Object.keys(draft.staged || {}).length;
|
||||
@@ -770,13 +932,13 @@ async function cmdWait() {
|
||||
url: handle ? handle.url : "",
|
||||
message: "Waiting on your answer in the web console",
|
||||
next: "NOT FINISHED, do not end your turn or write a summary: relay the message in one line, then run this same wait command again right now. Repeat until the exit code is not 10.",
|
||||
pendingChat: 0,
|
||||
...unansweredNote(dir, state),
|
||||
// A workspace change alone never ends a slice: it rides on the next send.
|
||||
pendingWorkspace: pendingWorkspaceChanges(dir).length,
|
||||
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
|
||||
});
|
||||
process.exitCode = 10;
|
||||
}
|
||||
}
|
||||
|
||||
// Quick questions already handed over with no reply yet. Always empty when all are answered.
|
||||
@@ -791,7 +953,7 @@ function serverGone(sid) {
|
||||
return {
|
||||
status: "server-gone",
|
||||
sid,
|
||||
message: "The console server is not running. Start it again with `open --resume <sid> --no-open`, then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
|
||||
message: "The console server is not running. Start it again with `open --resume <sid> --workflow <yours>` (it gets a new link: give it to the person; without --no-open the browser opens it), then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -895,7 +1057,7 @@ function advanceCursor(dir, entries) {
|
||||
async function cmdChat() {
|
||||
const dir = mustSession();
|
||||
const sid = path.basename(dir);
|
||||
const handle = listHandles(projectRoot()).find((h) => h.sid === sid);
|
||||
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === sid);
|
||||
if (!handle || !pidAlive(handle.pid) || !(await healthOk(handle))) {
|
||||
print(serverGone(sid));
|
||||
process.exitCode = 20;
|
||||
@@ -940,10 +1102,12 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
||||
const hop = hopFor(path.basename(dir), result);
|
||||
print({ ...out, ...hop, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
try {
|
||||
writeJsonAtomic(resultPath, collected);
|
||||
} catch {}
|
||||
markWorking(dir, result);
|
||||
appendEvent(dir, { type: "consume", kind: result.type });
|
||||
ledgerAnswers(dir, result);
|
||||
advanceCursor(dir, chat);
|
||||
@@ -952,6 +1116,70 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||
}
|
||||
|
||||
// A collected send is the agent's turn: the page says so at once, without the
|
||||
// agent spending a whole post on "working" before it starts. The activity
|
||||
// line belonged to the last stretch of work, so it goes; quietMinutes stays,
|
||||
// since the page only counts it while working. Never fatal.
|
||||
// The send is no longer waiting to be picked up either, so the phase the
|
||||
// server set on it goes back to collecting (status and post report it).
|
||||
function markWorking(dir, result) {
|
||||
if (!result) return;
|
||||
try {
|
||||
updateState(dir, (s) => {
|
||||
if (!s) return null;
|
||||
if (result.type !== "submit") return s.phase === "submitted" ? { ...s, phase: "collecting" } : null;
|
||||
// The cards this send carried, so `settle: true` settles what the agent
|
||||
// was handed and never a later send still waiting to be collected.
|
||||
const ids = [...new Set((result.actions || []).filter((a) => a && (a.type === "answer" || a.type === "skip") && typeof a.i === "string" && !a.i.startsWith("__")).map((a) => a.i))];
|
||||
return applyPatch({ ...s, phase: "collecting", collected: { at: result.consumedAt || nowIso(), ids } }, { agent: { status: "working", activity: null } });
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Waiting on an open question (or a finished screen's buttons) is the
|
||||
// person's turn, whatever the last post said: an agent that replied to a note
|
||||
// and went back to `wait` without restating its status left the page on
|
||||
// "working" with nobody working. With nothing open it stays as it is: an
|
||||
// agent waiting out its research subagents is still working. Only a change
|
||||
// is written.
|
||||
function markWaiting(dir) {
|
||||
try {
|
||||
updateState(dir, (s) => {
|
||||
if (!s || !s.agent || s.agent.status !== "working") return null;
|
||||
// The dashboard's menu and the git board are the page's own, and theirs
|
||||
// to click whenever the agent is waiting.
|
||||
const theirTurn =
|
||||
s.finish || s.workflow === "dashboard" || s.workflow === "git" || (s.items || []).some((i) => isOpen(i) && i.kind !== "notice");
|
||||
return theirTurn ? applyPatch(s, { agent: { status: "waiting" } }) : null;
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The session hops a send can ask for, each with the one command that makes
|
||||
// it and the skill file to follow after, so the agent copies instead of
|
||||
// assembling `open --resume …` from the action's fields.
|
||||
const HOP_ACTIONS = {
|
||||
launch: (a) => ({ workflow: a.workflow, spec: a.spec, skill: a.skill }),
|
||||
dashboard: () => ({ workflow: "dashboard", skill: "plan2code" }),
|
||||
commit: () => ({ workflow: "git", skill: "plan2code-git" }),
|
||||
};
|
||||
|
||||
function hopFor(sid, result) {
|
||||
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
|
||||
const action = actions.find((a) => a && Object.hasOwn(HOP_ACTIONS, a.type) && typeof a.i === "string" && a.i.startsWith("__"));
|
||||
if (!action) return {};
|
||||
const { workflow, spec, skill } = HOP_ACTIONS[action.type](action);
|
||||
if (typeof workflow !== "string" || !/^[a-z-]+$/.test(workflow)) return {};
|
||||
const quote = (v) => (/[\s"]/.test(v) ? `"${v.replace(/"/g, '\\"')}"` : v);
|
||||
const specArg = typeof spec === "string" && spec ? ` --spec ${quote(spec)}` : "";
|
||||
const out = { resume: `node "${path.join(HERE, "console.mjs")}" open --resume ${sid} --no-open --workflow ${workflow}${specArg}` };
|
||||
if (typeof skill === "string" && /^[a-z0-9-]+$/.test(skill)) {
|
||||
const file = path.resolve(HERE, "..", "..", "..", skill, "SKILL.md");
|
||||
if (fs.existsSync(file)) out.skillFile = file;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// One `answer` ledger line per item the person answered in this send, for
|
||||
// the session meter. The id carries the send's stamp, so a send collected
|
||||
// twice (a kill before consumedAt was written) still counts once, while the
|
||||
@@ -984,7 +1212,20 @@ function cmdKeep() {
|
||||
const project = state.project;
|
||||
|
||||
const upload = path.resolve(args.upload);
|
||||
if (!inside(path.join(dir, "uploads"), upload)) die("upload is not in this session's uploads folder", 3);
|
||||
// Compared as real paths: Windows hands the same folder out both long
|
||||
// (C:\Users\Justin.Parker) and 8.3 (C:\Users\JUSTIN~1.PAR), and the reply's
|
||||
// path need not be spelled the way this session's directory is.
|
||||
// A path that does not exist (yet) resolves through its nearest real parent,
|
||||
// so a missing upload still reads as missing, not as somewhere else.
|
||||
const real = (p) => {
|
||||
try {
|
||||
return fs.realpathSync.native(p);
|
||||
} catch {
|
||||
const parent = path.dirname(path.resolve(p));
|
||||
return parent === path.resolve(p) ? path.resolve(p) : path.join(real(parent), path.basename(p));
|
||||
}
|
||||
};
|
||||
if (!inside(real(path.join(dir, "uploads")), real(upload))) die("upload is not in this session's uploads folder", 3);
|
||||
const spec = path.resolve(project, args.spec);
|
||||
const attachments = path.join(spec, "attachments");
|
||||
if (!inside(project, spec) || !inside(fs.realpathSync(project), realNearest(attachments))) {
|
||||
@@ -992,7 +1233,23 @@ function cmdKeep() {
|
||||
}
|
||||
if (!fs.existsSync(upload) || !fs.statSync(upload).isFile()) die("no such upload", 3);
|
||||
|
||||
const file = attachmentName({ upload, name: args.name });
|
||||
// The file the link is written for has to be in the project too, or the
|
||||
// relative link would point out of it.
|
||||
if (typeof args.from === "string" && !inside(project, path.resolve(project, args.from))) {
|
||||
die("--from is outside the project", 3);
|
||||
}
|
||||
|
||||
// One upload, one copy: kept again under another name, the copy it already
|
||||
// has (named for the same upload id) is the one reused.
|
||||
// Named from the real path: an 8.3 spelling (7CF881~1.JPG) would name the
|
||||
// copy after the short form and miss the copy this upload already has.
|
||||
const named = attachmentName({ upload: real(upload), name: args.name });
|
||||
const suffix = named.slice(named.lastIndexOf("-"));
|
||||
let existing = null;
|
||||
try {
|
||||
existing = fs.readdirSync(attachments).find((f) => f.endsWith(suffix));
|
||||
} catch {}
|
||||
const file = existing || named;
|
||||
const target = path.join(attachments, file);
|
||||
fs.mkdirSync(attachments, { recursive: true });
|
||||
let reused = false;
|
||||
@@ -1047,6 +1304,8 @@ function cmdForget() {
|
||||
/* ----------------------------------------------------------------- help */
|
||||
|
||||
function cmdHelp() {
|
||||
const topic = args._[0];
|
||||
if (topic !== undefined) return helpTopic(String(topic));
|
||||
process.stdout.write(`console.mjs — the Plan2Code web console. A detached server, a loopback
|
||||
port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
|
||||
@@ -1064,15 +1323,21 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
May also print subagents: { state, revision, max, instruction } and
|
||||
a reply holding only its "Subagents: ..." lines, when a standing
|
||||
instruction (the page's Subagents switch) is owed to you.
|
||||
post --session <sid> --file <patch.json>
|
||||
post --session <sid> --file <patch.json | -> [--wait <N>]
|
||||
Merge a patch into the session. Prints terminalLine while the
|
||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||
server is live. Exit 3 = rejected; stderr says why. --wait <N>
|
||||
then waits up to N seconds in the same command (two JSON lines;
|
||||
the exit code is the wait's). The patch may carry settle: true
|
||||
(or a list of item ids) to mark the latest send's cards answered
|
||||
with what was sent; doc blocks may carry file: "<path>" (and
|
||||
select: "tasks"), read from the project, and a doc refresh: true
|
||||
re-reads them. A doc's version moves up by itself. A patch may
|
||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||
{ name, reason, hint? } (a workspace folder you could not read);
|
||||
both go to the ledger, never into the state. A patch may also
|
||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
||||
(see console.md → Standing instructions).
|
||||
(help subagents).
|
||||
wait --session <sid> [--seconds <N>]
|
||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||
@@ -1085,7 +1350,11 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
pendingWorkspace, and a change alone never ends a slice.
|
||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
||||
by the person, with its "Subagents: ..." lines last in reply); a
|
||||
setting change alone never ends a slice either.
|
||||
setting change alone never ends a slice either. A hop
|
||||
(__launch, __dashboard, __commit) carries resume, the exact
|
||||
open --resume command, and skillFile when installed. Collecting
|
||||
a send sets the page to working; a wait with a question open
|
||||
hands the turn back.
|
||||
chat --session <sid>
|
||||
Collect Quick questions, workspace changes and a Subagents
|
||||
setting change now, never waiting, never touching card sends.
|
||||
@@ -1102,23 +1371,59 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
folder (Finalize, after archiving it). Prints { ok, spec, forgot };
|
||||
forgot is false when nothing was saved. Exit 2 = bad usage.
|
||||
status [--session <sid>] [--all]
|
||||
One session, or every session belonging to this project.
|
||||
One session, or (--all) every session on this machine, every project.
|
||||
stop --session <sid> | --all
|
||||
Shut a session's server down. Always post finish first.
|
||||
|
||||
workflows: dashboard · init · init-update · pathfinder · quick-task · plan ·
|
||||
revise-plan · document · implement · implement-review · review ·
|
||||
finalize · handoff · git-commit · changelog
|
||||
finalize · handoff · git · changelog
|
||||
|
||||
A session handed to you by the dashboard (a --session id): resume it with
|
||||
"open --resume <sid> --no-open --workflow <yours> --title <t>" -- never a
|
||||
"open --resume <sid> --no-open --workflow <yours>" (the resume it carries) -- never a
|
||||
fresh "open", which would strand the page the person is watching.
|
||||
|
||||
The full contract is console.md beside this file. Build sessions
|
||||
(implement, implement-review, quick-task) also read building.md.
|
||||
The contract is console.md beside this file, read once; the rest is
|
||||
read when its moment comes. help <topic> prints one; help topics lists
|
||||
them. Build sessions (implement, implement-review, quick-task) also read
|
||||
building.md.
|
||||
`);
|
||||
}
|
||||
|
||||
// The contract's topic files, by the name console.md's index gives them.
|
||||
// Printing one saves an agent the path hunt: it already runs this CLI.
|
||||
const HELP_TOPICS = {
|
||||
console: "console.md",
|
||||
building: "building.md",
|
||||
"building-review": "building-review.md",
|
||||
finish: "console-finish.md",
|
||||
stop: "console-stop.md",
|
||||
attachments: "console-attachments.md",
|
||||
chat: "console-chat.md",
|
||||
workspace: "console-workspace.md",
|
||||
subagents: "console-subagents.md",
|
||||
launches: "console-launches.md",
|
||||
dashboard: "console-launches.md",
|
||||
meter: "console-meter.md",
|
||||
trouble: "console-trouble.md",
|
||||
};
|
||||
for (const f of fs.existsSync(path.join(HERE, "notes")) ? fs.readdirSync(path.join(HERE, "notes")) : []) {
|
||||
if (f.endsWith(".md")) HELP_TOPICS[f.slice(0, -3)] ??= `notes/${f}`;
|
||||
}
|
||||
HELP_TOPICS["init-update"] ??= HELP_TOPICS.init;
|
||||
HELP_TOPICS["implement-review"] ??= HELP_TOPICS.implement;
|
||||
|
||||
function helpTopic(topic) {
|
||||
const names = Object.keys(HELP_TOPICS).sort();
|
||||
if (topic === "topics") {
|
||||
print({ topics: Object.fromEntries(names.map((n) => [n, HELP_TOPICS[n]])) });
|
||||
return;
|
||||
}
|
||||
const file = Object.hasOwn(HELP_TOPICS, topic) ? HELP_TOPICS[topic] : null;
|
||||
if (!file) die(`no help topic "${topic}". Topics: ${names.join(", ")}`, 2);
|
||||
process.stdout.write(fs.readFileSync(path.join(HERE, file), "utf8"));
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- status */
|
||||
|
||||
async function cmdStatus() {
|
||||
@@ -1126,7 +1431,7 @@ async function cmdStatus() {
|
||||
if (args.session || args.sid) {
|
||||
const dir = mustSession();
|
||||
const state = readJson(path.join(dir, "state.json")) || {};
|
||||
const handle = listHandles(project).find((h) => h.sid === path.basename(dir));
|
||||
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === path.basename(dir));
|
||||
const result = readJson(path.join(dir, "result.json"));
|
||||
return print({
|
||||
sid: state.sid,
|
||||
@@ -1176,7 +1481,10 @@ async function cmdStatus() {
|
||||
/* ----------------------------------------------------------------- stop */
|
||||
|
||||
async function cmdStop() {
|
||||
const project = projectRoot();
|
||||
// --all is this folder's sessions; one named session is found wherever
|
||||
// the command runs from.
|
||||
const named = !args.all && (args.session || args.sid) ? sessionDir(path.basename(args.session || args.sid)) : null;
|
||||
const project = named && fs.existsSync(named) ? sessionProject(named) : projectRoot();
|
||||
const handles = listHandles(project);
|
||||
const targets = args.all
|
||||
? handles
|
||||
@@ -1224,6 +1532,14 @@ function mustSession() {
|
||||
return dir;
|
||||
}
|
||||
|
||||
// The project a session belongs to, from its own state: a command run from
|
||||
// another folder (an agent whose shell moved) still finds the session's
|
||||
// server, rather than reporting it gone and starting a second one.
|
||||
function sessionProject(dir) {
|
||||
const state = readJson(path.join(dir, "state.json"));
|
||||
return (state && typeof state.project === "string" && state.project) || projectRoot();
|
||||
}
|
||||
|
||||
function tail(file, lines) {
|
||||
try {
|
||||
return fs.readFileSync(file, "utf8").split("\n").slice(-lines).join("\n");
|
||||
@@ -1339,7 +1655,7 @@ if (Number.isFinite(nodeMajor) && nodeMajor < 18) {
|
||||
|
||||
if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
|
||||
process.stderr.write(
|
||||
"console: usage: console.mjs <open|post|wait|chat|keep|status|stop|help> [--session <id>] [--file <patch.json>] [--seconds N]\n"
|
||||
"console: usage: console.mjs <open|post|wait|chat|keep|forget|status|stop|help> [--session <id>] [--file <patch.json>] [--seconds N]\n"
|
||||
);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,542 @@
|
||||
// git-repo.mjs: the one read-only reader of a git repository.
|
||||
//
|
||||
// Everything the git board and the dashboard need to know about a repository
|
||||
// comes from here: the worktree status, the branch table, the default branch,
|
||||
// a merge or rebase in progress, the remotes and their web addresses, when it
|
||||
// was last fetched, and the pull-request link. This module only reads: it
|
||||
// never changes the repository, the index or the working tree, and every git
|
||||
// call carries GIT_OPTIONAL_LOCKS=0 so a background look cannot take the index
|
||||
// lock out from under a commit. The console imports it directly; the git
|
||||
// skill's scripts reach it through common.mjs. Node built-ins only.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
import { prUrl } from "./public/pr-url.js";
|
||||
|
||||
export { prUrl };
|
||||
|
||||
/* ----------------------------------------------------------- running git */
|
||||
|
||||
/** Run git with an args array (never a shell). { ok, out, err }. */
|
||||
export function git(args, cwd, { raw = false, timeout } = {}) {
|
||||
try {
|
||||
const stdout = execFileSync("git", args, {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
windowsHide: true,
|
||||
timeout,
|
||||
// Without this, git status refreshes the index on disk: a write.
|
||||
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
|
||||
});
|
||||
return { ok: true, out: raw ? stdout : stdout.trim(), err: "" };
|
||||
} catch (e) {
|
||||
return { ok: false, out: "", err: String(e?.stderr || e?.message || "").trim() };
|
||||
}
|
||||
}
|
||||
|
||||
// git switch and git switch -c arrived in 2.23 (August 2019).
|
||||
const FLOOR = [2, 23, 0];
|
||||
let floorResult = null;
|
||||
|
||||
/** Is git on PATH and at least 2.23? Checked once per process. */
|
||||
export function gitFloor() {
|
||||
if (floorResult) return floorResult;
|
||||
const res = git(["--version"]);
|
||||
const version = res.ok ? res.out.replace(/^git version\s+/, "") || null : null;
|
||||
const m = version && version.match(/^(\d+)\.(\d+)\.(\d+)/);
|
||||
if (!version) {
|
||||
floorResult = { ok: false, version: null, message: "git is not installed or not on PATH." };
|
||||
} else {
|
||||
const parts = m ? m.slice(1, 4).map(Number) : [0, 0, 0];
|
||||
const cmp = parts.map((n, i) => n - FLOOR[i]).find((d) => d !== 0) || 0;
|
||||
floorResult = m && cmp >= 0
|
||||
? { ok: true, version }
|
||||
: { ok: false, version, message: `The git board needs git 2.23 or newer (found ${version}). Update git, then try again.` };
|
||||
}
|
||||
return floorResult;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- worktree status */
|
||||
|
||||
// The fields before the path in each porcelain v2 entry kind.
|
||||
const PATH_AFTER = { 1: 8, 2: 9, u: 10 };
|
||||
|
||||
function pathField(record, fields) {
|
||||
let at = 0;
|
||||
for (let k = 0; k < fields; k++) {
|
||||
const next = record.indexOf(" ", at);
|
||||
if (next < 0) return "";
|
||||
at = next + 1;
|
||||
}
|
||||
return record.slice(at);
|
||||
}
|
||||
|
||||
const letter = (c) => (c === "." ? " " : c);
|
||||
|
||||
function fileState(x, y) {
|
||||
if (x === "A" || x === "?" || y === "A" || y === "?") return "new";
|
||||
if (x === "D" || y === "D") return "deleted";
|
||||
if (x === "R" || x === "C" || y === "R" || y === "C") return "renamed";
|
||||
return "modified";
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse `git status --porcelain=v2 -z --branch --untracked-files=normal`.
|
||||
* Untracked entries come back as files with index " " and worktree "?";
|
||||
* unmerged entries go only into `conflicted`. ahead/behind are null without
|
||||
* an upstream; hasCommits is false for "(initial)" or without branch headers.
|
||||
*/
|
||||
export function parseStatusV2(text) {
|
||||
const result = { oid: null, hasCommits: false, branch: null, upstream: null, ahead: null, behind: null, files: [], conflicted: [] };
|
||||
const fields = String(text || "").split("\0");
|
||||
for (let i = 0; i < fields.length; i++) {
|
||||
const rec = fields[i];
|
||||
if (!rec) continue;
|
||||
if (rec.startsWith("# ")) {
|
||||
const [key, ...rest] = rec.slice(2).split(" ");
|
||||
const value = rest.join(" ");
|
||||
if (key === "branch.oid") {
|
||||
result.oid = value === "(initial)" ? null : value;
|
||||
result.hasCommits = value !== "(initial)";
|
||||
} else if (key === "branch.head") result.branch = value === "(detached)" ? null : value;
|
||||
else if (key === "branch.upstream") result.upstream = value;
|
||||
else if (key === "branch.ab") {
|
||||
const m = value.match(/^\+(\d+) -(\d+)$/);
|
||||
if (m) [result.ahead, result.behind] = [Number(m[1]), Number(m[2])];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const kind = rec[0];
|
||||
if (kind === "?") {
|
||||
result.files.push({ path: rec.slice(2), index: " ", worktree: "?", state: "new" });
|
||||
continue;
|
||||
}
|
||||
if (!(kind in PATH_AFTER)) continue; // "!" ignored, anything unknown too
|
||||
const x = letter(rec[2]);
|
||||
const y = letter(rec[3]);
|
||||
const p = pathField(rec, PATH_AFTER[kind]);
|
||||
if (kind === "u") {
|
||||
result.conflicted.push({ path: p, status: rec.slice(2, 4) });
|
||||
continue;
|
||||
}
|
||||
const entry = { path: p, index: x, worktree: y, state: fileState(x, y) };
|
||||
// A rename or copy carries its original path as one more NUL field.
|
||||
if (kind === "2") entry.origPath = fields[++i] || "";
|
||||
result.files.push(entry);
|
||||
}
|
||||
if (!result.upstream) [result.ahead, result.behind] = [null, null];
|
||||
return result;
|
||||
}
|
||||
|
||||
export const LARGE_BYTES = 5 * 1024 * 1024;
|
||||
// Every name is checked for secrets, but only the first STAT_LIMIT files are
|
||||
// sized, so a forgotten node_modules cannot make this slow.
|
||||
export const STAT_LIMIT = 2000;
|
||||
|
||||
// Basename tests for files that probably hold secrets.
|
||||
export const ENV_OK = new Set([".env.example", ".env.sample", ".env.template"]);
|
||||
export function isSensitive(file) {
|
||||
const b = file.split("/").pop();
|
||||
if (b === ".env" || (b.startsWith(".env.") && !ENV_OK.has(b))) return true;
|
||||
if (/\.(pem|key|p12|pfx|keystore|jks)$/.test(b)) return true;
|
||||
if (/^id_(rsa|dsa|ecdsa|ed25519)/.test(b)) return true;
|
||||
if (/^credentials.*\.json$/.test(b) || b.endsWith(".credentials")) return true;
|
||||
if (b === ".npmrc" || b === ".pypirc" || b === ".netrc") return true;
|
||||
return b.startsWith("secrets.");
|
||||
}
|
||||
|
||||
/** Sensitive paths and files over 5 MB among `names` (paths from `root`). */
|
||||
export function riskyFiles(root, names) {
|
||||
const sensitive = [];
|
||||
const large = [];
|
||||
let statted = 0;
|
||||
for (const p of new Set(names)) {
|
||||
if (isSensitive(p)) sensitive.push(p);
|
||||
if (statted >= STAT_LIMIT) continue;
|
||||
statted++;
|
||||
try {
|
||||
const st = fs.statSync(path.join(root, p));
|
||||
if (st.isFile() && st.size > LARGE_BYTES) large.push({ path: p, bytes: st.size });
|
||||
} catch {
|
||||
// a deletion, or a file that vanished
|
||||
}
|
||||
}
|
||||
return { sensitive: sensitive.sort(), large: large.sort((a, b) => a.path.localeCompare(b.path)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* What a commit would take, from a parseStatusV2() result. An untracked
|
||||
* folder is one row (its files counted with one ls-files) and counts once;
|
||||
* risky files inside it still count towards heldBack.
|
||||
*/
|
||||
export function readChanges(root, parsed) {
|
||||
const listed = [];
|
||||
const untrackedDirs = [];
|
||||
const inside = [];
|
||||
for (const f of parsed?.files || []) {
|
||||
if (f.worktree === "?" && f.path.endsWith("/")) {
|
||||
const res = git(["ls-files", "-o", "--exclude-standard", "-z", "--", f.path], root, { raw: true });
|
||||
const names = res.out.split("\0").filter(Boolean);
|
||||
untrackedDirs.push({ path: f.path, files: names.length });
|
||||
inside.push(...names);
|
||||
} else listed.push(f);
|
||||
}
|
||||
const { sensitive, large } = riskyFiles(root, [...listed.map((f) => f.path), ...inside]);
|
||||
const risky = new Set([...sensitive, ...large.map((l) => l.path)]);
|
||||
const files = listed.map((f) => ({ path: f.path, state: f.state, risky: risky.has(f.path), staged: f.index !== " " }));
|
||||
return { count: files.length + untrackedDirs.length, heldBack: risky.size, files, untrackedDirs, sensitive, large };
|
||||
}
|
||||
|
||||
/* ------------------------------------------- branches and repository state */
|
||||
|
||||
/** origin/HEAD, else local main, else master, else (no commits, on main or master) that branch. */
|
||||
export function defaultBranch(root, { branch, hasCommits } = {}) {
|
||||
const head = git(["symbolic-ref", "-q", "--short", "refs/remotes/origin/HEAD"], root);
|
||||
if (head.ok && head.out) return { name: head.out.replace(/^origin\//, ""), from: "origin/HEAD" };
|
||||
if (git(["show-ref", "--verify", "-q", "refs/heads/main"], root).ok) return { name: "main", from: "local-main" };
|
||||
if (git(["show-ref", "--verify", "-q", "refs/heads/master"], root).ok) return { name: "master", from: "local-master" };
|
||||
if (!hasCommits && (branch === "main" || branch === "master")) return { name: branch, from: "unborn" };
|
||||
return { name: null, from: null };
|
||||
}
|
||||
|
||||
const REF_FIELDS = [
|
||||
"%(refname)",
|
||||
"%(refname:short)",
|
||||
"%(upstream:short)",
|
||||
"%(upstream:track)",
|
||||
"%(upstream:remotename)",
|
||||
"%(symref)",
|
||||
"%(committerdate:iso-strict)",
|
||||
"%(authorname)",
|
||||
"%(contents:subject)",
|
||||
];
|
||||
|
||||
function track(text) {
|
||||
const ahead = text.match(/ahead (\d+)/);
|
||||
const behind = text.match(/behind (\d+)/);
|
||||
return { ahead: ahead ? Number(ahead[1]) : 0, behind: behind ? Number(behind[1]) : 0, gone: text === "[gone]" };
|
||||
}
|
||||
|
||||
// Subjects and authors go into the board verbatim: drop control bytes, or a
|
||||
// crafted subject (a \x01 is legal in a commit message) forges a table row.
|
||||
const cleanText = (s) => (s || "").replace(/[\x00-\x1f\x7f]/g, " ");
|
||||
|
||||
/** Every ref under refs/heads and refs/remotes, from one for-each-ref. */
|
||||
export function readRefs(root) {
|
||||
const res = git(["for-each-ref", `--format=${REF_FIELDS.join("%00")}%01`, "refs/heads", "refs/remotes"], root, { raw: true });
|
||||
return res.out
|
||||
.split("\x01")
|
||||
.map((r) => r.replace(/^\r?\n/, ""))
|
||||
.filter(Boolean)
|
||||
.map((r) => {
|
||||
const [ref, short, upstream, trackText, upstreamRemote, symref, at, author, subject] = r.split("\0");
|
||||
return { ref, short, upstream, trackText, upstreamRemote, symref, last: { subject: cleanText(subject), author: cleanText(author), at: at || "" } };
|
||||
});
|
||||
}
|
||||
|
||||
/** The default branch read off refs already fetched: origin/HEAD's target, else main, else master, else the unborn branch. */
|
||||
export function defaultBranchFromRefs(refs, { branch, hasCommits } = {}) {
|
||||
const head = refs.find((r) => r.ref === "refs/remotes/origin/HEAD");
|
||||
if (head && head.symref) {
|
||||
const m = head.symref.match(/^refs\/remotes\/[^/]+\/(.+)$/);
|
||||
if (m) return { name: m[1], from: "origin/HEAD" };
|
||||
}
|
||||
if (refs.some((r) => r.ref === "refs/heads/main")) return { name: "main", from: "local-main" };
|
||||
if (refs.some((r) => r.ref === "refs/heads/master")) return { name: "master", from: "local-master" };
|
||||
if (!hasCommits && (branch === "main" || branch === "master")) return { name: branch, from: "unborn" };
|
||||
return { name: null, from: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Every local branch, plus a row for each remote branch no local branch
|
||||
* tracks or shares a name with, from the refs readRefs() already fetched
|
||||
* (and one --merged read against the default branch).
|
||||
*/
|
||||
export function branchesFromRefs(refs, root, { current, defaultName } = {}) {
|
||||
const refnames = new Set(refs.map((r) => r.ref));
|
||||
const local = [];
|
||||
const remote = [];
|
||||
for (const r of refs) {
|
||||
if (r.ref.startsWith("refs/heads/")) {
|
||||
const name = r.ref.slice("refs/heads/".length);
|
||||
const t = r.upstream ? track(r.trackText || "") : { ahead: null, behind: null, gone: false };
|
||||
local.push({
|
||||
name,
|
||||
current: name === current,
|
||||
default: name === defaultName,
|
||||
remote: null,
|
||||
upstream: r.upstream || null,
|
||||
upstreamRemote: r.upstreamRemote || null,
|
||||
ahead: t.ahead,
|
||||
behind: t.behind,
|
||||
gone: t.gone,
|
||||
merged: false,
|
||||
last: r.last,
|
||||
});
|
||||
} else if (r.ref.startsWith("refs/remotes/") && !r.ref.endsWith("/HEAD")) {
|
||||
const rest = r.ref.slice("refs/remotes/".length);
|
||||
const slash = rest.indexOf("/");
|
||||
if (slash < 0) continue;
|
||||
remote.push({ short: r.short, remote: rest.slice(0, slash), name: rest.slice(slash + 1), last: r.last });
|
||||
}
|
||||
}
|
||||
const tracked = new Set(local.map((b) => b.upstream).filter(Boolean));
|
||||
const names = new Set(local.map((b) => b.name));
|
||||
const remoteOnly = remote
|
||||
.filter((r) => !tracked.has(r.short) && !tracked.has(`${r.remote}/${r.name}`) && !names.has(r.name))
|
||||
.map((r) => ({
|
||||
name: r.name,
|
||||
current: false,
|
||||
default: r.name === defaultName,
|
||||
remote: r.remote,
|
||||
upstream: null,
|
||||
upstreamRemote: null,
|
||||
ahead: null,
|
||||
behind: null,
|
||||
gone: false,
|
||||
merged: false,
|
||||
last: r.last,
|
||||
}));
|
||||
|
||||
if (defaultName) {
|
||||
const defaultRef = refnames.has(`refs/remotes/origin/${defaultName}`)
|
||||
? `refs/remotes/origin/${defaultName}`
|
||||
: refnames.has(`refs/heads/${defaultName}`)
|
||||
? `refs/heads/${defaultName}`
|
||||
: null;
|
||||
if (defaultRef) {
|
||||
const merged = new Set(
|
||||
git(["for-each-ref", "--merged", defaultRef, "--format=%(refname)", "refs/heads"], root).out.split(/\r?\n/).filter(Boolean),
|
||||
);
|
||||
for (const b of local) b.merged = b.name !== defaultName && merged.has(`refs/heads/${b.name}`);
|
||||
}
|
||||
}
|
||||
return [...local, ...remoteOnly];
|
||||
}
|
||||
|
||||
/** Every local branch plus remote-only rows: readRefs() + branchesFromRefs() in one call. */
|
||||
export function readBranches(root, { current, defaultName } = {}) {
|
||||
return branchesFromRefs(readRefs(root), root, { current, defaultName });
|
||||
}
|
||||
|
||||
const GIT_PATHS = ["rebase-merge", "rebase-apply", "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "FETCH_HEAD"];
|
||||
|
||||
/** Where git keeps its marker files for this worktree, resolved against `root`. {} on failure. */
|
||||
export function gitPaths(root) {
|
||||
const res = git(["rev-parse", ...GIT_PATHS.flatMap((p) => ["--git-path", p])], root);
|
||||
const lines = res.ok ? res.out.split(/\r?\n/) : [];
|
||||
if (lines.length !== GIT_PATHS.length) return {};
|
||||
return Object.fromEntries(GIT_PATHS.map((name, i) => [name, path.resolve(root, lines[i])]));
|
||||
}
|
||||
|
||||
const exists = (p) => !!p && fs.existsSync(p);
|
||||
|
||||
/**
|
||||
* rebase, am, merge, cherry-pick, revert or null, first match wins, in that
|
||||
* order. The rebase dirs come first: a conflicted `merge` entry in an
|
||||
* interactive rebase leaves MERGE_HEAD beside rebase-merge/, and the outer
|
||||
* operation is the rebase. rebase-apply/applying is git's own am marker
|
||||
* (the rule its shell prompt uses); without it the dir is a rebase.
|
||||
*/
|
||||
export function inProgressOp(paths = {}) {
|
||||
if (exists(paths["rebase-merge"])) return "rebase";
|
||||
if (exists(paths["rebase-apply"])) return exists(path.join(paths["rebase-apply"], "applying")) ? "am" : "rebase";
|
||||
if (exists(paths.MERGE_HEAD)) return "merge";
|
||||
if (exists(paths.CHERRY_PICK_HEAD)) return "cherry-pick";
|
||||
if (exists(paths.REVERT_HEAD)) return "revert";
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The branch a rebase in progress is rewriting (rebase-merge/ or rebase-apply/
|
||||
* head-name), so the board can say "main, rebasing" rather than "not on a
|
||||
* branch": HEAD is detached while git replays, but the person is on main.
|
||||
*/
|
||||
export function rebasingBranch(paths = {}) {
|
||||
for (const dir of [paths["rebase-merge"], paths["rebase-apply"]]) {
|
||||
if (!dir) continue;
|
||||
try {
|
||||
const ref = fs.readFileSync(path.join(dir, "head-name"), "utf8").trim();
|
||||
if (ref.startsWith("refs/heads/")) return ref.slice("refs/heads/".length);
|
||||
} catch {}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** FETCH_HEAD's mtime as an ISO string; null when it was never fetched. */
|
||||
export function lastFetch(paths = {}) {
|
||||
try {
|
||||
return fs.statSync(paths.FETCH_HEAD).mtime.toISOString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------- remotes and pull requests */
|
||||
|
||||
function hostKind(host) {
|
||||
if (host === "github.com") return "github";
|
||||
if (host === "gitlab.com") return "gitlab";
|
||||
if (host === "bitbucket.org") return "bitbucket";
|
||||
if (host === "dev.azure.com" || host === "ssh.dev.azure.com" || host.endsWith(".visualstudio.com")) return "azure";
|
||||
return null;
|
||||
}
|
||||
|
||||
// user@host:path, but not a Windows drive (C:/repo) and not a URL.
|
||||
const SCP = /^(?:[^@/]+@)?([^:/]+):(?!\/\/)(.+)$/;
|
||||
|
||||
/** A remote URL as { host, web, kind }; web is always https:. null when it cannot be read. */
|
||||
export function parseRemoteUrl(url) {
|
||||
const raw = String(url || "").trim();
|
||||
let host;
|
||||
let port = "";
|
||||
let repoPath;
|
||||
let ssh = false;
|
||||
if (/^(https?|ssh):\/\//i.test(raw)) {
|
||||
let u;
|
||||
try {
|
||||
u = new URL(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
host = u.hostname.toLowerCase();
|
||||
ssh = u.protocol === "ssh:";
|
||||
if (!ssh && u.port) port = `:${u.port}`;
|
||||
// Already percent-encoded, which is what a web address needs.
|
||||
repoPath = u.pathname;
|
||||
} else {
|
||||
const m = raw.match(SCP);
|
||||
if (!m || /^[A-Za-z]$/.test(m[1])) return null;
|
||||
host = m[1].toLowerCase();
|
||||
ssh = true;
|
||||
repoPath = m[2];
|
||||
}
|
||||
repoPath = repoPath.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/, "");
|
||||
if (!host || !repoPath) return null;
|
||||
|
||||
// Azure DevOps SSH remotes name the repo as v3/<org>/<project>/<repo>.
|
||||
const v3 = repoPath.match(/^v3\/([^/]+)\/([^/]+)\/([^/]+)$/);
|
||||
if (ssh && v3 && host === "ssh.dev.azure.com") {
|
||||
return { host: "dev.azure.com", web: `https://dev.azure.com/${v3[1]}/${v3[2]}/_git/${v3[3]}`, kind: "azure" };
|
||||
}
|
||||
if (ssh && v3 && host === "vs-ssh.visualstudio.com") {
|
||||
const web = `https://${v3[1]}.visualstudio.com/${v3[2]}/_git/${v3[3]}`;
|
||||
return { host: `${v3[1]}.visualstudio.com`, web, kind: "azure" };
|
||||
}
|
||||
return { host, web: `https://${host}${port}/${repoPath}`, kind: hostKind(host) };
|
||||
}
|
||||
|
||||
// Userinfo out of a scheme URL: remotes like https://user:token@host/... are
|
||||
// real (Azure DevOps PATs especially), and this string lands in state.json and
|
||||
// every state frame. Scp-style user@host:path keeps its user.
|
||||
const stripUserinfo = (url) => url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@\s]*@/i, "$1");
|
||||
|
||||
/** Every remote's fetch URL, web address and host kind; unknown hosts take their kind from prHosts. */
|
||||
export function readRemotes(root, prHosts = {}) {
|
||||
const res = git(["remote", "-v"], root);
|
||||
const remotes = [];
|
||||
for (const line of res.out.split(/\r?\n/)) {
|
||||
const m = line.match(/^(\S+)\s+(.+?)\s+\(fetch\)$/);
|
||||
if (!m) continue;
|
||||
const parsed = parseRemoteUrl(m[2]);
|
||||
const host = parsed?.host || null;
|
||||
let kind = parsed?.kind || null;
|
||||
if (!kind && host && Object.hasOwn(prHosts || {}, host)) kind = prHosts[host];
|
||||
remotes.push({ name: m[1], url: stripUserinfo(m[2]), host, web: parsed?.web || null, kind });
|
||||
}
|
||||
return remotes;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------- snapshot and the count */
|
||||
|
||||
const MARKER = /^(<{7}|={7}|>{7})( |$)/m;
|
||||
|
||||
function hasMarkers(file) {
|
||||
try {
|
||||
return MARKER.test(fs.readFileSync(file, "utf8"));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function safe(fn, fallback) {
|
||||
try {
|
||||
return fn();
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The state.git snapshot of the worktree at `worktree` (its top level), from
|
||||
* about four git processes plus one ls-files per untracked folder. Never
|
||||
* throws: a git failure inside a section leaves that section empty.
|
||||
*/
|
||||
export function snapshot(worktree, { prHosts = {} } = {}) {
|
||||
const at = new Date().toISOString();
|
||||
const floor = gitFloor();
|
||||
if (!floor.ok) return { at, repo: true, error: floor.message };
|
||||
const status = git(["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=normal"], worktree, { raw: true });
|
||||
if (!status.ok && !git(["rev-parse", "--git-dir"], worktree).ok) return { at, repo: false };
|
||||
const parsed = safe(() => parseStatusV2(status.out), parseStatusV2(""));
|
||||
// The branch table's for-each-ref already reads every ref: the default
|
||||
// branch comes off it instead of three more probes. When it is empty the
|
||||
// standalone probes still answer (empty repo, odd ref state).
|
||||
const refs = safe(() => readRefs(worktree), []);
|
||||
const def = refs.length
|
||||
? defaultBranchFromRefs(refs, parsed)
|
||||
: safe(() => defaultBranch(worktree, parsed), { name: null, from: null });
|
||||
const branches = safe(() => branchesFromRefs(refs, worktree, { current: parsed.branch, defaultName: def.name }), []);
|
||||
const paths = safe(() => gitPaths(worktree), {});
|
||||
const remotes = safe(() => readRemotes(worktree, prHosts), []);
|
||||
const changes = safe(() => readChanges(worktree, parsed), { count: 0, heldBack: 0, files: [], untrackedDirs: [], sensitive: [], large: [] });
|
||||
|
||||
let pr = null;
|
||||
const cur = branches.find((b) => b.current && !b.remote);
|
||||
if (cur && cur.upstream && !cur.gone && !cur.default && def.name) {
|
||||
const remote = remotes.find((r) => r.name === cur.upstreamRemote);
|
||||
if (remote) pr = prUrl(remote, { base: def.name, head: cur.name });
|
||||
}
|
||||
|
||||
return {
|
||||
at,
|
||||
repo: true,
|
||||
hasCommits: parsed.hasCommits,
|
||||
head: {
|
||||
branch: parsed.branch,
|
||||
detached: parsed.branch ? null : parsed.oid ? parsed.oid.slice(0, 7) : null,
|
||||
...(parsed.branch ? {} : { rebasing: safe(() => rebasingBranch(paths), null) }),
|
||||
upstream: parsed.upstream,
|
||||
// Its remote copy was deleted (fetch --prune): the upstream name is
|
||||
// still configured, but there is nothing behind it to pull or push to.
|
||||
gone: Boolean(cur && cur.gone),
|
||||
ahead: parsed.ahead,
|
||||
behind: parsed.behind,
|
||||
},
|
||||
defaultBranch: def.name,
|
||||
inProgress: safe(() => inProgressOp(paths), null),
|
||||
conflicted: parsed.conflicted.map((c) => ({ ...c, markers: hasMarkers(path.join(worktree, c.path)) })),
|
||||
changes: { count: changes.count, heldBack: changes.heldBack, files: changes.files, untrackedDirs: changes.untrackedDirs },
|
||||
remotes,
|
||||
lastFetch: safe(() => lastFetch(paths), null),
|
||||
refreshFailed: false,
|
||||
branches,
|
||||
prUrl: pr,
|
||||
};
|
||||
}
|
||||
|
||||
/** How many paths a commit would take from `dir` (an untracked folder counts once); null when git cannot say. */
|
||||
export function countPending(dir) {
|
||||
const res = git(["status", "--porcelain=v2", "-z", "--untracked-files=normal"], dir, { raw: true, timeout: 3000 });
|
||||
if (!res.ok) return null;
|
||||
try {
|
||||
const parsed = parseStatusV2(res.out);
|
||||
return parsed.files.length + parsed.conflicted.length;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+292
-38
@@ -22,6 +22,7 @@ import crypto from "node:crypto";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { countPending } from "./git-repo.mjs";
|
||||
import { CHAT_LIMIT } from "./public/chat.js";
|
||||
import { DOC_TYPES } from "./public/answers.js";
|
||||
import { defaultName } from "./public/workspace.js";
|
||||
@@ -361,29 +362,11 @@ export function insideGitRepo(dir) {
|
||||
// How many paths git would commit from `dir`: modified, staged, deleted and
|
||||
// untracked (an untracked folder counts once), from one bounded `git status`.
|
||||
// null when git cannot say (not installed, not a repository, too slow), which
|
||||
// the page reads as "unknown", never as a clean tree. --no-optional-locks keeps
|
||||
// this background look from taking the index lock out from under a commit.
|
||||
// the page reads as "unknown", never as a clean tree. GIT_OPTIONAL_LOCKS=0 (set
|
||||
// by git-repo.mjs) keeps this background look from taking the index lock out
|
||||
// from under a commit.
|
||||
export function pendingFiles(dir) {
|
||||
try {
|
||||
const out = execFileSync("git", ["--no-optional-locks", "status", "--porcelain", "-z"], {
|
||||
cwd: dir,
|
||||
encoding: "utf8",
|
||||
timeout: 3000,
|
||||
windowsHide: true,
|
||||
maxBuffer: 8 * 1024 * 1024,
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
});
|
||||
const parts = out.split("\0").filter(Boolean);
|
||||
let n = 0;
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
n++;
|
||||
// A rename or copy carries its old path as one more field.
|
||||
if (/^[RC]/.test(parts[i])) i++;
|
||||
}
|
||||
return n;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return countPending(dir);
|
||||
}
|
||||
|
||||
export function projectRoot(cwd = process.cwd()) {
|
||||
@@ -535,12 +518,13 @@ export async function removeSessions(sessionsDir, sids) {
|
||||
|
||||
// The console folder's own files that no sweep may ever remove: the person's
|
||||
// looks, the folders remembered per project and spec, the Subagents switch
|
||||
// saved per project and workflow, the pointer to this console's directory,
|
||||
// and the cached release check.
|
||||
// saved per project and workflow, what each unknown git host is, the pointer
|
||||
// to this console's directory, and the cached release check.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
||||
"looks.json",
|
||||
"workspaces.json",
|
||||
"subagents.json",
|
||||
"pr-hosts.json",
|
||||
"console-dir",
|
||||
"update-check.json",
|
||||
]);
|
||||
@@ -667,6 +651,23 @@ function strayEntries(dir, kept, where, now) {
|
||||
.filter((e) => settled(e.path));
|
||||
}
|
||||
|
||||
// Finalize's archive, `<project>/specs--completed/<feature>/`: each feature
|
||||
// folder (or link) nobody has touched for `maxAgeMs`, judged by its newest
|
||||
// file. Loose files at the top are not specs and stay.
|
||||
function completedSpecs(project, now, maxAgeMs) {
|
||||
const dir = path.join(project, "specs--completed");
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return entries
|
||||
.filter((e) => e.isDirectory() || e.isSymbolicLink())
|
||||
.map((e) => ({ id: "completed:" + e.name, where: "completed", name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
||||
.filter((e) => now - newestMtime(e.path) > maxAgeMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything Cleanup would remove, worked out on the server and never taken
|
||||
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
|
||||
@@ -676,6 +677,7 @@ function strayEntries(dir, kept, where, now) {
|
||||
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
|
||||
* touched within `STRAY_GRACE_MS` are left for a later scan. A
|
||||
* console running from another home (tests, dev) never reaches ~/.plan2code.
|
||||
* Given a `project`, also its completed specs untouched for `maxAgeMs`.
|
||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
||||
*/
|
||||
export async function cleanupFindings({
|
||||
@@ -684,6 +686,7 @@ export async function cleanupFindings({
|
||||
now = Date.now(),
|
||||
maxAgeMs = SESSION_MAX_AGE_MS,
|
||||
skipSid,
|
||||
project,
|
||||
} = {}) {
|
||||
const found = [];
|
||||
const sessionsDir = path.join(consoleDir, "sessions");
|
||||
@@ -695,6 +698,7 @@ export async function cleanupFindings({
|
||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
||||
}
|
||||
if (project) found.push(...completedSpecs(project, now, maxAgeMs));
|
||||
const items = [];
|
||||
let bytes = 0;
|
||||
for (const f of found) {
|
||||
@@ -843,8 +847,13 @@ function classifySpec(dir, names) {
|
||||
let open = 0;
|
||||
for (const f of phases) {
|
||||
const text = readText(path.join(dir, f));
|
||||
done += (text.match(/^- \[[xX]\]/gm) || []).length;
|
||||
open += (text.match(/^- \[[ /!]\]/gm) || []).length;
|
||||
// The task lines when the file has them (`- [ ] **Task 1.2:**`), so an
|
||||
// Acceptance Criteria checkbox is not counted as a task; every checkbox
|
||||
// in a file written before that format.
|
||||
const tasks = text.split(/\r?\n/).filter((l) => TASK_LINE_RE.test(l));
|
||||
const lines = tasks.length ? tasks.join("\n") : text;
|
||||
done += (lines.match(/^\s*[-*] \[[xX]\]/gm) || []).length;
|
||||
open += (lines.match(/^\s*[-*] \[[ /!]\]/gm) || []).length;
|
||||
}
|
||||
const total = done + open;
|
||||
if (open === 0 && done > 0) return { state: "built", detail: "all tasks done" };
|
||||
@@ -884,7 +893,7 @@ function classifySpec(dir, names) {
|
||||
// A conversation log with no draft is a plan session interrupted before it
|
||||
// wrote anything: Plan resumes it, same as a cleared map.
|
||||
if (planConv) return { state: "mapped", detail: "planning in progress" };
|
||||
return { state: "unrecognized", detail: "files on disk" };
|
||||
return { state: "unrecognized", detail: "no pipeline files yet" };
|
||||
}
|
||||
|
||||
function isDir(p) {
|
||||
@@ -954,10 +963,15 @@ export function pidAlive(pid) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function healthOk(handle, timeoutMs = 1500) {
|
||||
export async function healthOk(handle, timeoutMs = 1500, signal) {
|
||||
if (!handle || !handle.url) return false;
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
||||
// The caller's own abort ends the check at once (a wait that is done).
|
||||
if (signal) {
|
||||
if (signal.aborted) ctrl.abort();
|
||||
else signal.addEventListener("abort", () => ctrl.abort(), { once: true });
|
||||
}
|
||||
try {
|
||||
// No explicit Host header: it is a forbidden header name, so fetch drops it
|
||||
// silently. Requesting 127.0.0.1 directly sets the right one anyway, which
|
||||
@@ -1147,9 +1161,20 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
||||
// A different kind is never a typo fix: a multi turned confirm is another question.
|
||||
const kindChanged = "kind" in entry && entry.kind !== prev.kind;
|
||||
const reopens = entry.status === "open" || entry.status === "reopened" || kindChanged;
|
||||
if (!rewritten || settles || (wasSettled && !reopens)) continue;
|
||||
// An explicit reopen counts as asking again even with the question's
|
||||
// words unchanged (the notes reopen with a status and a thread reply):
|
||||
// the last send stops being in flight, and its note moves to the thread.
|
||||
if ((!rewritten && !reopens) || settles || (wasSettled && !reopens)) continue;
|
||||
const item = merged.find((x) => x.id === entry.id);
|
||||
if (wasSettled && !("status" in entry)) item.status = "open";
|
||||
// What they wrote with that answer ("I want changes: rename tally") is the
|
||||
// context for the question being asked again, so it moves into the thread
|
||||
// rather than leaving with the record.
|
||||
const said = prev.submitted && typeof prev.submitted.text === "string" ? prev.submitted.text.trim() : "";
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
if (said && !thread.some((m) => m && m.who === "user" && String(m.text || "").trim() === said)) {
|
||||
item.thread = [...thread.filter((m) => !(m && m.who === "agent" && m.at === undefined)), { who: "user", text: said, at: prev.submitted.at }, ...thread.filter((m) => m && m.who === "agent" && m.at === undefined)];
|
||||
}
|
||||
if (!("submitted" in entry)) delete item.submitted;
|
||||
delete item.answer;
|
||||
}
|
||||
@@ -1217,10 +1242,174 @@ function mergeDocs(current, patchList) {
|
||||
if (!doc) continue;
|
||||
const prev = (current || []).find((d) => d.id === entry.id);
|
||||
doc.blocks = mergeKeyed(prev?.blocks, entry.blocks, "id", {}, "blocks");
|
||||
// A known doc whose content moved, sent with no version, is the next
|
||||
// version: the agent no longer has to track what the page holds, and a
|
||||
// repost of unchanged content is not a new version.
|
||||
if (prev && typeof entry.version !== "number" && typeof prev.version === "number") {
|
||||
const text = (blocks) => JSON.stringify((blocks || []).map((b) => [b.id, b.md, b.state]));
|
||||
if (text(prev.blocks) !== text(doc.blocks)) doc.version = prev.version + 1;
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* `settle` in a patch: the cards the person just answered, marked answered
|
||||
* with what they sent as the answer. `true` takes every open card from the
|
||||
* latest send (one send stamps every card it carries with the same `at`); a
|
||||
* list names the cards. An item the same patch settles itself keeps the
|
||||
* agent's own answer: settle only fills in what the patch left out.
|
||||
*/
|
||||
function settleItems(items, settle, patchItems, collected) {
|
||||
if (settle === undefined || settle === false) return items;
|
||||
if (settle !== true && !(Array.isArray(settle) && settle.every((id) => typeof id === "string"))) {
|
||||
throw new Error('"settle" must be true or a list of item ids');
|
||||
}
|
||||
const sent = (items || []).filter((i) => i && i.submitted && typeof i.submitted === "object");
|
||||
let ids;
|
||||
if (settle === true && collected && Array.isArray(collected.ids)) {
|
||||
// The send `wait` last handed over (state.collected, written as it was
|
||||
// collected): a later send the person made meanwhile is not the agent's yet.
|
||||
ids = sent.filter((i) => isOpen(i) && collected.ids.includes(i.id)).map((i) => i.id);
|
||||
} else if (settle === true) {
|
||||
const latest = sent.filter(isOpen).map((i) => String(i.submitted.at || "")).sort().pop();
|
||||
ids = sent.filter((i) => isOpen(i) && String(i.submitted.at || "") === latest).map((i) => i.id);
|
||||
} else {
|
||||
for (const id of settle) {
|
||||
// The same patch reopening it has already let go of what was sent; the
|
||||
// reopen wins below, so naming it is not an error.
|
||||
const reopening = (patchItems || []).some((e) => e && e.id === id && (e.status === "open" || e.status === "reopened"));
|
||||
if (!reopening && !sent.some((i) => i.id === id)) throw new Error(`settle: "${id}" has nothing sent to settle`);
|
||||
}
|
||||
ids = settle;
|
||||
}
|
||||
const own = new Map((patchItems || []).filter(isPlainObject).map((e) => [e.id, e]));
|
||||
return items.map((item) => {
|
||||
if (!ids.includes(item.id)) return item;
|
||||
const entry = own.get(item.id) || {};
|
||||
// The same patch reopening it (a `changes` verdict answered by a reworked
|
||||
// report) means it is not settled: no answer is recorded over the reopen.
|
||||
if (entry.status === "open" || entry.status === "reopened") return item;
|
||||
const { at, kind, ...answer } = item.submitted;
|
||||
return {
|
||||
...item,
|
||||
// A "Skip this one" send settles as skipped, not as an answer.
|
||||
status: "status" in entry ? item.status : answer.skipped === true ? "skipped" : "answered",
|
||||
...("answer" in entry ? {} : { answer }),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// A question the patch puts in front of the person: new, or reopened.
|
||||
function asksSomething(patchItems, before) {
|
||||
return (patchItems || []).some((e) => {
|
||||
if (!isPlainObject(e) || e._delete || e.kind === "notice") return false;
|
||||
const prev = (before || []).find((x) => x && x.id === e.id);
|
||||
if (!prev) return e.kind !== undefined && (e.status === undefined || e.status === "open");
|
||||
return e.status === "reopened" || (e.status === "open" && !isOpen(prev));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The agent block after a patch, with the rule kept here rather than in every
|
||||
* prompt: a patch that asks a question and says nothing of the status hands
|
||||
* the turn over (a question stops the work). `quietMinutes` stays put: the
|
||||
* page only counts it while working, and a build that asked a question goes
|
||||
* back to the same long tasks once it is answered.
|
||||
*/
|
||||
function settleAgent(next, patch, before) {
|
||||
const said = isPlainObject(patch.agent) ? patch.agent : null;
|
||||
const saidStatus = said && "status" in said;
|
||||
// A finish ends the working stretch too (nothing may still be running at
|
||||
// one): a pause posted without a wait would otherwise sit at "working".
|
||||
const finishes = isPlainObject(patch.finish);
|
||||
if (!saidStatus && (finishes || asksSomething(patch.items, before.items))) {
|
||||
next.agent = { ...(next.agent || {}), status: "waiting" };
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Doc blocks that name a file get their `md` from disk: a build's phase file
|
||||
* re-posted after every task was the biggest thing an agent typed, and every
|
||||
* word of it was already on disk. `{ "id": "body", "file": "specs/x/phase-3.md" }`
|
||||
* reads the file; `"select": "tasks"` keeps only its task checkbox lines; a doc
|
||||
* with `"refresh": true` re-reads every file block it already has. Paths are
|
||||
* relative to the worktree and must stay inside it. Runs in the CLI before
|
||||
* the merge, so applyPatch itself never touches the disk.
|
||||
*/
|
||||
export const DOC_FILE_MAX = 512 * 1024;
|
||||
const TASK_LINE_RE = /^\s*(?:[-*]|\d+\.)\s+\[.\]\s+\*\*Task\s/i;
|
||||
|
||||
export function resolveDocFiles(patch, state, worktree) {
|
||||
if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch;
|
||||
const root = path.resolve(worktree || state.worktree || process.cwd());
|
||||
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
|
||||
const read = (file, select, docId) => {
|
||||
if (typeof file !== "string" || !file.trim()) throw new Error(`doc "${docId}": a block's "file" must be a path`);
|
||||
const abs = path.resolve(root, file);
|
||||
let real;
|
||||
try {
|
||||
real = fs.realpathSync.native(abs);
|
||||
} catch {
|
||||
throw new Error(`doc "${docId}": no file at ${file}`);
|
||||
}
|
||||
const rootReal = (() => {
|
||||
try {
|
||||
return fs.realpathSync.native(root);
|
||||
} catch {
|
||||
return root;
|
||||
}
|
||||
})();
|
||||
// path.relative, not a prefix test: a worktree at a drive root ends in a
|
||||
// separator already, and win32's relative() folds case itself.
|
||||
const rel = path.relative(fold(rootReal), fold(real));
|
||||
if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error(`doc "${docId}": ${file} is outside the project`);
|
||||
const stat = fs.statSync(real);
|
||||
if (!stat.isFile()) throw new Error(`doc "${docId}": ${file} is not a file`);
|
||||
if (stat.size > DOC_FILE_MAX) throw new Error(`doc "${docId}": ${file} is larger than ${DOC_FILE_MAX / 1024} KB`);
|
||||
const text = fs.readFileSync(real, "utf8").replace(/\r\n/g, "\n");
|
||||
if (select === undefined) return text;
|
||||
if (select !== "tasks") throw new Error(`doc "${docId}": "select" only takes "tasks"`);
|
||||
const tasks = text.split("\n").filter((l) => TASK_LINE_RE.test(l)).map((l) => l.trim());
|
||||
if (!tasks.length) throw new Error(`doc "${docId}": ${file} has no task lines to select`);
|
||||
return tasks.join("\n");
|
||||
};
|
||||
const docs = patch.docs.map((entry) => {
|
||||
if (!isPlainObject(entry)) return entry;
|
||||
const { refresh, ...rest } = entry;
|
||||
let blocks = Array.isArray(rest.blocks) ? rest.blocks : undefined;
|
||||
if (refresh === true) {
|
||||
const prev = (state.docs || []).find((d) => d && d.id === entry.id);
|
||||
const named = new Set((blocks || []).map((b) => b && b.id));
|
||||
const again = ((prev && prev.blocks) || [])
|
||||
.filter((b) => b && typeof b.file === "string" && !named.has(b.id))
|
||||
.map((b) => ({ id: b.id, file: b.file, ...(b.select ? { select: b.select } : {}) }));
|
||||
if (!again.length && !blocks) throw new Error(`doc "${entry.id}": "refresh" found no file blocks to re-read`);
|
||||
blocks = [...(blocks || []), ...again];
|
||||
} else if (refresh !== undefined) throw new Error(`doc "${entry.id}": "refresh" must be true`);
|
||||
if (!blocks) return rest;
|
||||
const prevBlocks = (state.docs || []).find((d) => d && d.id === entry.id)?.blocks || [];
|
||||
return {
|
||||
...rest,
|
||||
blocks: blocks.map((b) => {
|
||||
if (!isPlainObject(b)) return b;
|
||||
const prevBlock = prevBlocks.find((x) => x && x.id === b.id);
|
||||
if (b.file === undefined || b.file === null) {
|
||||
// Typed text over a block that was a file: it stops being one, so a
|
||||
// later refresh cannot overwrite it and the prose scan sees it.
|
||||
return "md" in b && prevBlock && typeof prevBlock.file === "string" ? { ...b, file: null, select: null } : b;
|
||||
}
|
||||
// A file named again without `select` is the whole file, now and on
|
||||
// every refresh: an older select must not linger in the merge.
|
||||
const select = "select" in b ? b.select : null;
|
||||
return { state: prevBlock?.state || "settled", ...b, select, md: read(b.file, select ?? undefined, entry.id) };
|
||||
}),
|
||||
};
|
||||
});
|
||||
return { ...patch, docs };
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply an agent patch to the session state.
|
||||
*
|
||||
@@ -1233,6 +1422,8 @@ function mergeDocs(current, patchList) {
|
||||
export function applyPatch(state, patch) {
|
||||
guard(patch, "patch");
|
||||
patch = liftActivity(patch);
|
||||
const { settle, ...rest } = patch;
|
||||
patch = rest;
|
||||
const next = { ...state };
|
||||
for (const [k, v] of Object.entries(patch)) {
|
||||
if (v === null) {
|
||||
@@ -1277,7 +1468,12 @@ export function applyPatch(state, patch) {
|
||||
const chat = { ...(next.chat || {}) };
|
||||
if (v.replies != null) {
|
||||
if (!Array.isArray(v.replies)) throw new Error('"chat.replies" must be an array');
|
||||
chat.replies = mergeKeyed(chat.replies, v.replies, "id", {}, "chat.replies");
|
||||
// A reply with no id is named for the message it answers (`r<seq>`),
|
||||
// so a repeat delivery re-posted the same way replaces, never doubles.
|
||||
const named = v.replies.map((r) =>
|
||||
isPlainObject(r) && (r.id === undefined || r.id === "") && Number.isInteger(r.re) ? { ...r, id: `r${r.re}` } : r,
|
||||
);
|
||||
chat.replies = mergeKeyed(chat.replies, named, "id", {}, "chat.replies");
|
||||
}
|
||||
next.chat = chat;
|
||||
break;
|
||||
@@ -1286,7 +1482,8 @@ export function applyPatch(state, patch) {
|
||||
next[k] = v;
|
||||
}
|
||||
}
|
||||
return stampTimes(state, next);
|
||||
if (settle !== undefined) next.items = settleItems(next.items || [], settle, patch.items, state.collected);
|
||||
return stampTimes(state, settleAgent(next, patch, state));
|
||||
}
|
||||
|
||||
// `activity` belongs under `agent`, which is the only place the page reads it.
|
||||
@@ -1305,8 +1502,10 @@ function liftActivity(patch) {
|
||||
function stampTimes(before, next) {
|
||||
const now = nowIso();
|
||||
if (next.agent) {
|
||||
// A status change starts its own clock: `since` merged along from the
|
||||
// last status would date a fresh working turn to when the session opened.
|
||||
const changed = !before.agent || before.agent.status !== next.agent.status;
|
||||
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
||||
if (changed) next.agent = { ...next.agent, since: now };
|
||||
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
||||
}
|
||||
if (Array.isArray(next.items)) {
|
||||
@@ -1464,7 +1663,17 @@ export function validate(state) {
|
||||
if (recs.length > 1) problems.push(`item "${item.id}" marks ${recs.length} options recommended; at most one`);
|
||||
}
|
||||
|
||||
const openRequired = state.items.filter((i) => i.required !== false && isOpen(i));
|
||||
// The dashboard's page is the menu: a card posted there is drawn nowhere,
|
||||
// yet counts as open (and keeps Stop live for a question nobody can see).
|
||||
if (state.workflow === "dashboard" && state.items.some((i) => isOpen(i))) {
|
||||
problems.push(
|
||||
'The dashboard draws no question cards: post its "menu" (and "agent"), and launch the skill a question belongs to.'
|
||||
);
|
||||
}
|
||||
|
||||
// A notice asks nothing (the git board keeps its result line open all
|
||||
// session), so it never takes one of the three slots.
|
||||
const openRequired = state.items.filter((i) => i.required !== false && i.kind !== "notice" && isOpen(i));
|
||||
if (openRequired.length > MAX_OPEN_REQUIRED) {
|
||||
problems.push(
|
||||
`${openRequired.length} questions are open at once. The cap is ${MAX_OPEN_REQUIRED} ` +
|
||||
@@ -1532,11 +1741,18 @@ export function validate(state) {
|
||||
if (quiet != null && (typeof quiet !== "number" || !(quiet > 0) || quiet > 60)) {
|
||||
problems.push('"agent.quietMinutes" must be a number of minutes between 1 and 60 (or null to clear it)');
|
||||
}
|
||||
// The page reads exactly two: anything else would leave it guessing whose
|
||||
// turn it is.
|
||||
if (state.agent && state.agent.status != null && !["working", "waiting"].includes(state.agent.status)) {
|
||||
problems.push(`"agent.status" must be "working" or "waiting" (not "${state.agent.status}")`);
|
||||
}
|
||||
if (state.agent && state.agent.activity != null && typeof state.agent.activity !== "string") {
|
||||
problems.push('"agent.activity" must be a short sentence saying what you are doing');
|
||||
}
|
||||
|
||||
const gates = state.items.filter((i) => i.gate && i.gate.authoritative);
|
||||
// Open gates only: an approval already given (last phase's sign-off) is a
|
||||
// record, and must not stop the next phase from asking for its own.
|
||||
const gates = state.items.filter((i) => i.gate && i.gate.authoritative && isOpen(i));
|
||||
if (gates.length > 1) {
|
||||
problems.push(
|
||||
`${gates.length} authoritative approval gates are open (${gates
|
||||
@@ -1553,9 +1769,15 @@ export function validate(state) {
|
||||
...rest,
|
||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
||||
}));
|
||||
// A doc block read from a file (`file`) is the file's own words, already on
|
||||
// disk: the agent cannot reword it, and refusing it would wedge every post
|
||||
// that refreshes it. Only what the agent typed is scanned.
|
||||
const typedDocs = (state.docs || []).map((d) =>
|
||||
isPlainObject(d) && Array.isArray(d.blocks) ? { ...d, blocks: d.blocks.filter((b) => !(isPlainObject(b) && typeof b.file === "string")) } : d
|
||||
);
|
||||
const prose =
|
||||
JSON.stringify(authored) +
|
||||
JSON.stringify(state.docs || []) +
|
||||
JSON.stringify(typedDocs) +
|
||||
JSON.stringify(state.finish || {}) +
|
||||
JSON.stringify(state.menu || {});
|
||||
problems.push(...proseProblems(prose));
|
||||
@@ -1591,7 +1813,7 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
specDir: specDir || "",
|
||||
created: nowIso(),
|
||||
phase: "collecting",
|
||||
agent: { status: "working", since: nowIso(), handled: 0 },
|
||||
agent: { status: "working", since: nowIso() },
|
||||
headline: { stage: "", cleared: 0, total: 0, confidence: "", note: "" },
|
||||
topics: [],
|
||||
items: [],
|
||||
@@ -1601,7 +1823,8 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
|
||||
/**
|
||||
* A resume that passes through the dashboard (a finished skill going back to
|
||||
* it, or a launch from its menu) is a new skill taking the page over, so it
|
||||
* it, or a launch from its menu), or into Git from any skill
|
||||
* (Commit it now, Changelog's hand-off), is a new skill taking the page over, so it
|
||||
* starts from a blank page: the last skill's questions, sections, docs,
|
||||
* helpers, headline and ending are its record on disk, not the next skill's
|
||||
* opening.
|
||||
@@ -1770,8 +1993,12 @@ export function collectChat(dir, state) {
|
||||
// something the person said. A reset alone (every session opens with one)
|
||||
// waits and rides along with the next message, or `wait` would return on the
|
||||
// opening line of every session and every first card reply would carry it.
|
||||
// A run of resets (the session's opening one, then one per skill switch)
|
||||
// says one thing, so only the last of each run is handed over; it carries the
|
||||
// highest seq of the run, so the cursor still moves past all of them.
|
||||
export function deliverableChat(entries) {
|
||||
return entries.some((e) => e.kind !== "reset") ? entries : [];
|
||||
if (!entries.some((e) => e.kind !== "reset")) return [];
|
||||
return entries.filter((e, i) => !(e.kind === "reset" && entries[i + 1] && entries[i + 1].kind === "reset"));
|
||||
}
|
||||
|
||||
// Things the person said that were handed over but never answered. The page keeps
|
||||
@@ -2129,6 +2356,33 @@ export function saveSubagentStoreEntry(worktree, workflow, value) {
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- the PR host store */
|
||||
|
||||
// What kind of git host an unknown host is, so the git board can build its
|
||||
// pull-request link. One answer per host, for every project:
|
||||
//
|
||||
// { "<host>": "github" | "gitlab" | "bitbucket" | "azure" | "none" }
|
||||
export const PR_HOSTS_FILE = path.join(HOME_DIR, "pr-hosts.json");
|
||||
export const PR_HOST_KINDS = new Set(["github", "gitlab", "bitbucket", "azure", "none"]);
|
||||
const PR_HOSTS_LOCK = "pr-hosts.json.lock";
|
||||
|
||||
// The saved hosts as a plain object; malformed → {}, unknown kinds dropped.
|
||||
export function readPrHosts() {
|
||||
const saved = readJson(PR_HOSTS_FILE, null);
|
||||
if (!saved || typeof saved !== "object" || Array.isArray(saved)) return {};
|
||||
return Object.fromEntries(Object.entries(saved).filter(([, kind]) => PR_HOST_KINDS.has(kind)));
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this.
|
||||
export function savePrHost(host, kind) {
|
||||
ensureDir(path.dirname(PR_HOSTS_FILE));
|
||||
withStateLock(
|
||||
path.dirname(PR_HOSTS_FILE),
|
||||
() => writeJsonAtomic(PR_HOSTS_FILE, { ...readPrHosts(), [host]: kind }),
|
||||
PR_HOSTS_LOCK
|
||||
);
|
||||
}
|
||||
|
||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
||||
|
||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Changelog on the Web Console
|
||||
|
||||
Workflow notes for `changelog`, part of the web console contract (`console.md`).
|
||||
|
||||
Open with `--workflow changelog` (launched from the dashboard: resume the
|
||||
session instead). Post `activity` while you read the history and the diff. One
|
||||
card per step, each asked only when the step needs it:
|
||||
|
||||
| Step | On the page |
|
||||
| --- | --- |
|
||||
| Version | A `choice`, "Which version?": the computed version (recommended) with its reason in `body` (main is at X, the branch has Y), "Keep Y" when the branch's own entry could stay, and "Another version" (`allowOther`). A `choice` does not check what is typed, so check it yourself: anything that is not `X.Y.Z` gets the card again with a `thread` reply saying so. Left out when the entry is already right. |
|
||||
| Entries | A `list` titled "Entries to add": one row per suggested entry, `title` the entry line itself (the part they can edit) and `body` its section (`Added`, `Fixed`…). Removable and reorderable; `reply` names renames, additions and removals. A row they add has no section: ask, or file it where it reads best and say so. |
|
||||
| The result | The final entry as a doc (`id: "entry"`, marked `"saved": "CHANGELOG.md"` once written) plus a `review` card with verdicts `write` ("Write it"), `change` and `stop`. |
|
||||
| package.json | A `confirm` with the `old → new` in `consequences`. |
|
||||
| Commit this now? | A `confirm`, "Commit this now?". |
|
||||
|
||||
A yes to "Commit this now?" ends no session (no `finish`, no `stop`): settle
|
||||
the card, resume as `git` (`open --resume <sid> --no-open --workflow git`),
|
||||
then read `~/.agents/skills/plan2code-git/SKILL.md` with your file-read tool
|
||||
and start with its commit flow, in this same session, as a dashboard launch
|
||||
does (`console-launches.md`); the resume clears Changelog's page for it.
|
||||
Finish, on a no: `"dashboard": true` and the version and entries in `body`,
|
||||
with no `command`. A stop's finish is the bare `/plan2code-changelog`.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Documentation on the Web Console
|
||||
|
||||
Workflow notes for `document`, part of the web console contract (`console.md`).
|
||||
|
||||
The questions are few — which draft, a clarification, the sign-off — but the
|
||||
docs are the point: post each phase file as a doc as it is written, so a
|
||||
browser-only person watches the spec take shape. Each one mirrors a file on
|
||||
disk, so carry its `saved` path, and post it as a `file` block
|
||||
(`{ "id": "body", "file": "specs/<feature>/phase-2.md" }`) rather than pasting
|
||||
the text you just wrote. Pass `--spec specs/<feature>` once the folder is known;
|
||||
it is what the resume command needs. Finish commands follow the pipeline: the
|
||||
sign-off's is `/plan2code-3-implement specs/<feature>/overview.md`.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Finalize on the Web Console
|
||||
|
||||
Workflow notes for `finalize`, part of the web console contract (`console.md`).
|
||||
|
||||
Finalize is a run of reports and gates, and each maps onto a kind you already
|
||||
know:
|
||||
|
||||
| Step | On the page |
|
||||
| --- | --- |
|
||||
| 1, Task Completion Audit | The audit table as a doc (`id: "audit"`). If incomplete or blocked tasks exist (`totals.incomplete + totals.blocked > 0`), a `choice` with the three options — return to implementation, mark partially complete, abandon — with the counts against the thresholds in `body`. |
|
||||
| 2, Implementation Verification | The verification results as a doc. Nothing to ask unless an issue needs their decision. |
|
||||
| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`, as a `file` block on `overview.md`) so the page reader sees it land. |
|
||||
| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. |
|
||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
|
||||
|
||||
Post `activity` as each step starts, before its doc or question lands — reading
|
||||
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
|
||||
implementation — the same way Review does. A step with no card of its own
|
||||
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
|
||||
Finalize".
|
||||
|
||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||
Stopping mid-finalize loses nothing — the specs are untouched until Step 3's
|
||||
summary write — so a stop's finish just says where it paused and uses
|
||||
`"command": "/plan2code-4-finalize specs/<feature>/overview.md"`. On success
|
||||
the finish's `command` is the suggested commit when Step 4 doc updates landed
|
||||
(with `"where": "When you are happy with it, commit it from your terminal:"`), otherwise leave `command` out.
|
||||
When the finish prints that suggested commit, it also carries `"commit": true`,
|
||||
so the finished screen offers **Commit it now** (`console-finish.md`). The
|
||||
completion summary is printed to a terminal the browser user is not watching,
|
||||
so put it in `finish.body`.
|
||||
@@ -0,0 +1,119 @@
|
||||
# Git on the Web Console
|
||||
|
||||
Workflow notes for `git`, part of the web console contract (`console.md`).
|
||||
|
||||
Open with `--workflow git` (launched from the dashboard, or by a **Commit it
|
||||
now** or Changelog hand-off: resume the session instead). Like the dashboard,
|
||||
the main column is drawn by the page itself: the git board, from `state.git`,
|
||||
which `open` and every `reread` snapshot through `git-repo.mjs`. **You never
|
||||
post `git`** (exit 3: `state.git` is the console's own). Your cards sit above
|
||||
the board in the usual card slot.
|
||||
|
||||
**A click** arrives as one session action, one per send, and the board locks
|
||||
until your next post lands:
|
||||
|
||||
```jsonc
|
||||
{ "type": "submit",
|
||||
"actions": [{ "i": "__git", "type": "git", "op": "create",
|
||||
"name": "feature/export-csv", "from": "origin/main",
|
||||
"then": "commit", "files": ["src/a.js"], "ignore": ["dist/"] }],
|
||||
"reply": "Create feature/export-csv from origin/main. ..." }
|
||||
```
|
||||
|
||||
| `op` | Fields |
|
||||
| --- | --- |
|
||||
| `refresh`, `pull`, `push`, `abort`, `continue`, `done` | none (a `refresh` with no remote is "look again": `plan refresh` gives no commands, so just post `reread`) |
|
||||
| `publish` | `remote?` (left out when there are several: `plan publish` asks which) |
|
||||
| `switch`, `delete` | `branch` (a remote-only row is `<remote>/<name>`) |
|
||||
| `create` | `name`, `from`; `then: "commit"` with `files` (and `ignore`, when any) when it came from the commit panel's branch offer |
|
||||
| `cleanup` | `branches[]` |
|
||||
| `commit` | `files[]` (paths and untracked folders), `ignore[]` (folders to add to `.gitignore`) |
|
||||
| `pr-host` | `host`, `kind` (already saved by the page's `POST /pr-host`) |
|
||||
|
||||
`reply` is the plain instruction the terminal would get, so it reads like any
|
||||
answer. `__git` names no question, like `__stop`.
|
||||
|
||||
**After an action**, in ONE post (with `--wait`):
|
||||
|
||||
```jsonc
|
||||
{ "reread": true,
|
||||
"items": [{ "id": "git-result", "kind": "notice", "status": "open",
|
||||
"title": "Pushed 2 commits to origin/feature/x",
|
||||
"body": "a1b2c3d, e4f5a6b. [Open pull request](https://github.com/...)" }],
|
||||
"board": { "describe": "export-csv-button" } }
|
||||
```
|
||||
|
||||
- `reread` is `true`, or `{ "refreshFailed": true }` after a Refresh that
|
||||
failed (the board then says so beside the last refreshed time and keeps the
|
||||
last data). It goes only with the `git` workflow; anywhere else, or in any
|
||||
other shape, it is exit `3`. The console takes the snapshot inside the same
|
||||
locked write as your cards, so the result line and the fresh board land
|
||||
together.
|
||||
- `git-result` is a `notice` replaced every action (same id). The board shows
|
||||
it under its header, not in the card slot: what happened, with short hashes
|
||||
and, after a push or publish, the `pr-url` link. On a failure it quotes
|
||||
git's stderr verbatim with `classify-error`'s `next`.
|
||||
- `board.describe` is yours: a short kebab-case description of the changes
|
||||
still on the tree, which the Create prompt pre-fills. Post it with the
|
||||
reread whenever changes remain; leave it out otherwise.
|
||||
- The board is the person's to click whenever you wait, so `wait` hands the
|
||||
turn back by itself; no `agent` status is needed.
|
||||
|
||||
**Cards per `plan`.** `git.mjs plan <op>` decides whether to ask:
|
||||
|
||||
| `plan` says | On the page |
|
||||
| --- | --- |
|
||||
| `confirm` | A `confirm` card with its `title`, `body`, `danger` and `consequences` verbatim (the consequences end with the exact command). Where the plan names files, add them as `files: [{ "path", "state" }]`. |
|
||||
| `card.kind: "switch"` | A `choice`, "Bring your changes?": exactly the `options` given, labelled **Switch and bring them** (`bring`), **Commit first** (`commit-first`), **Cancel** (`cancel`); the files in `body`, and `reason` when git would refuse (then there is no `bring`). `allowOther: false`. |
|
||||
| `card.kind: "dirty"` | The same `choice` for a pull that needs a clean tree: **Commit first** / **Cancel**, `reason` in `body`. |
|
||||
| `card.kind: "remote"` | A `choice`, "Publish to which remote?": one option per remote, `preset` recommended. Then `plan publish --remote <it>` and its `confirm`. |
|
||||
| `ask: false` | No card: run it on the click. |
|
||||
| exit 4 or 5 | No card and nothing run: the `message` and `next` as the `git-result` notice. |
|
||||
|
||||
An `auth` failure gets a `notice` card saying the tool never handles logins,
|
||||
with `next`. The commit flow's own cards (message, groups, `git init`,
|
||||
`.gitignore`) are the rows below.
|
||||
|
||||
| Commit step | On the page |
|
||||
| --- | --- |
|
||||
| One commit | A `text` card whose `placeholder` is the drafted subject and whose `pattern` caps it at 100 characters, then a `confirm` "Commit this?" with the files in `consequences` and, as `files: [{ "path": "src/a.js", "state": "modified" }]` (states: modified, new, deleted, renamed), a collapsed **Show the N files** table on the card. With the subject given as the argument there is no card. |
|
||||
| A split | The groups as a doc (`id: "commits"`: each group's subject and files, and any file that mixes concerns) plus a `review` card with verdicts `approve`, `change` and `single` ("One commit instead"). Asked even when the subject came as the argument. |
|
||||
| Push | Not asked after a commit on the board: the board lights Push. `commit and push` (or a Push click) asks `plan push` / `plan publish`'s `confirm`. |
|
||||
| `git init` | A `confirm` naming the folder and its first branch (`init-check`'s `branch`, `danger: false`), its `consequences` `init-check`'s `commands`. Run those, not a bare `git init`. |
|
||||
| `.gitignore` | The proposed file, or the lines a `commit`'s `ignore[]` adds, as a doc plus a `review` card. |
|
||||
|
||||
Risky files (`sensitive`, `large`) are named in the card's `body`. On the
|
||||
board there is no branch-offer card: the commit panel's **You're on main**
|
||||
line asks it, and the answer arrives as `create` with `then: "commit"`.
|
||||
|
||||
**Conflict help.** A pull, rebase or merge stopped on conflicts asks first, a
|
||||
`choice` "Resolve them for me?": **Yes**, **I'll fix it**, **Abort pull**.
|
||||
On yes, every stop is a doc (`id: "conflict"`, replaced per stop, its version moving by itself: step N of M,
|
||||
the commit being replayed, each file with a one-line reason, then a per-file
|
||||
diff) plus a `review` card, fresh id per stop, `"nothingYet": false` (the resolution is already on disk), with the verdicts `continue`
|
||||
("Continue"), `change` ("Change it") and `abort` ("Abort pull", `danger`).
|
||||
Only **Continue** runs `plan continue`'s commands; **Abort pull** runs
|
||||
`plan abort` and the board is back on the exact original HEAD. A file you
|
||||
cannot resolve with confidence is named and left with its markers; **I'll fix
|
||||
it** leaves the markers too. The board's banner always offers Continue: a
|
||||
`continue` click is the person saying the files are fixed, so run `plan
|
||||
continue`; when it refuses (exit 5, markers left), post a `reread` with its
|
||||
`message` as the `git-result` notice, which also refreshes the banner's file
|
||||
list. Nothing is pushed during conflict help. At the end, a `notice`
|
||||
summary (commits replayed, each resolved file with its reason, "N commits
|
||||
ready to push").
|
||||
|
||||
**Meter events** (`console-meter.md`). Git scores on launch.
|
||||
Post `run: { "event": "git-commits", "id": "<first short hash>", "commits": N }`
|
||||
after each commit step (N commits made), and `run: { "event": "git-conflict",
|
||||
"id": "conflict-<n>" }` once per conflict help, resolved or aborted.
|
||||
|
||||
**Finishing** (`console-finish.md`). Done (`op: "done"`) with something done
|
||||
this session: a `finish` with a headline, the commits with hashes, pushes and
|
||||
branches created or deleted in `body`, no `command`, and `"dashboard": true`;
|
||||
keep waiting for the press. Done with nothing done: no finish screen — resume
|
||||
as `dashboard` at once (`open --resume <sid> --no-open --workflow dashboard`),
|
||||
read the dashboard skill (`~/.agents/skills/plan2code/SKILL.md`), post its
|
||||
`menu` with `--wait` and carry on from its "Coming back from another skill". A
|
||||
stop's finish is a pause, headline "Paused …", the bare `/plan2code-git`,
|
||||
then `stop`.
|
||||
@@ -0,0 +1,11 @@
|
||||
# Handoff on the Web Console
|
||||
|
||||
Workflow notes for `handoff`, part of the web console contract (`console.md`).
|
||||
|
||||
One gate: the next-task confirmation, then the document itself as a doc —
|
||||
that is what the person is there to download. Give it no `saved` and paste it
|
||||
as `md`: the handoff file often sits outside the project (the OS temp folder),
|
||||
where a `file` block is refused, and the download is the point. The finish carries no
|
||||
`command`: the doc download is the point, and the dashboard button and the
|
||||
"All done" line cover what comes next. Unless it is a pause, the finish carries
|
||||
`"dashboard": true` and you keep waiting for the press (`console-finish.md`).
|
||||
@@ -0,0 +1,155 @@
|
||||
# Implement on the Web Console
|
||||
|
||||
Workflow notes for `implement` and `implement-review`, part of the web console
|
||||
contract (`console.md`). Read `building.md` first.
|
||||
|
||||
## The first post of a phase
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "stage": "Phase 3: API layer", "cleared": 0, "total": 9 },
|
||||
"docs": [
|
||||
{ "id": "phase", "title": "Phase 3 tasks", "blocks": [
|
||||
{ "id": "tasks", "file": "specs/<feature>/phase-3.md", "select": "tasks" }
|
||||
]},
|
||||
{ "id": "phasefile", "title": "phase-3.md", "blocks": [
|
||||
{ "id": "body", "file": "specs/<feature>/phase-3.md" }
|
||||
]}
|
||||
],
|
||||
"agent": { "status": "working", "activity": "Checking the prerequisites", "quietMinutes": 15 }
|
||||
}
|
||||
```
|
||||
|
||||
`phase` is the task list, `phasefile` the whole `phase-X.md` as its own tab —
|
||||
the person can read the prerequisites and task specs while you build. Both are
|
||||
read from disk by the console: never paste the file. It renders as markdown, so
|
||||
the file's checkboxes show as ticks exactly as they stand on disk.
|
||||
|
||||
A later phase in the same session posts the same two docs with the new phase's
|
||||
title and file: their content changed, so their versions move up by themselves
|
||||
(a doc's version never goes back, and you no longer have to track it). Leave
|
||||
`version` out.
|
||||
|
||||
## After every task
|
||||
|
||||
In the same breath as writing the task's checkbox to disk:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "cleared": 4 },
|
||||
"docs": [ { "id": "phase", "refresh": true }, { "id": "phasefile", "refresh": true } ],
|
||||
"agent": { "activity": "Task 5 of 9: the rate limiter" }
|
||||
}
|
||||
```
|
||||
|
||||
`refresh` re-reads the file the checkbox write just changed, so both tabs tick
|
||||
in place; the Phase Completion Summary lands in `phasefile` the same way at the
|
||||
end. Then the `chat` check (`building.md` → Quick questions between tasks).
|
||||
|
||||
---
|
||||
|
||||
## Sign-off
|
||||
|
||||
Put the Completion Report on the page as a doc, then ask for approval as a
|
||||
`review` item pointing at it. The review offer rides on this card, as a verdict
|
||||
ahead of the approval buttons — not on the finish after it, where it could
|
||||
only ever be offered once nothing could come of it:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"docs": [{ "id": "report", "title": "Completion report", "blocks": [
|
||||
{ "id": "summary", "state": "settled", "md": "## Summary\n\n..." },
|
||||
{ "id": "files", "state": "settled", "md": "## Files\n\n..." },
|
||||
{ "id": "verify", "state": "settled", "md": "## How to check it\n\n..." }
|
||||
]}],
|
||||
"items": [{
|
||||
"id": "signoff", "kind": "review", "title": "Approve this phase", "doc": "report",
|
||||
"body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, or say what to change.",
|
||||
"verdicts": [
|
||||
{ "id": "review", "label": "Review the code first" },
|
||||
{ "id": "approve", "label": "Approve this phase" },
|
||||
{ "id": "changes", "label": "I want changes" }
|
||||
],
|
||||
"token": { "approve": "approved", "changes": "needs changes" },
|
||||
"nothingYet": "Nothing is marked complete until you approve.",
|
||||
"gate": { "id": "signoff", "authoritative": true }
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
Posted with `--wait`. `reply` carries `Approve this phase: approved`, which is
|
||||
the terminal's `approved`. If the note that came with an approval asks for a
|
||||
change, treat it as "describe any issues": do the change first and ask again.
|
||||
`changes` means exactly what it says: address it, update the report, and reopen
|
||||
the item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||
person asking for the code review before they approve anything — read
|
||||
`building-review.md`.
|
||||
|
||||
`gate` marks the one approval that counts. The server refuses a second open
|
||||
authoritative gate, which is what keeps a composed workflow from asking for
|
||||
sign-off twice. A later phase in the same session asks with a new id
|
||||
(`signoff-phase-2`, its title naming the phase, "Approve Phase 2", so the rail tells
|
||||
the two apart), since the last phase's approved card is a record: the same
|
||||
id posted again would only edit that record.
|
||||
|
||||
---
|
||||
|
||||
## After approval: the finish
|
||||
|
||||
Do everything the workflow does on approval (the checkboxes, the summary, the
|
||||
upcoming phases, the commit command) and print it in the terminal as usual.
|
||||
Then post the finish, wait for the dashboard button as `console-finish.md`
|
||||
says, and `stop`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"settle": true,
|
||||
"run": { "event": "implement-phase", "id": "phase-3", "tasks": 9 },
|
||||
"finish": {
|
||||
"headline": "Phase 3 is done",
|
||||
"body": "9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -A && git commit -m \"...\" -m \"AI Assisted\"\n```",
|
||||
"command": "/plan2code-3-implement specs/lunch-vote/overview.md",
|
||||
"doc": "report",
|
||||
"commit": true,
|
||||
"dashboard": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`"commit": true` is there because the body prints a git command: the finished
|
||||
screen gets a **Commit it now** button, and its `__commit` press is handled as
|
||||
`console-finish.md` says (resume as `git` and open its commit flow, same
|
||||
session). Leave it out when the body prints no commit.
|
||||
|
||||
`finish.command` is the next pipeline step, the same one the terminal names:
|
||||
the next `/plan2code-3-implement specs/<feature>/overview.md`, or
|
||||
`/plan2code-4-finalize specs/<feature>/overview.md` after the last phase. An `implement` finish never carries `review`: the offer was on the
|
||||
sign-off card, and approving past it was the answer. `implement-review` ends
|
||||
the same way; that phase was reviewed already.
|
||||
|
||||
`run` gives the approved phase its final score on the session meter
|
||||
(`console-meter.md`), in the same post that records the approval; it takes over
|
||||
what the build already counted from `cleared`, never adds to it:
|
||||
`implement-phase` for Implement, `implement-review-phase` for Implement +
|
||||
Review, id `phase-N`, and `tasks`: how many of the phase's tasks were
|
||||
completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a
|
||||
twelve-task phase weighs four times a three-task one; leave `tasks` out and
|
||||
every phase weighs the same. A review run on the page after a build reports its
|
||||
own (`building-review.md`).
|
||||
|
||||
---
|
||||
|
||||
## Implement + Review (`implement-review`)
|
||||
|
||||
The same build, then Stage 2 publishes the findings exactly as
|
||||
`building-review.md` → The findings (the `review` doc and the `fixes` item).
|
||||
Stage 3 fixes, with no "Check the fixes" item: Stage 4 is the only gate. The
|
||||
post that starts Stage 2's review carries `"run": { "event": "review", "id":
|
||||
"review" }`: in this workflow it scores the review stage's 1 point on the meter
|
||||
as it begins, and the phase's final `run` leaves that point out. Stage 4 is the
|
||||
sign-off above **without the review verdict** — the phase was already reviewed
|
||||
— with the review results and unresolved findings in the report doc, header
|
||||
"Reviewed and ready for sign-off" in the item's `body`. The finish never
|
||||
carries `review`, and its post carries `"run": { "event":
|
||||
"implement-review-phase", "id": "phase-N", "tasks": N }` with the count of
|
||||
completed tasks.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Init and Init Update on the Web Console
|
||||
|
||||
Workflow notes for `init` and `init-update`, part of the web console contract
|
||||
(`console.md`).
|
||||
|
||||
Setup conversations: every confirmation and Q&A item goes through the page.
|
||||
For `init` and `init-update` the finished AGENTS.md also lands as a doc so a
|
||||
browser-only person can read what was written — marked `"saved": "AGENTS.md"`,
|
||||
since the file itself is already on disk (or as a `file` block:
|
||||
`{ "id": "body", "file": "AGENTS.md" }`, instead of pasting it). A completed run
|
||||
finishes with **no** `command`: the page shows the "All done" line. Nothing is
|
||||
on disk to resume mid-run, so a stop's finish command is the bare
|
||||
`/plan2code-init` or `/plan2code-init-update` — the skill starts over
|
||||
either way.
|
||||
@@ -0,0 +1,76 @@
|
||||
# Pathfinder on the Web Console
|
||||
|
||||
Workflow notes for `pathfinder`, part of the web console contract (`console.md`).
|
||||
|
||||
- Every probe, recap and menu goes through the page.
|
||||
- Post `"stopWarning"` while no map exists (Steps 0 to 4) and `"stopWarning": ""`
|
||||
once it does, and `"specDir": "specs/<idea>"` when the folder is created
|
||||
(`console-stop.md` → Saying what stopping would cost).
|
||||
- The fresh-idea card carries `"templates": "idea"` (`console.md` → The kinds).
|
||||
- A doc that is a file exactly as written (the map once it is on disk, a
|
||||
brief) goes up as a `file` block (`{ "id": "body", "file":
|
||||
"specs/<idea>/pathfinder/map.md" }`) rather than pasted. Keep `md` blocks
|
||||
where a block's `assumed` / `draft` state carries meaning.
|
||||
- Chart Step 8's research subagents must all report back before the
|
||||
finish (`console-finish.md` → Nothing of yours may still be running); the
|
||||
finish body then names what each one found.
|
||||
- Report every research subagent as a helper, whatever the Subagents switch
|
||||
says (`console-subagents.md` → Reporting helpers).
|
||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||
sees the Trail Footer, and without this their last screen promises a question
|
||||
that is never coming.
|
||||
- Post `run` `pathfinder-chart` (id `map`) when a new map is first written,
|
||||
and `pathfinder-research` (id = the question's file slug; on `github`, `q<issue-number>`) as each research
|
||||
subagent reports back, or when you resolve a `research` question yourself
|
||||
(`console-meter.md`). Other questions score through their answers, so there is
|
||||
nothing to post for them.
|
||||
- The scope probe is **Leave for later**: "Which of these features are we
|
||||
leaving out this time?" as a `multi` with a recommended preset. Every option
|
||||
names a feature, and its `detail` ends "(Leaving this out = …)". Never phrase
|
||||
an option as a rule to keep.
|
||||
|
||||
## Briefs
|
||||
|
||||
The page shows a **Write a brief** button when `workflow` is `pathfinder`,
|
||||
because that is the workflow with a brief playbook. The person picks a range and
|
||||
presses it; nothing else about the session changes.
|
||||
|
||||
It arrives through the wait loop like any other send:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"type": "submit",
|
||||
"actions": [{ "i": "__brief", "type": "brief", "range": "since 2026-09-15" }],
|
||||
"reply": "Write a brief covering everything since 2026-09-15."
|
||||
}
|
||||
```
|
||||
|
||||
`range` is one of `today`, `this week`, `since <YYYY-MM-DD>` or `full`, which is
|
||||
the range grammar the brief playbook already parses. `reply` says the same thing
|
||||
in words, so a workflow that only reads `reply` needs no new code path. The
|
||||
`__brief` id is not an item and matches nothing; it marks the action as being
|
||||
about the session rather than about a question.
|
||||
|
||||
Run your normal brief procedure, write the file where it belongs, and then put
|
||||
the same report on the page as a doc, as a `file` block on the file you wrote:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"docs": [{
|
||||
"id": "brief",
|
||||
"title": "Brief",
|
||||
"note": "Covers this week",
|
||||
"blocks": [{ "id": "body", "file": "specs/<idea>/pathfinder/briefs/<the brief>.md" }]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
One block holding the whole report is right here: a brief is read start to
|
||||
finish, not block by block, and it gets Save as HTML, Print and Download buttons
|
||||
that work on the document as a whole. Save as HTML appears only on the doc with
|
||||
the id `brief`. Reuse the id `brief` so a second brief replaces the first
|
||||
rather than growing a row of tabs; its version moves up by itself.
|
||||
|
||||
Say in chat where the file went, as you always would. The page is a second copy
|
||||
for reading and printing, never the record.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Planning on the Web Console
|
||||
|
||||
Workflow notes for `plan`, part of the web console contract (`console.md`).
|
||||
|
||||
- Open with `--workflow plan`, first thing. Every question and sign-off gate
|
||||
goes through the page, phase breakdowns as an editable `list`.
|
||||
- The fresh-idea card carries `"templates": "idea"` (`console.md` → The kinds).
|
||||
- Planning has no mid-session save before the Large checkpoint or Phase 7, so for
|
||||
a stop before then say plainly in `finish.body` that nothing was kept, and use
|
||||
`"command": "/plan2code-1-plan"`. After the checkpoint, post
|
||||
`"stopWarning": ""` (`console-stop.md`).
|
||||
- At every session end, post `finish` BEFORE `stop`; on completion that is
|
||||
`"command": "/plan2code-2-document"`, and at the Large checkpoint it is
|
||||
`/plan2code-1-plan`. The closing message is printed to a terminal the
|
||||
browser user is not watching.
|
||||
- The Large checkpoint finish is a pause: a headline starting "Paused", no
|
||||
`dashboard`, and `stop` at once.
|
||||
@@ -0,0 +1,90 @@
|
||||
# Quick Task on the Web Console
|
||||
|
||||
Workflow notes for `quick-task`, part of the web console contract
|
||||
(`console.md`). Read `building.md` first.
|
||||
|
||||
## Quick task (`quick-task`)
|
||||
|
||||
- Open with the first clarifying question. Clarifying questions go out as
|
||||
`text` or `choice`, at most three at a time. The first, asking what to build,
|
||||
carries `"templates": "idea"` (`console.md` → The kinds).
|
||||
- Post `"stopWarning": "A quick task saves nothing until it is built, so stopping now loses what we have worked out."`
|
||||
at the start, and `"stopWarning": ""` once the build is under way.
|
||||
- **Scope check:** a `choice`, "Too big for a quick task?", options
|
||||
`1` Continue (lightweight format) and `2` Escalate to a full plan, with the
|
||||
measured counts against the thresholds in `body`.
|
||||
- **Feature name** (escalating): `text` with
|
||||
`"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"` and a kebab-case placeholder.
|
||||
- **The plan:** a `plan` doc titled "Plan", one block per section, with the
|
||||
Steps written as a checklist so the build can tick them in place, and a
|
||||
`review` item "Build this plan?" (`"doc": "plan"`) with verdicts `yes`
|
||||
("Build it"), `modify` ("Change the plan"), `escalate` ("Plan it properly
|
||||
instead") and `abort` ("Stop here", `"danger": true`):
|
||||
|
||||
```jsonc
|
||||
{ "id": "plan", "title": "Plan", "blocks": [
|
||||
{ "id": "summary", "state": "settled", "md": "## Summary\n\n..." },
|
||||
{ "id": "files", "state": "settled", "md": "## Files to change\n\n- `src/a.ts` - ..." },
|
||||
{ "id": "steps", "state": "settled", "md": "## Steps\n\n- [ ] **1.** Step one\n- [ ] **2.** Step two\n- [ ] **3.** Step three\n- [ ] **4.** Step four" },
|
||||
{ "id": "verify", "state": "settled", "md": "## Verify\n\n- [ ] ..." }
|
||||
]}
|
||||
```
|
||||
|
||||
A `modify` reposts the changed blocks, Steps still a checklist; the version
|
||||
moves up by itself.
|
||||
- **Building** after `yes`: the Plan tab is the build's live task list, the
|
||||
way an Implement phase has its tasks tab. There is no separate progress tab.
|
||||
Settle the verdict (`"settle": true`) in the post that starts the build; the
|
||||
plan's steps are the tasks and `total` is their number:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"stopWarning": "",
|
||||
"settle": true,
|
||||
"headline": { "stage": "Building", "cleared": 0, "total": 4 },
|
||||
"agent": { "status": "working", "activity": "Task 1 of 4: step one", "quietMinutes": 10 }
|
||||
}
|
||||
```
|
||||
|
||||
Then post after every step, as `building.md` → While you build says, in the
|
||||
same breath as finishing it: repost the plan's `steps` block alone (blocks
|
||||
merge by id, so Summary, Files and Verify stay as they are) with that step
|
||||
ticked; raise `headline.cleared`; set `agent.activity` to the next step
|
||||
("Task 2 of 4: step two"). The plan lives only on the page, so this block is
|
||||
`md`, not `file`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"headline": { "cleared": 1 },
|
||||
"docs": [{ "id": "plan", "blocks": [
|
||||
{ "id": "steps", "state": "settled", "md": "## Steps\n\n- [x] **1.** Step one\n- [ ] **2.** Step two\n- [ ] **3.** Step three\n- [ ] **4.** Step four" }
|
||||
]}],
|
||||
"agent": { "activity": "Task 2 of 4: step two" }
|
||||
}
|
||||
```
|
||||
|
||||
A step that cannot be done is `- [!]` with the reason after it, and is not
|
||||
counted in `cleared`. A step added mid-build goes into the list and raises
|
||||
`headline.total` in the same post. Tick each step the moment it is done,
|
||||
never in a batch at the end: the person is watching the Plan tab fill in.
|
||||
Check for a Quick question between steps, and do not call `wait` until the
|
||||
build is done. Tick the Verify block's boxes too as the checks pass, in the
|
||||
post that reports them.
|
||||
- **The finish after the build:** `command` is the commit command, filled in,
|
||||
in the project's commit format (AGENTS.md), with
|
||||
`"where": "When you are happy with it, commit it from your terminal:"`, and
|
||||
`review` on offer — the **Review it now** button, since a quick task has no
|
||||
sign-off card to put it on — `"commit": true` (the **Commit it now** button;
|
||||
`console-finish.md`) and `"dashboard": true`, so the finished screen
|
||||
also offers **Back to the dashboard**. Review and dashboard are required: a finish without
|
||||
`dashboard` leaves the person on a dead end. Keep waiting for whichever
|
||||
button is pressed, and everything after that is `building-review.md`.
|
||||
- **Escalated / aborted:** settle the verdict the same way in the finish post —
|
||||
finish with `"command": "/plan2code-1-plan"` and the
|
||||
PLAN-DRAFT's path in `body`, no review; or `"command": "/plan2code-quick-task"`.
|
||||
Both set `"dashboard": true`: an abort of a quick task saves nothing to
|
||||
resume, so it is not a pause.
|
||||
|
||||
## Stop requests during a build
|
||||
|
||||
See `building.md` → Stop requests during a build.
|
||||
@@ -0,0 +1,34 @@
|
||||
# Review on the Web Console
|
||||
|
||||
Workflow notes for `review`, part of the web console contract (`console.md`).
|
||||
A review run from a build's review button stays in the build's session, under
|
||||
its workflow: `building-review.md` governs it instead.
|
||||
|
||||
Scope questions up front — run standalone with nothing named, the first is
|
||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
||||
uncommitted changes, specs, files you name; each option with its size),
|
||||
never an assumed target; a build's review skips it (`building-review.md`). Then the
|
||||
findings report as a doc (`id: "report"`), then the pick-what-gets-fixed menu
|
||||
as a `multi` or `choice` keyed by finding id, carrying `"doc": "report"` so the
|
||||
card links straight to the findings. Settle that item (`"settle": true`) in the
|
||||
same post that takes the picks up: left open it stays on the page as a question
|
||||
still owed, next to whatever you ask next. Post `activity` while you read — a
|
||||
real review is long stretches of you working, and the page should say so rather
|
||||
than hint at questions.
|
||||
|
||||
When the session was launched from the dashboard, resume the session you were
|
||||
handed (`open --resume <sid> --no-open --workflow review`), never a fresh
|
||||
`open`.
|
||||
|
||||
Review Mode's closing gate ("Reply approved to commit, or request changes")
|
||||
is a `review` item titled "Check the fixes", `doc: "report"`, `"nothingYet":
|
||||
false` (the fixes are already on disk), verdicts `approve` and `changes`.
|
||||
|
||||
On completion the finish's `command` is the suggested commit when fixes
|
||||
landed — filled in, in the AGENTS.md format, with
|
||||
`"where": "When you are happy with it, commit it from your terminal:"` —
|
||||
otherwise leave `command` out; with one, `"commit": true` puts **Commit it
|
||||
now** beside it. The completion finish carries `"dashboard": true`
|
||||
so the finished screen offers **Back to the dashboard**; keep waiting for the
|
||||
press. A stop mid-review loses nothing on disk, so its finish is the bare
|
||||
`/plan2code-review` (a pause, so no dashboard button).
|
||||
@@ -0,0 +1,18 @@
|
||||
# Revision on the Web Console
|
||||
|
||||
Workflow notes for `revise-plan`, part of the web console contract (`console.md`).
|
||||
|
||||
Revision is a short run of gates, and each maps onto a kind you already know:
|
||||
|
||||
| Step | On the page |
|
||||
| --- | --- |
|
||||
| 1, Change Analysis | A `recap` item, "Is this the change?", with the affected-areas table in `summary`. |
|
||||
| 2, Impact Assessment | The Revision Impact Summary as a doc (`id: "impact"`), and a `review` item "Approve the spec changes" pointing at it: verdicts `approve` ("Approve these spec changes"), `refine` ("Refine the plan") and `abort` ("Abort", `"danger": true`), `nothingYet`: "No spec file changes until you approve." |
|
||||
| 3 to 5 | Nothing to ask. Post `activity` while you edit, then the Revision Complete summary as a doc. |
|
||||
| 6, Cleanup | A `confirm` per rename or removal, the paths in `consequences`. |
|
||||
|
||||
Revision's own rule holds on the page too: **no option, verdict or label ever
|
||||
offers to execute or implement.** Pass `--spec specs/<feature>` to `open`, or
|
||||
post `specDir` once you know it. The finish command is
|
||||
`/plan2code-3-implement specs/<feature>/overview.md`; an abort's is
|
||||
`/plan2code-1b-revise-plan specs/<feature>/overview.md`.
|
||||
@@ -3,7 +3,7 @@
|
||||
// A port of the launcher's picker (src/launcher/plan2code.js). The launcher
|
||||
// is self-contained CommonJS copied alone to ~/.plan2code/bin/, and this
|
||||
// console is ESM bundled into every skill, so the two cannot share a module:
|
||||
// this is a copy, and a drift test in scripts/test-web-console.mjs fails the
|
||||
// this is a copy, and a drift test in scripts/test-web-console-logic.mjs fails the
|
||||
// moment the launcher's picker changes without it. The prompt is a parameter
|
||||
// here rather than the launcher's constant.
|
||||
//
|
||||
|
||||
@@ -40,6 +40,18 @@ export function recordedAnswer(item) {
|
||||
return { ...(s || {}), ...(a || {}) };
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the agent wrote in the item's thread after the person's last send
|
||||
* and has not settled it: the question is being asked again, so what they sent
|
||||
* belongs back on the form rather than gone.
|
||||
*/
|
||||
export function agentRepliedAfterSend(item) {
|
||||
const s = item && item.submitted;
|
||||
if (!s || typeof s !== "object" || (item.answer && typeof item.answer === "object")) return false;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
return thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
}
|
||||
|
||||
/**
|
||||
* A send the person made that the agent never settled, still sitting on an
|
||||
* OPEN question.
|
||||
@@ -103,10 +115,19 @@ export function threadText(m) {
|
||||
|
||||
/* -------------------------------------------------------------- labels */
|
||||
|
||||
// A key worth showing: one or two letters or digits (A, 2) a person can say
|
||||
// back in the terminal. A word key (commit-first, yes) is an id for the agent,
|
||||
// and as a chip beside its own label it is noise.
|
||||
export function showKey(k, text) {
|
||||
if (k == null) return false;
|
||||
const key = String(k);
|
||||
return /^[A-Za-z0-9]{1,2}$/.test(key) && key.toLowerCase() !== String(text || "").trim().toLowerCase();
|
||||
}
|
||||
|
||||
export function optionLabel(item, k) {
|
||||
const o = ((item && item.options) || []).find((x) => x.k === k);
|
||||
if (!o) return String(k);
|
||||
return o.k ? `${o.k} · ${o.text}` : o.text;
|
||||
return showKey(o.k, o.text) ? `${o.k} · ${o.text}` : o.text;
|
||||
}
|
||||
|
||||
export function verdictLabel(item, id) {
|
||||
@@ -247,7 +268,7 @@ export const WORKFLOW_LABEL = {
|
||||
"quick-task": "Quick task",
|
||||
finalize: "Wrapping up",
|
||||
handoff: "Handoff",
|
||||
"git-commit": "Git commit",
|
||||
git: "Git",
|
||||
changelog: "Changelog",
|
||||
};
|
||||
|
||||
@@ -273,7 +294,7 @@ export const CONSOLE_WORKFLOWS = [
|
||||
"/plan2code-review",
|
||||
"/plan2code-4-finalize",
|
||||
"/plan2code-handoff",
|
||||
"/plan2code-git-commit",
|
||||
"/plan2code-git",
|
||||
"/plan2code-changelog",
|
||||
];
|
||||
|
||||
@@ -383,14 +404,16 @@ const HOME_TITLES = {
|
||||
* adrift: then it comes back, and a second press is safe because the server
|
||||
* refuses a duplicate while the first is uncollected.
|
||||
*/
|
||||
export function homeButtonState({ workflow, finished = false, stopping = false, homeward = false, adrift = false, ...turn } = {}) {
|
||||
export function homeButtonState({ workflow, finished = false, stopping = false, homeward = false, adrift = false, warned = false, ...turn } = {}) {
|
||||
if (!workflow || workflow === "dashboard" || finished || stopping) return { hidden: true, disabled: true, title: "" };
|
||||
if (homeward && !adrift) return { hidden: false, disabled: true, title: "Opening the dashboard…" };
|
||||
const gate = turnGate(turn);
|
||||
return {
|
||||
hidden: false,
|
||||
disabled: Boolean(gate),
|
||||
title: gate ? HOME_TITLES[gate] : "Back to the dashboard. Your place is saved first.",
|
||||
// With a stop warning up, the work since the last save is what leaving
|
||||
// loses: the tooltip says so rather than promising a saved place.
|
||||
title: gate ? HOME_TITLES[gate] : warned ? "Back to the dashboard. Work since the last save is not kept." : "Back to the dashboard. Your place is saved first.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -438,8 +461,8 @@ export function resumeCommand({ workflow, specDir } = {}) {
|
||||
return withOverview("/plan2code-4-finalize");
|
||||
case "handoff":
|
||||
return "/plan2code-handoff";
|
||||
case "git-commit":
|
||||
return "/plan2code-git-commit";
|
||||
case "git":
|
||||
return "/plan2code-git";
|
||||
case "changelog":
|
||||
return "/plan2code-changelog";
|
||||
default:
|
||||
@@ -456,7 +479,7 @@ export const REVIEW_REPLY =
|
||||
"Review what was just built before I go: run the focused code review on this session's changes, here on the page.";
|
||||
export const DONE_REPLY = "No review, thanks. I am done: close the session.";
|
||||
export const DASHBOARD_REPLY = "Take me back to the dashboard, right here in this session.";
|
||||
export const COMMIT_REPLY = "Commit what was just built: start Git commit, right here in this session.";
|
||||
export const COMMIT_REPLY = "Commit what was just built: open Git's commit flow, right here in this session.";
|
||||
|
||||
// Shown under the Back to the dashboard button: the press picks up in the same
|
||||
// conversation, which carries a long skill's context into the next one.
|
||||
@@ -475,7 +498,7 @@ export function dashboardOffer(fin) {
|
||||
/**
|
||||
* Whether a finish offers to commit what was just built from this page. The
|
||||
* agent opts in with `finish.commit: true` on a build that ended with a git
|
||||
* command; the press starts Git commit in the same session, as the dashboard's
|
||||
* command; the press starts Git's commit flow in the same session, as the dashboard's
|
||||
* card does. A pause never offers it.
|
||||
*/
|
||||
export function commitOffer(fin) {
|
||||
@@ -495,6 +518,16 @@ export function reviewOffer(fin) {
|
||||
return { label: label || "Review what was just built" };
|
||||
}
|
||||
|
||||
/**
|
||||
* One offer button on a finish (review, done, commit, dashboard). A press of
|
||||
* any of them is the session's one answer, so it locks every button until the
|
||||
* finish goes away, not just until the agent collects the send: `asked` is
|
||||
* the pressed one, which keeps its "requested…" label.
|
||||
*/
|
||||
export function afterFinishButton(afterBuild, kind, pendingResult) {
|
||||
return { asked: afterBuild === kind, disabled: Boolean(afterBuild) || Boolean(pendingResult) };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- the dashboard */
|
||||
|
||||
// The skills the dashboard offers, in the order it offers them. The page owns
|
||||
@@ -666,18 +699,18 @@ export const SKILL_CATALOG = [
|
||||
title: "Changelog",
|
||||
blurb: "Checks the CHANGELOG version against the main branch and suggests entries for what is new.",
|
||||
about:
|
||||
"Works out the right version from the default branch, then compares your branch with the latest CHANGELOG entry and suggests the entries it is missing. You edit them before anything is written, it keeps package.json in step, and it offers to run Git commit next. If the newest version is not released or on another branch yet, it adds to that entry instead of starting a new one.",
|
||||
"Works out the right version from the default branch, then compares your branch with the latest CHANGELOG entry and suggests the entries it is missing. You edit them before anything is written, it keeps package.json in step, and it offers to commit the result in Git. If the newest version is not released or on another branch yet, it adds to that entry instead of starting a new one.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-git-commit",
|
||||
command: "/plan2code-git-commit",
|
||||
workflow: "git-commit",
|
||||
skill: "plan2code-git",
|
||||
command: "/plan2code-git",
|
||||
workflow: "git",
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Git commit",
|
||||
blurb: "Commits your changes with a clear message, suggests a split when it is really two jobs, and offers to push.",
|
||||
title: "Git",
|
||||
blurb: "Branches, pull, push and commits on one board that stays open while you work.",
|
||||
about:
|
||||
"Reads what changed and drafts the commit message for you to approve. On the main branch it offers a new one first, and when the work is really two jobs it suggests splitting it into separate commits. It asks before every commit and every push, and never force-pushes.",
|
||||
"Shows your branch, what is ahead or behind, and every local and remote branch. Switch, create, delete or clean up branches, pull (rebasing when they have split, with help on conflicts), push or publish, and commit with a clear message. It asks before every push, publish and delete, and never force-pushes.",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -701,7 +734,7 @@ export const START_POSES = [
|
||||
"quick-task",
|
||||
"review",
|
||||
"handoff",
|
||||
"git-commit",
|
||||
"git",
|
||||
"changelog",
|
||||
];
|
||||
|
||||
@@ -743,7 +776,6 @@ const NEXT_FOR_STATE = {
|
||||
|
||||
const ON = { on: true };
|
||||
export const GIT_INIT_NOTE = "Not a git repository yet: it offers to start one";
|
||||
export const GIT_CLEAN_REASON = "Nothing to commit: no changed or new files";
|
||||
export const pendingNote = (n) => `${n} file${n === 1 ? "" : "s"} to commit`;
|
||||
const off = (reason) => ({ on: false, reason });
|
||||
|
||||
@@ -775,12 +807,10 @@ export function cardAvailability(entry, scan, sel) {
|
||||
case "plan2code-handoff":
|
||||
case "plan2code-changelog":
|
||||
return ON;
|
||||
case "plan2code-git-commit":
|
||||
case "plan2code-git":
|
||||
// Never greyed: a clean tree still has branches to switch, pull and push.
|
||||
if (scan && scan.isGit === false) return { on: true, note: GIT_INIT_NOTE };
|
||||
// `pending` is null when git could not say: stay clickable then.
|
||||
if (scan && scan.isGit && Number.isInteger(scan.pending)) {
|
||||
return scan.pending === 0 ? off(GIT_CLEAN_REASON) : { on: true, note: pendingNote(scan.pending) };
|
||||
}
|
||||
if (scan && Number.isInteger(scan.pending) && scan.pending > 0) return { on: true, note: pendingNote(scan.pending) };
|
||||
return ON;
|
||||
case "plan2code-0-pathfinder":
|
||||
if (!state || state === "exploring") return { ...ON, next };
|
||||
@@ -982,6 +1012,13 @@ export function noteAction(id, text, attachments) {
|
||||
return action;
|
||||
}
|
||||
|
||||
// Typed text past its first line, indented, so only a real entry ever starts a
|
||||
// reply line: a typed "Idea name: foo" or " Image: C:\x" must not read as an
|
||||
// answer or an attachment. Chat's lines already do this.
|
||||
export function indentReply(text, pad = " ") {
|
||||
return String(text).replace(/\r?\n/g, "\n" + pad);
|
||||
}
|
||||
|
||||
// A note as `reply` lines, one indented `Image:` or `File:` line per
|
||||
// attachment in the order attached, so the agent can open each path with its
|
||||
// file-read tool. An image-only note reads exactly as it always did.
|
||||
@@ -990,7 +1027,7 @@ export function noteReplyLines(title, text, attachments) {
|
||||
const anyFile = list.some((a) => attachmentKind(a) === "file");
|
||||
const said = text || (list.length ? (anyFile ? "(attachments only)" : "(images only)") : "");
|
||||
return [
|
||||
`Note on ${title}: ${said}`,
|
||||
`Note on ${title}: ${indentReply(said)}`,
|
||||
...list.map((a) => ` ${attachmentKind(a) === "file" ? "File" : "Image"}: ${a.path} (${a.name})`),
|
||||
];
|
||||
}
|
||||
|
||||
+223
-28
@@ -303,6 +303,12 @@ h1 {
|
||||
|
||||
.progress-block { flex: 1 1 260px; min-width: 200px; max-width: 460px; margin-left: auto; }
|
||||
|
||||
/* When the progress block is hidden (the dashboard, the git board) nothing
|
||||
grows to fill the row, so the icon buttons would sit beside the title. The
|
||||
first takes the slack instead; with the block shown its flex already eats
|
||||
the space, so this costs nothing. */
|
||||
#btn-about { margin-left: auto; }
|
||||
|
||||
.progress-label {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
@@ -690,13 +696,13 @@ h1 {
|
||||
}
|
||||
.wake.dormant .wake-hint { opacity: 1; }
|
||||
|
||||
/* Skip: muted, bottom right, so it never competes with the animation. */
|
||||
/* Skip: bottom right, out of the animation's way but big enough to find. */
|
||||
.wake-skip {
|
||||
position: absolute; right: 14px; bottom: 14px;
|
||||
padding: 4px 12px; border: 1px solid var(--ink-3); border-radius: 4px;
|
||||
background: transparent; color: var(--ink-3);
|
||||
font: inherit; font-size: 0.8rem; letter-spacing: 0.08em; text-transform: uppercase;
|
||||
cursor: pointer; opacity: 0.7;
|
||||
position: absolute; right: 24px; bottom: 24px;
|
||||
min-width: 120px; padding: 10px 26px; border: 1.5px solid var(--ink-2); border-radius: 6px;
|
||||
background: var(--panel-2); color: var(--ink-2);
|
||||
font: inherit; font-size: 1rem; font-weight: 600; letter-spacing: 0.1em; text-transform: uppercase;
|
||||
cursor: pointer; opacity: 0.9;
|
||||
}
|
||||
.wake-skip:hover, .wake-skip:focus-visible { opacity: 1; color: var(--ink); border-color: var(--ink); }
|
||||
|
||||
@@ -878,6 +884,11 @@ h1 {
|
||||
padding: 6px 13px;
|
||||
border-radius: 99px;
|
||||
cursor: pointer;
|
||||
/* A doc titled with a sentence keeps the tab row to one line. */
|
||||
max-width: 22ch;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.view-tab:hover { background: var(--panel-2); color: var(--ink); }
|
||||
.view-tab[aria-current="true"] {
|
||||
@@ -947,12 +958,20 @@ h1 {
|
||||
padding-right: 32px;
|
||||
}
|
||||
|
||||
/* The column itself never scrolls; the card does. */
|
||||
/* The column itself never scrolls; the card does. The git board is the one
|
||||
exception, below: it stacks a card over the board, so the column takes the
|
||||
scroll there and both flow through it at natural height. */
|
||||
.main > .card:not(.is-primary) { flex-shrink: 100; min-height: 104px; }
|
||||
.main > .card.is-primary { flex-shrink: 1; min-height: 0; }
|
||||
/* A card with a growing answer box takes the column's full height above the
|
||||
pager, and still scrolls its own contents. app.js sizes the box to fill it. */
|
||||
.main > .card.is-primary.has-grow { flex: 1 1 auto; }
|
||||
/* More below the fold (app.js markMore): the bottom edge fades, so a card
|
||||
cut by the window never reads as finished. */
|
||||
.main > .card.has-more {
|
||||
-webkit-mask-image: linear-gradient(to bottom, #000 calc(100% - 56px), transparent);
|
||||
mask-image: linear-gradient(to bottom, #000 calc(100% - 56px), transparent);
|
||||
}
|
||||
.pager { flex: none; }
|
||||
|
||||
/* A document is read top to bottom and has no pinned furniture, so it goes back
|
||||
@@ -1069,7 +1088,7 @@ h1 {
|
||||
}
|
||||
.ask-about-chip > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ask-about-chip .attach-remove { position: static; flex: none; }
|
||||
.ask-actions { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
|
||||
.ask-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-top: 8px; }
|
||||
/* + Add context and its menu. It opens upward, over the list: the composer
|
||||
sits at the bottom of a pane that clips anything hanging below it. */
|
||||
.ask-context { position: relative; }
|
||||
@@ -1754,6 +1773,7 @@ input[type="text"].invalid { border-color: var(--warn); }
|
||||
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
||||
.btn.ghost:hover { background: var(--panel-2); color: var(--ink); }
|
||||
.btn.danger { border-color: var(--warn); color: var(--warn); }
|
||||
.btn.danger.is-on { background: var(--warn); color: #fff; }
|
||||
.btn.small { padding: 7px 13px; font-size: 13.5px; }
|
||||
/* Available, but not the step. Reads as a button, does not shout like one. */
|
||||
.btn.standby {
|
||||
@@ -1954,7 +1974,10 @@ input[type="text"].invalid { border-color: var(--warn); }
|
||||
|
||||
/* ----------------------------------------------------------- markdown */
|
||||
|
||||
.md { max-width: 68ch; }
|
||||
/* A word or path longer than the line breaks instead of widening the page;
|
||||
code blocks and tables keep their own scroll. */
|
||||
.md { max-width: 68ch; overflow-wrap: anywhere; }
|
||||
.md pre, .md .md-table { overflow-wrap: normal; }
|
||||
.md-h { font-family: var(--serif); font-weight: 600; margin: 22px 0 9px; line-height: 1.25; }
|
||||
h2.md-h { font-size: 21px; }
|
||||
h3.md-h { font-size: 17.5px; }
|
||||
@@ -1964,9 +1987,12 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
.md-li { margin-bottom: 5px; }
|
||||
.md-task { display: inline-block; width: 16px; color: var(--ink-3); font-weight: 700; }
|
||||
.md-task.is-done { color: var(--ok); }
|
||||
.md-task.is-blocked { color: var(--warn); }
|
||||
.md-task.is-doing { color: var(--accent); }
|
||||
.md-task.is-assumed { color: var(--stage); }
|
||||
.md-li.is-task {
|
||||
list-style: none; margin-left: -18px;
|
||||
display: grid; grid-template-columns: 16px 1fr; column-gap: 4px; align-items: baseline;
|
||||
display: grid; grid-template-columns: 16px minmax(0, 1fr); column-gap: 4px; align-items: baseline;
|
||||
}
|
||||
.md-li.is-task > :not(.md-task) { grid-column: 2; }
|
||||
.md-li.is-task > .md-p:last-child { margin-bottom: 0; }
|
||||
@@ -2000,23 +2026,17 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
transition: opacity 0.12s;
|
||||
}
|
||||
.md-pre-wrap:hover .md-copy, .md-copy:focus { opacity: 1; }
|
||||
/* Run it, on git blocks: Copy's twin, tucked under it so the wider
|
||||
"Press Ctrl+C" fallback label can never collide. */
|
||||
.md-run {
|
||||
position: absolute; top: 34px; right: 8px;
|
||||
font: 600 11.5px var(--sans);
|
||||
background: var(--panel); color: var(--ink-2);
|
||||
border: 1px solid var(--rule-2); border-radius: 6px;
|
||||
padding: 4px 9px; cursor: pointer; opacity: 0;
|
||||
transition: opacity 0.12s;
|
||||
}
|
||||
.md-pre-wrap:hover .md-run, .md-run:focus { opacity: 1; }
|
||||
/* The muted nudge on other command-looking blocks, a caption under the block. */
|
||||
/* The muted nudge on command-looking blocks, a caption under the block. */
|
||||
.md-run-hint {
|
||||
margin: -6px 2px 0;
|
||||
margin: 4px 2px 0;
|
||||
font: 11px var(--sans); color: var(--ink-3);
|
||||
opacity: 0.8;
|
||||
}
|
||||
/* No "paste it into the Ask tab" nudge where the command is the card's own
|
||||
action (a confirm's consequences, a finished screen's commit beside its
|
||||
Commit it now button). */
|
||||
.is-consequences .md-run-hint,
|
||||
.handoff .md-run-hint { display: none; }
|
||||
.md-hr { border: 0; border-top: 1px solid var(--rule); margin: 20px 0; }
|
||||
.md-table-wrap { overflow-x: auto; margin: 0 0 13px; }
|
||||
.md-table { border-collapse: collapse; width: 100%; font-size: 13.5px; }
|
||||
@@ -2065,6 +2085,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
.footer.is-dash .footer-summary,
|
||||
.footer.is-dash .footer-actions { display: none; }
|
||||
.footer.is-dash .footer-where { grid-column: 2; }
|
||||
.footer.is-dash-done .footer-actions { display: none; }
|
||||
.hint { font-size: 12.5px; color: var(--ink-3); display: flex; align-items: center; gap: 7px; }
|
||||
/* A label, not a sentence: the full reason rides in the hint's tooltip, and
|
||||
the dock already carries the ticking clock this would otherwise repeat. */
|
||||
@@ -2165,6 +2186,9 @@ button.waiting-jump:hover { text-decoration-color: var(--accent); }
|
||||
.icon-btn:hover .ab-dot { fill: var(--accent); }
|
||||
|
||||
a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
/* A link in a dialog (the update modal's release, Help's version) keeps the
|
||||
accent once visited: the browser's purple is unreadable on the dark theme. */
|
||||
.modal a:not(.btn), .modal a:not(.btn):visited { color: var(--accent); }
|
||||
.icon-btn .mg-body { fill: none; stroke: var(--ink-3); stroke-width: 1.4; stroke-linejoin: round; }
|
||||
.icon-btn .mg-line { fill: none; stroke: var(--ink-2); stroke-width: 1.4; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.icon-btn:hover .mg-body, .icon-btn:hover .mg-line { stroke: var(--accent); }
|
||||
@@ -2629,6 +2653,14 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
@media (max-width: 720px) {
|
||||
.looks-row { grid-template-columns: 1fr; }
|
||||
}
|
||||
/* User Preferences itself (not the dialogs borrowing .looks): wider, and only
|
||||
the body scrolls, so Back to default and Done never leave the screen. */
|
||||
.modal.prefs { max-width: 880px; }
|
||||
.modal.prefs[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
||||
.prefs-body { overflow-y: auto; min-height: 0; flex: 1 1 auto; margin-right: -12px; padding-right: 12px; padding-top: 10px; }
|
||||
/* A line scrolled up under the title fades out rather than being sliced. */
|
||||
.prefs-body { -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 12px); mask-image: linear-gradient(to bottom, transparent 0, #000 12px); }
|
||||
.modal.prefs .modal-actions { flex: none; margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--rule); }
|
||||
|
||||
/* The Workspace dialog: one entry per folder, the original first, then the
|
||||
Add row. Wide enough for a real path; the list scrolls, the Add row and the
|
||||
@@ -2972,13 +3004,14 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid var(--rule);
|
||||
}
|
||||
/* Wraps at the dashes rather than cut off: a command missing its end
|
||||
("/plan2code-3-implement-revi…") is no command at all. */
|
||||
.dash-card-cmd {
|
||||
font-family: var(--mono);
|
||||
font-size: 11.5px;
|
||||
color: var(--ink-3);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dash-card-go { color: var(--accent); font-weight: 700; transition: transform 0.15s ease; }
|
||||
.dash-card:hover:not(:disabled) .dash-card-go { transform: translateX(3px); }
|
||||
@@ -3474,8 +3507,8 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
100% { transform: translateX(8px); opacity: 0; }
|
||||
}
|
||||
|
||||
/* Git commit -- the arm reaches out and a new commit settles onto the branch
|
||||
line in step with it. */
|
||||
/* Git -- the arm reaches out and a new commit settles onto the branch line in
|
||||
step with it. */
|
||||
.pose .gc-reach { transform-origin: 0% 50%; animation: gc-reach 2.4s ease-in-out infinite; }
|
||||
@keyframes gc-reach {
|
||||
0%, 100% { transform: scaleX(0.9); }
|
||||
@@ -3616,3 +3649,165 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
}
|
||||
.status-help:hover { text-decoration-thickness: 2px; }
|
||||
.status-help:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 3px; }
|
||||
|
||||
/* ------------------------------------------------------------ git board */
|
||||
|
||||
/* The git workflow's main column stacks two things where every other view
|
||||
holds one: the agent's card on top and the board under it. Stacked children
|
||||
that each scrolled would put a scrollbar inside a scrollbar, so here the
|
||||
column takes the one scroll and both flow through it at natural height. */
|
||||
.main:has(> .git-board) {
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
/* Listed with .is-primary.has-grow too: that rule (a card with a growing note
|
||||
box takes the column's height and shrinks into it) outranks a plain .card
|
||||
here, and a card shrunk under the board spilled its buttons beneath it. */
|
||||
.main:has(> .git-board) > .card,
|
||||
.main:has(> .git-board) > .card.is-primary.has-grow,
|
||||
.main:has(> .git-board) > .git-board {
|
||||
flex: none;
|
||||
overflow-y: visible;
|
||||
min-height: 0;
|
||||
}
|
||||
/* Over the board a card's boxes cannot fill the column (it flows, it does not
|
||||
stretch), so a note box grows with what is typed instead, where the browser
|
||||
can, rather than scrolling inside a 96px box. */
|
||||
.main:has(> .git-board) > .card textarea { field-sizing: content; max-height: 50vh; }
|
||||
.main > .git-board {
|
||||
padding-right: 32px;
|
||||
display: grid;
|
||||
/* minmax(0, …): the column never takes the branch table's no-wrap width. */
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
align-content: start;
|
||||
gap: 14px;
|
||||
max-width: var(--card-width);
|
||||
}
|
||||
/* The board's header is a section lead, not a second card: the agent's card
|
||||
above is the column's only framed element. */
|
||||
.git-head {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
padding: 0 0 10px;
|
||||
border-bottom: 1px solid var(--rule);
|
||||
}
|
||||
.git-head-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px 14px; }
|
||||
.git-branch { margin: 0; font: 600 22px/1.2 var(--serif); overflow-wrap: anywhere; }
|
||||
.git-track { font-family: var(--mono); font-size: 14px; color: var(--ink-2); }
|
||||
.git-head-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; font-size: 13.5px; color: var(--ink-2); }
|
||||
.git-noremote { font-weight: 600; color: var(--stage); }
|
||||
.git-activity { color: var(--accent); }
|
||||
.git-pr { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding-top: 6px; border-top: 1px solid var(--rule); }
|
||||
.git-pr-open { text-decoration: none; }
|
||||
.git-pr-ask { font-size: 14px; color: var(--ink); }
|
||||
.git-pr-base { font-size: 13.5px; color: var(--ink-2); }
|
||||
.git-pr-base select, .git-field select, .git-field input, .git-search {
|
||||
font: inherit;
|
||||
font-size: 14px;
|
||||
padding: 6px 10px;
|
||||
color: var(--ink);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.git-warn, .git-op {
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--warn);
|
||||
border-left-width: 4px;
|
||||
border-radius: var(--radius);
|
||||
background: var(--warn-soft);
|
||||
color: var(--ink);
|
||||
}
|
||||
.git-op { display: grid; gap: 8px; border-color: var(--stage); background: var(--stage-soft); }
|
||||
.git-op-files { margin: 0; padding-left: 20px; font-size: 13.5px; }
|
||||
.git-op-left { color: var(--warn); }
|
||||
.git-op-clear { color: var(--ok); }
|
||||
.git-op-actions, .git-panel-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.git-note { margin: 0; color: var(--ink-2); }
|
||||
.git-result {
|
||||
padding: 10px 16px;
|
||||
border: 1px solid var(--accent-line);
|
||||
border-radius: var(--radius);
|
||||
background: var(--accent-soft);
|
||||
font-size: 14px;
|
||||
}
|
||||
.git-result-body .md-p { margin: 4px 0 0; }
|
||||
/* The result box is the line length here: git's stderr runs the full width. */
|
||||
.git-result-body.md { max-width: none; }
|
||||
/* Pinned to the pane's bottom while the board scrolls past: the column is
|
||||
the scroller on this view, and the bar is the board's last child, so
|
||||
bottom: 0 holds it on screen until the board's end comes up to dock it.
|
||||
Opaque so the table slips underneath, bordered so the seam reads. */
|
||||
.git-bar {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
z-index: 6;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
padding: 10px 0 8px;
|
||||
background: var(--bg);
|
||||
border-top: 1px solid var(--rule);
|
||||
}
|
||||
.git-done { margin-left: auto; }
|
||||
.git-panel {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
padding: 14px 18px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--accent-line);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
.git-panel-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.git-panel-title { margin: 0; font-size: 16px; }
|
||||
.git-group-title { margin: 4px 0 0; font-size: 13.5px; color: var(--ink-2); }
|
||||
.git-field-row { display: flex; flex-wrap: wrap; align-items: end; gap: 10px; }
|
||||
.git-field { display: grid; gap: 4px; font-size: 13px; color: var(--ink-2); }
|
||||
.git-field.is-wide { flex: 1 1 16em; }
|
||||
.git-new-name { font-family: var(--mono); }
|
||||
.git-name-status { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 0; font-size: 13.5px; color: var(--ink-2); }
|
||||
.git-name-status.is-free { color: var(--ok); }
|
||||
.git-name-status.is-invalid, .git-name-status.is-nested { color: var(--warn); }
|
||||
.git-name-status.is-local, .git-name-status.is-remote { color: var(--stage); }
|
||||
.git-offer { margin: 0 auto 0 0; font-size: 14px; }
|
||||
.git-sweep { margin: 0; padding: 0; list-style: none; display: grid; gap: 4px; font-family: var(--mono); font-size: 13.5px; }
|
||||
.git-ignore { margin-left: 8px; white-space: nowrap; }
|
||||
.git-tools { display: flex; gap: 8px; align-items: center; margin-bottom: 8px; }
|
||||
.git-search { flex: 1 1 auto; }
|
||||
.git-branches { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; }
|
||||
.git-table-wrap { overflow-x: auto; }
|
||||
.git-table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
|
||||
.git-table th {
|
||||
text-align: left;
|
||||
font-size: 11.5px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
color: var(--ink-3);
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--rule);
|
||||
}
|
||||
.git-table td { padding: 7px 8px; border-bottom: 1px solid var(--rule); vertical-align: top; }
|
||||
.git-table tr.is-current td { background: var(--accent-soft); }
|
||||
.git-table tr.is-held td { color: var(--ink-2); }
|
||||
.git-cell-name { overflow-wrap: anywhere; }
|
||||
/* A branch name stays whole beside its badges (feature/export-csv never splits
|
||||
as feature/export- / csv), and the headers stay on one line: a narrow column
|
||||
scrolls the table sideways instead. */
|
||||
.git-cell-name .git-name { white-space: nowrap; }
|
||||
.git-table th { white-space: nowrap; }
|
||||
.git-name, .git-path { font-family: var(--mono); }
|
||||
.git-badge { margin-left: 6px; font-size: 10px; padding: 2px 6px; }
|
||||
.git-badge.is-merged { color: var(--ok); background: var(--ok-soft); border-color: var(--ok); }
|
||||
.git-badge.is-gone, .git-badge.is-held { color: var(--stage); background: var(--stage-soft); border-color: var(--stage); }
|
||||
.git-cell-track { font-family: var(--mono); white-space: nowrap; color: var(--ink-2); }
|
||||
/* Stacked with blocks, not `display: grid`: a grid <td> stops being a table
|
||||
cell, and its row's separator no longer lines up with the others. */
|
||||
.git-cell-last > span { display: block; }
|
||||
.git-cell-last > .git-by { margin-top: 2px; }
|
||||
.git-by { font-size: 12px; color: var(--ink-3); }
|
||||
.git-cell-actions { white-space: nowrap; text-align: right; }
|
||||
.git-cell-actions .btn + .btn { margin-left: 6px; }
|
||||
.git-remote-only summary { cursor: pointer; font-weight: 600; color: var(--ink-2); padding: 4px 0; }
|
||||
.git-empty { margin: 0; font-size: 13.5px; color: var(--ink-3); }
|
||||
+1282
-113
File diff suppressed because it is too large.
Load diff
@@ -31,7 +31,7 @@ function answeredFlags(messages) {
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const m = messages[i];
|
||||
if (m.from === "agent") replyLater = true;
|
||||
else if (m.kind === "message") flags.set(m.seq, replyLater);
|
||||
else if (m.kind === "message" || m.kind === "decision") flags.set(m.seq, replyLater);
|
||||
}
|
||||
return flags;
|
||||
}
|
||||
@@ -63,7 +63,7 @@ export function chatView(frameChat, ui = {}) {
|
||||
decided: decisions.get(m.id) || null,
|
||||
});
|
||||
} else if (m.kind === "decision") {
|
||||
rows.push({ kind: "decision", decision: m.decision, text: m.text || "", re: m.re });
|
||||
rows.push({ kind: "decision", decision: m.decision, text: m.text || "", re: m.re, done: Boolean(answered.get(m.seq)) });
|
||||
} else if (m.kind === "message") {
|
||||
const row = {
|
||||
kind: "person",
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
// Plan2Code Web Console - the git board's rules: branch order, names, buttons and replies.
|
||||
//
|
||||
// Everything the board decides from a state.git snapshot (git-repo.mjs ->
|
||||
// snapshot()) lives here so it is tested without a browser: how the branch
|
||||
// list is ordered and folded, whether a new branch name is free, which action
|
||||
// buttons show and which are enabled, the plain sentence each button sends
|
||||
// the agent, the "Last refreshed" line, which files start ticked in the
|
||||
// commit dialog and the pull-request link. app.js only renders what these
|
||||
// say. No DOM access at module scope and only one import: the page and
|
||||
// `node --test` both import this file.
|
||||
|
||||
import { prUrl } from "./pr-url.js";
|
||||
|
||||
export const BRANCH_TYPES = Object.freeze(["feature", "fix", "chore", "docs", "refactor", "test"]);
|
||||
export const REMOTE_FOLD = 50;
|
||||
// Matches under a search are capped too, or one fold draws thousands of rows.
|
||||
const QUERY_CAP = 200;
|
||||
export const UNTRACKED_TICK_LIMIT = 200;
|
||||
|
||||
export const PR_HOST_LABELS = Object.freeze({
|
||||
github: "GitHub",
|
||||
gitlab: "GitLab",
|
||||
bitbucket: "Bitbucket",
|
||||
azure: "Azure DevOps",
|
||||
none: "None",
|
||||
});
|
||||
|
||||
const list = (v) => (Array.isArray(v) ? v : []);
|
||||
const blank = (v) => typeof v !== "string" || v.trim() === "";
|
||||
|
||||
// Milliseconds of a row's last commit; -Infinity when missing or unreadable, so it sorts last.
|
||||
function lastTime(row) {
|
||||
const t = Date.parse(row && row.last && row.last.at);
|
||||
return Number.isNaN(t) ? -Infinity : t;
|
||||
}
|
||||
|
||||
const newestFirst = (a, b) => {
|
||||
const ta = lastTime(a);
|
||||
const tb = lastTime(b);
|
||||
if (ta === tb) return 0;
|
||||
return tb > ta ? 1 : -1;
|
||||
};
|
||||
|
||||
/** The local row for the checked-out branch, or null. */
|
||||
export function currentRow(git) {
|
||||
return list(git && git.branches).find((b) => b && b.current && !b.remote) || null;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ branches */
|
||||
|
||||
/**
|
||||
* `{ top, remoteOnly }`: local rows with the current branch first, then the
|
||||
* default branch (once, when it is also the current one), then the rest by
|
||||
* last commit, newest first; remote-only rows newest first. Never mutates.
|
||||
*/
|
||||
export function orderBranches(branches) {
|
||||
const rows = list(branches).filter(Boolean);
|
||||
const local = rows.filter((b) => !b.remote);
|
||||
const current = local.find((b) => b.current) || null;
|
||||
const def = local.find((b) => b.default && b !== current) || null;
|
||||
const rest = local.filter((b) => b !== current && b !== def).sort(newestFirst);
|
||||
const top = [...(current ? [current] : []), ...(def ? [def] : []), ...rest];
|
||||
const remoteOnly = rows.filter((b) => b.remote).sort(newestFirst);
|
||||
return { top, remoteOnly };
|
||||
}
|
||||
|
||||
/** Rows whose name, `remote/name` (remote-only rows) or last subject contain `query`, ignoring case. */
|
||||
export function filterBranches(rows, query) {
|
||||
if (blank(query)) return rows;
|
||||
const q = query.trim().toLowerCase();
|
||||
return list(rows).filter((b) => {
|
||||
const fields = [b.name, b.remote ? `${b.remote}/${b.name}` : "", b.last && b.last.subject];
|
||||
return fields.some((f) => typeof f === "string" && f.toLowerCase().includes(q));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The remote-only section: `{ shown, hidden, open }`. Without a query the
|
||||
* first REMOTE_FOLD rows show (all with showAll) and `hidden` counts the
|
||||
* rest; a query shows every match and opens the section.
|
||||
*/
|
||||
export function foldRemote(rows, { showAll = false, query = "" } = {}) {
|
||||
const all = list(rows);
|
||||
if (!blank(query)) {
|
||||
// A query also caps what it draws: a monorepo remote can match thousands.
|
||||
const matches = filterBranches(all, query);
|
||||
const shown = showAll ? matches : matches.slice(0, QUERY_CAP);
|
||||
return { shown, hidden: matches.length - shown.length, open: true };
|
||||
}
|
||||
const shown = showAll ? all.slice() : all.slice(0, REMOTE_FOLD);
|
||||
return { shown, hidden: all.length - shown.length, open: false };
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- new branch */
|
||||
|
||||
/** `<type>/<desc>`; "" with no description. */
|
||||
export function composeBranchName({ type, description } = {}) {
|
||||
const kind = blank(type) ? "feature" : type.trim();
|
||||
const desc = String(description || "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
return desc ? `${kind}/${desc}` : "";
|
||||
}
|
||||
|
||||
// The first rule `git check-ref-format --branch` would break, as a sentence; null when none.
|
||||
function refFormatProblem(name) {
|
||||
if (name === "@") return 'A branch cannot be named just "@".';
|
||||
// git refuses it as a branch name (git switch -c HEAD), as branch-check does.
|
||||
if (name === "HEAD") return 'A branch cannot be named "HEAD".';
|
||||
if (name.startsWith("-")) return "Branch names cannot start with a dash.";
|
||||
if (name.includes(" ")) return "Branch names cannot contain spaces.";
|
||||
if (name.includes("..")) return 'Branch names cannot contain "..".';
|
||||
if (name.includes("@{")) return 'Branch names cannot contain "@{".';
|
||||
if (name.includes("\\")) return "Branch names cannot contain a backslash.";
|
||||
const special = name.match(/[~^:?*[]/);
|
||||
if (special) return `Branch names cannot contain "${special[0]}".`;
|
||||
if ([...name].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127)) {
|
||||
return "Branch names cannot contain control characters.";
|
||||
}
|
||||
if (name.endsWith("/")) return 'Branch names cannot end with "/".';
|
||||
if (name.endsWith(".")) return 'Branch names cannot end with ".".';
|
||||
const parts = name.split("/");
|
||||
if (parts.some((p) => p === "")) return 'Branch names cannot start with "/" or contain "//".';
|
||||
if (parts.some((p) => p.startsWith("."))) return 'No part of a branch name can start with ".".';
|
||||
if (parts.some((p) => p.endsWith(".lock"))) return 'No part of a branch name can end with ".lock".';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `name` can be created: the first of empty, invalid (with a
|
||||
* reason), local (already a local branch), remote (a remote-only branch),
|
||||
* nested (it and a local branch would be folders of each other) or free.
|
||||
*/
|
||||
export function nameStatus(name, git) {
|
||||
if (blank(name)) return { kind: "empty" };
|
||||
const reason = refFormatProblem(name);
|
||||
if (reason) return { kind: "invalid", reason };
|
||||
const rows = list(git && git.branches).filter(Boolean);
|
||||
const locals = rows.filter((b) => !b.remote);
|
||||
const local = locals.find((b) => b.name === name);
|
||||
if (local) return { kind: "local", branch: local.name };
|
||||
// The board shows a remote-only branch as origin/name, so that is taken too.
|
||||
const remote = rows.find((b) => b.remote && (b.name === name || `${b.remote}/${b.name}` === name));
|
||||
if (remote) return { kind: "remote", remote: remote.remote, branch: remote.name };
|
||||
const nested = locals.find((b) => name.startsWith(`${b.name}/`) || b.name.startsWith(`${name}/`));
|
||||
if (nested) return { kind: "nested", clash: nested.name };
|
||||
return { kind: "free" };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- buttons */
|
||||
|
||||
const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
||||
|
||||
const button = (shown, enabled, label, title) => ({ shown, enabled: shown && enabled, label, ...(title ? { title } : {}) });
|
||||
|
||||
/**
|
||||
* Every board button as `{ shown, enabled, label, title? }`. Pull is enabled
|
||||
* only with an upstream to pull from; Push shows with an upstream, Publish
|
||||
* without one. `busy` greys everything out but Done; an operation in
|
||||
* progress hides everything but Done (its banner carries Abort / Continue).
|
||||
*/
|
||||
export function boardActions(git, { busy = false } = {}) {
|
||||
const g = git || {};
|
||||
const head = g.head || {};
|
||||
const changes = g.changes || {};
|
||||
const count = Number(changes.count) || 0;
|
||||
const heldBack = Number(changes.heldBack) || 0;
|
||||
const hasCommits = g.hasCommits !== false;
|
||||
const hasRemote = list(g.remotes).length > 0;
|
||||
const detached = hasCommits && !head.branch;
|
||||
const ahead = Number(head.ahead) || 0;
|
||||
const free = !busy;
|
||||
|
||||
const done = button(true, true, "Done");
|
||||
const hidden = (label) => button(false, false, label);
|
||||
|
||||
if (g.inProgress) {
|
||||
return {
|
||||
refresh: hidden("Refresh"),
|
||||
pull: hidden("Pull"),
|
||||
push: hidden("Push"),
|
||||
publish: hidden("Publish"),
|
||||
commit: hidden("Commit"),
|
||||
cleanup: hidden("Clean up"),
|
||||
done,
|
||||
};
|
||||
}
|
||||
|
||||
const commitLabel = !hasCommits
|
||||
? "Make the first commit"
|
||||
: `Commit ${plural(count, "file", "files")}${heldBack > 0 ? ` · ${heldBack} held back` : ""}`;
|
||||
const commit = button(count > 0, free, commitLabel);
|
||||
|
||||
if (!hasCommits) {
|
||||
return {
|
||||
refresh: button(true, free, "Refresh", "Look at this folder again"),
|
||||
pull: hidden("Pull"),
|
||||
push: hidden("Push"),
|
||||
publish: hidden("Publish"),
|
||||
commit,
|
||||
cleanup: hidden("Clean up"),
|
||||
done,
|
||||
};
|
||||
}
|
||||
|
||||
const notOnBranch = "Not on a branch: switch to one first";
|
||||
// Shown without a remote too: it is how edits made outside reach the board
|
||||
// (the agent re-reads the folder; with a remote it fetches first).
|
||||
const refresh = button(true, free, "Refresh", hasRemote ? undefined : "Look at this folder again");
|
||||
|
||||
// An upstream whose remote copy was deleted is no upstream: nothing to pull
|
||||
// from or push to, and Publish (which plan publish allows again) is the way.
|
||||
const live = Boolean(head.upstream) && !head.gone;
|
||||
let pull;
|
||||
if (detached) pull = button(hasRemote, false, "Pull", notOnBranch);
|
||||
else if (head.upstream && head.gone) pull = button(hasRemote, false, "Pull", "Its remote copy was deleted: publish it again");
|
||||
else if (!head.upstream) pull = button(hasRemote, false, "Pull", "Nothing to pull from yet: publish first");
|
||||
else pull = button(hasRemote, free, "Pull");
|
||||
|
||||
const showPush = hasRemote && live && !detached;
|
||||
const push =
|
||||
ahead > 0
|
||||
? button(showPush, free, `Push · ${ahead} to push`)
|
||||
: button(showPush, false, "Push", "Nothing to push");
|
||||
|
||||
const showPublish = hasRemote && !live;
|
||||
const publish = detached ? button(showPublish, false, "Publish", notOnBranch) : button(showPublish, free, "Publish");
|
||||
|
||||
const cleanable = list(g.branches).some((b) => b && !b.remote && !b.current && !b.default && (b.merged || b.gone));
|
||||
const cleanup = button(!!g.defaultBranch && cleanable, free, "Clean up");
|
||||
|
||||
return { refresh, pull, push, publish, commit, cleanup, done };
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the board is still waiting on the agent: a card send not yet
|
||||
* settled, or a board click at `sentAt` (ms) with no agent post since
|
||||
* (`updatedAt`, the state's last post, ISO). Collecting a click takes
|
||||
* milliseconds, so "uncollected" alone leaves the bar live while the agent
|
||||
* runs git. An agent gone quiet (`adrift`) releases the lock.
|
||||
*/
|
||||
export function boardAwaiting({ sentAt = null, updatedAt = null, cardsAwaiting = 0, adrift = false } = {}) {
|
||||
if (adrift) return false;
|
||||
if (cardsAwaiting > 0) return true;
|
||||
if (!sentAt) return false;
|
||||
const posted = Date.parse(updatedAt);
|
||||
return !(posted > sentAt);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- replies */
|
||||
|
||||
const names = (v) => list(v).filter((s) => typeof s === "string" && s);
|
||||
|
||||
// "these 3 files: a, b, c" or "this file: a".
|
||||
function filePhrase(files, count) {
|
||||
const n = Number.isInteger(count) ? count : files.length;
|
||||
const shown = files.length ? `: ${files.join(", ")}` : "";
|
||||
return n === 1 ? `this file${shown}` : `these ${n} files${shown}`;
|
||||
}
|
||||
|
||||
/** The plain instruction a board button sends the agent, one sentence per op. */
|
||||
export function gitReply(op, fields = {}) {
|
||||
const f = fields || {};
|
||||
switch (op) {
|
||||
case "refresh":
|
||||
return "Refresh.";
|
||||
case "pull":
|
||||
return "Pull.";
|
||||
case "push":
|
||||
return "Push.";
|
||||
case "publish":
|
||||
// No remote named: there are several, and the agent asks which.
|
||||
return f.remote ? `Publish to ${f.remote}.` : "Publish.";
|
||||
case "switch":
|
||||
return `Switch to ${f.branch}.`;
|
||||
case "create": {
|
||||
const start = `Create ${f.name} from ${f.from}.`;
|
||||
if (f.then !== "commit") return start;
|
||||
const ignore = names(f.ignore);
|
||||
const tail = ignore.length ? ` Add ${ignore.join(", ")} to .gitignore.` : "";
|
||||
return `${start} Then commit ${filePhrase(names(f.files), f.count)}.${tail}`;
|
||||
}
|
||||
case "delete":
|
||||
return `Delete ${f.branch}.`;
|
||||
case "cleanup": {
|
||||
const branches = names(f.branches);
|
||||
const n = Number.isInteger(f.count) ? f.count : branches.length;
|
||||
return `Clean up ${plural(n, "branch", "branches")}${branches.length ? `: ${branches.join(", ")}` : ""}.`;
|
||||
}
|
||||
case "commit": {
|
||||
const ignore = names(f.ignore);
|
||||
const tail = ignore.length ? ` Add ${ignore.join(", ")} to .gitignore.` : "";
|
||||
return `Commit ${filePhrase(names(f.files), f.count)}.${tail}`;
|
||||
}
|
||||
case "abort":
|
||||
return `Abort the ${f.operation === "am" ? "git am" : f.operation || "rebase"}.`;
|
||||
case "continue":
|
||||
return `Continue the ${f.operation === "am" ? "git am" : f.operation || "rebase"}.`;
|
||||
case "pr-host":
|
||||
if (f.kind === "none" || !Object.hasOwn(PR_HOST_LABELS, f.kind)) return "This host is none of those.";
|
||||
return `This host is ${PR_HOST_LABELS[f.kind]}.`;
|
||||
case "done":
|
||||
return "I'm done.";
|
||||
default:
|
||||
return `${op}.`;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- time */
|
||||
|
||||
const UNITS = [
|
||||
["year", 365 * 24 * 3600],
|
||||
["month", 30 * 24 * 3600],
|
||||
["week", 7 * 24 * 3600],
|
||||
["day", 24 * 3600],
|
||||
["hour", 3600],
|
||||
["minute", 60],
|
||||
];
|
||||
|
||||
let rtf = null;
|
||||
|
||||
/** "2 hr. ago" style age of `iso`, in its largest whole unit; "" for an unreadable date. */
|
||||
export function relativeAge(iso, now = Date.now()) {
|
||||
const t = typeof iso === "number" ? iso : Date.parse(iso);
|
||||
if (iso === null || iso === undefined || iso === "" || Number.isNaN(t) || !Number.isFinite(Number(now))) return "";
|
||||
rtf = rtf || new Intl.RelativeTimeFormat("en", { numeric: "auto", style: "short" });
|
||||
const seconds = (t - Number(now)) / 1000;
|
||||
const unit = UNITS.find(([, size]) => Math.abs(seconds) >= size);
|
||||
if (!unit) return rtf.format(0, "second");
|
||||
return rtf.format(Math.round(seconds / unit[1]), unit[0]);
|
||||
}
|
||||
|
||||
/** The board's footer line: when the remotes were last fetched, and whether the last try failed. */
|
||||
export function refreshedLine(git, now = Date.now()) {
|
||||
const g = git || {};
|
||||
const age = g.lastFetch ? relativeAge(g.lastFetch, now) : "";
|
||||
const line = age ? `Last refreshed ${age}` : "Never refreshed";
|
||||
return g.refreshFailed ? `${line} · refresh failed` : line;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- commit */
|
||||
|
||||
/**
|
||||
* The paths ticked when the commit dialog opens. Staged files win: when any
|
||||
* file is staged, exactly those. Otherwise every file that is not risky,
|
||||
* plus each untracked folder of at most UNTRACKED_TICK_LIMIT files.
|
||||
*/
|
||||
export function commitTicks(changes) {
|
||||
const files = list(changes && changes.files).filter((f) => f && typeof f.path === "string");
|
||||
const staged = files.filter((f) => f.staged);
|
||||
if (staged.length) return new Set(staged.map((f) => f.path));
|
||||
const ticks = new Set(files.filter((f) => !f.risky).map((f) => f.path));
|
||||
for (const dir of list(changes && changes.untrackedDirs)) {
|
||||
if (dir && typeof dir.path === "string" && Number(dir.files) <= UNTRACKED_TICK_LIMIT) ticks.add(dir.path);
|
||||
}
|
||||
return ticks;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- pull requests */
|
||||
|
||||
/**
|
||||
* The pull-request link for the current branch into `base` (the default
|
||||
* branch unless the picker chose another): `{ url, needsKind, host }`, where
|
||||
* needsKind means the host's kind is unknown and the person must name it
|
||||
* (url is null then). null when the branch is not pushed, is gone upstream,
|
||||
* is the default branch, or its remote or the base is missing.
|
||||
*/
|
||||
export function boardPrLink(git, base) {
|
||||
const cur = currentRow(git);
|
||||
if (!cur || !cur.upstream || cur.gone || cur.default) return null;
|
||||
const target = base || (git && git.defaultBranch);
|
||||
if (!target) return null;
|
||||
const remote = list(git.remotes).find((r) => r && r.name === cur.upstreamRemote);
|
||||
if (!remote) return null;
|
||||
const needsKind = remote.kind === null || remote.kind === undefined;
|
||||
return {
|
||||
url: needsKind ? null : prUrl(remote, { base: target, head: cur.name }),
|
||||
needsKind,
|
||||
host: remote.host || null,
|
||||
};
|
||||
}
|
||||
@@ -20,6 +20,7 @@ export const HELP_TABS = Object.freeze([
|
||||
tab("dashboard", "The dashboard", true),
|
||||
tab("meter", "Session meter", false),
|
||||
tab("build", "Watching a build", false),
|
||||
tab("git", "The git board", false),
|
||||
tab("subagents", "Helpers (subagents)", false),
|
||||
tab("ask", "Ask a quick question", false),
|
||||
tab("finishing", "Stopping and finishing", false),
|
||||
@@ -44,6 +45,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
||||
if (dashboard && meterRed) return "meter";
|
||||
if (dashboard) return "dashboard";
|
||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||
if (workflow === "git") return "git";
|
||||
if (HELP_BUILD_WORKFLOWS.has(workflow)) return "build";
|
||||
return "about";
|
||||
}
|
||||
|
||||
+209
-101
@@ -24,6 +24,8 @@
|
||||
<link rel="modulepreload" href="/subagents.js" />
|
||||
<link rel="modulepreload" href="/mentions.js" />
|
||||
<link rel="modulepreload" href="/favicon.js" />
|
||||
<link rel="modulepreload" href="/git-board.js" />
|
||||
<link rel="modulepreload" href="/pr-url.js" />
|
||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="icon" type="image/png" sizes="192x192" href="/favicon.png" />
|
||||
@@ -37,8 +39,8 @@
|
||||
rail drawing that powers on centre stage, then glides into the rail.
|
||||
Hidden unless boot.js is playing it; placed entirely by app.css,
|
||||
because the CSP refuses style attributes. -->
|
||||
<div class="wake" id="wake" hidden aria-hidden="true">
|
||||
<svg class="wake-bot" viewBox="0 0 22 30" focusable="false">
|
||||
<div class="wake" id="wake" hidden>
|
||||
<svg class="wake-bot" viewBox="0 0 22 30" focusable="false" aria-hidden="true">
|
||||
<g class="body">
|
||||
<rect class="foot f1" x="5.7" y="27.1" width="3.6" height="1.7" rx="0.85" />
|
||||
<rect class="foot f2" x="12.7" y="27.1" width="3.6" height="1.7" rx="0.85" />
|
||||
@@ -58,7 +60,7 @@
|
||||
</g>
|
||||
</svg>
|
||||
<p class="wake-hint">Click to wake Planny</p>
|
||||
<button class="wake-skip" type="button">Skip</button>
|
||||
<button class="wake-skip" type="button" aria-label="Skip the intro">Skip</button>
|
||||
</div>
|
||||
|
||||
<header class="topbar">
|
||||
@@ -565,13 +567,15 @@
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
<!-- Git commit: saving a step. Beside a branch line with two commits on
|
||||
it, one arm reaches to set a third commit onto the line. -->
|
||||
<svg class="pose pose-git-commit" data-pose="git-commit" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
|
||||
<!-- Git: minding the branches. Beside a branch line with a second branch
|
||||
forking off it, one arm reaches to set a new commit onto the line. -->
|
||||
<svg class="pose pose-git" data-pose="git" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
|
||||
<ellipse class="shadow" cx="126" cy="198" rx="44" ry="5" />
|
||||
<g class="prop">
|
||||
<line class="lt gc-line" x1="204" y1="62" x2="204" y2="172" />
|
||||
<path class="lt" d="M204 152 Q226 140 226 112 L226 72" />
|
||||
<circle class="ac" cx="204" cy="82" r="7" />
|
||||
<circle class="ac" cx="226" cy="92" r="6" />
|
||||
<circle class="ac" cx="204" cy="112" r="7" />
|
||||
<circle class="ac gc-dot" cx="204" cy="142" r="7" />
|
||||
</g>
|
||||
@@ -649,6 +653,12 @@
|
||||
<rect x="3" y="9" width="18" height="6" rx="3" />
|
||||
<path d="M6 12h7" />
|
||||
</symbol>
|
||||
<symbol id="hi-git" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="6" cy="5" r="2" />
|
||||
<circle cx="6" cy="19" r="2" />
|
||||
<circle cx="18" cy="7" r="2" />
|
||||
<path d="M6 7v10M18 9a7 7 0 0 1-7 7H6" />
|
||||
</symbol>
|
||||
<symbol id="hi-subagents" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="7" cy="12" r="3.5" />
|
||||
<circle cx="18" cy="5" r="2" />
|
||||
@@ -737,8 +747,9 @@
|
||||
<p>
|
||||
<strong>It stays up while this tab is open.</strong> Close the tab and
|
||||
it shuts itself down <span data-fact="closedTabMinutes">2</span> minutes
|
||||
later, and after <span data-fact="maxLifeHours">4</span> hours
|
||||
regardless. Reopening the same link brings everything back: nothing you
|
||||
later. It also stops after <span data-fact="idleMinutes">30</span>
|
||||
minutes without hearing from anyone, and after
|
||||
<span data-fact="maxLifeHours">4</span> hours regardless. Reopening the same link brings everything back: nothing you
|
||||
typed is kept in the browser alone.
|
||||
</p>
|
||||
<h4>Two halves, both running</h4>
|
||||
@@ -782,7 +793,7 @@
|
||||
<ol class="help-rows">
|
||||
<li class="help-row">
|
||||
<dl>
|
||||
<dt>You see</dt><dd>The line beside Planny stays quiet for a minute or two while it is working.</dd>
|
||||
<dt>You see</dt><dd>The line beside Planny stays quiet for half a minute or more while it is working.</dd>
|
||||
<dt>Likely cause</dt><dd>A permission prompt is waiting in your terminal.</dd>
|
||||
<dt>Do this</dt><dd>Switch to the terminal and answer it.</dd>
|
||||
</dl>
|
||||
@@ -798,7 +809,7 @@
|
||||
<dl>
|
||||
<dt>You see</dt><dd><strong>Not connected</strong> (Planny faded, his star shut).</dd>
|
||||
<dt>Likely cause</dt><dd>The program behind this page shut itself down.</dd>
|
||||
<dt>Do this</dt><dd>Ask Plan2Code to resume the session, and use the new link.</dd>
|
||||
<dt>Do this</dt><dd>Ask Plan2Code to resume the session (or run the command again), and use the new link.</dd>
|
||||
</dl>
|
||||
</li>
|
||||
<li class="help-row">
|
||||
@@ -1561,7 +1572,7 @@
|
||||
<li><strong>Review.</strong> A second opinion on the changes. Problems ranked, and you pick what gets fixed.</li>
|
||||
<li><strong>Handoff.</strong> Pack this conversation into a document a fresh session can pick up cold.</li>
|
||||
<li><strong>Changelog.</strong> Checks the CHANGELOG version against the main branch and suggests entries for what is new.</li>
|
||||
<li><strong>Git commit.</strong> Commits your changes with a clear message, suggests a split when it is really two jobs, and offers to push.</li>
|
||||
<li><strong>Git.</strong> Branches, pull, push and commits on one board, asking before anything leaves your machine. See "The git board".</li>
|
||||
</ul>
|
||||
<h4>Picking a spec</h4>
|
||||
<p>
|
||||
@@ -1718,7 +1729,94 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Helpers (subagents) -->
|
||||
<!-- Tab 13: The git board -->
|
||||
<section class="help-panel" data-tab="git">
|
||||
<h3>The git board</h3>
|
||||
<p class="help-lead">
|
||||
The Git card opens one board for your repository: branches, pull,
|
||||
push and commits in one place. Every button is a request to
|
||||
Plan2Code, which runs the git commands and says what each one did.
|
||||
</p>
|
||||
<h4>The header</h4>
|
||||
<ul>
|
||||
<li>The branch you are on, and how far it is ahead of or behind its remote copy.</li>
|
||||
<li>
|
||||
<strong>Last refreshed</strong> says when the remotes were last
|
||||
fetched. <strong>Refresh</strong> fetches again; if that fails, the
|
||||
line says so.
|
||||
</li>
|
||||
<li>
|
||||
Once your branch is pushed, <strong>Open pull request</strong> opens
|
||||
your host's new pull request page, into the default branch or the
|
||||
one you pick beside it. The first time a host is unknown, the board
|
||||
asks which kind it is and remembers the answer.
|
||||
</li>
|
||||
</ul>
|
||||
<h4>The branch table</h4>
|
||||
<ul>
|
||||
<li>
|
||||
The branch you are on and the default branch come first, then the
|
||||
rest, newest commit first, each with <strong>Switch</strong> and
|
||||
<strong>Delete</strong>.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Merged</strong> marks a branch already merged into the
|
||||
default branch, and <strong>Remote copy deleted</strong> one whose
|
||||
remote copy is gone. <strong>Clean up</strong> offers to delete those
|
||||
local branches in one go.
|
||||
</li>
|
||||
<li>
|
||||
Branches that exist only on the remote sit under
|
||||
<strong>Remote only</strong>, showing the first
|
||||
<span data-fact="remoteFold">50</span>; <strong>Show all</strong>
|
||||
lists the rest.
|
||||
</li>
|
||||
<li><strong>Search branches</strong> filters both lists by name or last commit.</li>
|
||||
</ul>
|
||||
<h4>What asks first</h4>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Push</strong>, <strong>Publish</strong>,
|
||||
<strong>Delete</strong> and <strong>Clean up</strong> always show
|
||||
exactly what will happen and wait for your yes. Deleting a branch
|
||||
that is not merged is a red confirm.
|
||||
</li>
|
||||
<li>
|
||||
Switching with uncommitted changes asks first: <strong>Switch and
|
||||
bring them</strong>, <strong>Commit first</strong> or
|
||||
<strong>Cancel</strong>. A pull that would touch your changes asks
|
||||
the same way.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Commit</strong> opens a list of your changed files to tick,
|
||||
and you approve the message before anything is committed.
|
||||
</li>
|
||||
<li>A remote branch is never deleted, and nothing is ever force-pushed.</li>
|
||||
</ul>
|
||||
<h4>One action at a time</h4>
|
||||
<p>
|
||||
While Planny works on a click, the bar is locked, so nothing queues
|
||||
up behind it. When it is done, a result line says what happened, with
|
||||
the commit hashes, and the board redraws from the repository as it now
|
||||
stands.
|
||||
</p>
|
||||
<h4>Done</h4>
|
||||
<p>
|
||||
<strong>Done</strong> ends the session. If anything happened, the last
|
||||
screen lists the commits, pushes and branches created or deleted, with
|
||||
<strong>Back to the dashboard</strong>. If nothing did, the page goes
|
||||
straight back to the dashboard.
|
||||
</p>
|
||||
<h4>In the terminal</h4>
|
||||
<p>
|
||||
The same skill takes plain instructions, such as
|
||||
<code>/plan2code-git switch to main</code> or
|
||||
<code>/plan2code-git commit and push</code>, and asks the same
|
||||
questions before every push, publish and delete.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 14: Helpers (subagents) -->
|
||||
<section class="help-panel" data-tab="subagents">
|
||||
<h3>Helpers (subagents)</h3>
|
||||
<p>
|
||||
@@ -1773,7 +1871,7 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 14: Ask a quick question -->
|
||||
<!-- Tab 15: Ask a quick question -->
|
||||
<section class="help-panel" data-tab="ask">
|
||||
<h3>Ask a quick question</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1864,7 +1962,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 15: Stopping and finishing -->
|
||||
<!-- Tab 16: Stopping and finishing -->
|
||||
<section class="help-panel" data-tab="finishing">
|
||||
<h3>Stopping and finishing</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1938,15 +2036,16 @@
|
||||
A finished screen (never a paused one) has a <strong>Back to the
|
||||
dashboard</strong> button. It turns this page back into the cards, in
|
||||
the same conversation, so the next step starts right here.
|
||||
Plan2Code listens for it for about ten minutes after the end. After
|
||||
that, or once the session has closed, the button becomes the
|
||||
<code>/plan2code</code> command to run in a new conversation instead.
|
||||
Plan2Code listens for it for as long as the session is open.
|
||||
Once the session has closed, the button becomes the
|
||||
<code>/plan2code</code> command to run in a new conversation
|
||||
instead.
|
||||
After a long step, a new conversation is the better choice anyway: it
|
||||
starts with a clean slate.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 16: Keyboard and preferences -->
|
||||
<!-- Tab 17: Keyboard and preferences -->
|
||||
<section class="help-panel" data-tab="prefs">
|
||||
<h3>Keyboard and preferences</h3>
|
||||
<p class="help-lead">
|
||||
@@ -2032,6 +2131,9 @@
|
||||
lists what Plan2Code doesn't need in your
|
||||
<code>~/.plan2code</code> folder: sessions nobody has opened for
|
||||
30 days, and files or folders that ended up there by mistake. It
|
||||
also lists this project's <code>specs--completed/</code> folders
|
||||
nobody has touched for 30 days; deleting one is permanent, since
|
||||
that folder is usually gitignored and git can't restore it. It
|
||||
shows each one with its size, and <strong>Delete these</strong>
|
||||
removes exactly that list. Your preferences, saved folders, models,
|
||||
the launcher and the session you are in always stay.
|
||||
@@ -2062,7 +2164,7 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 17: Privacy and where things are saved -->
|
||||
<!-- Tab 18: Privacy and where things are saved -->
|
||||
<section class="help-panel" data-tab="privacy">
|
||||
<h3>Privacy and where things are saved</h3>
|
||||
<p class="help-lead">
|
||||
@@ -2127,90 +2229,93 @@
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<dialog class="modal looks" id="looks-modal" aria-labelledby="looks-title">
|
||||
<dialog class="modal looks prefs" id="looks-modal" aria-labelledby="looks-title">
|
||||
<h2 id="looks-title">User Preferences</h2>
|
||||
<p class="modal-blurb">
|
||||
Kept on this machine, for every session you open here. Role only puts the
|
||||
starter templates most useful to you first; it never changes the questions
|
||||
you're asked.
|
||||
</p>
|
||||
<fieldset class="modal-ranges looks-row looks-role">
|
||||
<legend>Role</legend>
|
||||
<select id="looks-role" aria-label="Role"></select>
|
||||
<p class="help">Only puts the starter templates most useful to you first.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Theme</legend>
|
||||
<label><input type="radio" name="looks-theme" value="system" checked /> <span>Follow my system</span></label>
|
||||
<label><input type="radio" name="looks-theme" value="light" /> <span>Light</span></label>
|
||||
<label><input type="radio" name="looks-theme" value="dark" /> <span>Dark</span></label>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Card width</legend>
|
||||
<label><input type="radio" name="looks-width" value="narrow" /> <span>Narrow</span></label>
|
||||
<label><input type="radio" name="looks-width" value="comfortable" checked /> <span>Comfortable</span></label>
|
||||
<label><input type="radio" name="looks-width" value="wide" /> <span>Wide</span></label>
|
||||
<p class="help">How wide the question and documents are. On a smaller window they fit the space there is.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-accents">
|
||||
<legend>Highlight color</legend>
|
||||
<div class="swatches" id="looks-swatches"></div>
|
||||
<p class="help">
|
||||
Your highlight color marks what is yours to do, and Planny's
|
||||
star uses it while he works. Green, amber and red also mean done,
|
||||
staged and careful, so a highlight close to one of those can blur
|
||||
which is which.
|
||||
<div class="prefs-body">
|
||||
<p class="modal-blurb">
|
||||
Kept on this machine, for every session you open here. Role only puts the
|
||||
starter templates most useful to you first; it never changes the questions
|
||||
you're asked.
|
||||
</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-sounds">
|
||||
<legend>Sounds</legend>
|
||||
<label><input type="checkbox" id="looks-sound" checked /> <span>Play sounds</span></label>
|
||||
<div class="looks-row looks-sound-events" id="looks-sound-events">
|
||||
<label><input type="checkbox" data-sound="snore" checked /> <span>Planny snoring</span></label>
|
||||
<label><input type="checkbox" data-sound="bootup" checked /> <span>Planny waking up</span></label>
|
||||
<label><input type="checkbox" data-sound="startSkill" checked /> <span>Starting a skill</span></label>
|
||||
<label><input type="checkbox" data-sound="sessionStart" checked /> <span>Session opens</span></label>
|
||||
<label><input type="checkbox" data-sound="skillReady" checked /> <span>Skill is ready</span></label>
|
||||
<label><input type="checkbox" data-sound="sessionEnd" checked /> <span>Session ends</span></label>
|
||||
<label><input type="checkbox" data-sound="question" checked /> <span>New questions for you</span></label>
|
||||
<label><input type="checkbox" data-sound="chatReply" checked /> <span>Reply on the Ask tab</span></label>
|
||||
<label><input type="checkbox" data-sound="newTab" checked /> <span>New tab added</span></label>
|
||||
</div>
|
||||
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-cleanup">
|
||||
<legend>Cleanup</legend>
|
||||
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
|
||||
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
|
||||
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
|
||||
<span class="help" id="cleanup-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-models">
|
||||
<legend>Models</legend>
|
||||
<div class="models-tabs" role="group" aria-label="Which agent">
|
||||
<button type="button" class="btn small ghost" id="models-tab-claude" aria-pressed="true">Claude</button>
|
||||
<button type="button" class="btn small ghost" id="models-tab-devin" aria-pressed="false">Devin</button>
|
||||
</div>
|
||||
<div class="models-note">
|
||||
<p><strong>You usually don't need to change this.</strong> Plan2Code ships an up-to-date model list with every release. Add a model here only when a new one comes out before Plan2Code has been updated.</p>
|
||||
<ul>
|
||||
<li>Restart <code>plan2code</code> to see a change in its model menu.</li>
|
||||
<li>At any time, run <code>plan2code --model <id></code>, or pick your model inside your agent before running a skill.</li>
|
||||
<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>
|
||||
<li>Devin models are limited to Low, Medium and High effort.</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="models-list" id="models-shipped" aria-label="Built-in models"></div>
|
||||
<div class="models-list" id="models-user" aria-label="Models you added"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="models-add">Add a model</button>
|
||||
<button type="button" class="btn small ghost" id="models-reset">Reset to default</button>
|
||||
<span class="help" id="models-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-row looks-role">
|
||||
<legend>Role</legend>
|
||||
<select id="looks-role" aria-label="Role"></select>
|
||||
<p class="help">Only puts the starter templates most useful to you first.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Theme</legend>
|
||||
<label><input type="radio" name="looks-theme" value="system" checked /> <span>Follow my system</span></label>
|
||||
<label><input type="radio" name="looks-theme" value="light" /> <span>Light</span></label>
|
||||
<label><input type="radio" name="looks-theme" value="dark" /> <span>Dark</span></label>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Card width</legend>
|
||||
<label><input type="radio" name="looks-width" value="narrow" /> <span>Narrow</span></label>
|
||||
<label><input type="radio" name="looks-width" value="comfortable" checked /> <span>Comfortable</span></label>
|
||||
<label><input type="radio" name="looks-width" value="wide" /> <span>Wide</span></label>
|
||||
<p class="help">How wide the question and documents are. On a smaller window they fit the space there is.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-accents">
|
||||
<legend>Highlight color</legend>
|
||||
<div class="swatches" id="looks-swatches"></div>
|
||||
<p class="help">
|
||||
Your highlight color marks what is yours to do, and Planny's
|
||||
star uses it while he works. Green, amber and red also mean done,
|
||||
staged and careful, so a highlight close to one of those can blur
|
||||
which is which.
|
||||
</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-sounds">
|
||||
<legend>Sounds</legend>
|
||||
<label><input type="checkbox" id="looks-sound" checked /> <span>Play sounds</span></label>
|
||||
<div class="looks-row looks-sound-events" id="looks-sound-events">
|
||||
<label><input type="checkbox" data-sound="snore" checked /> <span>Planny snoring</span></label>
|
||||
<label><input type="checkbox" data-sound="bootup" checked /> <span>Planny waking up</span></label>
|
||||
<label><input type="checkbox" data-sound="startSkill" checked /> <span>Starting a skill</span></label>
|
||||
<label><input type="checkbox" data-sound="sessionStart" checked /> <span>Session opens</span></label>
|
||||
<label><input type="checkbox" data-sound="skillReady" checked /> <span>Skill is ready</span></label>
|
||||
<label><input type="checkbox" data-sound="sessionEnd" checked /> <span>Session ends</span></label>
|
||||
<label><input type="checkbox" data-sound="question" checked /> <span>New questions for you</span></label>
|
||||
<label><input type="checkbox" data-sound="chatReply" checked /> <span>Reply on the Ask tab</span></label>
|
||||
<label><input type="checkbox" data-sound="newTab" checked /> <span>New tab added</span></label>
|
||||
</div>
|
||||
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-cleanup">
|
||||
<legend>Cleanup</legend>
|
||||
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. It also lists this project's <code>specs--completed/</code> folders nobody has touched for 30 days; deleting one is permanent, since that folder is usually gitignored and git can't restore it. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
|
||||
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
|
||||
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
|
||||
<span class="help" id="cleanup-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-models">
|
||||
<legend>Models</legend>
|
||||
<div class="models-tabs" role="group" aria-label="Which agent">
|
||||
<button type="button" class="btn small ghost" id="models-tab-claude" aria-pressed="true">Claude</button>
|
||||
<button type="button" class="btn small ghost" id="models-tab-devin" aria-pressed="false">Devin</button>
|
||||
<button type="button" class="btn small ghost" id="models-tab-codex" aria-pressed="false">Codex</button>
|
||||
</div>
|
||||
<div class="models-note">
|
||||
<p><strong>You usually don't need to change this.</strong> Plan2Code ships an up-to-date model list with every release. Add a model here only when a new one comes out before Plan2Code has been updated.</p>
|
||||
<ul>
|
||||
<li>Restart <code>plan2code</code> to see a change in its model menu.</li>
|
||||
<li>At any time, run <code>plan2code --model <id></code>, or pick your model inside your agent before running a skill.</li>
|
||||
<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>
|
||||
<li>Devin models are limited to Low, Medium and High effort.</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="models-list" id="models-shipped" aria-label="Built-in models"></div>
|
||||
<div class="models-list" id="models-user" aria-label="Models you added"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="models-add">Add a model</button>
|
||||
<button type="button" class="btn small ghost" id="models-reset">Reset to default</button>
|
||||
<span class="help" id="models-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="looks-reset">Back to default</button>
|
||||
<button type="button" class="btn primary" id="looks-done">Done</button>
|
||||
@@ -2436,6 +2541,9 @@
|
||||
<li>
|
||||
Run this in your terminal (not in this page or your agent):
|
||||
<div class="update-command" id="update-command"></div>
|
||||
It opens the installer's menu. Back at your prompt with no output at all? npm
|
||||
could not reach the repository and hid the reason: run
|
||||
<code>git ls-remote https://github.com/jparkerweb/plan2code.git</code> to see it.
|
||||
</li>
|
||||
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
|
||||
</ol>
|
||||
|
||||
@@ -25,17 +25,27 @@ export const WEIGHTS = Object.freeze({
|
||||
"init-update": 2,
|
||||
finalize: 1,
|
||||
handoff: 0,
|
||||
"git-commit": 1,
|
||||
git: 1,
|
||||
// Scores 0 itself: Git's commits are tallied per run (COMMITS_PER_POINT).
|
||||
"git-commits": 0,
|
||||
"git-conflict": 1,
|
||||
changelog: 1,
|
||||
});
|
||||
|
||||
// Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder,
|
||||
// implement and implement-review score only through the agent's `run`
|
||||
// reports; dashboard and handoff never score; git-commit and changelog score 1 on launch.
|
||||
// reports; dashboard and handoff never score; git and changelog score 1 on
|
||||
// launch (Git then adds its commit tally and conflict help).
|
||||
export const LAUNCH_COUNTED = Object.freeze(
|
||||
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize", "git-commit", "changelog"])
|
||||
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize", "git", "changelog"])
|
||||
);
|
||||
|
||||
// Git's commits weigh what they add up to: each `git-commits` run carries
|
||||
// `commits`, and a skill run scores one point per COMMITS_PER_POINT commits,
|
||||
// rounded down. MAX_COMMITS is the most one run may report. Tune here.
|
||||
export const COMMITS_PER_POINT = 2;
|
||||
export const MAX_COMMITS = 999;
|
||||
|
||||
const weightOf = (key) => (Object.prototype.hasOwnProperty.call(WEIGHTS, key) ? WEIGHTS[key] : 0);
|
||||
|
||||
// The event names an agent may report in `run`.
|
||||
@@ -128,7 +138,7 @@ const WORKFLOW_NAMES = Object.freeze({
|
||||
"init-update": "Init update",
|
||||
finalize: "Finalize",
|
||||
handoff: "Handoff",
|
||||
"git-commit": "Git commit",
|
||||
git: "Git",
|
||||
changelog: "Changelog",
|
||||
});
|
||||
|
||||
@@ -145,7 +155,7 @@ const LAUNCH_LABELS = Object.freeze({
|
||||
init: "Init started",
|
||||
"init-update": "Init update started",
|
||||
finalize: "Finalize started",
|
||||
"git-commit": "Git commit started",
|
||||
git: "Git started",
|
||||
changelog: "Changelog started",
|
||||
});
|
||||
const RUN_LABELS = Object.freeze({
|
||||
@@ -163,7 +173,9 @@ const RUN_LABELS = Object.freeze({
|
||||
"init-update": "Init update run",
|
||||
finalize: "Finalize run",
|
||||
handoff: "Handoff written",
|
||||
"git-commit": "Git commit run",
|
||||
git: "Git run",
|
||||
"git-commits": "Commits in Git",
|
||||
"git-conflict": "Git conflict help",
|
||||
changelog: "Changelog run",
|
||||
});
|
||||
|
||||
@@ -180,6 +192,7 @@ export function breakdownFrom(entries) {
|
||||
const seen = new Set();
|
||||
const rows = [];
|
||||
const answers = new Map(); // launch id -> { row, count, workflow }
|
||||
const commits = new Map(); // launch id -> { row, count }
|
||||
const builds = new Map(); // launch id -> the row of the build in progress
|
||||
const reviewed = new Set(); // launch ids whose built-in review has scored
|
||||
for (const entry of Array.isArray(entries) ? entries : []) {
|
||||
@@ -188,6 +201,20 @@ export function breakdownFrom(entries) {
|
||||
if (seen.has(entry.id)) continue;
|
||||
seen.add(entry.id);
|
||||
}
|
||||
// A click on the git board is not back-and-forth: Git's answers score nothing.
|
||||
if (entry.kind === "answer" && entry.workflow === "git") continue;
|
||||
if (entry.kind === "run" && entry.event === "git-commits") {
|
||||
if (!Number.isInteger(entry.commits) || entry.commits < 1) continue;
|
||||
const launch = launchOf(entry.id);
|
||||
let tally = commits.get(launch);
|
||||
if (!tally) {
|
||||
tally = { row: { label: "", points: 0 }, count: 0 };
|
||||
commits.set(launch, tally);
|
||||
rows.push(tally.row);
|
||||
}
|
||||
tally.count += entry.commits;
|
||||
continue;
|
||||
}
|
||||
if (entry.kind === "answer") {
|
||||
const launch = launchOf(entry.id);
|
||||
let tally = answers.get(launch);
|
||||
@@ -255,6 +282,10 @@ export function breakdownFrom(entries) {
|
||||
const where = WORKFLOW_NAMES[workflow] ? ` in ${WORKFLOW_NAMES[workflow]}` : "";
|
||||
row.label = `${count} ${count === 1 ? "answer" : "answers"}${where}`;
|
||||
}
|
||||
for (const { row, count } of commits.values()) {
|
||||
row.points = Math.floor(count / COMMITS_PER_POINT);
|
||||
row.label = `${count} ${count === 1 ? "commit" : "commits"} in Git`;
|
||||
}
|
||||
return rows.filter((row) => row.points > 0).map(({ label, points }) => ({ label, points }));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// Plan2Code Web Console - the pull-request link for a branch.
|
||||
//
|
||||
// One pure builder for the four host shapes in the git-dashboard spec
|
||||
// (overview.md -> Pull-request URL shapes). git-repo.mjs re-exports it for the
|
||||
// snapshot, and the board's base picker rebuilds the link in the browser with
|
||||
// the same code. No DOM access at module scope and no imports: the server,
|
||||
// git-repo.mjs, the page and `node --test` all import this file.
|
||||
|
||||
// GitHub's compare path keeps the "/" in a branch name; each segment is
|
||||
// encoded on its own.
|
||||
const segments = (branch) => branch.split("/").map(encodeURIComponent).join("/");
|
||||
const q = encodeURIComponent;
|
||||
|
||||
const SHAPES = {
|
||||
github: (web, base, head) => `${web}/compare/${segments(base)}...${segments(head)}?quick_pull=1`,
|
||||
gitlab: (web, base, head) =>
|
||||
`${web}/-/merge_requests/new?merge_request%5Bsource_branch%5D=${q(head)}&merge_request%5Btarget_branch%5D=${q(base)}`,
|
||||
azure: (web, base, head) => `${web}/pullrequestcreate?sourceRef=${q(head)}&targetRef=${q(base)}`,
|
||||
bitbucket: (web, base, head) => `${web}/pull-requests/new?source=${q(head)}&dest=${q(base)}`,
|
||||
};
|
||||
|
||||
/**
|
||||
* The "open a pull request" link for `head` into `base` on a remote, or null
|
||||
* when the host has no known shape (kind null or "none"), the remote has no
|
||||
* web address, or the result would not be an https: link.
|
||||
*/
|
||||
export function prUrl({ web, kind } = {}, { base, head } = {}) {
|
||||
const shape = SHAPES[kind];
|
||||
if (!shape || !web || !base || !head) return null;
|
||||
const url = shape(String(web).replace(/\/+$/, ""), base, head);
|
||||
try {
|
||||
return new URL(url).protocol === "https:" ? url : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -20,9 +20,54 @@ import { marked } from "./vendor/marked.esm.js";
|
||||
// read the same way) is protocol-relative and would not, so it is refused.
|
||||
const SAFE_PROTOCOL = /^(https?:|mailto:|#|\/(?![/\\]))/i;
|
||||
|
||||
// A note attachment kept into the spec (`console.mjs keep`) is cited by a
|
||||
// relative path ending in attachments/<slug>-<id8>.<ext>; the server serves
|
||||
// exactly those from the session's spec, so the link and the image work.
|
||||
const KEPT_ATTACHMENT = /^(?:\.{0,2}\/)*(?:[\w.-]+\/)*attachments\/([a-z0-9-]{1,40}-[0-9a-f-]{8}\.[a-z0-9]{1,5})$/i;
|
||||
|
||||
// A link or image the page cannot follow (a relative path into the project,
|
||||
// a remote image the CSP refuses) still says where it points.
|
||||
function unreachable(parent, href) {
|
||||
const where = String(href || "").trim();
|
||||
if (!where || /^(javascript|data|vbscript):/i.test(where)) return;
|
||||
parent.appendChild(document.createTextNode(" ("));
|
||||
parent.appendChild(el("code", null, where));
|
||||
parent.appendChild(document.createTextNode(")"));
|
||||
}
|
||||
|
||||
// An html token that is only an HTML comment: it renders as nothing, as it
|
||||
// would in any markdown viewer. Anything else html stays literal text.
|
||||
function isComment(t) {
|
||||
return t.type === "html" && /^\s*<!--[\s\S]*?-->\s*$/.test(String(t.raw ?? t.text ?? ""));
|
||||
}
|
||||
|
||||
const TASK_MARKERS = {
|
||||
"/": { mark: "◐", label: "in progress", cls: "is-doing" },
|
||||
"!": { mark: "!", label: "blocked", cls: "is-blocked" },
|
||||
"?": { mark: "?", label: "assumed", cls: "is-assumed" },
|
||||
};
|
||||
|
||||
// A list item opening with one of TASK_MARKERS: the marker comes off its
|
||||
// first text token (so it is not drawn twice) and its look comes back.
|
||||
function takeMarker(item) {
|
||||
const first = item.tokens && item.tokens[0];
|
||||
const leaf = first && Array.isArray(first.tokens) && first.tokens[0];
|
||||
const m = /^\[([/!?])\]\s+/.exec((first && first.text) || "");
|
||||
if (!m || !leaf || leaf.type !== "text" || !String(leaf.text || "").startsWith(m[0])) return null;
|
||||
first.text = first.text.slice(m[0].length);
|
||||
leaf.text = leaf.text.slice(m[0].length);
|
||||
if (typeof leaf.raw === "string" && leaf.raw.startsWith(m[0])) leaf.raw = leaf.raw.slice(m[0].length);
|
||||
if (Array.isArray(leaf.tokens) && leaf.tokens[0] && leaf.tokens[0].type === "text") {
|
||||
leaf.tokens[0].text = String(leaf.tokens[0].text || "").replace(m[0], "");
|
||||
}
|
||||
return TASK_MARKERS[m[1]];
|
||||
}
|
||||
|
||||
function safeHref(href) {
|
||||
if (!href) return null;
|
||||
const trimmed = String(href).trim();
|
||||
const kept = KEPT_ATTACHMENT.exec(trimmed);
|
||||
if (kept) return "/attachments/" + kept[1].toLowerCase();
|
||||
// Blocks javascript: and data: hrefs before they can reach the DOM, and a
|
||||
// protocol-relative `//host` (or `/\host`), which leaves the page for another site.
|
||||
return SAFE_PROTOCOL.test(trimmed) ? trimmed : null;
|
||||
@@ -74,6 +119,7 @@ function inlineInto(parent, tokens) {
|
||||
const href = safeHref(t.href);
|
||||
if (!href) {
|
||||
inlineInto(parent, t.tokens);
|
||||
unreachable(parent, t.href);
|
||||
break;
|
||||
}
|
||||
const a = el("a");
|
||||
@@ -87,8 +133,12 @@ function inlineInto(parent, tokens) {
|
||||
}
|
||||
case "image": {
|
||||
const src = safeHref(t.href);
|
||||
if (!src) {
|
||||
// Only same-origin images load (the CSP's img-src is 'self'), so a
|
||||
// remote one gets the text-and-path treatment rather than a broken
|
||||
// image and a console error.
|
||||
if (!src || /^https?:/i.test(src)) {
|
||||
parent.appendChild(document.createTextNode(t.text || ""));
|
||||
unreachable(parent, t.href);
|
||||
break;
|
||||
}
|
||||
const img = el("img", "md-img");
|
||||
@@ -98,6 +148,8 @@ function inlineInto(parent, tokens) {
|
||||
break;
|
||||
}
|
||||
default:
|
||||
// A comment is a note to tools (a spec's METRICS_JSON), never shown.
|
||||
if (isComment(t)) break;
|
||||
// Includes `html`: rendered as literal text, never parsed.
|
||||
parent.appendChild(document.createTextNode(t.raw ?? t.text ?? ""));
|
||||
}
|
||||
@@ -105,11 +157,9 @@ function inlineInto(parent, tokens) {
|
||||
}
|
||||
|
||||
// What a fenced code block offers beside Copy, from its first non-empty line:
|
||||
// `'run'` gets a Run it button (git commands — the one kind a person keeps
|
||||
// copying into Ask by hand), `'hint'` a muted note that pasting it into Ask
|
||||
// may get the agent to run it, and `null` nothing extra. A leading `/` is a
|
||||
// skill command for a new conversation, never a terminal command, so it gets
|
||||
// neither.
|
||||
// `'hint'` a muted note that pasting it into Ask may get the agent to run it,
|
||||
// and `null` nothing extra. A leading `/` is a skill command for a new
|
||||
// conversation, never a terminal command, so it gets nothing.
|
||||
const COMMAND_WORDS =
|
||||
/^(git|node|npm|npx|pnpm|yarn|bun|deno|python3?|pip3?|brew|curl|wget|docker|kubectl|terraform|make|cmake|cargo|go|java|mvn|gradle|gh|aws|az|gcloud|jq|ssh|scp|rsync|chmod|chown|mkdir|cp|mv|rm|ls|cd|cat|echo|export|source|bash|sh|zsh|fish|pwsh|powershell|cmd|systemctl|service|apt|apt-get|dnf|yum|pacman|tar|unzip|zip)\b/i;
|
||||
|
||||
@@ -119,7 +169,6 @@ export function runHint(text) {
|
||||
.map((line) => line.trim())
|
||||
.find((line) => line.length > 0);
|
||||
if (!firstLine || firstLine.startsWith("/")) return null;
|
||||
if (/^git(\s|$)/.test(firstLine)) return "run";
|
||||
if (firstLine.startsWith("#!")) return "hint";
|
||||
return COMMAND_WORDS.test(firstLine) ? "hint" : null;
|
||||
}
|
||||
@@ -161,14 +210,8 @@ function blockInto(parent, tokens) {
|
||||
// textContent, so a fenced block containing markup is inert.
|
||||
pre.appendChild(el("code", null, t.text));
|
||||
wrap.appendChild(copyButton(t.text, "md-copy"));
|
||||
const hint = runHint(t.text);
|
||||
if (hint === "run") {
|
||||
const run = el("button", "md-run", "Run it");
|
||||
run.type = "button";
|
||||
wrap.appendChild(run);
|
||||
}
|
||||
wrap.appendChild(pre);
|
||||
if (hint === "hint") {
|
||||
if (runHint(t.text) === "hint") {
|
||||
wrap.appendChild(el("p", "md-run-hint", "The agent may be able to run this — paste it into the Ask tab"));
|
||||
}
|
||||
parent.appendChild(wrap);
|
||||
@@ -181,12 +224,21 @@ function blockInto(parent, tokens) {
|
||||
const list = el(t.ordered ? "ol" : "ul", "md-list");
|
||||
if (t.ordered && typeof t.start === "number" && t.start !== 1) list.start = t.start;
|
||||
for (const item of t.items || []) {
|
||||
const li = el("li", "md-li" + (item.task ? " is-task" : ""));
|
||||
// The spec's other task markers ([/] in progress, [!] blocked,
|
||||
// [?] assumed), which marked does not know: drawn like a task box
|
||||
// rather than left as a bullet reading "[!]".
|
||||
const other = !item.task && takeMarker(item);
|
||||
const li = el("li", "md-li" + (item.task || other ? " is-task" : ""));
|
||||
if (item.task) {
|
||||
const box = el("span", "md-task" + (item.checked ? " is-done" : ""));
|
||||
box.textContent = item.checked ? "✓" : "·";
|
||||
box.setAttribute("aria-label", item.checked ? "done" : "not done");
|
||||
li.appendChild(box);
|
||||
} else if (other) {
|
||||
const box = el("span", "md-task " + other.cls);
|
||||
box.textContent = other.mark;
|
||||
box.setAttribute("aria-label", other.label);
|
||||
li.appendChild(box);
|
||||
}
|
||||
blockInto(li, item.tokens);
|
||||
list.appendChild(li);
|
||||
@@ -224,6 +276,7 @@ function blockInto(parent, tokens) {
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
if (isComment(t)) break;
|
||||
// Unknown or raw html block: show the source, do not interpret it.
|
||||
const p = el("p", "md-p");
|
||||
p.textContent = t.raw ?? t.text ?? "";
|
||||
|
||||
@@ -88,7 +88,7 @@ export function cleanSetting(input) {
|
||||
// The non-editable part of every "on" block (FR-8).
|
||||
export const FRAME_LINES = Object.freeze([
|
||||
"Hand independent work to helpers if your tools allow it; otherwise carry on alone.",
|
||||
"Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.",
|
||||
"Report each helper on the page (console-subagents.md); questions for the person stay with you.",
|
||||
'If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.',
|
||||
]);
|
||||
|
||||
|
||||
+107
-11
@@ -55,6 +55,8 @@ import {
|
||||
removeCleanup,
|
||||
remoteWarning,
|
||||
saveSubagentStoreEntry,
|
||||
PR_HOST_KINDS,
|
||||
savePrHost,
|
||||
specKey,
|
||||
subagentStoreEntry,
|
||||
typedCount,
|
||||
@@ -129,6 +131,31 @@ const EXT_ALT = UPLOAD_EXTS.join("|");
|
||||
const UPLOAD_ANY_ROUTE = new RegExp(`^/uploads/([0-9a-f-]{36})\\.(${EXT_ALT})$`);
|
||||
const UPLOAD_NAME = new RegExp(`^[0-9a-f-]{36}\\.(${EXT_ALT})$`);
|
||||
|
||||
// A kept attachment's name, as attachmentName() in lib.mjs writes it:
|
||||
// <slug>-<first 8 of the upload id>.<the upload's extension>.
|
||||
const KEPT_ROUTE = new RegExp(`^/attachments/([a-z0-9-]{1,40}-[0-9a-f-]{8}\\.(${EXT_ALT}))$`);
|
||||
|
||||
function keptPath(name) {
|
||||
const state = readState() || {};
|
||||
if (typeof state.specDir !== "string" || !state.specDir.trim()) return null;
|
||||
const root = path.resolve(state.worktree || process.cwd());
|
||||
const dir = path.resolve(root, state.specDir, "attachments");
|
||||
const file = path.join(dir, name);
|
||||
try {
|
||||
const real = fs.realpathSync.native(file);
|
||||
const realDir = fs.realpathSync.native(dir);
|
||||
const realRoot = fs.realpathSync.native(root);
|
||||
const inside = (p, base) => {
|
||||
const rel = path.relative(base.toLowerCase(), p.toLowerCase());
|
||||
return rel && !rel.startsWith("..") && !path.isAbsolute(rel);
|
||||
};
|
||||
if (path.dirname(real).toLowerCase() !== realDir.toLowerCase() || !inside(real, realRoot)) return null;
|
||||
return fs.statSync(real).isFile() ? real : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function uploadPath(id, ext = "jpg") {
|
||||
if (!UPLOAD_EXTS.includes(ext)) return null;
|
||||
const result = path.join(UPLOADS_DIR, id + "." + ext);
|
||||
@@ -222,6 +249,8 @@ const SERVABLE = new Set([
|
||||
"subagents.js",
|
||||
"mentions.js",
|
||||
"favicon.js",
|
||||
"git-board.js",
|
||||
"pr-url.js",
|
||||
"start-stop.mp3",
|
||||
"next.mp3",
|
||||
"insert.mp3",
|
||||
@@ -598,7 +627,14 @@ function ensureConversation(state) {
|
||||
let entry = null;
|
||||
if (!last.conversation) {
|
||||
entry = appendChat(DIR, { kind: "reset", conversation: 1, workflow: state.workflow, reason: "start" });
|
||||
} else if (last.workflow !== state.workflow && (last.workflow === "dashboard" || state.workflow === "dashboard")) {
|
||||
} else if (
|
||||
last.workflow !== state.workflow &&
|
||||
// The same switches `open --resume` treats as a hop (a blank page, the
|
||||
// agent's replies included): through the dashboard, or into git from
|
||||
// anywhere (Commit it now, Changelog's "Commit this now?"). Without a new
|
||||
// conversation, the old questions would show as unanswered again.
|
||||
(last.workflow === "dashboard" || state.workflow === "dashboard" || state.workflow === "git")
|
||||
) {
|
||||
entry = appendChat(DIR, {
|
||||
kind: "reset",
|
||||
conversation: last.conversation + 1,
|
||||
@@ -728,7 +764,8 @@ function recordSubmitted(state, actions) {
|
||||
// JSON.parse makes "__proto__" an own property, and it would then be
|
||||
// written back into state.json and re-read forever.
|
||||
if (Object.prototype.hasOwnProperty.call(rest, "__proto__")) delete rest["__proto__"];
|
||||
item.submitted = { at, ...rest };
|
||||
// A skip says so on the record, so settling it can record a skip.
|
||||
item.submitted = { at, ...rest, ...(type === "skip" ? { skipped: true } : {}) };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -804,13 +841,14 @@ function touch() {
|
||||
lastContact = Date.now();
|
||||
}
|
||||
|
||||
const MODEL_CLIS = ["claude", "devin"];
|
||||
// The CLIs the launcher reads a model list for (src/launcher/plan2code.js listModels).
|
||||
const MODEL_CLIS = ["claude", "devin", "codex"];
|
||||
const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/;
|
||||
// Devin's XHigh and Max efforts are never offered, curated or added.
|
||||
const MODEL_EFFORT_BLOCKED = /-(xhigh|max)$/i;
|
||||
|
||||
/**
|
||||
* The user's added models: { claude: [{id,label}], devin: [...] }. Returns { models } or
|
||||
* The user's added models: { claude: [{id,label}], devin: [...], codex: [...] }. Returns { models } or
|
||||
* { error }. Blank rows are dropped; ids are trimmed and made unique per CLI; a label
|
||||
* defaults to the id. Nothing else in the body survives.
|
||||
*/
|
||||
@@ -1134,13 +1172,19 @@ const server = http.createServer((req, res) => {
|
||||
? asked
|
||||
: ""
|
||||
: state.specDir;
|
||||
// Most specs have no overview.md yet, which is normal, not an error: 204
|
||||
// keeps the browser console free of a failed request per pick.
|
||||
const noOverview = () => {
|
||||
res.writeHead(204, baseHeaders({ "cache-control": "no-store" }));
|
||||
res.end();
|
||||
};
|
||||
readOverview(state.worktree || state.project, spec)
|
||||
.then((text) =>
|
||||
typeof text === "string"
|
||||
? send(res, 200, text, "text/markdown; charset=utf-8", { "cache-control": "no-store" })
|
||||
: json(res, 404, { error: "no overview" })
|
||||
: noOverview()
|
||||
)
|
||||
.catch(() => json(res, 404, { error: "no overview" }));
|
||||
.catch(noOverview);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1268,11 +1312,38 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// What an unknown git host is, for the git board's pull-request link. Saved
|
||||
// to pr-hosts.json for every project; nothing is written under the project.
|
||||
// The page follows it with a __git pr-host action, and the agent's reread
|
||||
// rebuilds the link.
|
||||
if (pathname === "/pr-host" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const { host: raw, kind } = body && typeof body === "object" ? body : {};
|
||||
if (typeof raw !== "string" || !raw || raw.length > 253 || !/^[a-z0-9.-]+$/i.test(raw)) {
|
||||
return json(res, 400, { error: "bad-host" });
|
||||
}
|
||||
// Hosts are looked up lowercased (git-repo.mjs parseRemoteUrl).
|
||||
const host = raw.toLowerCase();
|
||||
if (!PR_HOST_KINDS.has(kind)) return json(res, 400, { error: "bad-kind" });
|
||||
const state = readState();
|
||||
if (!state || state.workflow !== "git") return json(res, 400, { error: "not-git" });
|
||||
try {
|
||||
savePrHost(host, kind);
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
appendEvent(DIR, { type: "pr-host", host, kind });
|
||||
return json(res, 200, { ok: true });
|
||||
});
|
||||
}
|
||||
|
||||
// The launcher's model menu: what ships (read-only here) and what the user added.
|
||||
if (pathname === "/models" && req.method === "GET") {
|
||||
const saved = readJson(USER_MODELS_FILE, null) || {};
|
||||
const { models } = cleanModels(saved);
|
||||
return json(res, 200, { shipped: shippedModels(), user: models || { claude: [], devin: [] } });
|
||||
return json(res, 200, { shipped: shippedModels(), user: models || Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []])) });
|
||||
}
|
||||
|
||||
if (pathname === "/models" && req.method === "POST") {
|
||||
@@ -1292,18 +1363,19 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
|
||||
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
|
||||
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
|
||||
// still finds. Never this session, never a path the page sent.
|
||||
// ~/.plan2code and the project's old completed specs; `{ delete: [id] }`
|
||||
// removes those of the ids a fresh scan still finds. Never this session,
|
||||
// never a path the page sent.
|
||||
if (pathname === "/cleanup" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
if (body && Array.isArray(body.delete)) {
|
||||
return removeCleanup(body.delete, { skipSid: SID })
|
||||
return removeCleanup(body.delete, { skipSid: SID, project: sessionWorktree() || PROJECT })
|
||||
.then((done) => json(res, 200, { ok: true, ...done }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
}
|
||||
return cleanupFindings({ skipSid: SID })
|
||||
return cleanupFindings({ skipSid: SID, project: sessionWorktree() || PROJECT })
|
||||
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
});
|
||||
@@ -1371,6 +1443,30 @@ const server = http.createServer((req, res) => {
|
||||
return readRaw(req, 0, () => json(res, 415, { error: "type" }));
|
||||
}
|
||||
|
||||
// A note attachment the agent kept into the spec (`console.mjs keep`), so a
|
||||
// doc citing `attachments/<name>` shows the image or opens the file. Read
|
||||
// only, and only one exact name shape (the one `keep` writes) directly
|
||||
// inside <worktree>/<specDir>/attachments/: nothing else in the project.
|
||||
if (pathname.startsWith("/attachments/") || req.url.startsWith("/attachments/")) {
|
||||
if (req.method !== "GET") return json(res, 405, { error: "method" });
|
||||
const m = KEPT_ROUTE.exec(req.url);
|
||||
const file = m && m[0] === pathname ? keptPath(m[1]) : null;
|
||||
if (!file) return json(res, 404, { error: "not found" });
|
||||
let buf;
|
||||
try {
|
||||
buf = fs.readFileSync(file);
|
||||
} catch {
|
||||
return json(res, 404, { error: "not found" });
|
||||
}
|
||||
const ext = m[2].toLowerCase();
|
||||
if (ext === "jpg") return send(res, 200, buf, "image/jpeg", { "cache-control": "private, max-age=3600" });
|
||||
const pdf = DOC_TYPES[ext].kind === "pdf";
|
||||
return send(res, 200, buf, pdf ? "application/pdf" : "text/plain; charset=utf-8", {
|
||||
...(pdf ? {} : { "content-security-policy": "sandbox" }),
|
||||
"cache-control": "private, max-age=3600",
|
||||
});
|
||||
}
|
||||
|
||||
// Matched on the raw request line as well as the parsed path: URL parsing
|
||||
// folds `..` segments away, and nothing that needed folding is an upload.
|
||||
// GET and DELETE take images and documents alike.
|
||||
|
||||
Reference in new issue
Block a user